From Zero to Code Quality Gates That Survive Production

An inherited API can pass deployment checks while returning the wrong answer. For the DevOps engineer supporting it, the first useful setup is not a load test or a rewrite:…

An inherited API can pass deployment checks while returning the wrong answer. For the DevOps engineer supporting it, the first useful setup is not a load test or a rewrite: it is a small, repeatable production-like test that can block a bad release. I would start with one deterministic account response, even if the code behind it is ugly, because an executable baseline is easier to operate than an undocumented expectation.

One isolated account is a better starting point than a test environment full of history

Pick one read-only route with a stable business result. This walkthrough uses GET /api/accounts/fixture-17, returning an account ID and a balance in cents. Before writing a test, trace that request through the router, authorization middleware, database query, and response serializer. Record which PostgreSQL table supplies the balance and whether a background job can change it. A test cannot be deterministic if its fixture is quietly mutable.

Bring up the inherited service and PostgreSQL 16 in an isolated Docker Compose v2 project. Use the repository’s existing migration command rather than copying a production database, because production data introduces privacy risk and makes failures harder to reproduce. Add a seed step that creates fixture-17 with a balance of 1250 cents and a test-only identity permitted to read it. The seed should be safe to rerun: either replace that fixture in a transaction or fail with a clear message if its state differs.

Keep the environment close to production where behavior depends on configuration. Match the database major version, enabled extensions, authorization mode, and feature flags; do not copy production credentials. Give the service a dedicated network and database, then verify the route manually with curl 8 before involving pytest. If the response varies between identical calls, investigate caches, time-dependent fields, and asynchronous writes now rather than accepting a flaky baseline.

I would not begin by generating traffic, because a higher request rate cannot tell you whether 1250 became an incorrect balance. Inherited Untested Code? Scale Will Expose the Seams makes the scaling risk explicit; for this setup, correctness at one repeatable request is the more useful first gate. Write down the fixture owner and reset command in the repository so the next on-call engineer can recreate the same state.

A narrow contract test catches regressions without freezing every response field

Install Python 3.12, pytest 8, and requests 2.32 in a pinned test environment. The application does not have to be written in Python: this test exercises its HTTP boundary. Put the following in tests/test_account_contract.py. It assumes the seeded service is reachable at BASE_URL and a test-only bearer token is supplied as TEST_TOKEN.

import os
import requests

def test_fixture_account():
    response = requests.get(
        os.environ["BASE_URL"] + "/api/accounts/fixture-17",
        headers={"Authorization": "Bearer " + os.environ["TEST_TOKEN"]},
        timeout=2,
    )
    assert response.status_code == 200
    data = response.json()
    assert data["id"] == "fixture-17"
    assert data["balance_cents"] == 1250
    assert "token" not in data

Run it with BASE_URL pointing at the isolated service and pytest -q tests/test_account_contract.py. The two-second timeout is an initial setting to adjust after observing local and CI latency; its immediate purpose is to prevent a stalled request from hanging the job indefinitely. Keep TEST_TOKEN in the CI secret store, mask it in logs, and restrict it to the fixture account.

There are two reasonable ways to check the response. Selected-field assertions, as above, win when the API adds harmless metadata often; they cost you coverage of fields you did not name. Full-response snapshots win when every byte of a versioned response is contractual; they cost review time because timestamps, ordering, and additive fields can produce noisy diffs. For this inherited route, I would choose selected fields and add assertions only for behavior an operator or client can explain.

The missing token assertion is deliberate: a status code and correct balance would still pass if the serializer leaked a credential-shaped field. Add separate tests for an unauthorized request and a missing account rather than packing all outcomes into one function, because a failed assertion should identify one broken behavior. Code Craftsmanship Tips for Cleaner, Safer Software favors cleaner code; I would leave the legacy handler alone until this boundary test makes a cleanup safe to verify.

The CI gate should prove its dependencies are ready before it judges the code

Put the fixture test in a dedicated GitHub Actions job that starts the Compose project, applies migrations, seeds the account, waits for readiness, runs pytest, and tears the project down even if pytest fails. Pin the action versions and container image digests used by the job, because an unreviewed runner change can make a legacy application fail for reasons unrelated to a pull request. Publish the test result and service logs as artifacts, but redact authorization headers and database connection strings.

Do not use “container started” as the readiness condition. Check an application endpoint that confirms it can query PostgreSQL, because the process can accept connections before migrations finish. Bound the wait: a provisional 60-second startup limit is long enough for many small CI environments but should be changed if your runners consistently need more time. On timeout, collect the service and database logs before teardown; otherwise the job reports only that a test never ran.

Run the contract job on every pull request touching the service, migrations, seed, or deployment configuration. Make it a required check once it has passed repeatedly on unchanged commits, because a flaky required gate invites people to bypass it. Distinguish an environment failure from an assertion failure in the job output: “database never became ready” calls for infrastructure investigation, while “balance was 1200” points toward application or fixture behavior.

Keep the gate small enough to diagnose. If a local trial reports a 180 ms p95 for this route, treat that as a measured baseline from that trial, not a universal performance target; track it separately in Prometheus using an HTTP request-duration histogram. Contract correctness should block a release immediately. Latency should block it only after you have a representative environment and an agreed threshold, since a shared CI runner can create slow requests without a code regression.

A failure rehearsal is necessary before the test earns a production role

A green happy-path test proves little about an on-call procedure. In the isolated environment, deliberately break the database connection, expire the test token, and change the seeded balance one at a time. Each change should produce a different, recognizable failure. Restore the fixture and rerun pytest after each rehearsal, because an exercise that leaves dirty state undermines the next build.

Use Toxiproxy 2.11 if the service’s database connection can be routed through a proxy; it provides a controlled way to interrupt that connection without changing application code. Check that the API fails within its configured request deadline rather than holding clients open indefinitely. Inspect OpenTelemetry traces for the request and database span, but verify that span attributes contain no token or account-sensitive payload. Prometheus and Grafana can show whether failures increase, while the pytest output identifies which promised response changed.

Write a short runbook alongside the test: the command to start the environment, the seed/reset command, the expected response, and where to find logs and traces. Include what to do if the test fails during an incident: verify fixture state and dependency health before assuming a developer changed the serializer. That order matters because the same red test can result from a code regression, an expired credential, or a failed migration.

Set an initial alert rule for three failed synthetic requests in ten minutes only after testing notification routing; those numbers are a starting threshold, not evidence of an appropriate production SLO. A synthetic check must use its own identity and fixture, since sharing a real customer account creates both operational noise and an access-control problem. Rehearse one alert through acknowledgment and resolution so the dashboard is connected to a person, not merely populated with graphs.

A small canary makes the baseline useful without turning it into a release ceremony

After CI is reliable, run the same contract against staging on deployment, using a separately seeded fixture and staging-only token. Then deploy to a small production canary and check existing service metrics before increasing traffic. An initial 1% canary for 15 minutes is a value to tune against actual request volume: at a quiet service, it may yield too few requests to support a decision. Do not run a destructive seed against production; if a synthetic production account is permitted, provision and audit it through the normal account-management path.

Define rollback before the first canary: name the previous image digest, the command or controller action that restores it, and the condition that stops promotion. Keep database changes backward-compatible across both versions, because rolling back an image cannot reverse a destructive migration. The contract test is one signal, not permission to ignore error rate or dependency health.

Start by creating fixture-17 in an isolated Compose environment and making the single pytest test pass twice after a full teardown and restart. Then deliberately change its seeded balance and confirm the job fails with an understandable message. That small exercise establishes the property a production gate needs most: another engineer can reproduce both its success and its failure without asking what the original author meant.