Build a Regression Test Suite for a REST API
System DesignModel answerLast updated
Design an automated testing strategy for a three-endpoint user service that survives frequent deployments without breaking existing behavior.
Scenario
You maintain a user profile service with three endpoints:
GET /users/{id}— fetch a user's profilePOST /users— create a new userPATCH /users/{id}— partially update a user's fields
The team ships changes several times a week. Your job is to design an automated regression suite so that a broken deployment is caught before it reaches production.
What you need to cover
-
Test layers. Describe the types of tests you would write (unit, integration, end-to-end, etc.), what each layer covers, and roughly how many tests belong at each level.
-
Schema and version safety. Explain how you would detect a change in the API's request or response shape before it reaches users, across current and future API versions.
-
Test data isolation. Describe how you would provision and clean up test data so that every CI run starts from a known state and parallel runs don't interfere with each other.
-
Deployment gate. List the explicit pass/fail criteria a build must meet before it is allowed to deploy.
Constraints
- The suite must run inside a CI/CD pipeline without manual setup.
- You must handle external dependencies (database, third-party auth service) without relying on shared infrastructure.
- Include a concrete code example showing how you would test that a
POST /usersrequest succeeds and that the newly created user can then be retrieved withGET /users/{id}.
Hints
Hint 1
Start from the testing pyramid: most tests should be fast and cheap (unit), fewer should be slow and broad (end-to-end). Explain the trade-off rather than just listing names.
Hint 2
Think about what 'schema safety' means at two levels: does your code match your OpenAPI spec, and does your spec match what consumers actually depend on? Those are different problems with different tools.
Hint 3
Test data isolation is mostly about who owns the database. Ask yourself: should the test talk to a real database, a container, or a mock? Each choice has consequences for what bugs you can actually catch.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
"Write tests" is not an engineering system. A strong answer turns the requirement into four concrete properties: the suite is layered (cheap tests run first and catch most bugs), contract-aware (shape changes are caught before consumers break), hermetic (every run is independent and repeatable), and gated (pass/fail criteria are decided in advance, not argued over at deploy time).
1. Test layers (the pyramid)
| Layer | What it tests | Dependencies | Rough share |
|---|---|---|---|
| Unit | Validation rules, serializers, PATCH allow-list logic | All mocked; pure functions | ~70%, seconds total |
| Integration | Full HTTP cycle through routing, middleware, handlers, real DB | Postgres in a container; auth replaced by a local stub | ~20%, a few minutes |
| Contract | Request/response shapes versus the published OpenAPI spec | Spec diffing only, or a Pact provider run | Fast; runs before integration |
| E2E smoke | A handful of critical journeys against a deployed staging environment | Real auth sandbox, real network | ~5–10 tests, post-deploy only |
The key distinction to make explicit: unit tests check isolated logic ("a PATCH body containing id is rejected because that field is immutable"), while integration tests check the wiring ("the PATCH actually persists, returns 200, and updated_at advances in the database").
Mocking policy: mock what you don't own — third-party auth, email delivery, analytics. Use real containerized instances of what you do own — Postgres, Redis. Mocking your own database hides real bugs: unique-constraint violations, transaction isolation issues, migration drift.
2. Schema and version safety
Three layers working together:
Spec as source of truth. Keep an OpenAPI document versioned in the repo. In CI, run a breaking-change diff (e.g., oasdiff) between the base branch spec and the PR spec. Fail the build on removed fields, narrowed types, newly required request fields, or changed status codes. Additive changes (new optional response fields) pass.
Response schema validation in tests. Every integration test validates actual HTTP responses against the spec's JSON Schema — not just "did I get a 200?" but "does the body match the declared shape?" This catches the case where code drifts from the spec silently.
Consumer-driven contracts. Web, mobile, and internal callers publish what they actually consume. The provider build replays those contracts (Pact is the standard tool). This catches breakage the spec diff can't see, like changing the meaning of a field without changing its type.
For services running multiple live versions (/v1, /v2): run the same golden fixture through both. Assert that shared fields are semantically identical. A user created via v2 must read back correctly via v1, with v2-only fields defaulted.
3. Test data isolation
Ephemeral environment per CI job. Use docker-compose or Testcontainers to spin up the service and a fresh Postgres for each pipeline run. Apply migrations from scratch — this tests the migrations themselves. Nothing is shared between runs.
Deterministic seed data. Use factory functions (make_user(**overrides)) rather than hand-written SQL dumps. Control time with a fake clock rather than sleeping. Generate emails and usernames with a UUID suffix so parallel test jobs never collide on unique constraints.
Teardown. This API has no DELETE endpoint, so cleaning up requires going to the data layer. Two workable approaches:
- Wrap each test in a transaction that rolls back — works when the test and the app share a database connection.
- For black-box HTTP tests, track created IDs during the test and delete them in a teardown fixture that runs even on failure.
4. Deployment gate
A build proceeds only when all of the following hold:
- 100% of unit, contract, and integration tests pass. Flaky tests are quarantined and tracked separately — they do not get a free pass on the gate.
- The OpenAPI breaking-change check is clean, or the PR carries an explicit version bump with approval.
- All consumer contracts verify green.
- Line coverage on changed code meets a floor (e.g., ≥80%). This is a minimum, not a target — it guards against untested new paths, not a metric to chase.
- p95 latency on integration endpoints has not regressed by more than ~20% against the baseline, so performance regressions are caught before they reach users.
- Post-deploy smoke tests pass on the canary slice. On failure, roll back automatically before widening the rollout.
Code example: POST then GET
import os
import uuid
import httpx
import psycopg
import pytest
from jsonschema import validate
BASE_URL = os.environ.get("API_BASE_URL", "http://localhost:8080")
DB_URL = os.environ.get("TEST_DB_URL", "postgresql://test:test@localhost:5432/users")
# Mirrors the OpenAPI schema for a User response object.
USER_SCHEMA = {
"type": "object",
"required": ["id", "email", "display_name", "created_at"],
"properties": {
"id": {"type": "string"},
"email": {"type": "string"},
"display_name": {"type": "string"},
"created_at": {"type": "string"},
},
"additionalProperties": False,
}
@pytest.fixture
def client():
# The in-test auth stub accepts any well-formed Bearer token.
headers = {"Authorization": "Bearer test-token"}
with httpx.Client(base_url=BASE_URL, headers=headers, timeout=5.0) as c:
yield c
@pytest.fixture
def cleanup_user_ids():
"""Collect IDs created during a test and delete them after, even on failure."""
ids: list[str] = []
yield ids
if ids:
with psycopg.connect(DB_URL) as conn:
conn.execute("DELETE FROM users WHERE id = ANY(%s)", (ids,))
def test_create_then_fetch_user(client, cleanup_user_ids):
payload = {
"email": f"reg-{uuid.uuid4().hex}@example.test",
"display_name": "Regression Rita",
}
# --- Create ---
create_resp = client.post("/users", json=payload)
assert create_resp.status_code == 201, create_resp.text
created = create_resp.json()
cleanup_user_ids.append(created["id"])
validate(instance=created, schema=USER_SCHEMA) # shape check
assert created["email"] == payload["email"] # value check
assert created["display_name"] == payload["display_name"]
# --- Fetch ---
get_resp = client.get(f"/users/{created['id']}")
assert get_resp.status_code == 200
fetched = get_resp.json()
validate(instance=fetched, schema=USER_SCHEMA)
# Read-after-write: the GET body must be identical to what POST returned.
assert fetched == created
Four things worth pointing out about this test: it asserts the exact status code (201, not merely "2xx"), it validates the response shape against the schema on both calls, it checks field values not just presence, and the cleanup fixture runs unconditionally so a failing test never leaves orphaned rows that corrupt the next run.
Common mistakes to avoid
- Mocking your own database. It hides real constraint violations and query bugs.
- Shared test data. A seeded "golden user" that multiple tests read and write causes flaky failures in parallel runs.
- Soft deployment gates. If "most tests pass" is acceptable, every team will quietly decide their failures are acceptable too. The gate must be binary.
- Testing only the happy path. Regression suites that skip 4xx responses miss a large class of real-world breakage — for example, a validation rule that silently stops enforcing.