Test path coverage for a simple function with multiple branches
Preconditions (2)
✅ Expected Result: All calls return the correct discounted price according to the function logic, covering all possible paths
import unittest # Function to test def calculate_discount(price: int, is_member: bool) -> int: if is_member: if price > 75: return int(price * 0.9) # 10% discount else: return price else: return price class TestCalculateDiscount(unittest.TestCase): def test_member_price_above_75(self): result = calculate_discount(100, True) self.assertEqual(result, 90) def test_non_member_price_above_75(self): result = calculate_discount(100, False) self.assertEqual(result, 100) def test_member_price_50(self): result = calculate_discount(50, True) self.assertEqual(result, 50) def test_non_member_price_50(self): result = calculate_discount(50, False) self.assertEqual(result, 50) if __name__ == '__main__': unittest.main()
The calculate_discount function has two decision points: whether the user is a member and whether the price is above 75. This creates four possible paths.
The test class TestCalculateDiscount has four test methods, each covering one path:
Each test calls the function with specific inputs and asserts the output matches the expected discounted price. This ensures full path coverage.
Using unittest framework provides clear structure and assertion methods. The tests are independent and repeatable.
Now add data-driven testing with 3 different input sets to cover all paths
path coverage testing ensure in software testing?if (x > 0) {
if (x < 10) {
print("A");
} else {
print("B");
}
} else {
print("C");
}if (a > 5) {
if (b == 0) {
print("X");
}
} else {
print("Y");
}if (x > 0) {
if (y > 0) {
print("P");
} else {
print("Q");
}
} else {
if (y > 0) {
print("R");
} else {
print("S");
}
}Pass the test and this pattern moves unknown