0
0
PyTesttesting~8 mins

Avoiding test interdependence in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Avoiding test interdependence
Folder Structure
tests/
├── test_login.py
├── test_shopping_cart.py
├── test_checkout.py
├── conftest.py
utilities/
├── helpers.py
├── data_loader.py
configs/
├── config.yaml
reports/
├── latest_report.html
pytest.ini
Test Framework Layers
  • Test Cases: Individual test files in tests/ folder, each test is independent and self-contained.
  • Fixtures: Defined in conftest.py to setup and teardown test data or environment, ensuring fresh state for each test.
  • Utilities: Helper functions and data loaders in utilities/ to avoid duplication and keep tests clean.
  • Configuration: Environment settings and credentials stored in configs/config.yaml and accessed via utility functions.
Configuration Patterns
  • Use pytest.ini to configure pytest options like markers and test paths.
  • Store environment-specific data (URLs, credentials) in configs/config.yaml.
  • Load configuration in fixtures or utilities to inject into tests.
  • Use fixtures with scope="function" to ensure each test runs with a clean setup.
Test Reporting and CI/CD Integration
  • Generate HTML reports using pytest --html=reports/latest_report.html.
  • Integrate pytest runs in CI pipelines (GitHub Actions, Jenkins) to run tests on each commit.
  • Fail fast option to stop on first failure to quickly identify interdependent test issues.
  • Use tags/markers to run subsets of tests independently.
Framework Design Principles
  1. Isolate Tests: Each test should setup and cleanup its own data to avoid sharing state.
  2. Use Fixtures: Use pytest fixtures to prepare fresh environments for every test function.
  3. No Test Order Dependency: Tests must pass regardless of execution order.
  4. Clear Naming: Name tests clearly to reflect their independent purpose.
  5. Data Reset: Reset or mock external resources between tests to prevent side effects.
Self Check

Where in this framework structure would you add a fixture that resets the database before each test?

Key Result
Use pytest fixtures to ensure each test runs independently with fresh setup and no shared state.