0
0
Selenium Pythontesting~10 mins

New window and tab creation in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a new browser tab and a new browser window, then verifies that the number of open windows/tabs matches the expected count.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest

class TestNewWindowTab(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com')

    def test_new_tab_and_window(self):
        driver = self.driver
        original_windows = driver.window_handles
        original_count = len(original_windows)

        # Open new tab
        driver.execute_script('window.open("https://example.com", "_blank");')
        WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == original_count + 1)

        # Open new window
        driver.execute_script('window.open("https://example.com", "_blank", "width=600,height=400");')
        WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == original_count + 2)

        # Verify total windows/tabs count
        self.assertEqual(len(driver.window_handles), original_count + 2)

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser opened at https://example.com with one tab-PASS
2Get current window handles and countOne window/tab handle presentCount of window handles is 1PASS
3Execute JavaScript to open a new tab with URL https://example.comTwo tabs open in the same browser windowWait until window handles count is original + 1 (2)PASS
4Execute JavaScript to open a new window with URL https://example.com and size 600x400Two tabs plus one new window open (total 3 windows/tabs)Wait until window handles count is original + 2 (3)PASS
5Assert that total window handles count equals original count + 2Three window handles presentlen(driver.window_handles) == original_count + 2PASS
6Test ends and browser closesBrowser closed, all windows/tabs closed-PASS
Failure Scenario
Failing Condition: New tab or new window did not open, so window handles count did not increase as expected
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify after opening a new tab and a new window?
AThe URL of the original tab changed
BThe total number of open windows/tabs increased by two
CThe browser title changed
DThe new tab opened in a separate browser instance
Key Result
Always verify the number of open windows or tabs after opening new ones to ensure your test environment matches expectations.