Test Overview
This test checks a simple function with an if-else branch. It verifies that both branches are tested to achieve full branch coverage.
Jump into concepts and practice - no test required
This test checks a simple function with an if-else branch. It verifies that both branches are tested to achieve full branch coverage.
def is_even(num): if num % 2 == 0: return True else: return False import pytest def test_is_even(): assert is_even(4) == True assert is_even(5) == False
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Calls is_even(4) | Function receives input 4 | Check if 4 % 2 == 0 branch is taken | PASS |
| 3 | Returns True for input 4 | Function returns True | Assert returned value is True | PASS |
| 4 | Calls is_even(5) | Function receives input 5 | Check if else branch is taken for 5 | PASS |
| 5 | Returns False for input 5 | Function returns False | Assert returned value is False | PASS |
| 6 | Test ends | All assertions passed | Branch coverage achieved for both if and else | PASS |
What does branch coverage measure in pytest testing?
Which pytest command option enables branch coverage measurement?
--cov enables coverage measurement, and --cov-branch adds branch coverage.pytest --cov --cov-branch to measure branch coverage.Given this code snippet tested with pytest and branch coverage enabled, what is the branch coverage result?
def check_num(x):
if x > 0:
return "Positive"
else:
return "Non-positive"
# Test cases:
assert check_num(5) == "Positive"
Identify the error in this pytest test that aims for full branch coverage:
def classify(n):
if n > 10:
return "High"
elif n > 5:
return "Medium"
else:
return "Low"
def test_classify():
assert classify(12) == "High"
assert classify(7) == "Medium"
You have this function. Which set of test inputs achieves 100% branch coverage?
def analyze_score(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
else:
return "C"