Advanced·12 min·engineering · testing · pytest
Testing with pytest
pytest: tests that are actually pleasant to write
Python's stdlib has unittest, but nobody uses it if pytest is an option. pytest is:
- Zero ceremony — a function named
test_*in a file namedtest_*.pyis a test. - Plain
assert— noself.assertEqualverbosity. - Rich failure output — shows the actual value that broke.
The whole API
assert expected == actual— pytest rewrites this to show both sides on failure.with pytest.raises(SomeError, match="..."):— assert exception + optional message.@pytest.mark.parametrize("a,b,expected", [...])— one test, many inputs.@pytest.fixture— reusable setup (next lesson).pytest -vverbose,pytest -k slugifyfilter by name,pytest -xstop on first failure.
Test organization
myapp/
__init__.py
slugify.py
tests/
test_slugify.py
Then just run pytest. It discovers everything.
Coverage
pip install pytest-cov
pytest --cov=myapp --cov-report=term-missing
Shows which lines your tests miss. Aim for 80%+ on business logic; don't chase 100% on plumbing.
Try it
- Add a test that
slugify("Python 🐍")behaves how you'd want. - Add a parametrize case where
bis negative.