Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/skipping.py

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