Install pytest and Write a First Test
A program that worked yesterday can break today after a small change, and running it by hand to find out is slow. A test is a short piece of code that runs your code and checks the result for you, so a mistake shows up the moment you run the tests. The tool that runs tests here, pytest, does not come with Python, so this page also shows how a project takes in code that other people have written.
Code that comes with Python, and code you add
Some ready-made code is always there. Python comes with its standard library: modules such as pathlib and json that every installation has, so import json works without any preparation.
Much more code is written by other people and shared with everyone. They publish it as a package: a bundle of modules with a name and a version number. Python packages are published in a public index called PyPI, the Python Package Index, where anyone can share a package and anyone can download one. A package from there is called a third-party package: it comes neither from Python nor from you, but from a third party.
A third-party package is not on your computer until you install it, and you install it only when a project needs it. pytest is one of them. Python does have a testing module of its own in the standard library, unittest, but pytest is the one most Python projects use, because a test written for it is just a plain function.
- Python standard library
- PyPI public index
- Your project its own packages
- Python to Your project: always there
- PyPI to Your project: installed when needed
True or false?
pytest is part of Python, so every computer that has Python can run it.
False. pytest is a third-party package from PyPI. It has to be added to a project before it can run.
A module from the standard library can be imported without installing anything.
True. The standard library is distributed with Python itself.
Adding a package to a project
A package a project needs is called a dependency of the project: the project depends on it to work. With uv, the project tool that runs a project's files, one command adds a dependency: uv add followed by the package's name. That one command changes three things at once.
- uv add
- pyproject.toml what the project needs
- uv.lock exact versions
- .venv installed packages
- uv add to pyproject.toml: lists it
- pyproject.toml to uv.lock: pins it
- uv.lock to .venv: installs it
- The project file,
pyproject.toml, is the list of what the project needs.uv addwrites the package's name there with a lowest allowed version, written with>=("this version or any newer one"). - The lock file,
uv.lock, records the exact version of every package that was chosen, including the packages that the added package needs in turn. It pins those versions: everyone who runs the project from the same lock file gets the same versions, so the code behaves the same on every computer. uv manages this file, and you never edit it by hand. - The environment, the folder
.venvnext to the project file, holds the installed packages of this one project, so two projects on the same computer can use different versions without getting in each other's way.
Some packages are needed only while you work on the code, never when someone just uses the program. pytest is like that: the program runs without its tests. Such a package is a development dependency, and the option --dev adds it as one:
uv add --dev pytestThis puts pytest in a group named dev under [dependency-groups] in pyproject.toml, apart from the dependencies the program itself needs. The group is still installed when you work on the project: uv run includes it by default.
There is no separate install step after uv add. Before every uv run, uv checks that the lock file matches the project file and that the environment matches the lock file, and puts right whatever does not. That is also why the project file and the lock file are the two files you keep and share with the code, and .venv is not: anyone can rebuild the environment from the lock file.
True or false?
To change which packages a project needs, you edit uv.lock.
False. The list you (or uv add) change is pyproject.toml. uv works out uv.lock from it.
A development dependency is installed when you run uv run in the project.
True. uv includes the dev group by default, so pytest is there whenever you work on the code.
The .venv folder should be shared with the code, so others get the same packages.
False. The lock file is shared. The environment is rebuilt from it on each computer.
A test is a function that checks a result
Take a small function that should double a number, saved in a file named calc.py:
def double(n: int) -> int:
return n * 2A test for it is another function, in another file. It calls double with a value whose answer you know, and states that answer with assert:
from calc import double
def test_double_two():
assert double(2) == 4
def test_double_three():
assert double(3) == 6assert is a Python statement followed by a condition. When the condition is True, nothing happens and the next line runs. When it is False, Python raises an AssertionError, and the test fails. So assert double(3) == 6 reads as "double of 3 must be 6". Each test checks one case, and its name says which.
The test file needs no import from pytest and no special structure. pytest finds the tests by their names: it looks through the folder it runs in and the folders inside it, opens every file whose name starts with test_ or ends with _test.py, and in those files runs every function whose name starts with test. A file or a function with any other name is skipped without a warning.
| Name | Run by pytest? |
|---|---|
| test_calc.py | yes, a test file |
| calc_test.py | yes, a test file |
| tests_calc.py | no, it does not start with test_ |
| def test_double_two() | yes, a test function |
| def double_two_test() | no, it does not start with test |
The line from calc import double works because pytest adds the folder of a test file to the places Python looks for modules, so a test file next to calc.py can import it like any of your own modules.
True or false?
A function named check_double in test_calc.py is run as a test.
False. Its name does not start with test, so pytest skips it without a warning.
A test file for pytest needs no import from pytest.
True. A plain function with a plain assert is a complete test.
Running the tests
The tests run with uv run pytest in the project folder. uv run starts pytest inside the project's environment, where it was installed. After a few header lines about the computer and the folder, pytest reports how many tests it found and one character per test: a dot for a test that passed.
$ uv run pytest
============================= test session starts ==============================
collected 2 items
test_calc.py .. [100%]
============================== 2 passed in 0.01s ===============================collected 2 items says both test functions were found. If that count is lower than the tests you wrote, a name is wrong. The time on the last line depends on the computer.
When pytest finds no test at all, it says so, and it does not count that as a success. Every program hands back a number when it ends, its exit code, and 0 means success. pytest ends with 0 when all its tests passed, but with 5, its code for "no tests collected", when it found none.
Reading a failed test
Now suppose someone changes double by mistake to return n * n. For 2 the answer is still 4, so the first test passes. For 3 the answer becomes 9, and the second test fails. pytest prints a failure report:
$ uv run pytest
============================= test session starts ==============================
collected 2 items
test_calc.py .F [100%]
=================================== FAILURES ===================================
______________________________ test_double_three _______________________________
def test_double_three():
> assert double(3) == 6
E assert 9 == 6
E + where 9 = double(3)
test_calc.py:9: AssertionError
=========================== short test summary info ============================
FAILED test_calc.py::test_double_three - assert 9 == 6
========================= 1 failed, 1 passed in 0.02s ==========================Read it from the top down:
- The progress line
.Fshows one test passed and then one failed:Fstands for a failure. - The line between the underscores names the failed test,
test_double_three, and pytest shows its code. - The
>marks theassertthat did not hold. - The
Elines show what was really compared.assert 9 == 6puts the actual value on the left and the value the test expected on the right.where 9 = double(3)says where the 9 came from. test_calc.py:9is the file and the line number of the failedassert.- The summary at the end names the test as
file::functionand counts the results.
A failed test tells you that the code and the expectation disagree, not which of them is wrong. Here the function is wrong, because double of 3 is 6. But a test can have a mistake too, so check both sides before you change anything.
When the two values are strings, pytest also prints the difference between them, line by line. A line starting with + comes from the left-hand value of the ==, the actual one. A line starting with - comes from the right-hand value, the expected one.
pytest can show these values because it rewrites the assert statements of the test files it collects before running them. An assert placed in an ordinary module of the program gets no such report.
True or false?
In the line assert 9 == 6, the 9 is the value the code actually gave.
True. The left side was written as double(3), and the where line confirms 9 = double(3).
A failed test always means the function under test has a bug.
False. It means the result and the expectation differ. The expected value in the test can be the mistake.
When one test fails, pytest stops and does not run the tests after it.
False. pytest runs every collected test and reports each one, as in 1 failed, 1 passed.