Structuring API Test Teardown So It Actually Runs
Most API test suites have teardown. Fewer have teardown that runs when it's needed most: after a failure. The classic version is a cleanup call at the bottom of a test. The test creates a user, makes some assertions and deletes the user. When an assertion fails, the delete never happens, the user stays behind, and the next run fails with a 409 Conflict that has nothing to do with the original bug.
Dirty state like this is one of the most common causes of suites that get flakier over time. Every failed run leaves a little more debris, and eventually tests fail because of what earlier runs left behind rather than anything in the code.
The same problem now shows up in a new place. When an AI agent with tool access creates real resources during an evaluation or an agent-driven test run, it leaves debris too, and it won't clean up after itself unless the harness makes it. In this article I'll cover the teardown patterns I rely on in pytest and Behave, the defensive habits that keep cleanup reliable, and how to apply them to agent runs.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Why cleanup at the end of a test doesn't run
A failing assert raises an exception. Everything after it in the test function is skipped. So any cleanup written as ordinary code at the end of the test only runs when the test passes, which is exactly when you need it least:
def test_deactivate_user(api, api_base_url):
user = api.post(f"{api_base_url}/users", json={"email": "qa@example.test"}).json()
response = api.post(f"{api_base_url}/users/{user['id']}/deactivate")
assert response.status_code == 200 # if this fails...
api.delete(f"{api_base_url}/users/{user['id']}") # ...this never runs
A try/finally block fixes it for one test, but repeating it in every test is noisy and easy to forget. Test frameworks give you better places to put cleanup.
Yield fixtures in pytest
In pytest, code after yield in a fixture runs when the test finishes, whether it passed, failed or errored:
import uuid
import pytest
@pytest.fixture
def user(api, api_base_url):
email = f"qa-{uuid.uuid4().hex[:10]}@example.test"
created = api.post(f"{api_base_url}/users", json={"email": email})
assert created.status_code == 201, created.text
user = created.json()
yield user
response = api.delete(f"{api_base_url}/users/{user['id']}")
assert response.status_code in (204, 404), f"cleanup failed: {response.status_code}"
def test_deactivate_user(api, api_base_url, user):
response = api.post(f"{api_base_url}/users/{user['id']}/deactivate")
assert response.status_code == 200
There's one gap to know about: if the fixture raises before it reaches yield, its teardown doesn't run. If setup creates several resources in sequence and the third creation fails, the first two are left behind. Two ways to close that gap:
- Use a factory fixture that appends each resource to a list the moment it's created, and cleans up the list after
yield. - Register cleanup with
request.addfinalizerimmediately after each creation succeeds. Finalizers registered before the failure still run.
@pytest.fixture
def order_with_customer(request, api, api_base_url):
customer = api.post(f"{api_base_url}/customers", json={"name": "QA"}).json()
request.addfinalizer(lambda: api.delete(f"{api_base_url}/customers/{customer['id']}"))
order = api.post(f"{api_base_url}/orders", json={"customer_id": customer["id"]}).json()
request.addfinalizer(lambda: api.delete(f"{api_base_url}/orders/{order['id']}"))
return order
Finalizers run in reverse order of registration, so the order is deleted before the customer it depends on. I go into fixture design more broadly in pytest fixtures for API testing beyond the basics.
Cleanup hooks in Behave
In Behave, after_scenario in environment.py runs after every scenario, including failed ones. The pattern I use is to record created resources on context as steps create them, and delete them in the hook:
# features/environment.py
def before_scenario(context, scenario):
context.created = []
def after_scenario(context, scenario):
for kind, resource_id in reversed(context.created):
try:
context.api.delete(f"/{kind}/{resource_id}")
except Exception as exc:
print(f"cleanup failed for {kind}/{resource_id}: {exc}")
Each step that creates something appends ("users", user_id) straight after the create call. The try around each delete keeps one failed cleanup from stopping the rest. Behave also offers context.add_cleanup, which registers a cleanup function on the current scenario and keeps it next to the creation code.
Defensive habits that keep teardown reliable
- Make cleanup idempotent. Treat a 404 on delete as success. The test itself may already have deleted the resource.
- Don't let cleanup hide the real failure. A cleanup error should be reported, but it shouldn't replace the test's own failure message.
- Use a recognisable prefix. Names like
qa-plus a unique id make leftover data easy to find. - Sweep as a backstop. A scheduled job, or a session-start step, that deletes old
qa-resources catches whatever a crashed run left behind. It's a safety net, not a replacement for per-test cleanup. - Prefer isolation where you can. A dedicated tenant or a disposable environment per run makes teardown less critical. See how much test data isolation is actually enough.
Teardown for agents that create real resources
More teams now run AI agents against real APIs: evaluation runs that check whether an agent can complete a task with its tools, or agent-driven exploratory testing against staging. An agent that creates orders, tickets or users during those runs leaves exactly the same debris as a failing test, often more, because agents retry, explore and abandon tasks halfway.
The fix is the same principle: cleanup belongs to the harness, not to the actor. I don't rely on the agent to delete what it created. Instead:
- The tool layer records every resource the agent creates, with its id, as a side effect of the create call.
- The harness deletes those resources after each run, in reverse order, whatever the outcome.
- Agent credentials are scoped to a test tenant or sandbox, so anything missed stays contained and the sweep job can find it.
class RecordingTools:
def __init__(self, api):
self.api = api
self.created = []
def create_ticket(self, title, body):
ticket = self.api.post("/tickets", json={"title": title, "body": body}).json()
self.created.append(("tickets", ticket["id"]))
return {"id": ticket["id"], "status": "created"}
def cleanup(self):
for kind, resource_id in reversed(self.created):
self.api.delete(f"/{kind}/{resource_id}")
Wrap each agent run in a pytest fixture that yields a fresh RecordingTools and calls cleanup() after yield, and agent runs get the same guarantee as ordinary tests. The created list is also useful evidence: it shows what the agent actually did, not what it said it did.
The same applies when a coding agent writes your tests. Agents often put cleanup at the end of the test body because that reads naturally. A line in your repository instructions file, such as "create server data only through fixtures that clean up after yield; never put cleanup at the end of a test", prevents the pattern before it reaches review.
Cleanup is part of the test
Teardown that only runs on success isn't teardown. Put it in fixtures and hooks, register it as soon as something is created, make it idempotent and keep a sweep as a backstop. Then apply the same rules to agents with real tool access. If you want to build API suites that stay clean run after run, in Python with Behave or Node with Cucumber, my API testing courses walk through it with VS Code and GitHub Copilot.