Debian Codegraph @

hypothesis-python/tests/common/utils.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 contextlib
12 import enum
13 import math
14 import sys
15 import time
16 import warnings
17 from io import StringIO
18 from threading import Barrier, Lock, RLock, Thread
19
20 import pytest
21 from pytest import mark
22
23 from hypothesis import Phase, settings
24 from hypothesis.errors import HypothesisDeprecationWarning
25 from hypothesis.internal import observability
26 from hypothesis.internal.floats import next_down
27 from hypothesis.internal.observability import (
28 Observation,
29 add_observability_callback,
30 remove_observability_callback,
31 )
32 from hypothesis.internal.reflection import get_pretty_function_description, proxies
33 from hypothesis.reporting import default, with_reporter
34 from hypothesis.strategies._internal.core import from_type, register_type_strategy
35 from hypothesis.strategies._internal.types import _global_type_lookup
36
37 # we need real time here, not monkeypatched for CI
38 time_sleep = time.sleep
39
40 skipif_emscripten = mark.skipif(
41 sys.platform == "emscripten",
42 reason="threads, processes, etc. are not available in the browser",
43 )
44
45 no_shrink = tuple(set(settings.default.phases) - {Phase.shrink, Phase.explain})
46
47
48 def flaky(max_runs, min_passes):
49 assert isinstance(max_runs, int)
50 assert isinstance(min_passes, int)
51 assert 0 < min_passes <= max_runs <= 50 # arbitrary cap
52
53 def accept(func):
54 @proxies(func)
55 def inner(*args, **kwargs):
56 runs = passes = 0
57 while passes < min_passes:
58 runs += 1
59 try:
60 func(*args, **kwargs)
61 passes += 1
62 except BaseException:
63 if runs >= max_runs:
64 raise
65
66 return inner
67
68 return accept
69
70
71 capture_out_lock = Lock()
72
73
74 @contextlib.contextmanager
75 def capture_out():
76 # replacing the singleton sys.stdout can't be made thread safe. Disallow
77 # concurrency by wrapping a lock around the entire block
78 with capture_out_lock:
79 old_out = sys.stdout
80 try:
81 new_out = StringIO()
82 sys.stdout = new_out
83 with with_reporter(default):
84 yield new_out
85 finally:
86 sys.stdout = old_out
87
88
89 class ExcInfo:
90 pass
91
92
93 def fails_with(e, *, match=None):
94 def accepts(f):
95 @proxies(f)
96 def inverted_test(*arguments, **kwargs):
97 with pytest.raises(e, match=match):
98 f(*arguments, **kwargs)
99
100 return inverted_test
101
102 return accepts
103
104
105 fails = fails_with(AssertionError)
106
107
108 class NotDeprecated(Exception):
109 pass
110
111
112 @contextlib.contextmanager
113 def validate_deprecation():
114
115 if settings.get_current_profile_name() == "threading":
116 import pytest
117
118 if sys.version_info[:2] < (3, 14):
119 pytest.skip("warnings module is not thread-safe before 3.14")
120
121 import warnings
122
123 try:
124 warnings.simplefilter("always", HypothesisDeprecationWarning)
125 with warnings.catch_warnings(record=True) as w:
126 yield
127 finally:
128 warnings.simplefilter("error", HypothesisDeprecationWarning)
129 if not any(e.category == HypothesisDeprecationWarning for e in w):
130 raise NotDeprecated(
131 f"Expected a deprecation warning but got {[e.category for e in w]!r}"
132 )
133
134
135 def checks_deprecated_behaviour(func):
136 """A decorator for testing deprecated behaviour."""
137
138 @proxies(func)
139 def _inner(*args, **kwargs):
140 with validate_deprecation():
141 return func(*args, **kwargs)
142
143 return _inner
144
145
146 def all_values(db):
147 return {v for vs in db.data.values() for v in vs}
148
149
150 def non_covering_examples(database):
151 return {
152 v for k, vs in database.data.items() if not k.endswith(b".pareto") for v in vs
153 }
154
155
156 def counts_calls(func):
157 """A decorator that counts how many times a function was called, and
158 stores that value in a ``.calls`` attribute.
159 """
160 assert not hasattr(func, "calls")
161
162 @proxies(func)
163 def _inner(*args, **kwargs):
164 _inner.calls += 1
165 return func(*args, **kwargs)
166
167 _inner.calls = 0
168 return _inner
169
170
171 def assert_output_contains_failure(output, test, **kwargs):
172 assert test.__name__ + "(" in output
173 for k, v in kwargs.items():
174 assert f"{k}={v!r}" in output, (f"{k}={v!r}", output)
175
176
177 def assert_falsifying_output(
178 test, example_type="Falsifying", expected_exception=AssertionError, **kwargs
179 ):
180 with capture_out() as out:
181 if expected_exception is None:
182 # Some tests want to check the output of non-failing runs.
183 test()
184 msg = ""
185 else:
186 with pytest.raises(expected_exception) as exc_info:
187 test()
188 notes = "\n".join(getattr(exc_info.value, "__notes__", []))
189 msg = str(exc_info.value) + "\n" + notes
190
191 output = out.getvalue() + msg
192 assert f"{example_type} example:" in output
193 assert_output_contains_failure(output, test, **kwargs)
194
195
196 temp_registered_lock = RLock()
197
198
199 @contextlib.contextmanager
200 def temp_registered(type_, strat_or_factory):
201 """Register and un-register a type for st.from_type().
202
203 This is not too hard, but there's a subtlety in restoring the
204 previously-registered strategy which we got wrong in a few places.
205 """
206 with temp_registered_lock:
207 prev = _global_type_lookup.get(type_)
208 register_type_strategy(type_, strat_or_factory)
209 try:
210 yield
211 finally:
212 del _global_type_lookup[type_]
213 from_type.__clear_cache()
214 if prev is not None:
215 register_type_strategy(type_, prev)
216
217
218 @contextlib.contextmanager
219 def raises_warning(expected_warning, match=None):
220 """Use instead of pytest.warns to check that the raised warning is handled properly"""
221 with pytest.raises(expected_warning, match=match) as r, warnings.catch_warnings():
222 warnings.simplefilter("error", category=expected_warning)
223 yield r
224
225
226 @contextlib.contextmanager
227 def capture_observations(*, choices=None):
228 ls: list[Observation] = []
229 add_observability_callback(ls.append)
230 if choices is not None:
231 old_choices = observability.OBSERVABILITY_CHOICES
232 observability.OBSERVABILITY_CHOICES = choices
233
234 try:
235 yield ls
236 finally:
237 remove_observability_callback(ls.append)
238 if choices is not None:
239 observability.OBSERVABILITY_CHOICES = old_choices
240
241
242 # Specifies whether we can represent subnormal floating point numbers.
243 # IEE-754 requires subnormal support, but it's often disabled anyway by unsafe
244 # compiler options like `-ffast-math`. On most hardware that's even a global
245 # config option, so *linking against* something built this way can break us.
246 # Everything is terrible
247 PYTHON_FTZ = next_down(sys.float_info.min) == 0.0
248
249
250 class Why(enum.Enum):
251 # Categorizing known failures, to ease later follow-up investigation.
252 # Some are crosshair issues, some hypothesis issues, others truly ok-to-xfail tests.
253 symbolic_outside_context = "CrosshairInternal error (using value outside context)"
254 nested_given = "nested @given decorators don't work with crosshair"
255 undiscovered = "crosshair may not find the failing input"
256 other = "reasons not elsewhere categorized"
257
258
259 def xfail_on_crosshair(why: Why, /, *, strict=True, as_marks=False):
260 # run `pytest -m xf_crosshair` to select these tests!
261 mark = pytest.mark.xfail(
262 strict=strict and why != Why.undiscovered,
263 reason=f"Expected failure due to: {why.value}",
264 condition=settings().backend == "crosshair",
265 )
266 if as_marks: # for use with pytest.param(..., marks=xfail_on_crosshair())
267 return (pytest.mark.xf_crosshair, mark)
268 return lambda fn: pytest.mark.xf_crosshair(mark(fn))
269
270
271 def skipif_threading(f):
272 return pytest.mark.skipif(
273 settings.get_current_profile_name() == "threading", reason="not thread safe"
274 )(f)
275
276
277 def xfail_if_gil_disabled(f):
278 try:
279 if not sys._is_gil_enabled(): # 3.13+
280 return pytest.mark.xfail(
281 reason="fails on free-threading build", strict=False
282 )(f)
283 except Exception:
284 pass
285 return f
286
287
288 # we don't monkeypatch _consistently_increment_time under threading
289 skipif_time_unpatched = skipif_threading
290
291
292 _restore_recursion_limit_lock = RLock()
293
294
295 @contextlib.contextmanager
296 def restore_recursion_limit():
297 with _restore_recursion_limit_lock:
298 original_limit = sys.getrecursionlimit()
299 try:
300 yield
301 finally:
302 sys.setrecursionlimit(original_limit)
303
304
305 def run_concurrently(function, *, n: int) -> None:
306 import pytest
307
308 if settings.get_current_profile_name() == "crosshair":
309 pytest.skip("crosshair is not thread safe")
310 if sys.platform == "emscripten":
311 pytest.skip("no threads on emscripten")
312
313 def run():
314 barrier.wait()
315 function()
316
317 threads = [Thread(target=run) for _ in range(n)]
318 barrier = Barrier(n)
319
320 for thread in threads:
321 thread.start()
322
323 for thread in threads:
324 thread.join(timeout=10)
325
326
327 def wait_for(condition, *, timeout=1, interval=0.01):
328 for _ in range(math.ceil(timeout / interval)):
329 if condition():
330 return
331 time_sleep(interval)
332 raise Exception(
333 f"timing out after waiting {timeout}s for condition "
334 f"{get_pretty_function_description(condition)}"
335 )
336
337
338 def run_test_for_falsifying_example(test_fn):
339 with pytest.raises(AssertionError) as err:
340 test_fn()
341 return "\n".join(err.value.__notes__).strip()