AUTOMATION FRAMEWORKS

API Tests That Catch Order-of-Operations Bugs, Agents Too

Order-of-operations bugs are some of the hardest API failures to spot. Every endpoint returns 200, every field is present, every type is right, and the system still breaks because something happened in the wrong sequence. A payment captured before the order was confirmed. An account activated before email verification finished. A resource deleted while another process still pointed at it. Each call looked fine on its own. The sequence was the bug.

Most suites are organised around endpoints, not workflows. One test per route proves a thing can happen, not that it happens at the right time and in the right state. That gap only shows up when real users walk through a full journey, which is why these bugs so often "can't be reproduced" in testing.

Sequence now matters in a second place too. If your product includes an AI agent that calls your API through tools, the agent decides the order, and it can get it wrong in ways no endpoint test will catch. In this article I'll show how I make sequence explicit in pytest and Behave, how I keep test state from hiding these bugs, and how I apply the same thinking to an agent's tool calls.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Make the sequence explicit in the test

The first habit is keeping the order of calls visible in the test itself, not buried in a fixture or implied by file order. When the sequence is explicit, a failure tells you exactly which step went wrong.

def test_checkout_after_adding_item(client, api_base_url):
    # 1. Create a cart
    cart = client.post(f"{api_base_url}/carts", timeout=10)
    assert cart.status_code == 201, cart.text
    cart_id = cart.json()["id"]

    # 2. Add an item (must happen before checkout)
    item = client.post(f"{api_base_url}/carts/{cart_id}/items",
                       json={"sku": "WIDGET-42", "qty": 1}, timeout=10)
    assert item.status_code == 200, item.text

    # 3. Checkout (only valid once the cart has an item)
    checkout = client.post(f"{api_base_url}/carts/{cart_id}/checkout", timeout=10)
    assert checkout.status_code == 200, checkout.text
    assert checkout.json()["status"] == "confirmed"

The numbered comments aren't decoration. They state the business rule: the order matters. The more valuable test, though, is the one that does things in the wrong order on purpose:

def test_checkout_rejected_on_empty_cart(client, api_base_url):
    cart_id = client.post(f"{api_base_url}/carts", timeout=10).json()["id"]

    # Skip adding an item and go straight to checkout
    checkout = client.post(f"{api_base_url}/carts/{cart_id}/checkout", timeout=10)
    assert checkout.status_code == 422, checkout.text

Use whatever status your API documents for this case; the point is to assert that the API enforces the precondition. If it lets you check out an empty cart, you've found an order-of-operations bug before a user did. For every workflow I test, I list the steps and ask: what happens if this one is skipped, repeated or done early? Each answer that matters becomes a negative test.

Assert intermediate state in Behave

Gherkin's Given/When/Then maps nicely onto a workflow. The discipline is checking state between steps, not only at the end. If you only check the final outcome, a bug in step two can be masked by a forgiving step three.

Feature: Order fulfilment sequence

  Scenario: Payment is not captured when the warehouse rejects an order
    Given a customer has a pending order with an authorized payment
    When the warehouse rejects the order
    Then the order status is "rejected"
    And the payment status is still "authorized"
# features/steps/order_steps.py
from behave import given, when, then


@given("a customer has a pending order with an authorized payment")
def step_pending_order(context):
    resp = context.session.post(f"{context.base_url}/orders",
                                json={"customer_id": "test-user"}, timeout=10)
    assert resp.status_code == 201, resp.text
    context.order_id = resp.json()["id"]
    assert resp.json()["payment"]["status"] == "authorized"


@when("the warehouse rejects the order")
def step_reject(context):
    context.response = context.session.post(
        f"{context.base_url}/orders/{context.order_id}/reject",
        json={"reason": "out_of_stock"}, timeout=10)


@then('the order status is "rejected"')
def step_rejected(context):
    assert context.response.status_code == 200, context.response.text
    assert context.response.json()["status"] == "rejected"


@then('the payment status is still "authorized"')
def step_payment_untouched(context):
    resp = context.session.get(
        f"{context.base_url}/orders/{context.order_id}/payment", timeout=10)
    status = resp.json()["status"]
    assert status == "authorized", (
        f"Payment is '{status}' on a rejected order: captured out of sequence?")

The Given step asserts the starting state, so a broken precondition fails there instead of producing a confusing failure later. The last step re-reads the payment from the API rather than trusting the earlier response. And the failure message says what probably happened. In CI, that saves a lot of digging.

Don't let test state hide the bug

Test suites create their own sequencing bugs. A test passes because an earlier test left state behind, and execution order becomes a hidden dependency. Run the suite in a different order or in parallel and the failures look random.

Each sequencing test should own its state from creation to cleanup. A yield fixture does that, because the teardown runs whether the test passes or fails:

import pytest


@pytest.fixture
def fresh_cart(client, api_base_url):
    cart_id = client.post(f"{api_base_url}/carts", timeout=10).json()["id"]
    yield cart_id
    client.delete(f"{api_base_url}/carts/{cart_id}", timeout=10)


def test_cannot_update_item_never_added(client, api_base_url, fresh_cart):
    resp = client.patch(f"{api_base_url}/carts/{fresh_cart}/items/WIDGET-42",
                        json={"qty": 5}, timeout=10)
    assert resp.status_code == 404, (
        f"Updating an item that was never added returned {resp.status_code}")

If a resource that "shouldn't exist yet" already exists because another test left it, the bug you're looking for disappears. There's more on this in structuring API test teardown so it actually runs.

When an agent decides the order

Agents add sequencing risk in two places.

Coding agents refactoring your workflow code. An agent asked to tidy an order service might move the payment capture above the confirmation check because the code reads more cleanly that way. Every endpoint test still passes. Only a negative sequence test like the ones above fails. That's a strong reason to have them, and to tell the agent in your instructions file (.github/copilot-instructions.md for Copilot) that workflow tests in tests/workflows/ must pass and must not be rewritten to match new behaviour.

AI agents in your product calling your API. If an assistant can call tools such as confirm_order and capture_payment, the model chooses the order at runtime. Your API should enforce preconditions regardless, but you also want to know how often the agent tries the wrong sequence. I record the agent's tool calls during a test run and assert on the trace:

def first_index(calls, name):
    return next((i for i, c in enumerate(calls) if c["name"] == name), None)


def test_agent_confirms_before_capturing(run_agent, order_scenarios):
    bad_runs = []
    for scenario in order_scenarios:
        calls = run_agent(scenario)  # list of {"name": ..., "args": ...} in call order
        confirm = first_index(calls, "confirm_order")
        capture = first_index(calls, "capture_payment")
        if capture is not None and (confirm is None or capture < confirm):
            bad_runs.append((scenario, [c["name"] for c in calls]))
    assert not bad_runs, bad_runs

run_agent is a fixture you write around your own agent loop, so this doesn't depend on any vendor SDK. Because model output varies, I run each scenario several times and report the pass rate as well as failing outright on any violation of a hard rule like this one. A rule that touches money should hold on every run; softer preferences can be judged by rate.

Think in journeys

Sequencing tests are integration tests by nature, so they belong after the fast unit and contract checks, but they should still gate merges when they touch money or accounts. Tests built around real user journeys catch these bugs naturally, because they follow the order a user actually takes. I go further into that in structuring API tests around user journeys, not endpoints.

Endpoint-by-endpoint testing will always miss the gaps between steps. Write down the order the business expects, test the wrong orders on purpose, and hold agents to the same rules. If you want to build workflow tests like these with pytest or Behave, VS Code and GitHub Copilot, my API testing courses walk through it.