Testing with pytest
Write tests that catch bugs before users do.
🎬 Video version coming soon — read it now
Tests are code that checks your code. They catch bugs before users do, and they let you change code confidently: if the tests still pass, you didn't break anything. In job interviews, "how do you test your code?" is a standard question.
Install and write a first test
pip install pytestCode in src/shop/pricing.py:
def with_gst(amount: float, rate: float = 0.18) -> float:
if amount < 0:
raise ValueError("amount cannot be negative")
return round(amount * (1 + rate), 2)Tests in tests/test_pricing.py:
import pytest
from shop.pricing import with_gst
def test_default_rate():
assert with_gst(100) == 118.0
def test_custom_rate():
assert with_gst(200, rate=0.05) == 210.0
def test_zero():
assert with_gst(0) == 0
def test_negative_raises():
with pytest.raises(ValueError):
with_gst(-1)Run them:
pytestpytest finds files named test_*.py and functions named test_*, runs them and reports passes and failures. A failing assert shows the actual and expected values.
What to test
- The normal case: typical inputs
- Edge cases: zero, empty lists, one item, very large values, Telugu text
- Errors: invalid input raises the right exception
- Bugs you fixed: add a test that would have caught it, so it never returns
Parametrize: many cases, one test
@pytest.mark.parametrize("marks, grade", [
(95, "A+"), (90, "A+"), (89, "A"), (75, "A"), (60, "B"), (34, "F"),
])
def test_grade(marks, grade):
assert grade_for(marks) == gradeFixtures: shared setup
@pytest.fixture
def sample_students():
return [{"name": "Anil", "cgpa": 8.4}, {"name": "Bhavana", "cgpa": 9.1}]
def test_topper(sample_students):
assert topper(sample_students)["name"] == "Bhavana"pytest passes the fixture's return value to any test that names it as a parameter. tmp_path is a built-in fixture that gives each test a fresh temporary folder, which is perfect for file code.
Don't call real AI APIs in tests
Network calls make tests slow, flaky and costly. Test your logic with a fake:
def test_classify_uses_model(monkeypatch):
monkeypatch.setattr("feedback_api.service.call_model", lambda text: "negative")
assert classify("Cold food") == "negative"Keep the AI call in one small function, then replace it in tests.
In one line
*pytest runs test_ functions full of asserts; cover normal, edge and error cases, use parametrize and fixtures, and fake out network calls.**
Share with a friend