Debian Codegraph @

hypothesis-python/tests/quality/test_poisoned_lists.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 from random import Random
12
13 import pytest
14
15 from hypothesis import settings, strategies as st
16 from hypothesis.internal.compat import ceil
17 from hypothesis.internal.conjecture.engine import ConjectureData, ConjectureRunner
18 from hypothesis.strategies._internal import SearchStrategy
19
20 from tests.conjecture.common import interesting_origin
21
22 POISON = "POISON"
23
24
25 class Poisoned(SearchStrategy):
26 def __init__(self, poison_chance):
27 super().__init__()
28 self.__poison_chance = poison_chance
29 self.__ints = st.integers(0, 10)
30
31 def do_draw(self, data):
32 if data.draw_boolean(self.__poison_chance):
33 return POISON
34 else:
35 return data.draw(self.__ints)
36
37
38 class LinearLists(SearchStrategy):
39 def __init__(self, elements, size):
40 super().__init__()
41 self.__length = st.integers(0, size)
42 self.__elements = elements
43
44 def do_draw(self, data):
45 return [data.draw(self.__elements) for _ in range(data.draw(self.__length))]
46
47
48 class Matrices(SearchStrategy):
49 def __init__(self, elements, size):
50 super().__init__()
51 self.__length = st.integers(0, ceil(size**0.5))
52 self.__elements = elements
53
54 def do_draw(self, data):
55 n = data.draw(self.__length)
56 m = data.draw(self.__length)
57
58 return [data.draw(self.__elements) for _ in range(n * m)]
59
60
61 LOTS = 10**6
62
63 TRIAL_SETTINGS = settings(max_examples=LOTS, database=None)
64
65
66 @pytest.mark.parametrize(
67 "seed", [2282791295271755424, 1284235381287210546, 14202812238092722246, 26097]
68 )
69 @pytest.mark.parametrize("size", [5, 10, 20])
70 @pytest.mark.parametrize("p", [0.01, 0.1])
71 @pytest.mark.parametrize("strategy_class", [LinearLists, Matrices])
72 def test_minimal_poisoned_containers(seed, size, p, strategy_class):
73 elements = Poisoned(p)
74 strategy = strategy_class(elements, size)
75
76 def test_function(data):
77 v = data.draw(strategy)
78 data.output = repr(v)
79 if POISON in v:
80 data.mark_interesting(interesting_origin())
81
82 runner = ConjectureRunner(
83 test_function, random=Random(seed), settings=TRIAL_SETTINGS
84 )
85 runner.run()
86 (v,) = runner.interesting_examples.values()
87 result = ConjectureData.for_choices(v.choices).draw(strategy)
88 assert len(result) == 1