skipping.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """Support for skip/xfail functions and markers."""
  2. import dataclasses
  3. import os
  4. import platform
  5. import sys
  6. import traceback
  7. from collections.abc import Mapping
  8. from typing import Generator
  9. from typing import Optional
  10. from typing import Tuple
  11. from typing import Type
  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.reports import BaseReport
  21. from _pytest.runner import CallInfo
  22. from _pytest.stash import StashKey
  23. def pytest_addoption(parser: Parser) -> None:
  24. group = parser.getgroup("general")
  25. group.addoption(
  26. "--runxfail",
  27. action="store_true",
  28. dest="runxfail",
  29. default=False,
  30. help="Report the results of xfail tests as if they were not marked",
  31. )
  32. parser.addini(
  33. "xfail_strict",
  34. "Default for the strict parameter of xfail "
  35. "markers when not given explicitly (default: False)",
  36. default=False,
  37. type="bool",
  38. )
  39. def pytest_configure(config: Config) -> None:
  40. if config.option.runxfail:
  41. # yay a hack
  42. import pytest
  43. old = pytest.xfail
  44. config.add_cleanup(lambda: setattr(pytest, "xfail", old))
  45. def nop(*args, **kwargs):
  46. pass
  47. nop.Exception = xfail.Exception # type: ignore[attr-defined]
  48. setattr(pytest, "xfail", nop)
  49. config.addinivalue_line(
  50. "markers",
  51. "skip(reason=None): skip the given test function with an optional reason. "
  52. 'Example: skip(reason="no way of currently testing this") skips the '
  53. "test.",
  54. )
  55. config.addinivalue_line(
  56. "markers",
  57. "skipif(condition, ..., *, reason=...): "
  58. "skip the given test function if any of the conditions evaluate to True. "
  59. "Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. "
  60. "See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif",
  61. )
  62. config.addinivalue_line(
  63. "markers",
  64. "xfail(condition, ..., *, reason=..., run=True, raises=None, strict=xfail_strict): "
  65. "mark the test function as an expected failure if any of the conditions "
  66. "evaluate to True. Optionally specify a reason for better reporting "
  67. "and run=False if you don't even want to execute the test function. "
  68. "If only specific exception(s) are expected, you can list them in "
  69. "raises, and if the test fails in other ways, it will be reported as "
  70. "a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail",
  71. )
  72. def evaluate_condition(item: Item, mark: Mark, condition: object) -> Tuple[bool, str]:
  73. """Evaluate a single skipif/xfail condition.
  74. If an old-style string condition is given, it is eval()'d, otherwise the
  75. condition is bool()'d. If this fails, an appropriately formatted pytest.fail
  76. is raised.
  77. Returns (result, reason). The reason is only relevant if the result is True.
  78. """
  79. # String condition.
  80. if isinstance(condition, str):
  81. globals_ = {
  82. "os": os,
  83. "sys": sys,
  84. "platform": platform,
  85. "config": item.config,
  86. }
  87. for dictionary in reversed(
  88. item.ihook.pytest_markeval_namespace(config=item.config)
  89. ):
  90. if not isinstance(dictionary, Mapping):
  91. raise ValueError(
  92. "pytest_markeval_namespace() needs to return a dict, got {!r}".format(
  93. dictionary
  94. )
  95. )
  96. globals_.update(dictionary)
  97. if hasattr(item, "obj"):
  98. globals_.update(item.obj.__globals__) # type: ignore[attr-defined]
  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. "Error evaluating %r condition" % mark.name,
  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. "Error evaluating %r condition" % mark.name,
  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. "Error evaluating %r condition as a boolean" % mark.name,
  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. "Error evaluating %r: " % mark.name
  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) -> Optional[Skip]:
  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__ = ("reason", "run", "strict", "raises")
  170. reason: str
  171. run: bool
  172. strict: bool
  173. raises: Optional[Tuple[Type[BaseException], ...]]
  174. def evaluate_xfail_marks(item: Item) -> Optional[Xfail]:
  175. """Evaluate xfail marks on item, returning Xfail if triggered."""
  176. for mark in item.iter_markers(name="xfail"):
  177. run = mark.kwargs.get("run", True)
  178. strict = mark.kwargs.get("strict", item.config.getini("xfail_strict"))
  179. raises = mark.kwargs.get("raises", None)
  180. if "condition" not in mark.kwargs:
  181. conditions = mark.args
  182. else:
  183. conditions = (mark.kwargs["condition"],)
  184. # Unconditional.
  185. if not conditions:
  186. reason = mark.kwargs.get("reason", "")
  187. return Xfail(reason, run, strict, raises)
  188. # If any of the conditions are true.
  189. for condition in conditions:
  190. result, reason = evaluate_condition(item, mark, condition)
  191. if result:
  192. return Xfail(reason, run, strict, raises)
  193. return None
  194. # Saves the xfail mark evaluation. Can be refreshed during call if None.
  195. xfailed_key = StashKey[Optional[Xfail]]()
  196. @hookimpl(tryfirst=True)
  197. def pytest_runtest_setup(item: Item) -> None:
  198. skipped = evaluate_skip_marks(item)
  199. if skipped:
  200. raise skip.Exception(skipped.reason, _use_item_location=True)
  201. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  202. if xfailed and not item.config.option.runxfail and not xfailed.run:
  203. xfail("[NOTRUN] " + xfailed.reason)
  204. @hookimpl(hookwrapper=True)
  205. def pytest_runtest_call(item: Item) -> Generator[None, None, None]:
  206. xfailed = item.stash.get(xfailed_key, None)
  207. if xfailed is None:
  208. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  209. if xfailed and not item.config.option.runxfail and not xfailed.run:
  210. xfail("[NOTRUN] " + xfailed.reason)
  211. yield
  212. # The test run may have added an xfail mark dynamically.
  213. xfailed = item.stash.get(xfailed_key, None)
  214. if xfailed is None:
  215. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  216. @hookimpl(hookwrapper=True)
  217. def pytest_runtest_makereport(item: Item, call: CallInfo[None]):
  218. outcome = yield
  219. rep = outcome.get_result()
  220. xfailed = item.stash.get(xfailed_key, None)
  221. if item.config.option.runxfail:
  222. pass # don't interfere
  223. elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception):
  224. assert call.excinfo.value.msg is not None
  225. rep.wasxfail = "reason: " + call.excinfo.value.msg
  226. rep.outcome = "skipped"
  227. elif not rep.skipped and xfailed:
  228. if call.excinfo:
  229. raises = xfailed.raises
  230. if raises is not None and not isinstance(call.excinfo.value, raises):
  231. rep.outcome = "failed"
  232. else:
  233. rep.outcome = "skipped"
  234. rep.wasxfail = xfailed.reason
  235. elif call.when == "call":
  236. if xfailed.strict:
  237. rep.outcome = "failed"
  238. rep.longrepr = "[XPASS(strict)] " + xfailed.reason
  239. else:
  240. rep.outcome = "passed"
  241. rep.wasxfail = xfailed.reason
  242. def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str]]:
  243. if hasattr(report, "wasxfail"):
  244. if report.skipped:
  245. return "xfailed", "x", "XFAIL"
  246. elif report.passed:
  247. return "xpassed", "X", "XPASS"
  248. return None