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