Verify code coverage meets minimum threshold using pytest
Preconditions (2)
✅ Expected Result: The coverage report shows total coverage percentage of 80% or higher, indicating tests cover at least 80% of the code.
Jump into concepts and practice - no test required
import pytest from coverage import Coverage # This test runs coverage programmatically and asserts threshold def test_coverage_threshold(): cov = Coverage(source=["your_package_name"]) cov.start() # Import the module to run its code coverage import your_package_name # Run tests programmatically using pytest main result = pytest.main(["tests/"]) cov.stop() cov.save() total_coverage = cov.report(show_missing=False) assert total_coverage >= 80, f"Coverage {total_coverage}% is below threshold of 80%"
This test uses the coverage module to start coverage measurement on the target package. It then runs all tests in the tests/ directory using pytest.main(). After tests finish, it stops coverage and reports the total coverage percentage. The assertion checks if coverage is at least 80%. If not, the test fails with a clear message.
This approach automates coverage threshold verification inside a test, so coverage enforcement is part of the test suite.
Now add data-driven testing to verify coverage thresholds for multiple packages with different minimum percentages
pytest --cov=myapp --cov-fail-under=90--cov-fail-under=75 but pytest does not fail even when coverage is 70%. What is the likely cause?