0
0
Testing Fundamentalstesting~15 mins

Test coverage metrics in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Verify test coverage metrics calculation for a simple function
Preconditions (2)
Step 1: Write tests to cover all branches of the 'calculate_discount' function
Step 2: Run the tests with coverage measurement enabled
Step 3: Check the coverage report for the 'discounts.py' file
Step 4: Verify that the coverage report shows 100% coverage for statements and branches
✅ Expected Result: The coverage report shows 100% statement and branch coverage for 'discounts.py'
Automation Requirements - pytest with coverage.py
Assertions Needed:
Assert that coverage report shows 100% statement coverage
Assert that coverage report shows 100% branch coverage
Best Practices:
Use pytest for writing tests
Use coverage.py to measure coverage
Write tests that cover all logical branches
Use assertions to verify coverage percentages programmatically
Automated Solution
Testing Fundamentals
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.

Common Mistakes - 4 Pitfalls
Not enabling branch coverage in coverage.py
Writing tests that cover only some branches
Checking coverage manually instead of programmatically
{'mistake': 'Not specifying the source module in coverage configuration', 'why_bad': 'Coverage may include unrelated files or miss the target file.', 'correct_approach': 'Specify source=["module_name"] when creating Coverage object.'}
Bonus Challenge

Now add data-driven testing with 3 different input amounts to cover all discount cases

Show Hint