pytest
pytest is the usual third-party test runner for Python. Tests are plain functions that use assert, plus fixtures for setup and plugins for almost everything else.
Detailed Explanation
A file named test_order.py with def test_total(): assert 1 + 1 == 2 is a complete pytest suite. You do not subclass anything. pytest rewrites assert to print both sides on failure, so assert left == right is the default, not self.assertEqual.
Discovery looks for test_*.py and *_test.py, functions test_*, and methods on classes named Test* that do not have __init__. pytest tests/test_order.py::test_total runs one test. -k express filters by name. -x stops on the first failure. --pdb drops into a debugger.
Fixtures are how you share setup. Parameterize is how you run one test over many inputs. Markers (@pytest.mark.slow) classify tests. conftest.py holds fixtures visible to a directory tree. Plugins add coverage, Django helpers, asyncio (pytest-asyncio), and HTTP fakes.
pytest can run unittest TestCase classes and some nose tests. New tests should be functions unless you need a TestCase feature (Django's test client on a class).
Keep tests in a tests/ package or next to the code. A src/ layout needs pip install -e . so imports resolve. python -m pytest uses the same interpreter as your venv; a bare pytest on PATH might not.
Do not print to debug a failure; read the assertion rewrite and the traceback. Use --showlocals when you need more. Do not hide failures in fixtures without need; a fixture that fails is a setup bug.
Code Examples
def tax(cents: int, rate: float = 0.2) -> int:
return int(cents * (1 + rate))
def test_tax():
assert tax(1000) == 1200
def test_zero():
assert tax(0) == 0import pytest
@pytest.mark.parametrize("cents,expected", [(100, 120), (0, 0)])
def test_tax_table(cents, expected):
assert int(cents * 1.2) == expectedpython -m pytest -q
python -m pytest tests/test_tax.py::test_tax -vvCommon Gotchas
A class named `TestOrder` with `__init__`
pytest skips it. Use fixtures, not constructors.
Running the system `pytest`
it may not see the venv's packages. Use `python -m pytest`.
Assertions in helper functions are not rewritten
the message is weaker. Assert in the test, or return a value and assert there.
`assert 0.1 + 0.2 == 0.3` fails
use `pytest.approx`.