pytest idioms

P30.pytest-foundations.01 · Audience: guest, it-ml, language-pro

Real LLM grading for this pageLLM grading (this page):

A test is just a function that runs your code and asserts what should be true. pytest adds almost nothing to that - a runner that finds test_* functions, a richer assert, and one context manager for exceptions. This module builds the two idioms you reach for every day, and the surprise is how small they are: the practice panel on your right is itself a from-scratch test runner, so you are learning the tool by rebuilding its parts.

Step 1 / 3assert is the whole language
ⓘ Concept: A test asserts one behaviour
A pytest test is a function named test_* that arranges some inputs, calls your code once, and asserts on the result. No return, no framework ceremony - if an assert fails, pytest reports that test as failed and shows the values. The discipline is one behaviour per test with a name that says which behaviour, so a red test names the bug before you open the file.

Why it matters — Every gate in this repo's own `make quality` ends in a pytest run; the entire edifice rests on plain assert statements checking one thing at a time.

Ask the mentor about this module

Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

2 graded rungs · ~24 min

Your turn: build the raises context manager, then read an arrange-act-assert suite and write the function it specifies.

Rung 1 - build pytest.raises from scratch

Loading exercise…

Rung 2 - code to a spec (arrange, act, assert)

Loading exercise…

By the end you should reach for assert, arrange-act-assert, and pytest.raises without thinking - and know exactly what each one does, because you built the ones that looked like magic.