Debian Codegraph @

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

raw
1 Adapting strategies
2 ===================
3
4 This page discusses ways to adapt strategies to your needs, either by transforming them inline with |.map|, or filtering out unwanted inputs with |.filter| and |assume|.
5
6 Mapping strategy inputs
7 -----------------------
8
9 Sometimes you want to apply a simple transformation to a strategy. For instance, we know that we can generate lists of integers with ``lists(integers())``. But maybe we wanted to instead generate sorted lists. We could use an inline |.map| to achieve this:
10
11 .. code-block:: pycon
12
13 >>> lists(integers()).map(sorted).example()
14 [-25527, -24245, -93, -70, -7, 0, 39, 65, 112, 6189, 19469, 32526, 1566924430]
15
16 In general, ``strategy.map(f)`` returns a new strategy which transforms all the examples generated by ``strategy`` by calling ``f`` on them.
17
18 Filtering strategy inputs
19 -------------------------
20
21 Many strategies in Hypothesis offer some control over the kinds of values that get generated. For instance, ``integers(min_value=0)`` generates positive integers, and ``integers(100, 200)`` generates integers between ``100`` and ``200``.
22
23 Sometimes, you need more control than this. The inputs from a strategy may not match exactly what you need, and you just need to filter out a few bad cases.
24
25 For instance, suppose we have written a simple test involving the modulo operator ``%``:
26
27 .. code-block:: python
28
29 from hypothesis import given, strategies as st
30
31 @given(st.integers(), st.integers())
32 def test_remainder_magnitude(a, b):
33 # the remainder after division is always less than
34 # the divisor
35 assert abs(a % b) < abs(b)
36
37 Hypothesis will quickly report a failure for this test: ``ZeroDivisionError: integer modulo by zero``. Just like division, modulo isn't defined for 0. The case of ``b == 0`` isn't interesting for the test, and we would like to get rid of it.
38
39 The best way to do this is with the |.filter| method:
40
41 .. code-block:: python
42
43 from hypothesis import assume, given, strategies as st
44
45 @given(st.integers(), st.integers().filter(lambda n: n != 0))
46 def test_remainder_magnitude(a, b):
47 # b is guaranteed to be nonzero here, thanks to the filter
48 assert abs(a % b) < abs(b)
49
50 This test now passes cleanly.
51
52 Calling |.filter| on a strategy creates a new strategy with that filter applied at generation-time. For instance, ``integers().filter(lambda n: n != 0)`` is a strategy which generates nonzero integers.
53
54 Assuming away test cases
55 ------------------------
56
57 |.filter| lets you filter test inputs from a single strategy. Hypothesis also provides an |assume| function for when you need to filter an entire test case, based on an arbitrary condition.
58
59 The |assume| function skips test cases where some condition evaluates to ``True``. You can use it anywhere in your test. We could have expressed our |.filter| example above using |assume| as well:
60
61 .. code-block:: python
62
63 from hypothesis import assume, given, strategies as st
64
65 @given(st.integers(), st.integers())
66 def test_remainder_magnitude(a, b):
67 assume(b != 0)
68 # b will be nonzero here
69 assert abs(a % b) < abs(b)
70
71 |assume| vs |.filter|
72 ~~~~~~~~~~~~~~~~~~~~~
73
74 Where possible, you should use |.filter|. Hypothesis can often rewrite simple filters into more efficient sampling methods than rejection sampling, and will retry filters several times instead of aborting the entire test case (as with |assume|).
75
76 For more complex relationships that can't be expressed with |.filter|, use |assume|.
77
78 Here's an example of a test where we want to filter out two different types of examples:
79
80 .. code-block:: python
81
82 from hypothesis import assume, given, strategies as st
83
84 @given(st.integers(), st.integers())
85 def test_floor_division_lossless_when_b_divides_a(a, b):
86 # we want to assume that:
87 # * b is nonzero, and
88 # * b divides a
89 assert (a // b) * b == a
90
91 We could start by using |assume| for both:
92
93 .. code-block:: python
94
95 from hypothesis import assume, given, strategies as st
96
97 @given(st.integers(), st.integers())
98 def test_floor_division_lossless_when_b_divides_a(a, b):
99 assume(b != 0)
100 assume(a % b == 0)
101 assert (a // b) * b == a
102
103 And then notice that the ``b != 0`` condition can be moved into the strategy definition as a |.filter| call:
104
105 .. code-block:: python
106
107 from hypothesis import assume, given, strategies as st
108
109 @given(st.integers(), st.integers().filter(lambda n: n != 0))
110 def test_floor_division_lossless_when_b_divides_a(a, b):
111 assume(a % b == 0)
112 assert (a // b) * b == a
113
114 However, the ``a % b == 0`` condition has to stay as an |assume|, because it expresses a more complicated relationship between ``a`` and ``b``.
115
116 |assume| vs early-returning
117 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
118
119 One other way we could have avoided the divide-by-zero error inside the test function is to early-return when ``b == 0``:
120
121 .. code-block:: python
122
123 from hypothesis import assume, given, strategies as st
124
125 @given(st.integers(), st.integers())
126 def test_remainder_magnitude(a, b):
127 if b == 0:
128 # bad plan - test "passes" without checking anything!
129 return
130 assert abs(a % b) < abs(b)
131
132 While this would have avoided the divide-by-zero, early-returning is not the same as using |assume|. With |assume|, Hypothesis knows that a test case has been filtered out, and will not count it towards the |max_examples| limit. In contrast, early-returns are counted as a passing test, even though the assertions didn't run! In more complicted cases, this could end up testing your code less than you expect, because many test cases get discarded without Hypothesis knowing about it.
133
134 In addition, |assume| lets you skip the test case at any point in the test, even inside arbitrarily deep nestings of functions.