Beyond example-based testing
Example tests verify specific inputs and outputs. Simulation tests verify invariants across random sequences of operations. This is valuable for stateful systems like caches, rate limiters, and state machines. Unkey usespkg/sim for simulation testing.
Simulation tests must document the invariant they protect. Random events can obscure intent, so the test docstring and validator names must state the production guarantee directly.
The mental model
A simulation has state, events, and validators.- State is the system under test plus any bookkeeping.
- Events modify state in random order.
- Validators check invariants after each step.
A simple example
Running the simulation
Reproducibility
When a simulation fails, save the seed and rerun withsim.SeedFromString to reproduce the sequence.
Writing effective events
Events must be self-contained and valid regardless of current state. If preconditions are not met, return early. Name events and validators after domain behavior.rejectExpiredKeyValidator is clearer than validator1 because it tells the reader which guarantee failed.