Verify code exclusion from coverage report using pytest
Preconditions (2)
✅ Expected Result: Coverage report shows 100% coverage excluding the marked lines
Jump into concepts and practice - no test required
import subprocess import xml.etree.ElementTree as ET def test_coverage_exclusion(): # Run pytest with coverage and generate XML report result = subprocess.run([ 'pytest', '--cov=sample_module', '--cov-report=xml', '--maxfail=1', '--disable-warnings' ], capture_output=True, text=True) assert result.returncode == 0, f"Pytest failed:\n{result.stdout}\n{result.stderr}" # Parse coverage XML report tree = ET.parse('coverage.xml') root = tree.getroot() # Find coverage line-rate attribute line_rate = float(root.attrib.get('line-rate', '0')) # Assert coverage is 1.0 (100%) excluding excluded lines assert line_rate == 1.0, f"Expected 100% coverage excluding excluded lines, got {line_rate*100:.2f}%"
This test runs pytest with coverage enabled on a sample module that has some lines marked with # pragma: no cover to exclude them from coverage.
It generates an XML coverage report, then parses it to check the overall line coverage rate.
The assertion verifies that the coverage is 100%, meaning the excluded lines are not counted against coverage.
Using subprocess.run allows running pytest as a separate process and capturing output and exit code.
This approach ensures the coverage exclusion comment works as expected.
Now add a test that verifies exclusion of multiple code blocks marked with '# pragma: no cover' in different files
# pragma: no cover in your Python test code when using pytest and coverage.py?# pragma: no cover tells coverage.py to ignore that line when measuring test coverage.# pragma: no cover exactly as written.def func(x):
if x > 0:
return x
else:
return -x # pragma: no cover
What will coverage.py report about the line with return -x if it is never executed?# pragma: no cover tells coverage.py to ignore that line regardless of execution.def example():
print('Start') # pragma no cover
print('End')But coverage.py still counts the first print line as uncovered. What is the likely problem?# pragma: no cover. Missing colon causes coverage.py to ignore the comment.# pragma: no cover only works line-by-line. Which approach correctly excludes multiple lines without affecting other code?# pragma: no cover comment excludes coverage only for the line it is on, so each line must have it to be excluded.if False: changes code behavior or testability; partial comments on first and last lines do not exclude intermediate lines.