Debian Codegraph @

hypothesis-python/tests/conjecture/test_choice.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 math
12 import sys
13 from copy import deepcopy
14
15 import pytest
16
17 from hypothesis import (
18 HealthCheck,
19 assume,
20 example,
21 given,
22 note,
23 settings,
24 strategies as st,
25 )
26 from hypothesis.errors import StopTest
27 from hypothesis.internal.conjecture.choice import (
28 ChoiceNode,
29 ChoiceTemplate,
30 choice_equal,
31 choice_from_index,
32 choice_permitted,
33 choice_to_index,
34 choices_key,
35 )
36 from hypothesis.internal.conjecture.data import (
37 COLLECTION_DEFAULT_MAX_SIZE,
38 ConjectureData,
39 Status,
40 choices_size,
41 )
42 from hypothesis.internal.conjecture.datatree import (
43 MAX_CHILDREN_EFFECTIVELY_INFINITE,
44 all_children,
45 compute_max_children,
46 )
47 from hypothesis.internal.conjecture.engine import choice_count
48 from hypothesis.internal.conjecture.provider_conformance import integer_constraints
49 from hypothesis.internal.floats import SMALLEST_SUBNORMAL, next_down, next_up
50 from hypothesis.internal.intervalsets import IntervalSet
51
52 from tests.common.debug import minimal
53 from tests.conjecture.common import (
54 choice_types_constraints,
55 clamped_shrink_towards,
56 draw_value,
57 float_constr,
58 fresh_data,
59 integer_constr,
60 nodes,
61 )
62
63
64 # we max out at 128 bit integers in the *unbounded* case, but someone may
65 # specify a bound with a larger magnitude. Ensure we calculate max children for
66 # those cases correctly.
67 @example(("integer", integer_constr(max_value=-(2**200))))
68 @example(("integer", integer_constr(min_value=2**200)))
69 @example(("integer", integer_constr(-(2**200), 2**200)))
70 @given(choice_types_constraints())
71 def test_compute_max_children_is_positive(choice_type_and_constraints):
72 choice_type, constraints = choice_type_and_constraints
73 assert compute_max_children(choice_type, constraints) >= 0
74
75
76 @pytest.mark.parametrize(
77 "choice_type, constraints, count_children",
78 [
79 ("integer", {"min_value": 1, "max_value": 2, "weights": {1: 0.1, 2: 0.1}}, 2),
80 # only possibility is the empty string
81 (
82 "string",
83 {"min_size": 0, "max_size": 100, "intervals": IntervalSet.from_string("")},
84 1,
85 ),
86 (
87 "string",
88 {"min_size": 0, "max_size": 0, "intervals": IntervalSet.from_string("abc")},
89 1,
90 ),
91 # 3 possibilities for each character, 8 characters, 3 ** 8 possibilities.
92 (
93 "string",
94 {"min_size": 8, "max_size": 8, "intervals": IntervalSet.from_string("abc")},
95 3**8,
96 ),
97 (
98 "string",
99 {
100 "min_size": 2,
101 "max_size": 8,
102 "intervals": IntervalSet.from_string("abcd"),
103 },
104 sum(4**k for k in range(2, 8 + 1)),
105 ),
106 (
107 "string",
108 {
109 "min_size": 0,
110 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
111 "intervals": IntervalSet.from_string("a"),
112 },
113 COLLECTION_DEFAULT_MAX_SIZE + 1,
114 ),
115 (
116 "string",
117 {
118 "min_size": 0,
119 "max_size": 10_000,
120 "intervals": IntervalSet.from_string("abcdefg"),
121 },
122 MAX_CHILDREN_EFFECTIVELY_INFINITE,
123 ),
124 (
125 "bytes",
126 {
127 "min_size": 0,
128 "max_size": 2,
129 },
130 sum(2 ** (8 * k) for k in range(2 + 1)),
131 ),
132 (
133 "bytes",
134 {
135 "min_size": 0,
136 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
137 },
138 MAX_CHILDREN_EFFECTIVELY_INFINITE,
139 ),
140 (
141 "bytes",
142 {
143 "min_size": 0,
144 "max_size": 10_000,
145 },
146 MAX_CHILDREN_EFFECTIVELY_INFINITE,
147 ),
148 ("boolean", {"p": 0.0}, 1),
149 ("boolean", {"p": 1.0}, 1),
150 ("boolean", {"p": 0.5}, 2),
151 ("boolean", {"p": 0.001}, 2),
152 ("boolean", {"p": 0.999}, 2),
153 ("float", float_constr(0.0, 0.0), 1),
154 ("float", float_constr(-0.0, -0.0), 1),
155 ("float", float_constr(-0.0, 0.0), 2),
156 ("float", float_constr(next_down(-0.0), next_up(0.0)), 4),
157 (
158 "float",
159 float_constr(
160 next_down(next_down(-0.0)),
161 next_up(next_up(0.0)),
162 smallest_nonzero_magnitude=next_up(SMALLEST_SUBNORMAL),
163 ),
164 4,
165 ),
166 ("float", float_constr(smallest_nonzero_magnitude=next_down(math.inf)), 6),
167 ("float", float_constr(1, 10, smallest_nonzero_magnitude=11.0), 0),
168 ("float", float_constr(-3, -2, smallest_nonzero_magnitude=4.0), 0),
169 ],
170 )
171 def test_compute_max_children(choice_type, constraints, count_children):
172 assert compute_max_children(choice_type, constraints) == count_children
173
174
175 @given(st.text(min_size=1, max_size=1), st.integers(0, 100))
176 def test_draw_string_single_interval_with_equal_bounds(s, n):
177 data = fresh_data()
178 intervals = IntervalSet.from_string(s)
179 assert data.draw_string(intervals, min_size=n, max_size=n) == s * n
180
181
182 @example(("boolean", {"p": 2**-65}))
183 @example(("boolean", {"p": 1 - 2**-65}))
184 @example(
185 (
186 "string",
187 {"min_size": 0, "max_size": 0, "intervals": IntervalSet.from_string("abc")},
188 )
189 )
190 @example(
191 ("string", {"min_size": 0, "max_size": 3, "intervals": IntervalSet.from_string("")})
192 )
193 @example(
194 (
195 "string",
196 {"min_size": 0, "max_size": 3, "intervals": IntervalSet.from_string("a")},
197 )
198 )
199 # all combinations of float signs
200 @example(("float", float_constr(next_down(-0.0), -0.0)))
201 @example(("float", float_constr(next_down(-0.0), next_up(0.0))))
202 @example(("float", float_constr(0.0, next_up(0.0))))
203 # using a smallest_nonzero_magnitude which happens to filter out everything
204 @example(("float", float_constr(1.0, 2.0, smallest_nonzero_magnitude=3.0)))
205 @example(("integer", integer_constr(1, 2, weights={1: 0.2, 2: 0.4})))
206 @given(choice_types_constraints())
207 @settings(suppress_health_check=[HealthCheck.filter_too_much])
208 def test_compute_max_children_and_all_children_agree(choice_type_and_constraints):
209 choice_type, constraints = choice_type_and_constraints
210 max_children = compute_max_children(choice_type, constraints)
211
212 # avoid slowdowns / OOM when reifying extremely large all_children generators.
213 # We also hard cap at MAX_CHILDREN_EFFECTIVELY_INFINITE, because max_children
214 # returns approximations after this value and so will disagree with
215 # all_children.
216 cap = min(100_000, MAX_CHILDREN_EFFECTIVELY_INFINITE)
217 assume(max_children < cap)
218 assert len(list(all_children(choice_type, constraints))) == max_children
219
220
221 # it's very hard to test that unbounded integer ranges agree with
222 # compute_max_children, because they by necessity require iterating over 2**127
223 # or more elements. We do the not great approximation of checking just the first
224 # element is what we expect.
225
226
227 @given(integer_constraints())
228 def test_compute_max_children_unbounded_integer_ranges(constraints):
229 expected = clamped_shrink_towards(constraints)
230 first = next(all_children("integer", constraints))
231 assert expected == first, (expected, first)
232
233
234 @given(st.randoms())
235 def test_nodes(random):
236 data = fresh_data(random=random)
237 data.draw_float(min_value=-10.0, max_value=10.0, forced=5.0)
238 data.draw_boolean(forced=True)
239
240 data.start_span(42)
241 data.draw_string(IntervalSet.from_string("abcd"), forced="abbcccdddd")
242 data.draw_bytes(8, 8, forced=bytes(8))
243 data.stop_span()
244
245 data.draw_integer(0, 100, forced=50)
246
247 data.freeze()
248 expected_tree_nodes = (
249 ChoiceNode(
250 type="float",
251 value=5.0,
252 constraints=float_constr(-10.0, 10.0),
253 was_forced=True,
254 ),
255 ChoiceNode(
256 type="boolean",
257 value=True,
258 constraints={"p": 0.5},
259 was_forced=True,
260 ),
261 ChoiceNode(
262 type="string",
263 value="abbcccdddd",
264 constraints={
265 "intervals": IntervalSet.from_string("abcd"),
266 "min_size": 0,
267 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
268 },
269 was_forced=True,
270 ),
271 ChoiceNode(
272 type="bytes",
273 value=bytes(8),
274 constraints={"min_size": 8, "max_size": 8},
275 was_forced=True,
276 ),
277 ChoiceNode(
278 type="integer",
279 value=50,
280 constraints=integer_constr(0, 100),
281 was_forced=True,
282 ),
283 )
284 assert data.nodes == expected_tree_nodes
285
286
287 @given(nodes())
288 def test_copy_choice_node(node):
289 assert node == node
290
291 assume(not node.was_forced)
292 new_value = draw_value(node.type, node.constraints)
293 # if we drew the same value as before, the node should still be equal
294 assert (node.copy(with_value=new_value) == node) is (
295 choice_equal(new_value, node.value)
296 )
297
298
299 @given(nodes())
300 def test_choice_node_equality(node):
301 assert node == node
302 # for coverage on our NotImplemented return, more than anything.
303 assert node != 42
304
305
306 @given(nodes(was_forced=True))
307 def test_cannot_modify_forced_nodes(node):
308 with pytest.raises(AssertionError):
309 node.copy(with_value=42)
310
311
312 def test_data_with_empty_choices_is_overrun():
313 data = ConjectureData.for_choices([])
314 with pytest.raises(StopTest):
315 data.draw_integer()
316
317 assert data.status is Status.OVERRUN
318
319
320 @given(nodes(was_forced=True))
321 def test_data_with_changed_forced_value(node):
322 # we had a forced node and then tried to draw a different forced value from it.
323 # nodes: v1 [was_forced=True]
324 # drawing: [forced=v2]
325 #
326 # This is actually fine; we'll just ignore the forced node (v1) and return
327 # what the draw expects (v2).
328
329 data = ConjectureData.for_choices([node.value])
330
331 draw_func = getattr(data, f"draw_{node.type}")
332 constraints = deepcopy(node.constraints)
333 constraints["forced"] = draw_value(node.type, node.constraints)
334 assume(not choice_equal(constraints["forced"], node.value))
335
336 assert choice_equal(draw_func(**constraints), constraints["forced"])
337
338
339 # ensure we hit bare-minimum coverage for all choice sequence types.
340 @example(
341 ChoiceNode(type="float", value=0.0, constraints=float_constr(), was_forced=True)
342 )
343 @example(
344 ChoiceNode(
345 type="boolean",
346 value=False,
347 constraints={"p": 0.5},
348 was_forced=True,
349 )
350 )
351 @example(
352 ChoiceNode(
353 type="integer", value=50, constraints=integer_constr(50, 100), was_forced=True
354 )
355 )
356 @example(
357 ChoiceNode(
358 type="string",
359 value="aaaa",
360 constraints={
361 "intervals": IntervalSet.from_string("bcda"),
362 "min_size": 4,
363 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
364 },
365 was_forced=True,
366 )
367 )
368 @example(
369 ChoiceNode(
370 type="bytes",
371 value=bytes(8),
372 constraints={"min_size": 8, "max_size": 8},
373 was_forced=True,
374 )
375 )
376 @given(nodes(was_forced=True))
377 def test_data_with_same_forced_value_is_valid(node):
378 # we had a forced node and then drew the same forced value. This is totally
379 # fine!
380 # nodes: v1 [was_forced=True]
381 # drawing: [forced=v1]
382 data = ConjectureData.for_choices([node.value])
383 draw_func = getattr(data, f"draw_{node.type}")
384
385 constraints = deepcopy(node.constraints)
386 constraints["forced"] = node.value
387 assert choice_equal(draw_func(**constraints), constraints["forced"])
388
389
390 @given(choice_types_constraints())
391 @settings(suppress_health_check=[HealthCheck.filter_too_much])
392 def test_all_children_are_permitted_values(choice_type_and_constraints):
393 choice_type, constraints = choice_type_and_constraints
394 max_children = compute_max_children(choice_type, constraints)
395
396 cap = min(100_000, MAX_CHILDREN_EFFECTIVELY_INFINITE)
397 assume(max_children < cap)
398
399 # test that all_children -> choice_permitted (but not necessarily the converse.)
400 for value in all_children(choice_type, constraints):
401 assert choice_permitted(value, constraints), value
402
403
404 @pytest.mark.parametrize(
405 "value, constraints, permitted",
406 [
407 (0, integer_constr(1, 2), False),
408 (2, integer_constr(0, 1), False),
409 (10, integer_constr(0, 20), True),
410 (int(2**128 / 2) - 1, integer_constr(), True),
411 (int(2**128 / 2), integer_constr(), True),
412 (math.nan, float_constr(0.0, 0.0), True),
413 (math.nan, float_constr(0.0, 0.0, allow_nan=False), False),
414 (2.0, float_constr(1.0, 3.0, smallest_nonzero_magnitude=2.5), False),
415 (
416 -2.0,
417 float_constr(-3.0, -1.0, smallest_nonzero_magnitude=2.5),
418 False,
419 ),
420 (1.0, float_constr(1.0, 1.0), True),
421 (
422 "abcd",
423 {
424 "min_size": 10,
425 "max_size": 20,
426 "intervals": IntervalSet.from_string("abcd"),
427 },
428 False,
429 ),
430 (
431 "abcd",
432 {
433 "min_size": 1,
434 "max_size": 3,
435 "intervals": IntervalSet.from_string("abcd"),
436 },
437 False,
438 ),
439 (
440 "abcd",
441 {"min_size": 1, "max_size": 10, "intervals": IntervalSet.from_string("e")},
442 False,
443 ),
444 (
445 "e",
446 {"min_size": 1, "max_size": 10, "intervals": IntervalSet.from_string("e")},
447 True,
448 ),
449 (b"a", {"min_size": 2, "max_size": 2}, False),
450 (b"aa", {"min_size": 2, "max_size": 2}, True),
451 (b"aa", {"min_size": 0, "max_size": 3}, True),
452 (b"a", {"min_size": 2, "max_size": 10}, False),
453 (True, {"p": 0}, False),
454 (False, {"p": 0}, True),
455 (True, {"p": 1}, True),
456 (False, {"p": 1}, False),
457 (True, {"p": 0.5}, True),
458 (False, {"p": 0.5}, True),
459 ],
460 )
461 def test_choice_permitted(value, constraints, permitted):
462 assert choice_permitted(value, constraints) == permitted
463
464
465 @given(nodes(was_forced=True))
466 def test_forced_nodes_are_trivial(node):
467 assert node.trivial
468
469
470 @pytest.mark.parametrize(
471 "node",
472 [
473 ChoiceNode(
474 type="float",
475 value=5.0,
476 constraints=float_constr(5.0, 10.0),
477 was_forced=False,
478 ),
479 ChoiceNode(
480 type="float",
481 value=0.0,
482 constraints=float_constr(-5.0, 5.0),
483 was_forced=False,
484 ),
485 ChoiceNode(
486 type="float", value=0.0, constraints=float_constr(), was_forced=False
487 ),
488 ChoiceNode(
489 type="boolean", value=False, constraints={"p": 0.5}, was_forced=False
490 ),
491 ChoiceNode(
492 type="boolean", value=True, constraints={"p": 1.0}, was_forced=False
493 ),
494 ChoiceNode(
495 type="boolean", value=False, constraints={"p": 0.0}, was_forced=False
496 ),
497 ChoiceNode(
498 type="string",
499 value="",
500 constraints={
501 "intervals": IntervalSet.from_string("abcd"),
502 "min_size": 0,
503 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
504 },
505 was_forced=False,
506 ),
507 ChoiceNode(
508 type="string",
509 value="aaaa",
510 constraints={
511 "intervals": IntervalSet.from_string("bcda"),
512 "min_size": 4,
513 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
514 },
515 was_forced=False,
516 ),
517 ChoiceNode(
518 type="bytes",
519 value=bytes(8),
520 constraints={"min_size": 8, "max_size": 8},
521 was_forced=False,
522 ),
523 ChoiceNode(
524 type="bytes",
525 value=bytes(2),
526 constraints={"min_size": 2, "max_size": COLLECTION_DEFAULT_MAX_SIZE},
527 was_forced=False,
528 ),
529 ChoiceNode(
530 type="integer",
531 value=50,
532 constraints=integer_constr(50, 100),
533 was_forced=False,
534 ),
535 ChoiceNode(
536 type="integer",
537 value=0,
538 constraints=integer_constr(-10, 10),
539 was_forced=False,
540 ),
541 ChoiceNode(
542 type="integer",
543 value=2,
544 constraints=integer_constr(-10, 10, shrink_towards=2),
545 was_forced=False,
546 ),
547 ChoiceNode(
548 type="integer",
549 value=-10,
550 constraints=integer_constr(-10, 10, shrink_towards=-12),
551 was_forced=False,
552 ),
553 ChoiceNode(
554 type="integer",
555 value=10,
556 constraints=integer_constr(-10, 10, shrink_towards=12),
557 was_forced=False,
558 ),
559 ChoiceNode(
560 type="integer", value=0, constraints=integer_constr(), was_forced=False
561 ),
562 ChoiceNode(
563 type="integer",
564 value=1,
565 constraints=integer_constr(min_value=-10, shrink_towards=1),
566 was_forced=False,
567 ),
568 ChoiceNode(
569 type="integer",
570 value=1,
571 constraints=integer_constr(max_value=10, shrink_towards=1),
572 was_forced=False,
573 ),
574 ChoiceNode(
575 type="integer",
576 value=1,
577 constraints={
578 "min_value": None,
579 "max_value": None,
580 "weights": None,
581 "shrink_towards": 1,
582 },
583 was_forced=False,
584 ),
585 ],
586 )
587 def test_trivial_nodes(node):
588 assert node.trivial
589
590 @st.composite
591 def values(draw):
592 data = draw(st.data()).conjecture_data
593 return getattr(data, f"draw_{node.type}")(**node.constraints)
594
595 # if we're trivial, then shrinking should produce the same value.
596 assert choice_equal(minimal(values()), node.value)
597
598
599 @pytest.mark.parametrize(
600 "node",
601 [
602 ChoiceNode(
603 type="float",
604 value=6.0,
605 constraints=float_constr(5.0, 10.0),
606 was_forced=False,
607 ),
608 ChoiceNode(
609 type="float",
610 value=-5.0,
611 constraints=float_constr(-5.0, 5.0),
612 was_forced=False,
613 ),
614 ChoiceNode(
615 type="float", value=1.0, constraints=float_constr(), was_forced=False
616 ),
617 ChoiceNode(
618 type="boolean", value=True, constraints={"p": 0.5}, was_forced=False
619 ),
620 ChoiceNode(
621 type="boolean", value=True, constraints={"p": 0.99}, was_forced=False
622 ),
623 ChoiceNode(
624 type="string",
625 value="d",
626 constraints={
627 "intervals": IntervalSet.from_string("abcd"),
628 "min_size": 1,
629 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
630 },
631 was_forced=False,
632 ),
633 ChoiceNode(
634 type="bytes",
635 value=b"\x01",
636 constraints={"min_size": 1, "max_size": 1},
637 was_forced=False,
638 ),
639 ChoiceNode(
640 type="bytes",
641 value=bytes(1),
642 constraints={"min_size": 0, "max_size": COLLECTION_DEFAULT_MAX_SIZE},
643 was_forced=False,
644 ),
645 ChoiceNode(
646 type="bytes",
647 value=bytes(2),
648 constraints={"min_size": 1, "max_size": 10},
649 was_forced=False,
650 ),
651 ChoiceNode(
652 type="integer",
653 value=-10,
654 constraints=integer_constr(-10, 10),
655 was_forced=False,
656 ),
657 ChoiceNode(
658 type="integer", value=42, constraints=integer_constr(), was_forced=False
659 ),
660 ],
661 )
662 def test_nontrivial_nodes(node):
663 assert not node.trivial
664
665 @st.composite
666 def values(draw):
667 data = draw(st.data()).conjecture_data
668 return getattr(data, f"draw_{node.type}")(**node.constraints)
669
670 # if we're nontrivial, then shrinking should produce something different.
671 assert not choice_equal(minimal(values()), node.value)
672
673
674 @pytest.mark.parametrize(
675 "node",
676 [
677 ChoiceNode(
678 type="float",
679 value=1.5,
680 constraints=float_constr(1.1, 1.6),
681 was_forced=False,
682 ),
683 ChoiceNode(
684 type="float",
685 value=float(math.floor(sys.float_info.max)),
686 constraints=float_constr(sys.float_info.max - 1, math.inf),
687 was_forced=False,
688 ),
689 ChoiceNode(
690 type="float",
691 value=float(math.ceil(-sys.float_info.max)),
692 constraints=float_constr(-math.inf, -sys.float_info.max + 1),
693 was_forced=False,
694 ),
695 ChoiceNode(
696 type="float",
697 value=math.inf,
698 constraints=float_constr(math.inf, math.inf),
699 was_forced=False,
700 ),
701 ChoiceNode(
702 type="float",
703 value=-math.inf,
704 constraints=float_constr(-math.inf, -math.inf),
705 was_forced=False,
706 ),
707 ],
708 )
709 def test_conservative_nontrivial_nodes(node):
710 # these nodes actually are trivial, but our analysis doesn't compute them
711 # as such. We'd like to improve this in the future!
712 assert not node.trivial
713
714 @st.composite
715 def values(draw):
716 data = draw(st.data()).conjecture_data
717 return getattr(data, f"draw_{node.type}")(**node.constraints)
718
719 assert choice_equal(minimal(values()), node.value)
720
721
722 @given(nodes())
723 def test_choice_node_is_hashable(node):
724 hash(node)
725
726
727 @given(st.lists(nodes()))
728 def test_choices_size_positive(nodes):
729 assert choices_size([n.value for n in nodes]) >= 0
730
731
732 @given(st.integers(min_value=1))
733 def test_node_template_count(n):
734 node = ChoiceTemplate(type="simplest", count=n)
735 assert choice_count([node]) == n
736
737
738 def test_node_template_to_overrun():
739 data = ConjectureData.for_choices([1, ChoiceTemplate("simplest", count=5)])
740 data.draw_integer()
741 with pytest.raises(StopTest):
742 for _ in range(10):
743 data.draw_integer()
744
745 assert data.status is Status.OVERRUN
746
747
748 def test_node_template_single_node_overruns():
749 # test for when drawing a single node takes more than BUFFER_SIZE, while in
750 # the ChoiceTemplate case
751 data = ConjectureData.for_choices((ChoiceTemplate("simplest", count=1),))
752 with pytest.raises(StopTest):
753 data.draw_bytes(10_000, 10_000)
754
755 assert data.status is Status.OVERRUN
756
757
758 @given(nodes())
759 def test_node_template_simplest_is_actually_trivial(node):
760 # TODO_IR node.trivial is sound but not complete for floats.
761 assume(node.type != "float")
762 data = ConjectureData.for_choices((ChoiceTemplate("simplest", count=1),))
763 getattr(data, f"draw_{node.type}")(**node.constraints)
764 assert len(data.nodes) == 1
765 assert data.nodes[0].trivial
766
767
768 @given(choice_types_constraints())
769 @example(("boolean", {"p": 0}))
770 @example(("boolean", {"p": 1}))
771 def test_choice_indices_are_positive(choice_type_and_constraints):
772 choice_type, constraints = choice_type_and_constraints
773 v = draw_value(choice_type, constraints)
774 assert choice_to_index(v, constraints) >= 0
775
776
777 @given(integer_constraints())
778 def test_shrink_towards_has_index_0(constraints):
779 shrink_towards = clamped_shrink_towards(constraints)
780 note({"clamped_shrink_towards": shrink_towards})
781 assert choice_to_index(shrink_towards, constraints) == 0
782 assert choice_from_index(0, "integer", constraints) == shrink_towards
783
784
785 @given(choice_types_constraints())
786 @settings(max_examples=20)
787 def test_choice_to_index_injective(choice_type_and_constraints):
788 # choice sequence ordering should be injective both ways.
789 choice_type, constraints = choice_type_and_constraints
790 # ...except for floats, which are hard to order bijectively.
791 assume(choice_type != "float")
792 # cap to 10k so this test finishes in a reasonable amount of time
793 cap = min(compute_max_children(choice_type, constraints), 10_000)
794
795 indices = set()
796 for i, choice in enumerate(all_children(choice_type, constraints)):
797 if i >= cap:
798 break
799 index = choice_to_index(choice, constraints)
800 assert index not in indices
801 indices.add(index)
802
803
804 @given(choice_types_constraints())
805 @settings(max_examples=10)
806 @example(
807 (
808 "string",
809 {"min_size": 0, "max_size": 10, "intervals": IntervalSet.from_string("a")},
810 )
811 )
812 def test_choice_from_value_injective(choice_type_and_constraints):
813 choice_type, constraints = choice_type_and_constraints
814 assume(choice_type != "float")
815 cap = min(compute_max_children(choice_type, constraints), 10_000)
816
817 choices = set()
818 for index in range(cap):
819 choice = choice_from_index(index, choice_type, constraints)
820 assert choice not in choices
821 choices.add(choice)
822
823
824 @given(choice_types_constraints())
825 def test_choice_index_and_value_are_inverses(choice_type_and_constraints):
826 choice_type, constraints = choice_type_and_constraints
827 v = draw_value(choice_type, constraints)
828 index = choice_to_index(v, constraints)
829 note({"v": v, "index": index})
830 choice_equal(choice_from_index(index, choice_type, constraints), v)
831
832
833 @pytest.mark.parametrize(
834 "choice_type, constraints, choices",
835 [
836 ("boolean", {"p": 1}, [True]),
837 ("boolean", {"p": 0}, [False]),
838 ("integer", integer_constr(min_value=1, shrink_towards=4), range(1, 10)),
839 ("integer", integer_constr(max_value=5, shrink_towards=2), range(-10, 5 + 1)),
840 ("integer", integer_constr(max_value=5), range(-10, 5 + 1)),
841 ("integer", integer_constr(min_value=0, shrink_towards=1), range(10)),
842 ("integer", integer_constr(-5, 5, shrink_towards=3), range(-5, 5 + 1)),
843 ("integer", integer_constr(-5, 5, shrink_towards=-3), range(-5, 5 + 1)),
844 (
845 "float",
846 float_constr(1.0, next_up(next_up(1.0))),
847 [1.0, next_up(1.0), next_up(next_up(1.0))],
848 ),
849 (
850 "float",
851 float_constr(next_down(-0.0), next_up(0.0)),
852 [next_down(-0.0), -0.0, 0.0, next_up(0.0)],
853 ),
854 ],
855 )
856 def test_choice_index_and_value_are_inverses_explicit(
857 choice_type, constraints, choices
858 ):
859 for choice in choices:
860 index = choice_to_index(choice, constraints)
861 assert choice_equal(choice_from_index(index, choice_type, constraints), choice)
862
863
864 @pytest.mark.parametrize(
865 "constraints, choices",
866 [
867 # unbounded
868 (integer_constr(), (0, 1, -1, 2, -2, 3, -3)),
869 (integer_constr(shrink_towards=2), (2, 3, 1, 4, 0, 5, -1, 6, -2)),
870 # semibounded (below)
871 (integer_constr(min_value=3), (3, 4, 5, 6, 7)),
872 (integer_constr(min_value=3, shrink_towards=5), (5, 6, 4, 7, 3, 8, 9)),
873 (integer_constr(min_value=-3), (0, 1, -1, 2, -2, 3, -3, 4, 5, 6)),
874 (integer_constr(min_value=-3, shrink_towards=-1), (-1, 0, -2, 1, -3, 2, 3, 4)),
875 # semibounded (above)
876 (integer_constr(max_value=3), (0, 1, -1, 2, -2, 3, -3, -4, -5, -6)),
877 (integer_constr(max_value=3, shrink_towards=1), (1, 2, 0, 3, -1, -2, -3, -4)),
878 (integer_constr(max_value=-3), (-3, -4, -5, -6, -7)),
879 (integer_constr(max_value=-3, shrink_towards=-5), (-5, -4, -6, -3, -7, -8, -9)),
880 # bounded
881 (integer_constr(-3, 3), (0, 1, -1, 2, -2, 3, -3)),
882 (integer_constr(-3, 3, shrink_towards=1), (1, 2, 0, 3, -1, -2, -3)),
883 (integer_constr(-3, 3, shrink_towards=-1), (-1, 0, -2, 1, -3, 2, 3)),
884 ],
885 ids=repr,
886 )
887 def test_integer_choice_index(constraints, choices):
888 # explicit test which checks that the order of `choices` matches the index
889 # order.
890 for i, choice in enumerate(choices):
891 assert choice_to_index(choice, constraints) == i
892
893
894 @given(st.lists(nodes()))
895 def test_drawing_directly_matches_for_choices(nodes):
896 data = ConjectureData.for_choices([n.value for n in nodes])
897 for node in nodes:
898 value = getattr(data, f"draw_{node.type}")(**node.constraints)
899 assert choice_equal(node.value, value)
900
901
902 def test_draw_directly_explicit():
903 # this is a much weaker and more explicit variant of the property-based test
904 # directly above, but this is such an important thing to ensure that we have
905 # correct that it's worth some duplication in case we ever screw up our pbt test.
906 assert (
907 ConjectureData.for_choices(["a"]).draw_string(
908 IntervalSet([(0, 127)]), min_size=1
909 )
910 == "a"
911 )
912 assert ConjectureData.for_choices([b"a"]).draw_bytes() == b"a"
913 assert (
914 ConjectureData.for_choices([1.0]).draw_float(
915 0.0, 2.0, allow_nan=False, smallest_nonzero_magnitude=0.5
916 )
917 == 1.0
918 )
919 assert ConjectureData.for_choices([True]).draw_boolean(0.3)
920 assert ConjectureData.for_choices([42]).draw_integer() == 42
921 assert (
922 ConjectureData.for_choices([-42]).draw_integer(min_value=-50, max_value=0)
923 == -42
924 )
925 assert (
926 ConjectureData.for_choices([10]).draw_integer(
927 min_value=10, max_value=11, weights={10: 0.1, 11: 0.3}
928 )
929 == 10
930 )
931
932
933 @pytest.mark.parametrize(
934 "choices1, choices2",
935 [
936 [(True,), (1,)],
937 [(True,), (1.0,)],
938 [(False,), (0,)],
939 [(False,), (0.0,)],
940 [(False,), (-0.0,)],
941 [(0.0,), (-0.0,)],
942 ],
943 )
944 def test_choices_key_distinguishes_weird_cases(choices1, choices2):
945 assert choices_key(choices1) != choices_key(choices2)
946
947
948 def test_node_template_overrun():
949 # different code path for overruning the ChoiceTemplate count, not BUFFER_SIZE.
950 cd = ConjectureData(
951 random=None,
952 prefix=[ChoiceTemplate("simplest", count=2)],
953 max_choices=100,
954 )
955
956 cd.draw_integer()
957 cd.draw_integer()
958 try:
959 cd.draw_integer()
960 except StopTest:
961 pass
962 assert cd.status is Status.OVERRUN