A first unit test
Arrange, act, assert: write one test for one function, watch it fail for the wrong reason and then the right one, and read what pytest tells you
You write your first test for a pricing function and run it. It fails. Which failure tells you the test is doing its job?
A unit test is a small program that calls one piece of your code with chosen inputs and checks the result. It runs in milliseconds, needs no server and no database, and tells you a yes or a no. That is all it is. Everything later in this course (what to test, how many tests, how to keep them fast and honest) builds on this one shape, so this chapter spends its time on the shape and on one habit: never trust a test you have not seen fail.
The code under test
Open checkout/pricing.py in the lab. The function you test first is the smallest one in it:
@dataclass(frozen=True)
class Line:
unit_price_kobo: int
qty: int
def line_total(line: Line) -> int:
... # a guard that raises ValueError when qty is below 1 (shown later)
return line.unit_price_kobo * line.qty
A basket is a list of lines. A line is a price and a quantity. The total of a line is the price times the quantity, in kobo (100 kobo is ₦1), as a plain integer. Money is an integer in this lab for the reason you will meet again in testing-money: a float cannot hold ₦18.50 exactly, and a test that compares floats ends up checking whether two rounding errors cancel.
The lab models the checkout service of Ojaline, a marketplace, not Tallowmere’s pharmacy. The rule is the same one any basket has, so Hawa’s request translates directly: one product at ₦1,850 (185,000 kobo), four of them, and a line total of ₦7,400, which is 740,000 kobo. The prices are illustrative.
Notice what this function is: it takes a value and returns a value. It reads no clock, no file and no network. That is why it is the right first target. You can call it with any input you like and the answer depends on nothing else. Code that is not shaped like this needs extra work before it can be tested, and the chapter Fakes, stubs and mocks covers that work.
The shape of a test
Every unit test, in every language, has three parts. People call them different things. This course uses the common set:
- Arrange. Build the inputs: here, a
Linewith a price and a quantity. - Act. Call the code under test, once.
- Assert. Compare the result with the answer you worked out by hand, before you ran anything.
In pytest the whole thing is a function whose name starts with test_, and the assert is the Python keyword:
from checkout.pricing import Line, line_total
def test_line_total_multiplies_price_by_quantity():
line = Line(185_000, 4) # arrange
total = line_total(line) # act
assert total == 740_000 # assert
Three things about this are worth saying aloud.
The expected value is worked out separately. You did the sum on paper: 185,000 times 4 is 740,000. The test does not compute it with the code under test, and it does not copy the code’s formula. A test that says assert line_total(line) == line.unit_price_kobo * line.qty repeats the implementation. If the implementation is wrong, the test is wrong in the same way, and it passes. This is exactly what happened to Jabu.
The name says the behaviour. test_line_total_multiplies_price_by_quantity is a sentence. When it fails in six months, the report says that sentence, and whoever reads it knows what broke before opening the file. test_1 and test_line_total_works say nothing.
One act, one reason to fail. The test calls the function once and checks one idea. If it checked the line total, the VAT and the delivery fee, three different faults would produce the same red line. The chapter What a good test looks like takes this much further.
How pytest finds your test
You do not register tests anywhere. pytest walks the directories under testpaths (the lab’s pyproject.toml sets it to tests), imports every file whose name matches test_*.py or *_test.py, and runs every function in them whose name starts with test. When pytest scans a directory, a file called my_first_test_file.py is never collected, and nothing tells you so: you get no tests ran and no error. If a test you wrote does not appear in the output, the name is the first thing to check.
Each test runs on its own. It passes if it returns normally, fails if an assertion raises AssertionError, and is also reported as failed if any other exception escapes the test body (a ValueError from the code, or a different exception type than pytest.raises expects). Pytest reports an error only when something goes wrong around the test: a collection problem, such as an import that fails at the top of the file, or a fixture that breaks in setup or teardown. A failure says the test ran and the answer was not what you expected. An error says the test could not get as far as running. The first is information about your code or your expectation. The second is usually information about your test file.
The lab also installs pytest-randomly, which shuffles the order tests run in and prints Using --randomly-seed=... at the top. It is there to catch tests that depend on each other (the order-dependent tests lesson shows how). For these first runs you can switch it off with -p no:randomly so the order is stable and your output matches this page.
Red, red, green
Write the test, then break it twice before you let it pass. It sounds like ceremony. It is the cheapest check there is that the test is connected to anything.
Red for the wrong reason. Misspell the name you import, line_totals for line_total. Run the file and pytest reports an ImportError while collecting. No test ran. The count at the bottom says 1 error, not 1 failed. This is the commonest first-test mistake, and it is harmless as long as you know that it is not the failure you want.
Red for the right reason. Fix the import and give the assert a wrong expected value: 7_400, as if the answer were in naira rather than kobo. This is a real mistake, because the lab speaks kobo and a human reads naira. Now the test runs, calls the function, compares, and fails. That is the red you were looking for.
Green. Put the correct value back, 740_000, and the test passes.
A test you have seen go red and then green has shown two things: it can fail, and it passes when the code is right. A test you only ever saw green shows neither. Kent Beck builds Test-Driven Development: By Example on this loop (red, green, refactor), and the first part of the book is a small money example, which suits a course about checkout. You return to the full practice in the chapter on test-driven development. Here you use only its first step: see it fail.
Reading what pytest tells you
When the assertion fails, pytest prints more than AssertionError:
> assert line_total(Line(185_000, 4)) == 7_400
E assert 740000 == 7400
E + where 740000 = line_total(Line(unit_price_kobo=185000, qty=4))
E + where Line(unit_price_kobo=185000, qty=4) = Line(185000, 4)
You wrote a bare assert. You did not call assertEqual, and you did not pass a message. Yet the report shows the result of the call, the value you expected and the object you passed in. That is assertion rewriting. When pytest imports a test module it rewrites the assert statements in it, so that each sub-expression is kept and printed if the assert fails. (--assert=plain switches it off, and you would then get a bare AssertionError with no values.)
Read the report from the bottom. The where lines unwind the expression: the left side 740000 came from line_total(...), which was called with a Line whose price was 185,000 and whose quantity was 4. The first E line is the comparison that failed: 740000 == 7400. In this case the numbers differ by a factor of exactly 100, and that is the signature of a kobo and naira mix-up. A good failure report points at the cause, and pytest builds it for you.
Rewriting applies to test modules and to the files a plugin registers. It does not rewrite the code under test, so an assert inside pricing.py behaves as it always does.
Check that the test can catch a bug
A green test shows that this input gives this output. It does not show that the test would notice if the code broke. You can check that directly, by hand: change the code on purpose and see whether the test goes red. This is a mutation. In tst2 you will meet the tool that does it by the hundred. Do one by hand now.
In checkout/pricing.py, change line.unit_price_kobo * line.qty to line.unit_price_kobo + line.qty and run the test. With 185,000 and 4 the code now returns 185,004, and the test fails with assert 185004 == 740000. The test is watching the behaviour it claims to watch.
Now try the same mutation against a test with weaker inputs:
def test_two_times_two_is_four_and_so_is_two_plus_two():
assert line_total(Line(2, 2)) == 4
Run it against the mutated code and it passes: 2 times 2 and 2 plus 2 are both 4. This test would not notice the bug. The inputs hide it. Choosing inputs that cannot hide a bug is a skill of its own, and it is the whole subject of the boundary values lesson and of the chapter Choosing test cases.
The lab’s existing tests/unit/test_pricing.py uses Line(250_000, 3) and the same mutation fails it too: 250003 against 750000. Good. That test was already doing its job for this function. The weakness in the starter suite is elsewhere: you met it in Why we test, where the suite stayed green with the discount edge broken.
A test for the unhappy path
line_total has a second behaviour: a quantity under 1 raises ValueError("qty must be at least 1"). A test for it needs pytest.raises:
import pytest
def test_a_quantity_of_zero_is_refused():
with pytest.raises(ValueError, match="qty must be at least 1"):
line_total(Line(185_000, 0))
If the code does not raise, the test fails with DID NOT RAISE. If it raises a different exception type, that exception propagates and the test fails with it. match is a regular expression searched in the message; it keeps the test from passing on an unrelated ValueError. Mutate the guard (change the 1 in it to 0) and confirm the test goes red. Quantity 0 is an edge, and edges are where code usually breaks.
Where to put the file
The lab keeps its unit tests in tests/unit/, next to test_money.py and test_pricing.py. A unit test goes in a directory called unit because you will later add tests/integration/ for tests that touch a real database, and you want to run them separately. A fast folder you run on every save and a slow folder you run on every push is a habit worth starting before you need it. Both directories contain an __init__.py, which makes each test module importable by its full name; this avoids a clash when two folders have a file called test_orders.py. pytest’s own good-practices page explains the options and why the lab’s layout works.
Put your test in tests/unit/test_my_first.py. The name is deliberately a placeholder. Real test files are named after the module they cover.
You write one test, break it twice on purpose, make it pass and then break the code to see it fail. Everything runs from labs/testing. Pytest output below is trimmed, and file paths are shortened.
1. Run the starter suite so you know what green looks like.
cd labs/testing
.venv/bin/pytest tests/unit -q -p no:randomly10 passed in about 0.1 s, one dot for each test in test_money.py and test_pricing.py. The full suite has more tests; you are running only the unit folder.2. Write the test with a wrong import. Create tests/unit/test_my_first.py with this content. The name line_totals is wrong on purpose.
from checkout.pricing import line_totals, Line
def test_line_total_multiplies_price_by_quantity():
assert line_totals(Line(185_000, 4)) == 740_000.venv/bin/pytest tests/unit/test_my_first.py -v -p no:randomlyERROR collecting tests/unit/test_my_first.py, then ImportError: cannot import name 'line_totals' from 'checkout.pricing', and 1 error at the bottom. No test ran. This is red for the wrong reason: the report is about your typo, not about the code.3. Fix the import, break the assertion. Replace the file with the version below. The expected value is wrong as if the answer were in naira.
from checkout.pricing import line_total, Line
def test_line_total_multiplies_price_by_quantity():
assert line_total(Line(185_000, 4)) == 7_400.venv/bin/pytest tests/unit/test_my_first.py -v -p no:randomlyFAILED, with the report assert 740000 == 7400, then two where lines showing line_total(Line(unit_price_kobo=185000, qty=4)). The footer says 1 failed. This is red for the right reason. Read the report from the bottom, as the chapter shows, and say aloud what each line tells you.4. Make it green. Change 7_400 to 740_000 and run the same command.
PASSED and 1 passed. You have now seen the test fail and pass, which is the evidence that it checks something.5. Break the code, not the test. Open checkout/pricing.py in your editor. In line_total, change line.unit_price_kobo * line.qty to line.unit_price_kobo + line.qty. Save, then run your test and the unit folder.
.venv/bin/pytest tests/unit/test_my_first.py -p no:randomly
.venv/bin/pytest tests/unit -q -p no:randomlyassert 185004 == 740000. The unit folder reports 2 failed, 9 passed: yours, and the starter test_pricing.py::test_line_total (assert 250003 == 750000). Two independent tests both catch the same bug.6. Add a test that cannot catch it, and one for the unhappy path. Leave the mutation in place. Replace tests/unit/test_my_first.py with all three tests:
import pytest
from checkout.pricing import Line, line_total
def test_line_total_multiplies_price_by_quantity():
assert line_total(Line(185_000, 4)) == 740_000
def test_two_times_two_is_four_and_so_is_two_plus_two():
assert line_total(Line(2, 2)) == 4
def test_a_quantity_of_zero_is_refused():
with pytest.raises(ValueError, match="qty must be at least 1"):
line_total(Line(185_000, 0)).venv/bin/pytest tests/unit/test_my_first.py -v -p no:randomlyFAILED for the first test (assert 185004 == 740000), PASSED for the second and PASSED for the third: 1 failed, 2 passed. The second test passes against broken code. That is the weak test from the chapter. The third passes because the guard on quantity is untouched.7. Revert the mutation and run everything. Change the + in line_total back to *, or restore the file with git checkout -- checkout/pricing.py if your copy is a git clone. Then:
.venv/bin/pytest tests/unit -q -p no:randomly13 passed in about 0.1 s: the ten starter tests plus your three. Later chapters reuse the habit, not the file, and their counts assume a clean tests/unit/.Break it further. Change the guard in line_total from if line.qty < 1: to if line.qty < 0: and run your tests. Which one fails? Now change it to if line.qty < 2:. Does anything fail? Then rename your file to my_first_check.py and run pytest tests/unit again. Where did your tests go, and what did pytest say about it?
When you are done, delete tests/unit/test_my_first.py (or my_first_check.py) so that tests/unit/ holds only the two starter test files. Every later chapter counts tests from that state: 10 passed for the unit folder, 23 passed, 1 skipped, 1 deselected for the whole suite.
Hawa, Tallowmere's first tester, has asked Jabu for one test on the basket total before Friday's release. The basket code mixes pricing with a database read for prescription items. Jabu has two hours. He can test the pure arithmetic of a line total in ten minutes, or spend the afternoon making the whole basket function testable first.
- DOC pytest: Get Started
The official first page: install, a first test, asserting that an exception is raised, grouping tests in a class and using a built-in fixture. Read it in ten minutes; skip the fixture section for now, it returns in the chapter on test data.
- DOC pytest: How to write and report assertions in tests
The reference for what this chapter showed: assertion introspection, pytest.raises with match, and how to turn assertion rewriting off. Skip the section on defining your own comparison hooks.
- DOC pytest: Good Integration Practices
Where test files live, how they are named and how pytest imports them, with the trade-offs between layouts. Read the test-discovery and test-layout parts to see why the lab's tests/unit folder works.
- BOOK Test-Driven Development: By Example Kent Beck, 2002
The source of the habit of watching a test fail first. The book is short and every step is small enough to follow with a pencil. Read: Part I, the money example (chapters 1 to 17): the red, green, refactor loop on a small money class. Skip Part II, the xUnit implementation, until you have read the chapter on test-driven development..
- POST Unit Test Martin Fowler, 2014
A short, honest account of the fact that there is no single definition of a unit test, and of the two camps (solitary and sociable) that disagree. Read it to see why people argue; the lab's test needs no definition to be useful.
- BOOK Unit Testing: Principles, Practices, and Patterns Vladimir Khorikov, 2020
A rigorous argument for what makes a test worth keeping. Chapter 1 explains why a growing suite can slow a project down, which is the cost behind everything this course asks you to weigh. Read: Chapter 1 (the goal of unit testing) and chapter 2 (what a unit test is). Skip the chapters on mocks and database testing until you meet them in this course..
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.