Debian Codegraph @

hypothesis-python/src/_hypothesis_pytestplugin.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 """
12 The pytest plugin for Hypothesis.
13
14 We move this from the old location at `hypothesis.extra.pytestplugin` so that it
15 can be loaded by Pytest without importing Hypothesis. In turn, this means that
16 Hypothesis will not load our own third-party plugins (with associated side-effects)
17 unless and until the user explicitly runs `import hypothesis`.
18
19 See https://github.com/HypothesisWorks/hypothesis/issues/3140 for details.
20 """
21
22 import base64
23 import json
24 import os
25 import sys
26 import warnings
27 from fnmatch import fnmatch
28 from inspect import signature
29
30 import _hypothesis_globals
31 import pytest
32
33 try:
34 from _pytest.junitxml import xml_key
35 except ImportError:
36 xml_key = "_xml" # type: ignore
37
38 LOAD_PROFILE_OPTION = "--hypothesis-profile"
39 VERBOSITY_OPTION = "--hypothesis-verbosity"
40 PRINT_STATISTICS_OPTION = "--hypothesis-show-statistics"
41 SEED_OPTION = "--hypothesis-seed"
42 EXPLAIN_OPTION = "--hypothesis-explain"
43
44 _VERBOSITY_NAMES = ["quiet", "normal", "verbose", "debug"]
45 _ALL_OPTIONS = [
46 LOAD_PROFILE_OPTION,
47 VERBOSITY_OPTION,
48 PRINT_STATISTICS_OPTION,
49 SEED_OPTION,
50 EXPLAIN_OPTION,
51 ]
52 STATS_KEY = "_hypothesis_stats"
53 FAILING_EXAMPLES_KEY = "_hypothesis_failing_examples"
54
55
56 class StoringReporter:
57 def __init__(self, config):
58 assert "hypothesis" in sys.modules
59 from hypothesis.reporting import default
60
61 self.report = default
62 self.config = config
63 self.results = []
64
65 def __call__(self, msg):
66 if self.config.getoption("capture", "fd") == "no":
67 self.report(msg)
68 if not isinstance(msg, str):
69 msg = repr(msg)
70 self.results.append(msg)
71
72
73 # Avoiding distutils.version.LooseVersion due to
74 # https://github.com/HypothesisWorks/hypothesis/issues/2490
75 if tuple(map(int, pytest.__version__.split(".")[:2])) < (4, 6): # pragma: no cover
76 import warnings
77
78 PYTEST_TOO_OLD_MESSAGE = """
79 You are using pytest version %s. Hypothesis tests work with any test
80 runner, but our pytest plugin requires pytest 4.6 or newer.
81 Note that the pytest developers no longer support your version either!
82 Disabling the Hypothesis pytest plugin...
83 """
84 warnings.warn(PYTEST_TOO_OLD_MESSAGE % (pytest.__version__,), stacklevel=1)
85
86 else:
87 # Restart side-effect detection as early as possible, to maximize coverage. We
88 # need balanced increment/decrement in configure/sessionstart to support nested
89 # pytest (e.g. runpytest_inprocess), so this early increment in effect replaces
90 # the first one in pytest_configure.
91 if not os.environ.get("HYPOTHESIS_EXTEND_INITIALIZATION"):
92 _hypothesis_globals.in_initialization += 1
93 if "hypothesis" in sys.modules:
94 # Some other plugin has imported hypothesis, so we'll check if there
95 # have been undetected side-effects and warn if so.
96 from hypothesis.configuration import notice_initialization_restarted
97
98 notice_initialization_restarted()
99
100 def pytest_addoption(parser):
101 group = parser.getgroup("hypothesis", "Hypothesis")
102 group.addoption(
103 LOAD_PROFILE_OPTION,
104 action="store",
105 help="Load in a registered hypothesis.settings profile",
106 )
107 group.addoption(
108 VERBOSITY_OPTION,
109 action="store",
110 choices=_VERBOSITY_NAMES,
111 help="Override profile with verbosity setting specified",
112 )
113 group.addoption(
114 PRINT_STATISTICS_OPTION,
115 action="store_true",
116 help="Configure when statistics are printed",
117 default=False,
118 )
119 group.addoption(
120 SEED_OPTION,
121 action="store",
122 help="Set a seed to use for all Hypothesis tests",
123 )
124 group.addoption(
125 EXPLAIN_OPTION,
126 action="store_true",
127 help="Enable the `explain` phase for failing Hypothesis tests",
128 default=False,
129 )
130
131 def _any_hypothesis_option(config):
132 return bool(any(config.getoption(opt) for opt in _ALL_OPTIONS))
133
134 def pytest_report_header(config):
135 if not (
136 config.option.verbose >= 1
137 or "hypothesis" in sys.modules
138 or _any_hypothesis_option(config)
139 ):
140 return None
141
142 from hypothesis import Verbosity, settings
143
144 if config.option.verbose < 1 and settings.default.verbosity < Verbosity.verbose:
145 return None
146 settings_str = settings.default.show_changed()
147 if settings_str != "":
148 settings_str = f" -> {settings_str}"
149 return (
150 f"hypothesis profile {settings.get_current_profile_name()!r}{settings_str}"
151 )
152
153 def pytest_configure(config):
154 config.addinivalue_line("markers", "hypothesis: Tests which use hypothesis.")
155 if not _any_hypothesis_option(config):
156 return
157 from hypothesis import Phase, Verbosity, core, settings
158
159 profile = config.getoption(LOAD_PROFILE_OPTION)
160 if profile:
161 settings.load_profile(profile)
162 verbosity_name = config.getoption(VERBOSITY_OPTION)
163 if verbosity_name and verbosity_name != settings.default.verbosity.name:
164 verbosity_value = Verbosity[verbosity_name]
165 name = (
166 f"{settings.get_current_profile_name()}-with-{verbosity_name}-verbosity"
167 )
168 # register_profile creates a new profile, exactly like the current one,
169 # with the extra values given (in this case 'verbosity')
170 settings.register_profile(name, verbosity=verbosity_value)
171 settings.load_profile(name)
172 if (
173 config.getoption(EXPLAIN_OPTION)
174 and Phase.explain not in settings.default.phases
175 ):
176 name = f"{settings.get_current_profile_name()}-with-explain-phase"
177 phases = (*settings.default.phases, Phase.explain)
178 settings.register_profile(name, phases=phases)
179 settings.load_profile(name)
180
181 seed = config.getoption(SEED_OPTION)
182 if seed is not None:
183 try:
184 seed = int(seed)
185 except ValueError:
186 pass
187 core.global_force_seed = seed
188
189 @pytest.hookimpl(hookwrapper=True)
190 def pytest_runtest_call(item):
191 __tracebackhide__ = True
192 if not (hasattr(item, "obj") and "hypothesis" in sys.modules):
193 yield
194 return
195
196 from hypothesis import core, is_hypothesis_test
197
198 # See https://github.com/pytest-dev/pytest/issues/9159
199 core.pytest_shows_exceptiongroups = (
200 getattr(pytest, "version_tuple", ())[:2] >= (7, 2)
201 or item.config.getoption("tbstyle", "auto") == "native"
202 )
203 core.running_under_pytest = True
204
205 if not is_hypothesis_test(item.obj):
206 # If @given was not applied, check whether other hypothesis
207 # decorators were applied, and raise an error if they were.
208 # We add this frame of indirection to enable __tracebackhide__.
209 def raise_hypothesis_usage_error(msg):
210 raise InvalidArgument(msg)
211
212 if getattr(item.obj, "is_hypothesis_strategy_function", False):
213 from hypothesis.errors import InvalidArgument
214
215 raise_hypothesis_usage_error(
216 f"{item.nodeid} is a function that returns a Hypothesis strategy, "
217 "but pytest has collected it as a test function. This is useless "
218 "as the function body will never be executed. To define a test "
219 "function, use @given instead of @composite."
220 )
221 message = "Using `@%s` on a test without `@given` is completely pointless."
222 for name, attribute in [
223 ("example", "hypothesis_explicit_examples"),
224 ("seed", "_hypothesis_internal_use_seed"),
225 ("settings", "_hypothesis_internal_settings_applied"),
226 ("reproduce_example", "_hypothesis_internal_use_reproduce_failure"),
227 ]:
228 if hasattr(item.obj, attribute):
229 from hypothesis.errors import InvalidArgument
230
231 raise_hypothesis_usage_error(message % (name,))
232 yield
233 return
234
235 from hypothesis import HealthCheck, settings as Settings
236 from hypothesis.internal.escalation import current_pytest_item
237 from hypothesis.internal.healthcheck import fail_health_check
238 from hypothesis.reporting import with_reporter
239 from hypothesis.statistics import collector, describe_statistics
240
241 # Retrieve the settings for this test from the test object, which
242 # is normally a Hypothesis wrapped_test wrapper. If this doesn't
243 # work, the test object is probably something weird
244 # (e.g a stateful test wrapper), so we skip the function-scoped
245 # fixture check.
246 settings = getattr(
247 item.obj, "_hypothesis_internal_use_settings", Settings.default
248 )
249
250 # Check for suspicious use of function-scoped fixtures, but only
251 # if the corresponding health check is not suppressed.
252 fixture_params = False
253 if not set(settings.suppress_health_check).issuperset(
254 {HealthCheck.function_scoped_fixture, HealthCheck.differing_executors}
255 ):
256 # Warn about function-scoped fixtures, excluding autouse fixtures because
257 # the advice is probably not actionable and the status quo seems OK...
258 # See https://github.com/HypothesisWorks/hypothesis/issues/377 for detail.
259 argnames = None
260 for fx_defs in item._request._fixturemanager.getfixtureinfo(
261 node=item, func=item.function, cls=None
262 ).name2fixturedefs.values():
263 if argnames is None:
264 argnames = frozenset(signature(item.function).parameters)
265 for fx in fx_defs:
266 fixture_params |= bool(fx.params)
267 if fx.argname not in argnames:
268 continue
269 active_fx = item._request._get_active_fixturedef(fx.argname)
270 if active_fx.scope == "function":
271 fail_health_check(
272 settings,
273 f"{item.nodeid!r} uses a function-scoped fixture {fx.argname!r}."
274 "\n\n"
275 "Function-scoped fixtures are not reset between inputs "
276 "generated by `@given(...)`, which is often surprising and "
277 "can cause subtle test bugs."
278 "\n\n"
279 "If you were expecting the fixture to run separately "
280 "for each generated input, then unfortunately you "
281 "will need to find a different way to achieve your "
282 "goal (for example, replacing the fixture with a similar "
283 "context manager inside of the test)."
284 "\n\n"
285 "If you are confident that your test will work correctly "
286 "even though the fixture is not reset between generated "
287 "inputs, you can suppress this health check with "
288 "@settings(suppress_health_check=[HealthCheck.function_scoped_fixture]). "
289 "See "
290 "https://hypothesis.readthedocs.io/en/latest/reference/api.html#hypothesis.HealthCheck "
291 "for details.",
292 HealthCheck.function_scoped_fixture,
293 )
294
295 if fixture_params or (item.get_closest_marker("parametrize") is not None):
296 # Disable the differing_executors health check due to false alarms:
297 # see https://github.com/HypothesisWorks/hypothesis/issues/3733
298 fn = getattr(item.obj, "__func__", item.obj)
299 fn._hypothesis_internal_use_settings = Settings(
300 parent=settings,
301 suppress_health_check={HealthCheck.differing_executors}
302 | set(settings.suppress_health_check),
303 )
304
305 # Give every parametrized test invocation a unique database key
306 key = item.nodeid.encode()
307 item.obj.hypothesis.inner_test._hypothesis_internal_add_digest = key
308
309 store = StoringReporter(item.config)
310
311 def note_statistics(stats):
312 stats["nodeid"] = item.nodeid
313 item.hypothesis_statistics = describe_statistics(stats)
314
315 with (
316 collector.with_value(note_statistics),
317 with_reporter(store),
318 current_pytest_item.with_value(item),
319 ):
320 yield
321
322 if store.results:
323 item.hypothesis_report_information = "\n".join(store.results)
324
325 def _stash_get(config, key, default):
326 if hasattr(config, "stash"):
327 # pytest 7
328 return config.stash.get(key, default)
329 elif hasattr(config, "_store"):
330 # pytest 5.4
331 return config._store.get(key, default)
332 else:
333 return getattr(config, key, default)
334
335 @pytest.hookimpl(hookwrapper=True)
336 def pytest_runtest_makereport(item, call):
337 report = (yield).get_result()
338 if hasattr(item, "hypothesis_report_information"):
339 report.sections.append(("Hypothesis", item.hypothesis_report_information))
340 if report.when != "teardown":
341 return
342
343 terminalreporter = item.config.pluginmanager.getplugin("terminalreporter")
344
345 if hasattr(item, "hypothesis_statistics"):
346 stats = item.hypothesis_statistics
347 stats_base64 = base64.b64encode(stats.encode()).decode()
348
349 name = "hypothesis-statistics-" + item.nodeid
350
351 # Include hypothesis information to the junit XML report.
352 #
353 # Note that when `pytest-xdist` is enabled, `xml_key` is not present in the
354 # stash, so we don't add anything to the junit XML report in that scenario.
355 # https://github.com/pytest-dev/pytest/issues/7767#issuecomment-1082436256
356 xml = _stash_get(item.config, xml_key, None)
357 if xml:
358 xml.add_global_property(name, stats_base64)
359
360 # If there's a terminal report, include our summary stats for each test
361 if terminalreporter is not None:
362 report.__dict__[STATS_KEY] = stats
363
364 # If there's an HTML report, include our summary stats for each test
365 pytest_html = item.config.pluginmanager.getplugin("html")
366 if pytest_html is not None: # pragma: no cover
367 report.extra = [
368 *getattr(report, "extra", []),
369 pytest_html.extras.text(stats, name="Hypothesis stats"),
370 ]
371
372 # This doesn't intrinsically have anything to do with the terminalreporter;
373 # we're just cargo-culting a way to get strings back to a single function
374 # even if the test were distributed with pytest-xdist.
375 failing_examples = getattr(item, FAILING_EXAMPLES_KEY, None)
376 if failing_examples and terminalreporter is not None:
377 try:
378 from hypothesis.extra._patching import FAIL_MSG, get_patch_for
379 except ImportError:
380 return
381 # We'll save this as a triple of [filename, hunk_before, hunk_after].
382 triple = get_patch_for(item.obj, [(x, FAIL_MSG) for x in failing_examples])
383 if triple is not None:
384 report.__dict__[FAILING_EXAMPLES_KEY] = json.dumps(triple)
385
386 def pytest_terminal_summary(terminalreporter):
387 failing_examples = []
388 print_stats = terminalreporter.config.getoption(PRINT_STATISTICS_OPTION)
389 if print_stats:
390 terminalreporter.section("Hypothesis Statistics")
391 for reports in terminalreporter.stats.values():
392 for report in reports:
393 stats = report.__dict__.get(STATS_KEY)
394 if stats and print_stats:
395 terminalreporter.write_line(stats + "\n\n")
396 examples = report.__dict__.get(FAILING_EXAMPLES_KEY)
397 if examples:
398 failing_examples.append(json.loads(examples))
399
400 from hypothesis.internal.observability import _WROTE_TO
401
402 if _WROTE_TO:
403 terminalreporter.section("Hypothesis")
404 for fname in sorted(_WROTE_TO):
405 terminalreporter.write_line(f"observations written to {fname}")
406
407 if failing_examples:
408 # This must have been imported already to write the failing examples
409 from hypothesis.extra._patching import gc_patches, make_patch, save_patch
410
411 patch = make_patch(failing_examples)
412 try:
413 gc_patches()
414 fname = save_patch(patch)
415 except Exception:
416 # fail gracefully if we hit any filesystem or permissions problems
417 return
418 if not _WROTE_TO:
419 terminalreporter.section("Hypothesis")
420 terminalreporter.write_line(
421 f"`git apply {fname}` to add failing examples to your code."
422 )
423
424 def pytest_collection_modifyitems(items):
425 if "hypothesis" not in sys.modules:
426 return
427
428 from hypothesis import is_hypothesis_test
429
430 has_hypothesis_tests = False
431 for item in items:
432 if isinstance(item, pytest.Function) and is_hypothesis_test(item.obj):
433 item.add_marker("hypothesis")
434 has_hypothesis_tests = True
435
436 if has_hypothesis_tests:
437 # Collect local constants now, during test collection, so that this
438 # time is not attributed to whatever test happens to run first.
439 # (see https://github.com/HypothesisWorks/hypothesis/issues/4627)
440 # We might miss weird wrapped uses (if there are no other PBTs!),
441 # in order to avoid the latency from inefficient 3rd party plugins.
442 from hypothesis.internal.conjecture.providers import _get_local_constants
443
444 _get_local_constants()
445
446 def pytest_sessionstart(session):
447 # Note: may be called multiple times, so we can go negative
448 _hypothesis_globals.in_initialization -= 1
449
450 # Monkeypatch some internals to prevent applying @pytest.fixture() to a
451 # function which has already been decorated with @hypothesis.given().
452 # (the reverse case is already an explicit error in Hypothesis)
453 # We do this here so that it catches people on old Pytest versions too.
454 from _pytest import fixtures
455
456 def _ban_given_call(self, function):
457 if "hypothesis" in sys.modules:
458 from hypothesis import is_hypothesis_test
459
460 if is_hypothesis_test(function):
461 raise RuntimeError(
462 f"Can't apply @pytest.fixture() to {function.__name__} because "
463 "it is already decorated with @hypothesis.given()"
464 )
465 return _orig_call(self, function)
466
467 _orig_call = fixtures.FixtureFunctionMarker.__call__
468 fixtures.FixtureFunctionMarker.__call__ = _ban_given_call # type: ignore
469
470 if int(pytest.__version__.split(".")[0]) >= 7: # pragma: no branch
471 # Hook has had this signature since Pytest 7.0, so skip on older versions
472
473 def pytest_ignore_collect(collection_path, config):
474 # Detect, warn about, and mititgate certain misconfigurations;
475 # this is mostly educational but can also speed up collection.
476 if (
477 (name := collection_path.name) == ".hypothesis"
478 and collection_path.is_dir()
479 and not any(fnmatch(name, p) for p in config.getini("norecursedirs"))
480 ):
481 warnings.warn(
482 "Skipping collection of '.hypothesis' directory - this usually "
483 "means you've explicitly set the `norecursedirs` pytest config "
484 "option, replacing rather than extending the default ignores.",
485 stacklevel=1,
486 )
487 return True
488 return None # let other hooks decide
489
490
491 def load():
492 """Required for `pluggy` to load a plugin from setuptools entrypoints."""