Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
Testing
Exhaustive, random, and the bugs to plant
The point: test the fast code against slow code that is obviously right, and then check that the test can fail.
Levels
Four tests, four kinds of bug
| Test | Finds | Size |
|---|---|---|
| Every game of size 3 | Wrong lines, wrong undo, wrong order of checks | 255,168 games, some seconds |
| Random games of sizes 1 to 8 | Things that are true only for 3 | Thousands |
| Refusals | A check after a change | Compare the state before and after |
| Names of cases | Nothing new, but they explain | A handful |
Plant
Would the test notice?
A green test proves little until it has been red. Change one thing in the code and see which test fails.
| Planted bug | First test that fails |
|---|---|
elif for the second diagonal | Every game: the middle square |
| Draw is checked before the win | Every game: a win with the ninth move |
Undo switches the turn instead of move.mark | Every game: the state after undoing a win |
add returns at the first full line | Every game: a double line, then undo |
| Size 3 written into the up diagonal | Random sizes |
Move stored before put | Refusals: undo after a refused move |
Refusals
A refused move is free
Python
def state(game): return (game.rows(), game.turn, game.status, len(game._moves), dict(game._lines._count))def check_refusals(game): before = state(game) n = len(game.rows()) squares = [(r, c) for r in range(-1, n + 1) for c in range(-1, n + 1)] for mark in Mark: for row, col in squares: if mark is game.turn and (row, col) in game.legal(): continue try: game.play(mark, row, col) assert False, (mark, row, col) except IllegalMove: assert state(game) == beforeComputer
Testing the player who never loses
- 1
Never loses
Play it against all possible answers, as both marks. Not random ones: all.
- 2
Takes a win in one, blocks a win in one
For every position where there is one.
- 3
Symmetric
The value of a turned board is the same. A cheap test that finds typing errors in the list of lines.
- 4
Known number
The value of the empty board is 0: a draw.
Choose a test