Debian Codegraph @

_pytest/skipping.py

raw symbols SCIP
1 """ support for skip/xfail functions and markers. """
2 import os
3 import sys
4 import traceback
5
6 import py
7 import pytest
8 from _pytest.mark import MarkInfo, MarkDecorator
9
10
11 def pytest_addoption(parser):
12 group = parser.getgroup("general")
13 group.addoption('--runxfail',
14 action="store_true", dest="runxfail", default=False,
15 help="run tests even if they are marked xfail")
16
17 parser.addini("xfail_strict", "default for the strict parameter of xfail "
18 "markers when not given explicitly (default: "
19 "False)",
20 default=False,
21 type="bool")
22
23
24 def pytest_configure(config):
25 if config.option.runxfail:
26 old = pytest.xfail
27 config._cleanup.append(lambda: setattr(pytest, "xfail", old))
28 def nop(*args, **kwargs):
29 pass
30 nop.Exception = XFailed
31 setattr(pytest, "xfail", nop)
32
33 config.addinivalue_line("markers",
34 "skip(reason=None): skip the given test function with an optional reason. "
35 "Example: skip(reason=\"no way of currently testing this\") skips the "
36 "test."
37 )
38 config.addinivalue_line("markers",
39 "skipif(condition): skip the given test function if eval(condition) "
40 "results in a True value. Evaluation happens within the "
41 "module global context. Example: skipif('sys.platform == \"win32\"') "
42 "skips the test if we are on the win32 platform. see "
43 "http://pytest.org/latest/skipping.html"
44 )
45 config.addinivalue_line("markers",
46 "xfail(condition, reason=None, run=True, raises=None, strict=False): "
47 "mark the the test function as an expected failure if eval(condition) "
48 "has a True value. Optionally specify a reason for better reporting "
49 "and run=False if you don't even want to execute the test function. "
50 "If only specific exception(s) are expected, you can list them in "
51 "raises, and if the test fails in other ways, it will be reported as "
52 "a true failure. See http://pytest.org/latest/skipping.html"
53 )
54
55
56 def pytest_namespace():
57 return dict(xfail=xfail)
58
59
60 class XFailed(pytest.fail.Exception):
61 """ raised from an explicit call to pytest.xfail() """
62
63
64 def xfail(reason=""):
65 """ xfail an executing test or setup functions with the given reason."""
66 __tracebackhide__ = True
67 raise XFailed(reason)
68 xfail.Exception = XFailed
69
70
71 class MarkEvaluator:
72 def __init__(self, item, name):
73 self.item = item
74 self.name = name
75
76 @property
77 def holder(self):
78 return self.item.keywords.get(self.name)
79
80 def __bool__(self):
81 return bool(self.holder)
82 __nonzero__ = __bool__
83
84 def wasvalid(self):
85 return not hasattr(self, 'exc')
86
87 def invalidraise(self, exc):
88 raises = self.get('raises')
89 if not raises:
90 return
91 return not isinstance(exc, raises)
92
93 def istrue(self):
94 try:
95 return self._istrue()
96 except Exception:
97 self.exc = sys.exc_info()
98 if isinstance(self.exc[1], SyntaxError):
99 msg = [" " * (self.exc[1].offset + 4) + "^",]
100 msg.append("SyntaxError: invalid syntax")
101 else:
102 msg = traceback.format_exception_only(*self.exc[:2])
103 pytest.fail("Error evaluating %r expression\n"
104 " %s\n"
105 "%s"
106 %(self.name, self.expr, "\n".join(msg)),
107 pytrace=False)
108
109 def _getglobals(self):
110 d = {'os': os, 'sys': sys, 'config': self.item.config}
111 func = self.item.obj
112 try:
113 d.update(func.__globals__)
114 except AttributeError:
115 d.update(func.func_globals)
116 return d
117
118 def _istrue(self):
119 if hasattr(self, 'result'):
120 return self.result
121 if self.holder:
122 d = self._getglobals()
123 if self.holder.args or 'condition' in self.holder.kwargs:
124 self.result = False
125 # "holder" might be a MarkInfo or a MarkDecorator; only
126 # MarkInfo keeps track of all parameters it received in an
127 # _arglist attribute
128 if hasattr(self.holder, '_arglist'):
129 arglist = self.holder._arglist
130 else:
131 arglist = [(self.holder.args, self.holder.kwargs)]
132 for args, kwargs in arglist:
133 if 'condition' in kwargs:
134 args = (kwargs['condition'],)
135 for expr in args:
136 self.expr = expr
137 if isinstance(expr, py.builtin._basestring):
138 result = cached_eval(self.item.config, expr, d)
139 else:
140 if "reason" not in kwargs:
141 # XXX better be checked at collection time
142 msg = "you need to specify reason=STRING " \
143 "when using booleans as conditions."
144 pytest.fail(msg)
145 result = bool(expr)
146 if result:
147 self.result = True
148 self.reason = kwargs.get('reason', None)
149 self.expr = expr
150 return self.result
151 else:
152 self.result = True
153 return getattr(self, 'result', False)
154
155 def get(self, attr, default=None):
156 return self.holder.kwargs.get(attr, default)
157
158 def getexplanation(self):
159 expl = getattr(self, 'reason', None) or self.get('reason', None)
160 if not expl:
161 if not hasattr(self, 'expr'):
162 return ""
163 else:
164 return "condition: " + str(self.expr)
165 return expl
166
167
168 @pytest.hookimpl(tryfirst=True)
169 def pytest_runtest_setup(item):
170 # Check if skip or skipif are specified as pytest marks
171
172 skipif_info = item.keywords.get('skipif')
173 if isinstance(skipif_info, (MarkInfo, MarkDecorator)):
174 eval_skipif = MarkEvaluator(item, 'skipif')
175 if eval_skipif.istrue():
176 item._evalskip = eval_skipif
177 pytest.skip(eval_skipif.getexplanation())
178
179 skip_info = item.keywords.get('skip')
180 if isinstance(skip_info, (MarkInfo, MarkDecorator)):
181 item._evalskip = True
182 if 'reason' in skip_info.kwargs:
183 pytest.skip(skip_info.kwargs['reason'])
184 elif skip_info.args:
185 pytest.skip(skip_info.args[0])
186 else:
187 pytest.skip("unconditional skip")
188
189 item._evalxfail = MarkEvaluator(item, 'xfail')
190 check_xfail_no_run(item)
191
192
193 @pytest.mark.hookwrapper
194 def pytest_pyfunc_call(pyfuncitem):
195 check_xfail_no_run(pyfuncitem)
196 outcome = yield
197 passed = outcome.excinfo is None
198 if passed:
199 check_strict_xfail(pyfuncitem)
200
201
202 def check_xfail_no_run(item):
203 """check xfail(run=False)"""
204 if not item.config.option.runxfail:
205 evalxfail = item._evalxfail
206 if evalxfail.istrue():
207 if not evalxfail.get('run', True):
208 pytest.xfail("[NOTRUN] " + evalxfail.getexplanation())
209
210
211 def check_strict_xfail(pyfuncitem):
212 """check xfail(strict=True) for the given PASSING test"""
213 evalxfail = pyfuncitem._evalxfail
214 if evalxfail.istrue():
215 strict_default = pyfuncitem.config.getini('xfail_strict')
216 is_strict_xfail = evalxfail.get('strict', strict_default)
217 if is_strict_xfail:
218 del pyfuncitem._evalxfail
219 explanation = evalxfail.getexplanation()
220 pytest.fail('[XPASS(strict)] ' + explanation, pytrace=False)
221
222
223 @pytest.hookimpl(hookwrapper=True)
224 def pytest_runtest_makereport(item, call):
225 outcome = yield
226 rep = outcome.get_result()
227 evalxfail = getattr(item, '_evalxfail', None)
228 evalskip = getattr(item, '_evalskip', None)
229 # unitttest special case, see setting of _unexpectedsuccess
230 if hasattr(item, '_unexpectedsuccess') and rep.when == "call":
231 # we need to translate into how pytest encodes xpass
232 rep.wasxfail = "reason: " + repr(item._unexpectedsuccess)
233 rep.outcome = "failed"
234 elif item.config.option.runxfail:
235 pass # don't interefere
236 elif call.excinfo and call.excinfo.errisinstance(pytest.xfail.Exception):
237 rep.wasxfail = "reason: " + call.excinfo.value.msg
238 rep.outcome = "skipped"
239 elif evalxfail and not rep.skipped and evalxfail.wasvalid() and \
240 evalxfail.istrue():
241 if call.excinfo:
242 if evalxfail.invalidraise(call.excinfo.value):
243 rep.outcome = "failed"
244 else:
245 rep.outcome = "skipped"
246 rep.wasxfail = evalxfail.getexplanation()
247 elif call.when == "call":
248 rep.outcome = "failed" # xpass outcome
249 rep.wasxfail = evalxfail.getexplanation()
250 elif evalskip is not None and rep.skipped and type(rep.longrepr) is tuple:
251 # skipped by mark.skipif; change the location of the failure
252 # to point to the item definition, otherwise it will display
253 # the location of where the skip exception was raised within pytest
254 filename, line, reason = rep.longrepr
255 filename, line = item.location[:2]
256 rep.longrepr = filename, line, reason
257
258 # called by terminalreporter progress reporting
259 def pytest_report_teststatus(report):
260 if hasattr(report, "wasxfail"):
261 if report.skipped:
262 return "xfailed", "x", "xfail"
263 elif report.failed:
264 return "xpassed", "X", ("XPASS", {'yellow': True})
265
266 # called by the terminalreporter instance/plugin
267 def pytest_terminal_summary(terminalreporter):
268 tr = terminalreporter
269 if not tr.reportchars:
270 #for name in "xfailed skipped failed xpassed":
271 # if not tr.stats.get(name, 0):
272 # tr.write_line("HINT: use '-r' option to see extra "
273 # "summary info about tests")
274 # break
275 return
276
277 lines = []
278 for char in tr.reportchars:
279 if char == "x":
280 show_xfailed(terminalreporter, lines)
281 elif char == "X":
282 show_xpassed(terminalreporter, lines)
283 elif char in "fF":
284 show_simple(terminalreporter, lines, 'failed', "FAIL %s")
285 elif char in "sS":
286 show_skipped(terminalreporter, lines)
287 elif char == "E":
288 show_simple(terminalreporter, lines, 'error', "ERROR %s")
289 elif char == 'p':
290 show_simple(terminalreporter, lines, 'passed', "PASSED %s")
291
292 if lines:
293 tr._tw.sep("=", "short test summary info")
294 for line in lines:
295 tr._tw.line(line)
296
297 def show_simple(terminalreporter, lines, stat, format):
298 failed = terminalreporter.stats.get(stat)
299 if failed:
300 for rep in failed:
301 pos = terminalreporter.config.cwd_relative_nodeid(rep.nodeid)
302 lines.append(format %(pos,))
303
304 def show_xfailed(terminalreporter, lines):
305 xfailed = terminalreporter.stats.get("xfailed")
306 if xfailed:
307 for rep in xfailed:
308 pos = terminalreporter.config.cwd_relative_nodeid(rep.nodeid)
309 reason = rep.wasxfail
310 lines.append("XFAIL %s" % (pos,))
311 if reason:
312 lines.append(" " + str(reason))
313
314 def show_xpassed(terminalreporter, lines):
315 xpassed = terminalreporter.stats.get("xpassed")
316 if xpassed:
317 for rep in xpassed:
318 pos = terminalreporter.config.cwd_relative_nodeid(rep.nodeid)
319 reason = rep.wasxfail
320 lines.append("XPASS %s %s" %(pos, reason))
321
322 def cached_eval(config, expr, d):
323 if not hasattr(config, '_evalcache'):
324 config._evalcache = {}
325 try:
326 return config._evalcache[expr]
327 except KeyError:
328 import _pytest._code
329 exprcode = _pytest._code.compile(expr, mode="eval")
330 config._evalcache[expr] = x = eval(exprcode, d)
331 return x
332
333
334 def folded_skips(skipped):
335 d = {}
336 for event in skipped:
337 key = event.longrepr
338 assert len(key) == 3, (event, key)
339 d.setdefault(key, []).append(event)
340 l = []
341 for key, events in d.items():
342 l.append((len(events),) + key)
343 return l
344
345 def show_skipped(terminalreporter, lines):
346 tr = terminalreporter
347 skipped = tr.stats.get('skipped', [])
348 if skipped:
349 #if not tr.hasopt('skipped'):
350 # tr.write_line(
351 # "%d skipped tests, specify -rs for more info" %
352 # len(skipped))
353 # return
354 fskips = folded_skips(skipped)
355 if fskips:
356 #tr.write_sep("_", "skipped test summary")
357 for num, fspath, lineno, reason in fskips:
358 if reason.startswith("Skipped: "):
359 reason = reason[9:]
360 lines.append("SKIP [%d] %s:%d: %s" %
361 (num, fspath, lineno, reason))