──────────────────────────────────────

35. The Repair Bench · Write a Test That Can Fail

Test a function using assert and describe the condition that failed.

Lesson files · lessons/debugging-and-tests/assertions

Before you start
- Call a function and use its return value.
- Read the error type and line number in a traceback.

By the end
- Use assert to compare a returned number with an expected result.
- Use a failing test to locate a mistake in the calculation.
- Explain why a test with zero alone can miss the mistake.

Where you can use it
Check a scoring rule after you edit it. Run assertions for a typical score and a boundary so you can catch a mistake right away.

An assertion checks a condition you expect to be true. In assert double(4) == 8, Python calls double(4) and compares its result with 8. If the check fails, Python raises AssertionError and stops at that line.

Choose expected results by hand. The starter's test of triple(4) catches a wrong multiplier. Its test of triple(0) checks that zero stays zero. Use assertions to test your functions. Use branches or exceptions to handle unexpected input from users.

Predict
What happens if double(4) returns 7?
- Python stops at the failing assertion.
- Python silently prints Tests passed.

Worked example (example.py)

def double(number):
    return number * 2

assert double(4) == 8
assert double(0) == 0
print("Tests passed")


Example result
Tests passed

Run the starter and read its failing assertion. Repair triple so triple(4) is 12 and triple(0) is 0. Keep both checks and add an assertion for a negative number. The last line displays the result for the number in Program input.

Starter program (starter.py)

def triple(number):
    return number * 2

assert triple(4) == 12, "Four times three should be twelve"
assert triple(0) == 0
print(f"Tripled: {triple(int(input()))}")


Starter input
4

Hint
Leave the expected results in the assertions as written. Change the return expression so the positive and zero tests pass.

Case 1. Try the sample
Input
4
Expected output
Tripled: 12

Case 2. Different input
Input
-3
Expected output
Tripled: -9

Stretch
Add a message to one assertion after a comma. Temporarily change its expected result, read the message in the traceback, then restore the correct test.

Reflect
Which single bug would the normal case catch that the zero case would miss?

Check your prediction
Python stops at the failing assertion. A failed assertion raises AssertionError before the final print.
