0
0
PyTesttesting~8 mins

Conftest fixtures (shared across files) in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Conftest fixtures (shared across files)
Folder Structure
tests/
├── conftest.py        # Shared fixtures for all test files
├── test_login.py      # Test file using shared fixtures
├── test_checkout.py   # Another test file using shared fixtures
└── utils/
    └── helpers.py     # Utility functions
Test Framework Layers
  • conftest.py: Defines fixtures shared across multiple test files.
  • Test files: Use fixtures by naming them as function parameters.
  • Utilities: Helper functions or classes to support tests.
  • Configuration: pytest.ini or pyproject.toml for pytest settings.
Configuration Patterns

Use pytest.ini or pyproject.toml to set global pytest options like markers or test paths.

Manage environment variables or config files for credentials and URLs, accessed inside fixtures.

Example: conftest.py fixture reads environment to decide base URL.

Test Reporting and CI/CD Integration
  • Use pytest plugins like pytest-html or pytest-cov for reports.
  • Configure CI pipelines (GitHub Actions, Jenkins) to run pytest and publish reports.
  • Fixtures in conftest.py ensure consistent setup/teardown across tests in CI.
Best Practices
  1. Keep fixtures reusable and generic so many tests can use them without duplication.
  2. Use scope wisely (function, module, session) to optimize test speed and resource use.
  3. Place shared fixtures in conftest.py at the root of tests folder for automatic discovery.
  4. Avoid importing conftest.py directly; pytest finds fixtures automatically.
  5. Use fixtures for setup and cleanup to keep tests clean and focused on assertions.
Self Check

Where would you add a new fixture that provides a database connection shared by multiple test files?

Key Result
Use conftest.py to define shared fixtures for reusable setup and teardown across pytest test files.