Sub topic 8
Checking AI Code with Tests You Write
What this chapter assumes
You can write and call functions in Python and run a script from a terminal. You have used an AI assistant to generate code at least once. You do not need prior experience with testing tools. The chapter introduces assert statements first and pytest after that.
By the end you should be able to decide what a function must do before you read the AI's version. You should also be able to turn that decision into tests, and to explain what a passing test run does and does not prove.
Why the tests must be yours
An AI assistant can write a function and a set of tests for it in one reply. The tests often pass. That is weak evidence, for two reasons.
- The same model wrote both. If it misunderstood the task, the code and the tests usually share the misunderstanding, so they agree with each other and are both wrong.
- You learn nothing from reading tests you did not have to think about. Deciding which inputs matter is the part of testing that builds skill. It forces you to say what "correct" means.
Writing your own tests makes you do the work that checks understanding. It is retrieval and prediction practice applied to code. You pull the specification out of your head, commit to an expected answer, and then compare it with reality.
AI-written tests are not forbidden. Use them as a source of ideas after you have written yours. Ask "what cases did I miss?" and then decide for yourself which ones are valid.
Write the expectations before reading the code
Follow this order whenever you request code from an AI:
- Write the task in one or two sentences in your own words.
- List the inputs and the output you expect for each. Include at least one input you think could break a naive solution.
- Only then read or run the generated code.
If you cannot write step 2, you do not yet understand the task well enough to judge any solution. Go back to the problem. That is a useful discovery. It tells you the next thing to learn.
Predict before you run
The smallest version of this habit is a prediction. Look at this function and write your expected output on paper before you run it.
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"))Count by hand: "Learning" has e, a, i. "with" has i. "AI" has A and I, which become a and i after lower(). That makes 6. If your prediction differed from the printed number, do not just fix the prediction. Find which letters you miscounted or which line of code behaves differently from what you assumed. The gap between prediction and result is where the learning happens.
Choosing test cases
Good test cases are chosen on purpose. This table lists the categories that catch most errors in small functions.
| Category | Example for a median function | What it catches |
|---|---|---|
| Typical input | `[3, 1, 2]` | The basic idea is wrong |
| Other parity or shape | `[4, 1, 3, 2]` (even length) | Code handles only one branch |
| Smallest valid input | `[5]` | Off-by-one errors in indexing |
| Empty or invalid input | `[]` | Crashes, wrong exception, silent bad value |
| Duplicates | `[2, 2, 2, 2]` | Code that assumes distinct values |
| Negative or zero values | `[-5, -1, -3]` | Hidden assumptions about sign |
| Unsorted vs. sorted | `[9, 1, 5]` and `[1, 5, 9]` | Forgetting to sort |
| Input left unchanged | Call, then compare the list | Unwanted side effects |
You rarely need every row. Pick the rows that fit the function and the way it can fail.
A worked example: median
Suppose you asked an AI for a function that returns the median of a list of numbers. Before looking at its answer, you wrote down what you expect:
[3, 1, 2]gives2.[4, 1, 3, 2]gives2.5, the mean of the two middle values.[5]gives5.[]raisesValueError, because no median exists.
Now read what came back and run your checks:
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")
print("All checks passed")The try/except/else block matters. If median([]) raised nothing, a bare try with except would pass silently. The else branch makes that case fail loudly.
Seeing a test fail
A test you have never seen fail may not be testing anything. Here is a plausible but wrong version an assistant could produce:
def median_buggy(values):
ordered = sorted(values)
return ordered[len(ordered) // 2]
print(median_buggy([3, 1, 2])) # 2, matches
print(median_buggy([5])) # 5, matches
print(median_buggy([4, 1, 3, 2])) # 3, but the expected value is 2.5
try:
median_buggy([])
except IndexError:
print("IndexError instead of ValueError")It passes the first two checks, so a quick test with only odd-length lists would approve it. Your even-length case and your empty-input case both expose it. Notice also that the empty-list failure is a different exception from the one you specified. A test that only checks "does not crash" would miss this.
Moving to a test runner
Plain assert statements work for a few checks. When you have more, a test runner reports every failure instead of stopping at the first. pytest is the common choice in Python. Install it with pip install pytest.
Save the median function from above in median.py. Then create test_median.py next to it:
import random
import pytest
from median import median
@pytest.mark.parametrize(
"values, expected",
[
([3, 1, 2], 2),
([4, 1, 3, 2], 2.5),
([5], 5),
([2, 2, 2, 2], 2),
([-5, -1, -3], -3),
([1, 2], 1.5),
],
)
def test_known_answers(values, expected):
assert median(values) == expected
def test_floats_use_approximate_comparison():
assert median([0.1, 0.2]) == pytest.approx(0.15)
def test_empty_input_raises_value_error():
with pytest.raises(ValueError, match="at least one"):
median([])
def test_input_is_not_modified():
data = [3, 1, 2]
median(data)
assert data == [3, 1, 2]
def test_order_does_not_matter():
rng = random.Random(0)
for _ in range(200):
data = [rng.randint(-50, 50) for _ in range(rng.randint(1, 15))]
shuffled = data[:]
rng.shuffle(shuffled)
assert median(data) == median(shuffled)
assert min(data) <= median(data) <= max(data)Run it with pytest -v. Each parametrized case appears as its own line in the output, so a failure names the exact input.
Two details deserve attention:
- Floating-point numbers are stored approximately, so
(0.1 + 0.2) / 2is0.15000000000000002.pytest.approxcompares with a small tolerance. Use it whenever a float result comes from arithmetic. - The last test checks properties instead of fixed answers. For any list, the median must lie between the minimum and maximum, and shuffling the input must not change it. The fixed seed
Random(0)makes the "random" inputs repeatable, so a failure can be reproduced.
The verification loop
Testing AI code is a loop, not a single step. Each failure sends you back either to the code or to your own expectations.
The decision "code or expectation?" is important. Sometimes the AI is right and your test encoded a misconception. Resolving that is real learning. Do not change a test just to make it pass. First work out why it fails.
Limits of what tests prove
A green test run means the code agrees with your checks on the inputs you tried. It says nothing about inputs you did not try. Keep these failure modes in mind.
Tests that copy the implementation
If you derive the expected value by running the AI's code and pasting the output into the test, the test will always pass. It only records what the code does. Compute expected values by hand or from a trusted source, such as a worked example from a textbook.
Missing the specification
If the task is ambiguous, tests cannot settle it. For a median, what should median([1, "a"]) do? What about a list containing None? You must decide whether those cases matter, and either test them or document that they are out of scope.
Narrow coverage
Passing tests give confidence only where you looked. Check which lines of the code your tests never executed. With the pytest-cov plugin, pytest --cov=median --cov-report=term-missing lists untested lines. Coverage shows that a line ran, not that its result was checked, so treat it as a hint and not as proof.
Tests written by the same assistant
If you do ask an AI for extra tests, read each assertion and compute the expected value yourself before trusting it. Models sometimes write a wrong expected value that happens to match their own wrong code.
Performance and scale
Small examples will not reveal code that takes minutes on a million items. If speed matters for your task, add one test with a large input and a time limit, or measure it directly.
A checklist before you accept AI code
- I wrote the expected behavior before reading the code.
- My tests include typical, smallest, empty or invalid, and boundary inputs.
- I watched at least one test fail, on a deliberately broken version or on the first draft.
- Expected values come from my own reasoning, not from the code's output.
- I can explain why each test is there.
- I know at least one case the tests do not cover.
Exercise
An AI gives you def is_leap_year(year). Before reading it, list the test inputs you would write and the expected result for each. Include at least one case that a careless implementation using only "divisible by 4" would get wrong.
Show answer
Leap years follow three rules: divisible by 4, except century years, unless divisible by 400. Good tests: 2024 is True (typical leap year), 2023 is False (typical non-leap year), 1900 is False (divisible by 100 but not by 400, which the "divisible by 4 only" version gets wrong), 2000 is True (divisible by 400), and 2100 is False. You might also add 4 as a small value and decide in advance what to do with 0 or negative years, since the rules need a documented choice there.
Exercise
Your test assert median([0.1, 0.2, 0.4, 0.3]) == 0.25 fails, and the function returns 0.25000000000000006. Should you change the function? What should you change instead?
Show answer
No, the function is behaving correctly. Floating-point arithmetic is approximate, so exact equality is the wrong check. Change the test to assert median([0.1, 0.2, 0.4, 0.3]) == pytest.approx(0.25). The tolerance is justified because the result comes from adding and dividing floats, and you can explain why in your own words.
Exercise
Take the count_vowels function from this chapter. Write four tests that you can verify by hand, including one that checks uppercase letters and one that checks the empty string. Then name one case the function treats in a way you might not want.
Show answer
Examples: count_vowels("") is 0, count_vowels("xyz") is 0, count_vowels("AEIOU") is 5, count_vowels("Learning with AI") is 6. A case you might not want: the letter "y" is never counted, and accented vowels such as "é" are not in the string "aeiou", so they are not counted either. Whether that is a bug depends on the specification you wrote for the function.