0
0
Selenium Pythontesting~8 mins

Window handles in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Window handles
Folder Structure
selenium_project/
├── tests/
│   ├── test_window_handles.py
│   └── __init__.py
├── pages/
│   ├── base_page.py
│   ├── main_page.py
│   └── popup_page.py
├── utils/
│   ├── window_manager.py
│   └── __init__.py
├── config/
│   ├── config.yaml
│   └── __init__.py
├── conftest.py
└── requirements.txt
    
Test Framework Layers
  • Driver Layer: Manages WebDriver setup and teardown (in conftest.py using pytest fixtures).
  • Page Objects: Classes representing pages/windows (base_page.py, main_page.py, popup_page.py), encapsulating element locators and actions.
  • Window Manager Utility: Helper functions to switch between window handles safely (window_manager.py).
  • Tests: Test scripts using pytest in tests/ folder, focusing on window handle scenarios.
  • Configuration: Environment settings, browser options, and credentials stored in config/config.yaml.
Configuration Patterns

Use a YAML file (config/config.yaml) to store environment URLs, browser types, and credentials.

Example config.yaml:

environment:
  base_url: "https://example.com"
browser: "chrome"
credentials:
  username: "user1"
  password: "pass123"
    

Load config in conftest.py and pass parameters to tests and page objects.

Test Reporting and CI/CD Integration
  • Use pytest with pytest-html plugin to generate readable HTML reports after test runs.
  • Integrate tests into CI/CD pipelines (e.g., GitHub Actions, Jenkins) to run on every code push.
  • Reports include pass/fail status of window handle tests and screenshots on failure.
  • Logs capture window switching actions for easier debugging.
Best Practices
  • Use Page Object Model: Encapsulate window-specific actions in page classes to keep tests clean.
  • Explicitly Manage Window Handles: Use utility functions to switch windows by handle or title to avoid flaky tests.
  • Wait for Windows: Use explicit waits to ensure new windows are available before switching.
  • Clean Up: Always close popup windows and switch back to the main window to keep test environment stable.
  • Parameterize Config: Keep environment and browser settings outside code for easy changes.
Self Check

Where would you add a new utility function to switch to a window by its title in this framework structure?

Key Result
Organize Selenium Python tests with clear layers: page objects, utilities for window handle management, config files, and structured tests for reliable window switching.