0
0
PyTesttesting~8 mins

Fixture finalization (request.addfinalizer) in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Fixture finalization (request.addfinalizer)
Folder Structure
project_root/
├── tests/
│   ├── test_example.py
│   └── conftest.py
├── src/
│   └── app_code.py
└── pytest.ini
Test Framework Layers
  • Fixtures Layer: Defined in conftest.py, provides setup and teardown using request.addfinalizer.
  • Test Layer: Test files in tests/ folder use fixtures for setup and cleanup.
  • Application Layer: Source code under src/ folder, tested by tests.
  • Utilities Layer: Helper functions or modules imported by fixtures or tests.
  • Configuration Layer: pytest.ini for pytest settings and options.
Configuration Patterns

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

Fixtures can accept request object to register finalizers for cleanup after tests.

Example: In conftest.py, define a fixture that sets up a resource and uses request.addfinalizer to release it after test finishes.

Environment variables or command line options can be accessed in fixtures for flexible configuration.

Test Reporting and CI/CD Integration
  • Pytest generates test reports with pass/fail results by default.
  • Use plugins like pytest-html for detailed HTML reports.
  • Integrate pytest runs in CI/CD pipelines (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Ensure finalizers run to clean up resources even if tests fail, keeping CI environment stable.
Best Practices
  • Use request.addfinalizer for teardown: It ensures cleanup code runs after each test using the fixture.
  • Keep setup and teardown close: Define finalizer inside the fixture for clarity.
  • Use fixtures for reusable setup/cleanup: Avoid repeating code in tests.
  • Handle exceptions in finalizers carefully: To avoid hiding test failures.
  • Use scope wisely: Fixtures can have scopes like function, module, or session to control setup frequency.
Self Check

Where in this folder structure would you add a new fixture that opens a database connection and ensures it closes after each test?

Answer: Add the fixture in conftest.py inside the tests/ folder, using request.addfinalizer to close the connection.

Key Result
Use pytest fixtures with request.addfinalizer to manage setup and guaranteed cleanup in tests.