Automation that changes production deserves the same safety net as the services it manages: tests with pytest that run in seconds, fakes for the network and the cloud, type hints checked by mypy, a linter and formatter (ruff), and a CI pipeline that builds and publishes the tool. This lesson takes the API inventory tool from "works on my laptop" to a tested, typed, released package, and shows the two gaps that let bugs through: tests that call the real API, and type hints nobody checks.
Difficulty: Advanced · Know this first: Lesson 35, Lesson 40
This bar adds up minutes from a change to a release. It is a worked example, not a measurement. The fakes and type-checker hops decide whether the safety net is fast and real.
Set how many tests call the live API. Each live test takes about 4 seconds and fails 2% of the time for reasons unrelated to your change.
Untrustworthy: almost every run fails for reasons unrelated to the change
Three questions. No score is saved anywhere — this is just you against the material.
Testing and shipping grow in four levels: first tests, isolated tests, checked code in CI, and release engineering.
At the basic level you can test a function.
test_*.py files, def test_...():, plain assert.pytest -q, -k pattern, -x to stop at the first failure.pytest.raises(ValueError) for expected errors.Where it breaks: testing only the happy path, never empty input or bad data.
Try it: Basic
How do you test that parse() raises ValueError on bad input?
Now do it: Add one test for an error path in one of your scripts.
At the intermediate level tests are fast and deterministic.
tmp_path, monkeypatch, parametrize.unittest.mock for the rest.Try it: Intermediate
Why pass the API client into a function instead of creating it inside?
Now do it: Refactor one function to accept its client as a parameter.
At the advanced level every change is checked automatically.
Try it: Advanced
You add type hints to a codebase but never run mypy. What value do they have?
Now do it: Run mypy on one project and fix the first three errors.
At the master level releases are routine and reversible.
Trade-off: strict checks slow the first change and speed up every change after; recorded API responses make tests fast and must be refreshed, or tests pass against an API that no longer exists.
Try it: Master
Your tests replay API responses recorded a year ago. What risk does that carry?
Now do it: Date your oldest recorded fixture and schedule a refresh.
A tested, typed module with a fake client. Save both files and run pytest -q and mypy.
from typing import Iterator, Protocol
class Client(Protocol):
def page(self, token: str | None) -> dict: ...
def instances(client: Client) -> Iterator[dict]:
token: str | None = None
while True:
page = client.page(token)
yield from page["items"]
token = page.get("next")
if not token:
return
def owner(tags: dict[str, str]) -> str | None:
return tags.get("owner")
def owners_report(client: Client) -> dict[str, int]:
counts: dict[str, int] = {}
for inst in instances(client):
name = (owner(inst.get("tags", {})) or "untagged").lower() # mypy forces the "or"
counts[name] = counts.get(name, 0) + 1
return dict(sorted(counts.items()))
import pytest
from inventory import owners_report
class FakeClient:
def __init__(self, pages):
self.pages = pages
def page(self, token):
return self.pages[token]
PAGES = {
None: {"items": [{"tags": {"owner": "Payments"}}, {"tags": {}}], "next": "p2"},
"p2": {"items": [{"tags": {"owner": "payments"}}]},
}
def test_report_follows_pages_and_handles_untagged():
assert owners_report(FakeClient(PAGES)) == {"payments": 2, "untagged": 1}
@pytest.mark.parametrize("pages, expected", [({None: {"items": []}}, {})])
def test_empty(pages, expected):
assert owners_report(FakeClient(pages)) == expected
# run: python3 -m pip install pytest mypy && python3 -m pytest -q && python3 -m mypy inventory.py
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A test suite trained people to ignore it.
Unit tests run with the network disabled, live integration tests run nightly against a sandbox with their own alerts, mypy and ruff gate every merge, and automatic test retries are switched off.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install pytest mypy ruff.
Type each one, read what it prints, and compare it with the note above it.
Write a function and a test, and run pytest.
mkdir -p /tmp/tlab && cd /tmp/tlab && printf "def owner(tags: dict[str, str]) -> str | None:\n return tags.get(\"owner\")\n\ndef label(tags: dict[str, str]) -> str:\n return owner(tags).lower()\n" > inv.py && printf "from inv import label\n\ndef test_label():\n assert label({\"owner\": \"Payments\"}) == \"payments\"\n" > test_inv.py && python3 -m pytest -q 2>/dev/null | tail -1The test passes, but mypy finds the None bug.
cd /tmp/tlab && python3 -m mypy inv.py 2>/dev/null | head -2
ruff finds common mistakes in milliseconds.
cd /tmp/tlab && printf "import os\ndef f(x, acc=[]):\n try:\n acc.append(x)\n except:\n pass\n" > bad.py && python3 -m ruff check --select E,F,B bad.py 2>/dev/null | head -6
Run the tests with the network unavailable (Linux, no root needed with user namespaces), then clean up.
cd /tmp/tlab && unshare -rn python3 -m pytest -q 2>/dev/null | tail -1; cd /; rm -rf /tmp/tlab
fake_client.pyThis program tests a paginated report against a fake client instead of the real API, and shows a test catching the "only the first page" bug in milliseconds. Save it as fake_client.py, then run it.
# fake_client.py
class FakeClient:
def __init__(self, pages):
self.pages, self.calls = pages, 0
def page(self, token):
self.calls += 1
return self.pages[token]
PAGES = {None: {"items": ["a", "b"], "next": "t2"}, "t2": {"items": ["c", "d"], "next": "t3"}, "t3": {"items": ["e"]}}
def count_buggy(client):
return len(client.page(None)["items"])
def count_fixed(client):
token, total = None, 0
while True:
page = client.page(token)
total += len(page["items"])
token = page.get("next")
if not token:
return total
for fn in (count_buggy, count_fixed):
client = FakeClient(PAGES)
got = fn(client)
print(f"{fn.__name__:<12} counted {got}, expected 5, pages fetched {client.calls}: {'PASS' if got == 5 else 'FAIL'}")
Run it, and you should see this output:
$ python3 fake_client.py count_buggy counted 2, expected 5, pages fetched 1: FAIL count_fixed counted 5, expected 5, pages fetched 3: PASS
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-testing-typing-and-shipping-tools && cd ~/labs/python-testing-typing-and-shipping-tools) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python Testing, Typing, and Shipping Tools", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Write a function and a test, and run pytest.'
'The test passes, but mypy finds the None bug.'
'ruff finds common mistakes in milliseconds.'
'Run the tests with the network unavailable (Linux, no root needed with user namespaces), then clean up.'
)
step_1() {
mkdir -p /tmp/tlab && cd /tmp/tlab && printf "def owner(tags: dict[str, str]) -> str | None:\n return tags.get(\"owner\")\n\ndef label(tags: dict[str, str]) -> str:\n return owner(tags).lower()\n" > inv.py && printf "from inv import label\n\ndef test_label():\n assert label({\"owner\": \"Payments\"}) == \"payments\"\n" > test_inv.py && python3 -m pytest -q 2>/dev/null | tail -1
}
step_2() {
cd /tmp/tlab && python3 -m mypy inv.py 2>/dev/null | head -2
}
step_3() {
cd /tmp/tlab && printf "import os\ndef f(x, acc=[]):\n try:\n acc.append(x)\n except:\n pass\n" > bad.py && python3 -m ruff check --select E,F,B bad.py 2>/dev/null | head -6
}
step_4() {
cd /tmp/tlab && unshare -rn python3 -m pytest -q 2>/dev/null | tail -1; cd /; rm -rf /tmp/tlab
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
head, tail, mkdir, rm, cd, Pipes, Redirection, If...Else.Add a safety net to an untested automation repository of 12 scripts that manage DNS records and cloud resources.
Which functions are tested first? How are the DNS and cloud APIs faked? Which checks gate a merge, and how long may they take? How do you release and roll back a script?
Say 12 scripts, 3,000 lines, four engineers, and a goal of a CI run under 5 minutes.
Extract pure functions (parsing, diffing desired and actual records) and test them first; inject API clients and add fakes with recorded responses; ruff and mypy (strict on new modules) in pre-commit and CI; pytest with coverage on 3.11 to 3.13; a nightly integration job against a sandbox zone; package as one tool with entry points, released by tag, installed with pipx at a pinned version.
Refactoring for testability changes working code and needs care; the first tests should cover current behaviour before improving it. Strict typing finds bugs early and slows the first weeks while the code is annotated.