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.