0
0
PyTesttesting~8 mins

Fixture composition in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Fixture composition
Folder Structure
tests/
├── test_login.py
├── test_shopping_cart.py
├── conftest.py
utilities/
├── helpers.py
├── data_providers.py
configs/
├── config.yaml
├── env_vars.yaml
reports/
├── latest_report.html
logs/
├── test_run.log

Test Framework Layers
  • Fixtures Layer: Defined in conftest.py, fixtures provide reusable setup and teardown logic. They can depend on each other to compose complex test states.
  • Test Layer: Test files in tests/ use fixtures by declaring them as function parameters. This keeps tests clean and focused on assertions.
  • Utilities Layer: Helper functions and data providers support fixtures and tests with reusable code.
  • Configuration Layer: YAML or other config files hold environment-specific data like URLs, credentials, and settings.
  • Reporting Layer: Test results and logs are saved in reports/ and logs/ folders for review.
Configuration Patterns
  • Environment Config: Use YAML files (e.g., config.yaml) to store URLs, timeouts, and environment-specific settings.
  • Fixture Parameters: Pass config values into fixtures using pytest_addoption or pytestconfig fixture for flexibility.
  • Credentials: Store sensitive data securely outside the repo or use environment variables accessed in fixtures.
  • Browser or Service Setup: Compose fixtures to build complex setups, e.g., a db_connection fixture used by a user_setup fixture.
Test Reporting and CI/CD Integration
  • Use pytest --junitxml=reports/results.xml to generate XML reports for CI tools.
  • Integrate with CI pipelines (GitHub Actions, Jenkins) to run tests on each commit and upload reports.
  • Use plugins like pytest-html to create readable HTML reports saved in reports/.
  • Log fixture setup and teardown steps to logs/test_run.log for debugging.
Best Practices for Fixture Composition
  1. Keep fixtures small and focused: Each fixture should do one thing well, then compose them for complex setups.
  2. Use scope wisely: Define fixture scope (function, module, session) to optimize test speed and resource use.
  3. Leverage fixture dependencies: Compose fixtures by calling other fixtures as parameters to reuse setup logic.
  4. Use autouse sparingly: Only when you want fixtures to run automatically without explicit declaration.
  5. Clean up resources: Use yield in fixtures to ensure proper teardown after tests.
Self Check

Where in this framework structure would you add a new fixture that sets up a test user with database access?

Key Result
Compose small, reusable pytest fixtures by declaring dependencies to build complex test setups cleanly.