_hypothesis_pytestplugin.py 19 KB

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