0
0
PyTesttesting~8 mins

Test independence in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Test independence
Folder Structure
project-root/
├── tests/
│   ├── test_login.py
│   ├── test_cart.py
│   ├── test_checkout.py
│   └── conftest.py
├── src/
│   └── app_code.py
├── utils/
│   └── helpers.py
├── pytest.ini
└── requirements.txt
    
Test Framework Layers
  • Tests: Individual test files in tests/ folder. Each test is independent and does not rely on others.
  • Fixtures: Setup and teardown code in conftest.py to prepare test data or environment fresh for each test.
  • Utilities: Helper functions in utils/helpers.py to avoid repeating code inside tests.
  • Application Code: The main code under test in src/app_code.py.
  • Configuration: pytest.ini for pytest settings and options.
Configuration Patterns

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

Use conftest.py to define fixtures that provide fresh setup for each test, ensuring no shared state.

Example fixture for fresh user data:

import pytest

@pytest.fixture
def new_user():
    return {"username": "testuser", "password": "pass123"}
    

Each test uses fixtures to get clean data and environment, avoiding dependencies between tests.

Test Reporting and CI/CD Integration

Use pytest built-in reporting with --junitxml=report.xml to generate XML reports.

Integrate with CI/CD tools (like GitHub Actions, Jenkins) to run tests on every code push.

Test independence ensures that failures are isolated and easy to diagnose in reports.

Best Practices for Test Independence
  • Isolate Tests: Each test should run alone without relying on others.
  • Use Fixtures: Setup fresh data and environment for each test using pytest fixtures.
  • No Shared State: Avoid global variables or shared data that can cause side effects.
  • Clear Setup and Teardown: Clean up after tests to avoid leftover data affecting others.
  • Idempotent Tests: Running tests multiple times should produce the same result.
Self Check

Where in this framework structure would you add a fixture that provides a fresh database connection for each test?

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