0
0
PyTesttesting~8 mins

Branch coverage in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Branch coverage
Folder Structure
project-root/
├── src/
│   └── calculator.py
├── tests/
│   ├── test_calculator.py
│   ├── __init__.py
│   └── conftest.py
├── pytest.ini
├── requirements.txt
└── README.md
  
Test Framework Layers
  • Source Code Layer (src/): Contains the application code to be tested, e.g., calculator.py with functions having branches (if/else).
  • Test Layer (tests/): Contains test files like test_calculator.py where pytest test functions verify different branches of the code.
  • Fixtures and Setup (conftest.py): Shared test setup or reusable fixtures for tests.
  • Configuration (pytest.ini): Configures pytest options including coverage settings.
  • Utilities (optional): Helper functions or test data if needed.
Configuration Patterns

Use pytest.ini to configure coverage options for branch coverage:

[pytest]
addopts = --cov=src --cov-branch --cov-report=term-missing
  

This enables branch coverage measurement and shows missing branches in the terminal report.

For environment-specific settings (like test vs. dev), use environment variables or separate config files loaded in conftest.py.

Test Reporting and CI/CD Integration
  • Use pytest-cov plugin to generate coverage reports including branch coverage.
  • Reports can be output as terminal summary, HTML, XML (for CI tools).
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to run tests and fail builds if branch coverage drops below threshold.
  • Example GitHub Actions step to run tests with coverage:
          - name: Run tests with coverage
            run: |
              pytest --cov=src --cov-branch --cov-report=xml
          
Best Practices for Branch Coverage Framework
  • Write tests for all decision points: Ensure tests cover both true and false branches of if/else statements.
  • Use pytest-cov plugin: It integrates smoothly with pytest and supports branch coverage.
  • Keep tests small and focused: Each test should verify one branch or behavior to isolate failures.
  • Fail build on coverage drop: Enforce minimum branch coverage thresholds in CI to maintain quality.
  • Use clear naming: Name tests to reflect which branch or condition they cover for easy maintenance.
Self Check

Where in this folder structure would you add a new test to verify the false branch of a conditional in the calculator.py file?

Key Result
Organize tests in a dedicated folder with pytest and use pytest-cov to measure branch coverage ensuring all decision branches are tested.