Turning a Failing Test Run Into a Useful Bug Report, With AI
A failing test is only half the job. The other half is turning that red output into something a developer can act on: a bug report with enough context that they don't have to come back with three questions before they can reproduce it. In practice this step is often an afterthought. Copy the traceback, paste it into the tracker, move on. That wastes everyone's time and slowly erodes trust in the suite.
AI assistants make the drafting part fast. Paste a failure into Copilot Chat and you'll get a tidy, well-written report in seconds. The catch is that it reads just as well when it's wrong. An assistant given only a traceback will fill the gaps with plausible guesses about the environment, the reproduction steps and the cause, and a developer can't tell which parts are evidence and which are invention.
So the workflow I use puts the effort where it belongs. The test run captures the evidence automatically, a template gives it structure, and the assistant only drafts from what was captured. Here's how each piece works.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Capture the exchange automatically on failure
For an API test, the most valuable artifact is the request and response pair. A traceback tells you an assertion failed. The exchange tells you why. Rather than relying on someone to grab it by hand, I have pytest save it whenever a test fails.
First, a hook in conftest.py that makes each test's result available to fixtures. This is a standard pattern from the pytest documentation:
import pytest
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, f"rep_{rep.when}", rep)
Then an autouse fixture that writes the last exchange to a file when the test body failed. It assumes your API client fixture, api, keeps a reference to its last response:
from pathlib import Path
ARTIFACTS = Path("artifacts")
SENSITIVE = {"authorization", "cookie", "x-api-key"}
def describe_exchange(response):
req = response.request
headers = {k: "[redacted]" if k.lower() in SENSITIVE else v
for k, v in req.headers.items()}
body = req.body.decode("utf-8", "replace") if isinstance(req.body, bytes) else req.body
return (f"{req.method} {req.url}\nRequest headers: {headers}\n"
f"Request body: {body}\n\n"
f"Status: {response.status_code}\nResponse body: {response.text[:5000]}\n")
@pytest.fixture(autouse=True)
def save_exchange_on_failure(request):
yield
rep = getattr(request.node, "rep_call", None)
if rep is None or not rep.failed or "api" not in request.fixturenames:
return
api = request.getfixturevalue("api")
if api.last_response is not None:
ARTIFACTS.mkdir(exist_ok=True)
name = request.node.nodeid.replace("/", "_").replace("::", "__")
(ARTIFACTS / f"{name}.txt").write_text(describe_exchange(api.last_response))
The redaction matters more than it used to. That file is going into a ticket, and quite possibly into an AI chat, so credentials must never be in it. For Behave, the same idea goes in an after_step hook in environment.py: check step.status.name == "failed" and write out whatever response your steps stored on context. I go deeper into what to log in debugging failed API tests faster with better logging.
Keep the slice tight
Pasting the whole terminal scroll into a report is noise. What belongs there is the failing assertion, the traceback frames in your own code (not deep inside a library), and the exchange file. I run with --tb=short by default for exactly this reason. For Behave, the headline is the scenario title and the failing step: "Then the response status should be 201" failed in "Create order with valid payload" tells a developer what's wrong before they open anything.
Structure the report around evidence
A useful bug report has the same four parts it always has, filled precisely from the run:
- Expected vs actual. Take it straight from the assertion.
assert 404 == 201becomes "Expected: 201 Created. Actual: 404 Not Found." Don't paraphrase it into "the endpoint didn't work." - Steps to reproduce. "Run the suite" isn't a reproduction path. Give the method, URL, headers and body from the exchange file, or a curl command built from them, so a developer can reproduce it without your test framework.
- Environment. Base URL, API version, active feature flags, and the commit SHA of the service under test. In CI, the SHA is usually available as an environment variable. Record it in the run's metadata so it reaches every report.
- Attachments. The exchange file and a link to the CI run.
Put this structure in .github/ISSUE_TEMPLATE/test-failure.md so nobody has to remember it under pressure:
---
name: Test failure
about: A defect found by an automated test
---
## Failing test
## Expected
## Actual
## Reproduction (request from the artifact)
## Environment (base URL, service SHA, flags)
## Evidence (artifact file, CI run link)
## Hypotheses (clearly marked as unconfirmed)
That last section is new in my template. It's the one place guesses are allowed, which keeps them out of the rest. For auth failures specifically, reproducing authentication errors your devs can actually fix covers the extra context those need.
Let the assistant draft, from evidence only
With the artifact and the template in place, an AI assistant does the drafting well. It turns a raw assertion and a JSON body into a clear expected/actual description quickly. I give Copilot Chat (or whichever assistant I'm using) the test source, the assertion output and the exchange file, plus explicit rules:
Draft a bug report using the template in .github/ISSUE_TEMPLATE/test-failure.md.
Use only facts from the test output and the artifact below.
If a section needs information that isn't there, write "UNKNOWN", don't guess.
Put any theory about the cause under Hypotheses, and say what evidence supports it.
Then I check the draft against the artifact before filing it, every time. The things I look for are an invented environment detail, a reproduction step that wasn't in the exchange, and a cause stated as fact. "UNKNOWN" in a draft is a good sign. It means the assistant followed the rules, and it tells me what I still need to find. If you're working out what a failure means in the first place, using AI to explain a test failure you did not write covers that step.
Bug reports for AI features and agent runs
If the failing test exercises an LLM feature or an agent, the usual template isn't enough, because a single failing output doesn't prove much. I add:
- The model identifier and prompt version, alongside the service SHA.
- The pass rate over the runs you made ("failed 4 of 10"), rather than "it failed".
- A few representative failing outputs, and one passing output for contrast.
- For agents, the trace: which tools were called, with what arguments, in what order. Most agent bugs are a wrong tool call, not a wrong final sentence.
Without these, the report reads as "the AI said something odd once", and it will be closed as unreproducible.
Treat report quality like test quality
If a developer comes back with "can't reproduce", the report failed. Work out what was missing and fix the template or the artifact capture, so the next report includes it automatically. Over time, the back-and-forth shrinks and the gap between a red build and a merged fix gets shorter. If you want to build an API suite that produces this kind of evidence from the start, my API testing courses walk through it with Copilot in the loop.