code.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  1. # mypy: allow-untyped-defs
  2. from __future__ import annotations
  3. import ast
  4. from collections.abc import Callable
  5. from collections.abc import Iterable
  6. from collections.abc import Mapping
  7. from collections.abc import Sequence
  8. import dataclasses
  9. import inspect
  10. from inspect import CO_VARARGS
  11. from inspect import CO_VARKEYWORDS
  12. from io import StringIO
  13. import os
  14. from pathlib import Path
  15. import re
  16. import sys
  17. from traceback import extract_tb
  18. from traceback import format_exception
  19. from traceback import format_exception_only
  20. from traceback import FrameSummary
  21. from types import CodeType
  22. from types import FrameType
  23. from types import TracebackType
  24. from typing import Any
  25. from typing import ClassVar
  26. from typing import Final
  27. from typing import final
  28. from typing import Generic
  29. from typing import Literal
  30. from typing import overload
  31. from typing import SupportsIndex
  32. from typing import TYPE_CHECKING
  33. from typing import TypeVar
  34. from typing import Union
  35. import pluggy
  36. import _pytest
  37. from _pytest._code.source import findsource
  38. from _pytest._code.source import getrawcode
  39. from _pytest._code.source import getstatementrange_ast
  40. from _pytest._code.source import Source
  41. from _pytest._io import TerminalWriter
  42. from _pytest._io.saferepr import safeformat
  43. from _pytest._io.saferepr import saferepr
  44. from _pytest.compat import get_real_func
  45. from _pytest.deprecated import check_ispytest
  46. from _pytest.pathlib import absolutepath
  47. from _pytest.pathlib import bestrelpath
  48. if sys.version_info < (3, 11):
  49. from exceptiongroup import BaseExceptionGroup
  50. TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]
  51. EXCEPTION_OR_MORE = Union[type[BaseException], tuple[type[BaseException], ...]]
  52. class Code:
  53. """Wrapper around Python code objects."""
  54. __slots__ = ("raw",)
  55. def __init__(self, obj: CodeType) -> None:
  56. self.raw = obj
  57. @classmethod
  58. def from_function(cls, obj: object) -> Code:
  59. return cls(getrawcode(obj))
  60. def __eq__(self, other):
  61. return self.raw == other.raw
  62. # Ignore type because of https://github.com/python/mypy/issues/4266.
  63. __hash__ = None # type: ignore
  64. @property
  65. def firstlineno(self) -> int:
  66. return self.raw.co_firstlineno - 1
  67. @property
  68. def name(self) -> str:
  69. return self.raw.co_name
  70. @property
  71. def path(self) -> Path | str:
  72. """Return a path object pointing to source code, or an ``str`` in
  73. case of ``OSError`` / non-existing file."""
  74. if not self.raw.co_filename:
  75. return ""
  76. try:
  77. p = absolutepath(self.raw.co_filename)
  78. # maybe don't try this checking
  79. if not p.exists():
  80. raise OSError("path check failed.")
  81. return p
  82. except OSError:
  83. # XXX maybe try harder like the weird logic
  84. # in the standard lib [linecache.updatecache] does?
  85. return self.raw.co_filename
  86. @property
  87. def fullsource(self) -> Source | None:
  88. """Return a _pytest._code.Source object for the full source file of the code."""
  89. full, _ = findsource(self.raw)
  90. return full
  91. def source(self) -> Source:
  92. """Return a _pytest._code.Source object for the code object's source only."""
  93. # return source only for that part of code
  94. return Source(self.raw)
  95. def getargs(self, var: bool = False) -> tuple[str, ...]:
  96. """Return a tuple with the argument names for the code object.
  97. If 'var' is set True also return the names of the variable and
  98. keyword arguments when present.
  99. """
  100. # Handy shortcut for getting args.
  101. raw = self.raw
  102. argcount = raw.co_argcount
  103. if var:
  104. argcount += raw.co_flags & CO_VARARGS
  105. argcount += raw.co_flags & CO_VARKEYWORDS
  106. return raw.co_varnames[:argcount]
  107. class Frame:
  108. """Wrapper around a Python frame holding f_locals and f_globals
  109. in which expressions can be evaluated."""
  110. __slots__ = ("raw",)
  111. def __init__(self, frame: FrameType) -> None:
  112. self.raw = frame
  113. @property
  114. def lineno(self) -> int:
  115. return self.raw.f_lineno - 1
  116. @property
  117. def f_globals(self) -> dict[str, Any]:
  118. return self.raw.f_globals
  119. @property
  120. def f_locals(self) -> dict[str, Any]:
  121. return self.raw.f_locals
  122. @property
  123. def code(self) -> Code:
  124. return Code(self.raw.f_code)
  125. @property
  126. def statement(self) -> Source:
  127. """Statement this frame is at."""
  128. if self.code.fullsource is None:
  129. return Source("")
  130. return self.code.fullsource.getstatement(self.lineno)
  131. def eval(self, code, **vars):
  132. """Evaluate 'code' in the frame.
  133. 'vars' are optional additional local variables.
  134. Returns the result of the evaluation.
  135. """
  136. f_locals = self.f_locals.copy()
  137. f_locals.update(vars)
  138. return eval(code, self.f_globals, f_locals)
  139. def repr(self, object: object) -> str:
  140. """Return a 'safe' (non-recursive, one-line) string repr for 'object'."""
  141. return saferepr(object)
  142. def getargs(self, var: bool = False):
  143. """Return a list of tuples (name, value) for all arguments.
  144. If 'var' is set True, also include the variable and keyword arguments
  145. when present.
  146. """
  147. retval = []
  148. for arg in self.code.getargs(var):
  149. try:
  150. retval.append((arg, self.f_locals[arg]))
  151. except KeyError:
  152. pass # this can occur when using Psyco
  153. return retval
  154. class TracebackEntry:
  155. """A single entry in a Traceback."""
  156. __slots__ = ("_rawentry", "_repr_style")
  157. def __init__(
  158. self,
  159. rawentry: TracebackType,
  160. repr_style: Literal["short", "long"] | None = None,
  161. ) -> None:
  162. self._rawentry: Final = rawentry
  163. self._repr_style: Final = repr_style
  164. def with_repr_style(
  165. self, repr_style: Literal["short", "long"] | None
  166. ) -> TracebackEntry:
  167. return TracebackEntry(self._rawentry, repr_style)
  168. @property
  169. def lineno(self) -> int:
  170. return self._rawentry.tb_lineno - 1
  171. def get_python_framesummary(self) -> FrameSummary:
  172. # Python's built-in traceback module implements all the nitty gritty
  173. # details to get column numbers of out frames.
  174. stack_summary = extract_tb(self._rawentry, limit=1)
  175. return stack_summary[0]
  176. # Column and end line numbers introduced in python 3.11
  177. if sys.version_info < (3, 11):
  178. @property
  179. def end_lineno_relative(self) -> int | None:
  180. return None
  181. @property
  182. def colno(self) -> int | None:
  183. return None
  184. @property
  185. def end_colno(self) -> int | None:
  186. return None
  187. else:
  188. @property
  189. def end_lineno_relative(self) -> int | None:
  190. frame_summary = self.get_python_framesummary()
  191. if frame_summary.end_lineno is None: # pragma: no cover
  192. return None
  193. return frame_summary.end_lineno - 1 - self.frame.code.firstlineno
  194. @property
  195. def colno(self) -> int | None:
  196. """Starting byte offset of the expression in the traceback entry."""
  197. return self.get_python_framesummary().colno
  198. @property
  199. def end_colno(self) -> int | None:
  200. """Ending byte offset of the expression in the traceback entry."""
  201. return self.get_python_framesummary().end_colno
  202. @property
  203. def frame(self) -> Frame:
  204. return Frame(self._rawentry.tb_frame)
  205. @property
  206. def relline(self) -> int:
  207. return self.lineno - self.frame.code.firstlineno
  208. def __repr__(self) -> str:
  209. return f"<TracebackEntry {self.frame.code.path}:{self.lineno + 1}>"
  210. @property
  211. def statement(self) -> Source:
  212. """_pytest._code.Source object for the current statement."""
  213. source = self.frame.code.fullsource
  214. assert source is not None
  215. return source.getstatement(self.lineno)
  216. @property
  217. def path(self) -> Path | str:
  218. """Path to the source code."""
  219. return self.frame.code.path
  220. @property
  221. def locals(self) -> dict[str, Any]:
  222. """Locals of underlying frame."""
  223. return self.frame.f_locals
  224. def getfirstlinesource(self) -> int:
  225. return self.frame.code.firstlineno
  226. def getsource(
  227. self, astcache: dict[str | Path, ast.AST] | None = None
  228. ) -> Source | None:
  229. """Return failing source code."""
  230. # we use the passed in astcache to not reparse asttrees
  231. # within exception info printing
  232. source = self.frame.code.fullsource
  233. if source is None:
  234. return None
  235. key = astnode = None
  236. if astcache is not None:
  237. key = self.frame.code.path
  238. if key is not None:
  239. astnode = astcache.get(key, None)
  240. start = self.getfirstlinesource()
  241. try:
  242. astnode, _, end = getstatementrange_ast(
  243. self.lineno, source, astnode=astnode
  244. )
  245. except SyntaxError:
  246. end = self.lineno + 1
  247. else:
  248. if key is not None and astcache is not None:
  249. astcache[key] = astnode
  250. return source[start:end]
  251. source = property(getsource)
  252. def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool:
  253. """Return True if the current frame has a var __tracebackhide__
  254. resolving to True.
  255. If __tracebackhide__ is a callable, it gets called with the
  256. ExceptionInfo instance and can decide whether to hide the traceback.
  257. Mostly for internal use.
  258. """
  259. tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False
  260. for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):
  261. # in normal cases, f_locals and f_globals are dictionaries
  262. # however via `exec(...)` / `eval(...)` they can be other types
  263. # (even incorrect types!).
  264. # as such, we suppress all exceptions while accessing __tracebackhide__
  265. try:
  266. tbh = maybe_ns_dct["__tracebackhide__"]
  267. except Exception:
  268. pass
  269. else:
  270. break
  271. if tbh and callable(tbh):
  272. return tbh(excinfo)
  273. return tbh
  274. def __str__(self) -> str:
  275. name = self.frame.code.name
  276. try:
  277. line = str(self.statement).lstrip()
  278. except KeyboardInterrupt:
  279. raise
  280. except BaseException:
  281. line = "???"
  282. # This output does not quite match Python's repr for traceback entries,
  283. # but changing it to do so would break certain plugins. See
  284. # https://github.com/pytest-dev/pytest/pull/7535/ for details.
  285. return f" File '{self.path}':{self.lineno + 1} in {name}\n {line}\n"
  286. @property
  287. def name(self) -> str:
  288. """co_name of underlying code."""
  289. return self.frame.code.raw.co_name
  290. class Traceback(list[TracebackEntry]):
  291. """Traceback objects encapsulate and offer higher level access to Traceback entries."""
  292. def __init__(
  293. self,
  294. tb: TracebackType | Iterable[TracebackEntry],
  295. ) -> None:
  296. """Initialize from given python traceback object and ExceptionInfo."""
  297. if isinstance(tb, TracebackType):
  298. def f(cur: TracebackType) -> Iterable[TracebackEntry]:
  299. cur_: TracebackType | None = cur
  300. while cur_ is not None:
  301. yield TracebackEntry(cur_)
  302. cur_ = cur_.tb_next
  303. super().__init__(f(tb))
  304. else:
  305. super().__init__(tb)
  306. def cut(
  307. self,
  308. path: os.PathLike[str] | str | None = None,
  309. lineno: int | None = None,
  310. firstlineno: int | None = None,
  311. excludepath: os.PathLike[str] | None = None,
  312. ) -> Traceback:
  313. """Return a Traceback instance wrapping part of this Traceback.
  314. By providing any combination of path, lineno and firstlineno, the
  315. first frame to start the to-be-returned traceback is determined.
  316. This allows cutting the first part of a Traceback instance e.g.
  317. for formatting reasons (removing some uninteresting bits that deal
  318. with handling of the exception/traceback).
  319. """
  320. path_ = None if path is None else os.fspath(path)
  321. excludepath_ = None if excludepath is None else os.fspath(excludepath)
  322. for x in self:
  323. code = x.frame.code
  324. codepath = code.path
  325. if path is not None and str(codepath) != path_:
  326. continue
  327. if (
  328. excludepath is not None
  329. and isinstance(codepath, Path)
  330. and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator]
  331. ):
  332. continue
  333. if lineno is not None and x.lineno != lineno:
  334. continue
  335. if firstlineno is not None and x.frame.code.firstlineno != firstlineno:
  336. continue
  337. return Traceback(x._rawentry)
  338. return self
  339. @overload
  340. def __getitem__(self, key: SupportsIndex) -> TracebackEntry: ...
  341. @overload
  342. def __getitem__(self, key: slice) -> Traceback: ...
  343. def __getitem__(self, key: SupportsIndex | slice) -> TracebackEntry | Traceback:
  344. if isinstance(key, slice):
  345. return self.__class__(super().__getitem__(key))
  346. else:
  347. return super().__getitem__(key)
  348. def filter(
  349. self,
  350. excinfo_or_fn: ExceptionInfo[BaseException] | Callable[[TracebackEntry], bool],
  351. /,
  352. ) -> Traceback:
  353. """Return a Traceback instance with certain items removed.
  354. If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s
  355. which are hidden (see ishidden() above).
  356. Otherwise, the filter is a function that gets a single argument, a
  357. ``TracebackEntry`` instance, and should return True when the item should
  358. be added to the ``Traceback``, False when not.
  359. """
  360. if isinstance(excinfo_or_fn, ExceptionInfo):
  361. fn = lambda x: not x.ishidden(excinfo_or_fn) # noqa: E731
  362. else:
  363. fn = excinfo_or_fn
  364. return Traceback(filter(fn, self))
  365. def recursionindex(self) -> int | None:
  366. """Return the index of the frame/TracebackEntry where recursion originates if
  367. appropriate, None if no recursion occurred."""
  368. cache: dict[tuple[Any, int, int], list[dict[str, Any]]] = {}
  369. for i, entry in enumerate(self):
  370. # id for the code.raw is needed to work around
  371. # the strange metaprogramming in the decorator lib from pypi
  372. # which generates code objects that have hash/value equality
  373. # XXX needs a test
  374. key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
  375. values = cache.setdefault(key, [])
  376. # Since Python 3.13 f_locals is a proxy, freeze it.
  377. loc = dict(entry.frame.f_locals)
  378. if values:
  379. for otherloc in values:
  380. if otherloc == loc:
  381. return i
  382. values.append(loc)
  383. return None
  384. def stringify_exception(
  385. exc: BaseException, include_subexception_msg: bool = True
  386. ) -> str:
  387. try:
  388. notes = getattr(exc, "__notes__", [])
  389. except KeyError:
  390. # Workaround for https://github.com/python/cpython/issues/98778 on
  391. # Python <= 3.9, and some 3.10 and 3.11 patch versions.
  392. HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ())
  393. if sys.version_info < (3, 12) and isinstance(exc, HTTPError):
  394. notes = []
  395. else: # pragma: no cover
  396. # exception not related to above bug, reraise
  397. raise
  398. if not include_subexception_msg and isinstance(exc, BaseExceptionGroup):
  399. message = exc.message
  400. else:
  401. message = str(exc)
  402. return "\n".join(
  403. [
  404. message,
  405. *notes,
  406. ]
  407. )
  408. E = TypeVar("E", bound=BaseException, covariant=True)
  409. @final
  410. @dataclasses.dataclass
  411. class ExceptionInfo(Generic[E]):
  412. """Wraps sys.exc_info() objects and offers help for navigating the traceback."""
  413. _assert_start_repr: ClassVar = "AssertionError('assert "
  414. _excinfo: tuple[type[E], E, TracebackType] | None
  415. _striptext: str
  416. _traceback: Traceback | None
  417. def __init__(
  418. self,
  419. excinfo: tuple[type[E], E, TracebackType] | None,
  420. striptext: str = "",
  421. traceback: Traceback | None = None,
  422. *,
  423. _ispytest: bool = False,
  424. ) -> None:
  425. check_ispytest(_ispytest)
  426. self._excinfo = excinfo
  427. self._striptext = striptext
  428. self._traceback = traceback
  429. @classmethod
  430. def from_exception(
  431. cls,
  432. # Ignoring error: "Cannot use a covariant type variable as a parameter".
  433. # This is OK to ignore because this class is (conceptually) readonly.
  434. # See https://github.com/python/mypy/issues/7049.
  435. exception: E, # type: ignore[misc]
  436. exprinfo: str | None = None,
  437. ) -> ExceptionInfo[E]:
  438. """Return an ExceptionInfo for an existing exception.
  439. The exception must have a non-``None`` ``__traceback__`` attribute,
  440. otherwise this function fails with an assertion error. This means that
  441. the exception must have been raised, or added a traceback with the
  442. :py:meth:`~BaseException.with_traceback()` method.
  443. :param exprinfo:
  444. A text string helping to determine if we should strip
  445. ``AssertionError`` from the output. Defaults to the exception
  446. message/``__str__()``.
  447. .. versionadded:: 7.4
  448. """
  449. assert exception.__traceback__, (
  450. "Exceptions passed to ExcInfo.from_exception(...)"
  451. " must have a non-None __traceback__."
  452. )
  453. exc_info = (type(exception), exception, exception.__traceback__)
  454. return cls.from_exc_info(exc_info, exprinfo)
  455. @classmethod
  456. def from_exc_info(
  457. cls,
  458. exc_info: tuple[type[E], E, TracebackType],
  459. exprinfo: str | None = None,
  460. ) -> ExceptionInfo[E]:
  461. """Like :func:`from_exception`, but using old-style exc_info tuple."""
  462. _striptext = ""
  463. if exprinfo is None and isinstance(exc_info[1], AssertionError):
  464. exprinfo = getattr(exc_info[1], "msg", None)
  465. if exprinfo is None:
  466. exprinfo = saferepr(exc_info[1])
  467. if exprinfo and exprinfo.startswith(cls._assert_start_repr):
  468. _striptext = "AssertionError: "
  469. return cls(exc_info, _striptext, _ispytest=True)
  470. @classmethod
  471. def from_current(cls, exprinfo: str | None = None) -> ExceptionInfo[BaseException]:
  472. """Return an ExceptionInfo matching the current traceback.
  473. .. warning::
  474. Experimental API
  475. :param exprinfo:
  476. A text string helping to determine if we should strip
  477. ``AssertionError`` from the output. Defaults to the exception
  478. message/``__str__()``.
  479. """
  480. tup = sys.exc_info()
  481. assert tup[0] is not None, "no current exception"
  482. assert tup[1] is not None, "no current exception"
  483. assert tup[2] is not None, "no current exception"
  484. exc_info = (tup[0], tup[1], tup[2])
  485. return ExceptionInfo.from_exc_info(exc_info, exprinfo)
  486. @classmethod
  487. def for_later(cls) -> ExceptionInfo[E]:
  488. """Return an unfilled ExceptionInfo."""
  489. return cls(None, _ispytest=True)
  490. def fill_unfilled(self, exc_info: tuple[type[E], E, TracebackType]) -> None:
  491. """Fill an unfilled ExceptionInfo created with ``for_later()``."""
  492. assert self._excinfo is None, "ExceptionInfo was already filled"
  493. self._excinfo = exc_info
  494. @property
  495. def type(self) -> type[E]:
  496. """The exception class."""
  497. assert self._excinfo is not None, (
  498. ".type can only be used after the context manager exits"
  499. )
  500. return self._excinfo[0]
  501. @property
  502. def value(self) -> E:
  503. """The exception value."""
  504. assert self._excinfo is not None, (
  505. ".value can only be used after the context manager exits"
  506. )
  507. return self._excinfo[1]
  508. @property
  509. def tb(self) -> TracebackType:
  510. """The exception raw traceback."""
  511. assert self._excinfo is not None, (
  512. ".tb can only be used after the context manager exits"
  513. )
  514. return self._excinfo[2]
  515. @property
  516. def typename(self) -> str:
  517. """The type name of the exception."""
  518. assert self._excinfo is not None, (
  519. ".typename can only be used after the context manager exits"
  520. )
  521. return self.type.__name__
  522. @property
  523. def traceback(self) -> Traceback:
  524. """The traceback."""
  525. if self._traceback is None:
  526. self._traceback = Traceback(self.tb)
  527. return self._traceback
  528. @traceback.setter
  529. def traceback(self, value: Traceback) -> None:
  530. self._traceback = value
  531. def __repr__(self) -> str:
  532. if self._excinfo is None:
  533. return "<ExceptionInfo for raises contextmanager>"
  534. return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"
  535. def exconly(self, tryshort: bool = False) -> str:
  536. """Return the exception as a string.
  537. When 'tryshort' resolves to True, and the exception is an
  538. AssertionError, only the actual exception part of the exception
  539. representation is returned (so 'AssertionError: ' is removed from
  540. the beginning).
  541. """
  542. def _get_single_subexc(
  543. eg: BaseExceptionGroup[BaseException],
  544. ) -> BaseException | None:
  545. if len(eg.exceptions) != 1:
  546. return None
  547. if isinstance(e := eg.exceptions[0], BaseExceptionGroup):
  548. return _get_single_subexc(e)
  549. return e
  550. if (
  551. tryshort
  552. and isinstance(self.value, BaseExceptionGroup)
  553. and (subexc := _get_single_subexc(self.value)) is not None
  554. ):
  555. return f"{subexc!r} [single exception in {type(self.value).__name__}]"
  556. lines = format_exception_only(self.type, self.value)
  557. text = "".join(lines)
  558. text = text.rstrip()
  559. if tryshort:
  560. if text.startswith(self._striptext):
  561. text = text[len(self._striptext) :]
  562. return text
  563. def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool:
  564. """Return True if the exception is an instance of exc.
  565. Consider using ``isinstance(excinfo.value, exc)`` instead.
  566. """
  567. return isinstance(self.value, exc)
  568. def _getreprcrash(self) -> ReprFileLocation | None:
  569. # Find last non-hidden traceback entry that led to the exception of the
  570. # traceback, or None if all hidden.
  571. for i in range(-1, -len(self.traceback) - 1, -1):
  572. entry = self.traceback[i]
  573. if not entry.ishidden(self):
  574. path, lineno = entry.frame.code.raw.co_filename, entry.lineno
  575. exconly = self.exconly(tryshort=True)
  576. return ReprFileLocation(path, lineno + 1, exconly)
  577. return None
  578. def getrepr(
  579. self,
  580. showlocals: bool = False,
  581. style: TracebackStyle = "long",
  582. abspath: bool = False,
  583. tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] = True,
  584. funcargs: bool = False,
  585. truncate_locals: bool = True,
  586. truncate_args: bool = True,
  587. chain: bool = True,
  588. ) -> ReprExceptionInfo | ExceptionChainRepr:
  589. """Return str()able representation of this exception info.
  590. :param bool showlocals:
  591. Show locals per traceback entry.
  592. Ignored if ``style=="native"``.
  593. :param str style:
  594. long|short|line|no|native|value traceback style.
  595. :param bool abspath:
  596. If paths should be changed to absolute or left unchanged.
  597. :param tbfilter:
  598. A filter for traceback entries.
  599. * If false, don't hide any entries.
  600. * If true, hide internal entries and entries that contain a local
  601. variable ``__tracebackhide__ = True``.
  602. * If a callable, delegates the filtering to the callable.
  603. Ignored if ``style`` is ``"native"``.
  604. :param bool funcargs:
  605. Show fixtures ("funcargs" for legacy purposes) per traceback entry.
  606. :param bool truncate_locals:
  607. With ``showlocals==True``, make sure locals can be safely represented as strings.
  608. :param bool truncate_args:
  609. With ``showargs==True``, make sure args can be safely represented as strings.
  610. :param bool chain:
  611. If chained exceptions in Python 3 should be shown.
  612. .. versionchanged:: 3.9
  613. Added the ``chain`` parameter.
  614. """
  615. if style == "native":
  616. return ReprExceptionInfo(
  617. reprtraceback=ReprTracebackNative(
  618. format_exception(
  619. self.type,
  620. self.value,
  621. self.traceback[0]._rawentry if self.traceback else None,
  622. )
  623. ),
  624. reprcrash=self._getreprcrash(),
  625. )
  626. fmt = FormattedExcinfo(
  627. showlocals=showlocals,
  628. style=style,
  629. abspath=abspath,
  630. tbfilter=tbfilter,
  631. funcargs=funcargs,
  632. truncate_locals=truncate_locals,
  633. truncate_args=truncate_args,
  634. chain=chain,
  635. )
  636. return fmt.repr_excinfo(self)
  637. def match(self, regexp: str | re.Pattern[str]) -> Literal[True]:
  638. """Check whether the regular expression `regexp` matches the string
  639. representation of the exception using :func:`python:re.search`.
  640. If it matches `True` is returned, otherwise an `AssertionError` is raised.
  641. """
  642. __tracebackhide__ = True
  643. value = stringify_exception(self.value)
  644. msg = f"Regex pattern did not match.\n Regex: {regexp!r}\n Input: {value!r}"
  645. if regexp == value:
  646. msg += "\n Did you mean to `re.escape()` the regex?"
  647. assert re.search(regexp, value), msg
  648. # Return True to allow for "assert excinfo.match()".
  649. return True
  650. def _group_contains(
  651. self,
  652. exc_group: BaseExceptionGroup[BaseException],
  653. expected_exception: EXCEPTION_OR_MORE,
  654. match: str | re.Pattern[str] | None,
  655. target_depth: int | None = None,
  656. current_depth: int = 1,
  657. ) -> bool:
  658. """Return `True` if a `BaseExceptionGroup` contains a matching exception."""
  659. if (target_depth is not None) and (current_depth > target_depth):
  660. # already descended past the target depth
  661. return False
  662. for exc in exc_group.exceptions:
  663. if isinstance(exc, BaseExceptionGroup):
  664. if self._group_contains(
  665. exc, expected_exception, match, target_depth, current_depth + 1
  666. ):
  667. return True
  668. if (target_depth is not None) and (current_depth != target_depth):
  669. # not at the target depth, no match
  670. continue
  671. if not isinstance(exc, expected_exception):
  672. continue
  673. if match is not None:
  674. value = stringify_exception(exc)
  675. if not re.search(match, value):
  676. continue
  677. return True
  678. return False
  679. def group_contains(
  680. self,
  681. expected_exception: EXCEPTION_OR_MORE,
  682. *,
  683. match: str | re.Pattern[str] | None = None,
  684. depth: int | None = None,
  685. ) -> bool:
  686. """Check whether a captured exception group contains a matching exception.
  687. :param Type[BaseException] | Tuple[Type[BaseException]] expected_exception:
  688. The expected exception type, or a tuple if one of multiple possible
  689. exception types are expected.
  690. :param str | re.Pattern[str] | None match:
  691. If specified, a string containing a regular expression,
  692. or a regular expression object, that is tested against the string
  693. representation of the exception and its `PEP-678 <https://peps.python.org/pep-0678/>` `__notes__`
  694. using :func:`re.search`.
  695. To match a literal string that may contain :ref:`special characters
  696. <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
  697. :param Optional[int] depth:
  698. If `None`, will search for a matching exception at any nesting depth.
  699. If >= 1, will only match an exception if it's at the specified depth (depth = 1 being
  700. the exceptions contained within the topmost exception group).
  701. .. versionadded:: 8.0
  702. .. warning::
  703. This helper makes it easy to check for the presence of specific exceptions,
  704. but it is very bad for checking that the group does *not* contain
  705. *any other exceptions*.
  706. You should instead consider using :class:`pytest.RaisesGroup`
  707. """
  708. msg = "Captured exception is not an instance of `BaseExceptionGroup`"
  709. assert isinstance(self.value, BaseExceptionGroup), msg
  710. msg = "`depth` must be >= 1 if specified"
  711. assert (depth is None) or (depth >= 1), msg
  712. return self._group_contains(self.value, expected_exception, match, depth)
  713. if TYPE_CHECKING:
  714. from typing_extensions import TypeAlias
  715. # Type alias for the `tbfilter` setting:
  716. # bool: If True, it should be filtered using Traceback.filter()
  717. # callable: A callable that takes an ExceptionInfo and returns the filtered traceback.
  718. TracebackFilter: TypeAlias = Union[
  719. bool, Callable[[ExceptionInfo[BaseException]], Traceback]
  720. ]
  721. @dataclasses.dataclass
  722. class FormattedExcinfo:
  723. """Presenting information about failing Functions and Generators."""
  724. # for traceback entries
  725. flow_marker: ClassVar = ">"
  726. fail_marker: ClassVar = "E"
  727. showlocals: bool = False
  728. style: TracebackStyle = "long"
  729. abspath: bool = True
  730. tbfilter: TracebackFilter = True
  731. funcargs: bool = False
  732. truncate_locals: bool = True
  733. truncate_args: bool = True
  734. chain: bool = True
  735. astcache: dict[str | Path, ast.AST] = dataclasses.field(
  736. default_factory=dict, init=False, repr=False
  737. )
  738. def _getindent(self, source: Source) -> int:
  739. # Figure out indent for the given source.
  740. try:
  741. s = str(source.getstatement(len(source) - 1))
  742. except KeyboardInterrupt:
  743. raise
  744. except BaseException:
  745. try:
  746. s = str(source[-1])
  747. except KeyboardInterrupt:
  748. raise
  749. except BaseException:
  750. return 0
  751. return 4 + (len(s) - len(s.lstrip()))
  752. def _getentrysource(self, entry: TracebackEntry) -> Source | None:
  753. source = entry.getsource(self.astcache)
  754. if source is not None:
  755. source = source.deindent()
  756. return source
  757. def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None:
  758. if self.funcargs:
  759. args = []
  760. for argname, argvalue in entry.frame.getargs(var=True):
  761. if self.truncate_args:
  762. str_repr = saferepr(argvalue)
  763. else:
  764. str_repr = saferepr(argvalue, maxsize=None)
  765. args.append((argname, str_repr))
  766. return ReprFuncArgs(args)
  767. return None
  768. def get_source(
  769. self,
  770. source: Source | None,
  771. line_index: int = -1,
  772. excinfo: ExceptionInfo[BaseException] | None = None,
  773. short: bool = False,
  774. end_line_index: int | None = None,
  775. colno: int | None = None,
  776. end_colno: int | None = None,
  777. ) -> list[str]:
  778. """Return formatted and marked up source lines."""
  779. lines = []
  780. if source is not None and line_index < 0:
  781. line_index += len(source)
  782. if source is None or line_index >= len(source.lines) or line_index < 0:
  783. # `line_index` could still be outside `range(len(source.lines))` if
  784. # we're processing AST with pathological position attributes.
  785. source = Source("???")
  786. line_index = 0
  787. space_prefix = " "
  788. if short:
  789. lines.append(space_prefix + source.lines[line_index].strip())
  790. lines.extend(
  791. self.get_highlight_arrows_for_line(
  792. raw_line=source.raw_lines[line_index],
  793. line=source.lines[line_index].strip(),
  794. lineno=line_index,
  795. end_lineno=end_line_index,
  796. colno=colno,
  797. end_colno=end_colno,
  798. )
  799. )
  800. else:
  801. for line in source.lines[:line_index]:
  802. lines.append(space_prefix + line)
  803. lines.append(self.flow_marker + " " + source.lines[line_index])
  804. lines.extend(
  805. self.get_highlight_arrows_for_line(
  806. raw_line=source.raw_lines[line_index],
  807. line=source.lines[line_index],
  808. lineno=line_index,
  809. end_lineno=end_line_index,
  810. colno=colno,
  811. end_colno=end_colno,
  812. )
  813. )
  814. for line in source.lines[line_index + 1 :]:
  815. lines.append(space_prefix + line)
  816. if excinfo is not None:
  817. indent = 4 if short else self._getindent(source)
  818. lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
  819. return lines
  820. def get_highlight_arrows_for_line(
  821. self,
  822. line: str,
  823. raw_line: str,
  824. lineno: int | None,
  825. end_lineno: int | None,
  826. colno: int | None,
  827. end_colno: int | None,
  828. ) -> list[str]:
  829. """Return characters highlighting a source line.
  830. Example with colno and end_colno pointing to the bar expression:
  831. "foo() + bar()"
  832. returns " ^^^^^"
  833. """
  834. if lineno != end_lineno:
  835. # Don't handle expressions that span multiple lines.
  836. return []
  837. if colno is None or end_colno is None:
  838. # Can't do anything without column information.
  839. return []
  840. num_stripped_chars = len(raw_line) - len(line)
  841. start_char_offset = _byte_offset_to_character_offset(raw_line, colno)
  842. end_char_offset = _byte_offset_to_character_offset(raw_line, end_colno)
  843. num_carets = end_char_offset - start_char_offset
  844. # If the highlight would span the whole line, it is redundant, don't
  845. # show it.
  846. if num_carets >= len(line.strip()):
  847. return []
  848. highlights = " "
  849. highlights += " " * (start_char_offset - num_stripped_chars + 1)
  850. highlights += "^" * num_carets
  851. return [highlights]
  852. def get_exconly(
  853. self,
  854. excinfo: ExceptionInfo[BaseException],
  855. indent: int = 4,
  856. markall: bool = False,
  857. ) -> list[str]:
  858. lines = []
  859. indentstr = " " * indent
  860. # Get the real exception information out.
  861. exlines = excinfo.exconly(tryshort=True).split("\n")
  862. failindent = self.fail_marker + indentstr[1:]
  863. for line in exlines:
  864. lines.append(failindent + line)
  865. if not markall:
  866. failindent = indentstr
  867. return lines
  868. def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None:
  869. if self.showlocals:
  870. lines = []
  871. keys = [loc for loc in locals if loc[0] != "@"]
  872. keys.sort()
  873. for name in keys:
  874. value = locals[name]
  875. if name == "__builtins__":
  876. lines.append("__builtins__ = <builtins>")
  877. else:
  878. # This formatting could all be handled by the
  879. # _repr() function, which is only reprlib.Repr in
  880. # disguise, so is very configurable.
  881. if self.truncate_locals:
  882. str_repr = saferepr(value)
  883. else:
  884. str_repr = safeformat(value)
  885. # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
  886. lines.append(f"{name:<10} = {str_repr}")
  887. # else:
  888. # self._line("%-10s =\\" % (name,))
  889. # # XXX
  890. # pprint.pprint(value, stream=self.excinfowriter)
  891. return ReprLocals(lines)
  892. return None
  893. def repr_traceback_entry(
  894. self,
  895. entry: TracebackEntry | None,
  896. excinfo: ExceptionInfo[BaseException] | None = None,
  897. ) -> ReprEntry:
  898. lines: list[str] = []
  899. style = (
  900. entry._repr_style
  901. if entry is not None and entry._repr_style is not None
  902. else self.style
  903. )
  904. if style in ("short", "long") and entry is not None:
  905. source = self._getentrysource(entry)
  906. if source is None:
  907. source = Source("???")
  908. line_index = 0
  909. end_line_index, colno, end_colno = None, None, None
  910. else:
  911. line_index = entry.relline
  912. end_line_index = entry.end_lineno_relative
  913. colno = entry.colno
  914. end_colno = entry.end_colno
  915. short = style == "short"
  916. reprargs = self.repr_args(entry) if not short else None
  917. s = self.get_source(
  918. source=source,
  919. line_index=line_index,
  920. excinfo=excinfo,
  921. short=short,
  922. end_line_index=end_line_index,
  923. colno=colno,
  924. end_colno=end_colno,
  925. )
  926. lines.extend(s)
  927. if short:
  928. message = f"in {entry.name}"
  929. else:
  930. message = (excinfo and excinfo.typename) or ""
  931. entry_path = entry.path
  932. path = self._makepath(entry_path)
  933. reprfileloc = ReprFileLocation(path, entry.lineno + 1, message)
  934. localsrepr = self.repr_locals(entry.locals)
  935. return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style)
  936. elif style == "value":
  937. if excinfo:
  938. lines.extend(str(excinfo.value).split("\n"))
  939. return ReprEntry(lines, None, None, None, style)
  940. else:
  941. if excinfo:
  942. lines.extend(self.get_exconly(excinfo, indent=4))
  943. return ReprEntry(lines, None, None, None, style)
  944. def _makepath(self, path: Path | str) -> str:
  945. if not self.abspath and isinstance(path, Path):
  946. try:
  947. np = bestrelpath(Path.cwd(), path)
  948. except OSError:
  949. return str(path)
  950. if len(np) < len(str(path)):
  951. return np
  952. return str(path)
  953. def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback:
  954. traceback = filter_excinfo_traceback(self.tbfilter, excinfo)
  955. if isinstance(excinfo.value, RecursionError):
  956. traceback, extraline = self._truncate_recursive_traceback(traceback)
  957. else:
  958. extraline = None
  959. if not traceback:
  960. if extraline is None:
  961. extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames."
  962. entries = [self.repr_traceback_entry(None, excinfo)]
  963. return ReprTraceback(entries, extraline, style=self.style)
  964. last = traceback[-1]
  965. if self.style == "value":
  966. entries = [self.repr_traceback_entry(last, excinfo)]
  967. return ReprTraceback(entries, None, style=self.style)
  968. entries = [
  969. self.repr_traceback_entry(entry, excinfo if last == entry else None)
  970. for entry in traceback
  971. ]
  972. return ReprTraceback(entries, extraline, style=self.style)
  973. def _truncate_recursive_traceback(
  974. self, traceback: Traceback
  975. ) -> tuple[Traceback, str | None]:
  976. """Truncate the given recursive traceback trying to find the starting
  977. point of the recursion.
  978. The detection is done by going through each traceback entry and
  979. finding the point in which the locals of the frame are equal to the
  980. locals of a previous frame (see ``recursionindex()``).
  981. Handle the situation where the recursion process might raise an
  982. exception (for example comparing numpy arrays using equality raises a
  983. TypeError), in which case we do our best to warn the user of the
  984. error and show a limited traceback.
  985. """
  986. try:
  987. recursionindex = traceback.recursionindex()
  988. except Exception as e:
  989. max_frames = 10
  990. extraline: str | None = (
  991. "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
  992. " The following exception happened when comparing locals in the stack frame:\n"
  993. f" {type(e).__name__}: {e!s}\n"
  994. f" Displaying first and last {max_frames} stack frames out of {len(traceback)}."
  995. )
  996. # Type ignored because adding two instances of a List subtype
  997. # currently incorrectly has type List instead of the subtype.
  998. traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore
  999. else:
  1000. if recursionindex is not None:
  1001. extraline = "!!! Recursion detected (same locals & position)"
  1002. traceback = traceback[: recursionindex + 1]
  1003. else:
  1004. extraline = None
  1005. return traceback, extraline
  1006. def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr:
  1007. repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = []
  1008. e: BaseException | None = excinfo.value
  1009. excinfo_: ExceptionInfo[BaseException] | None = excinfo
  1010. descr = None
  1011. seen: set[int] = set()
  1012. while e is not None and id(e) not in seen:
  1013. seen.add(id(e))
  1014. if excinfo_:
  1015. # Fall back to native traceback as a temporary workaround until
  1016. # full support for exception groups added to ExceptionInfo.
  1017. # See https://github.com/pytest-dev/pytest/issues/9159
  1018. reprtraceback: ReprTraceback | ReprTracebackNative
  1019. if isinstance(e, BaseExceptionGroup):
  1020. # don't filter any sub-exceptions since they shouldn't have any internal frames
  1021. traceback = filter_excinfo_traceback(self.tbfilter, excinfo)
  1022. reprtraceback = ReprTracebackNative(
  1023. format_exception(
  1024. type(excinfo.value),
  1025. excinfo.value,
  1026. traceback[0]._rawentry,
  1027. )
  1028. )
  1029. else:
  1030. reprtraceback = self.repr_traceback(excinfo_)
  1031. reprcrash = excinfo_._getreprcrash()
  1032. else:
  1033. # Fallback to native repr if the exception doesn't have a traceback:
  1034. # ExceptionInfo objects require a full traceback to work.
  1035. reprtraceback = ReprTracebackNative(format_exception(type(e), e, None))
  1036. reprcrash = None
  1037. repr_chain += [(reprtraceback, reprcrash, descr)]
  1038. if e.__cause__ is not None and self.chain:
  1039. e = e.__cause__
  1040. excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None
  1041. descr = "The above exception was the direct cause of the following exception:"
  1042. elif (
  1043. e.__context__ is not None and not e.__suppress_context__ and self.chain
  1044. ):
  1045. e = e.__context__
  1046. excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None
  1047. descr = "During handling of the above exception, another exception occurred:"
  1048. else:
  1049. e = None
  1050. repr_chain.reverse()
  1051. return ExceptionChainRepr(repr_chain)
  1052. @dataclasses.dataclass(eq=False)
  1053. class TerminalRepr:
  1054. def __str__(self) -> str:
  1055. # FYI this is called from pytest-xdist's serialization of exception
  1056. # information.
  1057. io = StringIO()
  1058. tw = TerminalWriter(file=io)
  1059. self.toterminal(tw)
  1060. return io.getvalue().strip()
  1061. def __repr__(self) -> str:
  1062. return f"<{self.__class__} instance at {id(self):0x}>"
  1063. def toterminal(self, tw: TerminalWriter) -> None:
  1064. raise NotImplementedError()
  1065. # This class is abstract -- only subclasses are instantiated.
  1066. @dataclasses.dataclass(eq=False)
  1067. class ExceptionRepr(TerminalRepr):
  1068. # Provided by subclasses.
  1069. reprtraceback: ReprTraceback
  1070. reprcrash: ReprFileLocation | None
  1071. sections: list[tuple[str, str, str]] = dataclasses.field(
  1072. init=False, default_factory=list
  1073. )
  1074. def addsection(self, name: str, content: str, sep: str = "-") -> None:
  1075. self.sections.append((name, content, sep))
  1076. def toterminal(self, tw: TerminalWriter) -> None:
  1077. for name, content, sep in self.sections:
  1078. tw.sep(sep, name)
  1079. tw.line(content)
  1080. @dataclasses.dataclass(eq=False)
  1081. class ExceptionChainRepr(ExceptionRepr):
  1082. chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]]
  1083. def __init__(
  1084. self,
  1085. chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]],
  1086. ) -> None:
  1087. # reprcrash and reprtraceback of the outermost (the newest) exception
  1088. # in the chain.
  1089. super().__init__(
  1090. reprtraceback=chain[-1][0],
  1091. reprcrash=chain[-1][1],
  1092. )
  1093. self.chain = chain
  1094. def toterminal(self, tw: TerminalWriter) -> None:
  1095. for element in self.chain:
  1096. element[0].toterminal(tw)
  1097. if element[2] is not None:
  1098. tw.line("")
  1099. tw.line(element[2], yellow=True)
  1100. super().toterminal(tw)
  1101. @dataclasses.dataclass(eq=False)
  1102. class ReprExceptionInfo(ExceptionRepr):
  1103. reprtraceback: ReprTraceback
  1104. reprcrash: ReprFileLocation | None
  1105. def toterminal(self, tw: TerminalWriter) -> None:
  1106. self.reprtraceback.toterminal(tw)
  1107. super().toterminal(tw)
  1108. @dataclasses.dataclass(eq=False)
  1109. class ReprTraceback(TerminalRepr):
  1110. reprentries: Sequence[ReprEntry | ReprEntryNative]
  1111. extraline: str | None
  1112. style: TracebackStyle
  1113. entrysep: ClassVar = "_ "
  1114. def toterminal(self, tw: TerminalWriter) -> None:
  1115. # The entries might have different styles.
  1116. for i, entry in enumerate(self.reprentries):
  1117. if entry.style == "long":
  1118. tw.line("")
  1119. entry.toterminal(tw)
  1120. if i < len(self.reprentries) - 1:
  1121. next_entry = self.reprentries[i + 1]
  1122. if entry.style == "long" or (
  1123. entry.style == "short" and next_entry.style == "long"
  1124. ):
  1125. tw.sep(self.entrysep)
  1126. if self.extraline:
  1127. tw.line(self.extraline)
  1128. class ReprTracebackNative(ReprTraceback):
  1129. def __init__(self, tblines: Sequence[str]) -> None:
  1130. self.reprentries = [ReprEntryNative(tblines)]
  1131. self.extraline = None
  1132. self.style = "native"
  1133. @dataclasses.dataclass(eq=False)
  1134. class ReprEntryNative(TerminalRepr):
  1135. lines: Sequence[str]
  1136. style: ClassVar[TracebackStyle] = "native"
  1137. def toterminal(self, tw: TerminalWriter) -> None:
  1138. tw.write("".join(self.lines))
  1139. @dataclasses.dataclass(eq=False)
  1140. class ReprEntry(TerminalRepr):
  1141. lines: Sequence[str]
  1142. reprfuncargs: ReprFuncArgs | None
  1143. reprlocals: ReprLocals | None
  1144. reprfileloc: ReprFileLocation | None
  1145. style: TracebackStyle
  1146. def _write_entry_lines(self, tw: TerminalWriter) -> None:
  1147. """Write the source code portions of a list of traceback entries with syntax highlighting.
  1148. Usually entries are lines like these:
  1149. " x = 1"
  1150. "> assert x == 2"
  1151. "E assert 1 == 2"
  1152. This function takes care of rendering the "source" portions of it (the lines without
  1153. the "E" prefix) using syntax highlighting, taking care to not highlighting the ">"
  1154. character, as doing so might break line continuations.
  1155. """
  1156. if not self.lines:
  1157. return
  1158. if self.style == "value":
  1159. # Using tw.write instead of tw.line for testing purposes due to TWMock implementation;
  1160. # lines written with TWMock.line and TWMock._write_source cannot be distinguished
  1161. # from each other, whereas lines written with TWMock.write are marked with TWMock.WRITE
  1162. for line in self.lines:
  1163. tw.write(line)
  1164. tw.write("\n")
  1165. return
  1166. # separate indents and source lines that are not failures: we want to
  1167. # highlight the code but not the indentation, which may contain markers
  1168. # such as "> assert 0"
  1169. fail_marker = f"{FormattedExcinfo.fail_marker} "
  1170. indent_size = len(fail_marker)
  1171. indents: list[str] = []
  1172. source_lines: list[str] = []
  1173. failure_lines: list[str] = []
  1174. for index, line in enumerate(self.lines):
  1175. is_failure_line = line.startswith(fail_marker)
  1176. if is_failure_line:
  1177. # from this point on all lines are considered part of the failure
  1178. failure_lines.extend(self.lines[index:])
  1179. break
  1180. else:
  1181. indents.append(line[:indent_size])
  1182. source_lines.append(line[indent_size:])
  1183. tw._write_source(source_lines, indents)
  1184. # failure lines are always completely red and bold
  1185. for line in failure_lines:
  1186. tw.line(line, bold=True, red=True)
  1187. def toterminal(self, tw: TerminalWriter) -> None:
  1188. if self.style == "short":
  1189. if self.reprfileloc:
  1190. self.reprfileloc.toterminal(tw)
  1191. self._write_entry_lines(tw)
  1192. if self.reprlocals:
  1193. self.reprlocals.toterminal(tw, indent=" " * 8)
  1194. return
  1195. if self.reprfuncargs:
  1196. self.reprfuncargs.toterminal(tw)
  1197. self._write_entry_lines(tw)
  1198. if self.reprlocals:
  1199. tw.line("")
  1200. self.reprlocals.toterminal(tw)
  1201. if self.reprfileloc:
  1202. if self.lines:
  1203. tw.line("")
  1204. self.reprfileloc.toterminal(tw)
  1205. def __str__(self) -> str:
  1206. return "{}\n{}\n{}".format(
  1207. "\n".join(self.lines), self.reprlocals, self.reprfileloc
  1208. )
  1209. @dataclasses.dataclass(eq=False)
  1210. class ReprFileLocation(TerminalRepr):
  1211. path: str
  1212. lineno: int
  1213. message: str
  1214. def __post_init__(self) -> None:
  1215. self.path = str(self.path)
  1216. def toterminal(self, tw: TerminalWriter) -> None:
  1217. # Filename and lineno output for each entry, using an output format
  1218. # that most editors understand.
  1219. msg = self.message
  1220. i = msg.find("\n")
  1221. if i != -1:
  1222. msg = msg[:i]
  1223. tw.write(self.path, bold=True, red=True)
  1224. tw.line(f":{self.lineno}: {msg}")
  1225. @dataclasses.dataclass(eq=False)
  1226. class ReprLocals(TerminalRepr):
  1227. lines: Sequence[str]
  1228. def toterminal(self, tw: TerminalWriter, indent="") -> None:
  1229. for line in self.lines:
  1230. tw.line(indent + line)
  1231. @dataclasses.dataclass(eq=False)
  1232. class ReprFuncArgs(TerminalRepr):
  1233. args: Sequence[tuple[str, object]]
  1234. def toterminal(self, tw: TerminalWriter) -> None:
  1235. if self.args:
  1236. linesofar = ""
  1237. for name, value in self.args:
  1238. ns = f"{name} = {value}"
  1239. if len(ns) + len(linesofar) + 2 > tw.fullwidth:
  1240. if linesofar:
  1241. tw.line(linesofar)
  1242. linesofar = ns
  1243. else:
  1244. if linesofar:
  1245. linesofar += ", " + ns
  1246. else:
  1247. linesofar = ns
  1248. if linesofar:
  1249. tw.line(linesofar)
  1250. tw.line("")
  1251. def getfslineno(obj: object) -> tuple[str | Path, int]:
  1252. """Return source location (path, lineno) for the given object.
  1253. If the source cannot be determined return ("", -1).
  1254. The line number is 0-based.
  1255. """
  1256. # xxx let decorators etc specify a sane ordering
  1257. # NOTE: this used to be done in _pytest.compat.getfslineno, initially added
  1258. # in 6ec13a2b9. It ("place_as") appears to be something very custom.
  1259. obj = get_real_func(obj)
  1260. if hasattr(obj, "place_as"):
  1261. obj = obj.place_as
  1262. try:
  1263. code = Code.from_function(obj)
  1264. except TypeError:
  1265. try:
  1266. fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type]
  1267. except TypeError:
  1268. return "", -1
  1269. fspath = (fn and absolutepath(fn)) or ""
  1270. lineno = -1
  1271. if fspath:
  1272. try:
  1273. _, lineno = findsource(obj)
  1274. except OSError:
  1275. pass
  1276. return fspath, lineno
  1277. return code.path, code.firstlineno
  1278. def _byte_offset_to_character_offset(str, offset):
  1279. """Converts a byte based offset in a string to a code-point."""
  1280. as_utf8 = str.encode("utf-8")
  1281. return len(as_utf8[:offset].decode("utf-8", errors="replace"))
  1282. # Relative paths that we use to filter traceback entries from appearing to the user;
  1283. # see filter_traceback.
  1284. # note: if we need to add more paths than what we have now we should probably use a list
  1285. # for better maintenance.
  1286. _PLUGGY_DIR = Path(pluggy.__file__.rstrip("oc"))
  1287. # pluggy is either a package or a single module depending on the version
  1288. if _PLUGGY_DIR.name == "__init__.py":
  1289. _PLUGGY_DIR = _PLUGGY_DIR.parent
  1290. _PYTEST_DIR = Path(_pytest.__file__).parent
  1291. def filter_traceback(entry: TracebackEntry) -> bool:
  1292. """Return True if a TracebackEntry instance should be included in tracebacks.
  1293. We hide traceback entries of:
  1294. * dynamically generated code (no code to show up for it);
  1295. * internal traceback from pytest or its internal libraries, py and pluggy.
  1296. """
  1297. # entry.path might sometimes return a str object when the entry
  1298. # points to dynamically generated code.
  1299. # See https://bitbucket.org/pytest-dev/py/issues/71.
  1300. raw_filename = entry.frame.code.raw.co_filename
  1301. is_generated = "<" in raw_filename and ">" in raw_filename
  1302. if is_generated:
  1303. return False
  1304. # entry.path might point to a non-existing file, in which case it will
  1305. # also return a str object. See #1133.
  1306. p = Path(entry.path)
  1307. parents = p.parents
  1308. if _PLUGGY_DIR in parents:
  1309. return False
  1310. if _PYTEST_DIR in parents:
  1311. return False
  1312. return True
  1313. def filter_excinfo_traceback(
  1314. tbfilter: TracebackFilter, excinfo: ExceptionInfo[BaseException]
  1315. ) -> Traceback:
  1316. """Filter the exception traceback in ``excinfo`` according to ``tbfilter``."""
  1317. if callable(tbfilter):
  1318. return tbfilter(excinfo)
  1319. elif tbfilter:
  1320. return excinfo.traceback.filter(excinfo)
  1321. else:
  1322. return excinfo.traceback