Testing with pytest
Overview
How do you know your code works? You run it and check the output. How do you know it still works after you change something? You’d have to check everything again, by hand, every time. Automated tests do that checking for you, in seconds. They’re the safety net that lets you improve code without fear, and every professional Python project has them.
pytest is the most popular testing tool for Python. Install it into your project’s environment:
python -m pip install pytest # or: uv add --dev pytestYour first tests
Suppose cart.py contains:
def total(items):
"""Return the total price of (price, quantity) pairs."""
return sum(price for price, quantity in items)Tests go in a separate file whose name starts with test_:
# test_cart.py
from cart import total
def test_empty_cart():
assert total([]) == 0
def test_quantity():
assert total([(10, 3)]) == 30Run pytest in the project folder:
$ pytest
...
test_cart.py .F [100%]
========================== FAILURES ==========================
_______________________ test_quantity ________________________
def test_quantity():
> assert total([(10, 3)]) == 30
E assert 10 == 30
E + where 10 = total([(10, 3)])
test_cart.py:7: AssertionError
================== short test summary info ===================
FAILED test_cart.py::test_quantity - assert 10 == 30
================ 1 failed, 1 passed in 0.02s =================pytest found the file and both functions automatically. One dot (.) per passing test, F per failure. For the failure, it shows exactly what was compared: total([(10, 3)]) returned 10, not 30. The bug: total ignores the quantity. Fix it —
return sum(price * quantity for price, quantity in items)— rerun, and you get 2 passed. That loop — write a test, see it fail, fix, see it pass — is the heart of testing.
How pytest finds tests
- files named
test_*.py(or*_test.py), in the current folder and subfolders; - functions named
test_*in those files (and methods in classes namedTest*).
Useful options:
pytest -v # verbose: one line per test
pytest -q # quiet
pytest test_cart.py # one file
pytest -k quantity # tests whose names match "quantity"
pytest -x # stop at the first failure
pytest --lf # rerun only the tests that failed last timeIf pytest can’t import your module (ModuleNotFoundError), run it as python -m pytest, which adds the current folder to the import path — or add pythonpath = ["."] under [tool.pytest.ini_options] in pyproject.toml.
Plain assert
Tests are just functions that assert things. No special methods to learn:
assert result == 42
assert "error" not in message
assert len(items) == 3
assert user is None
assert math.isclose(average, 0.3) # floats: never compare exactlypytest rewrites assert statements so that failures show the actual values — you rarely need custom messages.
Testing exceptions
Check that bad input raises the right error with pytest.raises:
import pytest
def test_negative_amount_rejected():
with pytest.raises(ValueError):
withdraw(100, -5)
def test_message_mentions_amount():
with pytest.raises(ValueError, match="must be positive"):
withdraw(100, -5)The test fails if no exception (or a different one) is raised. match checks the message with a regular expression.
Parametrize: one test, many inputs
@pytest.mark.parametrize(
"celsius, fahrenheit",
[(0, 32), (100, 212), (-40, -40), (37, 98.6)],
)
def test_conversion(celsius, fahrenheit):
assert math.isclose(celsius_to_fahrenheit(celsius), fahrenheit)pytest runs the test once per pair and reports each separately — far better than a loop inside one test, which stops at the first failure.
Fixtures
Fixtures provide things tests need. pytest supplies some built in — just name them as parameters:
def test_save_and_load(tmp_path): # a fresh temporary folder
path = tmp_path / "data.json"
save({"a": 1}, path)
assert load(path) == {"a": 1}
def test_greeting_output(capsys): # captures printed output
greet("Asha")
assert capsys.readouterr().out == "Hello, Asha!\n"You can write your own fixtures for shared setup:
@pytest.fixture
def sample_cart():
return [(10, 3), (2.5, 2)]
def test_total(sample_cart):
assert total(sample_cart) == 35What to test
For each function, think about:
- Normal cases — typical inputs and their expected results.
- Edge cases — empty lists, zero, one item, negative numbers, very large values, unusual text (spaces, accents, emoji).
- Error cases — invalid input raises the right exception.
Test behaviour (what a function returns or does), not implementation details (which variables it uses inside), so you can rewrite the inside freely while the tests keep you honest.
Good tests are short, independent (they don’t rely on each other’s order) and have names that describe the expectation: test_empty_cart_total_is_zero.
Making testing a habit
- Write a test for every bug you fix — before fixing it, so you see it fail.
- Keep functions pure where possible (Return values and scope); they’re trivial to test.
- Run tests often — many editors have a testing panel with a “run all” button.
- Some developers write the test first, then the code to make it pass: test-driven development. Try it on your next small function.
Remember:
test_*.pyfiles,test_*functions, plainassert. Runpytestafter every change, and let failures tell you exactly what broke.
Test a password checker
The starter contains password_strength(pw), which returns "weak", "medium" or "strong", and raises TypeError for anything that isn’t a string. Write tests in the same file (save it as test_passwords.py) and run them with pytest -v: (1) a test that an empty string is weak; (2) a parametrized test with at least four passwords and their expected strength; (3) a test that password_strength(None) raises TypeError, using pytest.raises; (4) a test that uses the tmp_path fixture to write three passwords to a file, read them back and check that exactly one is strong. All tests should pass.
# test_passwords.py
import pytest
def password_strength(pw):
if not isinstance(pw, str):
raise TypeError("password must be a string")
score = 0
score += len(pw) >= 12
score += any(ch.isdigit() for ch in pw)
score += any(ch.isupper() for ch in pw)
score += any(not ch.isalnum() for ch in pw)
if score >= 4:
return "strong"
if score >= 2:
return "medium"
return "weak"
# Your tests here# test_passwords.py
import pytest
def password_strength(pw):
if not isinstance(pw, str):
raise TypeError("password must be a string")
score = 0
score += len(pw) >= 12
score += any(ch.isdigit() for ch in pw)
score += any(ch.isupper() for ch in pw)
score += any(not ch.isalnum() for ch in pw)
if score >= 4:
return "strong"
if score >= 2:
return "medium"
return "weak"
def test_empty_password_is_weak():
assert password_strength("") == "weak"
@pytest.mark.parametrize(
"pw, expected",
[
("password", "weak"),
("Password1", "medium"),
("correcthorsebattery", "weak"),
("Correct-Horse-Battery-9", "strong"),
],
)
def test_strength(pw, expected):
assert password_strength(pw) == expected
def test_non_string_raises_type_error():
with pytest.raises(TypeError, match="must be a string"):
password_strength(None)
def test_passwords_from_file(tmp_path):
path = tmp_path / "passwords.txt"
path.write_text("abc\nPassword1\nCorrect-Horse-Battery-9\n", encoding="utf-8")
passwords = path.read_text(encoding="utf-8").splitlines()
results = [password_strength(pw) for pw in passwords]
assert results.count("strong") == 1Summary
- Install pytest in your environment; it finds files named
test_*.pyand runs functions namedtest_*. - Tests use plain
assert; when one fails, pytest shows the values involved. pytest.raises(SomeError)checks that code raises the right exception.@pytest.mark.parametrizeruns one test with many inputs; fixtures such astmp_pathprovide ready-made resources.- Test behaviour, not implementation: normal cases, edge cases (empty, zero, huge) and error cases.