pytest is a testing framework that discovers test functions, runs them and reports failed expectations or execution errors.
Write checks that distinguish correct behavior from a regression, including invalid inputs and expected exceptions.
A parser change silently drops warning lines. A useful test must distinguish that broken implementation from the intended one. Start with a concrete expected record and a rejected input, make each check fail deliberately, then see how a runner collects and reports those checks.

Quarry has grown. It walks a yard of files, pulls fields out of log lines,
stores records in a vault and reports on them. Last week someone "tidied" the
log-line parser, every run still finished, and three days later the report
was quietly missing every WARN line. Nothing crashed, nothing warned — the
only way anyone could have known was to check. This section builds Quarry's
test rig, and this lesson writes its first tests.
Every lesson in this section tests the same small function. Quarry's log
lines look like WARN yard: disk 91% full — a level, a stage, a colon-space,
then free text:
The second line's message itself contains : , and partition splits only
at the first one, so the message survives intact. That is exactly the kind
of detail a later "tidy-up" breaks — and exactly what a test pins down.
Catch the regression that slipped through silently
assert is Python's one built-in test primitive:
The rule is strict, which is the point:
assert 0.1 + 0.2 == 0.3
print("passed")Watch out:
assertstatements are removed when Python runs with-O. That can also weaken tests outside pytest's assertion rewriting, but it's why you must never useassertto validate input in production — raise a real exception there, the wayparse_linedoes.
On your own machine you'd put tests like this in a file named test_*.py
and run pytest. No classes, no special assertion methods, no registration:
pytest collects every function starting test, runs each one
separately so one failure never stops the rest, and reports — rewriting
a failing assert before running it so you see the actual values, not
just False:
def test_keeps_colons_in_message():
> assert parse_line("INFO vault: a: b")["msg"] == "a:b"
E AssertionError: assert 'a: b' == 'a:b'
test_parse.py:9: AssertionError
========== 1 failed, 1 passed in 0.02s ==========This course runner does not launch pytest. Its supported browser
activities use plain Python, so we
build the same three jobs by hand and grade the tests you write by calling
them. A module is, underneath, a dictionary from names to objects;
globals() hands you that dictionary, so collection is a filter over it:
testing_helper was collected — pytest's default rule is the prefix
test, not test_. And the report has three buckets, not two: a
failure means the code ran and gave the wrong answer; an error means
it never got that far, because something else raised first. The distinction
tells you where to look.
def test_lookup():
levels = {"WARN": 2}
assert levels["ERROR"] == 3
try:
test_lookup()
print("passed")
except AssertionError:
print("failed")
except Exception as e:
print("error:", type(e).__name__)Preparing this topic’s interactive investigation…
Prove a bad line really gets refused
Half of parse_line's job is saying no. pytest checks that with a context
manager — the with block passes only if the code inside raises that
exception (or a subclass), and fails if nothing is raised:
import pytest
def test_rejects_line_without_separator():
with pytest.raises(ValueError):
parse_line("no separator here")That last sentence — the test fails if nothing is raised — is easy to lose when you write the check by hand:
This parse_line has a regression — it accepts junk. The test exists to catch exactly that, so it should report fail. It reports pass. Fix the TEST (not parse_line) so it cannot pass when nothing is raised.
A test that cannot fail is worse than no test — it turns green, and green is a promise. Every time you write one, make it fail once on purpose: break the code, or the expectation, and watch it go red.
Python's own unittest does the identical collect/run/report, just worded
differently — a method on a TestCase, self.assertEqual instead of
assert — and it does run here:
pytest runs unittest classes unchanged, so nothing written this way is
wasted. For small pure functions, doctest turns the docstring's own
example into the test, so documentation can't drift away from the code it
describes:
The next lesson, 05a, goes deeper into unittest and doctest, plus
tox — the tool that runs a whole suite across several Python versions.
Write a test that distinguishes two implementations
A test earns its place by separating correct behavior from a plausible mistake. For a parser, assert parse_line(line) only says the result is truthy. A parser returning the same nonempty dict for every line could pass it.
Start from a concrete contract: the first ": " separates the header from the message, while later colons belong to the message. Your test should therefore include a message containing that separator and assert the complete expected record. A second case should check rejection of an unknown level. These two tests answer different questions; neither is a substitute for the other.
Make the evidence fail: replace partition with split and take only element 1. The first assertion should fail. Restore it, then remove the raise ValueError; the second check should fail. This confirms that each test observes the behavior it claims to protect.
On a local project, put the corresponding tests in test_parser.py and run python -m pytest -q test_parser.py. Keep the installed interpreter and environment from the packaging lessons. The browser's small collector demonstrates mechanics; it does not execute pytest or reproduce every pytest outcome category. In pytest, an unexpected exception during the test call is usually reported as a failure; setup/teardown problems are errors. The exercise's separate errors bucket is its own simpler reporting contract.
Reference: pytest discovery and test practices.
Habits that make a suite worth having
Name tests for a behavior. Arrange input, exercise that behavior, and assert its observable result. Several assertions can belong together when they establish one contract. Test returned values for a pure function, stdout for a CLI, and stored state for a persistence operation. A bug becomes a test: the first thing you write when Quarry misbehaves is the failing test that reproduces it, which then stays forever — choose cases for distinct risks. Test counts do not establish a probability of correctness, and tests sharing an assumption can all miss the same bug.
Quick practice
def test_div():
assert 1 / 0 == 0
try:
test_div()
print("passed")
except AssertionError:
print("failed")
except Exception as e:
print("error:", type(e).__name__)class Suite:
def test_inside_class(self):
assert True
def test_top_level():
assert True
def run_all(namespace):
report = {"passed": [], "failed": [], "errors": []}
for name, obj in list(namespace.items()):
if not (name.startswith("test") and callable(obj)):
continue
try:
obj()
report["passed"].append(name)
except AssertionError:
report["failed"].append(name)
except Exception:
report["errors"].append(name)
return report
print(run_all(globals())["passed"])def test_always_true():
result = parse_line("junk")
assert True
LEVELS = ("DEBUG", "INFO", "WARN", "ERROR")
def parse_line(line):
head, sep, msg = line.partition(": ")
if not sep:
raise ValueError("no separator")
return {"level": head, "stage": "", "msg": msg}
try:
test_always_true()
print("passed")
except Exception as e:
print("error:", type(e).__name__)🎯 Your turn
Build check_parse(cases) — the first piece of the test rig. Each case is a
pair [line, expected], where expected is either the dict parse_line
should return or the string "ValueError" when the line must be refused.
Run every case and return a report:
passed— how many cases behaved as expectedfailed— indices of cases that returned the wrong thing, or returned when they should have raisederrors— indices of cases that raised something nobody expected
check_parse([["WARN yard: disk full", {"level": "WARN", "stage": "yard", "msg": "disk full"}],
["junk", "ValueError"],
["INFO vault: ok", {"level": "INFO", "stage": "yard", "msg": "ok"}]])
# → {"passed": 2, "failed": [2], "errors": []}parse_line is already in the starter. Run each case in its own try, so
one bad case can never stop the rest — that is the first thing every test
runner promises.
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
pytest imports files named test_*.py or *_test.py. Write is_test_file(filename) returning True for those and False for everything else.
Given a list of outcomes ("passed", "failed", "error"), write tally(outcomes) returning the summary line a runner prints last: counts in the order failed, passed, errors, zero counts left out, joined by ", ". Use error for one and errors for more. An empty list gives "no tests ran". Example: ["passed", "failed", "passed"] → "1 failed, 2 passed".
pytest's report shows which part of a dict was wrong. Write diff_keys(got, expected) returning a sorted list of strings, one per differing key: "k: missing" if only expected has it, "k: unexpected" if only got has it, and "k: <got repr> != <expected repr>" if both have it with different values. Equal dicts give [].
Write expect_raises(fn_name, arg, exc_name). Look up the function in FUNCS and the exception class by name in builtins, call FUNCS[fn_name](arg), and return "pass" if it raised that exception or a subclass of it, "fail: did not raise" if it returned, or "fail: raised <Name>" if it raised something else.
Write run_module(source). Execute the source text into a fresh namespace dict, collect every function whose name starts with test in the order it was defined, call each with no arguments, and return {"passed": [...], "failed": [...], "errors": [...]} of names. An AssertionError is a failure; any other exception is an error. Non-functions (like a list called test_data) are not collected.
A teammate adds a test for Quarry's parser that wraps the call in try: ... except ValueError: pass and it goes green. Explain why a test like that can be worse than having no test at all, and describe the habit that would have caught it.