Debian Codegraph @

hypothesis-python/docs/tutorial/custom-strategies.rst

raw
1 Custom strategies
2 ==================
3
4 This page describes how to write a custom strategy, for when the built-in strategies don't quite fit your needs.
5
6 Writing helper functions
7 ------------------------
8
9 Sometimes you might find it useful to write helper functions, to more concisely express a common pattern for your project. For example, it's much easier to write (and read!) ``response=json()`` than to have the whole implementation inline:
10
11 .. code-block:: python
12
13 def json(*, finite_only=True):
14 """Helper function to describe JSON objects, with optional inf and nan."""
15 numbers = st.floats(allow_infinity=not finite_only, allow_nan=not finite_only)
16 return st.recursive(
17 st.none() | st.booleans() | st.integers() | numbers | st.text(),
18 extend=lambda xs: st.lists(xs) | st.dictionaries(st.text(), xs),
19 )
20
21 Writing your own strategy
22 -------------------------
23
24 If a strategy in Hypothesis doesn't match what you need, you can write your own strategy.
25
26 For instance, suppose we want to generate a list of floats which sum to ``1``. We might start implementing this by generating lists of integers between 0 and 1 with ``lists(floats(0, 1))``. But now we're a bit stuck, and can't go any further with the standard strategies.
27
28 One way to define a new strategy is using the |st.composite| decorator. |st.composite| lets you define a new strategy that uses arbitrary Python code. For instance, to implement the above:
29
30 .. code-block:: python
31
32 from hypothesis import strategies as st
33
34 @st.composite
35 def sums_to_one(draw):
36 l = draw(st.lists(st.floats(0, 1)))
37 return [f / sum(l) for f in l]
38
39 |st.composite| passes a ``draw`` function to the decorated function as its first argument. ``draw`` is used to draw a random value from another strategy. We return from ``sums_to_one`` a value of the form we wanted to generate; in this case, a list that sums to one.
40
41 Let's see this new strategy in action:
42
43 .. code-block:: python
44
45 import pytest
46
47 from hypothesis import given, strategies as st
48
49 @st.composite
50 def sums_to_one(draw):
51 lst = draw(st.lists(st.floats(0.001, 1), min_size=1))
52 return [f / sum(lst) for f in lst]
53
54 @given(sums_to_one())
55 def test(lst):
56 # ignore floating point errors
57 assert sum(lst) == pytest.approx(1)
58
59 .. note::
60
61 Just like all other strategies, we called ``sums_to_one`` before passing it to |@given|. |st.composite| should be thought of as turning its decorated function into a function which returns a strategy when called. This is actually the same as existing strategies in Hypothesis; |st.integers| is really a function, which returns a strategy for integers when called.
62
63 Combining |st.composite| with parameters
64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65
66 You can add parameters to functions decorated with |st.composite|, including keyword-only arguments. These work as you would normally expect.
67
68 For instance, suppose we wanted to generalize our ``sums_to_one`` function to ``sums_to_n``. We can add a parameter ``n``:
69
70 .. code-block:: python
71
72 import pytest
73
74 from hypothesis import assume, given, strategies as st
75
76 @st.composite
77 def sums_to_n(draw, n=1): # <-- changed
78 lst = draw(st.lists(st.floats(0, 1), min_size=1))
79 assume(sum(lst) > 0)
80 return [f / sum(lst) * n for f in lst] # <-- changed
81
82 @given(sums_to_n(10))
83 def test(lst):
84 assert sum(lst) == pytest.approx(10)
85
86 And we could just as easily have made ``n`` a keyword-only argument instead:
87
88 .. code-block:: python
89
90 import pytest
91
92 from hypothesis import assume, given, strategies as st
93
94 @st.composite
95 def sums_to_n(draw, *, n=1): # <-- changed
96 lst = draw(st.lists(st.floats(0, 1), min_size=1))
97 assume(sum(lst) > 0)
98 return [f / sum(lst) * n for f in lst]
99
100 @given(sums_to_n(n=10)) # <-- changed
101 def test(lst):
102 assert sum(lst) == pytest.approx(10)
103
104 Dependent generation with |st.composite|
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
106
107 Another scenario where |st.composite| is useful is when generating a value that depends on a value from another strategy. For instance, suppose we wanted to generate two integers ``n1`` and ``n2`` with ``n1 <= n2``. We can do this using |st.composite|:
108
109 .. code-block:: python
110
111 @st.composite
112 def ordered_pairs(draw):
113 n1 = draw(st.integers())
114 n2 = draw(st.integers(min_value=n1))
115 return (n1, n2)
116
117 @given(ordered_pairs())
118 def test_pairs_are_ordered(pair):
119 n1, n2 = pair
120 assert n1 <= n2
121
122 .. note::
123
124 We could also have written this particular strategy as ``st.tuples(st.integers(), st.integers()).map(sorted)`` (see :doc:`/tutorial/adapting-strategies`). Some prefer this inline approach, while others prefer defining well-named helper functions with |st.composite|. Our suggestion is simply that you prioritize ease of understanding when choosing which to use.
125
126 Mixing data generation and test code
127 ------------------------------------
128
129 When using |st.composite|, you have to finish generating the entire input before running your test. But maybe you don't want to generate all of the input until you're sure some initial test assertions have passed. Or maybe you have some complicated control flow which makes it necessary to generate something in the middle of the test.
130
131 |st.data| lets you to do this. It's similar to |st.composite|, except it lets you mix test code and generation code.
132
133 .. note::
134
135 The downside of this power is that |st.data| is incompatible |@example|, and that Hypothesis cannot print a nice representation of values generated from |st.data| when reporting failing examples, because the draws are spread out. Where possible, prefer |st.composite| to |st.data|.
136
137 For instance, here's how we would write our earlier |st.composite| example using |st.data|:
138
139 .. code-block:: python
140
141 import pytest
142
143 from hypothesis import given, strategies as st
144
145 @given(st.data())
146 def test(data):
147 lst = data.draw(st.lists(st.floats(0.001, 1), min_size=1))
148 lst = [f / sum(lst) for f in lst]
149 # ignore floating point errors
150 assert sum(lst) == pytest.approx(1)