Sub topic 9
Verify Generated Code with Tests and Review
Generated code looks finished. It is well formatted, it has plausible names, and it often comes with a confident explanation. None of that shows it works. This chapter covers how to check code from an assistant before you rely on it.
This chapter assumes you can write and run unit tests in Python with pytest, read a diff, and use a terminal. It builds on the earlier chapters: the goal, constraints, and examples you wrote in the prompt are the material you verify against.
Why generated code needs verification
An assistant produces text that fits the pattern of your request. It does not run the code unless your tool gives it an execution environment, and even then it only runs what it chose to try. Common results:
- The code solves a slightly different problem than the one you meant.
- The code handles the examples you gave and fails on inputs you did not mention.
- The code calls a function, parameter, or library that does not exist, or that exists only in another version.
- The code works, but breaks a constraint you set, such as using a third-party package.
Verification is how you catch these before they reach your project. The cost of checking is small compared to the cost of debugging the code later in production.
The verification loop
Verification is a loop, not a single step. Each pass either accepts the code or sends you back to refine the prompt.
The loop has two important properties. First, a failing test is information you can paste back into the conversation. Second, a problem found in review becomes a new test, so the same problem cannot return unnoticed.
Step 1: Read the code before you run it
Reading comes first because it is cheap and it also protects you. Code that you run executes with your permissions, so do not run code you have not looked at, especially code that touches files, the network, or the shell.
Check these points:
- Does it match the signature you asked for? Name, parameter types, and return type.
- Does it respect the constraints? Look at the imports first. If you said "standard library only," any other import is a violation.
- Does every called function exist? Unfamiliar names deserve a look at the official documentation for your version.
- Does it do anything you did not ask for? Extra file writes, network calls, or changed global state are red flags.
- Is the scope right? If you asked for one function and received a rewritten module, stop and decide whether you want that.
Take the slugify function from the earlier chapters:
import re
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]+", "-", text)
return text.strip("-")A reading pass confirms the signature, confirms that only re from the standard library is imported, and shows the three steps the prompt described: lowercase, replace runs of other characters with a hyphen, trim hyphens. Nothing extra appears. This code passes the read.
Step 2: Turn your prompt examples into tests
The examples you put in the prompt are already a specification. Copy them into a test so the check is repeatable and does not depend on your memory.
import pytest
from slugify_module import slugify
@pytest.mark.parametrize(
"text, expected",
[
("Hello, World!", "hello-world"),
(" Multiple spaces ", "multiple-spaces"),
("C++ & Rust", "c-rust"),
("Already-slugged", "already-slugged"),
],
)
def test_slugify(text, expected):
assert slugify(text) == expectedSave the function as slugify_module.py and the test as test_slugify.py in the same folder, then run:
pytest -qIf all four cases pass, the code meets the stated examples. That is a minimum, not a proof of correctness. The assistant saw those same examples when it wrote the code, so passing them is the easiest result to reach.
Step 3: Add tests the prompt did not mention
The next tests probe what the examples left out. Think of categories of input rather than single values.
| Category | Example input for `slugify` | Why it matters |
|---|---|---|
| Empty input | `""` | Often triggers an index error or a wrong default. |
| Only symbols | `"!!!"` | After trimming, nothing remains. The result should be an empty string. |
| Digits | `"Top 10 Tips"` | Digits belong in the allowed character class. |
| Repeated separators | `"a---b"` | Runs should collapse to one hyphen. |
| Leading and trailing symbols | `"--Hello--"` | Hyphens must be trimmed. |
| Non-ASCII text | `"Café"` | Outside the stated context, but you should know what happens. |
Write these as additional parametrized cases:
import pytest
from slugify_module import slugify
@pytest.mark.parametrize(
"text, expected",
[
("", ""),
("!!!", ""),
("Top 10 Tips", "top-10-tips"),
("a---b", "a-b"),
("--Hello--", "hello"),
],
)
def test_slugify_edge_cases(text, expected):
assert slugify(text) == expectedAll of these pass with the generated function. Now look at the last row of the table. slugify("Café") returns "caf", because é is not in [a-z0-9] and becomes a trailing hyphen that is then trimmed. The original prompt said titles are plain ASCII, so this is outside the contract. It is still worth recording what the code does, and deciding whether the contract should change. If your blog gets non-ASCII titles, the right move is to update the prompt (for example, "transliterate accented letters to ASCII") and generate again, not to patch around the result.
from slugify_module import slugify
def test_slugify_non_ascii_is_documented_behavior():
# The contract says ASCII only. This test records what happens otherwise.
assert slugify("Café") == "caf"A test like this makes a known limit visible to the next person who reads the suite.
Step 4: Review beyond what tests cover
Tests only check behavior you thought to test. A short review covers the rest.
Correctness and hidden assumptions
Ask what the code assumes. A function that parses dates may assume one locale. A function that reads a file may assume UTF-8. Write each assumption down, then check it against your real data.
Dependencies and versions
Compare every import with the versions you actually run. Generated code may use an API from a newer release, or one that was removed. Run it on the Python version from your prompt, not on whatever is installed by default. Confirm that any package it imports exists on the official package index under that exact name, and that you intended to add it.
Security
For code that touches input from outside, check these:
- SQL built by string formatting instead of parameterized queries.
- Shell commands built from user input.
- File paths built from user input without validation.
- Secrets written into source or logs.
Performance
If your prompt stated a limit, test it. A quick timing with a large input shows whether the code meets it:
import time
from slugify_module import slugify
big = "Hello, World! " * 100_000
start = time.perf_counter()
slugify(big)
print(f"{time.perf_counter() - start:.3f} seconds")The code above runs as is. Compare the printed time with the limit from your prompt.
Diff size
If you asked the assistant to change existing code, review the diff, not just the new file. Look for deleted lines you did not expect, renamed variables, or reformatted code that hides a real change. Run your existing test suite as well as the new tests, so you see regressions in code the assistant touched.
Using failures to improve the prompt
When a test fails, give the assistant the evidence. Include the test, the input, the expected output, and the actual output or traceback. Compare these two follow-ups:
Weak follow-up:
It doesn't work for some titles. Fix it.
Stronger follow-up:
slugify("Top 10 Tips") returns "top--tips" but should return "top-10-tips".
Digits should be kept. Here is the failing test and the current function.
Return only the corrected function.The second gives the assistant a concrete, checkable target, which connects to the goal and example techniques from earlier chapters. After the fix, rerun the whole suite, not only the failing test, because a fix for one case can break another.
What passing tests do not tell you
A green run means the code agrees with your tests. It does not show that:
- the tests cover your real inputs,
- the code is safe against hostile input,
- the code is readable and maintainable by your team,
- the dependencies are acceptable under your project's rules.
For code that matters, add a human review, run your linter and type checker, and test with real data samples. The more damage a bug could cause, the more of these checks you need.
A short checklist
- Read the code. Check signature, imports, and scope.
- Run the examples from the prompt as tests.
- Add tests for empty input, boundaries, repeated or odd characters, and invalid input.
- Check versions, dependencies, and security.
- Run the full existing test suite.
- Feed failures back to the assistant with exact inputs and outputs.
- Convert every bug you find into a permanent test.
Exercise
An assistant generates parse_price(text: str) -> float that turns "$1,234.50" into 1234.5. All three examples in your prompt pass. Name three further test inputs you would add, and say what each one checks.
Show answer
Possible answers: "" (empty input, checks that the function raises a clear error or returns a defined value instead of crashing unpredictably); "$0.00" (zero, a boundary value that is often mishandled by truthiness checks); "1,234" with no dollar sign (a missing symbol, checks whether the format is optional); "$1,23.4" (misplaced separators, checks input validation); "-$5.00" (negative values, a format the prompt did not mention). Any three that cover different categories, each with an expected result written down before running the code, are correct.
Exercise
Why is it risky to ask the assistant for a function and its only tests in the same reply, and to accept the code when those tests pass?
Show answer
The tests are written from the same understanding of the task as the code. If that understanding is wrong, both are wrong in the same way and the tests still pass. You should write some tests yourself from the original requirements, before reading the generated code, so they reflect your intent instead of the assistant's interpretation.
Exercise
A test in review shows that slugify("Café") returns "caf". The prompt said titles are plain ASCII. What are two reasonable responses, and which fits when your blog starts accepting accented titles?
Show answer
One response is to keep the code and add a test that documents the ASCII-only limit. The other is to change the prompt, for example by adding a constraint to transliterate accented letters to ASCII, and generate again. When accented titles become real input, the contract has changed, so update the prompt and tests and regenerate rather than patching the output.