Measure test coverage using pytest-cov
Preconditions (4)
✅ Expected Result: The console shows a coverage report indicating the percentage of calculator.py code covered by tests, with no errors or failures
import subprocess import re def test_coverage_report(): # Run pytest with coverage on calculator.py result = subprocess.run( ['pytest', '--cov=calculator', 'test_calculator.py', '--cov-report=term'], capture_output=True, text=True ) output = result.stdout # Check pytest ran successfully assert result.returncode == 0, f"Pytest failed with output:\n{output}" # Check coverage report contains calculator.py assert 'calculator.py' in output, "Coverage report does not include calculator.py" # Extract coverage percentage for calculator.py using regex match = re.search(r'calculator.py\s+\d+\s+\d+\s+(\d+)%', output) assert match is not None, "Could not find coverage percentage for calculator.py" coverage_percent = int(match.group(1)) assert coverage_percent == 100, f"Expected 100% coverage but got {coverage_percent}%"
This test runs pytest as a subprocess with the --cov=calculator option to measure coverage of the calculator.py module.
It captures the output and checks that pytest completed successfully (return code 0).
Then it verifies the coverage report includes calculator.py and extracts the coverage percentage using a regular expression.
Finally, it asserts the coverage is 100%, meaning all code lines in calculator.py are tested.
This approach automates verifying that coverage measurement works as expected using pytest-cov.
Now add data-driven testing to verify coverage for multiple modules like calculator.py and utils.py
pytest-cov in your testing workflow?myapp?--cov=package_name.--cov=myapp, which is the correct syntax. pytest --cov tests/ would incorrectly target the tests directory instead of the myapp package.pytest --cov=myapp tests/test_module.py--cov=myapp option measures coverage for the myapp package, not tests.tests/test_module.py with coverage enabled will show coverage report for myapp code exercised by those tests.pytest --cov=myapp but no coverage report appeared. What is the most likely cause?app using pytest-cov. Which command should you run?--cov-report=html generates an HTML coverage report.--cov=app and --cov-report=html together.Pass the test and this pattern moves unknown