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

Part 03 / Topic 2 of 6

Testing messy real-world inputs

On an engagement, the test cases are not invented — they are harvested from the customer's actual data. Acme's export contains 120 kg, 210 KG, 300 lbs, an empty weight and a negative one. Each becomes a test case:

# examples/01_test_a_parser_with_pytest_including.py
import pathlib, re, subprocess, sys, tempfile, textwrap

code = textwrap.dedent('''
    import re
    import pytest

    def parse_weight_kg(text):
        """'120 kg' -> 120.0, '300 lbs' -> 136.08, '' -> None"""
        if not text or not text.strip():
            return None
        m = re.fullmatch(r"\\s*(-?\\d+(?:\\.\\d+)?)\\s*(kg|lbs?)\\s*", text, re.IGNORECASE)
        if not m:
            raise ValueError(f"unrecognised weight: {text!r}")
        value, unit = float(m.group(1)), m.group(2).lower()
        return round(value * 0.45359237, 2) if unit.startswith("lb") else value

    @pytest.mark.parametrize("raw, expected", [
        ("120 kg", 120.0), ("210 KG", 210.0), ("300 lbs", 136.08), ("", None), ("  ", None),
    ])
    def test_valid(raw, expected):
        assert parse_weight_kg(raw) == expected

    def test_rejects_garbage():
        with pytest.raises(ValueError):
            parse_weight_kg("heavy")
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_weights.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
                   capture_output=True, text=True)
summary = r.stdout.strip().splitlines()[-1]
print(re.sub(r" in \d+\.\d+s", "", summary))  # timing varies run to run
# 6 passed

(The example writes its test file to a temp folder and runs pytest on it, so the lesson can show the real summary line. In your own work the test simply lives in tests/.)

The discipline: when a new strange value appears in production, it becomes a test case before it becomes a fix. The test suite grows into a catalogue of everything this customer's data has ever done to you.

🧪 Quick quiz — answer from memory, then check.

  1. Why test a parser with messy inputs such as 210 KG, 300 lbs and an empty string?
Show the answer

Real customer data contains exactly these cases, and each is a common way pipelines break. The parametrised test covers kg, KG, lbs, blank and garbage input: 6 tests passed. (verified against the example output above)

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

Search the guide