Sub topic 13
Checking invariants in tests
This chapter assumes you have read the AVL and red-black chapters. You should know the balance factor, the five red-black properties, and how insert and delete work in Python.
Why test invariants, not just lookups
A balanced tree can return correct search results while being badly shaped. If a rotation is missing, search still works. The tree has only lost its O(log n) guarantee, and an ordinary lookup test will not show that.
So test the invariants directly. An invariant is a rule that must hold after every public operation. A validator is a function that walks the whole tree and raises an error when a rule fails. The tests then do three things:
- Build a tree with many operations.
- Run the validator after each operation.
- Compare the tree's contents with a trusted model, such as a sorted list.
An AVL validator
The AVL rules are BST order, a height difference of at most one at every node, and a correct cached height field. The third rule is easy to forget. A rotation that skips update leaves a stale height, and later balance factors silently become wrong.
The validator below passes bounds down the tree to check order. It also recomputes each height from the children instead of trusting the cached value.
class Node:
def __init__(self, key, left=None, right=None, height=1):
self.key = key
self.left = left
self.right = right
self.height = height
def check_avl(root):
"""Raise ValueError if an AVL rule fails; return the tree height."""
def walk(n, lo, hi):
if n is None:
return 0
if (lo is not None and n.key <= lo) or (hi is not None and n.key >= hi):
raise ValueError("BST order violated at %r" % n.key)
lh = walk(n.left, lo, n.key)
rh = walk(n.right, n.key, hi)
if abs(lh - rh) > 1:
raise ValueError("unbalanced at %r: %d vs %d" % (n.key, lh, rh))
h = 1 + max(lh, rh)
if n.height != h:
raise ValueError("stale height at %r: cached %d, real %d" % (n.key, n.height, h))
return h
return walk(root, None, None)
good = Node(2, Node(1), Node(3), height=2)
print(check_avl(good)) # 2
chain = Node(1, None, Node(2, None, Node(3), 2), 3)
stale = Node(2, Node(1), Node(3), height=5)
for name, tree in (("chain", chain), ("stale", stale)):
try:
check_avl(tree)
except ValueError as e:
print(name, "->", e)The last loop prints chain -> unbalanced at 1: 0 vs 2 and stale -> stale height at 2: cached 5, real 2. Each message names the key and the broken rule, so a failing test points at the cause.
The red-black validator
The red-black validator from the earlier chapter, check_rb, follows the same pattern. It checks four things:
- The root is black.
- No red node has a red child.
- Every path to a nil leaf has the same black count.
- BST order holds.
It returns the black-height, so a passing call also gives you a number to print or compare.
Writing the property test
Fixed examples miss rare rotation cases. A randomized test covers many more. Use a seeded random generator so a failure can be reproduced.
import random
def run_trial(insert, delete, check, to_list, seed, steps=500):
rng = random.Random(seed)
root, model = None, set()
for step in range(steps):
key = rng.randrange(50) # small range forces duplicates and deletes
if rng.random() < 0.6:
root = insert(root, key)
model.add(key)
else:
root = delete(root, key)
model.discard(key)
check(root)
assert to_list(root) == sorted(model), "contents differ at step %d" % stepPass in your own insert, delete, check_avl (or check_rb), and an in-order traversal named to_list. Call run_trial for seeds 0 to 199. The small key range makes deletions hit existing keys often. It also exercises deletion from nodes with two children, which is where rebalancing bugs tend to hide.
Common mistakes in validators
- Checking each node only against its parent. A key in the left subtree of the root can be smaller than its parent yet larger than the root. Pass
loandhibounds down the tree. - Trusting cached heights. Recompute them from the children.
- Calling the validator inside the tree's own code. If
rebalanceand the validator share a helper, one bug can fool both. Keep the validator independent. - Testing only sorted input. Include random, reverse-sorted, and delete-heavy sequences.
Exercise
Your AVL rotate_left forgets to call update(y) on the new subtree root, but search tests still pass. Which check in check_avl catches this, and why do the search tests not?
Show answer
The stale-height check catches it, because the new root's cached height no longer equals 1 plus the larger child height. Search only uses key order, which rotations preserve, so lookups stay correct even though the stored heights, and later balance factors, are wrong.