Debian Codegraph @

hypothesis-python/tests/crosshair/test_crosshair.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 crosshair
12 import pytest
13 from hypothesis_crosshair_provider.crosshair_provider import CrossHairPrimitiveProvider
14
15 from hypothesis import Phase, Verbosity, event, given, settings, strategies as st
16 from hypothesis.database import InMemoryExampleDatabase
17 from hypothesis.internal.conjecture.providers import COLLECTION_DEFAULT_MAX_SIZE
18 from hypothesis.internal.intervalsets import IntervalSet
19 from hypothesis.internal.observability import with_observability_callback
20 from hypothesis.vendor.pretty import pretty
21
22 from tests.common.utils import capture_observations
23 from tests.conjecture.common import float_constr, integer_constr, string_constr
24
25
26 @pytest.mark.parametrize("verbosity", list(Verbosity))
27 def test_crosshair_works_for_all_verbosities(verbosity):
28 # check that we aren't realizing symbolics early in debug prints and killing
29 # test effectiveness.
30 @given(st.integers())
31 @settings(backend="crosshair", verbosity=verbosity, database=None)
32 def f(n):
33 assert n != 123456
34
35 with pytest.raises(AssertionError):
36 f()
37
38
39 @pytest.mark.parametrize("verbosity", list(Verbosity))
40 def test_crosshair_works_for_all_verbosities_data(verbosity):
41 # data draws have their own print path
42 if verbosity == Verbosity.quiet:
43 pytest.skip("Flaky test, pending fix")
44
45 @given(st.data())
46 @settings(backend="crosshair", verbosity=verbosity, database=None)
47 def f(data):
48 n = data.draw(st.integers())
49 assert n != 123456
50
51 with pytest.raises(AssertionError):
52 f()
53
54
55 def test_hypothesis_realizes_on_fatal_error():
56 # BaseException or internal hypothesis failures have a different database save
57 # path. Make sure we realize symbolic values on that path. This test is a bit
58 # of a no-op because we're really relying on our realization validation to
59 # pass here.
60 db = InMemoryExampleDatabase()
61
62 @given(st.integers())
63 @settings(database=db, backend="crosshair")
64 def f(n):
65 raise BaseException("marker")
66
67 with pytest.raises(BaseException, match="marker"):
68 f()
69
70
71 def count_choices_for(choice_type, constraints):
72 # returns the number of choices that crosshair makes for this draw, before
73 # hypothesis ever has a chance to interact with it.
74 provider = CrossHairPrimitiveProvider()
75 with provider.per_test_case_context_manager():
76 assert len(crosshair.statespace.context_statespace().choices_made) == 0
77 getattr(provider, f"draw_{choice_type}")(**constraints)
78 return len(crosshair.statespace.context_statespace().choices_made)
79
80
81 @pytest.mark.parametrize(
82 "strategy, expected_choices",
83 [
84 (st.integers(), lambda: count_choices_for("integer", integer_constr())),
85 (st.floats(), lambda: count_choices_for("float", float_constr())),
86 (
87 st.binary(),
88 lambda: count_choices_for(
89 "bytes", {"min_size": 0, "max_size": COLLECTION_DEFAULT_MAX_SIZE}
90 ),
91 ),
92 (st.booleans(), lambda: count_choices_for("boolean", {})),
93 (
94 st.text(),
95 lambda: count_choices_for(
96 "string", string_constr(IntervalSet.from_string("a"))
97 ),
98 ),
99 ],
100 ids=pretty,
101 )
102 def test_no_path_constraints_are_added_to_symbolic_values(strategy, expected_choices):
103 # check that we don't interact with returned symbolics from the crosshair
104 # provider in a way that would add decisions to crosshair's state space (ie
105 # add path constraints).
106
107 expected_choices = expected_choices()
108 # skip the first call, which is ChoiceTemplate(type="simplest") with the
109 # hypothesis backend.
110 called = False
111
112 # limit to one example to prevent crosshair from raising e.g.
113 # BackendCannotProceed(scope="verified") and switching to the hypothesis
114 # provider
115 @given(strategy)
116 @settings(
117 backend="crosshair", database=None, phases={Phase.generate}, max_examples=2
118 )
119 def f(value):
120 nonlocal called
121 if not called:
122 called = True
123 return
124 # if this test ever fails, we will replay it without crosshair, in which
125 # case the statespace is None.
126 statespace = crosshair.statespace.optional_context_statespace()
127 assert statespace is not None, "this test failed under crosshair"
128 assert len(statespace.choices_made) == expected_choices
129
130 f()
131
132
133 @pytest.mark.parametrize(
134 "strategy, extra_observability",
135 [
136 # we add an additional path constraint to ints in to_jsonable.
137 (st.integers(), 1),
138 (st.text(), 0),
139 (st.booleans(), 0),
140 (st.floats(), 0),
141 (st.binary(), 0),
142 ],
143 )
144 def test_observability_and_verbosity_dont_add_choices(strategy, extra_observability):
145 choices = {}
146 # skip the first call, which is ChoiceTemplate(type="simplest") with the
147 # hypothesis backend.
148 called = False
149
150 @given(strategy)
151 @settings(backend="crosshair", database=None, max_examples=2)
152 def f_normal(value):
153 nonlocal called
154 if called:
155 choices["normal"] = len(
156 crosshair.statespace.context_statespace().choices_made
157 )
158 called = True
159
160 f_normal()
161 called = False
162
163 @given(strategy)
164 @settings(
165 backend="crosshair", database=None, max_examples=2, verbosity=Verbosity.debug
166 )
167 def f_verbosity(value):
168 nonlocal called
169 if called:
170 choices["verbosity"] = len(
171 crosshair.statespace.context_statespace().choices_made
172 )
173 called = True
174
175 f_verbosity()
176 called = False
177
178 @given(strategy)
179 @settings(backend="crosshair", database=None, max_examples=2)
180 def f_observability(value):
181 nonlocal called
182 if called:
183 choices["observability"] = len(
184 crosshair.statespace.context_statespace().choices_made
185 )
186 called = True
187
188 with capture_observations():
189 f_observability()
190
191 assert (
192 choices["normal"]
193 == (choices["observability"] - extra_observability)
194 == choices["verbosity"]
195 )
196
197
198 def test_realizes_event():
199 saw_myevent = False
200
201 def callback(observation):
202 if observation.type != "test_case":
203 return
204
205 nonlocal saw_myevent
206 # crosshair might raise BackendCannotProceed(verified) during generation,
207 # which never reaches event().
208 if "myevent" in observation.features:
209 assert isinstance(observation.features["myevent"], int)
210 saw_myevent = True
211
212 @given(st.integers())
213 @settings(backend="crosshair", max_examples=5)
214 def test(n):
215 event("myevent", n)
216
217 with with_observability_callback(callback):
218 test()
219
220 assert saw_myevent
221
222
223 @given(st.integers())
224 @settings(backend="crosshair")
225 def test_event_with_realization(value):
226 event(value)
227 float(value)