0
0
PyTesttesting~8 mins

Database fixture patterns in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Database fixture patterns
Folder Structure
tests/
├── test_users.py
├── test_orders.py
├── conftest.py

fixtures/
├── db_fixtures.py

utils/
├── db_helpers.py

config/
├── config.yaml
Test Framework Layers
  • Fixtures Layer: Contains database setup and teardown code using pytest fixtures (e.g., db_fixtures.py).
  • Test Layer: Test files in tests/ use fixtures to prepare database state before running tests.
  • Utilities Layer: Helper functions for database operations like connecting, cleaning, or seeding data (db_helpers.py).
  • Configuration Layer: Holds environment settings such as database URLs and credentials (config.yaml).
Configuration Patterns
  • Use a config.yaml file to store database connection strings for different environments (dev, test, prod).
  • Load configuration in conftest.py to provide fixtures with environment-specific settings.
  • Use environment variables to override sensitive data like passwords.
  • Allow command-line options in pytest to select environment or database type.
Test Reporting and CI/CD Integration
  • Use pytest built-in reporting with --junitxml=report.xml for CI systems.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests on database fixtures automatically.
  • Ensure database is reset or migrated before tests run in CI to keep tests isolated.
  • Use pytest plugins like pytest-html for readable HTML reports.
Best Practices
  • Isolate Tests: Use fixtures to create fresh database state for each test to avoid side effects.
  • Use Scoped Fixtures: Use function scope for tests needing clean state, session scope for expensive setup.
  • Clear Data After Tests: Always clean or rollback changes after tests to keep database consistent.
  • Parameterize Fixtures: Allow fixtures to accept parameters to reuse setup for different test scenarios.
  • Keep Fixtures Simple: Avoid complex logic inside fixtures; delegate to helper functions.
Self Check

Where would you add a new fixture that sets up a test user in the database?

Key Result
Use pytest fixtures to manage database setup and teardown for isolated, repeatable tests.