Sub topic 15
Testing every implementation against one specification
An abstract data type (ADT) promises behavior, and each implementation has to keep that promise. This chapter shows how to write the tests once, from the specification, and run them against every implementation. It assumes you have read the earlier chapters on the stack ADT, its two implementations, representation invariants, and representation exposure. It also assumes you know Python's unittest module at a basic level.
Why one test suite per specification
Suppose you test ListStack with checks that read self._items and LinkedStack with checks that walk self._head. You now have two suites that check different things. Neither suite says whether the two classes behave the same. A third implementation would need a third suite, and the three would drift apart.
The alternative is to treat the specification as the only source of tests. A test written from the specification calls only public operations and checks only promised results. It cannot tell which representation is behind the interface, so it can run against any implementation.
This gives you three properties:
- Every implementation faces the same checks, so "passes" means the same thing for all of them.
- A new implementation costs one line of test code, not a new suite.
- The tests keep working when you change a representation, because they never looked inside it.
Deriving tests from the specification
The Stack specification has three kinds of statements. Each becomes a kind of test.
| Specification statement | Test it produces |
|---|---|
| A new stack has no items | `is_empty()` is true after construction |
| `push(x)` then `pop()` returns `x` | Push one item, pop it, compare |
| Items come out last in, first out | Push several items, check the pop order |
| `peek()` does not remove the item | Peek twice, get the same value, and pop still works |
| `pop()` and `peek()` raise `IndexError` when empty | Call each on an empty stack and expect the exception |
The tests do not mention _items, _head, or _Node. Those names belong to the representation, and a test that uses them stops being a test of the ADT.
The simplest form: one function
The behavior check from the stack chapter is already a contract test. It takes a factory (a callable that returns a new stack) and uses only the interface:
def check_stack_behavior(make_stack):
s = make_stack()
assert s.is_empty()
s.push(7)
assert not s.is_empty()
assert s.peek() == 7
s.push(9)
assert s.pop() == 9
assert s.pop() == 7
assert s.is_empty()
try:
s.pop()
except IndexError:
pass
else:
raise AssertionError("pop on empty stack must raise IndexError")This works, but one function stops at the first failure and reports only a line number. It also mixes several promises together. For a real project, split the promises into separate tests.
A reusable contract suite with unittest
The pattern is a mixin class that holds the tests but does not inherit from unittest.TestCase. Because it is not a TestCase, the test runner does not run it by itself. Each implementation gets a small subclass that supplies a factory.
Save the Stack, ListStack, and LinkedStack classes from the earlier chapter in a file named stacks.py. Then save this as test_stacks.py:
import unittest
from stacks import LinkedStack, ListStack
class StackContract:
"""Tests written from the Stack specification only.
Subclasses set make_stack to a callable that returns an empty stack.
"""
def test_new_stack_is_empty(self):
self.assertTrue(self.make_stack().is_empty())
def test_push_makes_stack_non_empty(self):
s = self.make_stack()
s.push(1)
self.assertFalse(s.is_empty())
def test_push_then_pop_returns_item(self):
s = self.make_stack()
s.push("a")
self.assertEqual(s.pop(), "a")
self.assertTrue(s.is_empty())
def test_last_in_first_out(self):
s = self.make_stack()
for x in (1, 2, 3):
s.push(x)
self.assertEqual([s.pop(), s.pop(), s.pop()], [3, 2, 1])
def test_peek_does_not_remove(self):
s = self.make_stack()
s.push(5)
self.assertEqual(s.peek(), 5)
self.assertEqual(s.peek(), 5)
self.assertEqual(s.pop(), 5)
def test_pop_on_empty_raises(self):
with self.assertRaises(IndexError):
self.make_stack().pop()
def test_peek_on_empty_raises(self):
with self.assertRaises(IndexError):
self.make_stack().peek()
def test_many_items(self):
s = self.make_stack()
for i in range(1000):
s.push(i)
for i in reversed(range(1000)):
self.assertEqual(s.pop(), i)
self.assertTrue(s.is_empty())
class TestListStack(StackContract, unittest.TestCase):
make_stack = ListStack
class TestLinkedStack(StackContract, unittest.TestCase):
make_stack = LinkedStack
if __name__ == "__main__":
unittest.main()Run it with python test_stacks.py. Each test runs twice, once per class, so you get 16 results. A failure is reported as TestLinkedStack.test_last_in_first_out, which names both the implementation and the promise it broke.
make_stack = ListStack works as a class attribute because a class stored on a class is not turned into a bound method. Calling self.make_stack() therefore calls the constructor with no arguments. A plain function stored this way would receive self, so use a class or a staticmethod in that case.
Checking that the tests can fail
A suite that cannot fail proves nothing. Write a deliberately wrong implementation and confirm that the suite catches it. This one takes items from the wrong end, so it behaves like a queue:
from stacks import ListStack
class FifoStack(ListStack):
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop(0)Add class TestFifoStack(StackContract, unittest.TestCase): make_stack = FifoStack temporarily and run the suite. These tests pass:
test_push_then_pop_returns_item, because with one item the front and back are the same.test_new_stack_is_empty,test_peek_does_not_remove, and the empty-stack error tests.
These tests fail:
test_last_in_first_outtest_many_items
This shows why a single push-then-pop test is not enough. The specification includes the ordering promise, so the suite needs a test with at least two items. Remove the temporary class when you are done.
Testing the parts that are not in the interface
The contract tests cover what clients can observe. Two other properties from earlier chapters need extra care.
Representation invariants
A representation invariant is checked inside the class, as IntSet._check_rep does. The contract tests then exercise it indirectly, because every public operation calls _check_rep. To make this useful, your tests must drive the object into the situations that could break the invariant. For IntSet, that means adding the same value twice:
import unittest
class IntSet:
"""A set of integers.
Abstraction function: the list [a, b, c] represents the set {a, b, c}.
Representation invariant: _items contains no duplicates.
"""
def __init__(self):
self._items = []
self._check_rep()
def _check_rep(self):
assert len(self._items) == len(set(self._items))
def add(self, x):
if x not in self._items:
self._items.append(x)
self._check_rep()
def contains(self, x):
return x in self._items
def size(self):
return len(self._items)
class TestIntSet(unittest.TestCase):
def test_duplicate_add_keeps_size(self):
s = IntSet()
s.add(3)
s.add(3)
self.assertEqual(s.size(), 1)
self.assertTrue(s.contains(3))
if __name__ == "__main__":
unittest.main()The assertion in _check_rep is a guard inside the class. The test is what makes the guard run on an input that matters. Without the duplicate case, a missing if x not in self._items check might never be noticed.
Representation exposure
Exposure is a behavior you can test from outside: change what an operation returns, then check that the object did not change. The earlier roster example gives a direct test:
import unittest
class LeakyRoster:
def __init__(self):
self._names = []
def add(self, name):
self._names.append(name)
def names(self):
return self._names # exposes the internal list
class SafeRoster(LeakyRoster):
def names(self):
return list(self._names) # returns a copy
class RosterContract:
def test_mutating_result_does_not_change_roster(self):
r = self.make_roster()
r.add("Ada")
r.names().clear()
self.assertEqual(r.names(), ["Ada"])
class TestSafeRoster(RosterContract, unittest.TestCase):
make_roster = SafeRoster
class TestLeakyRoster(RosterContract, unittest.TestCase):
make_roster = LeakyRoster
if __name__ == "__main__":
unittest.main()TestLeakyRoster fails, and that is the point of the example. It confirms the test detects the leak. In a real project you would keep only the class under test.
Common errors
- Reading private fields in a contract test.
assert s._items == [1, 2]fails onLinkedStackand ties the suite to one representation. Use only public operations. - Checking exception messages. The specification promises
IndexError, not the wording. Assert the type only. - Testing only the happy path. The empty-stack errors are part of the specification, so they need tests for every operation that promises them.
- Using a single item. Ordering bugs hide when there is nothing to order. Always include a test with several items.
- Forgetting to register a new implementation. A class that exists but has no test subclass is untested. Add the subclass in the same change that adds the implementation.
- Treating a passing suite as a proof. The suite samples behavior. It raises confidence, and it does not replace careful reasoning about the invariant.
Summary of the workflow
- Write the specification, including error cases.
- Turn each promise into a test that uses only public operations.
- Put the tests in a mixin that takes a factory.
- Add one subclass per implementation.
- Add tests for conditions that could break the invariant or leak the representation.
- Run a deliberately wrong implementation once to confirm the suite can fail.
Exercise
You write a new ArrayStack that stores items in a fixed-size list and raises IndexError from push when the list is full. It passes StackContract. Is it a correct implementation of the Stack ADT as specified in this chapter, and what would you change?
Show answer
It is not correct. The specification says push(x) followed by pop() returns x and has no capacity limit, so a stack that rejects pushes breaks the promise. StackContract.test_many_items pushes 1000 items, so it fails unless the array is larger than that. Passing here only shows the test is too weak for this bug. Either make ArrayStack grow when full, or change the specification to a bounded stack (with a documented full-stack error) and add tests for that error. Both options change the contract and the tests together.
Exercise
A teammate adds assert s._head is None to test_new_stack_is_empty in StackContract. What goes wrong, and how do you fix the test?
Show answer
ListStack has no _head attribute, so TestListStack raises AttributeError. Even for LinkedStack, the check ties the shared suite to one representation. Replace it with self.assertTrue(self.make_stack().is_empty()), which uses only the public operation. If you want to check _head for LinkedStack, put that test in a separate class that applies only to it.