What a good test looks like: one behaviour, a clear failure
A test is read most when it fails. Write it for the person reading the failure at two in the morning.
A test makes three assertions in a row. The first one fails. What does pytest report?
You wrote a first test in A first unit test. It went red for the right reason and then green. This chapter is about the next step: a test that someone else can read, trust and act on, months from now, without you.
A test has two readers. The first is the machine, which only cares whether it passes. The second is a person who is looking at a failure. That person did not write the test, may not know the module, and is probably in a hurry. Everything in this chapter serves the second reader. A test that cannot be understood when it fails costs more than it earns, because people stop trusting a red build they cannot explain.
What a failure owes the reader
When a test fails, the report is the only thing the reader has. It carries four pieces of information: the test’s name, the line that failed, the values involved, and the code around that line. A good test makes each one answer a question.
| Piece | The question it answers |
|---|---|
| Name | Which behaviour of the system is broken? |
| Failing line | What did we expect? |
| Values | What did we get instead? |
| Surrounding code | What input produced it? |
Compare two failures from the same suite. The first is FAILED tests/unit/test_one.py::test_1 - assert False. The name says nothing, the line says nothing, and there are no values. You have to read and run the test to learn anything. The second is FAILED ...::test_vat_is_charged_on_the_discounted_goods - assert 112500 == 106875. The name names a rule of the business. The values tell you VAT came out about 5% too high. A person who knows that VAT applies after the discount will guess that the code taxed the full subtotal, and be right, before opening any file.
The goal is not to write long tests or to comment heavily. The goal is that the failure message of each test points at one rule.
One behaviour per test
A behaviour is one rule the system must follow, stated as a cause and an effect: given this input, this outcome. “An order of ₦15,000 gets 5% off” is a behaviour. “VAT is charged on the goods after the discount, not on delivery” is another. “price_cart works” is not a behaviour. It is a hope.
A test should check one behaviour. The reason is mechanical, and you predicted it above. When a test checks three behaviours with three assertions, two things go wrong:
- The first failure hides the others. Python stops the test at the first failing
assert. If the discount is wrong, you never find out whether VAT and delivery are also wrong, until you fix the discount and run again. Fixing three bugs takes three cycles instead of one. - The name cannot be specific. A test that checks discount, VAT and delivery can only be named after what it calls:
test_price_cart. That name is true whichever rule is broken, so it tells the reader nothing. Meszaros, in his catalogue of test smells, calls the pattern Assertion Roulette: it is hard to tell which of several assertions failed, and the reader has to work it out.
Beck’s list of test properties, Test Desiderata, has a name for the opposite virtue: a test should be specific. If a test fails, the cause of the failure should be obvious.
This is not a rule to have exactly one assert per test. Several assertions can describe one behaviour. A response with a status code and a body is one outcome, and a test that checks status == 201 and body["id"].startswith("ord_") is checking one thing: that an order was created. The test for the question “do these assertions have a single reason to fail?” is better than counting lines. If a different change to the code would break each one, they are different behaviours and they want different tests.
The size of a behaviour
Beginners over-split, and the cure is the same question. A behaviour is a rule someone could state in a sentence to a colleague. “The discount boundary is inclusive” is one. “discount_bp returns an integer” is not a rule anyone cares about. If you cannot say why a stakeholder, a regulator or a customer would want the test to exist, it is probably checking an accident of the code.
Names that say the behaviour
Your test runner prints the name of each failure in its summary. In CI, that line is often all anyone reads. Treat the name as the one-line description of the rule.
A good name has three properties:
- It is a sentence about the system, not about the method:
test_a_cart_of_15000_naira_gets_5_percent_off, nottest_price_cart_1. - It includes the condition that matters, so that a failing test and a passing test with a similar name differ in the way that matters.
- It is long if it needs to be. Nobody types a test name. Pytest prints it. A name of 60 characters costs nothing.
Compare these three names for the same test:
def test_1(): ...
def test_price_cart(): ...
def test_a_cart_of_15000_naira_gets_5_percent_off(): ...
If the third fails, the report already says what is wrong. If the first fails, you open the file. The SWE at Google book makes the same point from the other side: it recommends testing behaviours, not methods, because a method such as price_cart can have many behaviours, and one test per method forces you to name the test after the call.
Write the name before the body. If you cannot write the name, you do not yet know what the test is for.
Arrange, act, assert
A readable test has a shape. Meszaros calls it the Four-Phase Test: set up the fixture, exercise the system under test, verify the result, tear down. Most Python tests need only three of the four, because pytest fixtures handle teardown. The three are:
def test_a_cart_of_15000_naira_gets_5_percent_off():
quote = price_cart([Line(500_000, 3)], distance_km=3, now=NOW) # arrange and act, in one line
assert quote.tier_discount == 75_000 # assert
When the setup is longer, separate the phases with a blank line each, so the eye finds them. This one is the lab’s own test_declined_payment_puts_the_stock_back, rewritten in that shape:
def test_a_declined_card_puts_the_stock_back(db, clock):
declining = StubPayments(ChargeResult("", "declined", "insufficient_funds")) # arrange
with pytest.raises(PaymentDeclined): # act
place_order(db, declining, clock, [{"product_id": 2, "qty": 3}], "key-2")
assert db.stock_of(2) == 100 # assert
Three rules keep the shape honest.
Act once. If the test calls the system under test twice, it is two tests, or a test of something else, such as a replay. The exception is when the second call is the behaviour, as in “the same idempotency key returns the same order”.
Assert on the outcome, not on the steps. The assertion checks what a caller can observe: a return value, a stored row, a response. It does not check that a helper was called with certain arguments, unless that call is the behaviour. The chapter Fakes, stubs and mocks returns to this.
No logic in the test. No if, no loop over expected values, no helper that recomputes the answer with the same formula as the code. SWE at Google puts it this way: a clear test is trivially correct on inspection. A test that calculates its expected value with the same arithmetic as the code repeats the code’s mistake, and when it fails you cannot tell which copy is wrong. Write the expected number as a literal. 75_000 is ₦750, and you can check it with a calculator.
There is one place where the delivery test below computes a value (total - net - vat). It does so because it needs to isolate delivery from the other fields, and the expression has no business rule in it, only subtraction. Keep such expressions to a single line, and name the result.
Messages: when the default is enough
Pytest rewrites your assert statements so that a failure shows the values on both sides. You write assert quote.vat == vat_on(quote.net) and pytest prints assert 112500 == 106875 and then shows what each side came from. You get this for free, and in most tests it is enough.
It is not enough when the expression hides the meaning of the numbers. Consider a delivery test that checks quote.total - quote.net - quote.vat == 150_000. If the total omits the fee, the failure reads assert ((1531875 - 1425000) - 106875) == 150000. The reader has to do the subtraction to learn that delivery is missing from the total.
You have two fixes. The first is to name the intermediate value, so that the failure reads assert 0 == 150000 next to a name like delivery_in_total. The second is a message, which is the second argument of assert:
delivery_in_total = quote.total - quote.net - quote.vat
assert delivery_in_total == 150_000, (
f"total {quote.total} should be net {quote.net} + VAT {quote.vat} + delivery 150000"
)
Add a message when you can name something the default output cannot. Do not add one that repeats the test name ("discount should be 5%" on a test called ..._gets_5_percent_off) or one that restates the assert in words. A message nobody needs is noise, and it goes stale when the numbers change.
Test behaviour, not implementation
Google’s Testing on the Toilet episode on this subject has one rule: in most cases, tests should focus on the code’s public API, and the implementation details should not need to be exposed to tests. The payoff is that a test written against behaviour survives a rewrite. If you replace the loop in discount_bp with a table lookup and every test still passes, the tests did their job. If forty tests fail because they reached into a private helper, the tests were a copy of the old code.
Beck’s Desiderata name this property structure-insensitive: a test should not change its result if the structure of the code changes. It sits next to a second property, behavioural: if the behaviour changes, the test result should change. A good test has both. It fails when a rule breaks, and it stays green when you tidy the code.
The checkout service is a good place to feel the difference. price_cart returns a Quote. A test that asserts on quote.vat is a test of behaviour. A test that patches vat_on and checks it was called once with the net amount is a test of how price_cart happens to be written. The second one fails when you inline vat_on, and passes when you break the rate.
Where this goes wrong
Over-splitting. A suite of five hundred one-line tests, each with a clever name and none with a reason to exist, is not an improvement. Split when the behaviours are independent and the name gets specific. Do not split to be tidy.
Shared setup that couples the tests. If three tests use the same cart and share a literal, a single bug can fail all three, and the report looks like three bugs. Keep the shared part small (an input, not an expected value) and let each test compute its own expectation from a different angle. You will see this in the break at the end of the lab.
DRY applied to tests. Programmers learn not to repeat themselves, and then they hide each test’s inputs behind a helper three files away. SWE at Google argues for the opposite in tests: DAMP, descriptive and meaningful phrases. A little duplication is fine if it makes the test readable in one place. Helpers are good for boring setup (a database fixture), not for the facts the test is about.
Names that rot. test_discount_is_5_percent is a lie after the rate changes. Put the facts that change in the body, or name the rule and not the number.
Fixing the wrong thing. A test that fails with a message nobody can read is not fixed by deleting it. It is fixed by rewriting it so it fails well. You will practise this on a test you break on purpose.
You will write the test most people write first, break the code three ways, then split the test and compare the failures. The lab ships no test like this, so you write it. Work in labs/testing with the venv active (source .venv/bin/activate, or prefix commands with .venv/bin/).
1. Write the test that checks three things.
Create tests/unit/test_price_cart_fat.py. It prices a cart of three items at ₦5,000 each, 3 km from the buyer. That is ₦15,000, over the ₦10,000 discount tier, so it gets 5% off.
from datetime import datetime, timezone
from checkout.pricing import Line, price_cart
NOW = datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc)
def test_price_cart():
quote = price_cart([Line(500_000, 3)], distance_km=3, now=NOW)
assert quote.tier_discount == 75_000
assert quote.vat == 106_875
assert quote.total == 1_681_875pytest tests/unit/test_price_cart_fat.py -q1 passed. The numbers are in kobo: a 5% discount on 1,500,000 is 75,000, VAT of 7.5% on the 1,425,000 that remains is 106,875, and the total is that net plus VAT plus the 150,000 delivery fee for up to 5 km. All three assertions pass.2. Break the code three ways, one at a time.
Keep a copy of the file so you can restore it: cp checkout/pricing.py pricing.py.orig. Make one edit, run the test, write down the first line of the failure, then restore with cp pricing.py.orig checkout/pricing.py.
Break A. In DISCOUNT_TIERS, change the 5% tier from (1_000_000, 500) to (1_000_000, 50).
Break B. In price_cart, change vat = vat_on(net) to vat = vat_on(subtotal).
Break C. In the last line of price_cart, change net + vat + fee to net + vat.
pytest tests/unit/test_price_cart_fat.py -qtest_price_cart. A fails at the first assert: assert 7500 == 75000. B fails at the second: assert 112500 == 106875. C fails at the third: assert 1531875 == 1681875. Pytest prints the whole Quote under each, so a careful reader can recover the picture, but the report line and the name are identical for three different bugs, and only one assertion is ever reported. In A the VAT and the total are wrong too (they follow from the discount), and the failure never says so.Restore the file before you go on, and check with git diff checkout/pricing.py (no output means it is clean).
3. Split it into three tests named for behaviours.
Create tests/unit/test_price_cart_split.py. Each test has the same three parts, separated by blank lines.
from datetime import datetime, timezone
from checkout.money import vat_on
from checkout.pricing import Line, price_cart
NOW = datetime(2026, 11, 23, 9, 0, tzinfo=timezone.utc)
CART = [Line(500_000, 3)] # N15,000: over the N10,000 tier, under N50,000
def test_a_cart_of_15000_naira_gets_5_percent_off():
quote = price_cart(CART, distance_km=3, now=NOW)
assert quote.tier_discount == 75_000
def test_vat_is_charged_on_the_discounted_goods():
quote = price_cart(CART, distance_km=3, now=NOW)
assert quote.vat == vat_on(quote.net)
def test_delivery_is_added_to_the_total_after_vat():
quote = price_cart(CART, distance_km=3, now=NOW)
assert quote.total - quote.net - quote.vat == 150_000pytest tests/unit/test_price_cart_split.py -vPASSED, then 3 passed. The VAT test compares with vat_on(quote.net) and not with a literal, so that it fails only when VAT is computed on the wrong amount, and not when the discount is wrong. The delivery test checks the part of the total that is neither goods nor VAT.4. Repeat the three breaks.
Apply A, B and C as before, one at a time, and run pytest tests/unit/test_price_cart_split.py -q, restoring the file between runs.
test_a_cart_of_15000_naira_gets_5_percent_off, assert 7500 == 75000. B: test_vat_is_charged_on_the_discounted_goods, assert 112500 == 106875. C: test_delivery_is_added_to_the_total_after_vat, and the line reads assert ((1531875 - 1425000) - 106875) == 150000. The names alone now tell you which rule broke. Break C’s line is still hard to read, which is what step 5 fixes.5. Add a message only where the default is unclear.
Only the delivery test needs one. Replace its body with a named value and a message:
def test_delivery_is_added_to_the_total_after_vat():
quote = price_cart(CART, distance_km=3, now=NOW)
delivery_in_total = quote.total - quote.net - quote.vat
assert delivery_in_total == 150_000, (
f"total {quote.total} should be net {quote.net} + VAT {quote.vat} + delivery 150000"
)Apply break C again and run it.
AssertionError: total 1531875 should be net 1425000 + VAT 106875 + delivery 150000, then assert 0 == 150000. A reader now sees that delivery contributes 0 to the total. Restore pricing.py (and delete pricing.py.orig), delete test_price_cart_fat.py, and run pytest tests/unit -q: 13 passed (the ten starter unit tests plus your three in the split file).assert quote.vat == 106_875, and apply break A (the wrong discount). Two tests now fail for one bug, because the VAT literal assumed the correct discount. Which failure should you read first? Now change it back. The lesson is that sharing one cart is fine, but sharing an expected value across tests turns one bug into several reports. Then write a deliberately bad version of the name, test_vat, run break B, and compare the summary line with the good name. How much did the longer name save you? When you are done, delete tests/unit/test_price_cart_split.py and any test_vat you added: the next chapters count tests from the ten starter unit tests.Tallowmere's order service has a test, test_order_flow, that creates an order, pays it, checks the stock and checks the confirmation email in four assertions. It is 30 lines, takes 40 ms, and has failed twice this month. Both times, someone spent an hour finding which part broke. A colleague wants it left alone because it covers the whole flow.
- DOC Four-Phase Test Gerard Meszaros
The pattern for the arrange, act, assert shape, with its fourth phase, teardown. Read the first screen to see why separating phases helps the reader. The page says the book has since changed the text, so treat it as the idea, not the final wording.
- DOC Test Smells Gerard Meszaros
A catalogue of what goes wrong in tests, grouped by what you see. Read Assertion Roulette, Obscure Test and Conditional Test Logic first; they are this chapter's failures. Skip the production-code smells until later.
- DOC Test Desiderata Kent Beck
Twelve properties that make a test valuable, each with a short definition, and the point that they trade against one another. Use it as a checklist for a test you are reviewing: specific, readable, structure-insensitive.
- POST Testing on the Toilet: Test Behavior, Not Implementation Andrew Trenk, 2013
One page, one example: a refactoring that should not change any test. Read all of it; it takes five minutes.
- BOOK Software Engineering at Google, chapter 12: Unit Testing Erik Kuefler, 2020
The most complete short account of readable tests, free to read online. The sections named here are the ones this chapter draws on. Read: Test Behaviors, Not Methods; Don't Put Logic in Tests; Write Clear Failure Messages; DAMP, Not DRY. Skip the sections on Java test doubles for now..
- BOOK Unit Testing: Principles, Practices, and Patterns Vladimir Khorikov, 2020
A book-length treatment of behaviour versus implementation and how to tell a brittle test from a useful one. Read it after this course's module on test doubles, not before. Read: Part 1, on what a unit test is, and Part 2, on what makes a test good..
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.