0
0
PyTesttesting~15 mins

Branch coverage in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test branch coverage for a function with conditional branches
Preconditions (2)
Step 1: Create a function that returns 'Positive' if input is greater than 0, 'Zero' if input is 0, and 'Negative' if input is less than 0
Step 2: Write test cases to cover all branches of the function
Step 3: Run pytest with coverage to verify branch coverage
✅ Expected Result: All branches of the function are executed and verified by tests, resulting in 100% branch coverage
Automation Requirements - pytest
Assertions Needed:
Assert function returns 'Positive' for input > 0
Assert function returns 'Zero' for input == 0
Assert function returns 'Negative' for input < 0
Best Practices:
Use clear and descriptive test function names
Use pytest parametrize to cover multiple inputs
Use coverage.py with branch coverage enabled
Keep tests independent and simple
Automated Solution
PyTest
import pytest

def check_number_sign(num: int) -> str:
    if num > 0:
        return 'Positive'
    elif num == 0:
        return 'Zero'
    else:
        return 'Negative'

@pytest.mark.parametrize('input_value, expected_output', [
    (10, 'Positive'),
    (0, 'Zero'),
    (-5, 'Negative')
])
def test_check_number_sign(input_value, expected_output):
    assert check_number_sign(input_value) == expected_output

The function check_number_sign has three branches: one for positive numbers, one for zero, and one for negative numbers.

The test uses pytest.mark.parametrize to run the same test logic with three different inputs, covering all branches.

This ensures 100% branch coverage because each conditional path is tested.

Assertions check that the function returns the correct string for each input.

Using parametrize keeps the test code clean and easy to maintain.

Common Mistakes - 3 Pitfalls
Writing only one test case that covers a single branch
Using print statements instead of assertions
Not enabling branch coverage in coverage.py
Bonus Challenge

Now add data-driven testing with 3 different inputs using pytest parametrize

Show Hint