Debug a failing pytest test with an AI coding agent
When a Python test fails inside a loop over hundreds of records, the traceback tells you where execution stopped, not which input caused it. Mercury CLI ships a built-in Debug tool speaking the Debug Adapter Protocol (DAP) and a Test tool whose debug operation launches a failing pytest or unittest test directly under the bundled debugpy adapter.
This walkthrough uses a small order ledger in Python where one daily-report test fails out of twelve tests. The example is a public repository anyone can clone: ledger-debug-demo.
The failing test and example code
The ledger reads 2,000 orders from data/orders.ndjson, computes each order's discounted subtotal and shipping cost, and totals revenue for a given day. Under python/:
python/ledger/parse.py:
import json
from pathlib import Path
def parse_override(value):
if value is None or value == "":
return None
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, str):
trimmed = value.strip()
if trimmed.isdigit():
return int(trimmed)
return trimmed.strip("\"'")
return None
python/ledger/shipping.py:
def shipping_cost(order):
override = order["shipping_override"]
if override == "waived":
return 0
if override is not None:
return override
return table_rate(order["region"], order["weight_grams"])
python/ledger/total.py:
from .pricing import discounted_subtotal
from .shipping import shipping_cost
def order_total(order):
subtotal = discounted_subtotal(order)
shipping = shipping_cost(order)
return subtotal + shipping
python/ledger/report.py:
from .total import order_total
def daily_report(orders, date):
day_orders = [order for order in orders if order["date"] == date]
revenue_pence = 0
for order in day_orders:
revenue_pence += order_total(order)
return {
"date": date,
"order_count": len(day_orders),
"revenue_pence": revenue_pence,
}
The failing test in python/tests/test_ledger.py asks for the report of one day, 19 October, and expects 67 orders and a revenue of 656094 pence.
Running the suite from the repository root (or python3 -m unittest inside python/) shows 11 passing tests and 1 error (the test's name line and path prefix are left out here):
python3 -m unittest discover -s python/tests -t python
........E...
======================================================================
Traceback (most recent call last):
File "python/ledger/ledger.py", line 14, in report_for_date
return daily_report(orders, date)
File "python/ledger/report.py", line 8, in daily_report
revenue_pence += order_total(order)
~~~~~~~~~~~^^^^^^^
File "python/ledger/total.py", line 8, in order_total
return subtotal + shipping
~~~~~~~~~^~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'
----------------------------------------------------------------------
Ran 12 tests in 0.021s
FAILED (errors=1)
Running pytest inside python/ collects the same 12 tests and fails on the same TypeError at ledger/total.py:8.
What guessing from the traceback gets wrong
The traceback stops at return subtotal + shipping on line 8 of python/ledger/total.py with TypeError: unsupported operand type(s) for +: 'int' and 'str'. It does not show which of that day's 67 orders failed, what string shipping contains, or how a string reached order_total.
The other 11 tests, including the unit tests for parse_override and shipping_cost, all pass. Guessing from the traceback often leads to casting int(shipping) inside order_total or patching shipping_cost. That masks the bad value instead of finding why a string arrived there.
Debug the failing test in Mercury
Clone the repository (git clone https://github.com/Whq02/ledger-debug-demo), open its python/ folder in your terminal, start mercury, and ask it to debug the failure:
One test fails. Find out why with the debugger and fix the cause.
The model picks its own steps, so the order in your run can differ. These are the calls that find the cause.
1. Launch the failing test under debugpy
The agent runs the suite with Test (run) to record the failing test, then calls Test debug for that test. Mercury asks permission for the launch, starts the test under the bundled debugpy adapter with no launch configuration written and no runner arguments reconstructed by hand, and pauses before the test body runs, ready for breakpoints. The tests in this example are unittest.TestCase classes, so Test runs them with unittest; a pytest-style test function goes the same way under pytest.
2. Set a conditional breakpoint and continue
Instead of stepping through every order in the loop, the agent calls Debug breakpoints on ledger/total.py with a condition:
{
"file": "ledger/total.py",
"breakpoints": [
{
"line": 8,
"condition": "not isinstance(shipping, int)"
}
]
}
Then the agent calls Debug continue. Execution runs past every valid order and stops once at ledger/total.py:8 on the offending order.
3. Read the live values
On the stopped frame, the agent calls Debug scopes and variables (or evaluate, which defaults frameId to the top frame of the thread that stopped last). The live locals read:
subtotal = 3750
shipping = '499'
order['id'] = 'ORD-11203'
order['shipping_override'] = '499'
4. Apply the one-line fix
Reading '499' as a string shows the root cause in ledger/parse.py:13. The input record for ORD-11203 has "shippingOverride": "\"499\"". Because trimmed = value.strip() checked trimmed.isdigit() before stripping outer quotes, '"499"' skipped int(trimmed), stripped its quotes on line 16, and returned '499' as a string.
The agent calls Debug disconnect to end the debug session, then makes the one-line fix at ledger/parse.py:13:
trimmed = value.strip().strip("\"'")
5. Rerun the test and the suite
The agent calls Test rerunFailed to check the recorded failure, then Test run to verify the full suite. All 12 tests pass.
Using unittest instead of pytest
The same Test debug workflow works for unittest under debugpy:
python3 -m unittest
Mercury selects between pytest and unittest automatically:
- In a Python project whose tests are plain
test_*.pyfiles with no pytest configuration marker,Testruns them underpytestwhenpytestis importable for the project's interpreter. - Files with a
TestCaseclass orunittest.main(keepunittest. Aunittest.mockimport alone does not selectunittest. - If
pytestis not importable, or ifunittestskips a test file it could not collect, the run reports failed and names the files and remedy. - When a
runorrerunFailedselection matches nothing inpytestorunittest,Testreportsno test matched <selection>: <the runner's own words>with zero counts and ano-matchverdict.
Python runtime and adapter checks
- Mercury vendors
debugpyin the build (with an installed-module fallback) and runs the Python adapter on the bundled CPython 3.14 runtime (vendor/python), so no separate Python installation is required to start the adapter. - Your code under debug runs on the project's interpreter (
MERCURY_PYTHON, the active or project virtual environment, orpython3onPATH) when that interpreter is Python 3.10 or newer; otherwise it runs on the bundled interpreter. launch,attach,continue,next,stepIn,stepOut,pauseandrestartaccepttimeoutMs(default10,000milliseconds; longer waits are allowed). Reaching the deadline reports that the program is still running without terminating it; usestatusto inspect it ordisconnectto end the session.- Run
mercury healthor enter/healthin a session and read theTools withheldrow to confirmDebugis available. SettingMERCURY_DAP=0removesDebugfrom the tool catalogue.