Sub topic 1
Tests as Executable Specifications
Prerequisites
Assume you can write basic Python, run unit tests with pytest, and read Git diffs. You should also know how to use a coding agent.
Tests as executable specifications
An automated test is an executable specification: it states a required behavior and checks whether the program provides it. An assertion is a statement that must be true.
For example, this test specifies that slugify lowercases words and joins them with hyphens:
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"The test gives an agent a precise target. The expected value is visible, repeatable, and independent of a verbal interpretation.
The red-green-refactor cycle
Test-driven development (TDD) repeats three steps:
- Red: write one test for behavior that does not work yet. Run it and confirm the expected failure.
- Green: make the smallest implementation change that passes the test.
- Refactor: improve the design without changing behavior. Run the tests again.
The first failure must be meaningful. An import error or syntax error does not prove that the requested behavior is missing.
# slugify_util.py, red phase
def slugify(text):
raise NotImplementedErrorAfter the test fails for the intended reason, the smallest green implementation is:
# slugify_util.py, green phase
def slugify(text):
return text.lower().replace(" ", "-")Run the feedback command after every change:
python -m pytest -qThe agent loop: read, edit, run, observe
A coding agent usually follows this loop:
The test output is feedback, not proof that the implementation is generally correct. Add varied tests as behavior expands. For example, punctuation and repeated separators would expose weaknesses in the simple implementation.
Telling the agent to work test-first
Give the agent explicit boundaries:
1. Write one failing test before changing production code.
2. Run it and verify the failure has the intended cause.
3. Make the smallest production change that passes it.
4. Run the full suite.
5. Do not edit, skip, delete, or weaken existing tests.
6. Do not hardcode values from the tests.Exercise
Why should an agent run a new test before implementing the requested behavior?
Show answer
To confirm that the test detects the missing behavior rather than failing because of a typo, import problem, or broken test setup.