Course outline · 0% complete

0/29 lessons0%

Course overview →

Failure Messages That Explain

lesson 2-3 · ~9 min · 6/29

Make the failure do the talking

On a team, most test failures are read far from the code that caused them — in a terminal scrollback or an automated test report, often by someone who did not write the test. A bare assert got == 6 that fails tells that reader almost nothing: just AssertionError and a line number. Python lets you attach a message that travels with the failure:

assert got == 6, f"expected 6, got {got}"

The message only appears when the assert fails, so there is no cost when things are green. Write it for the future reader who sees the failure without the context you have right now: name the call, show the actual value, show the expected value.

One formatting tool helps a lot: {got!r} inside an f-string prints the value's repr, so strings keep their quotes. 'hello-world' with quotes is much clearer in a message than bare hello-world.

Code exercise · python

Run this. The assert is wrong on purpose so you can see the message in action. We catch the AssertionError and print it, the same way the lesson 1-3 runner would.

Code exercise · python

Run this second example and read the message. The failure looks impossible — 0.29 × 100 should be 29 — until the message shows you the actual value, 28. Floating-point numbers are stored in binary and 0.29 is not exact, so 0.29 × 100 lands at 28.999…, and int() cuts everything after the decimal point. Without the message you would stare at the formula; with it, the hypothesis is handed to you.

Quiz

When does the message in `assert cond, message` get evaluated and shown?

Code exercise · python

Your turn. The assert below fails silently with no message. Add one so the output becomes exactly: FAIL: slugify('Hello World') returned 'hello-world', expected 'helloworld' (use {got!r} to keep the quotes)