0
0
PyTesttesting~8 mins

Fixture dependencies (fixture using fixture) in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Fixture dependencies (fixture using fixture)
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   └── conftest.py
├── src/
│   └── app_code.py
├── pytest.ini
└── requirements.txt
  
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py, fixtures can depend on other fixtures to share setup logic.
  • Test Layer: Test files in tests/ use fixtures by declaring them as function parameters.
  • Application Code Layer: The src/ folder contains the main application code under test.
  • Configuration Layer: pytest.ini holds pytest configuration options.
Configuration Patterns

Use pytest.ini or tox.ini to configure pytest options like markers and test paths.

Manage environment variables or secrets outside code, e.g., with .env files or CI environment settings.

Fixtures can accept parameters or use pytest_addoption to handle different environments or browsers.

Test Reporting and CI/CD Integration
  • Use pytest plugins like pytest-html or pytest-cov for HTML reports and coverage.
  • Integrate pytest runs in CI pipelines (GitHub Actions, Jenkins) with commands like pytest --junitxml=report.xml.
  • Reports help track test results and fixture setup success or failures.
Best Practices
  1. Keep fixtures small and focused: Each fixture should do one setup task.
  2. Use fixture dependencies: Let fixtures use other fixtures to avoid repeating setup code.
  3. Scope fixtures appropriately: Use function, module, or session scopes to optimize test speed.
  4. Use autouse sparingly: Only when you want fixtures to run automatically without explicit use.
  5. Document fixtures: Add docstrings so others understand what each fixture provides.
Self Check

Where in this folder structure would you add a new fixture that depends on an existing database connection fixture?

Key Result
Use pytest fixtures with dependencies defined in conftest.py to share setup logic cleanly across tests.