Sub topic 6
Green: the smallest change that passes
This chapter assumes you can write and run unit tests with pytest, read a Git diff, and have used a coding agent. It covers the green phase of red-green-refactor. In this phase you get a failing test to pass with the least code that works, and you check that the agent did not cheat to get there.
What green means
Green means every test in the suite passes. That includes the new failing test from the red phase and all the tests that passed before it. A new test that passes while an older one breaks is not green.
The goal of this phase is narrow. You are not building the final design, and you are not handling cases that no test describes. You write just enough code to move from red to green, so the test run tells you something reliable. If the suite was red for one reason and is now green, you know which change fixed it.
Green comes before refactoring. Separating the two keeps each step easy to check. If you change behavior and structure together, a failing test no longer tells you which change broke it.
Why "smallest" matters with an agent
A person writing code usually stops when the test passes. An agent often keeps going. It may add input validation, extra options, or a helper module, because it is trying to produce a complete solution. Each addition is code that no test requires, and it has three costs:
- It is unverified. No test fails if that code is wrong.
- It makes the diff longer, so review takes more effort.
- It can lock in design choices before you have tests that explain them.
Asking for the smallest change keeps the diff reviewable and keeps the tests as the specification. Code that exists should exist because a test required it.
Worked example: the slugify function
The red phase gave us one failing test:
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"The test fails because the behavior is missing. The smallest implementation that passes it is:
# slugify_util.py
def slugify(text):
return text.lower().replace(" ", "-")This version does not remove punctuation. It does not collapse repeated spaces. It does not handle tabs or leading whitespace. That is correct for now, because no test asks for those behaviors. Run the suite:
python -m pytest -qThe output should report one passing test. That output is the feedback the agent reads. The agent does not know the code is right. It knows only that the runner reported a pass, so the runner's output is the evidence you both rely on.
The next cycles
Behaviors you want but have not specified get their own cycles. Each test below is added separately, and each fails against the simple implementation before you change any code.
# test_slugify.py (added in the next cycles)
def test_strips_punctuation():
assert slugify("Hello, World!") == "hello-world"
def test_collapses_repeated_separators():
assert slugify("a -- b") == "a-b"With the simple implementation, slugify("Hello, World!") returns "hello,-world!", so the first new test fails. Fixing it is a green step. You might first write a small patch that strips punctuation. When the second test fails, you extend the implementation again. After both cycles, and a refactor, the code might look like this:
# slugify_util.py after the later cycles and a refactor
import re
def slugify(text):
words = re.findall(r"[a-z0-9]+", text.lower())
return "-".join(words)This version passes all three tests. Notice that it was not the first thing we wrote. The regular expression is a design that emerged from several small steps, and refactoring (the next chapter) produced the final shape.
Instructing the agent for the green step
An agent needs explicit limits. A prompt such as "make the test pass" invites broad changes. A better prompt names the target and the boundary:
- Say which test is failing and show its output.
- Ask for the smallest change that makes that test pass.
- Forbid edits to test files in this step.
- Ask the agent to run the full suite afterwards and report the result.
A prompt for the slugify case could read: "test_strips_punctuation fails. Make the smallest change to slugify_util.py that makes it pass. Do not change any test file. Then run python -m pytest -q and show the output."
Standing rules belong in the agent's instruction file, so you do not repeat them every time. This is the relevant part of a working agreement:
## Working agreement for this repository
1. Work test-first. Write one failing test for the requested behavior and run it.
2. Show the failure output and confirm it fails because the behavior is missing, not because of a typo or import error.
3. Write the smallest change that makes that test pass, then run the full test suite.
4. Refactor only while all tests are green, and run the suite again afterwards.
5. Do not edit, skip, or delete existing tests to make them pass. If a test seems wrong, stop and explain why.
6. Do not hardcode expected values from tests into the implementation.Rules 3, 5, and 6 apply directly to the green phase.
The green loop
The agent works in a loop: edit, run the tests, read the output, decide. In the green phase the loop is short and has a clear exit.
Two details matter. The agent runs the full suite, not only the new test, so a regression in older behavior shows up immediately. And the loop exits on a passing run, but the cycle does not end there. A human still reads the diff.
When green is not really green
A passing suite proves that the tests pass. It does not prove the code solves the problem. An agent optimizing for a green result can find ways to satisfy the tests without implementing the behavior.
Hardcoded results
This is the clearest case:
# A degenerate 'green' an agent might produce
def slugify(text):
return "hello-world"It passes test_lowercases_and_joins_words_with_hyphens, so the first run is green. It fails the other two tests, because they expect different outputs. This is why a suite needs several varied examples. One example per behavior allows a constant to pass. Two or three examples with different inputs force a real computation.
Note that hardcoding the first answer is sometimes a legitimate technique. Some TDD practitioners start with a constant and generalize as tests are added. The difference is intent and process. In a deliberate cycle you add a second test that forces the generalization. An agent that stops at the constant and reports success has not done that.
Other shortcuts to watch for
| Shortcut | What it looks like in the diff | How to catch it |
|---|---|---|
| Weakened assertion | `assert result == expected` becomes `assert result is not None` | The diff touches a test file in a green step |
| Skipped or deleted test | A new `@pytest.mark.skip` or a removed test function | The test count drops in the runner output |
| Special-casing inputs | `if text == "Hello World": return ...` | Branches that mention literal test values |
| Catching errors | A broad `try/except` that returns a default | Code paths no test exercises |
| Over-mocking | The tested function is replaced by a mock | The test no longer calls real code |
Most of these require changing a test or adding code that matches a test's literal values. That is why the working agreement forbids both.
Verifying a green result
Do not rely on the agent's statement that tests pass. Check three things yourself.
- The count. Compare the number of passing tests with what you expect. Run
python -m pytest -qand read the summary line. A lower count than before means something was removed or skipped. - The diff scope. Look at which files changed. In a green step only the implementation file should change. A modified test file is a red flag.
- The generality. Ask whether the code would work for an input the tests do not mention. Try one by hand, such as
slugify(" Many Spaces "), and see if the result makes sense.
If the code only works for the inputs in the tests, add a test for the missing behavior and start a new red phase. Do not patch the gap during the current green step.
Edge cases in practice
- The test passes immediately. If a new test is green before you write any code, the red phase failed to specify new behavior. Either the behavior already existed or the test is wrong. Stop and look before continuing.
- The test fails for a different reason after the change. If the failure message changes from an assertion mismatch to an exception such as
NameError, the agent introduced a bug. Fix that before moving on. - Fixing the new test breaks an old one. The suite is still red. Do not weaken the old test. Either the change was too broad, or the two tests conflict and you need to decide which behavior is right. Make that decision yourself.
- The smallest change is ugly. That is acceptable in green. Duplication and clumsy code are cleaned up in the refactor phase, with tests as a safety net.
- The agent wants to do more. If it proposes extra features, ask it to list them and add each as a separate test.
Commit discipline
When the suite is green and you have reviewed the diff, commit. One green result is one commit, or one commit that includes the test and its implementation. Small commits make it easy to revert a bad cycle without losing earlier work. If the agent makes several cycles' worth of changes at once, the commit becomes hard to review, which defeats the point of working in small steps.
Exercise
An agent is asked to make test_strips_punctuation pass. It returns a diff that adds if text == "Hello, World!": return "hello-world" to slugify and also changes test_collapses_repeated_separators to expect "a--b". The suite is green. List two problems and say what you would do.
Show answer
First, the special-case branch hardcodes the test's input, so the function does not strip punctuation in general. Second, the agent edited an existing test to match its output, which turns the test into a description of the code instead of the specification. Reject the diff, restore the test file with Git, and ask again with the rules to make the smallest general change and to leave test files untouched. If you doubt the original test, decide that yourself.
Exercise
You add a new test and run the suite before writing any code. It passes. What does that mean, and what should you do next?
Show answer
The test does not currently fail, so it does not specify new behavior. Either the code already handles the case or the test does not check what you intended. Do not proceed to green. Inspect the test, make it fail for the right reason (for example by choosing an input that exposes a missing behavior), and only then implement.