/
test_conjecture_engine.py
1622 lines (1232 loc) · 42 KB
/
test_conjecture_engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2019 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# consult the git log if you need to determine who owns an individual
# contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
#
# END HEADER
from __future__ import absolute_import, division, print_function
import re
from random import Random
import attr
import pytest
import hypothesis.internal.conjecture.engine as engine_module
import hypothesis.internal.conjecture.floats as flt
from hypothesis import HealthCheck, Phase, Verbosity, settings
from hypothesis.database import ExampleDatabase, InMemoryExampleDatabase
from hypothesis.errors import FailedHealthCheck, Flaky
from hypothesis.internal.compat import hbytes, hrange, int_from_bytes, int_to_bytes
from hypothesis.internal.conjecture.data import (
MAX_DEPTH,
ConjectureData,
Overrun,
Status,
)
from hypothesis.internal.conjecture.engine import (
MIN_TEST_CALLS,
ConjectureRunner,
ExitReason,
TargetSelector,
)
from hypothesis.internal.conjecture.shrinker import Shrinker, block_program
from hypothesis.internal.conjecture.shrinking import Float
from hypothesis.internal.conjecture.utils import Sampler, calc_label_from_name
from hypothesis.internal.entropy import deterministic_PRNG
from tests.common.strategies import SLOW, HardToShrink
from tests.common.utils import counts_calls, no_shrink
SOME_LABEL = calc_label_from_name("some label")
TEST_SETTINGS = settings(
max_examples=5000,
buffer_size=1024,
database=None,
suppress_health_check=HealthCheck.all(),
)
def run_to_data(f):
with deterministic_PRNG():
runner = ConjectureRunner(f, settings=TEST_SETTINGS)
runner.run()
assert runner.interesting_examples
last_data, = runner.interesting_examples.values()
return last_data
def run_to_buffer(f):
return hbytes(run_to_data(f).buffer)
def test_can_index_results():
@run_to_buffer
def f(data):
data.draw_bytes(5)
data.mark_interesting()
assert f.index(0) == 0
assert f.count(0) == 5
def test_non_cloneable_intervals():
@run_to_buffer
def x(data):
data.draw_bytes(10)
data.draw_bytes(9)
data.mark_interesting()
assert x == hbytes(19)
def test_duplicate_buffers():
@run_to_buffer
def x(data):
t = data.draw_bytes(10)
if not any(t):
data.mark_invalid()
s = data.draw_bytes(10)
if s == t:
data.mark_interesting()
assert x == hbytes([0] * 9 + [1]) * 2
def test_deletable_draws():
@run_to_buffer
def x(data):
while True:
x = data.draw_bytes(2)
if x[0] == 255:
data.mark_interesting()
assert x == hbytes([255, 0])
def zero_dist(random, n):
return hbytes(n)
def test_can_load_data_from_a_corpus():
key = b"hi there"
db = ExampleDatabase()
value = b"=\xc3\xe4l\x81\xe1\xc2H\xc9\xfb\x1a\xb6bM\xa8\x7f"
db.save(key, value)
def f(data):
if data.draw_bytes(len(value)) == value:
data.mark_interesting()
runner = ConjectureRunner(f, settings=settings(database=db), database_key=key)
runner.run()
last_data, = runner.interesting_examples.values()
assert last_data.buffer == value
assert len(list(db.fetch(key))) == 1
def slow_shrinker():
strat = HardToShrink()
def accept(data):
if data.draw(strat):
data.mark_interesting()
return accept
@pytest.mark.parametrize("n", [1, 5])
def test_terminates_shrinks(n, monkeypatch):
from hypothesis.internal.conjecture import engine
db = InMemoryExampleDatabase()
def generate_new_examples(self):
def draw_bytes(data, n):
return hbytes([255] * n)
self.test_function(self.new_conjecture_data(draw_bytes))
monkeypatch.setattr(
ConjectureRunner, "generate_new_examples", generate_new_examples
)
monkeypatch.setattr(engine, "MAX_SHRINKS", n)
runner = ConjectureRunner(
slow_shrinker(),
settings=settings(max_examples=5000, database=db),
random=Random(0),
database_key=b"key",
)
runner.run()
last_data, = runner.interesting_examples.values()
assert last_data.status == Status.INTERESTING
assert runner.shrinks == n
in_db = set(db.data[runner.secondary_key])
assert len(in_db) == n
def test_detects_flakiness():
failed_once = [False]
count = [0]
def tf(data):
data.draw_bytes(1)
count[0] += 1
if not failed_once[0]:
failed_once[0] = True
data.mark_interesting()
runner = ConjectureRunner(tf)
runner.run()
assert runner.exit_reason == ExitReason.flaky
assert count == [MIN_TEST_CALLS + 1]
def test_variadic_draw():
def draw_list(data):
result = []
while True:
data.start_example(SOME_LABEL)
d = data.draw_bytes(1)[0] & 7
if d:
result.append(data.draw_bytes(d))
data.stop_example()
if not d:
break
return result
@run_to_buffer
def b(data):
if any(all(d) for d in draw_list(data)):
data.mark_interesting()
ls = draw_list(ConjectureData.for_buffer(b))
assert len(ls) == 1
assert len(ls[0]) == 1
def test_draw_to_overrun():
@run_to_buffer
def x(data):
d = (data.draw_bytes(1)[0] - 8) & 0xFF
data.draw_bytes(128 * d)
if d >= 2:
data.mark_interesting()
assert x == hbytes([10]) + hbytes(128 * 2)
def test_can_navigate_to_a_valid_example():
def f(data):
i = int_from_bytes(data.draw_bytes(2))
data.draw_bytes(i)
data.mark_interesting()
runner = ConjectureRunner(
f, settings=settings(max_examples=5000, buffer_size=2, database=None)
)
runner.run()
assert runner.interesting_examples
def test_stops_after_max_examples_when_reading():
key = b"key"
db = ExampleDatabase(":memory:")
for i in range(10):
db.save(key, hbytes([i]))
seen = []
def f(data):
seen.append(data.draw_bytes(1))
runner = ConjectureRunner(
f, settings=settings(max_examples=1, database=db), database_key=key
)
runner.run()
assert len(seen) == 1
def test_stops_after_max_examples_when_generating():
seen = []
def f(data):
seen.append(data.draw_bytes(1))
runner = ConjectureRunner(f, settings=settings(max_examples=1, database=None))
runner.run()
assert len(seen) == 1
@pytest.mark.parametrize("examples", [1, 5, 20, 50])
def test_stops_after_max_examples_when_generating_more_bugs(examples):
seen = []
bad = [False, False]
def f(data):
seen.append(data.draw_bits(32))
# Rare, potentially multi-error conditions
if seen[-1] > 2 ** 31:
bad[0] = True
raise ValueError
bad[1] = True
raise Exception
runner = ConjectureRunner(
f, settings=settings(max_examples=examples, phases=[Phase.generate])
)
try:
runner.run()
except Exception:
pass
# No matter what, whether examples is larger or smalller than MAX_TEST_CALLS,
# we stop looking at max_examples. (and re-run each failure for the traceback)
assert len(seen) <= examples + sum(bad)
def test_interleaving_engines():
children = []
@run_to_buffer
def x(data):
rnd = Random(data.draw_bytes(1))
def g(d2):
d2.draw_bytes(1)
data.mark_interesting()
runner = ConjectureRunner(g, random=rnd)
children.append(runner)
runner.run()
if runner.interesting_examples:
data.mark_interesting()
assert x == b"\0"
for c in children:
assert not c.interesting_examples
def test_phases_can_disable_shrinking():
seen = set()
def f(data):
seen.add(hbytes(data.draw_bytes(32)))
data.mark_interesting()
runner = ConjectureRunner(
f, settings=settings(database=None, phases=(Phase.reuse, Phase.generate))
)
runner.run()
assert len(seen) == MIN_TEST_CALLS
def test_erratic_draws():
n = [0]
with pytest.raises(Flaky):
@run_to_buffer
def x(data):
data.draw_bytes(n[0])
data.draw_bytes(255 - n[0])
if n[0] == 255:
data.mark_interesting()
else:
n[0] += 1
def test_no_read_no_shrink():
count = [0]
@run_to_buffer
def x(data):
count[0] += 1
data.mark_interesting()
assert x == b""
assert count == [1]
def test_one_dead_branch():
with deterministic_PRNG():
seen = set()
@run_to_buffer
def x(data):
i = data.draw_bytes(1)[0]
if i > 0:
data.mark_invalid()
i = data.draw_bytes(1)[0]
if len(seen) < 255:
seen.add(i)
elif i not in seen:
data.mark_interesting()
def test_saves_on_interrupt():
def interrupts(data):
raise KeyboardInterrupt()
db = InMemoryExampleDatabase()
runner = ConjectureRunner(
interrupts, settings=settings(database=db), database_key=b"key"
)
with pytest.raises(KeyboardInterrupt):
runner.run()
assert db.data
def test_returns_written():
value = hbytes(b"\0\1\2\3")
@run_to_buffer
def written(data):
data.write(value)
data.mark_interesting()
assert value == written
def fails_health_check(label, **kwargs):
def accept(f):
runner = ConjectureRunner(
f,
settings=settings(
max_examples=100,
phases=no_shrink,
buffer_size=1024,
database=None,
**kwargs
),
)
with pytest.raises(FailedHealthCheck) as e:
runner.run()
assert e.value.health_check == label
assert not runner.interesting_examples
return accept
def test_fails_health_check_for_all_invalid():
@fails_health_check(HealthCheck.filter_too_much)
def _(data):
data.draw_bytes(2)
data.mark_invalid()
def test_fails_health_check_for_large_base():
@fails_health_check(HealthCheck.large_base_example)
def _(data):
data.draw_bytes(10 ** 6)
def test_fails_health_check_for_large_non_base():
@fails_health_check(HealthCheck.data_too_large)
def _(data):
if data.draw_bits(8):
data.draw_bytes(10 ** 6)
def test_fails_health_check_for_slow_draws():
@fails_health_check(HealthCheck.too_slow)
def _(data):
data.draw(SLOW)
@pytest.mark.parametrize("n_large", [1, 5, 8, 15])
def test_can_shrink_variable_draws(n_large):
target = 128 * n_large
@run_to_data
def data(data):
n = data.draw_bits(4)
b = [data.draw_bits(8) for _ in hrange(n)]
if sum(b) >= target:
data.mark_interesting()
x = data.buffer
assert x.count(0) == 0
assert sum(x[1:]) == target
@pytest.mark.parametrize("n", [1, 5, 8, 15])
def test_can_shrink_variable_draws_with_just_deletion(n, monkeypatch):
@shrinking_from([n] + [0] * (n - 1) + [1])
def shrinker(data):
n = data.draw_bits(4)
b = [data.draw_bits(8) for _ in hrange(n)]
if any(b):
data.mark_interesting()
# We normally would have populated this in minimize_individual_blocks
shrinker.is_shrinking_block = lambda x: True
shrinker.fixate_shrink_passes(["example_deletion_with_block_lowering"])
assert list(shrinker.shrink_target.buffer) == [1, 1]
def test_deletion_and_lowering_fails_to_shrink(monkeypatch):
monkeypatch.setattr(
Shrinker,
"shrink",
lambda self: self.fixate_shrink_passes(
["example_deletion_with_block_lowering"]
),
)
# Would normally be added by minimize_individual_blocks, but we skip
# that phase in this test.
monkeypatch.setattr(Shrinker, "is_shrinking_block", lambda self, i: i == 0)
def gen(self):
self.cached_test_function(10)
monkeypatch.setattr(ConjectureRunner, "generate_new_examples", gen)
@run_to_buffer
def x(data):
for _ in hrange(10):
data.draw_bytes(1)
data.mark_interesting()
assert x == hbytes(10)
def test_run_nothing():
def f(data):
assert False
runner = ConjectureRunner(f, settings=settings(phases=()))
runner.run()
assert runner.call_count == 0
class Foo(object):
def __repr__(self):
return "stuff"
@pytest.mark.parametrize("event", ["hi", Foo()])
def test_note_events(event):
def f(data):
data.note_event(event)
data.draw_bytes(1)
runner = ConjectureRunner(f)
runner.run()
assert runner.event_call_counts[str(event)] == runner.call_count > 0
def test_debug_data(capsys):
buf = [0, 1, 2]
def f(data):
for x in hbytes(buf):
if data.draw_bits(8) != x:
data.mark_invalid()
data.start_example(1)
data.stop_example()
data.mark_interesting()
runner = ConjectureRunner(
f,
settings=settings(
max_examples=5000,
buffer_size=1024,
database=None,
suppress_health_check=HealthCheck.all(),
verbosity=Verbosity.debug,
),
)
runner.cached_test_function(buf)
runner.run()
out, _ = capsys.readouterr()
assert re.match(u"\\d+ bytes \\[.*\\] -> ", out)
assert "INTERESTING" in out
def test_zeroes_bytes_above_bound():
def f(data):
if data.draw_bits(1):
x = data.draw_bytes(9)
assert not any(x[4:8])
ConjectureRunner(f, settings=settings(buffer_size=10)).run()
def test_can_write_bytes_towards_the_end():
buf = b"\1\2\3"
def f(data):
if data.draw_bits(1):
data.draw_bytes(5)
data.write(hbytes(buf))
assert hbytes(data.buffer[-len(buf) :]) == buf
ConjectureRunner(f, settings=settings(buffer_size=10)).run()
def test_can_increase_number_of_bytes_drawn_in_tail():
# This is designed to trigger a case where the zero bound queue will end up
# increasing the size of data drawn because moving zeroes into the initial
# prefix will increase the amount drawn.
def f(data):
x = data.draw_bytes(5)
n = x.count(0)
b = data.draw_bytes(n + 1)
assert not any(b)
runner = ConjectureRunner(
f,
settings=settings(
max_examples=100, buffer_size=11, suppress_health_check=HealthCheck.all()
),
)
runner.run()
def test_uniqueness_is_preserved_when_writing_at_beginning():
seen = set()
def f(data):
data.write(hbytes(1))
n = data.draw_bits(3)
assert n not in seen
seen.add(n)
runner = ConjectureRunner(f, settings=settings(max_examples=50))
runner.run()
assert runner.valid_examples == len(seen)
@pytest.mark.parametrize("skip_target", [False, True])
@pytest.mark.parametrize("initial_attempt", [127, 128])
def test_clears_out_its_database_on_shrinking(
initial_attempt, skip_target, monkeypatch
):
def generate_new_examples(self):
self.cached_test_function(initial_attempt)
monkeypatch.setattr(
ConjectureRunner, "generate_new_examples", generate_new_examples
)
key = b"key"
db = InMemoryExampleDatabase()
def f(data):
if data.draw_bits(8) >= 127:
data.mark_interesting()
runner = ConjectureRunner(
f,
settings=settings(database=db, max_examples=256),
database_key=key,
random=Random(0),
)
for n in hrange(256):
if n != 127 or not skip_target:
db.save(runner.secondary_key, hbytes([n]))
runner.run()
assert len(runner.interesting_examples) == 1
for b in db.fetch(runner.secondary_key):
assert b[0] >= 127
assert len(list(db.fetch(runner.database_key))) == 1
def test_can_delete_intervals():
@shrinking_from([255] * 10 + [1, 3])
def shrinker(data):
while True:
n = data.draw_bits(8)
if n == 255:
continue
elif n == 1:
break
else:
data.mark_invalid()
if data.draw_bits(8) == 3:
data.mark_interesting()
shrinker.fixate_shrink_passes(["adaptive_example_deletion"])
x = shrinker.shrink_target
assert x.buffer == hbytes([1, 3])
def test_detects_too_small_block_starts():
call_count = [0]
def f(data):
assert call_count[0] == 0
call_count[0] += 1
data.draw_bytes(8)
data.mark_interesting()
runner = ConjectureRunner(f, settings=settings(database=None))
r = runner.cached_test_function(hbytes(8))
assert r.status == Status.INTERESTING
assert call_count[0] == 1
r2 = runner.cached_test_function(hbytes([255] * 7))
assert r2.status == Status.OVERRUN
assert call_count[0] == 1
def test_shrinks_both_interesting_examples(monkeypatch):
def generate_new_examples(self):
self.cached_test_function(hbytes([1]))
monkeypatch.setattr(
ConjectureRunner, "generate_new_examples", generate_new_examples
)
def f(data):
n = data.draw_bits(8)
data.mark_interesting(n & 1)
runner = ConjectureRunner(f, database_key=b"key")
runner.run()
assert runner.interesting_examples[0].buffer == hbytes([0])
assert runner.interesting_examples[1].buffer == hbytes([1])
def test_duplicate_blocks_that_go_away():
@shrinking_from([1, 1, 1, 2] * 2 + [5] * 2)
def shrinker(data):
x = data.draw_bits(32)
y = data.draw_bits(32)
if x != y:
data.mark_invalid()
b = [data.draw_bytes(1) for _ in hrange(x & 255)]
if len(set(b)) <= 1:
data.mark_interesting()
shrinker.fixate_shrink_passes(["minimize_duplicated_blocks"])
assert shrinker.shrink_target.buffer == hbytes([0] * 8)
def test_accidental_duplication(monkeypatch):
@shrinking_from([18] * 20)
def shrinker(data):
x = data.draw_bits(8)
y = data.draw_bits(8)
if x != y:
data.mark_invalid()
if x < 5:
data.mark_invalid()
b = [data.draw_bytes(1) for _ in hrange(x)]
if len(set(b)) == 1:
data.mark_interesting()
shrinker.fixate_shrink_passes(["minimize_duplicated_blocks"])
assert list(shrinker.buffer) == [5] * 7
def test_discarding(monkeypatch):
monkeypatch.setattr(Shrinker, "shrink", Shrinker.remove_discarded)
monkeypatch.setattr(
ConjectureRunner,
"generate_new_examples",
lambda runner: runner.cached_test_function(hbytes([0, 1] * 10)),
)
@run_to_buffer
def x(data):
count = 0
while count < 10:
data.start_example(SOME_LABEL)
b = data.draw_bits(1)
if b:
count += 1
data.stop_example(discard=not b)
data.mark_interesting()
assert x == hbytes(hbytes([1]) * 10)
def test_can_remove_discarded_data():
@shrinking_from(hbytes([0] * 10) + hbytes([11]))
def shrinker(data):
while True:
data.start_example(SOME_LABEL)
b = data.draw_bits(8)
data.stop_example(discard=(b == 0))
if b == 11:
break
data.mark_interesting()
shrinker.remove_discarded()
assert list(shrinker.buffer) == [11]
def test_discarding_iterates_to_fixed_point():
@shrinking_from(hbytes([1] * 10) + hbytes([0]))
def shrinker(data):
data.start_example(0)
data.draw_bits(1)
data.stop_example(discard=True)
while data.draw_bits(1):
pass
data.mark_interesting()
shrinker.remove_discarded()
assert list(shrinker.buffer) == [1, 0]
def test_discarding_is_not_fooled_by_empty_discards():
@shrinking_from(hbytes([1, 1]))
def shrinker(data):
data.draw_bits(1)
data.start_example(0)
data.stop_example(discard=True)
data.draw_bits(1)
data.mark_interesting()
shrinker.remove_discarded()
assert shrinker.shrink_target.has_discards
def test_discarding_can_fail(monkeypatch):
@shrinking_from(hbytes([1]))
def shrinker(data):
data.start_example(0)
data.draw_bits(1)
data.stop_example(discard=True)
data.mark_interesting()
shrinker.remove_discarded()
assert any(e.discarded and e.length > 0 for e in shrinker.shrink_target.examples)
def test_depth_bounds_in_generation():
depth = [0]
def tails(data, n):
depth[0] = max(depth[0], n)
if data.draw_bits(8):
data.start_example(SOME_LABEL)
tails(data, n + 1)
data.stop_example()
def f(data):
tails(data, 0)
runner = ConjectureRunner(f, settings=settings(database=None, max_examples=20))
runner.run()
assert 0 < depth[0] <= MAX_DEPTH
def test_shrinking_from_mostly_zero(monkeypatch):
monkeypatch.setattr(
ConjectureRunner,
"generate_new_examples",
lambda self: self.cached_test_function(hbytes(5) + hbytes([2])),
)
@run_to_buffer
def x(data):
s = [data.draw_bits(8) for _ in hrange(6)]
if any(s):
data.mark_interesting()
assert x == hbytes(5) + hbytes([1])
def test_handles_nesting_of_discard_correctly(monkeypatch):
monkeypatch.setattr(Shrinker, "shrink", Shrinker.remove_discarded)
monkeypatch.setattr(
ConjectureRunner,
"generate_new_examples",
lambda runner: runner.cached_test_function(hbytes([0, 0, 1, 1])),
)
@run_to_buffer
def x(data):
while True:
data.start_example(SOME_LABEL)
succeeded = data.draw_bits(1)
data.start_example(SOME_LABEL)
data.draw_bits(1)
data.stop_example(discard=not succeeded)
data.stop_example(discard=not succeeded)
if succeeded:
data.mark_interesting()
assert x == hbytes([1, 1])
def test_can_zero_subintervals(monkeypatch):
@shrinking_from(hbytes([3, 0, 0, 0, 1]) * 10)
def shrinker(data):
for _ in hrange(10):
data.start_example(SOME_LABEL)
n = data.draw_bits(8)
data.draw_bytes(n)
data.stop_example()
if data.draw_bits(8) != 1:
return
data.mark_interesting()
shrinker.fixate_shrink_passes(["zero_examples"])
assert list(shrinker.buffer) == [0, 1] * 10
def test_can_pass_to_an_indirect_descendant(monkeypatch):
def tree(data):
data.start_example(1)
n = data.draw_bits(1)
label = data.draw_bits(8)
if n:
tree(data)
tree(data)
data.stop_example(1)
return label
initial = hbytes([1, 10, 0, 0, 1, 0, 0, 10, 0, 0])
target = hbytes([0, 10])
good = {initial, target}
@shrinking_from(initial)
def shrinker(data):
tree(data)
if hbytes(data.buffer) in good:
data.mark_interesting()
shrinker.fixate_shrink_passes(["pass_to_descendant"])
assert shrinker.shrink_target.buffer == target
def shrink(buffer, *passes):
def accept(f):
shrinker = shrinking_from(buffer)(f)
shrinker.fixate_shrink_passes(passes)
return list(shrinker.buffer)
return accept
def test_shrinking_blocks_from_common_offset():
@shrinking_from([11, 10])
def shrinker(data):
m = data.draw_bits(8)
n = data.draw_bits(8)
if abs(m - n) <= 1 and max(m, n) > 0:
data.mark_interesting()
shrinker.mark_changed(0)
shrinker.mark_changed(1)
shrinker.lower_common_block_offset()
x = shrinker.shrink_target.buffer
assert sorted(x) == [0, 1]
def test_handle_empty_draws(monkeypatch):
monkeypatch.setattr(
Shrinker,
"shrink",
lambda self: self.fixate_shrink_passes(["adaptive_example_deletion"]),
)
@run_to_buffer
def x(data):
while True:
data.start_example(SOME_LABEL)
n = data.draw_bits(1)
data.start_example(SOME_LABEL)
data.stop_example()
data.stop_example(discard=n > 0)
if not n:
break
data.mark_interesting()
assert x == hbytes([0])
def test_large_initial_write():
big = hbytes(b"\xff") * 512
def f(data):
data.write(big)
data.draw_bits(63)
with deterministic_PRNG():
runner = ConjectureRunner(
f,
settings=settings(
max_examples=5000,
buffer_size=1024,
database=None,
suppress_health_check=HealthCheck.all(),
),
)
runner.run()
assert runner.exit_reason == ExitReason.finished
def test_can_reorder_examples():
@shrinking_from([1, 0, 1, 1, 0, 1, 0, 0, 0])
def shrinker(data):
total = 0
for _ in range(5):
data.start_example(0)
if data.draw_bits(8):