Generators and Combinators
You'll learn how to build sophisticated test data generators by composing simple building blocks together.
The Composition Principle
A generator is a function that produces random test values (like integers, strings, or booleans). A combinator is a function that takes one or more generators and combines them into a new, more complex generator.
Think of it like cooking: basic ingredients (generators) like flour, eggs, and sugar can be combined using recipes (combinators) to create cakes, cookies, or pastries. You don't need infinite ingredients—you need smart ways to combine a few primitives.
How Combinators Work
Instead of writing generators from scratch for every data structure, you compose them:
- Start with primitive generators:
int(),string(),boolean() - Use combinators to build up:
list_of(),tuple_of(),dict_of(),one_of() - Create custom generators by combining these pieces
For example, to generate a user object, you might combine:
string()for the usernameint()for the ageone_of(["active", "inactive"])for status
A combinator like record() or object() then assembles these into a complete user generator.
Why This Matters
Combinators give you compositional power: build small, reusable generators and snap them together like LEGO blocks. This matches the structure of your actual data, making generators maintainable and expressive. When your data model changes, you adjust individual building blocks rather than rewriting everything.
Key Takeaway: Generators and combinators let you build complex test data structures by composing simple, reusable building blocks rather than hand-crafting each generator from scratch.