TEST ARCHITECTURE

When One API Test Suite Covers Multiple Environments and Agents

When a team moves from "we have some API tests" to "we run them against every environment in the pipeline," the suite design has to grow up too. A test that works against your local server but misleads you in staging, because of the wrong base URL, hardcoded credentials or seed data that only exists locally, is worse than no test. I've seen teams spend a long time chasing a red pipeline that turned out to be configuration, not a product bug.

The challenge is discipline more than technology. Every assumption a test makes about its environment has to live outside the test code: base URLs, tokens, timeouts, feature flags and which tests may run where. When that holds, switching environment is one variable. When it doesn't, you get copies of the suite per environment that slowly disagree.

There's a newer reason to get this right. Coding agents now run test suites too: Copilot in agent mode, Claude Code and similar tools run pytest from a terminal to check their own work. An agent will run whatever the defaults allow. Below are the three practices that make one suite reliable across environments, and the guardrails that keep an agent from running the wrong tests in the wrong place.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Keep every environment value out of test code

The first rule: no environment-specific value belongs in a test file. Not the base URL, not a key, not a timeout tuned for a slow staging server. I use a small config loader that reads the target from one environment variable and exposes a typed object:

# config/loader.py
import os
from dataclasses import dataclass
from pathlib import Path

import yaml

TEST_ENV = os.getenv("TEST_ENV", "dev")


@dataclass(frozen=True)
class Settings:
    env: str
    base_url: str
    api_key: str
    timeout: float


def load_settings() -> Settings:
    raw = yaml.safe_load(Path(f"config/{TEST_ENV}.yaml").read_text())
    return Settings(
        env=TEST_ENV,
        base_url=raw["base_url"],
        api_key=os.environ["API_KEY"],  # secrets come only from the environment
        timeout=float(raw.get("timeout", 10)),
    )

The YAML files hold non-secret values and are safe to commit. The API key comes only from the environment, which CI injects. If it's missing, the run fails at startup instead of halfway through with confusing 401s. Keeping test secrets out of version control covers the rest of that habit.

In Behave, load the settings once in before_all. One gotcha: don't store them as context.config. Behave already uses that name for its own configuration object, and overwriting it breaks things in confusing ways. Use your own name:

# features/environment.py
from config.loader import load_settings


def before_all(context):
    context.settings = load_settings()

Step definitions read context.settings.base_url. Switching environment is TEST_ENV=staging behave or TEST_ENV=staging pytest, with nothing in the suite changed. Put per-environment timeouts in the YAML too. A timeout that suits local and not staging produces failures that look flaky but are really configuration.

Not every test runs everywhere

Destructive tests that create and delete records are fine in dev and staging and unacceptable in production. Tests that need sandbox credentials don't work where live credentials are used. The fix is a small, fixed set of markers and one place that decides what runs where:

# conftest.py
import os

import pytest

SKIP_IN = {
    "production": {"destructive", "sandbox"},
    "staging": {"destructive_heavy"},
    "dev": set(),
}


def pytest_collection_modifyitems(config, items):
    env = os.getenv("TEST_ENV", "dev")
    for item in items:
        for name in SKIP_IN.get(env, set()):
            if item.get_closest_marker(name):
                item.add_marker(pytest.mark.skip(reason=f"'{name}' tests do not run in {env}"))

Register the markers in pytest.ini under markers = so a typo in a marker name fails loudly when you run with --strict-markers. In Behave, use tags and filter on the command line, for example behave --tags="not @destructive" in the production job. Tagging API tests so CI can run the right subset goes further into choosing the tag set.

The important part is that production runs the same suite as staging with a different filter, not a separate copy. Separate copies drift, and the production smoke suite stops checking the things that changed.

Guardrails for agents that run the suite

Skip rules protect you when the environment variable is set correctly. An agent working in a terminal may inherit a shell where someone exported TEST_ENV=production earlier, or may "helpfully" set it to reproduce a production bug. I don't want that decision to depend on the agent's judgment, so the suite refuses to run against production unless a second, explicit flag is set:

# conftest.py
def pytest_configure(config):
    if os.getenv("TEST_ENV") == "production" and os.getenv("ALLOW_PRODUCTION_TESTS") != "1":
        raise pytest.UsageError(
            "Refusing to run against production. Set ALLOW_PRODUCTION_TESTS=1 "
            "in the production smoke job only."
        )

Only the production smoke job in CI sets that flag. Locally, for a person or an agent, the safe default wins. Defaulting TEST_ENV to dev follows the same reasoning: the least dangerous environment is the one you get without asking.

Then say it in the repository instruction file your agent reads, such as .github/copilot-instructions.md: run tests only against dev or a local stack, never set ALLOW_PRODUCTION_TESTS, and never remove a skip marker to get a test to run somewhere. The code enforces it, and the instruction stops the agent wasting time trying.

If your API includes features that call a language model, treat the model and its settings as environment configuration too. Staging and production may point at different model versions, so record which one each run used, or a change in results will look like a code regression.

Data that doesn't tie assertions to one environment

Dev usually has rich, controllable seed data, staging may have an older sanitised copy, and production has real data you mustn't touch. Assertions written against specific IDs or counts pass in one and fail in the others.

Assert on shape and rules, not incidental values: every item has an integer id and a non-empty name, totals match the sum of line items. When a test needs a specific record, it creates one:

import uuid

import pytest


@pytest.fixture
def temp_user(api_client):
    response = api_client.post("/users", json={"name": f"suite-{uuid.uuid4().hex[:8]}", "role": "tester"})
    response.raise_for_status()
    user_id = response.json()["id"]
    yield user_id
    api_client.delete(f"/users/{user_id}")

Mark tests using this fixture destructive so they never run in production. Unique names per run keep parallel workers from colliding, which matters once you run the suite with pytest-xdist. Keeping local data close to staging is its own topic, covered in keeping a local test environment in sync with staging.

The idea behind all of this is simple: test code describes what the API should do, and the environment supplies everything else. If you want to build a suite like that with Behave or Cucumber and Copilot, my API testing courses walk through it.