Debian Codegraph @

hypothesis-python/tests/quality/test_discovery_ability.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 # -*- coding: utf-8 -*-
12 """Statistical tests over the forms of the distributions in the standard set of
13 definitions.
14
15 These tests all take the form of a classic hypothesis test with the null
16 hypothesis being that the probability of some event occurring when
17 drawing data from the distribution produced by some specifier is >=
18 REQUIRED_P
19 """
20
21 import collections
22 import math
23 import re
24
25 from hypothesis import HealthCheck, settings as Settings
26 from hypothesis.control import BuildContext
27 from hypothesis.errors import UnsatisfiedAssumption
28 from hypothesis.internal import reflection
29 from hypothesis.internal.conjecture.engine import ConjectureRunner
30 from hypothesis.strategies import (
31 binary,
32 booleans,
33 floats,
34 integers,
35 just,
36 lists,
37 one_of,
38 sampled_from,
39 sets,
40 text,
41 tuples,
42 )
43
44 from tests.common.utils import no_shrink
45 from tests.conjecture.common import interesting_origin
46
47
48 class HypothesisFalsified(AssertionError):
49 pass
50
51
52 def define_test(specifier, predicate, condition=None, p=0.5, suppress_health_check=()):
53 runs = 100
54 required_runs = int(runs * p)
55
56 def run_test():
57 if condition is None:
58
59 def _condition(x):
60 return True
61
62 condition_string = ""
63 else:
64 _condition = condition
65 condition_string = reflection.get_pretty_function_description(condition)
66 condition_string = re.compile("^lambda[^:]*:\\s*").sub("", condition_string)
67
68 def test_function(data):
69 with BuildContext(data, wrapped_test=None):
70 try:
71 value = data.draw(specifier)
72 except UnsatisfiedAssumption:
73 data.mark_invalid()
74 if not _condition(value):
75 data.mark_invalid()
76 if predicate(value):
77 data.mark_interesting(interesting_origin())
78
79 successes = 0
80 actual_runs = 0
81 for actual_runs in range(1, runs + 1):
82 # We choose the max_examples a bit larger than default so that we
83 # run at least 100 examples outside of the small example generation
84 # part of the generation phase.
85 runner = ConjectureRunner(
86 test_function,
87 settings=Settings(
88 max_examples=150,
89 phases=no_shrink,
90 suppress_health_check=suppress_health_check,
91 ),
92 )
93 runner.run()
94 if runner.interesting_examples:
95 successes += 1
96 if successes >= required_runs:
97 return
98
99 # If we reach a point where it's impossible to hit our target even
100 # if every remaining attempt were to succeed, give up early and
101 # report failure.
102 if (required_runs - successes) > (runs - actual_runs):
103 break
104
105 event = reflection.get_pretty_function_description(predicate)
106 if condition is not None:
107 event += "|"
108 event += condition_string
109
110 raise HypothesisFalsified(
111 f"P({event}) ~ {successes} / {actual_runs} = "
112 f"{successes / actual_runs:.2f} < {required_runs / runs:.2f}; "
113 "rejected"
114 )
115
116 return run_test
117
118
119 test_can_produce_zero = define_test(integers(), lambda x: x == 0)
120 test_can_produce_large_magnitude_integers = define_test(
121 integers(), lambda x: abs(x) > 1000
122 )
123 test_can_produce_large_positive_integers = define_test(integers(), lambda x: x > 1000)
124 test_can_produce_large_negative_integers = define_test(integers(), lambda x: x < -1000)
125
126
127 _factorials = {math.factorial(n) for n in range(9, 21)}
128
129
130 def is_factorial(n):
131 return abs(n) in _factorials
132
133
134 test_can_produce_large_factorial = define_test(
135 integers(), lambda n: n >= 50_000 and is_factorial(n), p=0.01
136 )
137 test_can_produce_above_large_factorial = define_test(
138 integers(), lambda n: n >= 50_000 and is_factorial(n - 1), p=0.01
139 )
140 test_can_produce_below_large_factorial = define_test(
141 integers(), lambda n: n >= 50_000 and is_factorial(n + 1), p=0.01
142 )
143 test_can_produce_large_factorial_negative = define_test(
144 integers(), lambda n: n <= -50_000 and is_factorial(n), p=0.01
145 )
146 test_can_produce_above_large_factorial_negative = define_test(
147 integers(), lambda n: n <= -50_000 and is_factorial(n - 1), p=0.01
148 )
149 test_can_produce_below_large_factorial_negative = define_test(
150 integers(), lambda n: n <= -50_000 and is_factorial(n + 1), p=0.01
151 )
152
153
154 test_can_produce_unstripped_strings = define_test(text(), lambda x: x != x.strip())
155 test_can_produce_stripped_strings = define_test(text(), lambda x: x == x.strip())
156 # The pass probability here was previously 0.5, but some intermediate changes
157 # while working on the ir tweaked the distribution and made it flaky. We can
158 # reevaluate this once things have settled down, and likely bump the pass
159 # probability back up.
160 test_can_produce_multi_line_strings = define_test(text(), lambda x: "\n" in x, p=0.35)
161 test_can_produce_ascii_strings = define_test(
162 text(), lambda x: all(ord(c) <= 127 for c in x)
163 )
164 test_can_produce_long_strings_with_no_ascii = define_test(
165 text(min_size=5), lambda x: all(ord(c) > 127 for c in x), p=0.1
166 )
167 test_can_produce_short_strings_with_some_non_ascii = define_test(
168 text(), lambda x: any(ord(c) > 127 for c in x), condition=lambda x: len(x) <= 3
169 )
170 test_can_produce_large_binary_strings = define_test(
171 binary(), lambda x: len(x) > 10, p=0.3
172 )
173 test_can_produce_positive_infinity = define_test(floats(), lambda x: x == math.inf)
174 test_can_produce_negative_infinity = define_test(floats(), lambda x: x == -math.inf)
175 test_can_produce_nan = define_test(floats(), math.isnan)
176 test_can_produce_floats_near_left = define_test(floats(0, 1), lambda t: t < 0.2)
177 test_can_produce_floats_near_right = define_test(floats(0, 1), lambda t: t > 0.8)
178 test_can_produce_floats_in_middle = define_test(floats(0, 1), lambda t: 0.2 <= t <= 0.8)
179 test_can_produce_long_lists = define_test(
180 lists(integers()), lambda x: len(x) >= 10, p=0.3
181 )
182 test_can_produce_short_lists = define_test(lists(integers()), lambda x: len(x) <= 10)
183 test_can_produce_the_same_int_twice = define_test(
184 lists(integers()), lambda t: len(set(t)) < len(t)
185 )
186
187
188 def distorted_value(x):
189 c = collections.Counter(x)
190 return min(c.values()) * 3 <= max(c.values())
191
192
193 test_sampled_from_large_number_can_mix = define_test(
194 lists(sampled_from(range(50)), min_size=50), lambda x: len(set(x)) >= 25
195 )
196 test_sampled_from_often_distorted = define_test(
197 lists(sampled_from(range(5))), distorted_value, condition=lambda x: len(x) >= 3
198 )
199 test_non_empty_subset_of_two_is_usually_large = define_test(
200 sets(sampled_from((1, 2))), lambda t: len(t) == 2
201 )
202 test_subset_of_ten_is_sometimes_empty = define_test(
203 sets(integers(1, 10)), lambda t: len(t) == 0
204 )
205
206 test_mostly_sensible_floats = define_test(floats(), lambda t: t + 1 > t)
207 test_mostly_largish_floats = define_test(
208 floats(), lambda t: t + 1 > 1, condition=lambda x: x > 0
209 )
210 test_ints_can_occasionally_be_really_large = define_test(
211 integers(), lambda t: t >= 2**63
212 )
213
214 test_mixing_is_sometimes_distorted = define_test(
215 lists(booleans() | tuples()),
216 lambda x: distorted_value(map(type, x)),
217 condition=lambda x: len(set(map(type, x))) == 2,
218 suppress_health_check=[HealthCheck.filter_too_much],
219 )
220
221 test_mixes_2_reasonably_often = define_test(
222 lists(booleans() | tuples()), lambda x: len(set(map(type, x))) > 1, condition=bool
223 )
224
225 test_partial_mixes_3_reasonably_often = define_test(
226 lists(booleans() | tuples() | just("hi")),
227 lambda x: 1 < len(set(map(type, x))) < 3,
228 condition=bool,
229 )
230
231 test_mixes_not_too_often = define_test(
232 lists(booleans() | tuples()), lambda x: len(set(map(type, x))) == 1, condition=bool
233 )
234
235 test_integers_are_usually_non_zero = define_test(integers(), lambda x: x != 0)
236 test_integers_are_sometimes_zero = define_test(integers(), lambda x: x == 0)
237 test_integers_are_often_small = define_test(integers(), lambda x: abs(x) <= 100)
238 test_integers_are_often_small_but_not_that_small = define_test(
239 integers(), lambda x: 50 <= abs(x) <= 255
240 )
241
242
243 # This series of tests checks that the one_of() strategy flattens branches
244 # correctly. We assert that the probability of any branch is >= 0.1,
245 # approximately (1/8 = 0.125), regardless of how heavily nested it is in the
246 # strategy.
247
248 # This first strategy chooses an integer between 0 and 7 (inclusive).
249 one_of_nested_strategy = one_of(
250 just(0),
251 one_of(
252 just(1), just(2), one_of(just(3), just(4), one_of(just(5), just(6), just(7)))
253 ),
254 )
255
256 for i in range(8):
257 exec(f"""test_one_of_flattens_branches_{i} = define_test(
258 one_of_nested_strategy, lambda x: x == {i}
259 )""")
260
261
262 xor_nested_strategy = just(0) | (
263 just(1) | just(2) | (just(3) | just(4) | (just(5) | just(6) | just(7)))
264 )
265
266 for i in range(8):
267 exec(f"""test_xor_flattens_branches_{i} = define_test(
268 xor_nested_strategy, lambda x: x == {i}
269 )""")
270
271
272 # This strategy tests interactions with `map()`. They generate integers
273 # from the set {1, 4, 6, 16, 20, 24, 28, 32}.
274 def double(x):
275 return x * 2
276
277
278 one_of_nested_strategy_with_map = one_of(
279 just(1),
280 one_of(
281 (just(2) | just(3)).map(double),
282 one_of(
283 (just(4) | just(5)).map(double),
284 one_of((just(6) | just(7) | just(8)).map(double)),
285 ).map(double),
286 ),
287 )
288
289 for i in (1, 4, 6, 16, 20, 24, 28, 32):
290 exec(f"""test_one_of_flattens_map_branches_{i} = define_test(
291 one_of_nested_strategy_with_map, lambda x: x == {i}
292 )""")
293
294
295 # This strategy tests interactions with `flatmap()`. It generates lists
296 # of length 0-7 (inclusive) in which every element is `None`.
297 one_of_nested_strategy_with_flatmap = just(None).flatmap(
298 lambda x: one_of(
299 just([x] * 0),
300 just([x] * 1),
301 one_of(
302 just([x] * 2),
303 just([x] * 3),
304 one_of(just([x] * 4), just([x] * 5), one_of(just([x] * 6), just([x] * 7))),
305 ),
306 )
307 )
308
309 for i in range(8):
310 exec(f"""test_one_of_flattens_flatmap_branches_{i} = define_test(
311 one_of_nested_strategy_with_flatmap, lambda x: len(x) == {i}
312 )""")
313
314
315 xor_nested_strategy_with_flatmap = just(None).flatmap(
316 lambda x: (
317 just([x] * 0)
318 | just([x] * 1)
319 | (
320 just([x] * 2)
321 | just([x] * 3)
322 | (just([x] * 4) | just([x] * 5) | (just([x] * 6) | just([x] * 7)))
323 )
324 )
325 )
326
327 for i in range(8):
328 exec(f"""test_xor_flattens_flatmap_branches_{i} = define_test(
329 xor_nested_strategy_with_flatmap, lambda x: len(x) == {i}
330 )""")
331
332
333 # This strategy tests interactions with `filter()`. It generates the even
334 # integers {0, 2, 4, 6} in equal measures.
335 one_of_nested_strategy_with_filter = one_of(
336 just(0),
337 just(1),
338 one_of(just(2), just(3), one_of(just(4), just(5), one_of(just(6), just(7)))),
339 ).filter(lambda x: x % 2 == 0)
340
341 for i in range(4):
342 exec(f"""test_one_of_flattens_filter_branches_{i} = define_test(
343 one_of_nested_strategy_with_filter, lambda x: x == 2 * {i}
344 )""")
345
346
347 test_long_duplicates_strings = define_test(
348 tuples(text(), text()), lambda s: len(s[0]) >= 5 and s[0] == s[1]
349 )
350 test_can_produce_nasty_strings = define_test(
351 text(), lambda s: s in {"NaN", "Inf", "undefined"}, p=0.01
352 )