Python · Module 09: Concurrency, APIs & TestingTutorial 28 of 30
All Tutorials·~1.5 hrs

9.3 Unit Testing with pytest, Mocking & Clean Code (PEP 8 / Ruff)

Ship bug-free Python with confidence! Learn pytest assertions, parametrized test tables, testing exceptions, mocking API calls, and auto-formatting clean PEP 8 code with Ruff.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Why Automated Tests Matter (The Parachute-Check Analogy)

Testing by hand with print() works when your script is 20 lines long. The moment your codebase grows to 50 functions and multiple contributors, manual testing breaks down: fixing a subtle bug in checkout pricing can silently break promo codes or tax rounding two modules away.

Think of automated unit tests like a pre-flight checklist that runs every time you touch the code. With pytest, you verify dozens of edge cases in 0.1 seconds using a single terminal command (pytest). Even better, tests act as living documentation — a new engineer can read test_pricing.py and immediately see every valid input, boundary condition, and expected error.

The Arrange–Act–Assert (AAA) Pattern

Nearly every clean unit test follows three distinct beats:

  1. Arrange: Set up the inputs, objects, or temporary files the function needs.
  2. Act: Call the single function or method you are testing.
  3. Assert: Verify the return value, state change, or raised exception using plain Python assert statements.

Unlike Python's older unittest module (which forces you to memorize assertEqual, assertTrue, and assertRaises), pytest inspects plain assert expressions and prints a rich diff showing the exact left-hand and right-hand values whenever a test fails.

PYTHON
# pricing.py
def apply_discount(price: float, percent: float) -> float:
    if not (0 <= percent <= 100):
        raise ValueError("Percent must be between 0 and 100")
    return round(price * (1 - percent / 100), 2)
PYTHON
# test_pricing.py  (File & function names MUST start with test_)
import pytest
from pricing import apply_discount

def test_basic_discount():
    # Arrange & Act
    final_price = apply_discount(100.0, 20)
    # Assert
    assert final_price == 80.0

# Test multiple edge cases in one clean table without copy-pasting!
@pytest.mark.parametrize("price,pct,expected", [
    (100.0, 0, 100.0),      # 0% boundary
    (200.0, 50, 100.0),     # standard discount
    (99.99, 100, 0.0),      # 100% free boundary
    (19.99, 15, 16.99),     # floating-point rounding check
])
def test_discount_cases(price, pct, expected):
    assert apply_discount(price, pct) == expected

# Verify that invalid inputs raise the right exception and message!
def test_invalid_percent_raises():
    with pytest.raises(ValueError, match="between 0 and 100"):
        apply_discount(100.0, 150)

Reusable Setup with @pytest.fixture and tmp_path

When multiple tests need the same sample data, database connection, or temporary directory, avoid repeating setup code in every function. Define a @pytest.fixture and pass its name as a parameter to your test — pytest injects a fresh copy automatically so tests never leak state into one another.

For file-system tests, pytest ships with a built-in tmp_path fixture (pathlib.Path) that creates an isolated temporary folder per test and cleans it up automatically afterward — meaning your tests never pollute your real project folder.


2. Mocking External APIs (Fast, Offline, Reliable Tests)

Your unit tests should never hit live production APIs, send real emails, or charge real credit cards. Live network calls make test suites slow, flaky when Wi-Fi drops, and vulnerable to third-party rate limits.

Instead, mock at the I/O boundary using unittest.mock.patch or pytest's monkeypatch fixture. You replace only the external HTTP call with a deterministic fake response, then verify that your parsing and error-handling logic behaves correctly:

PYTHON
# weather.py
import requests

def get_city_temp_c(city: str) -> float:
    resp = requests.get(f"https://api.example.com/weather?q={city}", timeout=5)
    resp.raise_for_status()
    return float(resp.json()["temp_c"])
PYTHON
# test_weather.py
from unittest.mock import Mock, patch
from weather import get_city_temp_c

@patch("weather.requests.get")
def test_get_city_temp_c_offline(mock_get):
    # Configure the fake HTTP response
    fake_response = Mock()
    fake_response.json.return_value = {"temp_c": 27.5}
    fake_response.raise_for_status.return_value = None
    mock_get.return_value = fake_response

    # Run our real function completely offline!
    assert get_city_temp_c("Bengaluru") == 27.5
    mock_get.assert_called_once()

Golden Rule of Mocking: Mock external boundaries (HTTP APIs, clocks, databases, file systems) — not your own internal helper functions. Over-mocking internal implementation details produces brittle tests that break every time you refactor clean code.


3. Clean Python Style: PEP 8 + Ruff

Readable code is read ten times more often than it is written. Python's official style guide, PEP 8, establishes shared conventions so any Python developer can scan a new repository effortlessly:

ElementPEP 8 ConventionExample
Variables & Functionssnake_casecalculate_tax(), user_count
Classes & ExceptionsPascalCaseOrderService, InvalidCouponError
Module ConstantsUPPER_SNAKE_CASEMAX_RETRIES = 3, DEFAULT_TIMEOUT = 5
Indentation & Line Length4 spaces · 88–100 chars maxConfigured once in pyproject.toml

Modern Python teams don't waste code-review time debating whitespace or unused imports — they let ruff (a Rust-powered linter and formatter that runs 10–100× faster than legacy flake8 + black + isort) enforce everything automatically on save and in CI:

BASH
pip install ruff
ruff check .          # Flags unused imports, mutable defaults, dead code, style bugs
ruff check --fix .    # Auto-fixes safe lint issues in milliseconds
ruff format .         # Auto-formats every .py file to consistent PEP 8!

Drop a minimal pyproject.toml at your project root so every teammate and GitHub Actions workflow shares identical rules:

TOML
[tool.ruff]
line-length = 88
target-version = "py312"

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]  # pycodestyle, pyflakes, isort, bugbear, pyupgrade

Pairing pytest + ruff check . in your pre-commit hook or CI pipeline catches subtle bugs (like mutable default arguments def add(item, items=[]) or shadowed built-ins) before code ever reaches production.


4. Interactive Trace: Running a Parametrized pytest Suite

Tracing pytest Executing a Parametrized Test
Interactive Line-by-Line Execution Trace · Step 1 of 4
1@pytest.mark.parametrize("n,ok", [(2, True), (3, False)])
2→def test_is_even(n, ok):
3 result = (n % 2 == 0)
4 assert result == ok
Variables in Memory
n2int
okTruebool
Console Output
(nothing printed yet)
What just happened: pytest automatically generates Case 1: test_is_even[2-True].

Quick Quiz: Module 9.3 — pytest & Clean Code

Q1.How does `pytest` automatically discover your test functions?
Q2.How do you assert that calling `divide(10, 0)` raises a `ZeroDivisionError` in pytest?
Q3.Why should unit tests mock external HTTP API calls?

Keep Exploring: Related Lessons & Tools

All Courses →