Testing Best Practices: Test Design, Architecture and Agents
Most test suites don't fail because someone picked the wrong framework. They fail slowly, through structure: tests that call the API five different ways, fixtures that depend on each other in ways nobody remembers, shared data that makes one test break another, and a CI job that runs everything or nothing. Test architecture is the set of decisions that keeps a suite cheap to change. In practice it matters more than any single tool.
It matters even more now that GitHub Copilot, Claude Code, Cursor and similar coding agents write a large share of test code. An agent copies the patterns it finds. In a well-structured suite, that means it adds tests in the right layer, through the right client, with the right fixtures. In a messy one, it multiplies the mess faster than anyone can review it. Good architecture has become the main control you have over agent-written tests.
This guide is how I approach test design and architecture for API suites: layers, a client layer, fixtures, test data, CI, and the rules I put in the repository so agents follow them. I'll finish with where I think the work is heading, without the hype.
From Zero to Smarter API Automation with Node.js & Cucumber — Using AI, CI/CD, and Modern Tooling.
Start with design: what is this test protecting?
Every test should answer one question: what behaviour breaks if this test goes red? If you can't say it in a sentence, the test is probably checking an implementation detail, or nothing at all. I design tests from the behaviour inward: the business rule, the contract the API promises, the error a client depends on. Then I pick the cheapest layer that can check it.
A few design habits pay off everywhere:
- One behaviour per test. A test that checks creation, update and deletion in one function tells you very little when it fails.
- Assert on documented behaviour. Status code plus a business field or a schema, taken from the spec, never from whatever the API returned the day the test was written.
- Name tests after the rule.
test_refund_rejected_after_30_daysis documentation.test_refund_3is not. - Make it able to fail. Break the expected value on purpose once and watch the test go red. A test that can't fail is decoration.
Layer the suite deliberately
The layers I use are familiar: unit tests next to the code, API tests against a running service, and a thin set of end-to-end journeys across services or the UI. The architectural part is deciding what each layer owns, so the same rule isn't checked three times at three speeds. Validation rules and edge cases belong at the API layer, where they're fast and precise. End-to-end tests should prove the pieces connect, not re-test every field. I go into the split in more detail in layering a test suite: unit, API, end to end.
A folder structure that makes the layers visible helps people and agents alike:
tests/
conftest.py # shared fixtures: config, client, auth
clients/
orders_client.py # the only place that knows URLs and headers
api/
test_orders.py
test_refunds.py
contract/
test_orders_schema.py
journeys/
test_checkout_flow.py
data/
builders.py # test data factories
pytest.ini
.github/copilot-instructions.md
Put a client layer between tests and HTTP
The single most valuable structural decision in an API suite is that tests don't call requests directly. They call a small client that owns the base URL, headers, timeouts and serialisation. When the API adds a version prefix or changes its auth header, you change one file instead of two hundred tests.
import requests
class OrdersClient:
def __init__(self, base_url, token, timeout=10):
self.base_url = base_url.rstrip("/")
self.session = requests.Session()
self.session.headers.update({"Authorization": f"Bearer {token}"})
self.timeout = timeout
def create_order(self, payload):
return self.session.post(f"{self.base_url}/orders", json=payload, timeout=self.timeout)
def get_order(self, order_id):
return self.session.get(f"{self.base_url}/orders/{order_id}", timeout=self.timeout)
def delete_order(self, order_id):
return self.session.delete(f"{self.base_url}/orders/{order_id}", timeout=self.timeout)
Notice the client returns the raw response. Assertions stay in the test, where a reader expects them. Clients that assert internally hide what a test checks, and they make negative tests awkward because every non-200 throws before the test can look at it.
Fixtures: small, explicit and scoped on purpose
Fixtures are where suites quietly rot. My rules: each fixture does one thing, its scope is chosen deliberately, and anything it creates it also cleans up.
import os
import pytest
from tests.clients.orders_client import OrdersClient
from tests.data.builders import order_payload
@pytest.fixture(scope="session")
def orders_client():
return OrdersClient(os.environ["API_BASE_URL"], os.environ["API_TOKEN"])
@pytest.fixture
def created_order(orders_client):
response = orders_client.create_order(order_payload())
assert response.status_code == 201
order = response.json()
yield order
orders_client.delete_order(order["id"])
Session scope for the expensive, read-only setup; function scope for anything a test mutates. Code after yield runs at teardown even when the test fails, which is exactly what you want for created records.
Test data: isolated by default
Shared data is the most common cause of tests that pass alone and fail together. I default to each test creating what it needs through builders, with unique identifiers so parallel runs don't collide. Fixed seed data is fine for reference values that never change, such as a list of currencies, but not for anything a test writes to. How far to take isolation is a judgment call, and I cover the trade-offs in how much test data isolation is actually enough.
One rule doesn't bend: no real customer data in fixtures, recorded responses or prompts. That rule matters more once an agent can read your fixtures and paste them into a model's context.
CI: run the right subset at the right time
Architecture shows up in CI as selection. Fast, deterministic API tests run on every pull request. Slower journeys and contract checks run on merge or nightly. Register markers so a typo can't silently create a new, never-run category:
[pytest]
addopts = --strict-markers
markers =
smoke: fast checks for every pull request
journey: multi-step flows, run on merge
llm: calls a model; reported as a pass rate, run nightly
Then each pipeline stage picks its subset, for example pytest -m smoke on pull requests and pytest -m "not llm" on merge. I've written more about this in tagging API tests so CI can run the right subset and where API tests belong in a CI/CD pipeline.
Treat flaky tests as defects with an owner, not as noise. A retry that hides a real race condition is worse than a red build.
Architecture for a suite that agents work in
This is the section I'd add to any test architecture guide written today. When a coding agent adds tests, it reads the repository and imitates it. So the architecture has to be explicit, written down where the agent will read it, and enforced by review.
Copilot reads repository-wide guidance from .github/copilot-instructions.md, and most other agents have an equivalent instructions file. I keep the architectural rules there:
## Test architecture rules
- Tests call clients in tests/clients/. Never call requests directly from a test.
- New fixtures go in the nearest conftest.py; reuse existing fixtures before adding one.
- Test data comes from tests/data/builders.py. No hardcoded IDs, no real customer data.
- Expected values come from openapi.yaml or the acceptance criteria, never a live response.
- Every new test has a marker: smoke, journey or llm.
- Never weaken, skip or delete a failing test to get CI green. Report it instead.
Then the review gate does the rest. Agent-written tests go through a branch, a pull request, CI and a human approval, the same as anyone else's. When I review them I check for the structural failures agents tend to produce: a second, slightly different HTTP helper; a fixture that duplicates one two folders up; snapshot assertions copied from the current response; and a pull request that changes product code and edits the test to agree with it.
A clean architecture also makes agent work easier to verify. If every test goes through one client and one set of builders, a reviewer only has to read the test's intent and assertions. If every test is its own little framework, review becomes a full code audit, and that's where generated volume starts to win against human attention.
Where test architecture is heading
I'm wary of trend predictions, so here's what I'm confident about. More products include an LLM feature or an agent that calls tools, and those need a different shape of test. Their output varies from run to run, so a single pass proves very little. The architecture answer is to keep them in their own layer, behind an injected generate(prompt) function so the test doesn't depend on a vendor SDK, scored as a pass rate over several runs against an agreed threshold, and reported separately from the deterministic suite. A golden dataset of inputs with expected properties becomes part of the suite, versioned and rerun whenever the prompt or model changes.
The other shift is that the work moves toward specification and review. Writing a test is close to free now. Deciding what should be tested, and confirming a test really protects it, is not. A clear architecture is what keeps that review manageable.
If you want to build a suite like this from scratch, with a client layer, fixtures, BDD scenarios and GitHub Copilot in VS Code, that's what my API testing courses walk through, in Python with Behave or Node with Cucumber.