Debian Codegraph @

hypothesis-python/tests/conjecture/common.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 dataclasses
12 import math
13 import sys
14 from contextlib import contextmanager
15 from random import Random
16 from threading import RLock
17
18 import pytest
19
20 from hypothesis import HealthCheck, Phase, settings, strategies as st
21 from hypothesis.control import current_build_context, currently_in_test_context
22 from hypothesis.internal.conjecture import engine as engine_module
23 from hypothesis.internal.conjecture.choice import ChoiceNode, ChoiceT
24 from hypothesis.internal.conjecture.data import ConjectureData, Status
25 from hypothesis.internal.conjecture.engine import ConjectureRunner
26 from hypothesis.internal.conjecture.provider_conformance import (
27 choice_types_constraints,
28 constraints_strategy,
29 )
30 from hypothesis.internal.conjecture.providers import COLLECTION_DEFAULT_MAX_SIZE
31 from hypothesis.internal.conjecture.utils import calc_label_from_name
32 from hypothesis.internal.escalation import InterestingOrigin
33 from hypothesis.internal.floats import SMALLEST_SUBNORMAL
34 from hypothesis.internal.intervalsets import IntervalSet
35
36 SOME_LABEL = calc_label_from_name("some label")
37
38
39 def interesting_origin(n: int | None = None) -> InterestingOrigin:
40 """
41 Creates and returns an InterestingOrigin, parameterized by n, such that
42 interesting_origin(n) == interesting_origin(m) iff n = m.
43
44 Since n=None may by chance concide with an explicitly-passed value of n, I
45 recommend not mixing interesting_origin() and interesting_origin(n) in the
46 same test.
47 """
48 try:
49 int("not an int")
50 except Exception as e:
51 origin = InterestingOrigin.from_exception(e)
52 return dataclasses.replace(origin, lineno=n if n is not None else origin.lineno)
53
54
55 def run_to_data(f):
56 runner = ConjectureRunner(
57 f,
58 settings=settings(
59 max_examples=300, database=None, suppress_health_check=list(HealthCheck)
60 ),
61 random=Random(0),
62 )
63 runner.run()
64 assert runner.interesting_examples
65 (last_data,) = runner.interesting_examples.values()
66 return last_data
67
68
69 def run_to_nodes(f):
70 return run_to_data(f).nodes
71
72
73 _buffer_size_lock = RLock()
74
75
76 @contextmanager
77 def buffer_size_limit(n):
78 with _buffer_size_lock:
79 original = engine_module.BUFFER_SIZE
80 try:
81 engine_module.BUFFER_SIZE = n
82 yield
83 finally:
84 engine_module.BUFFER_SIZE = original
85
86
87 def shrinking_from(start):
88 def accept(f):
89 runner = ConjectureRunner(
90 f,
91 settings=settings(
92 max_examples=5000,
93 database=None,
94 suppress_health_check=list(HealthCheck),
95 # avoid running the explain phase in shrinker.shrink() in tests
96 # which don't test the inquisitor.
97 phases=set(settings.default.phases) - {Phase.explain},
98 ),
99 random=Random(0),
100 )
101 runner.cached_test_function(start)
102 assert runner.interesting_examples
103
104 (last_data,) = runner.interesting_examples.values()
105 return runner.new_shrinker(last_data, lambda d: d.status == Status.INTERESTING)
106
107 return accept
108
109
110 def fresh_data(*, random=None, observer=None) -> ConjectureData:
111 context = current_build_context() if currently_in_test_context() else None
112 if context is not None and settings().backend == "crosshair":
113 # we should reeaxmine fresh_data sometime and see if we can replace it
114 # with nicer and higher level hypothesis idioms.
115 #
116 # For now it doesn't work well with crosshair tests. This is no big
117 # loss, because these tests often rely on hypothesis-provider-specific
118 # things.
119 pytest.skip(
120 "Fresh data is too low level (and too much of a hack) to be "
121 "worth supporting when testing with crosshair"
122 )
123
124 if random is None:
125 if context is None:
126 # ensure usage of fresh_data() is not flaky outside of property tests.
127 raise ValueError(
128 "must pass a seeded Random instance to fresh_data() when "
129 "outside of a build context"
130 ) from None
131
132 # within property tests, ensure fresh_data uses a controlled source of
133 # randomness.
134 # drawing this from the current build context is almost *too* magical. But
135 # the alternative is an extra @given(st.randoms()) everywhere we use
136 # fresh_data, so eh.
137
138 # @example uses a zero-length data, which means we can't use a
139 # hypothesis-backed random (which would entail drawing from the data).
140 # In this case, use a deterministic Random(0).
141 random = (
142 context.data.draw(st.randoms(use_true_random=True))
143 if (choices := context.data.max_choices) is None or choices > 0
144 else Random(0)
145 )
146
147 return ConjectureData(random=random, observer=observer)
148
149
150 def clamped_shrink_towards(constraints):
151 v = constraints["shrink_towards"]
152 if constraints["min_value"] is not None:
153 v = max(constraints["min_value"], v)
154 if constraints["max_value"] is not None:
155 v = min(constraints["max_value"], v)
156 return v
157
158
159 def draw_value(choice_type, constraints):
160 data = fresh_data()
161 return getattr(data, f"draw_{choice_type}")(**constraints)
162
163
164 @st.composite
165 def choices(draw):
166 (choice_type, constraints) = draw(choice_types_constraints())
167 return draw_value(choice_type, constraints)
168
169
170 @st.composite
171 def nodes(draw, *, was_forced=None, choice_types=None):
172 if choice_types is None:
173 (choice_type, constraints) = draw(choice_types_constraints())
174 else:
175 choice_type = draw(st.sampled_from(choice_types))
176 constraints = draw(constraints_strategy(choice_type))
177 # choice nodes don't include forced in their constraints. see was_forced attribute
178 del constraints["forced"]
179 value = draw_value(choice_type, constraints)
180 was_forced = draw(st.booleans()) if was_forced is None else was_forced
181
182 return ChoiceNode(
183 type=choice_type, value=value, constraints=constraints, was_forced=was_forced
184 )
185
186
187 def nodes_inline(*values: list[ChoiceT]) -> list[ChoiceNode]:
188 """
189 For inline-creating a choice node or list of choice nodes, where you don't
190 care about the constraints. This uses maximally-permissable constraints and
191 infers the choice_type you meant based on the type of the value.
192
193 You can optionally pass (value, constraints) to as an element in order to override
194 the default constraints for that element.
195 """
196 mapping = {
197 float: (
198 "float",
199 {
200 "min_value": -math.inf,
201 "max_value": math.inf,
202 "allow_nan": True,
203 "smallest_nonzero_magnitude": SMALLEST_SUBNORMAL,
204 },
205 ),
206 int: (
207 "integer",
208 {
209 "min_value": None,
210 "max_value": None,
211 "weights": None,
212 "shrink_towards": 0,
213 },
214 ),
215 str: (
216 "string",
217 {
218 "intervals": IntervalSet(((0, sys.maxunicode),)),
219 "min_size": 0,
220 "max_size": COLLECTION_DEFAULT_MAX_SIZE,
221 },
222 ),
223 bytes: ("bytes", {"min_size": 0, "max_size": COLLECTION_DEFAULT_MAX_SIZE}),
224 bool: ("boolean", {"p": 0.5}),
225 }
226 nodes = []
227 for value in values:
228 override_constraints = {}
229 if isinstance(value, tuple):
230 (value, override_constraints) = value
231 if override_constraints is None:
232 override_constraints = {}
233
234 (choice_type, constraints) = mapping[type(value)]
235
236 nodes.append(
237 ChoiceNode(
238 type=choice_type,
239 value=value,
240 constraints=constraints | override_constraints,
241 was_forced=False,
242 )
243 )
244
245 return tuple(nodes)
246
247
248 def float_constr(
249 min_value=-math.inf,
250 max_value=math.inf,
251 *,
252 allow_nan=True,
253 smallest_nonzero_magnitude=SMALLEST_SUBNORMAL,
254 ):
255 return {
256 "min_value": float(min_value),
257 "max_value": float(max_value),
258 "allow_nan": allow_nan,
259 "smallest_nonzero_magnitude": float(smallest_nonzero_magnitude),
260 }
261
262
263 def integer_constr(min_value=None, max_value=None, *, weights=None, shrink_towards=0):
264 return {
265 "min_value": min_value,
266 "max_value": max_value,
267 "weights": weights,
268 "shrink_towards": shrink_towards,
269 }
270
271
272 def string_constr(intervals, *, min_size=0, max_size=COLLECTION_DEFAULT_MAX_SIZE):
273 return {"intervals": intervals, "min_size": min_size, "max_size": max_size}
274
275
276 # we could in theory define bytes_constr and boolean_constr, but without any
277 # default kw values they aren't really a time save.