Lesson 54 of 55
PythonTesting with pytest
20 minutes
Course progress98%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 54 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
While unittest is built into the std‑lib, pytest has become the de‑facto standard for Python testing because of its simple syntax, powerful fixtures, and expressive assertions.
pip install pytest
test_math.py)# test_math.py
def add(a, b):
return a + b
def mul(a, b):
return a * b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_mul():
assert mul(3, 4) == 12
assert mul(0, 5) == 0
Run it with:
pytest -q
You’ll see a concise output showing which tests passed.
import pytest
@pytest.fixture
def sample_list():
return [1, 2, 3]
def test_append(sample_list):
sample_list.append(4)
assert sample_list == [1, 2, 3, 4]
Fixtures can also be autouse, scope‑session, scope‑module, etc.
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, 5, 10),
(-1, 1, 0)
])
def test_add_param(a, b, expected):
assert add(a, b) == expected
This replaces multiple near‑identical test functions with a single compact one.
import pytest
def div(a, b):
return a / b
def test_div_zero():
with pytest.raises(ZeroDivisionError):
div(1, 0)
# Run only tests in a specific file
pytest tests/test_api.py
# Run with coverage (requires pytest‑cov)
pip install pytest-cov
pytest --cov=myapp
tests/ folder.test_*.py and test functions test_*.pytest with mypy for type‑checked tests (--check-type).With pytest you’ll spend less time writing boilerplate and more time verifying that your code works.