Python Reference ยท Third-party Libraries
The pytest library
Overview of pytest: writing plain assert tests, fixtures, parametrize, pytest.raises, monkeypatch, tmp_path, markers and the command-line options you use daily.
pytest is the most widely used Python testing framework. A test is just a function whose name starts with test_ and that uses ordinary assert statements. pytest finds the tests, runs them, and when an assertion fails it shows both sides of the comparison in detail, with no special assertion methods to learn.
Install it with python -m pip install pytest. The snippets below are read-only: pytest discovers files on disk and is not available in the in-browser runner. A runnable stand-in at the end shows what assert and exceptions do. For the built-in alternative see unittest.
A first test file
# test_prices.py import pytest def with_tax(price, rate=0.2): if price < 0: raise ValueError("price cannot be negative") return round(price * (1 + rate), 2) def test_basic(): assert with_tax(10) == 12.0 def test_zero_rate(): assert with_tax(10, rate=0) == 10 def test_negative_price_rejected(): with pytest.raises(ValueError, match="negative"): with_tax(-1)
Run all tests with python -m pytest, one file with python -m pytest test_prices.py, and one test with python -m pytest test_prices.py::test_basic.
Fixtures and parametrize
import pytest @pytest.fixture def cart(): items = [] # setup yield items # the test runs here items.clear() # teardown def test_add(cart): cart.append("book") assert cart == ["book"] @pytest.mark.parametrize("price, expected", [ (10, 12.0), (0, 0.0), (19.99, 23.99), ]) def test_with_tax(price, expected): assert with_tax(price) == expected def test_write_file(tmp_path): target = tmp_path / "out.txt" target.write_text("hello") assert target.read_text() == "hello" def test_env(monkeypatch): monkeypatch.setenv("MODE", "test") import os assert os.environ["MODE"] == "test"
A fixture is a function that prepares something (data, a connection, a temporary folder) and hands it to every test that names it as a parameter. parametrize runs one test function with several inputs and reports each case separately. tmp_path and monkeypatch are built-in fixtures.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Command-line options
| Option | Effect |
|---|---|
-v |
Verbose: one line per test. |
-x |
Stop at the first failure. |
-k "name" |
Run only tests whose names match the expression. |
-m marker |
Run only tests with a marker such as @pytest.mark.slow. |
--lf |
Re-run only the tests that failed last time. |
-s |
Do not capture print output. |
--tb=short |
Shorter tracebacks. |
--cov |
Coverage report (needs the pytest-cov plugin). |
Usage notes
- Discovery rules: files named
test_*.pyor*_test.py, functionstest_*, classesTest*(without__init__). Keep test files importable, usually in atests/folder. - Compare floats with
pytest.approx:assert 0.1 + 0.2 == pytest.approx(0.3). pytest.raisesreturns information:with pytest.raises(ValueError) as info:then checkinfo.value. Usematch=for a regular expression on the message.- Fixtures have scopes: the default
functionscope runs setup per test;module,sessionand others share one result.conftest.pyholds fixtures shared by a folder. - Skip and expect failure:
@pytest.mark.skip(reason="..."),@pytest.mark.skipif(cond, reason=...)and@pytest.mark.xfail. - Do not put logic in tests (no loops and branches that decide what to assert). Use parametrize instead.
- Mocking uses
monkeypatchorunittest.mock; patch the name where the code under test looks it up. - Running pytest also runs
unittesttests, so migrating can happen gradually. - Plugins add features:
pytest-cov,pytest-asyncio,pytest-mock,pytest-xdist(parallel runs).