Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

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

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:

Project layout (changes in this lab)
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.

TOML · pyproject.toml (append)
[tool.mypy]
strict = true

[tool.pytest.ini_options]
testpaths = ["tests"]
Terminal
mypy src
Expected output
Success: no issues found in 4 source files

The 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.

Python · src/wordfreq/core.py (temporary change to the last line)
    return ranked[:n]
Terminal
mypy src
Expected output (the long first line is wrapped here)
src/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:

Python · 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),
    ]
Terminal
pytest -q
Illustrative output (the test count is exact; your timing will differ)
......                                                                   [100%]
6 passed in 0.58s

Four 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.parametrize runs 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 Counter instead 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 of core.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.

Illustrative output (excerpt; the long diff line is wrapped; timing will differ)
.....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.68s

pytest 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:

Python · tests/test_core.py (append)
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)
Terminal
pytest -q
Illustrative output (the test count is exact; your timing will differ)
.........                                                                [100%]
9 passed in 0.90s

pytest.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:

Python · 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.err
Terminal
pytest -q
Illustrative output (the test count is exact; your timing will differ)
...........                                                              [100%]
11 passed in 0.72s
Terminal
mypy src tests
Expected output
Success: no issues found in 6 source files

Eleven 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

Practice check · 3 questions

Tests and types

Apply what you used in this lab to new cases.

Q1. A test file holds two plain test functions and one function decorated with @pytest.mark.parametrize that lists four cases. How many tests does pytest report?
Q2. Inside a test, how do you check what main() wrote to standard error?
Q3. counts is annotated dict[str, int]. Which type does mypy give counts.get(word), called without a default?
Practice only: not graded, not saved, not evidence.

08. Apply it: stretch tasks

Finish the practice project and go a little further:

  1. Add a test that calls main() with --top 0. argparse reports bad arguments by raising SystemExit with code 2, so wrap the call in pytest.raises(SystemExit) as info and assert that info.value.code == 2.
  2. If you wrote bigrams() in the data-structures lesson, move it into core.py, annotate it and give it a parametrised test with at least three cases, including an empty list.
  3. Re-run python -m pip freeze --exclude-editable > requirements-dev.txt whenever you add or upgrade a tool, and commit the change together with the code that needs it.

09. Review prompt

Without looking back:

  1. Name one mistake mypy catches that a test might miss, and one that a test catches but mypy cannot.
  2. What does strict = true add, and why is it easier to adopt on a new project?
  3. How do you test that a function raises an exception, and how do you check its message?
  4. What do the tmp_path and capsys fixtures give a test, and which design choice in main() makes it easy to test?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check