AI-POWERED TESTING

API Tests That Document Business Rules for Humans and Agents

Most API test suites I see do a decent job of asserting status codes and response shapes. What they rarely do is say why an assertion exists. Someone new reads assert response.json()["discount"] == 0 and can't tell whether that zero is a quirk of the fixture data or a hard rule like "guests never receive loyalty discounts". That difference matters a lot when the rule changes.

It matters even more when a coding agent is editing the suite. An agent sees a failing assertion and a value, not a decision the business made. If the test doesn't state the rule, the agent has no way to know that "fixing" the test by updating the expected value is wrong. A test that reads like a specification is something a product manager can follow, a developer can trust and an agent can extend without quietly breaking a rule nobody told it about.

In this article I'll walk through how I name and write API tests so they document business rules, how I use AI assistants to pull rules out of acceptance criteria before any code exists, and how I keep these tests visible in CI and protected from well-meaning agent edits.

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

Name tests after the rule, not the HTTP mechanics

The cheapest improvement is naming. Compare:

# Describes the mechanics
def test_post_order_returns_422(): ...

# Describes the rule
def test_order_below_minimum_spend_is_rejected(): ...

When the second one fails in CI, you know a business constraint broke, not just that a 422 stopped appearing. AI assistants default to mechanics-first names because they pattern-match on code, not on your requirements, so I ask for rule-based names explicitly and put that convention in the repository's instructions file.

Assertion messages do the same job at a finer grain. Python's assert takes a second argument, and I use it to state the rule:

assert data["discount"] == 0, (
    "Rule: unauthenticated users are not eligible for loyalty discounts"
)

Now the failure message is a statement of the rule rather than a bare value mismatch. For anything non-obvious, I add a plain-English summary or a ticket reference. It takes seconds and saves a lot of digging later.

I also group tests by the business concept they protect. tests/pricing_rules/ tells a much clearer story than tests/api/v2/orders/, and when I point an agent at that folder to add a new pricing case, it picks up the conventions from its neighbours. Whether those rules belong in Gherkin or in plain pytest depends on who reads them, which I cover in when to use BDD vs plain pytest for API tests.

Extract the rules before generating any code

The most useful AI workflow I have for this is a two-step one. First, give the assistant the acceptance criteria and ask only for rules:

Acceptance criteria:
"A user can apply a promo code at checkout. Promo codes expire after their end date.
 A promo code cannot be applied more than once per account. Expired or already-used
 codes return an error message, not a discount."

List every distinct business rule as a numbered, testable statement.
Include the rejection case for each rule. Do not write any code yet.

This usually separates things you'd lumped together, such as "expired" and "already used" being two error paths, not one. Review that list with whoever owns the behaviour. That review is the important human gate: once the rules are right, generating the tests is mechanical.

Then ask for one test per rule, with the rule as the name and docstring:

import pytest


@pytest.mark.business_rule
def test_promo_code_cannot_be_applied_twice_to_same_account(client, api_base_url,
                                                           account_with_promo):
    """Rule: a promo code is single-use per account.
    A second application must be rejected with 409 and no discount applied."""
    url = f"{api_base_url}/checkout/promo"
    body = {"code": account_with_promo.code}

    first = client.post(url, json=body, headers=account_with_promo.headers, timeout=10)
    assert first.status_code == 200, first.text

    second = client.post(url, json=body, headers=account_with_promo.headers, timeout=10)
    assert second.status_code == 409, (
        f"Rule: promo codes are single-use per account. Got {second.status_code}: {second.text}")
    assert second.json().get("discount") in (None, 0), second.text

The docstring is the specification. If the test needs to change, it's the first thing the next engineer, or the next agent, should read.

One rule per test. Agents like to produce one long test that exercises several rules in sequence, which is quick to generate and useless as documentation: when it fails, you don't know which rule broke.

Check that the test can actually fail

The most common weakness I see in AI-generated rule tests is a test that only covers the happy side of a rule and never exercises the rejection. It passes, it looks thorough, and it protects nothing. I go through these failure modes in where AI-generated tests get API testing wrong.

A follow-up question I ask after any generated test: "What would have to be true in the API for this test to pass while the rule is broken?" If the answer describes a realistic scenario, the test needs another assertion or a separate negative test. When I can, I go one step further and break the rule on purpose, for example by pointing the test at a stub that allows double redemption, and confirm it goes red.

Protect rule tests from "fixes"

Here's the agent-specific risk. A pricing change lands, a rule test fails, and an agent asked to get CI green updates the expected value. If the business actually changed the rule, that's fine. If the change was a bug, the agent just rewrote the specification to match it. The agent can't tell the difference. That judgement has to stay with a person.

So I write it down for the agent. In .github/copilot-instructions.md, or your agent's equivalent:

## Business rule tests (marked business_rule)
- These encode decisions made by product, not implementation details.
- Never change an expected value, status code or rule docstring to make one pass.
- If one fails, stop and report which rule failed and what the API returned.
- New rules come from acceptance criteria in the ticket, one test per rule.

I also put the rule-test folders under CODEOWNERS, so changes to them always reach a human reviewer.

Keep them visible in CI

Register the marker and give these tests their own step, so a rule failure doesn't drown among hundreds of other results:

# pytest.ini
[pytest]
markers =
    business_rule: encodes a product decision; changes need product sign-off

# CI step
pytest -m business_rule -v

Business rules change on a different cadence from technical contracts. When product changes a pricing rule, you want to run exactly those tests, see which need updating, and update them deliberately. Setting up tags early is much easier than retrofitting them, as I describe in tagging API tests so CI can run the right subset.

Failure output matters too. A failure that states the rule, the status and the body is readable by a person and gives an AI assistant real context if you ask it to help diagnose. A one-line value mismatch gives either of them very little to work with.

When a rule changes, update the docstring and assertion message to describe the new rule, not just the new value. AI tools draft those updates well if you give them the old rule, the new rule and the existing test. What they won't do is notice on their own that a rule changed. That part is still yours. If you want to build a suite with this kind of discipline from the start, my API testing courses use pytest or Behave with VS Code and GitHub Copilot.