Testing Function Invariants Across Inputs
An invariant is a property expected to hold on a class of calls. Testing it checks more than a single example result.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Pick a necessary relationship
For a line-splitting function on an encoded text record, a stated protocol might require that joining its parts with the separator recovers the original. Test empty fields as well as ordinary ones. State which characters the input contract allows inside fields.
Keep examples with known outcomes
A faulty implementation returning one unchanged part could also satisfy the join property. Keep test cases that check the expected number and values of fields. Postconditions can combine complementary properties to prevent that loophole.[1][2]
Express a property with a clear scope
A stable deduplication function on lists should return an ordered subsequence containing exactly one occurrence of every distinct input value. Keeping only the first element passes several repetition-only examples, but fails on [4, 4, 7, 4, 8]. The result there should be [4, 7, 8]. Idempotence gives a useful secondary property, since applying deduplication again should preserve the result. By itself it would also allow a function that always returns an empty list. See deduplication in input order.
Build property checks that produce useful counterexamples
Generate short lists from a small alphabet to observe many repeated values and empty cases. For n up to five and values zero through two, there are \(\sum_{n=0}^{5}3^n=364\) lists. Each can be tested against independent checks for order, coverage and uniqueness. Consider unhashable inputs separately if they are advertised. When a failure occurs, show the original list and the violated property. See function postconditions.