Sub topic 9
Using tests as evidence
This chapter assumes you can write and run unit tests, read a Git diff, and have used an AI coding assistant. The examples use Python and pytest.
Why tests count as evidence
When you read AI-generated code, you form an opinion about whether it works. That opinion is a guess until something checks it. Code that reads well is not proof of anything, because an assistant is good at producing fluent, plausible code whether or not it is correct.
A passing test is evidence, but only for the behavior the test actually checks. Reviewing with tests means asking two questions:
- What did a test run show about this change?
- What could still be wrong that no test would catch?
Treat the answers as a record of what you know and what you are still assuming.
Run the existing tests first
Before you read any new tests, run the project's existing suite on the change. This shows whether the change broke behavior that already worked. AI edits often touch more than you asked for, such as a renamed helper, a changed default, or a "cleanup" in a nearby function.
git diff --stat
python -m pytest -qRead the result carefully:
- All green means the change did not break anything the existing tests cover. It does not mean the new behavior is correct.
- A failure you did not expect is a finding. Do not accept an assistant's suggestion to "just update the test" until you understand why it failed. Sometimes the old test was wrong, but often the new code changed behavior by mistake.
- A suite that was already failing or flaky before the change gives you weak evidence. Note it and compare against a run on the base branch.
Write the failing test before trusting the fix
The strongest use of tests in review is to write a test that targets a suspected weakness. If the test fails, you have found a real defect. If it passes, you have gained real confidence.
Consider this function an assistant might produce for the requirement "return the mean of a list of numbers":
def average(values):
return sum(values) / len(values)It looks correct and it works for typical input. The requirement never said what happens for an empty list. Probing that case shows ZeroDivisionError, which is a hidden decision the assistant made without telling you.
Once you decide the intended behavior, fix the code and pin that behavior with tests:
import pytest
def average(values):
if not values:
raise ValueError("values must not be empty")
return sum(values) / len(values)
def test_average_of_numbers():
assert average([2, 4, 6]) == 4
def test_average_of_empty_list_raises():
with pytest.raises(ValueError):
average([])Two things matter here. The second test records a decision (raise ValueError) so a future change cannot silently alter it. And the decision came from you, checked against the requirement, not from the assistant.
Check that the tests can fail
AI assistants often write tests along with the code. These tests are useful, but they have a known weakness: they were produced from the same understanding as the code, so they tend to agree with it, including its mistakes.
A test that cannot fail gives you no evidence. Before you trust a new test, check that it can fail.
Mutate the code and watch the test
The quickest check is to break the code on purpose. Change a + to a -, flip a comparison, or delete a branch, then rerun the test. If the suite stays green, the test is not checking that behavior.
def apply_discount(price, percent):
return price - price * percent / 100
def test_apply_discount():
result = apply_discount(200, 10)
assert result is not NoneThis test passes for almost any implementation, including a broken one. The assertion only checks that something was returned. A stronger version asserts the value:
def test_apply_discount_reduces_price():
assert apply_discount(200, 10) == 180Now mutate - to + in the function. The strong test fails and the weak one does not. That difference is what you are looking for.
Common weak-test patterns
| Pattern | Why it gives little evidence |
|---|---|
| `assert result is not None` or `assert result` | Passes for nearly any return value. |
| Computing the expected value with the same logic as the code | The test repeats the code, so both are wrong together. |
| Mocking the function under test | The test checks the mock, not your code. |
| No assertion at all | The test only proves the code does not crash. |
| `except Exception: pass` inside a test | Hides the failure you wanted to see. |
| Only one happy-path input | Says nothing about boundaries or errors. |
Watch for tests edited to pass
When a change includes edits to existing tests, read those edits first. Loosened assertions, deleted cases, added skip markers, and widened tolerances are all ways to turn red into green without fixing anything. Use the diff to see them:
git diff -- tests/A changed test needs a reason you can state in one sentence. If you cannot state one, treat the change as suspect.
Choose which cases to test
Tests are cheap compared to defects found in production, but you cannot test everything. Pick cases that match the failure modes you looked for earlier in the review:
- Boundaries: empty input, one element, the maximum size, zero, negative numbers.
- Invalid input:
None, wrong types, malformed strings. - Error paths: network failures, missing files, timeouts. Assistants often write only the happy path.
- State and ordering: repeated calls, calls in a different order, shared mutable defaults.
- Security-relevant input: quotes, path separators, and very long strings, where the code handles untrusted data.
Parametrized tests let you cover several of these without repeating code:
import pytest
def clamp(value, low, high):
if low > high:
raise ValueError("low must not exceed high")
return max(low, min(value, high))
@pytest.mark.parametrize(
"value, low, high, expected",
[
(5, 0, 10, 5),
(-1, 0, 10, 0),
(11, 0, 10, 10),
(0, 0, 10, 0),
(10, 0, 10, 10),
],
)
def test_clamp_values(value, low, high, expected):
assert clamp(value, low, high) == expected
def test_clamp_rejects_inverted_range():
with pytest.raises(ValueError):
clamp(1, 10, 0)The values at exactly low and high are the ones most often wrong, so they belong in the table.
Use a test to confirm security behavior
Security flaws often pass every functional test, because the code returns the right answer for normal input. You need a test that supplies hostile input. The following example compares an unsafe query with a parameterized one:
import sqlite3
def find_user_unsafe(conn: sqlite3.Connection, name: str):
# Builds SQL by string formatting: vulnerable to injection.
query = f"SELECT id, name FROM users WHERE name = '{name}'"
return conn.execute(query).fetchall()
def find_user(conn: sqlite3.Connection, name: str):
# Parameterized query: the driver treats name as data, not SQL.
return conn.execute(
"SELECT id, name FROM users WHERE name = ?", (name,)
).fetchall()Calling find_user_unsafe with "' OR '1'='1" returns every row, while find_user treats the same text as a literal name and returns nothing. A regression test using that input would fail on the unsafe version and pass on the safe one, which makes it a permanent guard.
Know what tests cannot show
A green run has limits. Keep them in view when you write your acceptance decision.
- Coverage is not correctness. A line can execute without any assertion checking its result. Coverage tells you what ran, not what was verified.
- Tests only cover what someone thought of. If neither you nor the assistant considered a case, no test exists for it.
- Tests do not check intent. They confirm the code matches the tests. Whether the tests match the requirement is still your judgment.
- Environment matters. A pass on your machine does not cover other versions, operating systems, or production data volumes.
A repeatable test-based review loop
Follow the loop each time:
- Run the existing suite and compare against the base branch if anything fails.
- Read new and edited tests before the code they cover, and note any weakened assertions.
- Break the code on purpose to confirm the tests detect it.
- Add tests for the edge, error, and security cases the change missed.
- Fix the code, not the tests, when something fails, then rerun everything.
- Write down what the tests showed and what they did not.
Record the evidence
When you accept a change, leave a short note in the pull request or commit message. For example:
- Existing suite passes (142 tests).
- Added tests for empty input and inverted range; both failed before the fix.
- Confirmed new tests fail when the discount sign is flipped.
- Not covered: behavior with more than one million items.
This turns an opinion into something a teammate can check, and it makes the gaps visible instead of hidden.
Exercise
An assistant adds a function is_adult(age) that returns age >= 18, along with the test assert is_adult(30) is not None. The suite passes. Why is this weak evidence, and which test cases would you add?
Show answer
The assertion only checks that a value was returned, so it passes even if the function is wrong (for example age > 18 or age <= 18). Replace it with real assertions: is_adult(30) is True, is_adult(5) is False, and the boundaries is_adult(18) is True and is_adult(17) is False. Also decide and test behavior for invalid input such as None or negative ages. To confirm the new tests work, change >= to > and check that the boundary test fails.
Exercise
A reviewed change fails one existing test. The assistant suggests changing the expected value in that test so the suite passes. What do you do before accepting that suggestion?
Show answer
First work out why the test fails. Check the requirement and the base branch to see whether the old expected value was correct. If the old value was correct, the new code introduced a bug and the code must be fixed. Only if the requirement truly changed should the test be updated, and the reason should be stated in the commit message.