Sub topic 8
Run the code: tests that expose wrong API usage
This chapter assumes you can write and run pytest tests, read a traceback, and use pip. Earlier chapters showed how to check that a symbol exists and how to surface deprecation warnings. Those checks are static. A test goes further because it runs the generated code against the library you have installed.
Why running the code matters
Generated code often reads as plausible. A call such as requests.get_json(...) looks fine in a diff, but it fails the first time the line executes. Existence checks and type checkers catch many of these cases. They miss others:
- A function exists but the generated code passes arguments the installed version rejects.
- A call succeeds but returns a different type than the code assumes, such as a
Responsewhere the code expects a dict. - A code path sits behind a branch that no one executes during review.
A test forces each of these paths to run. An AttributeError or TypeError then appears in your test report instead of in production.
Write a test that calls the real library
The most common mistake is to mock the library call. If you replace requests.get with a MagicMock, the mock accepts any attribute and any arguments. A mock will also accept requests.get_json, so the test passes while the code is wrong.
Consider a generated helper:
import requests
def fetch_items(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()["items"]You can test the helper without a network by serving a response through a real requests session adapter. The responses package does this. It patches the transport layer, so requests still validates the call.
import pytest
import responses
from items import fetch_items
@responses.activate
def test_fetch_items_returns_list():
responses.add(
responses.GET,
"https://example.com/api",
json={"items": [1, 2, 3]},
status=200,
)
assert fetch_items("https://example.com/api") == [1, 2, 3]
@responses.activate
def test_fetch_items_raises_on_error():
responses.add(responses.GET, "https://example.com/api", status=500)
with pytest.raises(Exception):
fetch_items("https://example.com/api")If the generated code had called requests.get_json, the first test would fail with AttributeError. The code runs through the real requests module, so the invented name cannot hide.
Use autospec when you must mock
Sometimes you need a mock, for example to avoid a payment call. Use create_autospec or patch(..., autospec=True). An autospecced mock copies the real signature, so a wrong call raises TypeError and a missing attribute raises AttributeError.
import json
from unittest.mock import create_autospec
fake_dumps = create_autospec(json.dumps, return_value="{}")
fake_dumps({"a": 1}, indent=2) # accepted: indent is a real parameter
try:
fake_dumps({"a": 1}, pretty=True) # not a real parameter
except TypeError as exc:
print("Caught:", exc)The second call fails because json.dumps has no pretty parameter. A plain MagicMock would have accepted it.
Make outdated usage fail
A test can also fail on deprecated calls. Add a filter to your test configuration so any DeprecationWarning raised during a test becomes an error. In pytest.ini:
[pytest]
filterwarnings =
error::DeprecationWarningOr pass the flag for a single run:
python -W error::DeprecationWarning -m pytestWith this setting, a generated call to datetime.utcnow() on Python 3.12 or later fails the test that reaches it. Without it, the warning scrolls past and the test passes.
Cover the paths the assistant added
Generated changes often add branches, such as error handling or a retry. Review the diff and ask which new lines no test executes. A coverage report answers this:
python -m pytest --cov=items --cov-report=term-missingThe Missing column lists line numbers that never ran. An unexecuted line is unverified, so its API calls may be invented. Write a test that reaches it, or inspect the calls by hand using the checks from earlier chapters.
Limits of this approach
A passing test shows that the code works for the inputs you chose. It does not show that the code handles every case, and it can't tell you the library behavior is what you intended. If the test asserts what the generated code already returns, it can encode a wrong assumption. Write the expected value from the documentation, not from the output you saw.
Exercise
A generated function calls session.fetch_json(url) on a requests.Session. Your test replaces the session with MagicMock() and passes. Why is the test unreliable, and what two changes would make it catch the problem?
Show answer
MagicMock creates any attribute on demand, so fetch_json "exists" on the mock even though requests.Session has no such method. Replace the mock with create_autospec(requests.Session, instance=True), which raises AttributeError for the invented name, or use a transport-level fake such as responses so the real Session runs.
Exercise
Your suite passes on Python 3.12, yet the generated code calls datetime.utcnow(). What setting makes the suite fail, and where can you set it?
Show answer
Turn DeprecationWarning into an error. Set filterwarnings = error::DeprecationWarning in pytest.ini, or run python -W error::DeprecationWarning -m pytest.