Verify test coverage metrics calculation for a simple function
Preconditions (2)
✅ Expected Result: The coverage report shows 100% statement and branch coverage for 'discounts.py'
import coverage import pytest from discounts import calculate_discount cov = coverage.Coverage(branch=True, source=["discounts"]) cov.start() # Test cases covering all branches def test_no_discount(): assert calculate_discount(50) == 50 def test_discount_10_percent(): assert calculate_discount(150) == 135 def test_discount_20_percent(): assert calculate_discount(300) == 240 cov.stop() cov.save() # Analyze coverage data analysis = cov.analysis2('discounts.py') statements, missing, excluded, missing_branches = analysis # Assertions for coverage assert len(missing) == 0, f"Missing statements: {missing}" assert len(missing_branches) == 0, f"Missing branches: {missing_branches}" print("All coverage assertions passed: 100% statements and branches covered.")
This script uses coverage.py to measure test coverage of the calculate_discount function in discounts.py.
First, it starts coverage measurement with branch coverage enabled.
Then, it defines three test functions to cover all logical branches of the discount calculation.
After running tests, it stops coverage and saves the data.
It analyzes coverage data for discounts.py to find missing statements and branches.
Assertions check that no statements or branches are missing, ensuring 100% coverage.
If assertions pass, it prints a confirmation message.
Now add data-driven testing with 3 different input amounts to cover all discount cases
Pass the test and this pattern moves unknown