0
0
PyTesttesting~8 mins

Dynamic fixture selection in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Dynamic fixture selection
Folder Structure
tests/
├── test_login.py
├── test_checkout.py
├── conftest.py
utilities/
├── browser_manager.py
├── data_loader.py
config/
├── config.yaml
reports/
├── latest_report.html
pytest.ini
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py, provides dynamic fixtures that select resources based on test parameters or environment variables.
  • Test Layer: Test files inside tests/ use fixtures to get test data or browser instances dynamically.
  • Utilities Layer: Helper modules like browser_manager.py manage browser setup and teardown, supporting dynamic fixture behavior.
  • Configuration Layer: config/config.yaml holds environment-specific settings used by fixtures to decide which resources to provide.
Configuration Patterns
  • Use pytest.ini or environment variables to specify parameters like --env or --browser.
  • conftest.py reads these parameters and selects fixtures dynamically using request.config.getoption().
  • Configuration files (YAML/JSON) store environment details (URLs, credentials) loaded by fixtures.
  • Dynamic fixtures use @pytest.fixture(params=[...]) or conditional logic inside fixtures to provide different resources.
Test Reporting and CI/CD Integration
  • Use pytest-html or pytest-allure plugins to generate readable HTML or Allure reports.
  • Reports saved in reports/ folder with timestamps for history.
  • CI/CD pipelines (GitHub Actions, Jenkins) run tests with different parameters to trigger dynamic fixtures for multiple environments or browsers.
  • Test results include which fixture variant was used, aiding debugging.
Best Practices
  • Keep fixtures simple and focused: Each fixture should provide one resource or setup.
  • Use request.param and request.config.getoption() for flexibility: This allows tests to control fixture behavior without code changes.
  • Centralize configuration: Store environment and browser details in config files, not hardcoded in fixtures.
  • Use descriptive fixture names: So tests clearly show what resource they depend on.
  • Document fixture usage: Explain how dynamic selection works to help team members understand test setup.
Self Check

Where in this framework structure would you add a new fixture that selects a database connection dynamically based on the test environment?

Key Result
Use pytest fixtures with parameters and config options to select test resources dynamically based on environment or test needs.