Debian Codegraph @

hypothesis-python/tests/quality/test_shrink_quality.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 from collections import Counter, OrderedDict, namedtuple
12 from fractions import Fraction
13 from functools import reduce
14
15 import pytest
16
17 import hypothesis.strategies as st
18 from hypothesis import HealthCheck, assume, given, settings
19 from hypothesis.strategies import (
20 booleans,
21 builds,
22 dictionaries,
23 fixed_dictionaries,
24 fractions,
25 frozensets,
26 integers,
27 just,
28 lists,
29 none,
30 sampled_from,
31 sets,
32 text,
33 tuples,
34 )
35
36 from tests.common.debug import minimal
37 from tests.common.utils import flaky
38
39
40 def test_integers_from_minimizes_leftwards():
41 assert minimal(integers(min_value=101)) == 101
42
43
44 def test_minimize_bounded_integers_to_zero():
45 assert minimal(integers(-10, 10)) == 0
46
47
48 def test_minimize_bounded_integers_to_positive():
49 zero = 0
50
51 def not_zero(x):
52 return x != zero
53
54 assert minimal(integers(-10, 10).filter(not_zero)) == 1
55
56
57 def test_minimal_fractions_1():
58 assert minimal(fractions()) == Fraction(0)
59
60
61 def test_minimal_fractions_2():
62 assert minimal(fractions(), lambda x: x >= 1) == Fraction(1)
63
64
65 def test_minimal_fractions_3():
66 assert minimal(lists(fractions()), lambda s: len(s) >= 5) == [Fraction(0)] * 5
67
68
69 def test_minimize_string_to_empty():
70 assert minimal(text()) == ""
71
72
73 def test_minimize_one_of():
74 for _ in range(100):
75 assert minimal(integers() | text() | booleans()) in (0, "", False)
76
77
78 def test_minimize_mixed_list():
79 mixed = minimal(lists(integers() | text()), lambda x: len(x) >= 10)
80 assert set(mixed).issubset({0, ""})
81
82
83 def test_minimize_longer_string():
84 assert minimal(text(), lambda x: len(x) >= 10) == "0" * 10
85
86
87 def test_minimize_longer_list_of_strings():
88 assert minimal(lists(text()), lambda x: len(x) >= 10) == [""] * 10
89
90
91 def test_minimize_3_set():
92 assert minimal(sets(integers()), lambda x: len(x) >= 3) in ({0, 1, 2}, {-1, 0, 1})
93
94
95 def test_minimize_3_set_of_tuples():
96 assert minimal(sets(tuples(integers())), lambda x: len(x) >= 2) == {(0,), (1,)}
97
98
99 def test_minimize_sets_of_sets():
100 elements = integers(1, 100)
101 size = 8
102 set_of_sets = minimal(sets(frozensets(elements), min_size=size))
103 assert frozenset() in set_of_sets
104 assert len(set_of_sets) == size
105 for s in set_of_sets:
106 if len(s) > 1:
107 assert any(s != t and t.issubset(s) for t in set_of_sets)
108
109
110 def test_minimize_sets_sampled_from():
111 assert minimal(st.sets(st.sampled_from(range(10)), min_size=3)) == {0, 1, 2}
112
113
114 def test_can_simplify_flatmap_with_bounded_left_hand_size():
115 assert (
116 minimal(booleans().flatmap(lambda x: lists(just(x))), lambda x: len(x) >= 10)
117 == [False] * 10
118 )
119
120
121 def test_can_simplify_across_flatmap_of_just():
122 assert minimal(integers().flatmap(just)) == 0
123
124
125 def test_can_simplify_on_right_hand_strategy_of_flatmap():
126 assert minimal(integers().flatmap(lambda x: lists(just(x)))) == []
127
128
129 @flaky(min_passes=5, max_runs=5)
130 def test_can_ignore_left_hand_side_of_flatmap():
131 assert (
132 minimal(integers().flatmap(lambda x: lists(integers())), lambda x: len(x) >= 10)
133 == [0] * 10
134 )
135
136
137 def test_can_simplify_on_both_sides_of_flatmap():
138 assert (
139 minimal(integers().flatmap(lambda x: lists(just(x))), lambda x: len(x) >= 10)
140 == [0] * 10
141 )
142
143
144 def test_flatmap_rectangles():
145 lengths = integers(min_value=0, max_value=10)
146
147 def lists_of_length(n):
148 return lists(sampled_from("ab"), min_size=n, max_size=n)
149
150 xs = minimal(
151 lengths.flatmap(lambda w: lists(lists_of_length(w))),
152 lambda x: ["a", "b"] in x,
153 settings=settings(database=None, max_examples=2000),
154 )
155 assert xs == [["a", "b"]]
156
157
158 @flaky(min_passes=5, max_runs=5)
159 @pytest.mark.parametrize("dict_class", [dict, OrderedDict])
160 def test_dictionary(dict_class):
161 assert (
162 minimal(dictionaries(keys=integers(), values=text(), dict_class=dict_class))
163 == dict_class()
164 )
165
166 x = minimal(
167 dictionaries(keys=integers(), values=text(), dict_class=dict_class),
168 lambda t: len(t) >= 3,
169 )
170 assert isinstance(x, dict_class)
171 assert set(x.values()) == {""}
172 for k in x:
173 if k < 0:
174 assert k + 1 in x
175 if k > 0:
176 assert k - 1 in x
177
178
179 def test_minimize_single_element_in_silly_large_int_range():
180 assert minimal(integers(-(2**256), 2**256), lambda x: x >= -(2**255)) == 0
181
182
183 def test_minimize_multiple_elements_in_silly_large_int_range():
184 actual = minimal(
185 lists(integers(-(2**256), 2**256)),
186 lambda x: len(x) >= 20,
187 settings(max_examples=10_000),
188 )
189 assert actual == [0] * 20
190
191
192 def test_minimize_multiple_elements_in_silly_large_int_range_min_is_not_dupe():
193 target = list(range(20))
194
195 actual = minimal(
196 lists(integers(0, 2**256)),
197 lambda x: (assume(len(x) >= 20) and all(x[i] >= target[i] for i in target)),
198 )
199 assert actual == target
200
201
202 def test_find_large_union_list():
203 size = 10
204
205 def large_mostly_non_overlapping(xs):
206 union = reduce(set.union, xs)
207 return len(union) >= size
208
209 result = minimal(
210 lists(sets(integers(), min_size=1), min_size=1),
211 large_mostly_non_overlapping,
212 )
213 assert len(result) == 1
214 union = reduce(set.union, result)
215 assert len(union) == size
216 assert max(union) == min(union) + len(union) - 1
217
218
219 @pytest.mark.parametrize("n", [0, 1, 10, 100, 1000])
220 @pytest.mark.parametrize(
221 "seed", [13878544811291720918, 15832355027548327468, 12901656430307478246]
222 )
223 def test_containment(n, seed):
224 iv = minimal(
225 tuples(lists(integers()), integers()),
226 lambda x: x[1] in x[0] and x[1] >= n,
227 )
228 assert iv == ([n], n)
229
230
231 def test_duplicate_containment():
232 ls, i = minimal(
233 tuples(lists(integers()), integers()),
234 lambda s: s[0].count(s[1]) > 1,
235 )
236 assert ls == [0, 0]
237 assert i == 0
238
239
240 @pytest.mark.parametrize("seed", [11, 28, 37])
241 def test_reordering_bytes(seed):
242 ls = minimal(lists(integers()), lambda x: sum(x) >= 10 and len(x) >= 3)
243 assert ls == sorted(ls)
244
245
246 def test_minimize_long_list():
247 assert (
248 minimal(lists(booleans(), min_size=50), lambda x: len(x) >= 70) == [False] * 70
249 )
250
251
252 def test_minimize_list_of_longish_lists():
253 size = 5
254 xs = minimal(
255 lists(lists(booleans())),
256 lambda x: len([t for t in x if any(t) and len(t) >= 2]) >= size,
257 )
258 assert len(xs) == size
259 for x in xs:
260 assert x == [False, True]
261
262
263 def test_minimize_list_of_fairly_non_unique_ints():
264 xs = minimal(lists(integers()), lambda x: len(set(x)) < len(x))
265 assert len(xs) == 2
266
267
268 def test_list_with_complex_sorting_structure():
269 xs = minimal(
270 lists(lists(booleans())),
271 lambda x: [list(reversed(t)) for t in x] > x and len(x) > 3,
272 )
273 assert len(xs) == 4
274
275
276 def test_list_with_wide_gap():
277 xs = minimal(lists(integers()), lambda x: x and (max(x) > min(x) + 10 > 0))
278 assert len(xs) == 2
279 xs.sort()
280 assert xs[1] == 11 + xs[0]
281
282
283 def test_minimize_namedtuple():
284 T = namedtuple("T", ("a", "b"))
285 tab = minimal(builds(T, integers(), integers()), lambda x: x.a < x.b)
286 assert tab.b == tab.a + 1
287
288
289 def test_minimize_dict():
290 tab = minimal(
291 fixed_dictionaries({"a": booleans(), "b": booleans()}),
292 lambda x: x["a"] or x["b"],
293 )
294 assert not (tab["a"] and tab["b"])
295
296
297 def test_minimize_list_of_sets():
298 assert minimal(
299 lists(sets(booleans())), lambda x: len(list(filter(None, x))) >= 3
300 ) == ([{False}] * 3)
301
302
303 def test_minimize_list_of_lists():
304 assert minimal(
305 lists(lists(integers())), lambda x: len(list(filter(None, x))) >= 3
306 ) == ([[0]] * 3)
307
308
309 def test_minimize_list_of_tuples():
310 xs = minimal(lists(tuples(integers(), integers())), lambda x: len(x) >= 2)
311 assert xs == [(0, 0), (0, 0)]
312
313
314 def test_minimize_multi_key_dicts():
315 assert minimal(dictionaries(keys=booleans(), values=booleans()), bool) == {
316 False: False
317 }
318
319
320 def test_multiple_empty_lists_are_independent():
321 x = minimal(lists(lists(none(), max_size=0)), lambda t: len(t) >= 2)
322 u, v = x
323 assert u is not v
324
325
326 def test_can_find_sets_unique_by_incomplete_data():
327 size = 5
328 ls = minimal(
329 lists(tuples(integers(), integers()), unique_by=max), lambda x: len(x) >= size
330 )
331 assert len(ls) == size
332 values = sorted(map(max, ls))
333 assert values[-1] - values[0] == size - 1
334 for u, _ in ls:
335 assert u <= 0
336
337
338 @pytest.mark.parametrize("n", range(10))
339 def test_lists_forced_near_top(n):
340 assert minimal(
341 lists(integers(), min_size=n, max_size=n + 2), lambda t: len(t) == n + 2
342 ) == [0] * (n + 2)
343
344
345 def test_sum_of_pair_int():
346 assert minimal(
347 tuples(integers(0, 1000), integers(0, 1000)), lambda x: sum(x) > 1000
348 ) == (1, 1000)
349
350
351 def test_sum_of_pair_float():
352 assert minimal(
353 tuples(st.floats(0, 1000), st.floats(0, 1000)), lambda x: sum(x) > 1000
354 ) == (1.0, 1000.0)
355
356
357 def test_sum_of_pair_mixed():
358 # check both orderings
359 assert minimal(
360 tuples(st.floats(0, 1000), st.integers(0, 1000)), lambda x: sum(x) > 1000
361 ) == (1.0, 1000)
362 assert minimal(
363 tuples(st.integers(0, 1000), st.floats(0, 1000)), lambda x: sum(x) > 1000
364 ) == (1, 1000.0)
365
366
367 def test_sum_of_pair_separated_int():
368 @st.composite
369 def separated_sum(draw):
370 n1 = draw(st.integers(0, 1000))
371 draw(st.text())
372 draw(st.booleans())
373 draw(st.integers())
374 n2 = draw(st.integers(0, 1000))
375 return (n1, n2)
376
377 assert minimal(separated_sum(), lambda x: sum(x) > 1000) == (1, 1000)
378
379
380 def test_sum_of_pair_separated_float():
381 @st.composite
382 def separated_sum(draw):
383 f1 = draw(st.floats(0, 1000))
384 draw(st.text())
385 draw(st.booleans())
386 draw(st.integers())
387 f2 = draw(st.floats(0, 1000))
388 return (f1, f2)
389
390 assert minimal(separated_sum(), lambda x: sum(x) > 1000) == (1, 1000)
391
392
393 def test_calculator_benchmark():
394 """This test comes from
395 https://github.com/jlink/shrinking-challenge/blob/main/challenges/calculator.md,
396 which is originally from Pike, Lee. "SmartCheck: automatic and efficient
397 counterexample reduction and generalization."
398 Proceedings of the 2014 ACM SIGPLAN symposium on Haskell. 2014.
399 """
400
401 expression = st.deferred(
402 lambda: st.one_of(
403 st.integers(),
404 st.tuples(st.just("+"), expression, expression),
405 st.tuples(st.just("/"), expression, expression),
406 )
407 )
408
409 def div_subterms(e):
410 if isinstance(e, int):
411 return True
412 if e[0] == "/" and e[-1] == 0:
413 return False
414 return div_subterms(e[1]) and div_subterms(e[2])
415
416 def evaluate(e):
417 if isinstance(e, int):
418 return e
419 elif e[0] == "+":
420 return evaluate(e[1]) + evaluate(e[2])
421 else:
422 assert e[0] == "/"
423 return evaluate(e[1]) // evaluate(e[2])
424
425 def is_failing(e):
426 assume(div_subterms(e))
427 try:
428 evaluate(e)
429 return False
430 except ZeroDivisionError:
431 return True
432
433 x = minimal(expression, is_failing)
434
435 assert x == ("/", 0, ("+", 0, 0))
436
437
438 def test_one_of_slip():
439 assert minimal(st.integers(101, 200) | st.integers(0, 100)) == 101
440
441
442 # this limit is only to avoid Unsatisfiable when searching for an initial
443 # counterexample in minimal, as we may generate a very large magnitude n.
444 @given(st.integers(-(2**32), 2**32))
445 @settings(max_examples=3, suppress_health_check=[HealthCheck.nested_given])
446 def test_perfectly_shrinks_integers(n):
447 if n >= 0:
448 assert minimal(st.integers(), lambda x: x >= n) == n
449 else:
450 assert minimal(st.integers(), lambda x: x <= n) == n
451
452
453 @given(st.integers(0, 20))
454 @settings(suppress_health_check=[HealthCheck.nested_given])
455 def test_lowering_together_positive(gap):
456 s = st.tuples(st.integers(0, 20), st.integers(0, 20))
457 assert minimal(s, lambda x: x[0] + gap == x[1]) == (0, gap)
458
459
460 @given(st.integers(-20, 0))
461 @settings(suppress_health_check=[HealthCheck.nested_given])
462 def test_lowering_together_negative(gap):
463 s = st.tuples(st.integers(-20, 0), st.integers(-20, 0))
464 assert minimal(s, lambda x: x[0] + gap == x[1]) == (0, gap)
465
466
467 @given(st.integers(-10, 10))
468 @settings(suppress_health_check=[HealthCheck.nested_given])
469 def test_lowering_together_mixed(gap):
470 s = st.tuples(st.integers(-10, 10), st.integers(-10, 10))
471 assert minimal(s, lambda x: x[0] + gap == x[1]) == (0, gap)
472
473
474 @given(st.integers(-10, 10))
475 @settings(suppress_health_check=[HealthCheck.nested_given])
476 def test_lowering_together_with_gap(gap):
477 s = st.tuples(st.integers(-10, 10), st.text(), st.floats(), st.integers(-10, 10))
478 assert minimal(s, lambda x: x[0] + gap == x[3]) == (0, "", 0.0, gap)
479
480
481 def test_run_length_encoding():
482 # extracted from https://github.com/HypothesisWorks/hypothesis/issues/4286,
483 # as well as our docs
484
485 def decode(table: list[tuple[int, str]]) -> str:
486 out = ""
487 for count, char in table:
488 out += count * char
489 return out
490
491 def encode(s: str) -> list[tuple[int, str]]:
492 count = 1
493 prev = ""
494 out = []
495
496 if not s:
497 return []
498
499 for char in s:
500 if char != prev:
501 if prev:
502 entry = (count, prev)
503 out.append(entry)
504 # BUG:
505 # count = 1
506 prev = char
507 else:
508 count += 1
509
510 entry = (count, char)
511 out.append(entry)
512 return out
513
514 assert minimal(st.text(), lambda s: decode(encode(s)) != s) == "001"
515
516
517 def test_minimize_duplicated_characters_within_a_choice():
518 # look for strings which have at least 3 of the same character, and also at
519 # least two different characters (to avoid the trivial shrink of replacing
520 # everything with "0" from working).
521
522 # we should test this for st.binary too, but it's difficult to get it
523 # to satisfy this precondition in the first place (probably worth improving
524 # our generation here to duplicate binary elements in generate_mutations_from)
525 assert (
526 minimal(
527 st.text(min_size=1),
528 lambda v: Counter(v).most_common()[0][1] > 2 and len(set(v)) > 1,
529 )
530 == "0001"
531 )
532
533
534 def test_nasty_string_shrinks():
535 # failures found via NASTY_STRINGS should shrink like normal
536 assert (
537 minimal(st.text(), lambda s: "π•Ώπ–π–Š" in s, settings=settings(max_examples=10000))
538 == "π•Ώπ–π–Š"
539 )
540
541
542 def test_bound5():
543 # redistribute_numeric_pairs should work for negative integers too
544 bounded_ints = st.lists(st.integers(-100, 0), max_size=1)
545
546 s = st.tuples(
547 bounded_ints,
548 bounded_ints,
549 bounded_ints,
550 bounded_ints,
551 bounded_ints,
552 )
553 assert minimal(s, lambda v: sum(sum(v, []), 0) < -150) == (
554 [],
555 [],
556 [],
557 [-51],
558 [-100],
559 )