skipping.py 10 KB

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