A metric indicating how much of your code is executed by automated tests.
Test Coverage (or Code Coverage) measures the percentage of source code lines, branches, or functions that are executed when your test suite runs. While 100% coverage doesn't guarantee your code is bug-free, low coverage guarantees that you are deploying untested logic.
The most important metric is often Branch Coverage, which ensures that every possible path (e.g., both the `if` and the `else` blocks) is tested, rather than just the happy path.
Consider a simple discount calculation. If your test only passes `is_member = True`, you have 100% function coverage, but only 50% branch coverage.
def get_price(price, is_member):
# Branch 1
if is_member:
return price * 0.9
# Branch 2 (Untested if we only test members!)
else:
return price
# TEST
def test_get_price():
assert get_price(100, True) == 90
# Missing test for get_price(100, False)!
A billing system has 95% line coverage. However, the one untested block is an `except DatabaseError:` block that sends an alert. In production, the database goes down. The `except` block executes for the first time, but it contains a typo (`sned_alert()` instead of `send_alert()`), causing a fatal crash and wiping out the user's payment state before the transaction can be rolled back.
Why might 100% Line Coverage still miss a critical bug?