0
0
PyTesttesting~8 mins

Fixture teardown (yield) in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Fixture teardown (yield)
Folder Structure
tests/
├── test_example.py
├── conftest.py
utilities/
├── helpers.py
pytest.ini

This is a simple pytest project structure. conftest.py holds fixtures including those with yield for teardown. Test files go in tests/. Utility functions live in utilities/.

Test Framework Layers
  • Fixtures Layer: conftest.py contains fixtures with setup and teardown using yield.
  • Test Layer: Test files in tests/ use fixtures to prepare and clean test state.
  • Utilities Layer: Helper functions or classes in utilities/ support tests and fixtures.
  • Configuration Layer: pytest.ini or environment variables configure test runs.
Configuration Patterns
  • Use pytest.ini to set default options like markers and test paths.
  • Use environment variables or pytest_addoption in conftest.py to select environments or browsers.
  • Store sensitive data like credentials outside code, load them in fixtures if needed.
  • Fixtures with yield handle setup before yield and teardown after, ensuring cleanup regardless of test outcome.
Test Reporting and CI/CD Integration
  • Use pytest built-in reports with --junitxml=report.xml for CI systems.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests on push or pull requests.
  • Teardown in fixtures ensures environment is clean after tests, preventing flaky results in CI.
  • Use plugins like pytest-html for readable HTML reports.
Best Practices
  1. Use yield in fixtures to clearly separate setup and teardown steps.
  2. Keep teardown code simple and reliable to avoid leaving resources open.
  3. Scope fixtures appropriately (function, module, session) to optimize test speed and resource use.
  4. Use conftest.py for shared fixtures to avoid duplication.
  5. Always clean up external resources like files, database connections, or network sockets in teardown.
Self Check

Where in this framework structure would you add a new fixture that sets up a temporary database connection and ensures it closes after tests?

Key Result
Use pytest fixtures with yield to manage setup and teardown cleanly and reliably.