0
0
PyTesttesting~10 mins

Coverage thresholds in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test runs pytest with coverage measurement and verifies that the code coverage meets the minimum threshold set in the configuration. It ensures that the tested code is sufficiently covered by tests.

Test Code - PyTest
PyTest
import subprocess
import sys

def test_coverage_threshold():
    # Run pytest with coverage and fail if coverage is below threshold
    result = subprocess.run([
        sys.executable, "-m", "pytest", "--cov=src", "--cov-fail-under=80"
    ], capture_output=True, text=True)
    # Check that pytest exited with code 0 (success)
    assert result.returncode == 0, f"Coverage threshold not met:\n{result.stdout}\n{result.stderr}"
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test starts by running pytest with coverage options and threshold set to 80%Terminal ready to execute pytest command-PASS
2Subprocess runs pytest with --cov=src and --cov-fail-under=80Pytest runs tests and measures coverage on 'src' folder-PASS
3Pytest finishes and returns exit codeCoverage report generated, exit code indicates pass/failCheck if return code is 0 (coverage >= 80%)PASS
4Assert that coverage threshold is metTest framework receives assertion resultAssert result.returncode == 0PASS
Failure Scenario
Failing Condition: Code coverage is below 80%, causing pytest to exit with non-zero code
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test check after running pytest with coverage?
AThat all tests passed regardless of coverage
BThat the coverage percentage is at least 80%
CThat the source code has no syntax errors
DThat pytest ran without any warnings
Key Result
Using coverage thresholds in automated tests helps ensure your code is well tested and prevents lowering test quality over time.