Test Overview
This test opens a new browser window, switches control to it, verifies the new window's title, then switches back to the original window and verifies its title.
This test opens a new browser window, switches control to it, verifies the new window's title, then switches back to the original window and verifies its title.
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 TestWindowHandles(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://example.com') def test_window_handles(self): driver = self.driver original_window = driver.current_window_handle # Click link that opens a new window link = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.LINK_TEXT, 'More information...')) ) link.click() # Wait for new window WebDriverWait(driver, 10).until(EC.new_window_is_opened([original_window])) # Switch to new window windows = driver.window_handles for window in windows: if window != original_window: driver.switch_to.window(window) break # Verify new window title self.assertIn('IANA', driver.title) # Switch back to original window driver.switch_to.window(original_window) # Verify original window title self.assertIn('Example Domain', driver.title) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and opens browser to 'https://example.com' | Browser shows 'Example Domain' page | - | PASS |
| 2 | Stores current window handle as original_window | One browser window open with handle stored | - | PASS |
| 3 | Waits for and clicks link with text 'More information...' that opens new window | User clicks link, new window opening | - | PASS |
| 4 | Waits until new window is opened | Two browser windows open | - | PASS |
| 5 | Switches control to the new window | Driver controls new window | - | PASS |
| 6 | Checks that new window title contains 'IANA' | New window title visible | Assert 'IANA' in driver.title | PASS |
| 7 | Switches back to original window | Driver controls original window | - | PASS |
| 8 | Checks that original window title contains 'Example Domain' | Original window title visible | Assert 'Example Domain' in driver.title | PASS |
| 9 | Test ends and browser closes | No browser windows open | - | PASS |