Lesson 5 of 9 · 26m
Contract Testing in CI: Prove the Server Keeps the Promise
Validate implementation responses against the spec, exercise edge cases statefully, and make contract drift a build failure rather than a support ticket.
The most dangerous API change is rarely a deleted endpoint. It is the field that became nullable, the enum that grew a value, the error shape that changed during a framework upgrade, or the datetime that lost its Z. These are small diffs with blast radius. Contract testing exists to catch them while the developer still remembers why the change was made.
Start with schema conformance
At minimum, verify representative responses conform to the OpenAPI schema. Tools such as Schemathesis can generate requests from the contract:
schemathesis run openapi.yaml --base-url http://127.0.0.1:8080 --checks all --hypothesis-max-examples 100 --header "Authorization: Bearer $TEST_TOKEN"Run this in CI against a disposable test environment. Treat 500s, undocumented responses, schema mismatches, and unexpected success as defects or explicit risk acceptance.
Conformance is necessary, not sufficient
A response can match the schema and still violate the business contract. status: active may be syntactically valid while the object is actually suspended. Schema tests validate representation; workflow tests validate truth.
Build stateful scenarios:
create customer -> create order -> pay order -> read order
invite user -> accept invite -> revoke membership -> read member
create export -> poll job -> download artifact -> delete artifactEach step should assert both visible representation and forbidden access. The important API failures usually involve relationships and lifecycle state, not malformed JSON.
Golden responses are useful when diffs are reviewed
Snapshot testing gets a bad reputation because teams blindly approve changes. Used carefully, it is excellent drift detection:
pytest tests/contract/test_orders.py --snapshot-updateNever update snapshots automatically in CI. A snapshot diff should force a human to say, “yes, this is the contract change we intended.”
Test error behavior too
Many teams test successful responses and leave errors to vibes. Assert exact status, content type, error schema, field-level details, and idempotency behavior:
def test_duplicate_idempotency_conflict(client, order_payload):
key = "ord_test_9f8e7d6c"
first = client.post("/orders", json=order_payload, headers={"Idempotency-Key": key})
changed = dict(order_payload, customerId=str(uuid4()))
second = client.post("/orders", json=changed, headers={"Idempotency-Key": key})
assert first.status_code == 201
assert second.status_code == 409Keep test data boring and deterministic
Use seeded tenants, customers, orders, and permissions. Contract tests should fail because behavior changed, not because random data found an uncontrolled edge. Save fuzzing as a separate stage with explicit triage.
Field notes
- Validate requests leaving the client too; server-only validation lets broken integrations travel farther before failing.
- Do not point mutation-heavy contract tests at shared staging environments. State collisions create flaky nonsense.
- Mark undocumented behavior in tests as a bug or document it. A private exception list becomes a secret second contract.
- Contract tests belong near implementation, but the spec review belongs with consumers as well.
Was this lesson helpful?