Sub topic 8
Run the code: tests that expose wrong API usage
Reading generated code tells you whether it looks right. Running it tells you whether it works. This chapter covers how to write tests that make invented functions, wrong signatures, and removed behavior fail quickly and visibly.
You should know how to write pytest tests, how unittest.mock.patch works at a basic level, and how to read a Python traceback. The examples use Python 3.12 or later, pytest, requests, and pandas 2.x.
Why running beats reading
A reviewer can miss requests.get_json(url), because the name looks plausible. Python does not miss it. The interpreter raises AttributeError the moment that line executes. The same is true of a wrong keyword argument (TypeError) or a removed method.
The catch is that Python only checks a name when the line runs. A call inside a branch that no test reaches is never checked. So the first goal of a verification test is to execute every line the model wrote.
Errors in AI-generated code surface at different times and need different tests:
| Problem | When Python reports it | What your test must do |
|---|---|---|
| Invented module-level import | Import time | Import the module |
| Invented function or method | When the line runs | Reach the line |
| Wrong keyword argument or arity | When the call runs | Call the real function, or a signature-checked mock |
| Removed method on an object | When the line runs | Build a real object of the right type |
| Changed return type or semantics | Never, unless you assert on it | Assert on the actual output |
Start with a plain smoke test
The cheapest check calls the function with realistic input and asserts something about the result. Suppose an assistant wrote this helper:
# report.py
import json
def to_report(data):
return json.dumps(data, pretty=True)Nothing in this file is a syntax error, and many readers would accept pretty=True. This test exposes it:
# test_report.py
from report import to_report
def test_to_report_contains_key():
assert '"a"' in to_report({"a": 1})Running pytest fails with a TypeError that names the unexpected keyword argument pretty. The real json.dumps accepts indent, not pretty. No mock was needed, because the function has no external dependencies, so the real library does the checking.
When a function can run for real in a test, let it. Every mock you add is a place where an invented API can hide.
Why plain mocks hide invented APIs
Code that talks to a network, a database, or a cloud service usually needs a mock. A default MagicMock accepts any attribute and any call. That is the opposite of what you want here.
Here is a function with an invented call:
# fetch_bad.py
import requests
def fetch_user(user_id):
return requests.get_json(f"https://example.com/api/users/{user_id}")A test written in the usual quick way passes:
# test_fetch_bad.py
from unittest import mock
import fetch_bad
def test_passes_even_though_the_api_is_invented():
with mock.patch("fetch_bad.requests") as fake_requests:
fake_requests.get_json.return_value = {"id": 7}
assert fetch_bad.fetch_user(7) == {"id": 7}The test replaces the entire requests module with a MagicMock. The mock invents get_json on demand, so the test confirms the model's mistake instead of catching it. This is the most common way AI-generated code ships with a bad API call: the assistant wrote the code and the test from the same wrong belief.
Use autospec so mocks follow the real API
autospec builds a mock from the real object. The mock has the same attributes and the same call signatures. Calling a method that does not exist raises AttributeError, and calling with a bad argument list raises TypeError.
Here is the corrected function and a test that holds it to the real requests API:
# fetch.py
import requests
def fetch_user(user_id):
response = requests.get(
f"https://example.com/api/users/{user_id}", timeout=10
)
response.raise_for_status()
return response.json()# test_fetch.py
from unittest import mock
import requests
import fetch
def test_fetch_user_returns_decoded_body():
fake_response = mock.create_autospec(requests.Response, instance=True)
fake_response.status_code = 200
fake_response.json.return_value = {"id": 7}
with mock.patch(
"fetch.requests.get", autospec=True, return_value=fake_response
) as get:
result = fetch.fetch_user(7)
assert result == {"id": 7}
get.assert_called_once_with("https://example.com/api/users/7", timeout=10)Three things make this test strict:
mock.patch("fetch.requests.get", autospec=True)replaces only thegetfunction. The rest ofrequestsstays real, sorequests.get_jsonwould still raiseAttributeError. The patch also checks the signature ofget.create_autospec(requests.Response, instance=True)gives a response object that has only the methods of the realResponseclass. A call such asresponse.jsn()fails.assert_called_once_withpins the exact arguments, includingtimeout, so a dropped or renamed argument shows up.
Run the original fetch_bad.py against this test by importing it as fetch and the test fails with AttributeError: module 'requests' has no attribute 'get_json'. That failure is the signal you want.
Assert on behavior that does not raise
Some outdated usage never raises an exception. It returns something slightly different. Only an assertion on the real output can catch it.
A common case is timestamps. An assistant trained on older code often writes datetime.utcnow(). It still works in Python 3.12 but is deprecated, and it returns a naive datetime with no timezone attached. A test can pin the property you actually care about:
# clock.py
from datetime import datetime, timezone
def utc_timestamp():
return datetime.now(timezone.utc)# test_clock.py
from datetime import timedelta
from clock import utc_timestamp
def test_timestamp_is_timezone_aware_utc():
stamp = utc_timestamp()
assert stamp.tzinfo is not None
assert stamp.utcoffset() == timedelta(0)If the code had used utcnow(), tzinfo would be None and the first assertion would fail. The test states the requirement, not the function name, so it keeps working if someone later swaps the implementation.
Removed APIs are easier because they raise. This old pandas pattern fails on pandas 2.0 and later:
# frames.py
import pandas as pd
def build_frame(rows):
df = pd.DataFrame()
for row in rows:
df = df.append(row, ignore_index=True)
return df# test_frames.py
from frames import build_frame
def test_build_frame_has_one_row_per_input():
df = build_frame([{"id": 1}, {"id": 2}])
assert len(df) == 2
assert list(df["id"]) == [1, 2]On pandas 2.x the test fails with an AttributeError saying the DataFrame has no attribute append. The fix is pd.DataFrame(rows), and the same test then passes unchanged. That unchanged test is the point: it describes the result you want, so it works as a regression check while you repair the code.
Cover every branch the model wrote
An invented call inside an error handler or a rarely used option is only found if a test reaches it. Assistants often add retry logic, fallbacks, and cleanup paths that nobody exercises. Measure what your tests execute:
python -m pip install pytest pytest-cov
python -m pytest --cov=. --cov-branch --cov-report=term-missingThe Missing column lists line numbers that never ran. Treat each one in generated code as unverified. Either write a test that reaches it, or ask whether the model needed that branch at all.
For error paths, make the mock raise:
# test_fetch_errors.py
from unittest import mock
import pytest
import requests
import fetch
def test_http_error_propagates():
fake_response = mock.create_autospec(requests.Response, instance=True)
fake_response.raise_for_status.side_effect = requests.HTTPError("404")
with mock.patch("fetch.requests.get", autospec=True, return_value=fake_response):
with pytest.raises(requests.HTTPError):
fetch.fetch_user(404)Here requests.HTTPError is the real exception class. If generated code had caught requests.HttpError, which does not exist, the except clause would raise AttributeError only when an exception actually occurred. Without an error-path test, that bug would wait for a production incident.
Combine tests with warning filters
Many outdated calls still work and only emit a DeprecationWarning. Pytest shows these in its summary but does not fail on them. Promote them to errors for the run, as the deprecation chapter describes:
python -W error::DeprecationWarning -m pytestWith that flag, datetime.utcnow() fails the test on Python 3.12 or later. Your tests then catch both removed APIs, which raise already, and deprecated ones, which warn.
Common mistakes
- Letting the model write code and tests from one prompt. Both can share the same wrong assumption. Review the test's mocks first, and prefer real objects.
- Patching the wrong name. Patch where the code looks the name up, such as
fetch.requests.get, not somewhere unrelated. If the patch target is wrong, the real network call may run. - Asserting only that something was called.
get.assert_called()passes with any arguments. Useassert_called_once_withor checkcall_args. - Using
MagicMockreturn values as results. If the function under test returns a mock, an assertion likeassert resultpasses. Assert on concrete values. - Testing against the wrong version. A test that passes in your local environment may fail in CI if the installed versions differ. Pin versions as covered earlier in this tutorial.
A repeatable routine
For each AI-generated change that touches a library:
- Run the new function with real inputs wherever that is safe.
- For external services, mock with
autospec=Trueandcreate_autospec, never a bareMagicMockof a whole module. - Assert on values, types, and properties such as timezone awareness, not just that no exception occurred.
- Check coverage and write tests for every branch the model added.
- Run the suite with deprecation warnings as errors.
Exercise
A teammate's test for a function that calls boto3.client("s3").upload_filee(...) (note the typo) uses mock.patch("app.boto3") and passes. Explain why it passes, and describe a change that would make it fail.
Show answer
Patching app.boto3 replaces the whole module with a MagicMock. A MagicMock returns another mock for any attribute, so client("s3").upload_filee(...) succeeds regardless of the typo. To catch it, patch with an autospec built from the real object, for example mock.patch("app.boto3.client", autospec=True) and also build the returned client with mock.create_autospec of a real client class, or use a stub from a library such as botocore's Stubber or moto. Then calling a nonexistent method raises AttributeError and the test fails.
Exercise
A generated function uses datetime.utcnow() and a test only checks that it returns a datetime. The test passes on Python 3.12 with no failures. Name two changes that would make the problem visible.
Show answer
First, assert on the behavior you need, for example assert result.tzinfo is not None, which fails for the naive value utcnow() returns. Second, run the suite with python -W error::DeprecationWarning -m pytest, which turns the deprecation warning on Python 3.12 or later into an error.