Debian Codegraph @

website/content/2020-06-08-complex-data-strategies.md

raw symbols SCIP
1 ---
2 tags: python intro technical properties
3 date: 2020-06-08 15:00
4 title: Property Testing with Complex Inputs
5 author: hwayne
6 ---
7
8 Once you learn the basics, there are two hard parts to using property-based testing:
9
10 * What are good properties to test?
11 * How do I generate complex inputs?
12
13 These are also the _main_ parts of property-based testing! And both require some skill and creativity to solve. This post is to help you get some basics on the second question, how we generate complex inputs. Often we're working with data that has lots of preconditions and we want to actually generate inputs that satisfies the preconditions. We also often need to create data that depends on other data, or data with extra conditions, or [independent-but-similar](https://www.hillelwayne.com/post/metamorphic-testing/) data. We need some way to build more complex strategies.
14
15 There are a few different ways to do this, so let's go into each of them.
16
17 ## The problem
18
19 We have an Exam which consists of a set of questions and multiple-choice answers. Students take ExamInstances, which consists of the exam they took and the answers they gave. For each question they may either list an answer or leave it blank. There are many things we could test here, but the first step is actually generating the data.
20
21 For the purposes of this tutorial we will make the data classes as simple as possible:
22
23 ```py
24 from dataclasses import dataclass
25
26 @dataclass
27 class Exam:
28 """The abstract exam. Students take ExamInstances."""
29 name: str
30 answer_key: list[int]
31
32 @dataclass
33 class ExamInstance:
34 """The instantiation of the exam."""
35 student: int
36 exam: Exam
37 answers: list[int | None] # must be same length, but answers may be blank
38 ```
39
40 For our property tests we need to generate both Exams and ExamInstances. We have some restrictions on the Exam, and we need the ExamInstances to match the Exam in terms of answer length. This makes it somewhat more complex than the usual "generate an integer" case.
41
42 ## Generating Exams
43
44 ### Type inference
45
46 We don't _have to_ write a special generator for Exam. We've already type-annotated every field of Exam, so Hypothesis is smart enough to generate valid Exams via the `from_type` strategy.
47
48 ```py
49 from hypothesis import given
50 import hypothesis.strategies as st
51
52 @given(st.from_type(Exam))
53 def test_1(exam):
54 ...
55 ```
56
57 In fact, it can even generate valid ExamInstances, as all those fields are typed, too:
58
59 ```py
60 @given(st.from_type(ExamInstance))
61 def test_2(ei):
62 ...
63 ```
64
65 Sometimes this is good enough. In our case it is not for a couple of reasons:
66
67 * The state space is huge. Hypothesis is using the default generators for each of the fields, when for our purposes they should be more constrained. The more narrowly we can constrain the search space the more likely we are to get interesting edge cases.
68 * Hypothesis is going to generate a lot of "nonsensical" exams. You might get something where the answer key is `[-45, 0, 800002]`. We want to use stricter strategies for the fields of Exam.
69
70 ### Simple customizations
71
72 If our requirements are simple and we know that most generated inputs will be correct, we can usually get away with using `filter` and `assume`. `filter` is a method on all strategies, while `assume` goes in the body of the test itself. Both of them, when false, tell hypothesis to discard the invalid data and make a new draw. We can also use `assume` to relate several parameters to each other.
73
74 ```py
75 # very inefficient - don't do this!
76 @given(st.from_type(Exam).filter(lambda x: x.answer_key and min(x.answer_key) >= 0))
77 def test_2(exam):
78 assume(max(exam.answer_key) <= 5)
79 ...
80 ```
81
82 The upside of `filter` and `assume` is that they're easy to write and clearly express what our constraints are. The downside is that we are still generating bad inputs- we're just throwing it away right after. This makes the testing slower and Hypothesis might not find enough valid inputs.
83
84 We're better off writing a customized generator that _always_ generates good inputs. Fortunately that's a lot easier than it sounds.
85
86 ### `builds`
87
88 The `builds` strategy takes in an object and a set of initialization strategies, draws the corresponding values, and passes them into the object's `__init__`. Let's say we want to make sure that `answer_key` only uses numbers between 1 and 5. We can use `builds` to do this.
89
90 ```py
91 @given(st.builds(Exam, answer_key=st.lists(st.integers(1, 5))))
92 def test_3(exam):
93 for x in exam.answer_key:
94 assert x in range(6)
95 ```
96
97 We haven't specified what `name` is, so Hypothesis will use the default generator for text. If we want to always use the same name, we can use the `just` strategy:
98
99 ```py
100 @given(st.builds(Exam, name=st.just(""), answer_key=st.lists(st.integers(1, 5))))
101 def test_3(exam):
102 # same
103 ```
104
105 At this point we should probably pull it into its own function:
106
107 ```py
108 def exam_strategy(names=st.just(""), n_options=5):
109 return st.builds(
110 Exam,
111 name=names,
112 answer_key=st.lists(st.integers(1, n_options)),
113 )
114
115 @given(exam_strategy())
116 def test_3(exam):
117 # same
118 ```
119
120 ### `register_type_strategy`
121
122 Now that we have a custom builder, we can tell Hypothesis to always use it when inferring Exams. We do this with `register_type_strategy`.
123
124 ```py
125 def exam_strategy():
126 ...
127
128 st.register_type_strategy(Exam, exam_strategy())
129 ```
130
131 This will now be used any time Hypothesis infers that it needs to build an Exam, even if it needs to do so as part of generating something else, like an ExamInstance.
132
133 ```py
134 @given(st.from_type(Exam))
135 def test_4(exam):
136 ...
137 ```
138
139 That takes care of the Exam. But we still have a problem with the ExamInstance: its `answer` must have the same length as its exam's `answer_key`. But there's no way to guarantee that with our builder. We can't link strategies to each other.
140
141 ```py
142 # This will fail
143 @given(st.from_type(ExamInstance))
144 def test_5(ei):
145 assert len(ei.answers) == len(ei.exam.answer_key)
146 ```
147
148 In order to combine multiple strategies we need to use something a little more powerful: `composite`.
149
150 ## `composite`
151
152 Composite strategies are user-written functions "lifted" into full strategies. They can be a little bit unintuitive at first, so let's start with a simple example. This composite strategy returns a list of numbers where the first element of the list is always the smallest number in the list:
153
154 ```py
155 @st.composite
156 def example(draw):
157 i = draw(st.integers())
158 l = draw(st.lists(st.integers(min_value=i)))
159 return [i] + l
160 ```
161
162 Let's break down what's going on here. First we have the inner function. **The inner function does not return a strategy.** It returns regular Python values. The `@composite` decorator is what converts this function into a strategy. In addition to its usual parameters, the inner function also has a `draw` parameter. Calling this function on a strategy draws a concrete value. We need this because, again, the inner function only returns values, not strategies. We do not explicitly include `draw` when calling the full function; the decorator takes care of that. So we would call this function in a test like:
163
164 ```py
165 @given(example())
166 def test_example(l):
167 assert min(l) == l[0]
168 ```
169
170 We can do anything we want inside the body of the composite function, making it an exceptionally powerful tool. Here's how we can make sure that our Exam and ExamInstance have the same length:
171
172 ```py
173 # Helper function to make the following examples terser
174 def ei_answers_strategy(exam):
175 return st.lists(
176 st.none() | st.integers(1, 5),
177 min_size=len(exam.answer_key),
178 max_size=len(exam.answer_key),
179 )
180
181 @st.composite
182 def exam_instance_strategy(draw):
183 exam = draw(st.from_type(Exam))
184 answers = ei_answers_strategy(exam)
185 return ExamInstance(student=1, exam=exam, answers=draw(answers))
186 ```
187
188 We use it like any other strategy.
189
190 ```py
191 @given(exam_instance_strategy())
192 def test_6(ei):
193 assert len(ei.answers) == len(ei.exam.answer_key)
194 ```
195
196 ### More with `composite`
197
198 Composite strategies are just functions and can be called in other strategies. This means you can use it to create complex connected data. Let's say we want to generate several `ExamInstances` for the same student and exam. We can break this into several composable pieces:
199
200 ```py
201 @st.composite
202 def exam_instance_for_exam(draw, exam, student=""):
203 answers = ei_answers_strategy(exam)
204 return ExamInstance(student=student, exam=exam, answers=draw(answers))
205
206 @st.composite
207 def many_exam_instances(draw, student=""):
208 exam = draw(st.from_type(Exam))
209 exams = st.lists(exam_instance_for_exam(exam, student), min_size=1)
210 return draw(exams)
211
212 @given(many_exam_instances("brian"))
213 def test_7(eis):
214 ...
215 ```
216
217 In this case we're only passing raw values into the composite. This means we can't randomize the name of the student. In some cases this is an advantage, as it restricts the state space we have to search. In other cases this is a disadvantage, as it goes against the spirit of property testing. If you want the more thorough testing, you can pass in strategies instead into the composite and draw values in the body of the function.
218
219 ```py
220 @st.composite
221 def exam_instance_for_exam(draw, exam, student=st.just("")):
222 student = draw(student)
223 exam = draw(exam)
224 answers = ei_answers_strategy(exam)
225 return ExamInstance(student=student, exam=exam, answers=draw(answers))
226
227 # many_exam_instances is the same... for now
228 ```
229
230 There's a usability problem with this, though. Imagine we have `many_exam_instances` pass in complex strategies for `exam` and `student`. How do we know what values we drew? In this _particular_ case we can extract them from the returned ExamInstance, but we can't always rely on that, especially if we do more complex transformations. For this reason it's usually a good idea to pass back all the draws from the composite.
231
232 ```diff
233 @st.composite
234 def exam_instance_for_exam(draw, exam, student=st.just("")):
235 - return ExamInstance(student=student, exam=exam, answers=draw(answers))
236 + return exam, student, ExamInstance(student=student, exam=exam, answers=draw(answers))
237 ```
238
239 We also have to adjust `many_exam_instances` and our test. In particular we can't pass `exam_instance_for_exam` directly to the `lists` strategy anymore, as that assumed it only returned an ExamInstance. Now that we're returning a tuple of data it gets a bit messier.
240
241 ```py
242 @st.composite
243 def many_exam_instances(draw, student=st.just("")):
244 exam = draw(st.from_type(Exam))
245 student = draw(student)
246
247 # Unidiomatic/inefficient: getting the values in a loop
248 number = draw(st.integers(1, 5))
249 instances = []
250 for _ in range(number):
251 ei_strategy = exam_instance_for_exam(exam=st.just(exam), student=st.just(student))
252 _, _, ei = draw(ei_strategy)
253 instances.append(ei)
254
255 # Best practice: use lists(), in this case after .map()
256 instance_strat = exam_instance_for_exam(exam, student).map(lambda x: x[2])
257 instances = draw(st.lists(instance_strat, min_size=1))
258
259 return number, exam, student, instances
260
261 @given(many_exam_instances(student=st.characters()))
262 def test_8(stuff):
263 _, exam, _, eis = stuff
264 ...
265 ```
266
267 As you can see, this leads to a bit more boilerplate. Whether the tradeoffs are worth it depends on your specific case.
268
269 ## `data`
270
271 The last way to generate complex inputs is the `data` strategy. Like `composite`, it gives us a `draw` function that we can use to interactively pick values. Unlike `composite`, we can use it in the test body! Instead of `exam_instance_strategy`, we can do this instead:
272
273 ```py
274 @given(st.data(), st.from_type(Exam))
275 def test_data(data, exam):
276 answers = data.draw(ei_answers_strategy(exam))
277
278 ei = ExamInstance(student=1, exam=exam, answers=answers)
279 assert len(ei.answers) == len(ei.exam.answer_key)
280 ```
281
282 The main benefit of `data` is that you can customize your strategy based on the behavior inside the test. Something like:
283
284 ```py
285 if f(x):
286 y = data.draw(st.integers(min_value=1, max_value=10))
287 else:
288 y = data.draw(st.integers(min_value=6, max_value=20))
289 ```
290
291 The downside is that `data` doesn't play well with some other Hypothesis features, like the `@example()` decorator, and error reporting is a bit more complicated. If you can generate all your data ahead of time then you're better off using composites.
292
293 ## Summary
294
295 Hypothesis can infer a lot using `from_type`. If most random inputs are valid and you just need to rule out rare edge cases, then `assume` and `filter` are simple and effective. Past that, you can use `builds` to generate data with complex invariants. The `composite` strategy gives you even more control and lets you relate multiple draws to each other, making it possible to create lots of interdependent data. Finally, the `data` strategy lets you interactively pick values in the test itself. And all custom strategies can be associated with a type via `register_type_strategy`.
296
297 Hypothesis provides a lot of mechanisms to create complex data. Learning how to use them well is a bit of an art, but well worth it. Hopefully this makes "what to use when" a little more clear.
298
299 _Thanks to Zac Hatfield-Dodds and Oskar Wickström for feedback._