code.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. import inspect
  6. import re
  7. import sys
  8. import traceback
  9. from inspect import CO_VARARGS
  10. from inspect import CO_VARKEYWORDS
  11. from weakref import ref
  12. import attr
  13. import pluggy
  14. import py
  15. from six import text_type
  16. import _pytest
  17. from _pytest._io.saferepr import safeformat
  18. from _pytest._io.saferepr import saferepr
  19. from _pytest.compat import _PY2
  20. from _pytest.compat import _PY3
  21. from _pytest.compat import PY35
  22. from _pytest.compat import safe_str
  23. if _PY3:
  24. from traceback import format_exception_only
  25. else:
  26. from ._py2traceback import format_exception_only
  27. class Code(object):
  28. """ wrapper around Python code objects """
  29. def __init__(self, rawcode):
  30. if not hasattr(rawcode, "co_filename"):
  31. rawcode = getrawcode(rawcode)
  32. try:
  33. self.filename = rawcode.co_filename
  34. self.firstlineno = rawcode.co_firstlineno - 1
  35. self.name = rawcode.co_name
  36. except AttributeError:
  37. raise TypeError("not a code object: %r" % (rawcode,))
  38. self.raw = rawcode
  39. def __eq__(self, other):
  40. return self.raw == other.raw
  41. __hash__ = None
  42. def __ne__(self, other):
  43. return not self == other
  44. @property
  45. def path(self):
  46. """ return a path object pointing to source code (note that it
  47. might not point to an actually existing file). """
  48. try:
  49. p = py.path.local(self.raw.co_filename)
  50. # maybe don't try this checking
  51. if not p.check():
  52. raise OSError("py.path check failed.")
  53. except OSError:
  54. # XXX maybe try harder like the weird logic
  55. # in the standard lib [linecache.updatecache] does?
  56. p = self.raw.co_filename
  57. return p
  58. @property
  59. def fullsource(self):
  60. """ return a _pytest._code.Source object for the full source file of the code
  61. """
  62. from _pytest._code import source
  63. full, _ = source.findsource(self.raw)
  64. return full
  65. def source(self):
  66. """ return a _pytest._code.Source object for the code object's source only
  67. """
  68. # return source only for that part of code
  69. import _pytest._code
  70. return _pytest._code.Source(self.raw)
  71. def getargs(self, var=False):
  72. """ return a tuple with the argument names for the code object
  73. if 'var' is set True also return the names of the variable and
  74. keyword arguments when present
  75. """
  76. # handfull shortcut for getting args
  77. raw = self.raw
  78. argcount = raw.co_argcount
  79. if var:
  80. argcount += raw.co_flags & CO_VARARGS
  81. argcount += raw.co_flags & CO_VARKEYWORDS
  82. return raw.co_varnames[:argcount]
  83. class Frame(object):
  84. """Wrapper around a Python frame holding f_locals and f_globals
  85. in which expressions can be evaluated."""
  86. def __init__(self, frame):
  87. self.lineno = frame.f_lineno - 1
  88. self.f_globals = frame.f_globals
  89. self.f_locals = frame.f_locals
  90. self.raw = frame
  91. self.code = Code(frame.f_code)
  92. @property
  93. def statement(self):
  94. """ statement this frame is at """
  95. import _pytest._code
  96. if self.code.fullsource is None:
  97. return _pytest._code.Source("")
  98. return self.code.fullsource.getstatement(self.lineno)
  99. def eval(self, code, **vars):
  100. """ evaluate 'code' in the frame
  101. 'vars' are optional additional local variables
  102. returns the result of the evaluation
  103. """
  104. f_locals = self.f_locals.copy()
  105. f_locals.update(vars)
  106. return eval(code, self.f_globals, f_locals)
  107. def exec_(self, code, **vars):
  108. """ exec 'code' in the frame
  109. 'vars' are optiona; additional local variables
  110. """
  111. f_locals = self.f_locals.copy()
  112. f_locals.update(vars)
  113. exec(code, self.f_globals, f_locals)
  114. def repr(self, object):
  115. """ return a 'safe' (non-recursive, one-line) string repr for 'object'
  116. """
  117. return saferepr(object)
  118. def is_true(self, object):
  119. return object
  120. def getargs(self, var=False):
  121. """ return a list of tuples (name, value) for all arguments
  122. if 'var' is set True also include the variable and keyword
  123. arguments when present
  124. """
  125. retval = []
  126. for arg in self.code.getargs(var):
  127. try:
  128. retval.append((arg, self.f_locals[arg]))
  129. except KeyError:
  130. pass # this can occur when using Psyco
  131. return retval
  132. class TracebackEntry(object):
  133. """ a single entry in a traceback """
  134. _repr_style = None
  135. exprinfo = None
  136. def __init__(self, rawentry, excinfo=None):
  137. self._excinfo = excinfo
  138. self._rawentry = rawentry
  139. self.lineno = rawentry.tb_lineno - 1
  140. def set_repr_style(self, mode):
  141. assert mode in ("short", "long")
  142. self._repr_style = mode
  143. @property
  144. def frame(self):
  145. import _pytest._code
  146. return _pytest._code.Frame(self._rawentry.tb_frame)
  147. @property
  148. def relline(self):
  149. return self.lineno - self.frame.code.firstlineno
  150. def __repr__(self):
  151. return "<TracebackEntry %s:%d>" % (self.frame.code.path, self.lineno + 1)
  152. @property
  153. def statement(self):
  154. """ _pytest._code.Source object for the current statement """
  155. source = self.frame.code.fullsource
  156. return source.getstatement(self.lineno)
  157. @property
  158. def path(self):
  159. """ path to the source code """
  160. return self.frame.code.path
  161. def getlocals(self):
  162. return self.frame.f_locals
  163. locals = property(getlocals, None, None, "locals of underlaying frame")
  164. def getfirstlinesource(self):
  165. # on Jython this firstlineno can be -1 apparently
  166. return max(self.frame.code.firstlineno, 0)
  167. def getsource(self, astcache=None):
  168. """ return failing source code. """
  169. # we use the passed in astcache to not reparse asttrees
  170. # within exception info printing
  171. from _pytest._code.source import getstatementrange_ast
  172. source = self.frame.code.fullsource
  173. if source is None:
  174. return None
  175. key = astnode = None
  176. if astcache is not None:
  177. key = self.frame.code.path
  178. if key is not None:
  179. astnode = astcache.get(key, None)
  180. start = self.getfirstlinesource()
  181. try:
  182. astnode, _, end = getstatementrange_ast(
  183. self.lineno, source, astnode=astnode
  184. )
  185. except SyntaxError:
  186. end = self.lineno + 1
  187. else:
  188. if key is not None:
  189. astcache[key] = astnode
  190. return source[start:end]
  191. source = property(getsource)
  192. def ishidden(self):
  193. """ return True if the current frame has a var __tracebackhide__
  194. resolving to True.
  195. If __tracebackhide__ is a callable, it gets called with the
  196. ExceptionInfo instance and can decide whether to hide the traceback.
  197. mostly for internal use
  198. """
  199. f = self.frame
  200. tbh = f.f_locals.get(
  201. "__tracebackhide__", f.f_globals.get("__tracebackhide__", False)
  202. )
  203. if tbh and callable(tbh):
  204. return tbh(None if self._excinfo is None else self._excinfo())
  205. return tbh
  206. def __str__(self):
  207. try:
  208. fn = str(self.path)
  209. except py.error.Error:
  210. fn = "???"
  211. name = self.frame.code.name
  212. try:
  213. line = str(self.statement).lstrip()
  214. except KeyboardInterrupt:
  215. raise
  216. except: # noqa
  217. line = "???"
  218. return " File %r:%d in %s\n %s\n" % (fn, self.lineno + 1, name, line)
  219. def name(self):
  220. return self.frame.code.raw.co_name
  221. name = property(name, None, None, "co_name of underlaying code")
  222. class Traceback(list):
  223. """ Traceback objects encapsulate and offer higher level
  224. access to Traceback entries.
  225. """
  226. Entry = TracebackEntry
  227. def __init__(self, tb, excinfo=None):
  228. """ initialize from given python traceback object and ExceptionInfo """
  229. self._excinfo = excinfo
  230. if hasattr(tb, "tb_next"):
  231. def f(cur):
  232. while cur is not None:
  233. yield self.Entry(cur, excinfo=excinfo)
  234. cur = cur.tb_next
  235. list.__init__(self, f(tb))
  236. else:
  237. list.__init__(self, tb)
  238. def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
  239. """ return a Traceback instance wrapping part of this Traceback
  240. by provding any combination of path, lineno and firstlineno, the
  241. first frame to start the to-be-returned traceback is determined
  242. this allows cutting the first part of a Traceback instance e.g.
  243. for formatting reasons (removing some uninteresting bits that deal
  244. with handling of the exception/traceback)
  245. """
  246. for x in self:
  247. code = x.frame.code
  248. codepath = code.path
  249. if (
  250. (path is None or codepath == path)
  251. and (
  252. excludepath is None
  253. or not hasattr(codepath, "relto")
  254. or not codepath.relto(excludepath)
  255. )
  256. and (lineno is None or x.lineno == lineno)
  257. and (firstlineno is None or x.frame.code.firstlineno == firstlineno)
  258. ):
  259. return Traceback(x._rawentry, self._excinfo)
  260. return self
  261. def __getitem__(self, key):
  262. val = super(Traceback, self).__getitem__(key)
  263. if isinstance(key, type(slice(0))):
  264. val = self.__class__(val)
  265. return val
  266. def filter(self, fn=lambda x: not x.ishidden()):
  267. """ return a Traceback instance with certain items removed
  268. fn is a function that gets a single argument, a TracebackEntry
  269. instance, and should return True when the item should be added
  270. to the Traceback, False when not
  271. by default this removes all the TracebackEntries which are hidden
  272. (see ishidden() above)
  273. """
  274. return Traceback(filter(fn, self), self._excinfo)
  275. def getcrashentry(self):
  276. """ return last non-hidden traceback entry that lead
  277. to the exception of a traceback.
  278. """
  279. for i in range(-1, -len(self) - 1, -1):
  280. entry = self[i]
  281. if not entry.ishidden():
  282. return entry
  283. return self[-1]
  284. def recursionindex(self):
  285. """ return the index of the frame/TracebackEntry where recursion
  286. originates if appropriate, None if no recursion occurred
  287. """
  288. cache = {}
  289. for i, entry in enumerate(self):
  290. # id for the code.raw is needed to work around
  291. # the strange metaprogramming in the decorator lib from pypi
  292. # which generates code objects that have hash/value equality
  293. # XXX needs a test
  294. key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
  295. # print "checking for recursion at", key
  296. values = cache.setdefault(key, [])
  297. if values:
  298. f = entry.frame
  299. loc = f.f_locals
  300. for otherloc in values:
  301. if f.is_true(
  302. f.eval(
  303. co_equal,
  304. __recursioncache_locals_1=loc,
  305. __recursioncache_locals_2=otherloc,
  306. )
  307. ):
  308. return i
  309. values.append(entry.frame.f_locals)
  310. return None
  311. co_equal = compile(
  312. "__recursioncache_locals_1 == __recursioncache_locals_2", "?", "eval"
  313. )
  314. @attr.s(repr=False)
  315. class ExceptionInfo(object):
  316. """ wraps sys.exc_info() objects and offers
  317. help for navigating the traceback.
  318. """
  319. _assert_start_repr = (
  320. "AssertionError(u'assert " if _PY2 else "AssertionError('assert "
  321. )
  322. _excinfo = attr.ib()
  323. _striptext = attr.ib(default="")
  324. _traceback = attr.ib(default=None)
  325. @classmethod
  326. def from_current(cls, exprinfo=None):
  327. """returns an ExceptionInfo matching the current traceback
  328. .. warning::
  329. Experimental API
  330. :param exprinfo: a text string helping to determine if we should
  331. strip ``AssertionError`` from the output, defaults
  332. to the exception message/``__str__()``
  333. """
  334. tup = sys.exc_info()
  335. assert tup[0] is not None, "no current exception"
  336. _striptext = ""
  337. if exprinfo is None and isinstance(tup[1], AssertionError):
  338. exprinfo = getattr(tup[1], "msg", None)
  339. if exprinfo is None:
  340. exprinfo = saferepr(tup[1])
  341. if exprinfo and exprinfo.startswith(cls._assert_start_repr):
  342. _striptext = "AssertionError: "
  343. return cls(tup, _striptext)
  344. @classmethod
  345. def for_later(cls):
  346. """return an unfilled ExceptionInfo
  347. """
  348. return cls(None)
  349. @property
  350. def type(self):
  351. """the exception class"""
  352. return self._excinfo[0]
  353. @property
  354. def value(self):
  355. """the exception value"""
  356. return self._excinfo[1]
  357. @property
  358. def tb(self):
  359. """the exception raw traceback"""
  360. return self._excinfo[2]
  361. @property
  362. def typename(self):
  363. """the type name of the exception"""
  364. return self.type.__name__
  365. @property
  366. def traceback(self):
  367. """the traceback"""
  368. if self._traceback is None:
  369. self._traceback = Traceback(self.tb, excinfo=ref(self))
  370. return self._traceback
  371. @traceback.setter
  372. def traceback(self, value):
  373. self._traceback = value
  374. def __repr__(self):
  375. if self._excinfo is None:
  376. return "<ExceptionInfo for raises contextmanager>"
  377. return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
  378. def exconly(self, tryshort=False):
  379. """ return the exception as a string
  380. when 'tryshort' resolves to True, and the exception is a
  381. _pytest._code._AssertionError, only the actual exception part of
  382. the exception representation is returned (so 'AssertionError: ' is
  383. removed from the beginning)
  384. """
  385. lines = format_exception_only(self.type, self.value)
  386. text = "".join(lines)
  387. text = text.rstrip()
  388. if tryshort:
  389. if text.startswith(self._striptext):
  390. text = text[len(self._striptext) :]
  391. return text
  392. def errisinstance(self, exc):
  393. """ return True if the exception is an instance of exc """
  394. return isinstance(self.value, exc)
  395. def _getreprcrash(self):
  396. exconly = self.exconly(tryshort=True)
  397. entry = self.traceback.getcrashentry()
  398. path, lineno = entry.frame.code.raw.co_filename, entry.lineno
  399. return ReprFileLocation(path, lineno + 1, exconly)
  400. def getrepr(
  401. self,
  402. showlocals=False,
  403. style="long",
  404. abspath=False,
  405. tbfilter=True,
  406. funcargs=False,
  407. truncate_locals=True,
  408. chain=True,
  409. ):
  410. """
  411. Return str()able representation of this exception info.
  412. :param bool showlocals:
  413. Show locals per traceback entry.
  414. Ignored if ``style=="native"``.
  415. :param str style: long|short|no|native traceback style
  416. :param bool abspath:
  417. If paths should be changed to absolute or left unchanged.
  418. :param bool tbfilter:
  419. Hide entries that contain a local variable ``__tracebackhide__==True``.
  420. Ignored if ``style=="native"``.
  421. :param bool funcargs:
  422. Show fixtures ("funcargs" for legacy purposes) per traceback entry.
  423. :param bool truncate_locals:
  424. With ``showlocals==True``, make sure locals can be safely represented as strings.
  425. :param bool chain: if chained exceptions in Python 3 should be shown.
  426. .. versionchanged:: 3.9
  427. Added the ``chain`` parameter.
  428. """
  429. if style == "native":
  430. return ReprExceptionInfo(
  431. ReprTracebackNative(
  432. traceback.format_exception(
  433. self.type, self.value, self.traceback[0]._rawentry
  434. )
  435. ),
  436. self._getreprcrash(),
  437. )
  438. fmt = FormattedExcinfo(
  439. showlocals=showlocals,
  440. style=style,
  441. abspath=abspath,
  442. tbfilter=tbfilter,
  443. funcargs=funcargs,
  444. truncate_locals=truncate_locals,
  445. chain=chain,
  446. )
  447. return fmt.repr_excinfo(self)
  448. def __str__(self):
  449. if self._excinfo is None:
  450. return repr(self)
  451. entry = self.traceback[-1]
  452. loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
  453. return str(loc)
  454. def __unicode__(self):
  455. entry = self.traceback[-1]
  456. loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
  457. return text_type(loc)
  458. def match(self, regexp):
  459. """
  460. Check whether the regular expression 'regexp' is found in the string
  461. representation of the exception using ``re.search``. If it matches
  462. then True is returned (so that it is possible to write
  463. ``assert excinfo.match()``). If it doesn't match an AssertionError is
  464. raised.
  465. """
  466. __tracebackhide__ = True
  467. value = (
  468. text_type(self.value) if isinstance(regexp, text_type) else str(self.value)
  469. )
  470. if not re.search(regexp, value):
  471. raise AssertionError(
  472. u"Pattern {!r} not found in {!r}".format(regexp, value)
  473. )
  474. return True
  475. @attr.s
  476. class FormattedExcinfo(object):
  477. """ presenting information about failing Functions and Generators. """
  478. # for traceback entries
  479. flow_marker = ">"
  480. fail_marker = "E"
  481. showlocals = attr.ib(default=False)
  482. style = attr.ib(default="long")
  483. abspath = attr.ib(default=True)
  484. tbfilter = attr.ib(default=True)
  485. funcargs = attr.ib(default=False)
  486. truncate_locals = attr.ib(default=True)
  487. chain = attr.ib(default=True)
  488. astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)
  489. def _getindent(self, source):
  490. # figure out indent for given source
  491. try:
  492. s = str(source.getstatement(len(source) - 1))
  493. except KeyboardInterrupt:
  494. raise
  495. except: # noqa
  496. try:
  497. s = str(source[-1])
  498. except KeyboardInterrupt:
  499. raise
  500. except: # noqa
  501. return 0
  502. return 4 + (len(s) - len(s.lstrip()))
  503. def _getentrysource(self, entry):
  504. source = entry.getsource(self.astcache)
  505. if source is not None:
  506. source = source.deindent()
  507. return source
  508. def repr_args(self, entry):
  509. if self.funcargs:
  510. args = []
  511. for argname, argvalue in entry.frame.getargs(var=True):
  512. args.append((argname, saferepr(argvalue)))
  513. return ReprFuncArgs(args)
  514. def get_source(self, source, line_index=-1, excinfo=None, short=False):
  515. """ return formatted and marked up source lines. """
  516. import _pytest._code
  517. lines = []
  518. if source is None or line_index >= len(source.lines):
  519. source = _pytest._code.Source("???")
  520. line_index = 0
  521. if line_index < 0:
  522. line_index += len(source)
  523. space_prefix = " "
  524. if short:
  525. lines.append(space_prefix + source.lines[line_index].strip())
  526. else:
  527. for line in source.lines[:line_index]:
  528. lines.append(space_prefix + line)
  529. lines.append(self.flow_marker + " " + source.lines[line_index])
  530. for line in source.lines[line_index + 1 :]:
  531. lines.append(space_prefix + line)
  532. if excinfo is not None:
  533. indent = 4 if short else self._getindent(source)
  534. lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
  535. return lines
  536. def get_exconly(self, excinfo, indent=4, markall=False):
  537. lines = []
  538. indent = " " * indent
  539. # get the real exception information out
  540. exlines = excinfo.exconly(tryshort=True).split("\n")
  541. failindent = self.fail_marker + indent[1:]
  542. for line in exlines:
  543. lines.append(failindent + line)
  544. if not markall:
  545. failindent = indent
  546. return lines
  547. def repr_locals(self, locals):
  548. if self.showlocals:
  549. lines = []
  550. keys = [loc for loc in locals if loc[0] != "@"]
  551. keys.sort()
  552. for name in keys:
  553. value = locals[name]
  554. if name == "__builtins__":
  555. lines.append("__builtins__ = <builtins>")
  556. else:
  557. # This formatting could all be handled by the
  558. # _repr() function, which is only reprlib.Repr in
  559. # disguise, so is very configurable.
  560. if self.truncate_locals:
  561. str_repr = saferepr(value)
  562. else:
  563. str_repr = safeformat(value)
  564. # if len(str_repr) < 70 or not isinstance(value,
  565. # (list, tuple, dict)):
  566. lines.append("%-10s = %s" % (name, str_repr))
  567. # else:
  568. # self._line("%-10s =\\" % (name,))
  569. # # XXX
  570. # pprint.pprint(value, stream=self.excinfowriter)
  571. return ReprLocals(lines)
  572. def repr_traceback_entry(self, entry, excinfo=None):
  573. import _pytest._code
  574. source = self._getentrysource(entry)
  575. if source is None:
  576. source = _pytest._code.Source("???")
  577. line_index = 0
  578. else:
  579. # entry.getfirstlinesource() can be -1, should be 0 on jython
  580. line_index = entry.lineno - max(entry.getfirstlinesource(), 0)
  581. lines = []
  582. style = entry._repr_style
  583. if style is None:
  584. style = self.style
  585. if style in ("short", "long"):
  586. short = style == "short"
  587. reprargs = self.repr_args(entry) if not short else None
  588. s = self.get_source(source, line_index, excinfo, short=short)
  589. lines.extend(s)
  590. if short:
  591. message = "in %s" % (entry.name)
  592. else:
  593. message = excinfo and excinfo.typename or ""
  594. path = self._makepath(entry.path)
  595. filelocrepr = ReprFileLocation(path, entry.lineno + 1, message)
  596. localsrepr = None
  597. if not short:
  598. localsrepr = self.repr_locals(entry.locals)
  599. return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)
  600. if excinfo:
  601. lines.extend(self.get_exconly(excinfo, indent=4))
  602. return ReprEntry(lines, None, None, None, style)
  603. def _makepath(self, path):
  604. if not self.abspath:
  605. try:
  606. np = py.path.local().bestrelpath(path)
  607. except OSError:
  608. return path
  609. if len(np) < len(str(path)):
  610. path = np
  611. return path
  612. def repr_traceback(self, excinfo):
  613. traceback = excinfo.traceback
  614. if self.tbfilter:
  615. traceback = traceback.filter()
  616. if is_recursion_error(excinfo):
  617. traceback, extraline = self._truncate_recursive_traceback(traceback)
  618. else:
  619. extraline = None
  620. last = traceback[-1]
  621. entries = []
  622. for index, entry in enumerate(traceback):
  623. einfo = (last == entry) and excinfo or None
  624. reprentry = self.repr_traceback_entry(entry, einfo)
  625. entries.append(reprentry)
  626. return ReprTraceback(entries, extraline, style=self.style)
  627. def _truncate_recursive_traceback(self, traceback):
  628. """
  629. Truncate the given recursive traceback trying to find the starting point
  630. of the recursion.
  631. The detection is done by going through each traceback entry and finding the
  632. point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.
  633. Handle the situation where the recursion process might raise an exception (for example
  634. comparing numpy arrays using equality raises a TypeError), in which case we do our best to
  635. warn the user of the error and show a limited traceback.
  636. """
  637. try:
  638. recursionindex = traceback.recursionindex()
  639. except Exception as e:
  640. max_frames = 10
  641. extraline = (
  642. "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
  643. " The following exception happened when comparing locals in the stack frame:\n"
  644. " {exc_type}: {exc_msg}\n"
  645. " Displaying first and last {max_frames} stack frames out of {total}."
  646. ).format(
  647. exc_type=type(e).__name__,
  648. exc_msg=safe_str(e),
  649. max_frames=max_frames,
  650. total=len(traceback),
  651. )
  652. traceback = traceback[:max_frames] + traceback[-max_frames:]
  653. else:
  654. if recursionindex is not None:
  655. extraline = "!!! Recursion detected (same locals & position)"
  656. traceback = traceback[: recursionindex + 1]
  657. else:
  658. extraline = None
  659. return traceback, extraline
  660. def repr_excinfo(self, excinfo):
  661. if _PY2:
  662. reprtraceback = self.repr_traceback(excinfo)
  663. reprcrash = excinfo._getreprcrash()
  664. return ReprExceptionInfo(reprtraceback, reprcrash)
  665. else:
  666. repr_chain = []
  667. e = excinfo.value
  668. descr = None
  669. seen = set()
  670. while e is not None and id(e) not in seen:
  671. seen.add(id(e))
  672. if excinfo:
  673. reprtraceback = self.repr_traceback(excinfo)
  674. reprcrash = excinfo._getreprcrash()
  675. else:
  676. # fallback to native repr if the exception doesn't have a traceback:
  677. # ExceptionInfo objects require a full traceback to work
  678. reprtraceback = ReprTracebackNative(
  679. traceback.format_exception(type(e), e, None)
  680. )
  681. reprcrash = None
  682. repr_chain += [(reprtraceback, reprcrash, descr)]
  683. if e.__cause__ is not None and self.chain:
  684. e = e.__cause__
  685. excinfo = (
  686. ExceptionInfo((type(e), e, e.__traceback__))
  687. if e.__traceback__
  688. else None
  689. )
  690. descr = "The above exception was the direct cause of the following exception:"
  691. elif (
  692. e.__context__ is not None
  693. and not e.__suppress_context__
  694. and self.chain
  695. ):
  696. e = e.__context__
  697. excinfo = (
  698. ExceptionInfo((type(e), e, e.__traceback__))
  699. if e.__traceback__
  700. else None
  701. )
  702. descr = "During handling of the above exception, another exception occurred:"
  703. else:
  704. e = None
  705. repr_chain.reverse()
  706. return ExceptionChainRepr(repr_chain)
  707. class TerminalRepr(object):
  708. def __str__(self):
  709. s = self.__unicode__()
  710. if _PY2:
  711. s = s.encode("utf-8")
  712. return s
  713. def __unicode__(self):
  714. # FYI this is called from pytest-xdist's serialization of exception
  715. # information.
  716. io = py.io.TextIO()
  717. tw = py.io.TerminalWriter(file=io)
  718. self.toterminal(tw)
  719. return io.getvalue().strip()
  720. def __repr__(self):
  721. return "<%s instance at %0x>" % (self.__class__, id(self))
  722. class ExceptionRepr(TerminalRepr):
  723. def __init__(self):
  724. self.sections = []
  725. def addsection(self, name, content, sep="-"):
  726. self.sections.append((name, content, sep))
  727. def toterminal(self, tw):
  728. for name, content, sep in self.sections:
  729. tw.sep(sep, name)
  730. tw.line(content)
  731. class ExceptionChainRepr(ExceptionRepr):
  732. def __init__(self, chain):
  733. super(ExceptionChainRepr, self).__init__()
  734. self.chain = chain
  735. # reprcrash and reprtraceback of the outermost (the newest) exception
  736. # in the chain
  737. self.reprtraceback = chain[-1][0]
  738. self.reprcrash = chain[-1][1]
  739. def toterminal(self, tw):
  740. for element in self.chain:
  741. element[0].toterminal(tw)
  742. if element[2] is not None:
  743. tw.line("")
  744. tw.line(element[2], yellow=True)
  745. super(ExceptionChainRepr, self).toterminal(tw)
  746. class ReprExceptionInfo(ExceptionRepr):
  747. def __init__(self, reprtraceback, reprcrash):
  748. super(ReprExceptionInfo, self).__init__()
  749. self.reprtraceback = reprtraceback
  750. self.reprcrash = reprcrash
  751. def toterminal(self, tw):
  752. self.reprtraceback.toterminal(tw)
  753. super(ReprExceptionInfo, self).toterminal(tw)
  754. class ReprTraceback(TerminalRepr):
  755. entrysep = "_ "
  756. def __init__(self, reprentries, extraline, style):
  757. self.reprentries = reprentries
  758. self.extraline = extraline
  759. self.style = style
  760. def toterminal(self, tw):
  761. # the entries might have different styles
  762. for i, entry in enumerate(self.reprentries):
  763. if entry.style == "long":
  764. tw.line("")
  765. entry.toterminal(tw)
  766. if i < len(self.reprentries) - 1:
  767. next_entry = self.reprentries[i + 1]
  768. if (
  769. entry.style == "long"
  770. or entry.style == "short"
  771. and next_entry.style == "long"
  772. ):
  773. tw.sep(self.entrysep)
  774. if self.extraline:
  775. tw.line(self.extraline)
  776. class ReprTracebackNative(ReprTraceback):
  777. def __init__(self, tblines):
  778. self.style = "native"
  779. self.reprentries = [ReprEntryNative(tblines)]
  780. self.extraline = None
  781. class ReprEntryNative(TerminalRepr):
  782. style = "native"
  783. def __init__(self, tblines):
  784. self.lines = tblines
  785. def toterminal(self, tw):
  786. tw.write("".join(self.lines))
  787. class ReprEntry(TerminalRepr):
  788. def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):
  789. self.lines = lines
  790. self.reprfuncargs = reprfuncargs
  791. self.reprlocals = reprlocals
  792. self.reprfileloc = filelocrepr
  793. self.style = style
  794. def toterminal(self, tw):
  795. if self.style == "short":
  796. self.reprfileloc.toterminal(tw)
  797. for line in self.lines:
  798. red = line.startswith("E ")
  799. tw.line(line, bold=True, red=red)
  800. # tw.line("")
  801. return
  802. if self.reprfuncargs:
  803. self.reprfuncargs.toterminal(tw)
  804. for line in self.lines:
  805. red = line.startswith("E ")
  806. tw.line(line, bold=True, red=red)
  807. if self.reprlocals:
  808. tw.line("")
  809. self.reprlocals.toterminal(tw)
  810. if self.reprfileloc:
  811. if self.lines:
  812. tw.line("")
  813. self.reprfileloc.toterminal(tw)
  814. def __str__(self):
  815. return "%s\n%s\n%s" % ("\n".join(self.lines), self.reprlocals, self.reprfileloc)
  816. class ReprFileLocation(TerminalRepr):
  817. def __init__(self, path, lineno, message):
  818. self.path = str(path)
  819. self.lineno = lineno
  820. self.message = message
  821. def toterminal(self, tw):
  822. # filename and lineno output for each entry,
  823. # using an output format that most editors unterstand
  824. msg = self.message
  825. i = msg.find("\n")
  826. if i != -1:
  827. msg = msg[:i]
  828. tw.write(self.path, bold=True, red=True)
  829. tw.line(":%s: %s" % (self.lineno, msg))
  830. class ReprLocals(TerminalRepr):
  831. def __init__(self, lines):
  832. self.lines = lines
  833. def toterminal(self, tw):
  834. for line in self.lines:
  835. tw.line(line)
  836. class ReprFuncArgs(TerminalRepr):
  837. def __init__(self, args):
  838. self.args = args
  839. def toterminal(self, tw):
  840. if self.args:
  841. linesofar = ""
  842. for name, value in self.args:
  843. ns = "%s = %s" % (safe_str(name), safe_str(value))
  844. if len(ns) + len(linesofar) + 2 > tw.fullwidth:
  845. if linesofar:
  846. tw.line(linesofar)
  847. linesofar = ns
  848. else:
  849. if linesofar:
  850. linesofar += ", " + ns
  851. else:
  852. linesofar = ns
  853. if linesofar:
  854. tw.line(linesofar)
  855. tw.line("")
  856. def getrawcode(obj, trycall=True):
  857. """ return code object for given function. """
  858. try:
  859. return obj.__code__
  860. except AttributeError:
  861. obj = getattr(obj, "im_func", obj)
  862. obj = getattr(obj, "func_code", obj)
  863. obj = getattr(obj, "f_code", obj)
  864. obj = getattr(obj, "__code__", obj)
  865. if trycall and not hasattr(obj, "co_firstlineno"):
  866. if hasattr(obj, "__call__") and not inspect.isclass(obj):
  867. x = getrawcode(obj.__call__, trycall=False)
  868. if hasattr(x, "co_firstlineno"):
  869. return x
  870. return obj
  871. if PY35: # RecursionError introduced in 3.5
  872. def is_recursion_error(excinfo):
  873. return excinfo.errisinstance(RecursionError) # noqa
  874. else:
  875. def is_recursion_error(excinfo):
  876. if not excinfo.errisinstance(RuntimeError):
  877. return False
  878. try:
  879. return "maximum recursion depth exceeded" in str(excinfo.value)
  880. except UnicodeError:
  881. return False
  882. # relative paths that we use to filter traceback entries from appearing to the user;
  883. # see filter_traceback
  884. # note: if we need to add more paths than what we have now we should probably use a list
  885. # for better maintenance
  886. _PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip("oc"))
  887. # pluggy is either a package or a single module depending on the version
  888. if _PLUGGY_DIR.basename == "__init__.py":
  889. _PLUGGY_DIR = _PLUGGY_DIR.dirpath()
  890. _PYTEST_DIR = py.path.local(_pytest.__file__).dirpath()
  891. _PY_DIR = py.path.local(py.__file__).dirpath()
  892. def filter_traceback(entry):
  893. """Return True if a TracebackEntry instance should be removed from tracebacks:
  894. * dynamically generated code (no code to show up for it);
  895. * internal traceback from pytest or its internal libraries, py and pluggy.
  896. """
  897. # entry.path might sometimes return a str object when the entry
  898. # points to dynamically generated code
  899. # see https://bitbucket.org/pytest-dev/py/issues/71
  900. raw_filename = entry.frame.code.raw.co_filename
  901. is_generated = "<" in raw_filename and ">" in raw_filename
  902. if is_generated:
  903. return False
  904. # entry.path might point to a non-existing file, in which case it will
  905. # also return a str object. see #1133
  906. p = py.path.local(entry.path)
  907. return (
  908. not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)
  909. )