Sub topic 1
Tests as Executable Specifications
Prerequisites
This chapter assumes you have the following:
- Basic programming in one language. The examples use Python.
- Experience writing and running unit tests with a framework such as pytest.
- Familiarity with Git commits and diffs.
- Basic use of a coding agent or AI coding assistant.
You do not need to know test-driven development (TDD) yet. The next chapter introduces the red-green-refactor cycle. This chapter covers the idea underneath it: a test is a precise, runnable statement of what code should do.
Why a test can act as a specification
A specification says what a piece of software must do. Most specifications are prose: a ticket, a design note, a chat message. Prose is easy to write and easy to misread. Two people can read "make slugs from titles" and build different things.
A test is a specification you can run. It names an input, states the expected output, and reports pass or fail. It cannot be vague, because the computer either agrees with it or does not.
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"This test says three things:
- A function named
slugifyexists in the moduleslugify_util. - It accepts one string.
- For
"Hello World"it returns exactly"hello-world".
No one has to interpret it. If the implementation returns "Hello-World", the test fails and says so.
What an assertion is
An assertion is a statement that must be true for the test to pass. In pytest you write it with the plain assert keyword. When the condition is false, pytest raises an AssertionError and shows both sides of the comparison. A test with no assertion checks only that the code does not crash.
The parts of a test follow a common pattern, often called arrange, act, assert:
| Part | Purpose | In the example |
|---|---|---|
| Arrange | Set up inputs and state | The string `"Hello World"` |
| Act | Call the code under test | `slugify("Hello World")` |
| Assert | State the expected result | `== "hello-world"` |
Small tests like this one fold all three parts into a single line. Larger tests separate them.
What makes a test good as a specification
Not every test works well as a specification. A useful one has these properties.
- It names one behavior. The test name should read as a sentence about the behavior, such as
test_lowercases_and_joins_words_with_hyphens. When it fails, the name tells you what broke. - It checks observable results. It asserts on return values, raised errors, or visible side effects. It does not assert on private variables or the order of internal calls.
- It is deterministic. The same code gives the same result every run. Tests that depend on the clock, the network, or random numbers without control produce noise.
- It fails for one reason. If a test checks five unrelated things, a failure does not tell you which behavior is missing.
- It is fast. A test you can run in a fraction of a second gets run after every change.
Tests that check implementation details break when you refactor, even though the behavior is unchanged. Tests that check behavior survive refactoring. This difference matters later, when an agent rewrites code while the tests stay fixed.
What tests can and cannot specify
A test specifies by example. Each test pins down one input and its expected output. A set of examples describes a behavior, but it never describes it completely.
Consider the single slugify test above. These implementations all pass it:
def slugify(text):
return text.lower().replace(" ", "-")def slugify(text):
return "hello-world"The first is a reasonable beginning. The second ignores its input. Both satisfy the specification as written, so the specification is incomplete.
This gap is the central limit of tests as specifications:
- Tests only cover the examples you wrote.
- Behavior between and beyond those examples is unspecified. Any implementation that fits the examples is allowed.
- Behavior you forgot to think about is unspecified too.
Humans usually fill the gap with common sense. They read the test, see that the function should handle any title, and write general code. A coding agent also tends to write general code, but nothing in the test forces it to. When the agent is under pressure to turn a failing test green, a hardcoded answer is a legal move. Later chapters cover how to detect and prevent this. For now, keep one rule in mind: the quality of the code you get is bounded by the quality of the examples you provide.
Writing examples that close the gap
You close the gap by adding examples that differ from each other in meaningful ways. For slugify, the next two behaviors are punctuation and repeated separators.
# 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"Now the hardcoded return "hello-world" fails the third test, because "a-b" is not "hello-world". Each new example removes a family of wrong implementations. The specification becomes tighter without becoming longer than it needs to be.
A practical way to choose examples:
- Start with the simplest typical case.
- Add a case for each rule you can state in a sentence ("punctuation is removed").
- Add boundary cases: empty input, a single character, input that is only punctuation.
- Add a case for each bug you find later, so it cannot return unnoticed.
Tests as a feedback signal
A specification also has to say when you are done. Prose does not. A passing test run does.
When you run the suite, you get a result:
python -m pytest -qA passing run looks like this:
... [100%]
3 passed in 0.02sA failing run shows which test failed and why. For the hardcoded implementation, the failure for the punctuation test reads roughly:
FAILED test_slugify.py::test_strips_punctuation - AssertionError: assert 'hello-world' == ...This output is information. It tells a reader, human or agent, which behavior is missing and what the code returned instead. That is why tests matter even more with a coding agent than without one. An agent cannot see your intent. It can read files and run commands, and the test output is the clearest signal it gets about whether its change worked.
The same idea explains why the agent needs a command it can run. A test that exists but cannot be executed gives no feedback. Make sure the project has one documented command, such as python -m pytest -q, that runs the whole suite and exits with a non-zero code on failure.
A specification written before the code
The order in which you write things changes what the test means.
- A test written after the code often describes what the code happens to do. It tends to copy the implementation's choices, including its mistakes.
- A test written before the code describes what you want. It can only reflect your intent, because there is nothing else to reflect.
The second kind is a specification. The first is closer to a record. Both are useful, but only the second tells an agent what to build. This is the reason TDD pairs well with coding agents: the test is written first, by you or reviewed by you, and then the agent works toward it.
Specification at different levels
Tests exist at several levels, and each specifies a different scope.
| Level | What it specifies | Typical speed | Example |
|---|---|---|---|
| Unit | One function or class in isolation | Milliseconds | `slugify("Hello World")` returns `"hello-world"` |
| Integration | Several parts working together | Seconds | A function saves a record and reads it back |
| End to end | The whole system through its public entry point | Seconds to minutes | A user submits a form and sees a result |
For TDD with an agent, unit tests are the default choice. They are fast, they point to a specific failure, and an agent can run them after every small edit. Higher-level tests are valuable as a final check, but a slow, broad test gives weak feedback: a failure says something is wrong somewhere.
Common mistakes
- Asserting too little. A test that calls the function and checks only that no exception occurred passes for almost any implementation.
- Asserting too much. Comparing a large output to a long literal makes the test fragile. Small, deliberate assertions are easier to read and to maintain.
- Copying the output into the test. If you run the code, paste what it returns into the expected value, and call that a test, you have recorded behavior without deciding whether it is correct. This is sometimes useful, but it is not a specification of intent.
- Vague names.
test_slugify_1tells nobody what failed. - Hidden dependencies. A test that relies on files, environment variables, or the current date can pass on one machine and fail on another.
How this connects to the rest of the tutorial
The remaining chapters build on three facts from this chapter:
- A test is a precise, runnable statement of expected behavior.
- A set of tests is an incomplete specification, so the choice of examples matters.
- Test output is the feedback an agent reads to decide its next step.
The red-green-refactor cycle in the next chapter puts these facts into a repeatable process. Later chapters then show how to instruct an agent to follow that process and how to guard against an agent that satisfies the tests without solving the problem.
Exercises
Exercise
The test assert slugify("Hello World") == "hello-world" is the only test in a project. Name one implementation that passes it but is clearly wrong, and describe one additional test that would reject it.
Show answer
The implementation def slugify(text): return "hello-world" passes because it ignores its input. Adding assert slugify("a -- b") == "a-b" rejects it, since the hardcoded value is not "a-b". Any test with a different input and a different expected output works.
Exercise
A teammate writes a test by running a function, copying its output into the expected value, and committing the test. Why is this weaker as a specification than a test written before the code?
Show answer
The expected value comes from the implementation, so it records what the code already does, including any mistakes, instead of what you intended. A test written first can only reflect your intent, so a failure points to a real gap between intent and code.
Exercise
Why is a fast unit test usually a better feedback signal for a coding agent than a slow end-to-end test?
Show answer
The agent can run a unit test after every small edit, and a failure points to a specific behavior. An end-to-end test is slower and a failure only says that something in the system is wrong, which gives the agent less to act on.