Debian Codegraph @

_pytest/runner.py

raw symbols SCIP
1 """ basic collect and runtest protocol implementations """
2 import bdb
3 import sys
4 from time import time
5
6 import py
7 import pytest
8 from _pytest._code.code import TerminalRepr, ExceptionInfo
9
10
11 def pytest_namespace():
12 return {
13 'fail' : fail,
14 'skip' : skip,
15 'importorskip' : importorskip,
16 'exit' : exit,
17 }
18
19 #
20 # pytest plugin hooks
21
22 def pytest_addoption(parser):
23 group = parser.getgroup("terminal reporting", "reporting", after="general")
24 group.addoption('--durations',
25 action="store", type=int, default=None, metavar="N",
26 help="show N slowest setup/test durations (N=0 for all)."),
27
28 def pytest_terminal_summary(terminalreporter):
29 durations = terminalreporter.config.option.durations
30 if durations is None:
31 return
32 tr = terminalreporter
33 dlist = []
34 for replist in tr.stats.values():
35 for rep in replist:
36 if hasattr(rep, 'duration'):
37 dlist.append(rep)
38 if not dlist:
39 return
40 dlist.sort(key=lambda x: x.duration)
41 dlist.reverse()
42 if not durations:
43 tr.write_sep("=", "slowest test durations")
44 else:
45 tr.write_sep("=", "slowest %s test durations" % durations)
46 dlist = dlist[:durations]
47
48 for rep in dlist:
49 nodeid = rep.nodeid.replace("::()::", "::")
50 tr.write_line("%02.2fs %-8s %s" %
51 (rep.duration, rep.when, nodeid))
52
53 def pytest_sessionstart(session):
54 session._setupstate = SetupState()
55 def pytest_sessionfinish(session):
56 session._setupstate.teardown_all()
57
58 class NodeInfo:
59 def __init__(self, location):
60 self.location = location
61
62 def pytest_runtest_protocol(item, nextitem):
63 item.ihook.pytest_runtest_logstart(
64 nodeid=item.nodeid, location=item.location,
65 )
66 runtestprotocol(item, nextitem=nextitem)
67 return True
68
69 def runtestprotocol(item, log=True, nextitem=None):
70 hasrequest = hasattr(item, "_request")
71 if hasrequest and not item._request:
72 item._initrequest()
73 rep = call_and_report(item, "setup", log)
74 reports = [rep]
75 if rep.passed:
76 reports.append(call_and_report(item, "call", log))
77 reports.append(call_and_report(item, "teardown", log,
78 nextitem=nextitem))
79 # after all teardown hooks have been called
80 # want funcargs and request info to go away
81 if hasrequest:
82 item._request = False
83 item.funcargs = None
84 return reports
85
86 def pytest_runtest_setup(item):
87 item.session._setupstate.prepare(item)
88
89 def pytest_runtest_call(item):
90 try:
91 item.runtest()
92 except Exception:
93 # Store trace info to allow postmortem debugging
94 type, value, tb = sys.exc_info()
95 tb = tb.tb_next # Skip *this* frame
96 sys.last_type = type
97 sys.last_value = value
98 sys.last_traceback = tb
99 del tb # Get rid of it in this namespace
100 raise
101
102 def pytest_runtest_teardown(item, nextitem):
103 item.session._setupstate.teardown_exact(item, nextitem)
104
105 def pytest_report_teststatus(report):
106 if report.when in ("setup", "teardown"):
107 if report.failed:
108 # category, shortletter, verbose-word
109 return "error", "E", "ERROR"
110 elif report.skipped:
111 return "skipped", "s", "SKIPPED"
112 else:
113 return "", "", ""
114
115
116 #
117 # Implementation
118
119 def call_and_report(item, when, log=True, **kwds):
120 call = call_runtest_hook(item, when, **kwds)
121 hook = item.ihook
122 report = hook.pytest_runtest_makereport(item=item, call=call)
123 if log:
124 hook.pytest_runtest_logreport(report=report)
125 if check_interactive_exception(call, report):
126 hook.pytest_exception_interact(node=item, call=call, report=report)
127 return report
128
129 def check_interactive_exception(call, report):
130 return call.excinfo and not (
131 hasattr(report, "wasxfail") or
132 call.excinfo.errisinstance(skip.Exception) or
133 call.excinfo.errisinstance(bdb.BdbQuit))
134
135 def call_runtest_hook(item, when, **kwds):
136 hookname = "pytest_runtest_" + when
137 ihook = getattr(item.ihook, hookname)
138 return CallInfo(lambda: ihook(item=item, **kwds), when=when)
139
140 class CallInfo:
141 """ Result/Exception info a function invocation. """
142 #: None or ExceptionInfo object.
143 excinfo = None
144 def __init__(self, func, when):
145 #: context of invocation: one of "setup", "call",
146 #: "teardown", "memocollect"
147 self.when = when
148 self.start = time()
149 try:
150 self.result = func()
151 except KeyboardInterrupt:
152 self.stop = time()
153 raise
154 except:
155 self.excinfo = ExceptionInfo()
156 self.stop = time()
157
158 def __repr__(self):
159 if self.excinfo:
160 status = "exception: %s" % str(self.excinfo.value)
161 else:
162 status = "result: %r" % (self.result,)
163 return "<CallInfo when=%r %s>" % (self.when, status)
164
165 def getslaveinfoline(node):
166 try:
167 return node._slaveinfocache
168 except AttributeError:
169 d = node.slaveinfo
170 ver = "%s.%s.%s" % d['version_info'][:3]
171 node._slaveinfocache = s = "[%s] %s -- Python %s %s" % (
172 d['id'], d['sysplatform'], ver, d['executable'])
173 return s
174
175 class BaseReport(object):
176
177 def __init__(self, **kw):
178 self.__dict__.update(kw)
179
180 def toterminal(self, out):
181 if hasattr(self, 'node'):
182 out.line(getslaveinfoline(self.node))
183
184 longrepr = self.longrepr
185 if longrepr is None:
186 return
187
188 if hasattr(longrepr, 'toterminal'):
189 longrepr.toterminal(out)
190 else:
191 try:
192 out.line(longrepr)
193 except UnicodeEncodeError:
194 out.line("<unprintable longrepr>")
195
196 def get_sections(self, prefix):
197 for name, content in self.sections:
198 if name.startswith(prefix):
199 yield prefix, content
200
201 passed = property(lambda x: x.outcome == "passed")
202 failed = property(lambda x: x.outcome == "failed")
203 skipped = property(lambda x: x.outcome == "skipped")
204
205 @property
206 def fspath(self):
207 return self.nodeid.split("::")[0]
208
209 def pytest_runtest_makereport(item, call):
210 when = call.when
211 duration = call.stop-call.start
212 keywords = dict([(x,1) for x in item.keywords])
213 excinfo = call.excinfo
214 sections = []
215 if not call.excinfo:
216 outcome = "passed"
217 longrepr = None
218 else:
219 if not isinstance(excinfo, ExceptionInfo):
220 outcome = "failed"
221 longrepr = excinfo
222 elif excinfo.errisinstance(pytest.skip.Exception):
223 outcome = "skipped"
224 r = excinfo._getreprcrash()
225 longrepr = (str(r.path), r.lineno, r.message)
226 else:
227 outcome = "failed"
228 if call.when == "call":
229 longrepr = item.repr_failure(excinfo)
230 else: # exception in setup or teardown
231 longrepr = item._repr_failure_py(excinfo,
232 style=item.config.option.tbstyle)
233 for rwhen, key, content in item._report_sections:
234 sections.append(("Captured %s %s" %(key, rwhen), content))
235 return TestReport(item.nodeid, item.location,
236 keywords, outcome, longrepr, when,
237 sections, duration)
238
239 class TestReport(BaseReport):
240 """ Basic test report object (also used for setup and teardown calls if
241 they fail).
242 """
243 def __init__(self, nodeid, location, keywords, outcome,
244 longrepr, when, sections=(), duration=0, **extra):
245 #: normalized collection node id
246 self.nodeid = nodeid
247
248 #: a (filesystempath, lineno, domaininfo) tuple indicating the
249 #: actual location of a test item - it might be different from the
250 #: collected one e.g. if a method is inherited from a different module.
251 self.location = location
252
253 #: a name -> value dictionary containing all keywords and
254 #: markers associated with a test invocation.
255 self.keywords = keywords
256
257 #: test outcome, always one of "passed", "failed", "skipped".
258 self.outcome = outcome
259
260 #: None or a failure representation.
261 self.longrepr = longrepr
262
263 #: one of 'setup', 'call', 'teardown' to indicate runtest phase.
264 self.when = when
265
266 #: list of (secname, data) extra information which needs to
267 #: marshallable
268 self.sections = list(sections)
269
270 #: time it took to run just the test
271 self.duration = duration
272
273 self.__dict__.update(extra)
274
275 def __repr__(self):
276 return "<TestReport %r when=%r outcome=%r>" % (
277 self.nodeid, self.when, self.outcome)
278
279 class TeardownErrorReport(BaseReport):
280 outcome = "failed"
281 when = "teardown"
282 def __init__(self, longrepr, **extra):
283 self.longrepr = longrepr
284 self.sections = []
285 self.__dict__.update(extra)
286
287 def pytest_make_collect_report(collector):
288 call = CallInfo(collector._memocollect, "memocollect")
289 longrepr = None
290 if not call.excinfo:
291 outcome = "passed"
292 else:
293 from _pytest import nose
294 skip_exceptions = (Skipped,) + nose.get_skip_exceptions()
295 if call.excinfo.errisinstance(skip_exceptions):
296 outcome = "skipped"
297 r = collector._repr_failure_py(call.excinfo, "line").reprcrash
298 longrepr = (str(r.path), r.lineno, r.message)
299 else:
300 outcome = "failed"
301 errorinfo = collector.repr_failure(call.excinfo)
302 if not hasattr(errorinfo, "toterminal"):
303 errorinfo = CollectErrorRepr(errorinfo)
304 longrepr = errorinfo
305 rep = CollectReport(collector.nodeid, outcome, longrepr,
306 getattr(call, 'result', None))
307 rep.call = call # see collect_one_node
308 return rep
309
310
311 class CollectReport(BaseReport):
312 def __init__(self, nodeid, outcome, longrepr, result,
313 sections=(), **extra):
314 self.nodeid = nodeid
315 self.outcome = outcome
316 self.longrepr = longrepr
317 self.result = result or []
318 self.sections = list(sections)
319 self.__dict__.update(extra)
320
321 @property
322 def location(self):
323 return (self.fspath, None, self.fspath)
324
325 def __repr__(self):
326 return "<CollectReport %r lenresult=%s outcome=%r>" % (
327 self.nodeid, len(self.result), self.outcome)
328
329 class CollectErrorRepr(TerminalRepr):
330 def __init__(self, msg):
331 self.longrepr = msg
332 def toterminal(self, out):
333 out.line(self.longrepr, red=True)
334
335 class SetupState(object):
336 """ shared state for setting up/tearing down test items or collectors. """
337 def __init__(self):
338 self.stack = []
339 self._finalizers = {}
340
341 def addfinalizer(self, finalizer, colitem):
342 """ attach a finalizer to the given colitem.
343 if colitem is None, this will add a finalizer that
344 is called at the end of teardown_all().
345 """
346 assert colitem and not isinstance(colitem, tuple)
347 assert py.builtin.callable(finalizer)
348 #assert colitem in self.stack # some unit tests don't setup stack :/
349 self._finalizers.setdefault(colitem, []).append(finalizer)
350
351 def _pop_and_teardown(self):
352 colitem = self.stack.pop()
353 self._teardown_with_finalization(colitem)
354
355 def _callfinalizers(self, colitem):
356 finalizers = self._finalizers.pop(colitem, None)
357 exc = None
358 while finalizers:
359 fin = finalizers.pop()
360 try:
361 fin()
362 except Exception:
363 # XXX Only first exception will be seen by user,
364 # ideally all should be reported.
365 if exc is None:
366 exc = sys.exc_info()
367 if exc:
368 py.builtin._reraise(*exc)
369
370 def _teardown_with_finalization(self, colitem):
371 self._callfinalizers(colitem)
372 if hasattr(colitem, "teardown"):
373 colitem.teardown()
374 for colitem in self._finalizers:
375 assert colitem is None or colitem in self.stack \
376 or isinstance(colitem, tuple)
377
378 def teardown_all(self):
379 while self.stack:
380 self._pop_and_teardown()
381 for key in list(self._finalizers):
382 self._teardown_with_finalization(key)
383 assert not self._finalizers
384
385 def teardown_exact(self, item, nextitem):
386 needed_collectors = nextitem and nextitem.listchain() or []
387 self._teardown_towards(needed_collectors)
388
389 def _teardown_towards(self, needed_collectors):
390 while self.stack:
391 if self.stack == needed_collectors[:len(self.stack)]:
392 break
393 self._pop_and_teardown()
394
395 def prepare(self, colitem):
396 """ setup objects along the collector chain to the test-method
397 and teardown previously setup objects."""
398 needed_collectors = colitem.listchain()
399 self._teardown_towards(needed_collectors)
400
401 # check if the last collection node has raised an error
402 for col in self.stack:
403 if hasattr(col, '_prepare_exc'):
404 py.builtin._reraise(*col._prepare_exc)
405 for col in needed_collectors[len(self.stack):]:
406 self.stack.append(col)
407 try:
408 col.setup()
409 except Exception:
410 col._prepare_exc = sys.exc_info()
411 raise
412
413 def collect_one_node(collector):
414 ihook = collector.ihook
415 ihook.pytest_collectstart(collector=collector)
416 rep = ihook.pytest_make_collect_report(collector=collector)
417 call = rep.__dict__.pop("call", None)
418 if call and check_interactive_exception(call, rep):
419 ihook.pytest_exception_interact(node=collector, call=call, report=rep)
420 return rep
421
422
423 # =============================================================
424 # Test OutcomeExceptions and helpers for creating them.
425
426
427 class OutcomeException(Exception):
428 """ OutcomeException and its subclass instances indicate and
429 contain info about test and collection outcomes.
430 """
431 def __init__(self, msg=None, pytrace=True):
432 Exception.__init__(self, msg)
433 self.msg = msg
434 self.pytrace = pytrace
435
436 def __repr__(self):
437 if self.msg:
438 val = self.msg
439 if isinstance(val, bytes):
440 val = py._builtin._totext(val, errors='replace')
441 return val
442 return "<%s instance>" %(self.__class__.__name__,)
443 __str__ = __repr__
444
445 class Skipped(OutcomeException):
446 # XXX hackish: on 3k we fake to live in the builtins
447 # in order to have Skipped exception printing shorter/nicer
448 __module__ = 'builtins'
449
450 class Failed(OutcomeException):
451 """ raised from an explicit call to pytest.fail() """
452 __module__ = 'builtins'
453
454 class Exit(KeyboardInterrupt):
455 """ raised for immediate program exits (no tracebacks/summaries)"""
456 def __init__(self, msg="unknown reason"):
457 self.msg = msg
458 KeyboardInterrupt.__init__(self, msg)
459
460 # exposed helper methods
461
462 def exit(msg):
463 """ exit testing process as if KeyboardInterrupt was triggered. """
464 __tracebackhide__ = True
465 raise Exit(msg)
466
467 exit.Exception = Exit
468
469 def skip(msg=""):
470 """ skip an executing test with the given message. Note: it's usually
471 better to use the pytest.mark.skipif marker to declare a test to be
472 skipped under certain conditions like mismatching platforms or
473 dependencies. See the pytest_skipping plugin for details.
474 """
475 __tracebackhide__ = True
476 raise Skipped(msg=msg)
477 skip.Exception = Skipped
478
479 def fail(msg="", pytrace=True):
480 """ explicitly fail an currently-executing test with the given Message.
481
482 :arg pytrace: if false the msg represents the full failure information
483 and no python traceback will be reported.
484 """
485 __tracebackhide__ = True
486 raise Failed(msg=msg, pytrace=pytrace)
487 fail.Exception = Failed
488
489
490 def importorskip(modname, minversion=None):
491 """ return imported module if it has at least "minversion" as its
492 __version__ attribute. If no minversion is specified the a skip
493 is only triggered if the module can not be imported.
494 """
495 __tracebackhide__ = True
496 compile(modname, '', 'eval') # to catch syntaxerrors
497 try:
498 __import__(modname)
499 except ImportError:
500 skip("could not import %r" %(modname,))
501 mod = sys.modules[modname]
502 if minversion is None:
503 return mod
504 verattr = getattr(mod, '__version__', None)
505 if minversion is not None:
506 try:
507 from pkg_resources import parse_version as pv
508 except ImportError:
509 skip("we have a required version for %r but can not import "
510 "no pkg_resources to parse version strings." %(modname,))
511 if verattr is None or pv(verattr) < pv(minversion):
512 skip("module %r has __version__ %r, required is: %r" %(
513 modname, verattr, minversion))
514 return mod
515