0
0
Selenium Pythontesting~8 mins

Screenshot on failure in Selenium Python - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Screenshot on failure
Folder Structure
selenium_project/
├── tests/
│   ├── test_login.py
│   └── test_checkout.py
├── pages/
│   ├── login_page.py
│   └── checkout_page.py
├── utils/
│   ├── screenshot_helper.py
│   └── driver_factory.py
├── config/
│   └── config.yaml
├── reports/
│   └── screenshots/
└── conftest.py
    
Test Framework Layers
  • Driver Layer: Manages browser setup and teardown (e.g., driver_factory.py).
  • Page Objects: Encapsulate page elements and actions (e.g., login_page.py).
  • Tests: Actual test cases using pytest (e.g., test_login.py).
  • Utilities: Helpers like screenshot capture on failure (screenshot_helper.py).
  • Config: Environment and browser settings (config.yaml).
  • Reports: Stores test reports and screenshots (reports/screenshots/).
Configuration Patterns

Use a config.yaml file to store environment URLs, browser choices, and credentials. Load this config in conftest.py to provide fixtures for tests.

Example config.yaml snippet:

environment:
  url: "https://example.com"
browser: "chrome"
credentials:
  username: "testuser"
  password: "password123"
    

Use pytest hooks in conftest.py to capture screenshots on test failure automatically.

Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with --html=report.html for readable reports.
  • Store screenshots in reports/screenshots/ with timestamped filenames.
  • Integrate with CI tools like GitHub Actions or Jenkins to run tests on push.
  • Configure CI to archive reports and screenshots as build artifacts for easy access.
Best Practices
  1. Centralize Screenshot Logic: Keep screenshot capture in a utility function to reuse and maintain easily.
  2. Use Pytest Hooks: Implement pytest_runtest_makereport to detect failures and trigger screenshots automatically.
  3. Organize Screenshots: Save screenshots with clear names and timestamps in a dedicated folder.
  4. Keep Tests Clean: Avoid screenshot code inside test cases; use hooks or fixtures instead.
  5. Integrate with Reports: Link screenshots in test reports for quick debugging.
Self Check

Where in this folder structure would you add the code that captures a screenshot when a test fails?

Key Result
Use pytest hooks and a utility function to capture and save screenshots automatically on test failure.