Property Tests for Sorting

A sort can be tested over generated lists by checking order and preservation of multiplicities independently.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Write two properties
  2. Generate informative input
  3. Detect element loss and unstable tie handling
  4. Generate cases with repeated keys intentionally

Write two properties

For any output, each neighboring pair should be nondecreasing. The frequencies of input and output values should match. An implementation returning empty output passes the first condition only. See function postconditions for why both belong to the guarantee.

Generate informative input

Include empty lists, repeated values, sorted lists, and reverse order. When stability is promised, label tied records and track their original order. Stable ordering adds that separate property to the test.[1]

Detect element loss and unstable tie handling

A test checking nondecreasing order alone accepts a function that returns an empty list. Add a comparison of input and output multiplicities. For stable record ordering, label equal-key records distinctly and compare their relative order. See stable ordering.

Input records (2,A), (1,B), (2,C)
Sorted stable output: B,A,C
Empty output passes order alone but fails preservation
B,C,A passes key order but fails stability

Generate cases with repeated keys intentionally

Uniform large key ranges produce few ties, so restrict some generated cases to a small palette. Include already ordered, reversed and duplicate-heavy inputs. A generated failure should report both the original data and the specific violated property.

References

  1. Hypothesis Contributors, Introduction to Hypothesis ↩