| name | test-structural-invariants |
| description | For data structure validation: test lengths, relationships, constraints that must hold, verify setup is correct. |
test-structural-invariants
When to Use
- After building complex data structures
- Verifying precomputed relationships
- Checking initialization is correct
- Invariants that should always hold
When NOT to Use
- Simple data
- No structural constraints
- Runtime performance critical
The Pattern
Assert properties that must be true about your data structures.
def test_structure():
assert len(items) == EXPECTED_SIZE
assert all(condition(item) for item in items)
assert set(keys) == expected_keys
for a, bs in graph.items():
for b in bs:
assert a in graph[b]
Example (from pytudes)
def test():
"""A set of tests that must pass."""
assert len(squares) == 81
assert len(unitlist) == 27
assert all(len(units[s]) == 3 for s in squares)
assert all(len(peers[s]) == 20 for s in squares)
assert units['C2'] == [
['A2', 'B2', 'C2', 'D2', 'E2', 'F2', 'G2', 'H2', 'I2'],
['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'],
['A1', 'A2', , , , , , , ]
]
peers[] == ([.. peers...])
()
():
make_Apowers(, ) == {
: [],
: [, , , ],
: [, , , ],
...
}
make_Czroots(make_Apowers(, )) == {: , : , : , ...}
** + ** Czroots
** Czroots
** Czroots
():
(WORDS) ==
(WORDS.values()) ==
WORDS.most_common() == [
(, ), (, ), (, ), ...
]
Key Principles
- Test after construction: Verify build was correct
- Size invariants: Expected counts
- Relationship invariants: Things that must be connected
- Specific examples: Check known cases manually
- Use
all() for universal checks: Clean assertion syntax