Debian Codegraph @

hypothesis-python/tests/cover/test_validation.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 functools
12 import warnings
13
14 import pytest
15
16 from hypothesis import find, given, strategies as st
17 from hypothesis.errors import HypothesisWarning, InvalidArgument
18 from hypothesis.internal.validation import check_type
19 from hypothesis.strategies import (
20 SearchStrategy as ActualSearchStrategy,
21 binary,
22 booleans,
23 data,
24 dictionaries,
25 floats,
26 frozensets,
27 integers,
28 lists,
29 nothing,
30 recursive,
31 sets,
32 text,
33 )
34 from hypothesis.strategies._internal.strategies import check_strategy
35
36 from tests.common.debug import check_can_generate_examples, find_any
37 from tests.common.utils import fails_with
38
39
40 def test_errors_when_given_varargs():
41 @given(integers())
42 def has_varargs(*args):
43 pass
44
45 with pytest.raises(InvalidArgument) as e:
46 has_varargs()
47 assert "varargs" in e.value.args[0]
48
49
50 def test_varargs_without_positional_arguments_allowed():
51 @given(somearg=integers())
52 def has_varargs(somearg, *args):
53 pass
54
55
56 def test_errors_when_given_varargs_and_kwargs_with_positional_arguments():
57 @given(integers())
58 def has_varargs(*args, **kw):
59 pass
60
61 with pytest.raises(InvalidArgument) as e:
62 has_varargs()
63 assert "varargs" in e.value.args[0]
64
65
66 def test_varargs_and_kwargs_without_positional_arguments_allowed():
67 @given(somearg=integers())
68 def has_varargs(*args, **kw):
69 pass
70
71
72 def test_bare_given_errors():
73 @given()
74 def test():
75 pass
76
77 with pytest.raises(InvalidArgument):
78 test()
79
80
81 def test_errors_on_unwanted_kwargs():
82 @given(hello=int, world=int)
83 def greet(world):
84 pass
85
86 with pytest.raises(InvalidArgument):
87 greet()
88
89
90 def test_errors_on_too_many_positional_args():
91 @given(integers(), int, int)
92 def foo(x, y):
93 pass
94
95 with pytest.raises(InvalidArgument):
96 foo()
97
98
99 def test_errors_on_any_varargs():
100 @given(integers())
101 def oops(*args):
102 pass
103
104 with pytest.raises(InvalidArgument):
105 oops()
106
107
108 def test_can_put_arguments_in_the_middle():
109 @given(y=integers())
110 def foo(x, y, z):
111 pass
112
113 foo(1, 2)
114
115
116 def test_float_ranges():
117 with pytest.raises(InvalidArgument):
118 check_can_generate_examples(floats(float("nan"), 0))
119 with pytest.raises(InvalidArgument):
120 check_can_generate_examples(floats(1, -1))
121
122
123 def test_float_range_and_allow_nan_cannot_both_be_enabled():
124 with pytest.raises(InvalidArgument):
125 check_can_generate_examples(floats(min_value=1, allow_nan=True))
126 with pytest.raises(InvalidArgument):
127 check_can_generate_examples(floats(max_value=1, allow_nan=True))
128
129
130 def test_float_finite_range_and_allow_infinity_cannot_both_be_enabled():
131 with pytest.raises(InvalidArgument):
132 check_can_generate_examples(floats(0, 1, allow_infinity=True))
133
134
135 def test_does_not_error_if_min_size_is_bigger_than_default_size():
136 find_any(lists(integers(), min_size=50))
137 find_any(sets(integers(), min_size=50))
138 find_any(frozensets(integers(), min_size=50))
139 find_any(lists(integers(), min_size=50, unique=True))
140
141
142 def test_list_unique_and_unique_by_cannot_both_be_enabled():
143 @given(lists(integers(), unique=True, unique_by=lambda x: x))
144 def boom(t):
145 pass
146
147 with pytest.raises(InvalidArgument) as e:
148 boom()
149 assert "unique " in e.value.args[0]
150 assert "unique_by" in e.value.args[0]
151
152
153 def test_min_before_max():
154 with pytest.raises(InvalidArgument):
155 integers(min_value=1, max_value=0).validate()
156
157
158 def test_filter_validates():
159 with pytest.raises(InvalidArgument):
160 integers(min_value=1, max_value=0).filter(bool).validate()
161
162
163 def test_recursion_validates_base_case():
164 with pytest.raises(InvalidArgument):
165 recursive(integers(min_value=1, max_value=0), lists).validate()
166
167
168 def test_recursion_validates_recursive_step():
169 with pytest.raises(InvalidArgument):
170 recursive(integers(), lambda x: lists(x, min_size=3, max_size=1)).validate()
171
172
173 @fails_with(InvalidArgument)
174 @given(x=integers())
175 def test_stuff_keyword(x=1): # noqa: PT028
176 pass
177
178
179 @fails_with(InvalidArgument)
180 @given(integers())
181 def test_stuff_positional(x=1): # noqa: PT028
182 pass
183
184
185 @fails_with(InvalidArgument)
186 @given(integers(), integers())
187 def test_too_many_positional(x):
188 pass
189
190
191 def test_given_warns_on_use_of_non_strategies():
192 @given(bool)
193 def test(x):
194 pass
195
196 with pytest.raises(InvalidArgument):
197 test()
198
199
200 def test_given_warns_when_mixing_positional_with_keyword():
201 @given(booleans(), y=booleans())
202 def test(x, y):
203 pass
204
205 with pytest.raises(InvalidArgument):
206 test()
207
208
209 def test_cannot_find_non_strategies():
210 with pytest.raises(InvalidArgument):
211 find(bool, bool)
212
213
214 @pytest.mark.parametrize(
215 "strategy",
216 [
217 functools.partial(lists, elements=integers()),
218 functools.partial(dictionaries, keys=integers(), values=integers()),
219 text,
220 binary,
221 ],
222 )
223 @pytest.mark.parametrize("min_size,max_size", [(0, "10"), ("0", 10)])
224 def test_valid_sizes(strategy, min_size, max_size):
225 @given(strategy(min_size=min_size, max_size=max_size))
226 def test(x):
227 pass
228
229 with pytest.raises(InvalidArgument):
230 test()
231
232
233 def test_check_type_with_tuple_of_length_two():
234 def type_checker(x):
235 check_type((int, str), x, "x")
236
237 type_checker(1)
238 type_checker("1")
239 with pytest.raises(InvalidArgument, match="Expected one of int, str but got "):
240 type_checker(1.0)
241
242
243 def test_validation_happens_on_draw():
244 @given(data())
245 def test(data):
246 data.draw(integers().flatmap(lambda _: lists(nothing(), min_size=1)))
247
248 with pytest.raises(InvalidArgument, match="has no values"):
249 test()
250
251
252 class SearchStrategy:
253 """Not the SearchStrategy type you were looking for."""
254
255
256 def check_type_(*args):
257 return check_type(*args)
258
259
260 def test_check_type_suggests_check_strategy():
261 check_type_(SearchStrategy, SearchStrategy(), "this is OK")
262 with pytest.raises(AssertionError, match="use check_strategy instead"):
263 check_type_(ActualSearchStrategy, None, "SearchStrategy assertion")
264
265
266 def check_strategy_(*args):
267 return check_strategy(*args)
268
269
270 def test_check_strategy_might_suggest_sampled_from():
271 with pytest.raises(InvalidArgument) as excinfo:
272 check_strategy_("not a strategy")
273 assert "sampled_from" not in str(excinfo.value)
274 with pytest.raises(InvalidArgument, match="such as st\\.sampled_from"):
275 check_strategy_([1, 2, 3])
276 with pytest.raises(InvalidArgument, match="such as st\\.sampled_from"):
277 check_strategy_((1, 2, 3))
278 check_strategy_(integers(), "passes for our custom coverage check")
279
280
281 @pytest.mark.parametrize("codec", ["ascii", "utf-8"])
282 def test_warn_on_strings_matching_common_codecs(codec):
283 with pytest.warns(
284 HypothesisWarning,
285 match=f"it seems like you are trying to use the codec {codec!r}",
286 ):
287
288 @given(st.text(codec))
289 def f(s):
290 pass
291
292 f()
293
294 # if we reorder, it doesn't warn anymore
295 with warnings.catch_warnings():
296 warnings.simplefilter("error")
297
298 @given(st.text(codec[1:] + codec[:1]))
299 def f(s):
300 pass
301
302 f()