0
0
PyTesttesting~8 mins

Database rollback fixtures in PyTest - Framework Patterns

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

src/
├── app.py
├── db.py

utils/
├── db_helpers.py
Test Framework Layers
  • Fixtures Layer:
    Contains pytest fixtures like db_session that manage database transactions and rollback after each test.
  • Test Layer:
    Test files in tests/ use fixtures to run tests isolated from each other.
  • Application Layer:
    Application code that interacts with the database, e.g., src/db.py.
  • Utilities Layer:
    Helper functions for database setup, teardown, or common queries.
Configuration Patterns
  • Database URL: Use environment variables to configure database connection strings for different environments (test, dev, prod).
  • Fixture Scope: Use function scope for rollback fixtures to isolate tests.
  • Credentials: Store sensitive info securely outside code, e.g., in .env files or CI secrets.
  • Transaction Management: Start a transaction at fixture setup and rollback at teardown to keep DB clean.
Test Reporting and CI/CD Integration
  • Use pytest's built-in reporting with --junitxml=report.xml for CI systems.
  • Integrate with CI tools like GitHub Actions, GitLab CI, or Jenkins to run tests on each commit.
  • Fail tests if database rollback does not work, ensuring no side effects remain.
  • Use coverage tools to ensure database-related code is tested.
Best Practices
  1. Use Transaction Rollback: Wrap each test in a transaction and rollback to keep tests isolated.
  2. Fixture Reuse: Define reusable fixtures in conftest.py for easy sharing across tests.
  3. Keep Tests Independent: Never rely on data created by other tests; use fixtures to set up needed data.
  4. Secure Configurations: Avoid hardcoding credentials; use environment variables or secret managers.
  5. Clear Naming: Name fixtures clearly to indicate their purpose, e.g., db_session, rollback_transaction.
Self Check

Where in this folder structure would you add a new fixture that starts a database transaction and rolls it back after each test?

Key Result
Use pytest fixtures to start a database transaction before each test and rollback after to keep tests isolated and the database clean.