0
0
PyTesttesting~8 mins

Coverage report formats (terminal, HTML, XML) in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Coverage report formats (terminal, HTML, XML)
Folder Structure
project-root/
├── src/
│   └── your_code.py
├── tests/
│   ├── test_example.py
│   └── __init__.py
├── .coveragerc
├── pytest.ini
└── reports/
    ├── coverage_html/
    └── coverage_xml/

This structure keeps source code in src/, tests in tests/, and coverage reports in reports/.

Test Framework Layers
  • Test Layer: tests/ contains pytest test files.
  • Source Layer: src/ holds the application code.
  • Coverage Layer: Coverage.py integrated with pytest to measure code coverage.
  • Reporting Layer: Generates coverage reports in terminal, HTML, and XML formats.
  • Configuration Layer: Settings for coverage and pytest in .coveragerc and pytest.ini.
Configuration Patterns

Use .coveragerc to configure coverage reporting formats and options:

[run]
source = src
branch = True

[report]
show_missing = True

[html]
dir = reports/coverage_html

[xml]
output = reports/coverage_xml/coverage.xml

Use pytest.ini to enable coverage plugin and specify options:

[pytest]
addopts = --cov=src --cov-report=term --cov-report=html --cov-report=xml

This setup runs tests with coverage on src/, shows summary in terminal, and generates HTML and XML reports in reports/.

Test Reporting and CI/CD Integration
  • Terminal Report: Quick summary of coverage percentages and missing lines shown after test run.
  • HTML Report: Detailed, interactive report with color-coded coverage view accessible via browser.
  • XML Report: Machine-readable format for CI tools like Jenkins, GitHub Actions, or SonarQube.
  • CI/CD Integration: Configure pipeline to run pytest with coverage, archive reports, and fail build if coverage thresholds are not met.
Best Practices
  • Keep coverage reports in a dedicated reports/ folder to separate artifacts from source code.
  • Use .coveragerc to centralize coverage settings for consistency across environments.
  • Generate multiple report formats to serve different needs: quick terminal feedback, detailed HTML for developers, and XML for CI tools.
  • Set coverage thresholds in CI to maintain code quality and prevent coverage regression.
  • Regularly review HTML reports to identify untested code and improve tests.
Self Check

Where in this folder structure would you add a new HTML coverage report if you want to keep reports organized?

Answer: Inside the reports/coverage_html/ directory.

Key Result
Use pytest with coverage.py to generate terminal, HTML, and XML coverage reports organized in a dedicated reports folder.