0
0
PyTesttesting~10 mins

Coverage in CI pipelines in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test runs a Python pytest suite with coverage measurement in a Continuous Integration (CI) pipeline. It verifies that the test coverage meets the minimum required threshold.

Test Code - pytest
PyTest
import pytest
import subprocess

def test_coverage_threshold():
    # Run pytest with coverage and generate a coverage report
    result = subprocess.run([
        'pytest', '--cov=.', '--cov-report=term-missing', '--cov-fail-under=80', '-k', 'not test_coverage_threshold'
    ], capture_output=True, text=True)

    # Assert that pytest exited with code 0 (success)
    assert result.returncode == 0, f"Coverage threshold not met. Output:\n{result.stdout}\n{result.stderr}"
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts: pytest command with coverage options is executedCI environment runs pytest with coverage measuring all source files-PASS
2pytest discovers and runs all test functionsTests execute, coverage data is collected for each source line-PASS
3pytest generates coverage report showing lines covered and missingCoverage report output is available in terminal-PASS
4pytest checks if coverage percentage meets or exceeds 80%Coverage threshold check performed internally by pytest-cov pluginAssert that pytest exit code is 0 indicating coverage threshold metPASS
5Test ends with success if coverage threshold is metCI pipeline receives success status-PASS
Failure Scenario
Failing Condition: Coverage is below 80%, causing pytest to exit with non-zero code
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test assert to verify coverage in the CI pipeline?
AThat all tests pass regardless of coverage
BThat coverage report file exists on disk
CThat pytest exits with code 0 indicating coverage threshold met
DThat coverage percentage is exactly 100%
Key Result
Always enforce a minimum coverage threshold in CI pipelines to catch untested code early and maintain code quality.