Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 03 / Topic 1 of 6

pytest basics

pytest discovers any test_*.py file and runs every test_* function in it; a plain assert is the whole assertion API. The three features you will use constantly:

import pytest

def test_simple():                      # 1. plain asserts
    assert parse_weight_kg("120 kg") == 120.0

@pytest.fixture
def export(tmp_path):                   # 2. fixtures: shared setup, torn down for you
    path = tmp_path / "shipments.csv"
    path.write_text(SHIPMENTS_CSV)
    return path

@pytest.mark.parametrize("raw, expected", [   # 3. one test, many cases
    ("120 kg", 120.0), ("300 lbs", 136.08),
])
def test_weights(raw, expected):
    assert parse_weight_kg(raw) == expected

Run with pytest -q. Parametrise is the workhorse of integration testing: the same parser, fed every strange value the customer's data contains, each case reported separately.

Done here? The practice set for Part 3 — 4 exercises with solutions — is on the part page.

Search the guide