code.py 46 KB

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