Verify test coverage report generation in CI pipeline using pytest
Preconditions (3)
✅ Expected Result: The coverage report XML file is generated and saved successfully in the CI pipeline after running pytest tests
Jump into concepts and practice - no test required
import os import subprocess import pytest def test_coverage_report_generation(): # Run pytest with coverage options to generate XML report result = subprocess.run([ 'pytest', '--cov=.', '--cov-report=xml:coverage.xml', '--maxfail=1', '--disable-warnings' ], capture_output=True, text=True) # Assert pytest run was successful assert result.returncode == 0, f"Pytest failed:\n{result.stdout}\n{result.stderr}" # Assert coverage.xml file is created assert os.path.exists('coverage.xml'), "Coverage XML report was not generated" # Clean up coverage file after test os.remove('coverage.xml') if __name__ == '__main__': pytest.main([__file__])
This test runs pytest as a subprocess with coverage options to generate an XML report named coverage.xml.
We capture the output and check the return code to ensure tests passed.
Then we assert that the coverage.xml file exists, confirming coverage data was generated.
Finally, we clean up the coverage file to keep the environment clean.
This simulates what a CI pipeline would do: run tests with coverage and produce a report file.
Now add data-driven testing to run coverage report generation on multiple test folders
pytest --cov in CI pipelines?--cov to specify coverage on the current directory.pytest --cov=myapp --cov-report=term
term option prints coverage summary in the terminal output.pytest --cov=myapp --cov-report=html
htmlcov in the current directory.--cov-fail-under which sets a minimum coverage percentage.