Python Designing Good Tests
What you will learn
- Qualities of a good test: fast, independent, repeatable, clear
- The Arrange-Act-Assert shape and good names
- Choosing cases: normal, edge, boundary, error
- Making code testable
- Flaky tests and how to avoid them
- Coverage, and its limits
- Test-first development, and checking that tests can fail
1. Tests are code too
Lessons 18.2 and 18.3 showed the tools. This lesson is about what to test and how to write tests so they help rather than annoy. A good test suite is:
| Quality | Meaning |
|---|---|
| Fast | the whole suite runs in seconds, so you run it often |
| Independent | tests do not depend on order or on each other |
| Repeatable | same result every time, on any machine |
| Self-checking | pass or fail with no human judgement |
| Clear | a failure tells you what is wrong |
| Focused | each test checks one behaviour |
2. Arrange, Act, Assert
Give every test three parts, in this order:
def test_hours_and_minutes():
text = "1h30m" # Arrange: prepare the input
result = parse_duration(text) # Act: do the one thing
assert result == 5400 # Assert: check the outcome
Short tests may fold these into one line, but the order stays. If you need many asserts, or the Act part is several calls, the test probably checks more than one behaviour: split it.
Names
A test name should read as a sentence about behaviour; when it fails, the name alone tells you what broke:
| Weak | Better |
|---|---|
test1 |
test_seconds_only |
test_parse |
test_spaces_and_case_are_ignored |
test_error |
test_bad_text_raises_value_error |
Quick check: what are the three parts of a well-formed test?
Arrange (set up), Act (run the code under test), Assert (check the result).
3. Choosing cases
You cannot test every input, so choose carefully. For each function think of:
- Normal cases: typical, valid input.
- Boundaries: values at the edge of a rule. If
n < 10is "small", test 9 and 10. Most off-by-one bugs live here (lesson 18.1). - Empty and minimal: an empty string, empty list, zero, one item.
- Extremes: very large values, very long text, many items.
- Invalid input: the wrong type or an impossible value, expecting the right exception (lesson 14.4).
- Special characters: spaces, mixed case, non-English letters, newlines.
- Past bugs: the exact input that once failed.
A function classifying numbers shows why boundaries matter:
def classify(n):
if n < 0:
return "negative"
if n == 0:
return "zero"
if n < 10:
return "small"
return "large"
print([classify(x) for x in (-1, 0, 1, 9, 10)])
['negative', 'zero', 'small', 'small', 'large']
The inputs -1, 0, 1, 9, 10 sit on either side of every rule; (-1, 0, 5, 50) would have missed the edge between 9 and 10.
Properties
Sometimes you cannot predict one exact answer, but you know something that must always be true. The average of numbers lies between the smallest and the largest:
import random
def average(values):
return sum(values) / len(values)
random.seed(1)
for _ in range(1000):
xs = [random.randint(-100, 100) for _ in range(random.randint(1, 20))]
assert min(xs) <= average(xs) <= max(xs)
print("property holds")
property holds
This "property" check tried 1,000 random lists. (Libraries such as hypothesis automate this style.)
4. Make code testable
Tests are easy when functions take what they need as arguments and return results (lesson 13.9). Hard-wired things make tests slow or unpredictable:
| Hard to test | Make it testable by |
|---|---|
the current time (datetime.now()) |
passing the time in |
| random numbers | passing a random.Random(seed) or the value in |
| files, web, databases | passing the file/client in, or using tmp_path, mocks (lesson 18.2) |
print output |
returning the text and printing at the edge |
| environment variables | passing settings in; monkeypatch |
For example, a greeting that depends on the time:
import datetime
def greeting(now=None):
now = now or datetime.datetime.now()
return "Good morning" if now.hour < 12 else "Good afternoon" if now.hour < 18 else "Good evening"
print(greeting(datetime.datetime(2026, 1, 1, 9)))
print(greeting(datetime.datetime(2026, 1, 1, 13)))
print(greeting(datetime.datetime(2026, 1, 1, 20)))
Good morning
Good afternoon
Good evening
Because the time can be passed in, a test can check every part of the day at any hour.
5. Flaky tests
A flaky test passes sometimes and fails sometimes with no code change. They destroy trust: people start ignoring failures. Usual causes and cures:
| Cause | Cure |
|---|---|
| depends on the clock or dates | pass a fixed time in |
| unseeded randomness | seed a private generator |
| tests share state (a file, a global, a database) | give each test fresh state (fixtures, tmp_path) |
| depends on test order | make tests independent |
| real network or slow services | fake them |
timing (sleep then check) |
wait for a condition, or fake the clock |
| dictionary/set order assumptions | compare as sorted lists or sets |
The classic shared-state trap is a mutable default argument:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"), add_item("b"))
['a', 'b'] ['a', 'b']
Both calls return the same list, so a test that calls add_item twice in a suite sees leftovers from earlier tests (lesson 11.9).
6. Coverage
Coverage measures which lines (and branches) of your code the tests actually run. The coverage tool (installed with python -m pip install coverage) reports it:
python -m coverage run --branch -m pytest
python -m coverage report -m
Using only two tests for classify (-1 and 5):
Name Stmts Miss Branch BrPart Cover Missing
----------------------------------------------------
cls.py 8 2 6 2 71% 5, 8
Missing lists the lines never run: line 5 (return "zero") and line 8 (return "large"). That tells you precisely which cases to add. The limits of coverage:
- 100 percent coverage does not mean no bugs. A test can run a line without checking anything about the result.
- Chasing the number can produce useless tests. Treat it as a map of untested code, not a goal.
- Missing coverage in important code is a warning; missing coverage in trivial code is not.
7. Tests that can fail
A test that cannot fail is worthless. Two ways to check:
Test first (TDD). Write the test before the code, watch it fail (red), write the simplest code that passes (green), then clean up (refactor). Seeing the red proves the test can detect a missing feature. For example, with the function body replaced by raise NotImplementedError, all 17 tests of the worked example below fail:
17 failed in 0.11s
Break the code on purpose ("mutation testing" by hand). Make a small deliberate mistake and confirm that some test notices. If every test still passes, a test is missing. In the worked example, removing one check from the function makes two tests fail:
FAILED test_m.py::test_bad_text_raises_value_error[1h 30] - Failed: DID NOT RAISE
FAILED test_m.py::test_bad_text_raises_value_error[-5m] - Failed: DID NOT RAISE
2 failed, 15 passed
Those two cases ("1h 30" and "-5m") exist precisely because they catch that mistake.
Worked example: a duration parser, test-first
Goal: turn text like "1h30m" into seconds. We list behaviours first, then write tests, then the function.
test_duration.py:
import pytest
from duration import parse_duration
def test_hours_and_minutes():
assert parse_duration("1h30m") == 5400
def test_seconds_only():
assert parse_duration("90s") == 90
def test_spaces_and_case_are_ignored():
assert parse_duration(" 2H 5m 10S ") == 7510
@pytest.mark.parametrize("text, seconds", [
("0s", 0),
("59s", 59),
("60s", 60),
("1m", 60),
("1h", 3600),
("100h", 360000),
])
def test_boundaries(text, seconds):
assert parse_duration(text) == seconds
@pytest.mark.parametrize("bad", ["", " ", "abc", "10", "1x", "1h 30", "-5m"])
def test_bad_text_raises_value_error(bad):
with pytest.raises(ValueError):
parse_duration(bad)
def test_wrong_type_raises_type_error():
with pytest.raises(TypeError):
parse_duration(90)
Red: with a stub parse_duration that raises NotImplementedError, 17 failed.
Green: the function (duration.py):
import re
_PART = re.compile(r"(\d+)\s*([hms])")
def parse_duration(text):
"""Turn '1h30m', '90s' or '2h 5m 10s' into a number of seconds."""
if not isinstance(text, str):
raise TypeError("text must be a string")
cleaned = text.strip().lower()
if not cleaned:
raise ValueError("empty duration")
matches = _PART.findall(cleaned)
if not matches or _PART.sub("", cleaned).strip():
raise ValueError(f"cannot read duration: {text!r}")
factor = {"h": 3600, "m": 60, "s": 1}
return sum(int(number) * factor[unit] for number, unit in matches)
................. [100%]
17 passed in 0.03s
Coverage with --branch:
duration.py 13 0 6 0 100%
Mutation check: deleting or _PART.sub("", cleaned).strip() (the part that rejects leftover text) made "1h 30" and "-5m" pass silently, and exactly those two tests failed, as shown above.
| Idea | Where |
|---|---|
| Arrange-Act-Assert, descriptive names | the first three tests |
| boundaries | 0s, 59s, 60s, 1m: the edge between seconds and minutes |
| invalid input as data | the bad list, one line per case |
| the type error | parse_duration(90) |
| the test caught a deliberate bug | the mutation check |
The inputs are examples chosen for the lesson. The regular expression is explained in lesson 17.6.
Common mistakes
- One giant test that checks many things.
- Tests that depend on the clock, randomness, network or order.
- No edge cases: only the happy path.
- Asserting nothing useful, or copying the code's logic into the test.
- Testing implementation details that change often, instead of behaviour.
- Chasing 100 percent coverage with empty tests.
- Ignoring flaky tests or deleting failing tests to get green.
- Never seeing a new test fail, so not knowing that it works.
Key takeaways
- Good tests are fast, independent, repeatable, clear and focused: Arrange, Act, Assert, with descriptive names.
- Choose cases deliberately: normal, boundaries, empty, extremes, invalid input, special characters, past bugs.
- Make code testable by passing in time, randomness, files and clients.
- Remove flakiness by controlling time, randomness, shared state and order.
- Coverage shows untested lines; it does not prove correctness.
- Watch a test fail first, and break the code on purpose to prove the tests notice.
Practice
1. Which values would you test for a rule "valid if 1 <= n <= 10"?
Show answer
The boundaries and their neighbours: 0, 1, 2, 9, 10, 11.
2. How can you make greeting() testable?
Show answer
Let it accept the current time as a parameter (defaulting to datetime.now()), so tests pass fixed times.
3. What is a flaky test?
Show answer
One that sometimes passes and sometimes fails without any change in the code, usually because of time, randomness, shared state or the network.
4. Does 100 percent coverage prove a program is correct?
Show answer
No. It shows that every line ran, not that results were checked or that all inputs work.
5. Why watch a new test fail before making it pass?
Show answer
It proves the test can detect the missing behaviour; a test that never fails could be checking nothing.
6. Name three things worth testing for a function that reads a number from text.
Show answer
A normal number, spaces around it, an empty string, text that is not a number (expecting ValueError), negative and very large values.