Sub topic 8
Checking AI Code with Tests You Write
This chapter assumes you can run a Python script and a simple test in a terminal or editor. It also assumes you have read the previous chapter on reading generated code critically. Reading code tells you what it seems to do. Tests tell you what it actually does.
Why your tests, not the AI's
An AI can write a function and a set of tests for it in one reply. Those tests are weak evidence. The same model made the same assumptions in both places. If it misunderstood the task, the code and the tests will agree with each other and both will be wrong.
Writing the tests yourself forces you to decide what correct means before you look at the answer. That decision is the learning. It is a form of prediction, and it also gives you an independent check on the code.
A practical order:
- Read the task and write down the cases you expect, before looking at the AI's code.
- Turn those cases into tests.
- Run the tests against the AI's code.
- When a test fails, find out whether the code or your expectation is wrong.
Choosing cases
Good tests cover more than the typical input. For most functions, check these groups:
| Case type | Example for a median function |
|---|---|
| Typical input | `[3, 1, 2]` |
| Other branch of the logic | `[4, 1, 3, 2]` (even length) |
| Smallest valid input | `[5]` (a single item) |
| Empty or missing input | `[]` |
| Unsorted input | `[9, 1, 5]` |
The "other branch" row matters most. A median function has one path for odd length and another for even length. A test that only uses odd lengths leaves half the code unchecked.
A worked example
Suppose an AI gives you this function. Before running anything, you have already decided on four cases: odd length, even length, one item and empty input. The empty case needs a decision too. Raising an error is one reasonable choice, and you must pick it yourself rather than accept whatever the code does.
def median(values):
if not values:
raise ValueError("median() requires at least one value")
ordered = sorted(values)
mid = len(ordered) // 2
if len(ordered) % 2 == 1:
return ordered[mid]
return (ordered[mid - 1] + ordered[mid]) / 2
assert median([3, 1, 2]) == 2
assert median([4, 1, 3, 2]) == 2.5
assert median([5]) == 5
try:
median([])
except ValueError:
pass
else:
raise AssertionError("median([]) should raise ValueError")If the script finishes without output, every check passed. An assert statement raises AssertionError when its condition is false, so silence means success.
Notice that the tests use [3, 1, 2] and [4, 1, 3, 2], which are not in sorted order. That checks that the function sorts its input. A test using [1, 2, 3] would pass even if the sort were missing.
Predict before you run
A test is only a learning tool if you commit to an answer first. Try this small exercise on a function you did not write. Write your expected result on paper, then run the code.
def count_vowels(text):
return sum(1 for ch in text.lower() if ch in "aeiou")
# Predict the output before you run this line.
print(count_vowels("Learning with AI"))The expected result is 6: the letters e, a, i, i, a, and i, found in "Learning with AI". If your prediction and the output differ, do not just fix the number. Work out why. Either you miscounted or you misunderstood what the code does, and both are worth finding.
When a test fails
A failing test gives you a question: is the code wrong, or is the test wrong? Check your expectation against the task first. If the test is correct, you have found a real bug.
Try to form your own hypothesis about the cause before asking the AI. Then, if you ask, share the failing test and the actual output, and ask for a hint rather than a rewrite. The debugging chapter covers this in more detail.
Limits of testing
Passing tests show that the cases you thought of work. They do not prove the code is correct. Your tests are only as good as your ideas about what could go wrong. Keep adding cases as you learn about new failure modes, such as repeated values, negative numbers, or very large lists.
Exercise
An AI gives you a median function and also writes three tests for it, all using lists of odd length. All three pass. Why is this not enough, and what would you add?
Show answer
The tests only exercise the odd-length branch, so the even-length branch is unchecked. The AI also wrote both the code and the tests, so shared misunderstandings go unnoticed. Add your own tests, written before reading the code, for an even-length list such as [4, 1, 3, 2] (expecting 2.5), a single item, an unsorted list, and an empty list (expecting a ValueError).
Exercise
A test you wrote fails. The AI says "just change the expected value so it matches the output." What should you do first?
Show answer
Check your expectation against the task. Work out by hand what the correct result should be. Only if your expected value was wrong should you change the test. If it was right, the code has a bug, and you should form a hypothesis about the cause before asking for a hint.