Debian Codegraph @

hypothesis-python/tests/conjecture/test_engine.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 enum
12 import re
13 import time
14 from random import Random
15 from unittest.mock import Mock
16
17 import pytest
18
19 from hypothesis import (
20 HealthCheck,
21 Phase,
22 Verbosity,
23 assume,
24 given,
25 settings,
26 strategies as st,
27 )
28 from hypothesis.database import (
29 InMemoryExampleDatabase,
30 choices_from_bytes,
31 choices_to_bytes,
32 )
33 from hypothesis.errors import FailedHealthCheck, FlakyStrategyDefinition
34 from hypothesis.internal.compat import PYPY, bit_count, int_from_bytes
35 from hypothesis.internal.conjecture import engine as engine_module
36 from hypothesis.internal.conjecture.data import ConjectureData, Overrun, Status
37 from hypothesis.internal.conjecture.datatree import compute_max_children
38 from hypothesis.internal.conjecture.engine import (
39 INVALID_PER_VALID,
40 INVALID_THRESHOLD_BASE,
41 MIN_TEST_CALLS,
42 ConjectureRunner,
43 ExitReason,
44 HealthCheckState,
45 RunIsComplete,
46 )
47 from hypothesis.internal.conjecture.junkdrawer import startswith
48 from hypothesis.internal.conjecture.pareto import DominanceRelation, dominance
49 from hypothesis.internal.conjecture.shrinker import Shrinker, ShrinkPass
50 from hypothesis.internal.coverage import IN_COVERAGE_TESTS
51
52 from tests.common.debug import minimal
53 from tests.common.strategies import SLOW, HardToShrink
54 from tests.common.utils import no_shrink, skipif_time_unpatched
55 from tests.conjecture.common import (
56 SOME_LABEL,
57 buffer_size_limit,
58 interesting_origin,
59 nodes,
60 run_to_nodes,
61 shrinking_from,
62 )
63
64 runner_settings = settings(
65 max_examples=100, database=None, suppress_health_check=list(HealthCheck)
66 )
67
68
69 def test_non_cloneable_intervals():
70 @run_to_nodes
71 def nodes(data):
72 data.draw_bytes(10, 10)
73 data.draw_bytes(9, 9)
74 data.mark_interesting(interesting_origin())
75
76 assert tuple(n.value for n in nodes) == (bytes(10), bytes(9))
77
78
79 def test_deletable_draws():
80 @run_to_nodes
81 def nodes(data):
82 while True:
83 x = data.draw_bytes(2, 2)
84 if x[0] == 255:
85 data.mark_interesting(interesting_origin())
86
87 assert tuple(n.value for n in nodes) == (b"\xff\x00",)
88
89
90 def test_can_load_data_from_a_corpus():
91 key = b"hi there"
92 db = InMemoryExampleDatabase()
93 value = b"=\xc3\xe4l\x81\xe1\xc2H\xc9\xfb\x1a\xb6bM\xa8\x7f"
94 db.save(key, choices_to_bytes([value]))
95
96 def f(data):
97 if data.draw_bytes() == value:
98 data.mark_interesting(interesting_origin())
99
100 runner = ConjectureRunner(f, settings=settings(database=db), database_key=key)
101 runner.run()
102 (last_data,) = runner.interesting_examples.values()
103 assert last_data.choices == (value,)
104 assert len(list(db.fetch(key))) == 1
105
106
107 def slow_shrinker():
108 strat = HardToShrink()
109
110 def accept(data):
111 if data.draw(strat):
112 data.mark_interesting(interesting_origin())
113
114 return accept
115
116
117 @pytest.mark.parametrize("n", [1, 5])
118 def test_terminates_shrinks(n, monkeypatch):
119 db = InMemoryExampleDatabase()
120
121 def generate_new_examples(self):
122 self.cached_test_function((255,) * 1000)
123
124 monkeypatch.setattr(
125 ConjectureRunner, "generate_new_examples", generate_new_examples
126 )
127 monkeypatch.setattr(engine_module, "MAX_SHRINKS", n)
128
129 runner = ConjectureRunner(
130 slow_shrinker(),
131 settings=settings(max_examples=5000, database=db),
132 random=Random(0),
133 database_key=b"key",
134 )
135 runner.run()
136 (last_data,) = runner.interesting_examples.values()
137 assert last_data.status == Status.INTERESTING
138 assert runner.exit_reason == ExitReason.max_shrinks
139 assert runner.shrinks == n
140 in_db = set(db.data[runner.secondary_key])
141 assert len(in_db) == n
142
143
144 def test_detects_flakiness():
145 failed_once = False
146 count = 0
147
148 def tf(data):
149 nonlocal count, failed_once
150 data.draw_bytes(1, 1)
151 count += 1
152 if not failed_once:
153 failed_once = True
154 data.mark_interesting(interesting_origin())
155
156 runner = ConjectureRunner(tf)
157 runner.run()
158 assert runner.exit_reason == ExitReason.flaky
159 assert count == MIN_TEST_CALLS + 1
160
161
162 def recur(i, data):
163 if i >= 1:
164 recur(i - 1, data)
165
166
167 @pytest.mark.skipif(PYPY, reason="stack tricks only work reliably on CPython")
168 @pytest.mark.skipif(
169 IN_COVERAGE_TESTS, reason="flaky under coverage instrumentation? see #4391"
170 )
171 def test_recursion_error_is_not_flaky():
172 def tf(data):
173 i = data.draw_integer(0, 2**16 - 1)
174 try:
175 recur(i, data)
176 except RecursionError:
177 data.mark_interesting(interesting_origin())
178
179 runner = ConjectureRunner(tf, settings=settings(derandomize=True))
180 runner.run()
181 assert runner.exit_reason == ExitReason.finished
182
183
184 def test_variadic_draw():
185 def draw_list(data):
186 result = []
187 while True:
188 data.start_span(SOME_LABEL)
189 n = data.draw_integer(0, 2)
190 if n:
191 result.append(data.draw_bytes(n, n))
192 data.stop_span()
193 if not n:
194 break
195 return result
196
197 @run_to_nodes
198 def nodes(data):
199 if any(all(d) for d in draw_list(data)):
200 data.mark_interesting(interesting_origin())
201
202 assert tuple(n.value for n in nodes) == (1, b"\x01", 0)
203
204
205 def test_draw_to_overrun():
206 @run_to_nodes
207 def nodes(data):
208 d = (data.draw_bytes(1, 1)[0] - 8) & 0xFF
209 data.draw_bytes(128 * d, 128 * d)
210 if d >= 2:
211 data.mark_interesting(interesting_origin())
212
213 assert tuple(n.value for n in nodes) == (bytes([10]),) + (bytes(128 * 2),)
214
215
216 def test_can_navigate_to_a_valid_example():
217 def f(data):
218 i = int_from_bytes(data.draw_bytes(2, 2))
219 data.draw_bytes(i, i)
220 data.mark_interesting(interesting_origin())
221
222 runner = ConjectureRunner(f, settings=settings(max_examples=5000, database=None))
223 with buffer_size_limit(4):
224 runner.run()
225 assert runner.interesting_examples
226
227
228 def test_stops_after_max_examples_when_reading():
229 key = b"key"
230
231 db = InMemoryExampleDatabase()
232 for i in range(10):
233 db.save(key, bytes([i]))
234
235 seen = []
236
237 def f(data):
238 seen.append(data.draw_bytes(1, 1))
239
240 runner = ConjectureRunner(
241 f, settings=settings(max_examples=1, database=db), database_key=key
242 )
243 runner.run()
244 assert len(seen) == 1
245
246
247 def test_stops_after_max_examples_when_generating():
248 seen = []
249
250 def f(data):
251 seen.append(data.draw_bytes(1, 1))
252
253 runner = ConjectureRunner(f, settings=settings(max_examples=1, database=None))
254 runner.run()
255 assert len(seen) == 1
256
257
258 @pytest.mark.parametrize("examples", [1, 5, 20, 50])
259 def test_stops_after_max_examples_when_generating_more_bugs(examples):
260 seen = []
261 err_common = False
262 err_rare = False
263
264 def f(data):
265 seen.append(data.draw_integer(0, 2**32 - 1))
266 # Rare, potentially multi-error conditions
267 nonlocal err_common, err_rare
268 if seen[-1] > 2**31:
269 err_rare = True
270 raise ValueError
271 err_common = True
272 raise Exception
273
274 runner = ConjectureRunner(
275 f, settings=settings(max_examples=examples, phases=[Phase.generate])
276 )
277 try:
278 runner.run()
279 except Exception:
280 pass
281 # No matter what, whether examples is larger or smalller than MAX_TEST_CALLS,
282 # we stop looking at max_examples. (and re-run each failure for the traceback)
283 assert len(seen) <= examples + err_common + err_rare
284
285
286 def test_interleaving_engines():
287 children = []
288
289 @run_to_nodes
290 def nodes(data):
291 rnd = Random(data.draw_bytes(1, 1))
292
293 def g(d2):
294 d2.draw_bytes(1, 1)
295 data.mark_interesting(interesting_origin())
296
297 runner = ConjectureRunner(g, random=rnd)
298 children.append(runner)
299 runner.run()
300 if runner.interesting_examples:
301 data.mark_interesting(interesting_origin())
302
303 assert tuple(n.value for n in nodes) == (b"\0",)
304 for c in children:
305 assert not c.interesting_examples
306
307
308 def test_phases_can_disable_shrinking():
309 seen = set()
310
311 def f(data):
312 seen.add(bytes(data.draw_bytes(32, 32)))
313 data.mark_interesting(interesting_origin())
314
315 runner = ConjectureRunner(
316 f, settings=settings(database=None, phases=(Phase.reuse, Phase.generate))
317 )
318 runner.run()
319 assert len(seen) == 1
320
321
322 def test_reuse_phase_runs_for_max_examples_if_generation_is_disabled():
323 db = InMemoryExampleDatabase()
324 for i in range(256):
325 db.save(b"key", choices_to_bytes([i]))
326 seen = set()
327
328 def test(data):
329 seen.add(data.draw_integer(0, 2**8 - 1))
330
331 ConjectureRunner(
332 test,
333 settings=settings(max_examples=100, database=db, phases=[Phase.reuse]),
334 database_key=b"key",
335 random=Random(0),
336 ).run()
337
338 assert len(seen) == 100
339
340
341 def test_erratic_draws():
342 n = 0
343
344 with pytest.raises(FlakyStrategyDefinition):
345
346 @run_to_nodes
347 def nodes(data):
348 nonlocal n
349 data.draw_bytes(n, n)
350 data.draw_bytes(255 - n, 255 - n)
351 if n == 255:
352 data.mark_interesting(interesting_origin())
353 else:
354 n += 1
355
356
357 def test_no_read_no_shrink():
358 count = 0
359
360 @run_to_nodes
361 def nodes(data):
362 nonlocal count
363 count += 1
364 data.mark_interesting(interesting_origin())
365
366 assert nodes == ()
367 assert count == 1
368
369
370 def test_one_dead_branch():
371 seen = set()
372
373 @run_to_nodes
374 def nodes(data):
375 i = data.draw_bytes(1, 1)[0]
376 if i > 0:
377 data.mark_invalid()
378 i = data.draw_bytes(1, 1)[0]
379 if len(seen) < 255:
380 seen.add(i)
381 elif i not in seen:
382 data.mark_interesting(interesting_origin())
383
384
385 def test_does_not_save_on_interrupt():
386 def interrupts(data):
387 raise KeyboardInterrupt
388
389 db = InMemoryExampleDatabase()
390 runner = ConjectureRunner(
391 interrupts, settings=settings(database=db), database_key=b"key"
392 )
393 with pytest.raises(KeyboardInterrupt):
394 runner.run()
395 assert not db.data
396
397
398 def test_saves_on_skip_exceptions_to_reraise():
399 # skip exceptions should be saved to the db so we spend as little time as
400 # possible exploring these tests in the future (if eg the skip is guarded
401 # by a conditional that takes some time to hit). see also
402 # https://github.com/HypothesisWorks/hypothesis/pull/4316#discussion_r2008912585
403 def raises(data):
404 pytest.skip()
405
406 db = InMemoryExampleDatabase()
407 runner = ConjectureRunner(
408 raises, settings=settings(database=db), database_key=b"key"
409 )
410 with pytest.raises(pytest.skip.Exception):
411 runner.run()
412
413 assert len(db.data) == 1
414
415
416 def test_returns_forced():
417 value = b"\0\1\2\3"
418
419 @run_to_nodes
420 def nodes(data):
421 data.draw_bytes(len(value), len(value), forced=value)
422 data.mark_interesting(interesting_origin())
423
424 assert tuple(n.value for n in nodes) == (value,)
425
426
427 def fails_health_check(label, **kwargs):
428 def accept(f):
429 runner = ConjectureRunner(
430 f,
431 settings=settings(
432 max_examples=100, phases=no_shrink, database=None, **kwargs
433 ),
434 )
435
436 with pytest.raises(FailedHealthCheck) as e:
437 runner.run()
438 assert str(label) in str(e.value)
439 assert not runner.interesting_examples
440
441 return accept
442
443
444 def test_fails_health_check_for_all_invalid():
445 @fails_health_check(HealthCheck.filter_too_much)
446 def _(data):
447 data.draw_bytes(2, 2)
448 data.mark_invalid()
449
450
451 def test_fails_health_check_for_large_base():
452 @fails_health_check(HealthCheck.large_base_example)
453 def _(data):
454 data.draw_bytes(10**6, 10**6)
455
456
457 def test_fails_health_check_for_large_non_base():
458 @fails_health_check(HealthCheck.data_too_large)
459 def _(data):
460 if data.draw_boolean():
461 data.draw_bytes(10_000, 10_000)
462
463
464 @skipif_time_unpatched
465 def test_fails_health_check_for_slow_draws():
466 @fails_health_check(HealthCheck.too_slow)
467 def _(data):
468 data.draw(SLOW)
469
470
471 def test_health_check_too_slow_with_invalid_examples():
472 @st.composite
473 def s(draw):
474 n = draw(st.integers())
475 if n > 0:
476 assume(False)
477
478 time.sleep(0.2)
479
480 @given(s())
481 @settings(derandomize=True, max_examples=100)
482 def test(x):
483 pass
484
485 with pytest.raises(FailedHealthCheck) as exc:
486 test()
487
488 assert str(HealthCheck.too_slow) in str(exc.value)
489 assert re.search(r"\d+ invalid inputs", str(exc.value))
490
491
492 def test_health_check_too_slow_with_overrun_examples():
493 @st.composite
494 def s(draw):
495 n = draw(st.integers())
496 if n > 0:
497 draw(st.binary(min_size=50))
498 assume(False)
499
500 time.sleep(0.2)
501
502 @given(s())
503 @settings(derandomize=True, max_examples=100)
504 def test(x):
505 pass
506
507 with buffer_size_limit(10), pytest.raises(FailedHealthCheck) as exc:
508 test()
509
510 assert str(HealthCheck.too_slow) in str(exc.value)
511 assert re.search(
512 r"\d+ inputs which exceeded the maximum allowed entropy", str(exc.value)
513 )
514
515
516 @pytest.mark.parametrize("n_large", [1, 5, 8, 15])
517 def test_can_shrink_variable_draws(n_large):
518 target = 128 * n_large
519
520 @st.composite
521 def strategy(draw):
522 n = draw(st.integers(0, 15))
523 return [draw(st.integers(0, 255)) for _ in range(n)]
524
525 ints = minimal(strategy(), lambda ints: sum(ints) >= target)
526 # should look like [4, 255, 255, 255]
527 assert ints == [target % 255] + [255] * (len(ints) - 1)
528
529
530 def test_can_shrink_variable_string_draws():
531 @st.composite
532 def strategy(draw):
533 n = draw(st.integers(min_value=0, max_value=20))
534 return draw(st.text(st.characters(codec="ascii"), min_size=n, max_size=n))
535
536 s = minimal(strategy(), lambda s: len(s) >= 10 and "a" in s)
537
538 # TODO_BETTER_SHRINK: this should be
539 # assert s == "0" * 9 + "a"
540 # but we first shrink to having a single a at the end of the string and then
541 # fail to apply our special case invalid logic when shrinking the min_size n,
542 # because that logic removes from the end of the string (which fails our
543 # precondition).
544 assert re.match("0+a", s)
545
546
547 def test_variable_size_string_increasing():
548 # coverage test for min_size increasing during shrinking (because the test
549 # function inverts n).
550 # ...except this currently overruns instead and misses that check.
551 @st.composite
552 def strategy(draw):
553 n = 10 - draw(st.integers(0, 10))
554 return draw(st.text(st.characters(codec="ascii"), min_size=n, max_size=n))
555
556 s = minimal(strategy(), lambda s: len(s) >= 5 and "a" in s)
557 # TODO_BETTER_SHRINK: this should be
558 # assert s == "0000a"
559 # but instead shrinks to 00000000a.
560 assert re.match("0+a", s)
561
562
563 def test_run_nothing():
564 def f(data):
565 raise AssertionError
566
567 runner = ConjectureRunner(f, settings=settings(phases=()))
568 runner.run()
569 assert runner.call_count == 0
570
571
572 class Foo:
573 def __repr__(self):
574 return "stuff"
575
576
577 def test_debug_data(capsys):
578 choices = (0, 1, 2)
579
580 def f(data):
581 for choice in choices:
582 if data.draw(st.integers(0, 100)) != choice:
583 data.mark_invalid()
584 data.start_span(1)
585 data.stop_span()
586 data.mark_interesting(interesting_origin())
587
588 runner = ConjectureRunner(
589 f,
590 settings=settings(
591 max_examples=5000,
592 database=None,
593 suppress_health_check=list(HealthCheck),
594 verbosity=Verbosity.debug,
595 ),
596 )
597 runner.cached_test_function(choices)
598 runner.run()
599
600 out, _ = capsys.readouterr()
601 assert re.match(r"\d+ choices -> ", out)
602 assert "INTERESTING" in out
603
604
605 def test_can_write_bytes_towards_the_end():
606 buf = b"\1\2\3"
607
608 def f(data):
609 if data.draw_boolean():
610 data.draw_bytes(5, 5)
611 data.draw_bytes(len(buf), len(buf), forced=buf)
612 assert data.choices[2] == buf
613
614 with buffer_size_limit(15):
615 ConjectureRunner(f).run()
616
617
618 def test_uniqueness_is_preserved_when_writing_at_beginning():
619 seen = set()
620
621 def f(data):
622 data.draw_bytes(1, 1, forced=bytes(1))
623 n = data.draw_integer(0, 2**3 - 1)
624 assert n not in seen
625 seen.add(n)
626
627 runner = ConjectureRunner(f, settings=settings(max_examples=50))
628 runner.run()
629 assert runner.valid_examples == len(seen)
630
631
632 @pytest.mark.parametrize("skip_target", [False, True])
633 @pytest.mark.parametrize("initial_attempt", [(127,), (128,)])
634 def test_clears_out_its_database_on_shrinking(
635 initial_attempt, skip_target, monkeypatch
636 ):
637 def generate_new_examples(self):
638 self.cached_test_function(initial_attempt)
639
640 monkeypatch.setattr(
641 ConjectureRunner, "generate_new_examples", generate_new_examples
642 )
643
644 key = b"key"
645 db = InMemoryExampleDatabase()
646
647 def f(data):
648 if data.draw_integer() >= 127:
649 data.mark_interesting(interesting_origin())
650
651 runner = ConjectureRunner(
652 f,
653 settings=settings(database=db, max_examples=256),
654 database_key=key,
655 random=Random(0),
656 )
657
658 for n in range(256):
659 if n != 127 or not skip_target:
660 db.save(runner.secondary_key, choices_to_bytes([n]))
661 runner.run()
662 assert len(runner.interesting_examples) == 1
663 for b in db.fetch(runner.secondary_key):
664 assert choices_from_bytes(b)[0] >= 127
665 assert len(list(db.fetch(runner.database_key))) == 1
666
667
668 def test_shrinks_both_interesting_examples(monkeypatch):
669 def generate_new_examples(self):
670 self.cached_test_function((1,))
671
672 monkeypatch.setattr(
673 ConjectureRunner, "generate_new_examples", generate_new_examples
674 )
675
676 def f(data):
677 n = data.draw_integer(0, 2**8 - 1)
678 data.mark_interesting(interesting_origin(n & 1))
679
680 runner = ConjectureRunner(f)
681 runner.run()
682 assert runner.interesting_examples[interesting_origin(0)].choices == (0,)
683 assert runner.interesting_examples[interesting_origin(1)].choices == (1,)
684
685
686 def test_discarding(monkeypatch):
687 monkeypatch.setattr(Shrinker, "shrink", Shrinker.remove_discarded)
688 monkeypatch.setattr(
689 ConjectureRunner,
690 "generate_new_examples",
691 lambda runner: runner.cached_test_function((False, True) * 10),
692 )
693
694 @run_to_nodes
695 def nodes(data):
696 count = 0
697 while count < 10:
698 data.start_span(SOME_LABEL)
699 b = data.draw_boolean()
700 if b:
701 count += 1
702 data.stop_span(discard=not b)
703 data.mark_interesting(interesting_origin())
704
705 assert tuple(n.value for n in nodes) == (True,) * 10
706
707
708 def test_can_remove_discarded_data():
709 @shrinking_from((0,) * 10 + (11,))
710 def shrinker(data: ConjectureData):
711 while True:
712 data.start_span(SOME_LABEL)
713 b = data.draw_integer(0, 2**8 - 1)
714 data.stop_span(discard=(b == 0))
715 if b == 11:
716 break
717 data.mark_interesting(interesting_origin())
718
719 shrinker.remove_discarded()
720 assert shrinker.choices == (11,)
721
722
723 def test_discarding_iterates_to_fixed_point():
724 @shrinking_from(list(range(100, -1, -1)))
725 def shrinker(data: ConjectureData):
726 data.start_span(0)
727 data.draw_integer(0, 2**8 - 1)
728 data.stop_span(discard=True)
729 while data.draw_integer(0, 2**8 - 1):
730 pass
731 data.mark_interesting(interesting_origin())
732
733 shrinker.remove_discarded()
734 assert shrinker.choices == (1, 0)
735
736
737 def test_discarding_is_not_fooled_by_empty_discards():
738 @shrinking_from((1, 1))
739 def shrinker(data: ConjectureData):
740 data.draw_integer(0, 2**1 - 1)
741 data.start_span(0)
742 data.stop_span(discard=True)
743 data.draw_integer(0, 2**1 - 1)
744 data.mark_interesting(interesting_origin())
745
746 shrinker.remove_discarded()
747 assert shrinker.shrink_target.has_discards
748
749
750 def test_discarding_can_fail():
751 @shrinking_from((1,))
752 def shrinker(data: ConjectureData):
753 data.start_span(0)
754 data.draw_boolean()
755 data.stop_span(discard=True)
756 data.mark_interesting(interesting_origin())
757
758 shrinker.remove_discarded()
759 assert any(e.discarded and e.choice_count > 0 for e in shrinker.shrink_target.spans)
760
761
762 def test_shrinking_from_mostly_zero(monkeypatch):
763 monkeypatch.setattr(
764 ConjectureRunner,
765 "generate_new_examples",
766 lambda self: self.cached_test_function((0,) * 5 + (2,)),
767 )
768
769 @run_to_nodes
770 def nodes(data):
771 s = [data.draw_integer(0, 2**8 - 1) for _ in range(6)]
772 if any(s):
773 data.mark_interesting(interesting_origin())
774
775 assert tuple(n.value for n in nodes) == (0,) * 5 + (1,)
776
777
778 def test_handles_nesting_of_discard_correctly(monkeypatch):
779 monkeypatch.setattr(Shrinker, "shrink", Shrinker.remove_discarded)
780 monkeypatch.setattr(
781 ConjectureRunner,
782 "generate_new_examples",
783 lambda runner: runner.cached_test_function((False, False, True, True)),
784 )
785
786 @run_to_nodes
787 def nodes(data):
788 while True:
789 data.start_span(SOME_LABEL)
790 succeeded = data.draw_boolean()
791 data.start_span(SOME_LABEL)
792 data.draw_boolean()
793 data.stop_span(discard=not succeeded)
794 data.stop_span(discard=not succeeded)
795 if succeeded:
796 data.mark_interesting(interesting_origin())
797
798 assert tuple(n.value for n in nodes) == (True, True)
799
800
801 def test_database_clears_secondary_key():
802 key = b"key"
803 database = InMemoryExampleDatabase()
804
805 def f(data):
806 if data.draw_integer() == 10:
807 data.mark_interesting(interesting_origin())
808 else:
809 data.mark_invalid()
810
811 runner = ConjectureRunner(
812 f,
813 settings=settings(
814 max_examples=1, database=database, suppress_health_check=list(HealthCheck)
815 ),
816 database_key=key,
817 )
818
819 for i in range(10):
820 database.save(runner.secondary_key, choices_to_bytes([i]))
821
822 runner.cached_test_function((10,))
823 assert runner.interesting_examples
824
825 assert len(set(database.fetch(key))) == 1
826 assert len(set(database.fetch(runner.secondary_key))) == 10
827
828 runner.clear_secondary_key()
829
830 assert len(set(database.fetch(key))) == 1
831 assert len(set(database.fetch(runner.secondary_key))) == 0
832
833
834 def test_database_uses_values_from_secondary_key():
835 key = b"key"
836 database = InMemoryExampleDatabase()
837
838 def f(data):
839 if data.draw_integer() >= 5:
840 data.mark_interesting(interesting_origin())
841 else:
842 data.mark_invalid()
843
844 runner = ConjectureRunner(
845 f,
846 settings=settings(
847 max_examples=1, database=database, suppress_health_check=list(HealthCheck)
848 ),
849 database_key=key,
850 )
851 for i in range(10):
852 database.save(runner.secondary_key, choices_to_bytes([i]))
853
854 runner.cached_test_function((10,))
855 assert runner.interesting_examples
856 assert len(set(database.fetch(key))) == 1
857 assert len(set(database.fetch(runner.secondary_key))) == 10
858
859 runner.clear_secondary_key()
860
861 assert len(set(database.fetch(key))) == 1
862 assert {
863 choices_from_bytes(b)[0] for b in database.fetch(runner.secondary_key)
864 } == set(range(6, 11))
865
866 (v,) = runner.interesting_examples.values()
867 assert v.choices == (5,)
868
869
870 def test_exit_because_max_iterations():
871 def f(data):
872 data.draw_integer(0, 2**64 - 1)
873 data.mark_invalid()
874
875 runner = ConjectureRunner(
876 f,
877 settings=settings(
878 max_examples=1, database=None, suppress_health_check=list(HealthCheck)
879 ),
880 )
881
882 runner.run()
883
884 assert runner.call_count <= 1000
885 assert runner.exit_reason == ExitReason.max_iterations
886
887
888 def test_max_iterations_with_all_invalid():
889 # With assume(False) on every example, we stop after INVALID_THRESHOLD_BASE + 1
890 # invalid attempts (the check is > not >=).
891 def f(data):
892 data.draw_integer(0, 2**64 - 1)
893 data.mark_invalid()
894
895 runner = ConjectureRunner(
896 f,
897 settings=settings(
898 max_examples=10_000, database=None, suppress_health_check=list(HealthCheck)
899 ),
900 )
901 runner.run()
902
903 assert runner.call_count == INVALID_THRESHOLD_BASE + 1
904 assert runner.exit_reason == ExitReason.max_iterations
905
906
907 @pytest.mark.parametrize("n_valid", [1, 2, 5])
908 def test_max_iterations_with_some_valid(n_valid):
909 valid_count = 0
910
911 def f(data):
912 nonlocal valid_count
913 data.draw_integer(0, 2**64 - 1)
914 if valid_count < n_valid:
915 valid_count += 1
916 else:
917 data.mark_invalid()
918
919 runner = ConjectureRunner(
920 f,
921 settings=settings(
922 max_examples=10_000, database=None, suppress_health_check=list(HealthCheck)
923 ),
924 )
925 runner.run()
926
927 assert (
928 runner.call_count
929 == n_valid + INVALID_THRESHOLD_BASE + n_valid * INVALID_PER_VALID + 1
930 )
931 assert runner.exit_reason == ExitReason.max_iterations
932
933
934 def test_exit_because_shrink_phase_timeout(monkeypatch):
935 val = 0
936
937 def fast_time():
938 nonlocal val
939 val += 1000
940 return val
941
942 def f(data):
943 if data.draw_integer(0, 2**64 - 1) > 2**33:
944 data.mark_interesting(interesting_origin())
945
946 monkeypatch.setattr(time, "perf_counter", fast_time)
947 runner = ConjectureRunner(f, settings=settings(database=None, max_examples=100_000))
948 runner.run()
949 assert runner.exit_reason == ExitReason.very_slow_shrinking
950 assert runner.statistics["stopped-because"] == "shrinking was very slow"
951
952
953 def test_dependent_block_pairs_can_lower_to_zero():
954 @shrinking_from((True, 1))
955 def shrinker(data: ConjectureData):
956 if data.draw_boolean():
957 n = data.draw_integer(0, 2**16 - 1)
958 else:
959 n = data.draw_integer(0, 2**8 - 1)
960
961 if n == 1:
962 data.mark_interesting(interesting_origin())
963
964 shrinker.fixate_shrink_passes([ShrinkPass(shrinker.minimize_individual_choices)])
965 assert shrinker.choices == (False, 1)
966
967
968 def test_handle_size_too_large_during_dependent_lowering():
969 @shrinking_from((True, 255, 0))
970 def shrinker(data: ConjectureData):
971 if data.draw_boolean():
972 data.draw_integer(0, 2**16 - 1)
973 data.mark_interesting(interesting_origin())
974 else:
975 data.draw_integer(0, 2**8 - 1)
976
977 shrinker.fixate_shrink_passes([ShrinkPass(shrinker.minimize_individual_choices)])
978
979
980 def test_block_may_grow_during_lexical_shrinking():
981 @shrinking_from((2, 1, 1))
982 def shrinker(data: ConjectureData):
983 n = data.draw_integer(0, 2**8 - 1)
984 if n == 2:
985 data.draw_integer(0, 2**8 - 1)
986 data.draw_integer(0, 2**8 - 1)
987 else:
988 data.draw_integer(0, 2**16 - 1)
989 data.mark_interesting(interesting_origin())
990
991 shrinker.fixate_shrink_passes([ShrinkPass(shrinker.minimize_individual_choices)])
992 assert shrinker.choices == (0, 0)
993
994
995 def test_lower_common_node_offset_does_nothing_when_changed_blocks_are_zero():
996 @shrinking_from((True, False, True, False))
997 def shrinker(data: ConjectureData):
998 data.draw_boolean()
999 data.draw_boolean()
1000 data.draw_boolean()
1001 data.draw_boolean()
1002 data.mark_interesting(interesting_origin())
1003
1004 shrinker.mark_changed(1)
1005 shrinker.mark_changed(3)
1006 shrinker.lower_common_node_offset()
1007 assert shrinker.choices == (True, False, True, False)
1008
1009
1010 def test_lower_common_node_offset_ignores_zeros():
1011 @shrinking_from((2, 2, 0))
1012 def shrinker(data: ConjectureData):
1013 n = data.draw_integer(0, 2**8 - 1)
1014 data.draw_integer(0, 2**8 - 1)
1015 data.draw_integer(0, 2**8 - 1)
1016 if n > 0:
1017 data.mark_interesting(interesting_origin())
1018
1019 for i in range(3):
1020 shrinker.mark_changed(i)
1021 shrinker.lower_common_node_offset()
1022 assert shrinker.choices == (1, 1, 0)
1023
1024
1025 def test_cached_test_function_returns_right_value():
1026 count = 0
1027
1028 def tf(data):
1029 nonlocal count
1030 count += 1
1031 data.draw_integer(0, 3)
1032 data.mark_interesting(interesting_origin())
1033
1034 runner = ConjectureRunner(tf, settings=runner_settings, random=Random(0))
1035 for _ in range(2):
1036 for choices in ((0,), (1,)):
1037 d = runner.cached_test_function(choices)
1038 assert d.status == Status.INTERESTING
1039 assert d.choices == choices
1040 assert count == 2
1041
1042
1043 def test_cached_test_function_does_not_reinvoke_on_prefix():
1044 call_count = 0
1045
1046 def test_function(data):
1047 nonlocal call_count
1048 call_count += 1
1049 data.draw_integer(0, 2**8 - 1)
1050 data.draw_bytes(1, 1, forced=bytes([7]))
1051 data.draw_integer(0, 2**8 - 1)
1052
1053 runner = ConjectureRunner(test_function, settings=runner_settings, random=Random(0))
1054
1055 data = runner.cached_test_function((0, b"\0", 0))
1056 assert data.status == Status.VALID
1057 for n in [2, 1, 0]:
1058 d = runner.cached_test_function(data.choices[:n])
1059 assert d is Overrun
1060 assert call_count == 1
1061
1062
1063 def test_will_evict_entries_from_the_cache(monkeypatch):
1064 monkeypatch.setattr(engine_module, "CACHE_SIZE", 5)
1065 count = 0
1066
1067 def tf(data):
1068 nonlocal count
1069 data.draw_integer(0, 2**8 - 1)
1070 count += 1
1071
1072 runner = ConjectureRunner(tf, settings=runner_settings)
1073
1074 for _ in range(3):
1075 for n in range(10):
1076 runner.cached_test_function((n,))
1077
1078 # Because we exceeded the cache size, our previous
1079 # calls will have been evicted, so each call to
1080 # cached_test_function will have to reexecute.
1081 assert count == 30
1082
1083
1084 def test_branch_ending_in_write():
1085 seen = set()
1086
1087 def tf(data):
1088 count = 0
1089 while data.draw_boolean():
1090 count += 1
1091
1092 if count > 1:
1093 data.draw_boolean(forced=False)
1094
1095 assert data.nodes not in seen
1096 seen.add(data.nodes)
1097
1098 # max_examples high enough that our for loop below won't hit it
1099 runner = ConjectureRunner(
1100 tf, settings=settings(runner_settings, max_examples=200), random=Random(0)
1101 )
1102
1103 for _ in range(100):
1104 prefix = runner.generate_novel_prefix()
1105 attempt = prefix + (False, False)
1106 data = runner.cached_test_function(attempt)
1107 assert data.status is Status.VALID
1108 assert startswith(attempt, data.choices)
1109
1110
1111 def test_exhaust_space():
1112 runner = ConjectureRunner(
1113 lambda data: data.draw_boolean(), settings=runner_settings, random=Random(0)
1114 )
1115 runner.run()
1116 assert runner.tree.is_exhausted
1117 assert runner.valid_examples == 2
1118
1119
1120 SMALL_COUNT_SETTINGS = settings(runner_settings, max_examples=500)
1121
1122
1123 def test_discards_kill_branches():
1124 seen = set()
1125
1126 def test(data: ConjectureData):
1127 data.start_span(1)
1128 n1 = data.draw_integer(0, 9)
1129 data.stop_span(discard=n1 > 0)
1130 n2 = data.draw_integer(0, 9)
1131 n3 = data.draw_integer(0, 9)
1132
1133 assert (n1, n2, n3) not in seen
1134 seen.add((n1, n2, n3))
1135
1136 runner = ConjectureRunner(test, settings=SMALL_COUNT_SETTINGS)
1137 runner.run()
1138 assert runner.exit_reason is ExitReason.finished
1139 # 10 to explore the initial n1 = 0-9 statespace, then 100 to explore just
1140 # the (0, n1, n2) statespace, because every prefix other than 0 is a discard
1141 # and is not explored. Subtract the overlap, which occurs once at n1 = 0.
1142 assert len(seen) == 100 + 10 - 1
1143
1144
1145 @pytest.mark.parametrize("n", range(1, 32))
1146 def test_number_of_examples_in_integer_range_is_bounded(n):
1147 def test(data):
1148 assert runner.call_count <= 2 * n
1149 data.draw_integer(0, n)
1150
1151 runner = ConjectureRunner(test, settings=SMALL_COUNT_SETTINGS, random=Random(0))
1152 runner.run()
1153
1154
1155 def test_prefix_cannot_exceed_buffer_size(monkeypatch):
1156 buffer_size = 10
1157
1158 with buffer_size_limit(buffer_size):
1159
1160 def test(data):
1161 while data.draw_boolean():
1162 assert data.length <= buffer_size
1163 assert data.length <= buffer_size
1164
1165 runner = ConjectureRunner(test, settings=SMALL_COUNT_SETTINGS, random=Random(0))
1166 runner.run()
1167 assert runner.valid_examples == buffer_size
1168
1169
1170 def test_does_not_shrink_multiple_bugs_when_told_not_to():
1171 def test(data):
1172 m = data.draw_integer(0, 2**8 - 1)
1173 n = data.draw_integer(0, 2**8 - 1)
1174
1175 if m > 0:
1176 data.mark_interesting(interesting_origin(1))
1177 if n > 5:
1178 data.mark_interesting(interesting_origin(2))
1179
1180 runner = ConjectureRunner(
1181 test,
1182 settings=settings(runner_settings, report_multiple_bugs=False),
1183 random=Random(0),
1184 )
1185 runner.cached_test_function((255, 255))
1186 runner.shrink_interesting_examples()
1187
1188 results = {d.choices for d in runner.interesting_examples.values()}
1189 assert len(results.intersection({(0, 1), (1, 0)})) == 1
1190
1191
1192 def test_does_not_keep_generating_when_multiple_bugs():
1193 def test(data):
1194 if data.draw_integer(0, 2**20 - 1) > 0:
1195 data.draw_integer(0, 2**20 - 1)
1196 data.mark_interesting(interesting_origin())
1197
1198 runner = ConjectureRunner(
1199 test,
1200 settings=settings(
1201 runner_settings, report_multiple_bugs=False, phases=[Phase.generate]
1202 ),
1203 random=Random(0),
1204 )
1205 runner.run()
1206
1207 assert runner.call_count == 2
1208
1209
1210 def test_shrink_after_max_examples():
1211 """If we find a bug, keep looking for more, and then hit the valid-example
1212 limit, we should still proceed to shrinking.
1213 """
1214 max_examples = 100
1215 fail_at = max_examples - 5
1216
1217 seen = set()
1218 bad = set()
1219 post_failure_calls = [0]
1220
1221 def test(data):
1222 if bad:
1223 post_failure_calls[0] += 1
1224
1225 value = data.draw_integer(0, 2**8 - 1)
1226
1227 if value in seen and value not in bad:
1228 return
1229
1230 seen.add(value)
1231 if len(seen) == fail_at:
1232 bad.add(value)
1233
1234 if value in bad:
1235 data.mark_interesting(interesting_origin())
1236
1237 runner = ConjectureRunner(
1238 test,
1239 settings=settings(
1240 runner_settings,
1241 max_examples=max_examples,
1242 phases=[Phase.generate, Phase.shrink],
1243 report_multiple_bugs=True,
1244 ),
1245 # This shouldn't need to be deterministic, but it makes things much easier
1246 # to debug if anything goes wrong.
1247 random=Random(0),
1248 )
1249 runner.shrink_interesting_examples = Mock(name="shrink_interesting_examples")
1250 runner.run()
1251
1252 # First, verify our test assumptions: we found a bug, kept running, and
1253 # then hit max-examples.
1254 assert runner.interesting_examples
1255 assert post_failure_calls[0] >= (max_examples - fail_at)
1256 assert runner.call_count >= max_examples
1257 assert runner.valid_examples == max_examples
1258
1259 # Now check that we still performed shrinking, even after hitting the
1260 # example limit.
1261 assert runner.shrink_interesting_examples.call_count == 1
1262 assert runner.exit_reason == ExitReason.finished
1263
1264
1265 def test_shrink_after_max_iterations():
1266 """If we find a bug, keep looking for more, and then hit the invalid
1267 examples limit, we should still proceed to shrinking.
1268 """
1269 max_examples = 10
1270 max_iterations = INVALID_THRESHOLD_BASE
1271 fail_at = max_iterations - 5
1272
1273 invalid = set()
1274 bad = set()
1275 post_failure_calls = [0]
1276
1277 def test(data):
1278 if bad:
1279 post_failure_calls[0] += 1
1280
1281 value = data.draw_integer(0, 2**16 - 1)
1282
1283 if value in invalid:
1284 data.mark_invalid()
1285
1286 if value in bad or (not bad and len(invalid) == fail_at):
1287 bad.add(value)
1288 data.mark_interesting(interesting_origin())
1289
1290 invalid.add(value)
1291 data.mark_invalid()
1292
1293 # This shouldn't need to be deterministic, but it makes things much easier
1294 # to debug if anything goes wrong.
1295 runner = ConjectureRunner(
1296 test,
1297 settings=settings(
1298 runner_settings,
1299 max_examples=max_examples,
1300 phases=[Phase.generate, Phase.shrink],
1301 report_multiple_bugs=True,
1302 ),
1303 random=Random(0),
1304 )
1305 runner.shrink_interesting_examples = Mock(name="shrink_interesting_examples")
1306 runner.run()
1307
1308 # First, verify our test assumptions: we found a bug, kept running, and
1309 # then hit the test call limit.
1310 assert runner.interesting_examples
1311 assert post_failure_calls[0] >= (max_iterations - fail_at) - 1
1312 assert runner.call_count >= max_iterations
1313 assert runner.valid_examples == 0
1314
1315 # Now check that we still performed shrinking, even after hitting the
1316 # test call limit.
1317 assert runner.shrink_interesting_examples.call_count == 1
1318 assert runner.exit_reason == ExitReason.finished
1319
1320
1321 def test_populates_the_pareto_front():
1322 def test(data):
1323 data.target_observations[""] = data.draw_integer(0, 2**4 - 1)
1324
1325 runner = ConjectureRunner(
1326 test,
1327 settings=settings(
1328 max_examples=5000,
1329 database=InMemoryExampleDatabase(),
1330 suppress_health_check=list(HealthCheck),
1331 ),
1332 database_key=b"stuff",
1333 random=Random(0),
1334 )
1335 runner.run()
1336
1337 assert len(runner.pareto_front) == 2**4
1338
1339
1340 def test_pareto_front_contains_smallest_valid():
1341 def test(data):
1342 data.target_observations[""] = 1
1343 data.draw_integer(0, 2**4 - 1)
1344
1345 runner = ConjectureRunner(
1346 test,
1347 settings=settings(
1348 max_examples=5000,
1349 database=InMemoryExampleDatabase(),
1350 suppress_health_check=list(HealthCheck),
1351 ),
1352 database_key=b"stuff",
1353 random=Random(0),
1354 )
1355 runner.run()
1356
1357 assert len(runner.pareto_front) == 1
1358
1359
1360 def test_replaces_all_dominated():
1361 def test(data):
1362 data.target_observations["m"] = 3 - data.draw_integer(0, 3)
1363 data.target_observations["n"] = 3 - data.draw_integer(0, 3)
1364
1365 runner = ConjectureRunner(
1366 test,
1367 settings=settings(runner_settings, database=InMemoryExampleDatabase()),
1368 database_key=b"stuff",
1369 )
1370
1371 d1 = runner.cached_test_function((0, 1)).as_result()
1372 d2 = runner.cached_test_function((1, 0)).as_result()
1373
1374 assert len(runner.pareto_front) == 2
1375
1376 assert runner.pareto_front[0] == d1
1377 assert runner.pareto_front[1] == d2
1378
1379 d3 = runner.cached_test_function((0, 0)).as_result()
1380 assert len(runner.pareto_front) == 1
1381
1382 assert runner.pareto_front[0] == d3
1383
1384
1385 def test_does_not_duplicate_elements():
1386 def test(data):
1387 data.target_observations["m"] = data.draw_integer(0, 2**8 - 1)
1388
1389 runner = ConjectureRunner(
1390 test,
1391 settings=settings(runner_settings, database=InMemoryExampleDatabase()),
1392 database_key=b"stuff",
1393 )
1394 d1 = runner.cached_test_function((1,)).as_result()
1395
1396 assert len(runner.pareto_front) == 1
1397 # This can happen in practice if we e.g. reexecute a test because it has
1398 # expired from the cache. It's easier just to test it directly though
1399 # rather than simulate the failure mode.
1400 assert runner.pareto_front.add(d1)
1401 assert len(runner.pareto_front) == 1
1402
1403
1404 def test_includes_right_hand_side_targets_in_dominance():
1405 def test(data):
1406 if data.draw_integer(0, 2**8 - 1):
1407 data.target_observations[""] = 10
1408
1409 runner = ConjectureRunner(
1410 test,
1411 settings=settings(runner_settings, database=InMemoryExampleDatabase()),
1412 database_key=b"stuff",
1413 )
1414
1415 d1 = runner.cached_test_function((0,)).as_result()
1416 d2 = runner.cached_test_function((1,)).as_result()
1417
1418 assert dominance(d1, d2) == DominanceRelation.NO_DOMINANCE
1419
1420
1421 def test_smaller_interesting_dominates_larger_valid():
1422 def test(data):
1423 if data.draw_integer(0, 2**8 - 1) == 0:
1424 data.mark_interesting(interesting_origin())
1425
1426 runner = ConjectureRunner(
1427 test,
1428 settings=settings(runner_settings, database=InMemoryExampleDatabase()),
1429 database_key=b"stuff",
1430 )
1431
1432 d1 = runner.cached_test_function((0,)).as_result()
1433 d2 = runner.cached_test_function((1,)).as_result()
1434 assert dominance(d1, d2) == DominanceRelation.LEFT_DOMINATES
1435
1436
1437 def test_runs_full_set_of_examples():
1438 def test(data):
1439 data.draw_integer(0, 2**64 - 1)
1440
1441 runner = ConjectureRunner(
1442 test,
1443 settings=settings(runner_settings, database=InMemoryExampleDatabase()),
1444 database_key=b"stuff",
1445 )
1446
1447 runner.run()
1448 assert runner.valid_examples == runner_settings.max_examples
1449
1450
1451 def test_runs_optimisation_even_if_not_generating():
1452 def test(data):
1453 data.target_observations["n"] = data.draw_integer(0, 2**16 - 1)
1454
1455 runner = ConjectureRunner(
1456 test,
1457 settings=settings(runner_settings, phases=[Phase.target]),
1458 random=Random(0),
1459 )
1460 runner.cached_test_function((0,))
1461 runner.run()
1462
1463 assert runner.best_observed_targets["n"] == (2**16) - 1
1464
1465
1466 def test_runs_optimisation_once_when_generating():
1467 def test(data):
1468 data.target_observations["n"] = data.draw_integer(0, 2**16 - 1)
1469
1470 runner = ConjectureRunner(
1471 test, settings=settings(runner_settings, max_examples=100), random=Random(0)
1472 )
1473
1474 runner.optimise_targets = Mock(name="optimise_targets")
1475 try:
1476 runner.generate_new_examples()
1477 except RunIsComplete:
1478 pass
1479 assert runner.optimise_targets.call_count == 1
1480
1481
1482 def test_does_not_run_optimisation_when_max_examples_is_small():
1483 def test(data):
1484 data.target_observations["n"] = data.draw_integer(0, 2**16 - 1)
1485
1486 runner = ConjectureRunner(
1487 test, settings=settings(runner_settings, max_examples=10), random=Random(0)
1488 )
1489
1490 runner.optimise_targets = Mock(name="optimise_targets")
1491 try:
1492 runner.generate_new_examples()
1493 except RunIsComplete:
1494 pass
1495 assert runner.optimise_targets.call_count == 0
1496
1497
1498 def test_does_not_cache_extended_prefix():
1499 def test(data):
1500 data.draw_integer()
1501 data.draw_integer()
1502
1503 runner = ConjectureRunner(test, settings=runner_settings, random=Random(0))
1504
1505 d1 = runner.cached_test_function((0,), extend=10)
1506 assert runner.call_count == 1
1507 d2 = runner.cached_test_function((0,), extend=10)
1508 assert runner.call_count == 2
1509 assert d1.status is d2.status is Status.VALID
1510
1511
1512 def test_does_cache_if_extend_is_not_used():
1513 calls = 0
1514
1515 def test(data):
1516 nonlocal calls
1517 calls += 1
1518 data.draw_bytes(1, 1)
1519
1520 runner = ConjectureRunner(test, settings=runner_settings, random=Random(0))
1521
1522 d1 = runner.cached_test_function((b"\0"), extend=8)
1523 d2 = runner.cached_test_function((b"\0"), extend=8)
1524 assert d1.status == d2.status == Status.VALID
1525 assert d1.choices == d2.choices
1526 assert calls == 1
1527
1528
1529 def test_does_result_for_reuse():
1530 calls = 0
1531
1532 def test(data):
1533 nonlocal calls
1534 calls += 1
1535 data.draw_bytes(1, 1)
1536
1537 runner = ConjectureRunner(test, settings=runner_settings, random=Random(0))
1538
1539 d1 = runner.cached_test_function((b"\0"), extend=8)
1540 d2 = runner.cached_test_function(d1.choices)
1541 assert d1.status == d2.status == Status.VALID
1542 assert d1.nodes == d2.nodes
1543 assert calls == 1
1544
1545
1546 def test_does_not_use_cached_overrun_if_extending():
1547 def test(data):
1548 data.draw_integer()
1549 data.draw_integer()
1550
1551 runner = ConjectureRunner(test, settings=runner_settings, random=Random(0))
1552
1553 data = runner.cached_test_function((1,))
1554 assert data.status == Status.OVERRUN
1555 assert runner.call_count == 1
1556
1557 # the choice sequence of (1,) maps to an overrun in the cache, but we
1558 # do not want to use this cache entry if we're extending.
1559 data = runner.cached_test_function((1,), extend=1)
1560 assert data.status == Status.VALID
1561 assert runner.call_count == 2
1562
1563
1564 def test_uses_cached_overrun_if_not_extending():
1565 def test(data):
1566 data.draw_integer()
1567 data.draw_integer()
1568
1569 runner = ConjectureRunner(test, settings=runner_settings, random=Random(0))
1570
1571 data = runner.cached_test_function((1,), extend=0)
1572 assert data.status is Status.OVERRUN
1573 assert runner.call_count == 1
1574
1575 data = runner.cached_test_function((1,), extend=0)
1576 assert data.status is Status.OVERRUN
1577 assert runner.call_count == 1
1578
1579
1580 def test_can_be_set_to_ignore_limits():
1581 def test(data):
1582 data.draw_integer(0, 2**8 - 1)
1583
1584 runner = ConjectureRunner(
1585 test,
1586 settings=settings(runner_settings, max_examples=1),
1587 ignore_limits=True,
1588 random=Random(0),
1589 )
1590 for c in range(256):
1591 runner.cached_test_function((c,))
1592
1593 assert runner.tree.is_exhausted
1594
1595
1596 def test_too_slow_report():
1597 state = HealthCheckState()
1598 assert state.timing_report() == "" # no draws recorded -> no report
1599 state.draw_times = {
1600 "generate:a": [2.0, 0.356789, 0.0],
1601 "generate:b": [0.1111111, 0.0, 0.002345678, 0.05, 0.123456, 0.1, 0.1, 0.1],
1602 "generate:c": [0.03, 0.05, 0.2],
1603 "generate:d": [0.04],
1604 "generate:e": [0.05, 0.01],
1605 "generate:f": [0.06],
1606 "generate:g": [0.07],
1607 "generate:h": [0.08],
1608 "generate:i": [0.09, 0.00001],
1609 }
1610 expected = """
1611 count | fraction | slowest draws (seconds)
1612 a | 3 | 65% | -- -- -- 0.357, 2.000
1613 b | 8 | 16% | 0.100, 0.100, 0.100, 0.111, 0.123
1614 c | 3 | 8% | -- -- 0.030, 0.050, 0.200
1615 i | 2 | 2% | -- -- -- -- 0.090
1616 h | 1 | 2% | -- -- -- -- 0.080
1617 (skipped 4 rows of fast draws)"""
1618 got = state.timing_report()
1619 print(got)
1620 assert expected == got
1621
1622
1623 def _draw(cd, node):
1624 return getattr(cd, f"draw_{node.type}")(**node.constraints)
1625
1626
1627 @given(nodes(was_forced=False))
1628 def test_overruns_with_extend_are_not_cached(node):
1629 assume(compute_max_children(node.type, node.constraints) > 100)
1630
1631 def test(cd):
1632 _draw(cd, node)
1633 _draw(cd, node)
1634
1635 runner = ConjectureRunner(test)
1636 assert runner.call_count == 0
1637
1638 data = runner.cached_test_function([node.value])
1639 assert runner.call_count == 1
1640 assert data.status is Status.OVERRUN
1641
1642 # cache hit
1643 data = runner.cached_test_function([node.value])
1644 assert runner.call_count == 1
1645 assert data.status is Status.OVERRUN
1646
1647 # cache miss
1648 data = runner.cached_test_function([node.value], extend="full")
1649 assert runner.call_count == 2
1650 assert data.status is Status.VALID
1651
1652
1653 def test_simulate_to_evicted_data(monkeypatch):
1654 # test that we do not rely on the false invariant that correctly simulating
1655 # a data to a result means we have that result in the cache, due to e.g.
1656 # cache evictions (but also potentially other trickery).
1657 monkeypatch.setattr(engine_module, "CACHE_SIZE", 1)
1658
1659 def test(data):
1660 data.draw_integer()
1661
1662 runner = ConjectureRunner(test)
1663 runner.cached_test_function([0])
1664 # cache size is 1 so this evicts [0]
1665 runner.cached_test_function([1])
1666 assert runner.call_count == 2
1667
1668 # we dont throw PreviouslyUnseenBehavior when simulating, but the result
1669 # was evicted to the cache so we will still call through to the test function.
1670 runner.tree.simulate_test_function(ConjectureData.for_choices([0]))
1671 runner.cached_test_function([0])
1672 assert runner.call_count == 3
1673
1674
1675 @pytest.mark.parametrize(
1676 "strategy, condition",
1677 [
1678 (st.lists(st.integers(), min_size=5), lambda v: True),
1679 (st.lists(st.text(), min_size=2, unique=True), lambda v: True),
1680 (
1681 st.sampled_from(
1682 enum.Flag("LargeFlag", {f"bit{i}": enum.auto() for i in range(64)})
1683 ),
1684 lambda f: bit_count(f.value) > 1,
1685 ),
1686 ],
1687 )
1688 def test_mildly_complicated_strategies(strategy, condition):
1689 # There are some code paths in engine.py and shrinker.py that are easily
1690 # covered by shrinking any mildly compliated strategy and aren't worth
1691 # testing explicitly for. This covers those.
1692 minimal(strategy, condition)
1693
1694
1695 def test_does_not_shrink_if_replaying_from_database():
1696 db = InMemoryExampleDatabase()
1697 key = b"foo"
1698
1699 def f(data):
1700 if data.draw_integer(0, 255) == 123:
1701 data.mark_interesting(interesting_origin())
1702
1703 runner = ConjectureRunner(f, settings=settings(database=db), database_key=key)
1704 choices = (123,)
1705 runner.save_choices(choices)
1706 runner.shrink_interesting_examples = None
1707 runner.run()
1708 (last_data,) = runner.interesting_examples.values()
1709 assert last_data.choices == choices
1710
1711
1712 def test_does_shrink_if_replaying_inexact_from_database():
1713 db = InMemoryExampleDatabase()
1714 key = b"foo"
1715
1716 def f(data):
1717 data.draw_integer(0, 255)
1718 data.mark_interesting(interesting_origin())
1719
1720 runner = ConjectureRunner(f, settings=settings(database=db), database_key=key)
1721 runner.save_choices((123, 2))
1722 runner.run()
1723 (last_data,) = runner.interesting_examples.values()
1724 assert last_data.choices == (0,)
1725
1726
1727 def test_stops_if_hits_interesting_early_and_only_want_one_bug():
1728 db = InMemoryExampleDatabase()
1729 key = b"foo"
1730
1731 def f(data):
1732 data.draw_integer(0, 255)
1733 data.mark_interesting(interesting_origin())
1734
1735 runner = ConjectureRunner(
1736 f, settings=settings(database=db, report_multiple_bugs=False), database_key=key
1737 )
1738 for i in range(256):
1739 runner.save_choices([i])
1740 runner.run()
1741 assert runner.call_count == 1
1742
1743
1744 def test_skips_secondary_if_interesting_is_found():
1745 db = InMemoryExampleDatabase()
1746 key = b"foo"
1747
1748 def f(data):
1749 data.draw_integer(0, 255)
1750 data.mark_interesting(interesting_origin())
1751
1752 runner = ConjectureRunner(
1753 f,
1754 settings=settings(max_examples=1000, database=db, report_multiple_bugs=True),
1755 database_key=key,
1756 )
1757 for i in range(256):
1758 db.save(
1759 runner.database_key if i < 10 else runner.secondary_key,
1760 choices_to_bytes([i]),
1761 )
1762 runner.reuse_existing_examples()
1763 assert runner.call_count == 10
1764
1765
1766 @pytest.mark.parametrize("key_name", ["database_key", "secondary_key"])
1767 def test_discards_invalid_db_entries(key_name):
1768 def test(data):
1769 data.draw_integer()
1770 data.mark_interesting(interesting_origin())
1771
1772 db = InMemoryExampleDatabase()
1773 runner = ConjectureRunner(
1774 test,
1775 # stop IN_COVERAGE_TESTS from overriding max_examples, which changes
1776 # db behavior
1777 settings=settings(database=db, max_examples=100),
1778 database_key=b"stuff",
1779 random=Random(0),
1780 )
1781 key = getattr(runner, key_name)
1782 valid = choices_to_bytes([1])
1783 db.save(key, valid)
1784 for n in range(5):
1785 b = bytes([255, n])
1786 # save a bunch of invalid entries under the database key
1787 assert choices_from_bytes(b) is None
1788 db.save(key, b)
1789
1790 assert len(set(db.fetch(key))) == 6
1791 # this will clear out the invalid entries and use the valid one
1792 runner.reuse_existing_examples()
1793 runner.clear_secondary_key()
1794
1795 assert set(db.fetch(runner.database_key)) == {valid}
1796 assert runner.call_count == 1
1797
1798
1799 def test_discards_invalid_db_entries_pareto():
1800 def test(data):
1801 data.draw_integer()
1802 data.mark_interesting(interesting_origin())
1803
1804 db = InMemoryExampleDatabase()
1805 runner = ConjectureRunner(
1806 test,
1807 settings=settings(database=db, max_examples=100),
1808 database_key=b"stuff",
1809 random=Random(0),
1810 )
1811 for n in range(5):
1812 b = bytes([255, n])
1813 assert choices_from_bytes(b) is None
1814 db.save(runner.pareto_key, b)
1815
1816 assert len(set(db.fetch(runner.pareto_key))) == 5
1817 runner.reuse_existing_examples()
1818
1819 assert not set(db.fetch(runner.database_key))
1820 assert not set(db.fetch(runner.pareto_key))
1821 assert runner.call_count == 0