0
0
Testing Fundamentalstesting~15 mins

Statement coverage in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Automate statement coverage test for a simple function
Preconditions (2)
Step 1: Create a Python function named calculate_discount that takes a price and a boolean is_member
Step 2: If is_member is True, apply 10% discount to price, else no discount
Step 3: Write test cases to call calculate_discount with both True and False for is_member
Step 4: Run tests and verify all statements in calculate_discount are executed
✅ Expected Result: All statements in calculate_discount function are executed and tests pass
Automation Requirements - pytest
Assertions Needed:
Assert discounted price is correct for member
Assert price remains same for non-member
Best Practices:
Use clear test function names
Test all branches to cover all statements
Keep tests independent and simple
Automated Solution
Testing Fundamentals
def calculate_discount(price: float, is_member: bool) -> float:
    if is_member:
        return price * 0.9
    else:
        return price

import pytest

def test_calculate_discount_member():
    assert calculate_discount(100, True) == 90

def test_calculate_discount_non_member():
    assert calculate_discount(100, False) == 100

The calculate_discount function applies a 10% discount if the user is a member. The tests test_calculate_discount_member and test_calculate_discount_non_member call the function with both possible values of is_member. This ensures every statement in the function runs at least once, achieving full statement coverage. Assertions check the returned price is correct. Using pytest allows easy running and reporting of test results.

Common Mistakes - 3 Pitfalls
Testing only one branch of the if statement
Using print statements instead of assertions
Combining multiple test cases into one
Bonus Challenge

Now add data-driven testing with 3 different prices and both member statuses

Show Hint