skipping.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # mypy: allow-untyped-defs
  2. """Support for skip/xfail functions and markers."""
  3. from __future__ import annotations
  4. from collections.abc import Generator
  5. from collections.abc import Mapping
  6. import dataclasses
  7. import os
  8. import platform
  9. import sys
  10. import traceback
  11. from _pytest.config import Config
  12. from _pytest.config import hookimpl
  13. from _pytest.config.argparsing import Parser
  14. from _pytest.mark.structures import Mark
  15. from _pytest.nodes import Item
  16. from _pytest.outcomes import fail
  17. from _pytest.outcomes import skip
  18. from _pytest.outcomes import xfail
  19. from _pytest.raises import AbstractRaises
  20. from _pytest.reports import BaseReport
  21. from _pytest.reports import TestReport
  22. from _pytest.runner import CallInfo
  23. from _pytest.stash import StashKey
  24. def pytest_addoption(parser: Parser) -> None:
  25. group = parser.getgroup("general")
  26. group.addoption(
  27. "--runxfail",
  28. action="store_true",
  29. dest="runxfail",
  30. default=False,
  31. help="Report the results of xfail tests as if they were not marked",
  32. )
  33. parser.addini(
  34. "strict_xfail",
  35. "Default for the strict parameter of xfail "
  36. "markers when not given explicitly (default: False) (alias: xfail_strict)",
  37. type="bool",
  38. # None => fallback to `strict`.
  39. default=None,
  40. aliases=["xfail_strict"],
  41. )
  42. def pytest_configure(config: Config) -> None:
  43. if config.option.runxfail:
  44. # yay a hack
  45. import pytest
  46. old = pytest.xfail
  47. config.add_cleanup(lambda: setattr(pytest, "xfail", old))
  48. def nop(*args, **kwargs):
  49. pass
  50. nop.Exception = xfail.Exception # type: ignore[attr-defined]
  51. setattr(pytest, "xfail", nop)
  52. config.addinivalue_line(
  53. "markers",
  54. "skip(reason=None): skip the given test function with an optional reason. "
  55. 'Example: skip(reason="no way of currently testing this") skips the '
  56. "test.",
  57. )
  58. config.addinivalue_line(
  59. "markers",
  60. "skipif(condition, ..., *, reason=...): "
  61. "skip the given test function if any of the conditions evaluate to True. "
  62. "Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. "
  63. "See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif",
  64. )
  65. config.addinivalue_line(
  66. "markers",
  67. "xfail(condition, ..., *, reason=..., run=True, raises=None, strict=strict_xfail): "
  68. "mark the test function as an expected failure if any of the conditions "
  69. "evaluate to True. Optionally specify a reason for better reporting "
  70. "and run=False if you don't even want to execute the test function. "
  71. "If only specific exception(s) are expected, you can list them in "
  72. "raises, and if the test fails in other ways, it will be reported as "
  73. "a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail",
  74. )
  75. def evaluate_condition(item: Item, mark: Mark, condition: object) -> tuple[bool, str]:
  76. """Evaluate a single skipif/xfail condition.
  77. If an old-style string condition is given, it is eval()'d, otherwise the
  78. condition is bool()'d. If this fails, an appropriately formatted pytest.fail
  79. is raised.
  80. Returns (result, reason). The reason is only relevant if the result is True.
  81. """
  82. # String condition.
  83. if isinstance(condition, str):
  84. globals_ = {
  85. "os": os,
  86. "sys": sys,
  87. "platform": platform,
  88. "config": item.config,
  89. }
  90. for dictionary in reversed(
  91. item.ihook.pytest_markeval_namespace(config=item.config)
  92. ):
  93. if not isinstance(dictionary, Mapping):
  94. raise ValueError(
  95. f"pytest_markeval_namespace() needs to return a dict, got {dictionary!r}"
  96. )
  97. globals_.update(dictionary)
  98. if hasattr(item, "obj"):
  99. globals_.update(item.obj.__globals__)
  100. try:
  101. filename = f"<{mark.name} condition>"
  102. condition_code = compile(condition, filename, "eval")
  103. result = eval(condition_code, globals_)
  104. except SyntaxError as exc:
  105. msglines = [
  106. f"Error evaluating {mark.name!r} condition",
  107. " " + condition,
  108. " " + " " * (exc.offset or 0) + "^",
  109. "SyntaxError: invalid syntax",
  110. ]
  111. fail("\n".join(msglines), pytrace=False)
  112. except Exception as exc:
  113. msglines = [
  114. f"Error evaluating {mark.name!r} condition",
  115. " " + condition,
  116. *traceback.format_exception_only(type(exc), exc),
  117. ]
  118. fail("\n".join(msglines), pytrace=False)
  119. # Boolean condition.
  120. else:
  121. try:
  122. result = bool(condition)
  123. except Exception as exc:
  124. msglines = [
  125. f"Error evaluating {mark.name!r} condition as a boolean",
  126. *traceback.format_exception_only(type(exc), exc),
  127. ]
  128. fail("\n".join(msglines), pytrace=False)
  129. reason = mark.kwargs.get("reason", None)
  130. if reason is None:
  131. if isinstance(condition, str):
  132. reason = "condition: " + condition
  133. else:
  134. # XXX better be checked at collection time
  135. msg = (
  136. f"Error evaluating {mark.name!r}: "
  137. + "you need to specify reason=STRING when using booleans as conditions."
  138. )
  139. fail(msg, pytrace=False)
  140. return result, reason
  141. @dataclasses.dataclass(frozen=True)
  142. class Skip:
  143. """The result of evaluate_skip_marks()."""
  144. reason: str = "unconditional skip"
  145. def evaluate_skip_marks(item: Item) -> Skip | None:
  146. """Evaluate skip and skipif marks on item, returning Skip if triggered."""
  147. for mark in item.iter_markers(name="skipif"):
  148. if "condition" not in mark.kwargs:
  149. conditions = mark.args
  150. else:
  151. conditions = (mark.kwargs["condition"],)
  152. # Unconditional.
  153. if not conditions:
  154. reason = mark.kwargs.get("reason", "")
  155. return Skip(reason)
  156. # If any of the conditions are true.
  157. for condition in conditions:
  158. result, reason = evaluate_condition(item, mark, condition)
  159. if result:
  160. return Skip(reason)
  161. for mark in item.iter_markers(name="skip"):
  162. try:
  163. return Skip(*mark.args, **mark.kwargs)
  164. except TypeError as e:
  165. raise TypeError(str(e) + " - maybe you meant pytest.mark.skipif?") from None
  166. return None
  167. @dataclasses.dataclass(frozen=True)
  168. class Xfail:
  169. """The result of evaluate_xfail_marks()."""
  170. __slots__ = ("raises", "reason", "run", "strict")
  171. reason: str
  172. run: bool
  173. strict: bool
  174. raises: (
  175. type[BaseException]
  176. | tuple[type[BaseException], ...]
  177. | AbstractRaises[BaseException]
  178. | None
  179. )
  180. def evaluate_xfail_marks(item: Item) -> Xfail | None:
  181. """Evaluate xfail marks on item, returning Xfail if triggered."""
  182. for mark in item.iter_markers(name="xfail"):
  183. run = mark.kwargs.get("run", True)
  184. strict = mark.kwargs.get("strict")
  185. if strict is None:
  186. strict = item.config.getini("strict_xfail")
  187. if strict is None:
  188. strict = item.config.getini("strict")
  189. raises = mark.kwargs.get("raises", None)
  190. if "condition" not in mark.kwargs:
  191. conditions = mark.args
  192. else:
  193. conditions = (mark.kwargs["condition"],)
  194. # Unconditional.
  195. if not conditions:
  196. reason = mark.kwargs.get("reason", "")
  197. return Xfail(reason, run, strict, raises)
  198. # If any of the conditions are true.
  199. for condition in conditions:
  200. result, reason = evaluate_condition(item, mark, condition)
  201. if result:
  202. return Xfail(reason, run, strict, raises)
  203. return None
  204. # Saves the xfail mark evaluation. Can be refreshed during call if None.
  205. xfailed_key = StashKey[Xfail | None]()
  206. @hookimpl(tryfirst=True)
  207. def pytest_runtest_setup(item: Item) -> None:
  208. skipped = evaluate_skip_marks(item)
  209. if skipped:
  210. raise skip.Exception(skipped.reason, _use_item_location=True)
  211. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  212. if xfailed and not item.config.option.runxfail and not xfailed.run:
  213. xfail("[NOTRUN] " + xfailed.reason)
  214. @hookimpl(wrapper=True)
  215. def pytest_runtest_call(item: Item) -> Generator[None]:
  216. xfailed = item.stash.get(xfailed_key, None)
  217. if xfailed is None:
  218. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  219. if xfailed and not item.config.option.runxfail and not xfailed.run:
  220. xfail("[NOTRUN] " + xfailed.reason)
  221. try:
  222. return (yield)
  223. finally:
  224. # The test run may have added an xfail mark dynamically.
  225. xfailed = item.stash.get(xfailed_key, None)
  226. if xfailed is None:
  227. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  228. @hookimpl(wrapper=True)
  229. def pytest_runtest_makereport(
  230. item: Item, call: CallInfo[None]
  231. ) -> Generator[None, TestReport, TestReport]:
  232. rep = yield
  233. xfailed = item.stash.get(xfailed_key, None)
  234. if item.config.option.runxfail:
  235. pass # don't interfere
  236. elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception):
  237. assert call.excinfo.value.msg is not None
  238. rep.wasxfail = call.excinfo.value.msg
  239. rep.outcome = "skipped"
  240. elif not rep.skipped and xfailed:
  241. if call.excinfo:
  242. raises = xfailed.raises
  243. if raises is None or (
  244. (
  245. isinstance(raises, type | tuple)
  246. and isinstance(call.excinfo.value, raises)
  247. )
  248. or (
  249. isinstance(raises, AbstractRaises)
  250. and raises.matches(call.excinfo.value)
  251. )
  252. ):
  253. rep.outcome = "skipped"
  254. rep.wasxfail = xfailed.reason
  255. else:
  256. rep.outcome = "failed"
  257. elif call.when == "call":
  258. if xfailed.strict:
  259. rep.outcome = "failed"
  260. rep.longrepr = "[XPASS(strict)] " + xfailed.reason
  261. else:
  262. rep.outcome = "passed"
  263. rep.wasxfail = xfailed.reason
  264. return rep
  265. def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None:
  266. if hasattr(report, "wasxfail"):
  267. if report.skipped:
  268. return "xfailed", "x", "XFAIL"
  269. elif report.passed:
  270. return "xpassed", "X", "XPASS"
  271. return None