pytest is the most popular Python testing tool, and for good reason: tests are plain functions with a bare assert — no classes or special methods required — yet it scales to powerful fixtures and plugins. Most projects choose it over unittest.
Plain functions, plain assert
# test_math.py — pytest discovers test_*.py files and test_* functionsdef add(a, b):return a + bdef test_add():assert add(2, 3) == 5 # bare assert — rich failure output for freeimport pytestdef test_raises():with pytest.raises(TypeError):add(1, "x")# run: pytest (from the terminal)
Parametrize & fixtures
parametrize runs one test across many inputs; fixtures provide reusable setup injected by name:
@pytest.mark.parametrize("a,b,expected", [(1,1,2), (2,3,5), (0,0,0)])def test_add_many(a, b, expected):assert add(a, b) == expected # runs 3 times, one per row@pytest.fixturedef sample_users():return [{"name": "Ana"}, {"name": "Ravi"}]def test_count(sample_users): # fixture injected by parameter nameassert len(sample_users) == 2
Key takeaways
- 01pytest uses plain functions and a bare assert — minimal boilerplate.
- 02It auto-discovers test_*.py files and test_* functions.
- 03parametrize runs one test over many input sets.
- 04Fixtures provide reusable setup, injected by parameter name.
- 05It is the de-facto standard; pytest-cov reports coverage.
