Sub topic 7
Refactor while the tests stay green
This chapter assumes you can write and run pytest tests, read a Git diff, and have used a coding agent that edits files and runs commands. It also assumes you know the red and green phases from the previous chapters. Refactoring is the third phase of the cycle. It is also where agents most often change behavior without anyone noticing.
What refactoring means here
Refactoring is changing the structure of code without changing what it does. You rename things, remove duplication, replace a clumsy loop with a clearer expression, or split a long function. The visible behavior stays the same.
The test suite is what makes this safe. Before the change, every test passes. After the change, every test must still pass. If one fails, the change altered behavior, and you undo it or fix it. Without green tests you can't tell a refactor from a rewrite that happens to look tidy.
This gives the phase one rule: refactor only while the suite is green, and run the suite after every step. Never refactor on red. If a test is failing, you can't tell whether a new failure comes from your restructuring or from the existing problem.
Why green code needs cleanup
The green phase asks for the smallest change that passes. That produces code that works but is often awkward. Each cycle bolts on a condition or a special case. After a few cycles the function is correct and hard to read.
Here is what slugify can look like after three cycles. The tests for lowercasing, punctuation stripping, and repeated separators all pass.
# slugify_util.py after cycle 3, before refactoring
def slugify(text):
result = ""
for ch in text.lower():
if ch.isalnum():
result = result + ch
elif ch == " " or ch == "-":
if result != "" and result[-1] != "-":
result = result + "-"
if result.endswith("-"):
result = result[:-1]
return resultEvery branch exists because some test demanded it. Nothing here is wrong, but a reader has to simulate the loop to see what it does. This is the right moment to clean up, because three tests now describe the behavior.
The refactored version
The intent is "take the runs of letters and digits, then join them with hyphens". A regular expression says that directly.
# slugify_util.py after the refactor
import re
def slugify(text):
words = re.findall(r"[a-z0-9]+", text.lower())
return "-".join(words)Run the suite against it:
python -m pytest -qAll three tests pass, so the refactor is accepted. The function went from eleven lines to two, and the tests never changed. That unchanged test file is the evidence that behavior was preserved.
The loop for one refactoring step
A refactoring session is a series of small moves, each followed by a test run.
Two details matter. First, a failure means undo, not "fix forward". The previous state was known to be good, and a failing refactor tells you the move was not behavior-preserving. Second, you can stop at any point. Refactoring has no required amount of cleanup, and the next failing test will bring you back here.
What the green suite does not prove
A passing suite only proves that the behaviors you tested were preserved. Compare the two slugify versions on inputs the tests never covered:
| Input | Before the refactor | After the refactor |
|---|---|---|
| `"a_b"` | `"ab"` | `"a-b"` |
| `"Café"` | `"café"` | `"caf"` |
| `"Hello World"` | `"hello-world"` | `"hello-world"` |
The loop version treats an underscore as ignorable and keeps accented letters, because str.isalnum() accepts any Unicode letter. The regex only accepts a-z and 0-9. The two functions are different, and the suite is green for both.
This is not a flaw in the refactor step. It shows the limit of the safety net: a refactor is only as safe as the tests are complete. You have three ways to respond:
- Decide which behavior you want, and add a failing test for it in a new red phase. For example, a test that
"Café"becomes"cafe"would start a new cycle. - Accept the change if neither input matters to your users, and note it in the commit message.
- If the old behavior matters and has no test, add that test before refactoring. The legacy code chapter covers this.
The wrong response is to treat the refactor as finished because the suite is green and move on without thinking about it.
Refactoring with an agent
Agents are good at refactoring mechanics: extracting functions, renaming across files, simplifying loops. They are also prone to the temptations that make this phase risky.
- Scope creep. You ask for a cleanup of one function, and the agent also renames public APIs, reformats unrelated files, and adds a feature "while it is there".
- Behavior changes that look like cleanup. Dropping a branch that "looks unnecessary" is a common one, and the dropped branch is often the one no test covers.
- Editing tests to match. If a refactor makes a test fail, an agent may adjust the assertion instead of reverting. In a refactor, a test that needs editing is a signal that behavior changed.
- Mixing phases. The agent adds a new behavior and restructures in the same step, so a failure can't be traced to either.
Counter these with explicit instructions in the file your agent reads. The working agreement from earlier chapters already contains the key lines:
## 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 4 and 5 govern this phase. You can add refactor-specific rules for tasks that need them:
- Refactor one function or one concern per step.
- Do not change function signatures or public names unless asked.
- Do not combine a refactor and a new behavior in one change.
- If the suite fails after a refactor, revert the refactor and report which test failed.
A prompt that uses these rules might read: "All tests pass. Simplify slugify without changing its behavior. Make one change, run python -m pytest -q, and show me the output. Don't touch the test file."
Reading the feedback
The test runner output is the agent's evidence, and yours. After a refactor step, check three things in what the agent reports:
- The command that ran was the full suite, not a single test file or a filtered selection.
- The summary line shows the same number of passing tests as before. A drop in the count means tests were removed, skipped, or never collected.
- The test files do not appear in the diff.
You can check the third point yourself:
git diff --statFor a pure refactor, the stat output should list only implementation files. If a test file appears, ask why before accepting the change.
Commit refactors separately
Commit the refactor as its own commit, apart from the red-green work that preceded it. A history such as "Add punctuation handling" followed by "Refactor slugify to use regex" has two benefits. A reviewer can read the second commit knowing no behavior should differ, and a later bisect or revert can target the cleanup alone.
If you let the agent commit, tell it to keep the phases apart. A single commit that adds a test, changes behavior, and restructures code makes review slow and hides problems like the underscore difference above.
Common errors
| Error | Symptom | Fix |
|---|---|---|
| Refactoring on red | Several tests fail and no one knows which cause is which | Get to green first, or stash the refactor |
| Large refactor in one step | A failure could come from many edits | Break it into steps and run tests after each |
| Editing a test to pass | Test file changes in a "refactor" diff | Revert the test edit and investigate the behavior change |
| Mixing new behavior in | The diff adds branches or options | Split into a red-green cycle and a refactor |
| Trusting a thin suite | A refactor drops handling for an untested input | Add tests for the behavior you care about before refactoring |
| Testing implementation details | Tests break when you rename a helper, though behavior is unchanged | Test through public functions, not internals |
The last row is worth attention. If your tests call private helpers or mock internals, then ordinary refactoring forces test edits, and the safety net stops working. Tests should describe what the code does, not how it does it.
Exercise
After three TDD cycles, an agent refactors slugify and reports "all tests pass". The diff shows changes to slugify_util.py and to test_slugify.py, where one assertion was changed from "hello-world" to "hello_world". What should you do, and why?
Show answer
Reject the change and revert it. A refactor must not require changing a test, so the edited assertion means the refactor changed behavior (hyphens became underscores). Restore the original test, re-run the suite against the refactored code, and confirm it fails. Then have the agent fix the implementation, or undo the refactor, so the original tests pass without any test edits. If you actually want underscores, make that a separate red-green cycle with its own failing test.
Exercise
The refactored regex version of slugify returns "caf" for "Café", while the earlier loop version returned "café". The suite stays green. Name two reasonable ways to handle this.
Show answer
First, decide the intended behavior and write a failing test for it, such as expecting "cafe" or "café", then change the implementation in a new red-green cycle. Second, if neither result matters for your use, accept the difference and record it in the commit message. In both cases, do not leave the change unexamined just because the suite passes.