Type Hints and Tests with pytest
Check the word-frequency package with mypy in strict mode and cover it with pytest tests, including a missing input file, a bad argument and the command-line entry point.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: configure and run mypy
- Step 2: watch mypy catch a bug
- Step 3: write unit tests for the core
- Step 4: test the error paths
- Step 5: test the command-line entry point
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Python Foundations
- Values, Control Flow, Functions and Classes Concept · 25 min
- Choosing Lists, Dicts, Sets, Tuples and Dataclasses Worked example · 20 min
- Exceptions and Defensive Input Handling Worked example · 15 min
- Modules, Packages and Virtual Environments Lab · 25 min
- Type Hints and Tests with pytest Lab · 25 min
- Check: Read, Fix and Test a Script Knowledge check · 6 questions
What you will learn
- Write unit tests with pytest and add type hints that a type checker accepts.
01. Goal and setup
This lab adds the two safety nets that let you change code with confidence. A type checker reads your type hints and reports calls and return values that do not match them, without running anything. Tests run the code and check that it does what you claim. They catch different kinds of mistake, so you want both.
You need: the wordfreq project from the previous lab, with its virtual environment active and the dev extra installed (python -m pip install -e ".[dev]"). That gives you pytest 9 or later and mypy 2 or later, the floors set in the previous lab. Pyright is a good alternative type checker, and the hints you write here work with either. You will add a tests/ folder:
wordfreq/
├── pyproject.toml gains [tool.mypy] and [tool.pytest.ini_options]
├── src/wordfreq/ unchanged from the previous lab
└── tests/
├── test_core.py new: unit tests for core.py
└── test_cli.py new: tests that call main()02. Step 1: configure and run mypy
Append the tool settings below to pyproject.toml. strict = true switches on the full set of mypy checks, including the rule that every function must be annotated. Starting strict on a small project is far easier than tightening the rules later on a large one. testpaths tells pytest where your tests live.
[tool.mypy]
strict = true
[tool.pytest.ini_options]
testpaths = ["tests"]mypy srcSuccess: no issues found in 4 source filesThe code from the earlier lessons already carries hints, so there is nothing to report; the four files are the package modules. The hints use built-in types directly, such as list[str], dict[str, int] and Counter[str], and X | None for an X or nothing. mypy treats None as a type of its own: it will not let you call a string method on a value annotated str | None until your code has checked that the value is not None.
03. Step 2: watch mypy catch a bug
Make a realistic mistake on purpose. In top_words(), change the last line so that the function returns the ranked tuples instead of WordCount records, then run mypy again.
return ranked[:n]mypy srcsrc/wordfreq/core.py:56: error: Incompatible return value type (got
"list[tuple[str, int]]", expected "list[WordCount]") [return-value]
Found 1 error in 1 file (checked 4 source files)The message gives the file and line, what mypy found and what the annotation promised, and an error code in brackets that you can look up in the mypy documentation. At run time this bug would not crash where it was made: the CLI would happily print ('refund', 3), and the failure would only appear later, in whatever code expects .word and .count. mypy found it without running anything. Undo the change and check that mypy src reports success again before you move on.
04. Step 3: write unit tests for the core
A pytest test is a function whose name starts with test_, in a file whose name starts with test_, and it checks results with a plain assert. When an assertion fails, pytest shows both sides of the comparison, so you rarely need to write failure messages yourself. Create tests/test_core.py:
from collections import Counter
from pathlib import Path
import pytest
from wordfreq.core import (
InputError,
WordCount,
count_words,
load_text,
tokenize,
top_words,
)
def test_tokenize_lowercases_and_strips_punctuation() -> None:
assert tokenize("Refund, please! REFUND.") == ["refund", "please", "refund"]
@pytest.mark.parametrize(
("text", "expected"),
[
("", []),
(" \n\t ", []),
("... !!", []),
],
)
def test_tokenize_returns_no_words_for_blank_input(
text: str, expected: list[str]
) -> None:
assert tokenize(text) == expected
def test_count_words_skips_stop_words() -> None:
counts = count_words(["the", "invoice", "of", "the", "invoice"])
assert counts == Counter({"invoice": 2})
def test_top_words_breaks_ties_alphabetically() -> None:
counts = Counter({"refund": 3, "app": 1, "amount": 1, "invoice": 2})
assert top_words(counts, 3) == [
WordCount("refund", 3),
WordCount("invoice", 2),
WordCount("amount", 1),
]pytest -q...... [100%]
6 passed in 0.58sFour functions produce six tests, and three ideas carry most of the weight:
- Each test checks one behaviour, and its name says which, so a failure report reads like a bug report.
@pytest.mark.parametrizeruns one test function once per case. The three blank-input cases share a body but pass, fail and are reported independently.- The tie-break test builds its own
Counterinstead of reading a file. Tests of pure functions need no setup and run in microseconds, which is the pay-off for keeping input and output out ofcore.py.
Now see a failure. In top_words(), change the sort to sorted(counts.items(), key=lambda item: item[1], reverse=True), which drops the alphabetical tie-break, and run pytest -q again.
.....F [100%]
...
E At index 2 diff: WordCount(word='app', count=1) !=
WordCount(word='amount', count=1)
...
FAILED tests/test_core.py::test_top_words_breaks_ties_alphabetically - Assert...
1 failed, 5 passed in 3.68spytest points at the first position where the lists differ: app came before amount because the two tied words kept their insertion order. The type checker could not catch this, since both versions return the right type; only a test that pins down the behaviour can. Restore the original sort key and rerun the tests before you continue.
05. Step 4: test the error paths
Error handling is code too, and it is the code most likely to decay unnoticed, because nobody exercises it by hand. Append three tests to tests/test_core.py:
def test_top_words_rejects_n_below_one() -> None:
with pytest.raises(ValueError, match="at least 1"):
top_words(Counter({"refund": 1}), 0)
def test_load_text_reports_missing_file(tmp_path: Path) -> None:
missing = tmp_path / "missing.txt"
with pytest.raises(InputError, match="file not found") as info:
load_text(missing)
assert info.value.path == missing
def test_load_text_reports_non_utf8_file(tmp_path: Path) -> None:
binary = tmp_path / "scan.bin"
binary.write_bytes(b"\xff\xfe\x00 not text")
with pytest.raises(InputError, match="not UTF-8"):
load_text(binary)pytest -q......... [100%]
9 passed in 0.90spytest.raises is a context manager: the test passes only if the block raises the given exception type, and match checks the message against a regular expression. Adding as info keeps the exception object, so you can also assert on its attributes, as the missing-file test does with info.value.path.
tmp_path is a fixture. You request it by naming it as a parameter, and pytest passes in a fresh, empty temporary directory, as a pathlib.Path, unique to that test. Use it whenever a test needs files, so that tests never depend on, or leave behind, files in your project.
06. Step 5: test the command-line entry point
Because main() takes an argument list and returns an exit code, instead of reading sys.argv and calling sys.exit() itself, you can call it from a test like any other function. The built-in capsys fixture captures everything it prints. Create tests/test_cli.py:
from pathlib import Path
import pytest
from wordfreq.cli import main
def test_main_prints_top_words(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
source = tmp_path / "tickets.txt"
source.write_text("Refund the refund. Invoice!", encoding="utf-8")
exit_code = main([str(source), "--top", "2"])
assert exit_code == 0
assert capsys.readouterr().out.splitlines() == [
"WordCount(word='refund', count=2)",
"WordCount(word='invoice', count=1)",
]
def test_main_reports_missing_file_on_stderr(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
exit_code = main([str(tmp_path / "nope.txt")])
captured = capsys.readouterr()
assert exit_code == 1
assert captured.out == ""
assert "file not found" in captured.errpytest -q........... [100%]
11 passed in 0.72smypy src testsSuccess: no issues found in 6 source filesEleven tests now cover tokenising, counting, ranking, both input errors, the argument check and the command line, including a missing input file. Running mypy over tests/ as well keeps the tests honest. Strict mode is the reason each test is annotated -> None and capsys is typed as pytest.CaptureFixture[str].
Make both commands a habit: run them before every commit, and later in CI, so that a change that breaks a promise is caught before anyone else sees it.
07. Check your understanding
08. Apply it: stretch tasks
Finish the practice project and go a little further:
- Add a test that calls
main()with--top 0.argparsereports bad arguments by raisingSystemExitwith code 2, so wrap the call inpytest.raises(SystemExit) as infoand assert thatinfo.value.code == 2. - If you wrote
bigrams()in the data-structures lesson, move it intocore.py, annotate it and give it a parametrised test with at least three cases, including an empty list. - Re-run
python -m pip freeze --exclude-editable > requirements-dev.txtwhenever you add or upgrade a tool, and commit the change together with the code that needs it.
09. Review prompt
Without looking back:
- Name one mistake mypy catches that a test might miss, and one that a test catches but mypy cannot.
- What does
strict = trueadd, and why is it easier to adopt on a new project? - How do you test that a function raises an exception, and how do you check its message?
- What do the
tmp_pathandcapsysfixtures give a test, and which design choice inmain()makes it easy to test?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.