Skip to content
IT Vizag
← Production Python

Testing with pytest

Lesson 2 of 10 · 2 min read

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 pytest

Code 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:

pytest

pytest 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) == grade

Fixtures: 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.

Tip: Write the test first for bug fixes: reproduce the bug as a failing test, fix the code, watch it pass. That's called test-driven bug fixing, and it's a great interview story.

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.**

Saved on this device. Sign in to keep progress everywhere.

Share with a friend