A unit test runs a small piece of code and compares its result with an expected result. A passing test only covers the cases it actually runs; it cannot establish correctness for every input.
Consider an average. Dividing by the number of values works for a nonempty list, but an empty list would divide by zero. This implementation deliberately defines the empty result as 0.0; another application may instead reject the input.
def average(values: list[int]) -> float:
if not values:
return 0.0
return sum(values) / len(values)
cases = [([4, 6], 5.0), ([7], 7.0), ([], 0.0)]
for values, expected in cases:
actual = average(values)
print(values, "->", actual, "matches:", actual == expected)
[4, 6] -> 5.0 matches: True
[7] -> 7.0 matches: True
[] -> 0.0 matches: True
A test for only the first two cases would miss the empty-input failure in a version without the guard. A failing test can identify the gap between a chosen rule and implementation; after changing the implementation, run the cases again. This feedback cycle is part of test-driven development when the test is written before the implementation. Libraries such as Python’s unittest and third-party pytest provide richer reporting and organization. For many floating-point results, approximate comparison is safer than exact equality; these particular expected results are exactly representable.