Debian Codegraph @

hypothesis-python/tests/conftest.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 gc
12 import inspect
13 import json
14 import os
15 import random
16 import sys
17 import time as time_module
18 from functools import wraps
19 from pathlib import Path
20
21 import pytest
22 from _pytest.monkeypatch import MonkeyPatch
23
24 from hypothesis import is_hypothesis_test, settings
25 from hypothesis._settings import is_in_ci
26 from hypothesis.errors import NonInteractiveExampleWarning
27 from hypothesis.internal import lambda_sources
28 from hypothesis.internal.compat import add_note
29 from hypothesis.internal.conjecture import junkdrawer
30
31 from tests.common import TIME_INCREMENT
32 from tests.common.setup import run
33 from tests.common.utils import raises_warning
34
35 run()
36
37 # Skip collection of tests which require the Django test runner,
38 # or that don't work on the current version of Python.
39 collect_ignore_glob = ["django/*"]
40 # this checks up until py319
41 for minor_increment in range(10):
42 minor = 10 + minor_increment
43 if sys.version_info < (3, minor):
44 collect_ignore_glob.append(f"cover/*py3{minor}*.py")
45
46 if sys.version_info >= (3, 11):
47 collect_ignore_glob.append("cover/test_asyncio.py") # @asyncio.coroutine removed
48
49
50 in_shrinking_benchmark = False
51
52
53 def pytest_configure(config):
54 config.addinivalue_line("markers", "slow: pandas expects this marker to exist.")
55 config.addinivalue_line(
56 "markers",
57 "xp_min_version(api_version): run when greater or equal to api_version",
58 )
59 config.addinivalue_line("markers", "xf_crosshair: selection for xfailing symbolics")
60
61 if config.getoption("--hypothesis-benchmark-shrinks"):
62 # we'd like to support xdist here, but a session-scope fixture won't
63 # be enough: https://github.com/pytest-dev/pytest-xdist/issues/271.
64 # Need a lockfile or equivalent.
65
66 assert config.getoption(
67 "--hypothesis-benchmark-output"
68 ), "must specify shrinking output file"
69
70 global in_shrinking_benchmark
71 in_shrinking_benchmark = True
72
73
74 def pytest_addoption(parser):
75 parser.addoption("--hypothesis-update-outputs", action="store_true")
76 parser.addoption("--hypothesis-benchmark-shrinks", type=str, choices=["new", "old"])
77 parser.addoption("--hypothesis-benchmark-output", type=str)
78
79
80 @pytest.fixture(scope="function", params=["warns", "raises"])
81 def warns_or_raises(request):
82 """This runs the test twice: first to check that a warning is emitted
83 and execution continues successfully despite the warning; then to check
84 that the raised warning is handled properly.
85 """
86 if request.param == "raises":
87 return raises_warning
88 else:
89 return pytest.warns
90
91
92 # crosshair needs actual time for its path timeouts; load it before patching
93 try:
94 import hypothesis_crosshair_provider.crosshair_provider # noqa: F401
95 except ImportError:
96 pass
97
98
99 if sys.version_info >= (3, 11):
100 # To detect if changes in code generation causes lambda test compilation
101 # to fail. Older versions (3.10 and earlier) have a few known false
102 # negatives which we ignore.
103 @pytest.fixture(scope="function", autouse=True)
104 def _make_unknown_lambdas_fail(monkeypatch):
105
106 def fail(candidate):
107 msg = (
108 f"Failed to find a matching source for {candidate}. "
109 "This could indicate changes in the Python code generator,\n"
110 "or just a previously unknown case. To quickly resolve this "
111 "problem, use the `allow_unknown_lambdas` fixture."
112 )
113 raise AssertionError(msg)
114
115 monkeypatch.setattr(
116 lambda_sources, "_check_unknown_perfectly_aligned_lambda", fail
117 )
118
119
120 @pytest.fixture(scope="function")
121 def allow_unknown_lambdas(monkeypatch):
122 # Will run after make...fail since autouse are run first
123
124 def nofail(candidate):
125 pass
126
127 monkeypatch.setattr(
128 lambda_sources, "_check_unknown_perfectly_aligned_lambda", nofail
129 )
130
131
132 # monkeypatch is not thread-safe, so pytest-run-parallel will skip all our tests
133 # if we define this.
134 if settings.get_current_profile_name() != "threading":
135
136 @pytest.fixture(scope="function", autouse=True)
137 def _consistently_increment_time(monkeypatch):
138 """Rather than rely on real system time we monkey patch time.time so that
139 it passes at a consistent rate between calls.
140
141 The reason for this is that when these tests run in CI, their performance is
142 extremely variable and the VM the tests are on might go to sleep for a bit,
143 introducing arbitrary delays. This can cause a number of tests to fail
144 flakily.
145
146 Replacing time with a fake version under our control avoids this problem.
147 """
148 frozen = False
149
150 current_time = time_module.time()
151
152 def time():
153 nonlocal current_time
154 if not frozen:
155 current_time += TIME_INCREMENT
156 return current_time
157
158 def sleep(naptime):
159 nonlocal current_time
160 current_time += naptime
161
162 def freeze():
163 nonlocal frozen
164 frozen = True
165
166 def _patch(name, fn):
167 monkeypatch.setattr(
168 time_module, name, wraps(getattr(time_module, name))(fn)
169 )
170
171 _patch("time", time)
172 _patch("monotonic", time)
173 _patch("perf_counter", time)
174 _patch("sleep", sleep)
175 monkeypatch.setattr(time_module, "freeze", freeze, raising=False)
176
177 # In the patched time regime, observing it causes it to increment. To avoid reintroducing
178 # non-determinism due to GC running at arbitrary times, we patch the GC observer
179 # to NOT increment time.
180
181 monkeypatch.setattr(junkdrawer, "_perf_counter", time)
182
183 if hasattr(gc, "callbacks"):
184 # ensure timer callback is added, then bracket it by freeze/unfreeze below
185 junkdrawer.gc_cumulative_time()
186
187 _was_frozen = False
188
189 def _freezer(*_):
190 nonlocal _was_frozen, frozen
191 _was_frozen = frozen
192 frozen = True
193
194 def _unfreezer(*_):
195 nonlocal _was_frozen, frozen
196 frozen = _was_frozen
197
198 gc.callbacks.insert(0, _freezer) # freeze before gc callback
199 gc.callbacks.append(_unfreezer) # unfreeze after
200
201 yield
202
203 assert gc.callbacks.pop(0) == _freezer
204 assert gc.callbacks.pop() == _unfreezer
205 else: # pragma: no cover # branch never taken in CPython
206 yield
207
208
209 random_states_after_tests = {}
210 independent_random = random.Random()
211
212
213 @pytest.hookimpl(hookwrapper=True)
214 def pytest_runtest_call(item):
215 if item.config.getoption("--hypothesis-benchmark-shrinks"):
216 yield from _benchmark_shrinks(item)
217 # ideally benchmark shrinking would not be mutually exclusive with the
218 # other checks in this function, but it's cleaner to early-return here,
219 # and in practice they will error in normal tests before one runs a
220 # benchmark.
221 return
222 # This hookwrapper checks for PRNG state leaks from Hypothesis tests.
223 # See: https://github.com/HypothesisWorks/hypothesis/issues/1919
224 if (
225 not (hasattr(item, "obj") and is_hypothesis_test(item.obj))
226 # we disable this check on the threading job, due to races in the global
227 # state.
228 or settings.get_current_profile_name() == "threading"
229 ):
230 outcome = yield
231 elif "pytest_randomly" in sys.modules:
232 # See https://github.com/HypothesisWorks/hypothesis/issues/3041 - this
233 # branch exists to make it easier on external contributors, but should
234 # never run in our CI (because that would disable the check entirely).
235 assert not is_in_ci()
236 outcome = yield
237 else:
238 # We start by peturbing the state of the PRNG, because repeatedly
239 # leaking PRNG state resets state_after to the (previously leaked)
240 # state_before, and that just shows as "no use of random".
241 random.seed(independent_random.randrange(2**32))
242 before = random.getstate()
243 outcome = yield
244 after = random.getstate()
245 if before != after:
246 if after in random_states_after_tests:
247 raise Exception(
248 f"{item.nodeid!r} and {random_states_after_tests[after]!r} "
249 "both used the `random` module, and finished with the "
250 "same global `random.getstate()`; this is probably a nasty bug!"
251 )
252 random_states_after_tests[after] = item.nodeid
253
254 # Annotate usage of .example() with a hint about alternatives
255 if isinstance(getattr(outcome, "exception", None), NonInteractiveExampleWarning):
256 add_note(
257 outcome.exception,
258 "For hypothesis' own test suite, consider using one of the helper "
259 "methods in tests.common.debug instead.",
260 )
261
262
263 timer = time_module.process_time
264
265
266 def _worker_path(session: pytest.Session) -> Path:
267 return (
268 Path(session.config.getoption("--hypothesis-benchmark-output")).parent
269 # https://pytest-xdist.readthedocs.io/en/stable/how-to.html#envvar-PYTEST_XDIST_WORKER
270 / f"shrinking_results_{os.environ['PYTEST_XDIST_WORKER']}.json"
271 )
272
273
274 def _benchmark_shrinks(item: pytest.Function) -> None:
275 from hypothesis.internal.conjecture.shrinker import Shrinker
276
277 # this isn't perfect, but it is cheap!
278 if "minimal(" not in inspect.getsource(item.function):
279 pytest.skip("(probably) does not call minimal()")
280
281 actual_shrink = Shrinker.shrink
282 shrink_calls = []
283 shrink_time = []
284
285 def shrink(self, *args, **kwargs):
286 nonlocal shrink_calls
287 nonlocal shrink_time
288 start_t = timer()
289 result = actual_shrink(self, *args, **kwargs)
290 shrink_calls.append(self.engine.call_count - self.initial_calls)
291 shrink_time.append(timer() - start_t)
292 return result
293
294 monkeypatch = MonkeyPatch()
295 monkeypatch.setattr(Shrinker, "shrink", shrink)
296
297 # pytest_runtest_call must yield at some point. This executes the test function
298 # n - 1 times, and then yields for the final execution.
299 for _ in range(5 - 1):
300 item.runtest()
301 yield
302
303 monkeypatch.undo()
304
305 # remove leading hypothesis-python/tests/...
306 nodeid = item.nodeid.rsplit("/", 1)[1]
307
308 results_p = _worker_path(item.session)
309 if not results_p.exists():
310 results_p.write_text(json.dumps({"calls": {}, "time": {}}))
311
312 data = json.loads(results_p.read_text())
313 data["calls"][nodeid] = shrink_calls
314 data["time"][nodeid] = shrink_time
315 results_p.write_text(json.dumps(data))
316
317
318 def pytest_sessionfinish(session, exitstatus):
319 if not (mode := session.config.getoption("--hypothesis-benchmark-shrinks")):
320 return
321 # only run on the controller process, not the workers
322 if hasattr(session.config, "workerinput"):
323 return
324
325 results = {"calls": {}, "time": {}}
326 output_p = Path(session.config.getoption("--hypothesis-benchmark-output"))
327 for p in output_p.parent.iterdir():
328 if p.name.startswith("shrinking_results_"):
329 worker_results = json.loads(p.read_text())
330 results["calls"] |= worker_results["calls"]
331 results["time"] |= worker_results["time"]
332 p.unlink()
333
334 results = {mode: results}
335 if not output_p.exists():
336 output_p.write_text(json.dumps(results))
337 else:
338 data = json.loads(output_p.read_text())
339 data[mode] = results[mode]
340 output_p.write_text(json.dumps(data))