skipping.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. """Support for skip/xfail functions and markers."""
  2. import os
  3. import platform
  4. import sys
  5. import traceback
  6. from collections.abc import Mapping
  7. from typing import Generator
  8. from typing import Optional
  9. from typing import Tuple
  10. from typing import Type
  11. import attr
  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. @attr.s(slots=True, frozen=True, auto_attribs=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. @attr.s(slots=True, frozen=True, auto_attribs=True)
  167. class Xfail:
  168. """The result of evaluate_xfail_marks()."""
  169. reason: str
  170. run: bool
  171. strict: bool
  172. raises: Optional[Tuple[Type[BaseException], ...]]
  173. def evaluate_xfail_marks(item: Item) -> Optional[Xfail]:
  174. """Evaluate xfail marks on item, returning Xfail if triggered."""
  175. for mark in item.iter_markers(name="xfail"):
  176. run = mark.kwargs.get("run", True)
  177. strict = mark.kwargs.get("strict", item.config.getini("xfail_strict"))
  178. raises = mark.kwargs.get("raises", None)
  179. if "condition" not in mark.kwargs:
  180. conditions = mark.args
  181. else:
  182. conditions = (mark.kwargs["condition"],)
  183. # Unconditional.
  184. if not conditions:
  185. reason = mark.kwargs.get("reason", "")
  186. return Xfail(reason, run, strict, raises)
  187. # If any of the conditions are true.
  188. for condition in conditions:
  189. result, reason = evaluate_condition(item, mark, condition)
  190. if result:
  191. return Xfail(reason, run, strict, raises)
  192. return None
  193. # Saves the xfail mark evaluation. Can be refreshed during call if None.
  194. xfailed_key = StashKey[Optional[Xfail]]()
  195. @hookimpl(tryfirst=True)
  196. def pytest_runtest_setup(item: Item) -> None:
  197. skipped = evaluate_skip_marks(item)
  198. if skipped:
  199. raise skip.Exception(skipped.reason, _use_item_location=True)
  200. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  201. if xfailed and not item.config.option.runxfail and not xfailed.run:
  202. xfail("[NOTRUN] " + xfailed.reason)
  203. @hookimpl(hookwrapper=True)
  204. def pytest_runtest_call(item: Item) -> Generator[None, None, None]:
  205. xfailed = item.stash.get(xfailed_key, None)
  206. if xfailed is None:
  207. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  208. if xfailed and not item.config.option.runxfail and not xfailed.run:
  209. xfail("[NOTRUN] " + xfailed.reason)
  210. yield
  211. # The test run may have added an xfail mark dynamically.
  212. xfailed = item.stash.get(xfailed_key, None)
  213. if xfailed is None:
  214. item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
  215. @hookimpl(hookwrapper=True)
  216. def pytest_runtest_makereport(item: Item, call: CallInfo[None]):
  217. outcome = yield
  218. rep = outcome.get_result()
  219. xfailed = item.stash.get(xfailed_key, None)
  220. if item.config.option.runxfail:
  221. pass # don't interfere
  222. elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception):
  223. assert call.excinfo.value.msg is not None
  224. rep.wasxfail = "reason: " + call.excinfo.value.msg
  225. rep.outcome = "skipped"
  226. elif not rep.skipped and xfailed:
  227. if call.excinfo:
  228. raises = xfailed.raises
  229. if raises is not None and not isinstance(call.excinfo.value, raises):
  230. rep.outcome = "failed"
  231. else:
  232. rep.outcome = "skipped"
  233. rep.wasxfail = xfailed.reason
  234. elif call.when == "call":
  235. if xfailed.strict:
  236. rep.outcome = "failed"
  237. rep.longrepr = "[XPASS(strict)] " + xfailed.reason
  238. else:
  239. rep.outcome = "passed"
  240. rep.wasxfail = xfailed.reason
  241. def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str]]:
  242. if hasattr(report, "wasxfail"):
  243. if report.skipped:
  244. return "xfailed", "x", "XFAIL"
  245. elif report.passed:
  246. return "xpassed", "X", "XPASS"
  247. return None