5. Concurrency, Testing & Code Quality

Intermediate pytest: Fixtures, Parametrize, Mocking & Code Quality

Write clean, scalable test suites with pytest fixtures, @pytest.mark.parametrize, monkeypatch/unittest.mock, and keep projects spotless with ruff and mypy.

5 min readUpdated 2026-11-30
In This Lesson
  • Share clean test setup without duplication using @pytest.fixture and tmp_path
  • Run one test across many edge-case inputs using @pytest.mark.parametrize
  • Isolate external APIs, clocks, and randomness with unittest.mock and monkeypatch

In Python Fundamentals, you learned how assert and basic test_*.py functions catch bugs. Once your project grows to 30+ tests, copying sample dictionaries into every test and hitting real APIs slows everything down and makes tests flaky.

Why It Matters: Before vs After

Compare brittle, duplicated test setup against clean pytest dependency injection and mocking:

python
# Before: duplicated setup + real network call (slow, flaky, hard to test edge cases)
def test_discount_ok():
    cart = [{"name": "Keyboard", "price": 80.0, "qty": 1}]
    ...

def test_discount_zero():
    cart = [{"name": "Keyboard", "price": 80.0, "qty": 1}]
    ...

# After: shared fixture + parametrized input matrix + isolated offline mocks
@pytest.mark.parametrize("percent, expected", [(0, True), (50, True), (51, False)])
def test_discount_bounds(percent, expected):
    assert is_valid_discount(percent) is expected

1. Reusable Setup & Teardown with @pytest.fixture & tmp_path

A fixture creates fresh test data (or temporary files) and injects it by parameter name into any test function that requests it. Using yield inside a fixture even gives you guaranteed teardown after the test completes:

python
import pytest

@pytest.fixture
def sample_cart():
    return [
        {"name": "Keyboard", "price": 80.0, "qty": 1},
        {"name": "Cable", "price": 15.0, "qty": 2},
    ]

@pytest.fixture
def db_connection():
    conn = connect_test_db()  # Setup
    yield conn                # Hand connection to the test
    conn.close()              # Guaranteed teardown, even if the test fails!

def test_save_report(tmp_path):
    # tmp_path is a built-in pytest fixture giving an isolated Path folder!
    out = tmp_path / "report.txt"
    out.write_text("OK", encoding="utf-8")
    assert out.read_text(encoding="utf-8") == "OK"

Because each test gets a fresh fixture call by default (scope="function"), mutating sample_cart in one test never leaks dirty state into the next test!

2. Testing Many Edge Cases with @pytest.mark.parametrize

Never copy-paste the same test 6 times just to check boundary values. @pytest.mark.parametrize expands one test function into separate test cases in pytest's runner:

python
import pytest

def is_valid_discount(percent: int) -> bool:
    return 0 <= percent <= 50

@pytest.mark.parametrize(
    "percent, expected",
    [
        (0, True),
        (25, True),
        (50, True),
        (-1, False),
        (51, False),
    ],
)
def test_discount_bounds(percent, expected):
    assert is_valid_discount(percent) is expected

If (51, False) ever fails, pytest isolates and reports that exact parameter row without hiding failures in the remaining rows!

3. Isolating Dependencies with unittest.mock & monkeypatch

Unit tests should be fast, offline, and deterministic. Replace external HTTP APIs, system clocks, or os.environ using Mock, unittest.mock.patch, or pytest's monkeypatch:

python
from unittest.mock import Mock

def fetch_username(api_client, user_id: int) -> str:
    payload = api_client.get_user(user_id)
    return payload["name"].upper()

def test_fetch_username_with_mock():
    fake_client = Mock()
    fake_client.get_user.return_value = {"id": 7, "name": "maya"}

    assert fetch_username(fake_client, 7) == "MAYA"
    fake_client.get_user.assert_called_once_with(7)

Crucial Rule: mock.patch Where It's Looked Up, Not Where It's Defined!

mock.patch Rule: Patch Where Looked Up, Not Defined

api.py

def fetch_rate() (Original)

billing.py

patch("billing.fetch_rate") ✓

If billing.py runs `from api import fetch_rate`, patch `billing.fetch_rate`—because billing.py holds its own reference.

Suppose service.py writes from httpx import get and calls get(url) inside fetch_data().

  • Wrong: @patch("httpx.get") — service.py already bound its own local reference service.get at import time!
  • Right: @patch("service.get", autospec=True) — patches the name inside service where fetch_data() actually looks it up!

(Adding autospec=True makes the mock enforce the real function's parameter signature, catching typos like fake_client.get_usr(7) immediately!)

Decision Table: Which Test Double Tool to Use?

ToolScopeBest Used When
Mock() / MagicMock()Passed explicitly as an argumentDependency injection (api_client passed into function)
unittest.mock.patch(..., autospec=True)Context manager or decoratorReplacing module-level imports or datetime/uuid calls
monkeypatch (pytest fixture)Auto-restores after each testSetting env vars (monkeypatch.setenv), attributes, sys.path

4. Modern Code Quality Tooling (ruff & mypy)

Before pushing code to GitHub, clean Python repos run two fast CLI tools:

  • ruff check . & ruff format .: Catches unused imports, mutable default arguments, and bug-prone patterns while formatting code in milliseconds (replacing Flake8, isort, and Black in one tool).
  • mypy src/ (or pyright): Verifies your type hints statically before runtime—catching None bugs like calling .strip() on an str | None value!

Try It Yourself in the Playground

Pyodide includes unittest.mock right out of the box! Test mocking a weather client and running table-driven edge-case checks below:

Python 3Try It Live: Mocking External Dependencies & Parametrized Checks
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Using unittest.mock.Mock, create a fake_repo whose .find_price("book") returns 20.0, call a function apply_tax(repo, item, rate=0.1) returning 22.0, and verify fake_repo.find_price.assert_called_once_with("book").

Quick Checkpoints

Check Your Understanding

What does pytest's built-in tmp_path fixture provide to a test function?

Check Your Understanding

When should you use @pytest.mark.parametrize?