Debian Codegraph @

hypothesis-python/tests/cover/test_composite.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import typing
12
13 import pytest
14
15 from hypothesis import HealthCheck, assume, given, settings, strategies as st
16 from hypothesis.errors import (
17 HypothesisDeprecationWarning,
18 HypothesisWarning,
19 InvalidArgument,
20 )
21
22 from tests.common.debug import minimal
23 from tests.common.utils import flaky
24
25
26 @st.composite
27 def badly_draw_lists(draw, m=0):
28 length = draw(st.integers(m, m + 10))
29 return [draw(st.integers()) for _ in range(length)]
30
31
32 def test_simplify_draws():
33 assert minimal(badly_draw_lists(), lambda x: len(x) >= 3) == [0] * 3
34
35
36 def test_can_pass_through_arguments():
37 assert minimal(badly_draw_lists(5)) == [0] * 5
38 assert minimal(badly_draw_lists(m=6)) == [0] * 6
39
40
41 @st.composite
42 def draw_ordered_with_assume(draw):
43 x = draw(st.floats())
44 y = draw(st.floats())
45 assume(x < y)
46 return (x, y)
47
48
49 @given(draw_ordered_with_assume())
50 @settings(suppress_health_check=[HealthCheck.filter_too_much])
51 def test_can_assume_in_draw(xy):
52 assert xy[0] < xy[1]
53
54
55 def test_uses_definitions_for_reprs():
56 assert repr(badly_draw_lists()) == "badly_draw_lists()"
57 assert repr(badly_draw_lists(1)) == "badly_draw_lists(m=1)"
58 assert repr(badly_draw_lists(m=1)) == "badly_draw_lists(m=1)"
59
60
61 def test_errors_given_default_for_draw():
62 with pytest.raises(InvalidArgument):
63
64 @st.composite
65 def foo(x=None):
66 pass
67
68
69 def test_errors_given_function_of_no_arguments():
70 with pytest.raises(InvalidArgument):
71
72 @st.composite
73 def foo():
74 pass
75
76
77 def test_errors_given_kwargs_only():
78 with pytest.raises(InvalidArgument):
79
80 @st.composite
81 def foo(**kwargs):
82 pass
83
84
85 def test_warning_given_no_drawfn_call():
86 with pytest.warns(HypothesisDeprecationWarning):
87
88 @st.composite
89 def foo(_):
90 return "bar"
91
92
93 def test_can_use_pure_args():
94 @st.composite
95 def stuff(*args):
96 return args[0](st.sampled_from(args[1:]))
97
98 assert minimal(stuff(1, 2, 3, 4, 5)) == 1
99
100
101 def test_composite_of_lists():
102 @st.composite
103 def f(draw):
104 return draw(st.integers()) + draw(st.integers())
105
106 assert minimal(st.lists(f()), lambda x: len(x) >= 10) == [0] * 10
107
108
109 @flaky(min_passes=2, max_runs=5)
110 def test_can_shrink_matrices_with_length_param():
111 @st.composite
112 def matrix(draw):
113 rows = draw(st.integers(1, 10))
114 columns = draw(st.integers(1, 10))
115 return [
116 [draw(st.integers(0, 10000)) for _ in range(columns)] for _ in range(rows)
117 ]
118
119 def transpose(m):
120 return [[row[i] for row in m] for i in range(len(m[0]))]
121
122 def is_square(m):
123 return len(m) == len(m[0])
124
125 value = minimal(matrix(), lambda m: is_square(m) and transpose(m) != m)
126 assert len(value) == 2
127 assert len(value[0]) == 2
128 assert sorted(value[0] + value[1]) == [0, 0, 0, 1]
129
130
131 class MyList(list):
132 pass
133
134
135 @given(st.data(), st.lists(st.integers()).map(MyList))
136 def test_does_not_change_arguments(data, ls):
137 # regression test for issue #1017 or other argument mutation
138 @st.composite
139 def strat(draw, arg):
140 draw(st.none())
141 return arg
142
143 ex = data.draw(strat(ls))
144 assert ex is ls
145
146
147 class ClsWithStrategyMethods:
148 @classmethod
149 @st.composite
150 def st_classmethod_then_composite(draw, cls):
151 return draw(st.integers(0, 10))
152
153 @st.composite
154 @classmethod
155 def st_composite_then_classmethod(draw, cls):
156 return draw(st.integers(0, 10))
157
158 @staticmethod
159 @st.composite
160 def st_staticmethod_then_composite(draw):
161 return draw(st.integers(0, 10))
162
163 @st.composite
164 @staticmethod
165 def st_composite_then_staticmethod(draw):
166 return draw(st.integers(0, 10))
167
168 @st.composite
169 def st_composite_method(draw, self):
170 return draw(st.integers(0, 10))
171
172
173 @given(st.data())
174 def test_applying_composite_decorator_to_methods(data):
175 instance = ClsWithStrategyMethods()
176 for strategy in [
177 ClsWithStrategyMethods.st_classmethod_then_composite(),
178 ClsWithStrategyMethods.st_composite_then_classmethod(),
179 ClsWithStrategyMethods.st_staticmethod_then_composite(),
180 ClsWithStrategyMethods.st_composite_then_staticmethod(),
181 instance.st_classmethod_then_composite(),
182 instance.st_composite_then_classmethod(),
183 instance.st_staticmethod_then_composite(),
184 instance.st_composite_then_staticmethod(),
185 instance.st_composite_method(),
186 ]:
187 x = data.draw(strategy)
188 assert isinstance(x, int)
189 assert 0 <= x <= 10
190
191
192 def test_drawfn_cannot_be_instantiated():
193 with pytest.raises(TypeError):
194 st.DrawFn()
195
196
197 def test_warns_on_strategy_annotation():
198 with pytest.warns(HypothesisWarning, match="Return-type annotation") as w:
199
200 @st.composite
201 def my_integers(draw: st.DrawFn) -> st.SearchStrategy[int]:
202 return draw(st.integers())
203
204 assert len(w.list) == 1
205 assert w.list[0].filename == __file__ # check stacklevel points to user code
206
207
208 def test_composite_allows_overload_without_draw():
209 # See https://github.com/HypothesisWorks/hypothesis/issues/3970
210 @st.composite
211 @typing.overload
212 def overloaded(draw: st.DrawFn, *, x: int) -> typing.Literal[True]: ...
213
214 @st.composite
215 @typing.overload
216 def overloaded(draw: st.DrawFn, *, x: str) -> typing.Literal[False]: ...
217
218 @st.composite
219 def overloaded(draw: st.DrawFn, *, x: int | str) -> bool:
220 return draw(st.just(isinstance(x, int)))