Sub topic 12
Know what these checks will not catch
This chapter assumes you have worked through the earlier chapters. You should be comfortable with introspection (inspect, importlib), type checkers, warning filters, and pytest. Everything so far has been about catching invented and outdated API usage. This chapter covers what still gets through, so you can decide where a human has to look and how much trust a green build deserves.
What the checks have in common
Each check you built answers a narrow question:
- Introspection asks whether a name exists and whether a call fits its signature.
- Documentation review asks whether the documented behavior matches the claim.
- A type checker asks whether the types line up where it can see them.
- Deprecation warnings ask whether the library has flagged this call as old.
- Tests ask whether the executed paths produce the asserted results.
- Dependency verification asks whether a package exists and is the one you intended.
None of these asks whether the code does what you wanted. A change can pass every one of them and still be wrong. The diagram shows the layers and what remains after the last one.
A real symbol can still do the wrong thing
An existence check proves that a name resolves. It says nothing about whether the name does what the author assumed. Models often reach for a real function that sounds right.
A classic case is str.lstrip. It looks like "remove this prefix", but it removes any leading characters that appear in the argument.
name = "test_set_up"
print(name.lstrip("test_")) # up
print(name.removeprefix("test_")) # set_upBoth calls exist. Both accept the argument. Both return a string, so a type checker is satisfied. Only the second does what a reader of the first would assume. removeprefix requires Python 3.9 or later, which is another reason to know your version.
The same pattern shows up with:
subprocess.runwithoutcheck=True, which never raises on a failing command.requests.getwithoutraise_for_status(), which treats a 500 response as a normal result.datetime.strptimewith a format string that parses successfully but swaps day and month.dict.updatewhere the code needed a deep merge.
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "raise SystemExit(3)"])
print(result.returncode) # 3, and no exception was raisedNothing here is invented, deprecated, or mistyped. The defect is in the assumption about behavior, and only a test with an assertion on the outcome, or a reviewer who knows the API, will find it.
Signature checks give wrong answers when `**kwargs` is involved
Earlier you used inspect.signature to confirm that a keyword argument exists. That check has a blind spot. A function that accepts **kwargs takes any keyword, so the parameter is absent from the signature but the call still succeeds.
import inspect
def render(data, **options):
return str(data)
sig = inspect.signature(render)
print("pretty" in sig.parameters) # False
print(render({"a": 1}, pretty=True)) # works, and pretty is ignoredThe check reports "no such parameter", yet the call runs. The opposite error is worse for a reviewer: the model passes pretty=True, the call succeeds, and the option has no effect. You can run into this with plotting libraries, HTTP clients, and wrappers that forward options to another function. For these, the real contract lives in the documentation of the function that eventually consumes the keywords.
Static analysis has similar limits:
- Attributes created with
setattr,__getattr__, or metaprogramming are invisible to the checker. - Libraries without type hints or stubs resolve to
Any, and calls onAnyare never flagged. - A
# type: ignoreor an overly broadcastadded to quiet an error also hides the signal you wanted. - ORMs, dataframes, and dynamic clients often expose columns or methods only at runtime.
Warnings only fire on code that runs
Turning DeprecationWarning into an error is one of the cheapest guardrails. It is also limited by execution. A warning is raised when the deprecated call executes, not when the code is imported.
import warnings
warnings.simplefilter("error", DeprecationWarning)
def old_helper():
warnings.warn("old_helper is deprecated", DeprecationWarning, stacklevel=2)
def handler(use_legacy):
if use_legacy:
old_helper()
return "ok"
print(handler(False)) # ok, the deprecated path never ran
try:
handler(True)
except DeprecationWarning as exc:
print("caught:", exc)If your tests only call handler(False), the suite stays green while the deprecated branch ships. Error handlers, retry paths, rarely used flags, and migration code are the usual places where this happens.
Three more gaps:
- Some removals come without a deprecation period, or the deprecation is only in the changelog.
- Some libraries emit
FutureWarningor a custom warning class instead ofDeprecationWarning. Check which category yours uses. - Python hides
DeprecationWarningby default outside__main__and test runners, so a filter set in the wrong place can silently do nothing.
Behavior changes that raise nothing
The hardest outdated-usage cases are the ones where the API still exists and still accepts the same arguments, but the result differs by version. Examples include a changed default value, a different sort order, a changed rounding rule, or a function that used to return a list and now returns an iterator.
A model trained mostly on older code will write the older assumption. Your existence check passes against the new version, the type checker may pass, and the tests pass if they never inspected the changed detail. Only the changelog or a version-specific test reveals it.
You can reduce this risk with a small characterization test: record the behavior you rely on as an assertion, so a future upgrade or a generated change that assumes something else breaks it.
def test_removeprefix_keeps_inner_characters():
assert "test_set_up".removeprefix("test_") == "set_up"Tests prove what they assert
Chapter-level advice said to run the generated code. That helps only in proportion to the tests' quality. Generated tests deserve the same suspicion as generated code, because the same model often writes both and shares the same wrong assumption in each.
Common weaknesses:
- The test asserts only that no exception occurred, not that the result is correct.
- The test mocks the library call, so the invented or misused API is never actually reached. A mock accepts any attribute, so
mock.get_json()passes happily. - The test data is too simple to expose a behavior difference, such as a single-element list or an ASCII-only string.
- Coverage is high but the assertions are weak.
If a test uses unittest.mock.Mock for a library, consider create_autospec. It builds a mock from the real object, so calls with a wrong name or signature fail.
from unittest.mock import create_autospec
import json
fake_dumps = create_autospec(json.dumps)
fake_dumps({"a": 1}, indent=2) # fine
try:
fake_dumps({"a": 1}, pretty=True)
except TypeError as exc:
print("rejected:", exc)This closes one gap, though it still does not make the test assert the correct behavior.
A package that exists is not a package you can trust
Dependency checks answer whether a name resolves on the index. They cannot answer whether the package is the one you meant. Several risks remain after "it exists on PyPI":
- A look-alike name registered by someone else, which is the failure that attackers exploit when a model repeatedly suggests the same nonexistent name.
- An abandoned package that exists but no longer works with your Python version.
- A legitimate package at a version whose API differs from what the generated code assumes.
- A transitive dependency pulled in by the new package that you never reviewed.
Pinning with hashes reduces some of this by fixing what gets installed, but it does not make the pinned artifact safe. Reviewing the project's age, maintainers, repository, and download history remains a human task.
Environment differences hide failures until later
Your checks run in one environment. Production may use a different Python version, a different resolved version of a transitive library, or a different operating system. Code that passes locally on pandas 2.2 may fail on a deployment image that resolved something else. Verify that CI installs from the same lock file as production, and that the versions you recorded earlier describe the deployed system, not just your laptop.
Summary of coverage
| Check | Catches | Does not catch |
|---|---|---|
| Introspection (`resolve`, `inspect.signature`) | Missing names, wrong parameter names on fixed signatures | Wrong behavior, `**kwargs` pass-through, ignored options |
| Versioned docs and changelogs | Behavior and removals documented for your version | Undocumented changes, outdated third-party pages |
| Type checker and linter | Missing attributes and type mismatches in typed code | Dynamic attributes, `Any`, untyped libraries, ignored errors |
| Warnings as errors | Deprecated calls on executed paths | Unexecuted paths, removals without warnings, other warning classes |
| Tests | Failures on asserted behavior | Behavior no test asserts, shared wrong assumptions, mocked-away calls |
| Package verification | Nonexistent names, unpinned installs | Look-alike packages, abandoned projects, transitive risk |
Using the gaps in practice
Knowing the gaps tells you where to spend human attention.
- Review semantics, not just names. For each external call in a generated change, ask what it returns on failure, what its defaults are, and what it does with unknown options.
- Write assertions about results. A test that checks a value catches more than a test that checks "no error".
- Cover both branches of any code that touches a library. Warnings and failures only appear on paths that run.
- Prefer autospecced mocks, or no mocks for pure library calls.
- Read the changelog between the version the model likely learned and the version you run, especially for defaults.
- Test in an environment built from your lock file, and keep a matrix if you support several versions.
- Treat a new dependency as a change that needs its own review.
Exercises
Exercise
A generated function calls client.fetch(url, retries=5). inspect.signature(client.fetch) shows (self, url, **kwargs). Your check for retries in sig.parameters returns False. Does that prove the call is wrong, and what should you do next?
Show answer
No. Because the signature has **kwargs, the call is accepted whether or not retries has any effect. The result only shows that the parameter is not declared here. Next, find where kwargs is consumed (in the source or the documentation for your installed version), then write a test that shows retries actually happen, for example against a stub server that fails twice.
Exercise
Your CI runs python -W error::DeprecationWarning -m pytest and passes. A reviewer says the generated change still uses a deprecated call. Give two reasons both statements can be true.
Show answer
First, the deprecated call may sit on a path no test executes, and warnings fire only when the call runs. Second, the library may signal the deprecation with a different category such as FutureWarning, or only in its changelog, so the DeprecationWarning filter never sees it. Other valid reasons are that the warning is emitted in a subprocess that does not inherit the filter, or that the library has not marked the call as deprecated.
Exercise
A generated test mocks requests.get with Mock() and asserts that the code returns mock.return_value.get_json.return_value. The test passes, but Response has no get_json. What went wrong, and how do you change the test?
Show answer
A plain Mock creates any attribute on demand, so the invented method was never checked against the real class. Use create_autospec or Mock(spec=requests.Response) so unknown attributes raise AttributeError, and assert on the decoded result produced from a response whose body you control, for example by using a real Response object or a local test server.