_hypothesis_pytestplugin.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. _configured = False
  85. if not os.environ.get("HYPOTHESIS_EXTEND_INITIALIZATION"):
  86. _hypothesis_globals.in_initialization += 1
  87. if "hypothesis" in sys.modules:
  88. # Some other plugin has imported hypothesis, so we'll check if there
  89. # have been undetected side-effects and warn if so.
  90. from hypothesis.configuration import notice_initialization_restarted
  91. notice_initialization_restarted()
  92. def pytest_addoption(parser):
  93. group = parser.getgroup("hypothesis", "Hypothesis")
  94. group.addoption(
  95. LOAD_PROFILE_OPTION,
  96. action="store",
  97. help="Load in a registered hypothesis.settings profile",
  98. )
  99. group.addoption(
  100. VERBOSITY_OPTION,
  101. action="store",
  102. choices=_VERBOSITY_NAMES,
  103. help="Override profile with verbosity setting specified",
  104. )
  105. group.addoption(
  106. PRINT_STATISTICS_OPTION,
  107. action="store_true",
  108. help="Configure when statistics are printed",
  109. default=False,
  110. )
  111. group.addoption(
  112. SEED_OPTION,
  113. action="store",
  114. help="Set a seed to use for all Hypothesis tests",
  115. )
  116. group.addoption(
  117. EXPLAIN_OPTION,
  118. action="store_true",
  119. help="Enable the `explain` phase for failing Hypothesis tests",
  120. default=False,
  121. )
  122. def _any_hypothesis_option(config):
  123. return bool(any(config.getoption(opt) for opt in _ALL_OPTIONS))
  124. def pytest_report_header(config):
  125. if not (
  126. config.option.verbose >= 1
  127. or "hypothesis" in sys.modules
  128. or _any_hypothesis_option(config)
  129. ):
  130. return None
  131. from hypothesis import Verbosity, settings
  132. if config.option.verbose < 1 and settings.default.verbosity < Verbosity.verbose:
  133. return None
  134. settings_str = settings.default.show_changed()
  135. if settings_str != "":
  136. settings_str = f" -> {settings_str}"
  137. return f"hypothesis profile {settings._current_profile!r}{settings_str}"
  138. def pytest_configure(config):
  139. global _configured
  140. # skip first increment because we pre-incremented at import time
  141. if _configured:
  142. _hypothesis_globals.in_initialization += 1
  143. _configured = True
  144. config.addinivalue_line("markers", "hypothesis: Tests which use hypothesis.")
  145. if not _any_hypothesis_option(config):
  146. return
  147. from hypothesis import Phase, Verbosity, core, settings
  148. profile = config.getoption(LOAD_PROFILE_OPTION)
  149. if profile:
  150. settings.load_profile(profile)
  151. verbosity_name = config.getoption(VERBOSITY_OPTION)
  152. if verbosity_name and verbosity_name != settings.default.verbosity.name:
  153. verbosity_value = Verbosity[verbosity_name]
  154. name = f"{settings._current_profile}-with-{verbosity_name}-verbosity"
  155. # register_profile creates a new profile, exactly like the current one,
  156. # with the extra values given (in this case 'verbosity')
  157. settings.register_profile(name, verbosity=verbosity_value)
  158. settings.load_profile(name)
  159. if (
  160. config.getoption(EXPLAIN_OPTION)
  161. and Phase.explain not in settings.default.phases
  162. ):
  163. name = f"{settings._current_profile}-with-explain-phase"
  164. phases = (*settings.default.phases, Phase.explain)
  165. settings.register_profile(name, phases=phases)
  166. settings.load_profile(name)
  167. seed = config.getoption(SEED_OPTION)
  168. if seed is not None:
  169. try:
  170. seed = int(seed)
  171. except ValueError:
  172. pass
  173. core.global_force_seed = seed
  174. @pytest.hookimpl(hookwrapper=True)
  175. def pytest_runtest_call(item):
  176. __tracebackhide__ = True
  177. if not (hasattr(item, "obj") and "hypothesis" in sys.modules):
  178. yield
  179. return
  180. from hypothesis import core
  181. from hypothesis.internal.detection import is_hypothesis_test
  182. # See https://github.com/pytest-dev/pytest/issues/9159
  183. core.pytest_shows_exceptiongroups = (
  184. getattr(pytest, "version_tuple", ())[:2] >= (7, 2)
  185. or item.config.getoption("tbstyle", "auto") == "native"
  186. )
  187. core.running_under_pytest = True
  188. if not is_hypothesis_test(item.obj):
  189. # If @given was not applied, check whether other hypothesis
  190. # decorators were applied, and raise an error if they were.
  191. # We add this frame of indirection to enable __tracebackhide__.
  192. def raise_hypothesis_usage_error(msg):
  193. raise InvalidArgument(msg)
  194. if getattr(item.obj, "is_hypothesis_strategy_function", False):
  195. from hypothesis.errors import InvalidArgument
  196. raise_hypothesis_usage_error(
  197. f"{item.nodeid} is a function that returns a Hypothesis strategy, "
  198. "but pytest has collected it as a test function. This is useless "
  199. "as the function body will never be executed. To define a test "
  200. "function, use @given instead of @composite."
  201. )
  202. message = "Using `@%s` on a test without `@given` is completely pointless."
  203. for name, attribute in [
  204. ("example", "hypothesis_explicit_examples"),
  205. ("seed", "_hypothesis_internal_use_seed"),
  206. ("settings", "_hypothesis_internal_settings_applied"),
  207. ("reproduce_example", "_hypothesis_internal_use_reproduce_failure"),
  208. ]:
  209. if hasattr(item.obj, attribute):
  210. from hypothesis.errors import InvalidArgument
  211. raise_hypothesis_usage_error(message % (name,))
  212. yield
  213. else:
  214. from hypothesis import HealthCheck, settings as Settings
  215. from hypothesis.internal.escalation import current_pytest_item
  216. from hypothesis.internal.healthcheck import fail_health_check
  217. from hypothesis.reporting import with_reporter
  218. from hypothesis.statistics import collector, describe_statistics
  219. # Retrieve the settings for this test from the test object, which
  220. # is normally a Hypothesis wrapped_test wrapper. If this doesn't
  221. # work, the test object is probably something weird
  222. # (e.g a stateful test wrapper), so we skip the function-scoped
  223. # fixture check.
  224. settings = getattr(
  225. item.obj, "_hypothesis_internal_use_settings", Settings.default
  226. )
  227. # Check for suspicious use of function-scoped fixtures, but only
  228. # if the corresponding health check is not suppressed.
  229. fixture_params = False
  230. if not set(settings.suppress_health_check).issuperset(
  231. {HealthCheck.function_scoped_fixture, HealthCheck.differing_executors}
  232. ):
  233. # Warn about function-scoped fixtures, excluding autouse fixtures because
  234. # the advice is probably not actionable and the status quo seems OK...
  235. # See https://github.com/HypothesisWorks/hypothesis/issues/377 for detail.
  236. argnames = None
  237. for fx_defs in item._request._fixturemanager.getfixtureinfo(
  238. node=item, func=item.function, cls=None
  239. ).name2fixturedefs.values():
  240. if argnames is None:
  241. argnames = frozenset(signature(item.function).parameters)
  242. for fx in fx_defs:
  243. fixture_params |= bool(fx.params)
  244. if fx.argname in argnames:
  245. active_fx = item._request._get_active_fixturedef(fx.argname)
  246. if active_fx.scope == "function":
  247. fail_health_check(
  248. settings,
  249. _FIXTURE_MSG.format(fx.argname, item.nodeid),
  250. HealthCheck.function_scoped_fixture,
  251. )
  252. if fixture_params or (item.get_closest_marker("parametrize") is not None):
  253. # Disable the differing_executors health check due to false alarms:
  254. # see https://github.com/HypothesisWorks/hypothesis/issues/3733
  255. from hypothesis import settings as Settings
  256. fn = getattr(item.obj, "__func__", item.obj)
  257. fn._hypothesis_internal_use_settings = Settings(
  258. parent=settings,
  259. suppress_health_check={HealthCheck.differing_executors}
  260. | set(settings.suppress_health_check),
  261. )
  262. # Give every parametrized test invocation a unique database key
  263. key = item.nodeid.encode()
  264. item.obj.hypothesis.inner_test._hypothesis_internal_add_digest = key
  265. store = StoringReporter(item.config)
  266. def note_statistics(stats):
  267. stats["nodeid"] = item.nodeid
  268. item.hypothesis_statistics = describe_statistics(stats)
  269. with collector.with_value(note_statistics):
  270. with with_reporter(store):
  271. with current_pytest_item.with_value(item):
  272. yield
  273. if store.results:
  274. item.hypothesis_report_information = list(store.results)
  275. def _stash_get(config, key, default):
  276. if hasattr(config, "stash"):
  277. # pytest 7
  278. return config.stash.get(key, default)
  279. elif hasattr(config, "_store"):
  280. # pytest 5.4
  281. return config._store.get(key, default)
  282. else:
  283. return getattr(config, key, default)
  284. @pytest.hookimpl(hookwrapper=True)
  285. def pytest_runtest_makereport(item, call):
  286. report = (yield).get_result()
  287. if hasattr(item, "hypothesis_report_information"):
  288. report.sections.append(
  289. ("Hypothesis", "\n".join(item.hypothesis_report_information))
  290. )
  291. if report.when != "teardown":
  292. return
  293. terminalreporter = item.config.pluginmanager.getplugin("terminalreporter")
  294. if hasattr(item, "hypothesis_statistics"):
  295. stats = item.hypothesis_statistics
  296. stats_base64 = base64.b64encode(stats.encode()).decode()
  297. name = "hypothesis-statistics-" + item.nodeid
  298. # Include hypothesis information to the junit XML report.
  299. #
  300. # Note that when `pytest-xdist` is enabled, `xml_key` is not present in the
  301. # stash, so we don't add anything to the junit XML report in that scenario.
  302. # https://github.com/pytest-dev/pytest/issues/7767#issuecomment-1082436256
  303. xml = _stash_get(item.config, xml_key, None)
  304. if xml:
  305. xml.add_global_property(name, stats_base64)
  306. # If there's a terminal report, include our summary stats for each test
  307. if terminalreporter is not None:
  308. report.__dict__[STATS_KEY] = stats
  309. # If there's an HTML report, include our summary stats for each test
  310. pytest_html = item.config.pluginmanager.getplugin("html")
  311. if pytest_html is not None: # pragma: no cover
  312. report.extra = [
  313. *getattr(report, "extra", []),
  314. pytest_html.extras.text(stats, name="Hypothesis stats"),
  315. ]
  316. # This doesn't intrinsically have anything to do with the terminalreporter;
  317. # we're just cargo-culting a way to get strings back to a single function
  318. # even if the test were distributed with pytest-xdist.
  319. failing_examples = getattr(item, FAILING_EXAMPLES_KEY, None)
  320. if failing_examples and terminalreporter is not None:
  321. try:
  322. from hypothesis.extra._patching import FAIL_MSG, get_patch_for
  323. except ImportError:
  324. return
  325. # We'll save this as a triple of [filename, hunk_before, hunk_after].
  326. triple = get_patch_for(item.obj, [(x, FAIL_MSG) for x in failing_examples])
  327. if triple is not None:
  328. report.__dict__[FAILING_EXAMPLES_KEY] = json.dumps(triple)
  329. def pytest_terminal_summary(terminalreporter):
  330. failing_examples = []
  331. print_stats = terminalreporter.config.getoption(PRINT_STATISTICS_OPTION)
  332. if print_stats:
  333. terminalreporter.section("Hypothesis Statistics")
  334. for reports in terminalreporter.stats.values():
  335. for report in reports:
  336. stats = report.__dict__.get(STATS_KEY)
  337. if stats and print_stats:
  338. terminalreporter.write_line(stats + "\n\n")
  339. fex = report.__dict__.get(FAILING_EXAMPLES_KEY)
  340. if fex:
  341. failing_examples.append(json.loads(fex))
  342. from hypothesis.internal.observability import _WROTE_TO
  343. if _WROTE_TO:
  344. terminalreporter.section("Hypothesis")
  345. for fname in sorted(_WROTE_TO):
  346. terminalreporter.write_line(f"observations written to {fname}")
  347. if failing_examples:
  348. # This must have been imported already to write the failing examples
  349. from hypothesis.extra._patching import gc_patches, make_patch, save_patch
  350. patch = make_patch(failing_examples)
  351. try:
  352. gc_patches()
  353. fname = save_patch(patch)
  354. except Exception:
  355. # fail gracefully if we hit any filesystem or permissions problems
  356. return
  357. if not _WROTE_TO:
  358. terminalreporter.section("Hypothesis")
  359. terminalreporter.write_line(
  360. f"`git apply {fname}` to add failing examples to your code."
  361. )
  362. def pytest_collection_modifyitems(items):
  363. if "hypothesis" not in sys.modules:
  364. return
  365. from hypothesis.internal.detection import is_hypothesis_test
  366. for item in items:
  367. if isinstance(item, pytest.Function) and is_hypothesis_test(item.obj):
  368. item.add_marker("hypothesis")
  369. def pytest_sessionstart(session):
  370. _hypothesis_globals.in_initialization -= 1
  371. # Monkeypatch some internals to prevent applying @pytest.fixture() to a
  372. # function which has already been decorated with @hypothesis.given().
  373. # (the reverse case is already an explicit error in Hypothesis)
  374. # We do this here so that it catches people on old Pytest versions too.
  375. from _pytest import fixtures
  376. def _ban_given_call(self, function):
  377. if "hypothesis" in sys.modules:
  378. from hypothesis.internal.detection import is_hypothesis_test
  379. if is_hypothesis_test(function):
  380. raise RuntimeError(
  381. f"Can't apply @pytest.fixture() to {function.__name__} because "
  382. "it is already decorated with @hypothesis.given()"
  383. )
  384. return _orig_call(self, function)
  385. _orig_call = fixtures.FixtureFunctionMarker.__call__
  386. fixtures.FixtureFunctionMarker.__call__ = _ban_given_call # type: ignore
  387. def load():
  388. """Required for `pluggy` to load a plugin from setuptools entrypoints."""