05 - How to Test AI-Generated Code
The code an assistant hands you compiles, has sensible names and looks already reviewed. To find out whether it works you have to run it, and how you do that matters more than which tool you use: a test written by looking at the code confirms what the code does, not what it was supposed to do. The rule behind this article is a single one: tests come from the requirement, not from the implementation, and their strength is measured by deliberately breaking the code to see whether they notice. You will see it by running three listings, all written by hand by me for the occasion.
This is the fifth article in the series. It takes for granted the criterion from the first (who reads the diff) and picks up from the third the idea of a test that must fail "for the right reason" before you write the code. Security has an article of its own, the seventh, and I leave it aside here.
A test that copies the code proves nothing
The first listing contains the "generated code", with two defects I chose because they are plausible: page_count computes how many pages are needed to show a given number of items,
and miscounts the remainder when it is exactly 1 (> 1 instead of > 0); label calls capitalise, with the British spelling, a method that Python strings do not have.
I did not see a model produce them: they are constructed examples, and I state that they serve to show a mechanism, not a frequency. Below them are three tests for page_count that differ in where
the expected result comes from, and a small runner that prints one outcome per test.
import unittest
# --- "Generated" code: written by hand by me, with two typical defects -----------
def page_count(total, per_page):
"""Pages needed to show `total` items, `per_page` per page."""
return total // per_page + (1 if total % per_page > 1 else 0)
def label(name):
return name.strip().capitalise()
LABEL_SOURCE = '''def label(name):
return name.strip().capitalise()
'''
# --- Three tests for page_count, with three different origins --------------------
class Examples(unittest.TestCase):
def test_1_happy_path(self):
self.assertEqual(page_count(100, 10), 10)
def test_2_copied_from_the_code(self):
# the expected result is computed with the same formula as the implementation
t, p = 11, 10
self.assertEqual(page_count(t, p), t // p + (1 if t % p > 1 else 0))
def test_3_from_the_requirement(self):
# requirement: 11 items with 10 per page take up 2 pages
self.assertEqual(page_count(11, 10), 2)
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(Examples)
for test in suite:
outcome = unittest.TestResult()
test.run(outcome)
if outcome.failures:
detail = outcome.failures[0][1].strip().splitlines()[-1]
print(f"{test._testMethodName:28} FAILS {detail}")
else:
print(f"{test._testMethodName:28} passes")
compile(LABEL_SOURCE, "label.py", "exec")
print("label: the code compiles without errors")
try:
label(" mario ")
except AttributeError as error:
print(f"label: but running it -> AttributeError: {error}")
# test_1_happy_path passes
# test_2_copied_from_the_code passes
# test_3_from_the_requirement FAILS AssertionError: 1 != 2
# label: the code compiles without errors
# label: but running it -> AttributeError: 'str' object has no attribute 'capitalise'
The first test is the one everyone writes first: a hundred items, ten per page, ten pages. It passes, and it passes with the defect too, because the remainder is zero. The second computes the expected result with the same formula
as the implementation: it passes by construction, and would keep passing if the defect got worse. It is the shape of test you get when you paste the function and ask "write the tests": the only specification the test
has in front of it is the code. I have not measured how often this happens with a real assistant; it follows from what the test receives as input. The third starts from the requirement ("11 items with 10 per page take up 2 pages") and
fails with 1 != 2, which is exactly the signal you need.
With label something else happens. compile accepts it, because the syntax is valid, and the error shows up only when you run it: AttributeError, because str has no capitalise.
A quick read does not catch it, because the name sounds right. A type checker would flag it without running the code: I did not try one here, but it is worth having in CI. The cheapest test remains a real call, even with a minimal input.
Three families of errors, and what catches them
I have not found a primary source that quantifies the types of error in generated code in general: the studies I read measure specific cases, such as vulnerabilities and invented packages in the previous article of the series. So I give no percentages. I can, however, classify errors by what it takes to catch them, which is the useful question when deciding how to test:
- A function or method that does not exist: caught by any execution of the path, even a minimal one, or by a type check.
- An error at the boundaries (remainder 1, empty list, exactly at the threshold): caught by a test with values chosen from the requirement, or by a property.
- Plausible but wrong for the domain (a rounding rule, a case the requirement does not mention): caught only by someone who knows the domain, which is why review stays.
The first two families can be automated, the third cannot, and tests do not remove it: if the requirement is badly written, the test inherits it. The work that remains yours, even with every check green, is making sure the requirement is the right one.
Properties instead of examples: Hypothesis
An example-based test depends on the values you thought of. Hypothesis, the property-based testing library for Python, starts from the other end: its documentation says you write tests that must pass for all inputs in the range you describe, and let
the library choose which ones to try, including the edge cases you had not thought of. The listing below describes two properties of page_count that follow from the requirement: the pages are enough to hold all the items, and no page is completely empty.
I set derandomize=True and database=None to get reproducible output: the documentation says derandomize is meant for deterministic tests in CI. Hypothesis is not part of the standard library and I installed it in a temporary environment outside the repository (version 6.170.15).
from hypothesis import given, settings, strategies as st
from examples import page_count
@settings(derandomize=True, database=None, max_examples=200)
@given(total=st.integers(min_value=0, max_value=1000),
per_page=st.integers(min_value=1, max_value=50))
def pages_property(total, per_page):
pages = page_count(total, per_page)
assert pages * per_page >= total # all items fit in the pages
assert pages == 0 or (pages - 1) * per_page < total # no page is completely empty
if __name__ == "__main__":
try:
pages_property()
print("the property holds on all generated examples")
except AssertionError as error:
for note in getattr(error, "__notes__", []):
print(note)
# Failing test case: pages_property(
# total=1,
# per_page=2,
# )
The property fails and Hypothesis reports a small counterexample: one item, two per page, and page_count returns 0 pages. It is not the input I had chosen (11 and 10), it is another one that
exposes the same cause, the remainder equal to 1. That is the concrete advantage: the property finds inputs you did not have in mind, and shrinks the counterexample to something you can read at a glance. The cost is that you have to be able to state the property. "The result is correct" is not one; "pages times items per page covers the total
and no page is left empty" is. A list of useful properties for a function is already half a specification.
There is also research that combines the two. A 2025 arXiv paper describes an agent based on a language model that reads Python modules, derives properties from the code and the documentation, writes and runs Hypothesis tests and produces reports: on 100 popular packages, after manual review 56% of the reports were valid bugs and 32% were bugs the authors would report to maintainers. Read the other way round, 44% of the reports were not valid bugs: even tests written by an agent need someone to judge them.
How strong your tests are: mutants
Coverage tells you which lines ran, not whether the tests would notice if those lines were wrong. The correct page_count is a single line and a suite with two calls (100 over 10, 50 over 5) runs all of it: a coverage tool would say 100%, even though I did not measure it. Mutation testing turns the question around:
you modify the code at one point at a time so as to introduce a defect, and check whether the suite fails. If it does not, that defect would get through.
The listing applies four mutations to the correct version (> 0 becomes > 1, which is precisely the defect of the first listing; a plus becomes a minus; the division becomes a remainder; > 0 becomes >= 0)
and tries them against two suites. It is a minimal mechanism written by me with the standard library: dedicated tools exist for many languages, and I have not run any of them.
ORIGINAL = "def page_count(total, per_page):\n" \
" return total // per_page + (1 if total % per_page > 0 else 0)\n"
MUTATIONS = {
"> 0 becomes > 1": ("% per_page > 0", "% per_page > 1"),
"+ (1 if becomes - (1 if": ("+ (1 if", "- (1 if"),
"// becomes %": ("total // per_page", "total % per_page"),
"> 0 becomes >= 0": ("% per_page > 0", "% per_page >= 0"),
}
WEAK_SUITE = [(100, 10, 10), (50, 5, 10)]
SUITE_WITH_BOUNDARIES = WEAK_SUITE + [(0, 10, 0), (1, 10, 1), (10, 10, 1), (11, 10, 2), (21, 10, 3)]
def passes(source, suite):
environment = {}
exec(source, environment)
return all(environment["page_count"](t, p) == expected for t, p, expected in suite)
if __name__ == "__main__":
assert passes(ORIGINAL, SUITE_WITH_BOUNDARIES) # the correct version passes both suites
for name, suite in (("weak suite", WEAK_SUITE), ("suite with boundaries", SUITE_WITH_BOUNDARIES)):
killed = [m for m, (a, b) in MUTATIONS.items()
if not passes(ORIGINAL.replace(a, b), suite)]
print(f"{name:22} mutants caught: {len(killed)} of {len(MUTATIONS)}")
for m in MUTATIONS:
print(f" {'caught ' if m in killed else 'SURVIVES '} {m}")
# weak suite mutants caught: 2 of 4
# SURVIVES > 0 becomes > 1
# SURVIVES + (1 if becomes - (1 if
# caught // becomes %
# caught > 0 becomes >= 0
# suite with boundaries mutants caught: 4 of 4
# caught > 0 becomes > 1
# caught + (1 if becomes - (1 if
# caught // becomes %
# caught > 0 becomes >= 0
The weak suite, which passes on the correct version, leaves two mutants out of four alive: precisely the two that touch the remainder, because in all its cases the remainder is zero. Adding five cases at the boundaries (0, 1, 10, 11 and 21 items) catches them all. The difference between the two suites is not in the amount of lines covered, which is the same, but in the values chosen. The number of mutants caught is therefore a more honest measure than coverage: it tells you whether a change of behaviour goes unnoticed. A surviving mutant, moreover, tells you which test to write.
With an assistant: the test first, from the requirement
In practice, the way to use an assistant for tests is to reverse the order. You write, or have it write, the test starting from the requirement, not from the code; you run it and check that it fails for the right reason (not because of an import error, as in the check from the article on agentic workflows); only then do you ask for the implementation and rerun the test. If an assistant writes both the test and the code from the same prompt, the two can share the same misunderstanding, and their agreement proves nothing. That is why the requirement goes into the prompt as data (what must hold, with examples at the boundaries), in the terms seen in the article on prompts and instruction files, and the verification command with its output is part of the request.
Before accepting a generated diff
- Does the test fail if the requirement is not met? Try breaking the code by hand, even a single character.
- Does the expected result come from a requirement or from the implementation?
- Are there cases for zero, one, exactly the threshold and one step beyond?
- Does every function called really exist? A minimal run or a type check will tell you.
- Did you read the output of the verification command, and not only the sentence "the tests pass"?
The order makes sense: the first two questions check that the test is able to fail, the other three that it covers what matters. A test that cannot fail gives no information, whatever colour it shows. The questions are mine, derived from the experiments above, and not an official checklist.
Frequently asked questions
Can I have the assistant write the tests?
Yes, provided you give it the requirement and not only the code, and you check that the tests know how to fail (with hand-made mutants or with a dedicated tool). The research cited above shows that even a specialised agent produces invalid reports in a significant share of cases.
Isn't 100% coverage enough?
No. In the second listing, two suites run the same lines and only one catches all the defects introduced. Coverage measures what runs, not what gets checked.
Does Hypothesis replace example-based tests?
No: examples document precise cases of the requirement, properties explore what you did not think of. The property in the listing found a case (1 over 2) that I had not chosen, but it is a boundary example that made the defect readable to a person.
What about security defects?
They have a dedicated article, with three defects proven by running them: Security in vibe coding. The functional tests in this article do not replace them.
What you can do now
You can recognise a test that copies the code and write one that starts from the requirement, you can use a property with Hypothesis to find a minimal counterexample, and you can measure the strength of a suite with defects introduced by hand instead of with coverage alone. The next step in the series is on the level of decisions: the future of agentic development.
Sources
- Hypothesis, documentation - description of the library and of the settings (
derandomize,database), consulted on 2026-11-13 - Agentic Property-Based Testing: Finding Bugs Across the Python Ecosystem (arXiv 2510.09907) - 100 packages, 56% valid reports, 32% to report to maintainers (abstract), consulted on 2026-11-13
- Python: the unittest module - definition of test case and
TestCase, consulted on 2026-11-13
The three listings were run twice each, with identical output (cmp on the output files): examples.py and mutants.py with Python 3.14.4 and the standard library only, properties.py with Hypothesis 6.170.15 installed in a temporary environment outside the repository. The functions under test were written by hand for the article and not generated by a model. No model was called, and no static analyser or mutation testing tool was run.

Commenti
Caricamento commenti...
Sign in to comment