Debugging and testing · 3 / 14 Theory

assert and test cases

The best way to find logic errors is to test the code with cases whose result you already know. The simplest tool in Python is assert.

The assert statement

assert condition, message does nothing if the condition is true. If it is false, it raises an AssertionError with the message:

def is_leap(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

assert is_leap(2024) == True
assert is_leap(1900) == False, "1900 is not a leap year"

print("All the tests pass")   # All the tests pass

# assert is_leap(2023), "2023 is not a leap year"
# AssertionError: 2023 is not a leap year

If all the assert statements pass, the program carries on silently. As soon as one fails, the program stops and tells you which one.

Test case table

Instead of writing many assert statements, it is more convenient to store the cases in a list of pairs (input, expected result) and loop over it:

cases = [
    (2000, True),
    (1900, False),
    (2024, True),
    (2023, False),
]

failures = 0
for year, expected in cases:
    got = is_leap(year)
    if got == expected:
        print(f"{year}: OK")
    else:
        print(f"{year}: FAIL (expected {expected}, got {got})")
        failures += 1

print(f"Failures: {failures}")
# 2000: OK
# 1900: OK
# 2024: OK
# 2023: OK
# Failures: 0

Adding a new case is adding one line. Practice with Testing with assert and Text test table.

Finding an error with a test

Let us look at a function with a hidden bug. We test it by comparing with the correct result:

def maximum(items):
    largest = 0
    for n in items:
        if n > largest:
            largest = n
    return largest

print(maximum([3, 8, 1]))        # 8   (it seems to work)
print(maximum([-5, -2, -9]))     # 0   (it should be -2!)

The bug: largest starts at 0, so it is never smaller than 0. Only a case with all the numbers negative discovers it. Practice with Hunt the bug. The fix is to start with the first element:

def maximum(items):
    largest = items[0]
    for n in items:
        if n > largest:
            largest = n
    return largest

print(maximum([-5, -2, -9]))     # -2

assert as a precondition

assert is also used to check that a function receives valid data, and it fails clearly if not:

def divide(a, b):
    assert b != 0, "The divisor cannot be zero"
    return a / b

try:
    divide(5, 0)
except AssertionError as e:
    print("Error:", e)   # Error: The divisor cannot be zero

Practice with Preconditions with assert.

When NOT to use assert

assert is for detecting programmer errors, not for validating user data. Python can be run with the -O option, which disables assert statements. For external data (an age typed by the user, a file), use if and raise an exception:

def read_age(text):
    age = int(text)
    if age < 0:
        raise ValueError("The age cannot be negative")
    return age

try:
    read_age("-3")
except ValueError as e:
    print(e)   # The age cannot be negative