Common Property Patterns
You'll learn: The typical patterns that properties follow in property-based testing, making it easier to identify testable relationships in your code.
The Core Idea
When writing property-based tests, you're not inventing properties from scratch—most fall into recognizable patterns. Four common patterns emerge repeatedly:
Inverse relationships describe operations that undo each other. If you serialize then deserialize data, you should get the original back. If you encrypt then decrypt, same thing. Think of it like folding and unfolding a letter—they're opposites that cancel out.
Idempotence means applying an operation multiple times has the same effect as applying it once. Sorting an already-sorted list returns the same list. Deleting a file twice doesn't crash—the file stays deleted. Like pressing an elevator button repeatedly: the elevator still just comes once.
Invariants are properties that never change regardless of operations. The length of a list after sorting equals its original length. After adding item A to a set, the set contains A. These are truths that remain constant through transformations.
Metamorphic properties relate different inputs to each other. If you reverse a list twice, you get the original. If you sort list A then add item B, that's the same as adding B first then sorting. These describe how changing inputs affects outputs in predictable ways.
Why These Matter
Recognizing these patterns helps you spot properties quickly. Instead of staring at code wondering "what property should I test?", you can ask: "What's the inverse here? What stays the same? Is this operation idempotent?"
Key Takeaway: Most properties in property-based testing follow common patterns—inverse relationships, idempotence, invariants, and metamorphic properties—making them easier to identify and implement once you recognize these templates.