import subprocess
import re
def square(x):
return x * x
def test_square_one():
assert square(3) == 9
# Run coverage for initial test
result1 = subprocess.run(['coverage', 'run', '-m', 'pytest', '-q', '--tb=line'], capture_output=True, text=True)
result_report1 = subprocess.run(['coverage', 'report'], capture_output=True, text=True)
# Extract coverage percent for the file
match1 = re.search(r'square.py\s+\d+\s+\d+\s+(\d+)%', result_report1.stdout)
coverage1 = int(match1.group(1)) if match1 else 0
# Add second test to cover all lines
def test_square_zero():
assert square(0) == 0
# Run coverage again with both tests
result2 = subprocess.run(['coverage', 'run', '-m', 'pytest', '-q', '--tb=line'], capture_output=True, text=True)
result_report2 = subprocess.run(['coverage', 'report'], capture_output=True, text=True)
match2 = re.search(r'square.py\s+\d+\s+\d+\s+(\d+)%', result_report2.stdout)
coverage2 = int(match2.group(1)) if match2 else 0
# Assertions
assert coverage1 < 100, f"Expected coverage less than 100%, got {coverage1}%"
assert coverage2 == 100, f"Expected coverage 100%, got {coverage2}%"This script defines a simple function square and two pytest test functions.
First, it runs pytest with coverage enabled with only one test, then captures the coverage report and extracts the coverage percentage.
Then it adds a second test to cover all code paths and runs coverage again.
Finally, it asserts that the first coverage is less than 100% and the second coverage is exactly 100%, showing how coverage measures test completeness.
Using subprocess allows running coverage commands programmatically.
Regex extracts coverage percent from the report output.
This approach teaches how coverage helps identify missing tests and improve completeness.