Sub topic 2
The red-green-refactor cycle
This chapter assumes you can write and run unit tests in Python with pytest, read a Git diff, and have used a coding agent. It covers the cycle itself and what changes when an agent does the typing.
The three phases
Test-driven development (TDD) builds code in short loops. Each loop has three phases.
- Red. Write one test for a behavior that does not exist yet. Run it and watch it fail.
- Green. Write the smallest change that makes the test pass. Run the full suite.
- Refactor. Clean up the code and the tests while every test stays green. Run the suite again.
The test is the specification. It states what the code must do in a form a machine can check. That matters for an agent, because the pass or fail result gives the agent a signal it can act on without guessing what you meant.
A worked cycle: slugify
A slug is a URL-friendly version of a title, such as hello-world. We will build slugify one behavior at a time.
Red
Write the first test before any implementation exists.
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"Run it with the command the agent will also use:
python -m pytest -qAt this point the run fails with an import error, because slugify_util does not exist. That failure does not tell you much. A good red has the right cause: the behavior is missing, not a typo or a missing module. Create an empty slugify function that returns None, and the failure becomes an assertion error. Now the test fails for the intended reason.
Green
Write the least code that passes.
# slugify_util.py
def slugify(text):
return text.lower().replace(" ", "-")This code ignores punctuation and repeated separators. That is deliberate. No test asks for those yet, so no code handles them.
Next cycles
Add one test at a time. Each fails against the current code and drives the next change.
# 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"Refactor
After the later cycles, the implementation can be restructured while all three tests stay green.
# 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)Refactoring means changing structure without changing behavior. The tests are the proof that behavior did not change.
What changes with an agent
The cycle stays the same. The risks change, because an agent optimizes for a passing run. Two points matter in this chapter.
- Green means the smallest change, not the best one. Agents tend to write more than the test requires. Extra code has no test behind it, so nothing checks it.
- A pass is only as good as the tests. Suppose the suite has only the first test. This implementation then passes:
# A degenerate 'green' an agent might produce
def slugify(text):
return "hello-world"It is green, and it is wrong. Adding the punctuation and separator tests makes it fail, which is why you want several varied examples. Later chapters cover this failure mode and how to guard against it.
Who does what
A practical split is that you write or approve the red test, and the agent handles green and refactor. You decide what the behavior is. The agent supplies the code and reads the test output to know when it is done.
| Phase | Your role | Agent's role |
|---|---|---|
| Red | Specify the behavior, check the failure reason | Draft the test if asked |
| Green | Confirm the change is minimal | Write the change, run the suite |
| Refactor | Confirm behavior is unchanged | Restructure, run the suite |
Exercise
A new test fails with "ModuleNotFoundError: No module named 'slugify_util'". Is this a valid red? What would you do next, and what does a valid red look like here?
Show answer
It is not a valid red. The test fails because of a missing module, not because the behavior is missing. Create the module with a stub slugify that returns None, then rerun. A valid red is an AssertionError showing the actual value differs from "hello-world".
Exercise
Your suite contains only testlowercasesandjoinswordswithhyphens. An agent reports green after changing slugify to return "hello-world". Name the problem and one way to expose it.
Show answer
The implementation hardcodes the expected value, so it passes without implementing the behavior. Add a test with different input, such as slugify("Good Morning") == "good-morning". It fails against the hardcoded version.