Backend tests verify what the user interface hides: that every API endpoint answers correctly, that failures are handled instead of swallowed, and that the contract with the provider still holds. My reference project is API-Pytest: a typed Python client for a public weather API, built and tested like a production library, with 68 offline tests, 100% coverage, strict typing and lint, plus live contract tests that run under a request budget. It is planned from a risk-based test plan rather than written test by test.
In short
- A typed API client tested like a production library, with strict typing and lint.
- Planned from a risk-based test plan that also lists what is not automated yet.
- Live contract tests run under a request budget, and the API key never reaches exceptions or reports.
68
offline tests
100%
coverage
90%
branch-coverage floor in CI
9
live requests per run
What the suite proves
| Layer | What is tested |
|---|---|
| Input validation | Blank city, coordinates at the limits (±90, ±180) and just beyond: rejected before any HTTP call, so no quota is spent |
| Error mapping | 400, 401, 404, 429 and 5xx become typed exceptions that keep the status and message. Client errors are never retried |
| Resilience | Exponential backoff, Retry-After honoured but capped at 30 s, timeouts retried, a typed error once retries are exhausted |
| Contract | Responses validated by strict models and a published JSON schema. Mutated payloads, non-JSON bodies and an error payload served with a 200 all raise a typed error |
| Security | The API key never appears in exception text or in __cause__, and it is held as a secret value in the settings |
| Live | Nine real requests per run, with tolerances for values that depend on the weather. They skip cleanly without a key |
Offline first, live as a contract check
- Deterministic by design. The client receives its HTTP session and its
sleepfunction as parameters, so tests stub the network and record every wait instead of sleeping. The whole offline suite needs no network and no secrets. - Live tests are a budget. Markers separate
mockedfromlive, and the plan counts the nine live requests so that daily and push runs stay inside the free quota. Live results never gate pull requests. - Secrets are a design constraint. The key comes from the environment or an untracked file, is never printed, and never reaches a report.
Two details from the code. The client drops the original network exception, because its text embeds the request URL and with it the API key. And a huge Retry-After value cannot stall a run:
except (requests.ConnectionError, requests.Timeout) as exc:
# The original exception embeds the request URL, which contains the API key.
if attempt >= self._max_retries:
raise UpstreamError(f"Network failure: {type(exc).__name__}") from None
def test_retry_after_header_is_capped(client, http, weather_url, sleeper, madrid_payload):
http.add(responses.GET, weather_url, status=429, headers={"Retry-After": "86400"})
http.add(responses.GET, weather_url, json=madrid_payload)
client.current_by_city("Madrid")
assert sleeper.delays == [30.0]
Planned from risk, with an honest coverage map
The test plan follows the structure of ISO/IEC/IEEE 29119-3. It ranks the risks first (API key leaks, wrong error class, retry storms, silent payload drift) and spends the effort in that order. Test cases come from named techniques: equivalence partitioning for status codes, boundary values for coordinates and retry counts, a decision table and a state model for the retry loop, and error guessing for malformed payloads. A traceability matrix links every case to its test, and the plan lists the behaviours that are not automated yet instead of claiming full coverage.
Quality gates in CI
Every change runs ruff for lint and format, mypy in strict mode and the offline suite with a branch-coverage floor of 90%. The live tests run on pushes and every day at 15:00 UTC. GitHub Actions are pinned to commit SHAs, and the HTML and JUnit reports are uploaded as artifacts. See CI/CD pipelines.
AI-assisted failure triage
When a run fails, a small agent in the repository turns the JUnit report into a classified issue. Code does everything deterministic, and the model is called only for the judgement call: is this a product defect, a test defect, an environment problem or a flaky test?
JUnit XML -> parse -> redact secrets -> fingerprint -> (new failure?) -> model classifies -> Markdown issue
- Redact before anything else, so no later step, including the model call, can leak a secret.
- Known failures never reach the model. A fingerprint of test ids and normalised messages recognises them, which keeps cost and noise down.
- Typed verdicts, untrusted input. The answer is validated against a schema, and the failure text is declared untrusted because test output can contain instructions.
- Fails safe. Without an API key the report is still produced, marked as not triaged.
Status, stated plainly: the agent and the workflow that opens one deduplicated issue after a failed API run are built and tested with a stub client, and I have not run them against the live model API yet. The same thinking applies to AI systems under test: see LLM evaluation.
Earlier work: circuits with database verification
Before the typed client, I built API test circuits against private environments with requests and unittest: tests that share state (the token from sign-in feeds every following call), read identifiers the API does not return directly from Firestore, verify the stored fields, and clean up after themselves so the next run starts from a known state. Jenkins scheduled the runs. That code is kept as a record in legacy/Jenkins-CI, with the Jenkins pipeline described on its own page. For the data side, see data quality and ETL testing.
