python.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  1. """Python test discovery, setup and run of test functions."""
  2. import dataclasses
  3. import enum
  4. import fnmatch
  5. import inspect
  6. import itertools
  7. import os
  8. import sys
  9. import types
  10. import warnings
  11. from collections import Counter
  12. from collections import defaultdict
  13. from functools import partial
  14. from pathlib import Path
  15. from typing import Any
  16. from typing import Callable
  17. from typing import Dict
  18. from typing import Generator
  19. from typing import Iterable
  20. from typing import Iterator
  21. from typing import List
  22. from typing import Mapping
  23. from typing import Optional
  24. from typing import Pattern
  25. from typing import Sequence
  26. from typing import Set
  27. from typing import Tuple
  28. from typing import TYPE_CHECKING
  29. from typing import Union
  30. import _pytest
  31. from _pytest import fixtures
  32. from _pytest import nodes
  33. from _pytest._code import filter_traceback
  34. from _pytest._code import getfslineno
  35. from _pytest._code.code import ExceptionInfo
  36. from _pytest._code.code import TerminalRepr
  37. from _pytest._code.code import Traceback
  38. from _pytest._io import TerminalWriter
  39. from _pytest._io.saferepr import saferepr
  40. from _pytest.compat import ascii_escaped
  41. from _pytest.compat import assert_never
  42. from _pytest.compat import final
  43. from _pytest.compat import get_default_arg_names
  44. from _pytest.compat import get_real_func
  45. from _pytest.compat import getimfunc
  46. from _pytest.compat import getlocation
  47. from _pytest.compat import is_async_function
  48. from _pytest.compat import is_generator
  49. from _pytest.compat import LEGACY_PATH
  50. from _pytest.compat import NOTSET
  51. from _pytest.compat import safe_getattr
  52. from _pytest.compat import safe_isclass
  53. from _pytest.compat import STRING_TYPES
  54. from _pytest.config import Config
  55. from _pytest.config import ExitCode
  56. from _pytest.config import hookimpl
  57. from _pytest.config.argparsing import Parser
  58. from _pytest.deprecated import check_ispytest
  59. from _pytest.deprecated import INSTANCE_COLLECTOR
  60. from _pytest.deprecated import NOSE_SUPPORT_METHOD
  61. from _pytest.fixtures import FuncFixtureInfo
  62. from _pytest.main import Session
  63. from _pytest.mark import MARK_GEN
  64. from _pytest.mark import ParameterSet
  65. from _pytest.mark.structures import get_unpacked_marks
  66. from _pytest.mark.structures import Mark
  67. from _pytest.mark.structures import MarkDecorator
  68. from _pytest.mark.structures import normalize_mark_list
  69. from _pytest.outcomes import fail
  70. from _pytest.outcomes import skip
  71. from _pytest.pathlib import bestrelpath
  72. from _pytest.pathlib import fnmatch_ex
  73. from _pytest.pathlib import import_path
  74. from _pytest.pathlib import ImportPathMismatchError
  75. from _pytest.pathlib import parts
  76. from _pytest.pathlib import visit
  77. from _pytest.scope import Scope
  78. from _pytest.warning_types import PytestCollectionWarning
  79. from _pytest.warning_types import PytestReturnNotNoneWarning
  80. from _pytest.warning_types import PytestUnhandledCoroutineWarning
  81. if TYPE_CHECKING:
  82. from typing_extensions import Literal
  83. from _pytest.scope import _ScopeName
  84. _PYTEST_DIR = Path(_pytest.__file__).parent
  85. def pytest_addoption(parser: Parser) -> None:
  86. group = parser.getgroup("general")
  87. group.addoption(
  88. "--fixtures",
  89. "--funcargs",
  90. action="store_true",
  91. dest="showfixtures",
  92. default=False,
  93. help="Show available fixtures, sorted by plugin appearance "
  94. "(fixtures with leading '_' are only shown with '-v')",
  95. )
  96. group.addoption(
  97. "--fixtures-per-test",
  98. action="store_true",
  99. dest="show_fixtures_per_test",
  100. default=False,
  101. help="Show fixtures per test",
  102. )
  103. parser.addini(
  104. "python_files",
  105. type="args",
  106. # NOTE: default is also used in AssertionRewritingHook.
  107. default=["test_*.py", "*_test.py"],
  108. help="Glob-style file patterns for Python test module discovery",
  109. )
  110. parser.addini(
  111. "python_classes",
  112. type="args",
  113. default=["Test"],
  114. help="Prefixes or glob names for Python test class discovery",
  115. )
  116. parser.addini(
  117. "python_functions",
  118. type="args",
  119. default=["test"],
  120. help="Prefixes or glob names for Python test function and method discovery",
  121. )
  122. parser.addini(
  123. "disable_test_id_escaping_and_forfeit_all_rights_to_community_support",
  124. type="bool",
  125. default=False,
  126. help="Disable string escape non-ASCII characters, might cause unwanted "
  127. "side effects(use at your own risk)",
  128. )
  129. def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
  130. if config.option.showfixtures:
  131. showfixtures(config)
  132. return 0
  133. if config.option.show_fixtures_per_test:
  134. show_fixtures_per_test(config)
  135. return 0
  136. return None
  137. def pytest_generate_tests(metafunc: "Metafunc") -> None:
  138. for marker in metafunc.definition.iter_markers(name="parametrize"):
  139. metafunc.parametrize(*marker.args, **marker.kwargs, _param_mark=marker)
  140. def pytest_configure(config: Config) -> None:
  141. config.addinivalue_line(
  142. "markers",
  143. "parametrize(argnames, argvalues): call a test function multiple "
  144. "times passing in different arguments in turn. argvalues generally "
  145. "needs to be a list of values if argnames specifies only one name "
  146. "or a list of tuples of values if argnames specifies multiple names. "
  147. "Example: @parametrize('arg1', [1,2]) would lead to two calls of the "
  148. "decorated test function, one with arg1=1 and another with arg1=2."
  149. "see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info "
  150. "and examples.",
  151. )
  152. config.addinivalue_line(
  153. "markers",
  154. "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
  155. "all of the specified fixtures. see "
  156. "https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures ",
  157. )
  158. def async_warn_and_skip(nodeid: str) -> None:
  159. msg = "async def functions are not natively supported and have been skipped.\n"
  160. msg += (
  161. "You need to install a suitable plugin for your async framework, for example:\n"
  162. )
  163. msg += " - anyio\n"
  164. msg += " - pytest-asyncio\n"
  165. msg += " - pytest-tornasync\n"
  166. msg += " - pytest-trio\n"
  167. msg += " - pytest-twisted"
  168. warnings.warn(PytestUnhandledCoroutineWarning(msg.format(nodeid)))
  169. skip(reason="async def function and no async plugin installed (see warnings)")
  170. @hookimpl(trylast=True)
  171. def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
  172. testfunction = pyfuncitem.obj
  173. if is_async_function(testfunction):
  174. async_warn_and_skip(pyfuncitem.nodeid)
  175. funcargs = pyfuncitem.funcargs
  176. testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
  177. result = testfunction(**testargs)
  178. if hasattr(result, "__await__") or hasattr(result, "__aiter__"):
  179. async_warn_and_skip(pyfuncitem.nodeid)
  180. elif result is not None:
  181. warnings.warn(
  182. PytestReturnNotNoneWarning(
  183. f"Expected None, but {pyfuncitem.nodeid} returned {result!r}, which will be an error in a "
  184. "future version of pytest. Did you mean to use `assert` instead of `return`?"
  185. )
  186. )
  187. return True
  188. def pytest_collect_file(file_path: Path, parent: nodes.Collector) -> Optional["Module"]:
  189. if file_path.suffix == ".py":
  190. if not parent.session.isinitpath(file_path):
  191. if not path_matches_patterns(
  192. file_path, parent.config.getini("python_files") + ["__init__.py"]
  193. ):
  194. return None
  195. ihook = parent.session.gethookproxy(file_path)
  196. module: Module = ihook.pytest_pycollect_makemodule(
  197. module_path=file_path, parent=parent
  198. )
  199. return module
  200. return None
  201. def path_matches_patterns(path: Path, patterns: Iterable[str]) -> bool:
  202. """Return whether path matches any of the patterns in the list of globs given."""
  203. return any(fnmatch_ex(pattern, path) for pattern in patterns)
  204. def pytest_pycollect_makemodule(module_path: Path, parent) -> "Module":
  205. if module_path.name == "__init__.py":
  206. pkg: Package = Package.from_parent(parent, path=module_path)
  207. return pkg
  208. mod: Module = Module.from_parent(parent, path=module_path)
  209. return mod
  210. @hookimpl(trylast=True)
  211. def pytest_pycollect_makeitem(
  212. collector: Union["Module", "Class"], name: str, obj: object
  213. ) -> Union[None, nodes.Item, nodes.Collector, List[Union[nodes.Item, nodes.Collector]]]:
  214. assert isinstance(collector, (Class, Module)), type(collector)
  215. # Nothing was collected elsewhere, let's do it here.
  216. if safe_isclass(obj):
  217. if collector.istestclass(obj, name):
  218. klass: Class = Class.from_parent(collector, name=name, obj=obj)
  219. return klass
  220. elif collector.istestfunction(obj, name):
  221. # mock seems to store unbound methods (issue473), normalize it.
  222. obj = getattr(obj, "__func__", obj)
  223. # We need to try and unwrap the function if it's a functools.partial
  224. # or a functools.wrapped.
  225. # We mustn't if it's been wrapped with mock.patch (python 2 only).
  226. if not (inspect.isfunction(obj) or inspect.isfunction(get_real_func(obj))):
  227. filename, lineno = getfslineno(obj)
  228. warnings.warn_explicit(
  229. message=PytestCollectionWarning(
  230. "cannot collect %r because it is not a function." % name
  231. ),
  232. category=None,
  233. filename=str(filename),
  234. lineno=lineno + 1,
  235. )
  236. elif getattr(obj, "__test__", True):
  237. if is_generator(obj):
  238. res: Function = Function.from_parent(collector, name=name)
  239. reason = "yield tests were removed in pytest 4.0 - {name} will be ignored".format(
  240. name=name
  241. )
  242. res.add_marker(MARK_GEN.xfail(run=False, reason=reason))
  243. res.warn(PytestCollectionWarning(reason))
  244. return res
  245. else:
  246. return list(collector._genfunctions(name, obj))
  247. return None
  248. class PyobjMixin(nodes.Node):
  249. """this mix-in inherits from Node to carry over the typing information
  250. as its intended to always mix in before a node
  251. its position in the mro is unaffected"""
  252. _ALLOW_MARKERS = True
  253. @property
  254. def module(self):
  255. """Python module object this node was collected from (can be None)."""
  256. node = self.getparent(Module)
  257. return node.obj if node is not None else None
  258. @property
  259. def cls(self):
  260. """Python class object this node was collected from (can be None)."""
  261. node = self.getparent(Class)
  262. return node.obj if node is not None else None
  263. @property
  264. def instance(self):
  265. """Python instance object the function is bound to.
  266. Returns None if not a test method, e.g. for a standalone test function,
  267. a staticmethod, a class or a module.
  268. """
  269. node = self.getparent(Function)
  270. return getattr(node.obj, "__self__", None) if node is not None else None
  271. @property
  272. def obj(self):
  273. """Underlying Python object."""
  274. obj = getattr(self, "_obj", None)
  275. if obj is None:
  276. self._obj = obj = self._getobj()
  277. # XXX evil hack
  278. # used to avoid Function marker duplication
  279. if self._ALLOW_MARKERS:
  280. self.own_markers.extend(get_unpacked_marks(self.obj))
  281. # This assumes that `obj` is called before there is a chance
  282. # to add custom keys to `self.keywords`, so no fear of overriding.
  283. self.keywords.update((mark.name, mark) for mark in self.own_markers)
  284. return obj
  285. @obj.setter
  286. def obj(self, value):
  287. self._obj = value
  288. def _getobj(self):
  289. """Get the underlying Python object. May be overwritten by subclasses."""
  290. # TODO: Improve the type of `parent` such that assert/ignore aren't needed.
  291. assert self.parent is not None
  292. obj = self.parent.obj # type: ignore[attr-defined]
  293. return getattr(obj, self.name)
  294. def getmodpath(self, stopatmodule: bool = True, includemodule: bool = False) -> str:
  295. """Return Python path relative to the containing module."""
  296. chain = self.listchain()
  297. chain.reverse()
  298. parts = []
  299. for node in chain:
  300. name = node.name
  301. if isinstance(node, Module):
  302. name = os.path.splitext(name)[0]
  303. if stopatmodule:
  304. if includemodule:
  305. parts.append(name)
  306. break
  307. parts.append(name)
  308. parts.reverse()
  309. return ".".join(parts)
  310. def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
  311. # XXX caching?
  312. obj = self.obj
  313. compat_co_firstlineno = getattr(obj, "compat_co_firstlineno", None)
  314. if isinstance(compat_co_firstlineno, int):
  315. # nose compatibility
  316. file_path = sys.modules[obj.__module__].__file__
  317. assert file_path is not None
  318. if file_path.endswith(".pyc"):
  319. file_path = file_path[:-1]
  320. path: Union["os.PathLike[str]", str] = file_path
  321. lineno = compat_co_firstlineno
  322. else:
  323. path, lineno = getfslineno(obj)
  324. modpath = self.getmodpath()
  325. assert isinstance(lineno, int)
  326. return path, lineno, modpath
  327. # As an optimization, these builtin attribute names are pre-ignored when
  328. # iterating over an object during collection -- the pytest_pycollect_makeitem
  329. # hook is not called for them.
  330. # fmt: off
  331. class _EmptyClass: pass # noqa: E701
  332. IGNORED_ATTRIBUTES = frozenset.union( # noqa: E305
  333. frozenset(),
  334. # Module.
  335. dir(types.ModuleType("empty_module")),
  336. # Some extra module attributes the above doesn't catch.
  337. {"__builtins__", "__file__", "__cached__"},
  338. # Class.
  339. dir(_EmptyClass),
  340. # Instance.
  341. dir(_EmptyClass()),
  342. )
  343. del _EmptyClass
  344. # fmt: on
  345. class PyCollector(PyobjMixin, nodes.Collector):
  346. def funcnamefilter(self, name: str) -> bool:
  347. return self._matches_prefix_or_glob_option("python_functions", name)
  348. def isnosetest(self, obj: object) -> bool:
  349. """Look for the __test__ attribute, which is applied by the
  350. @nose.tools.istest decorator.
  351. """
  352. # We explicitly check for "is True" here to not mistakenly treat
  353. # classes with a custom __getattr__ returning something truthy (like a
  354. # function) as test classes.
  355. return safe_getattr(obj, "__test__", False) is True
  356. def classnamefilter(self, name: str) -> bool:
  357. return self._matches_prefix_or_glob_option("python_classes", name)
  358. def istestfunction(self, obj: object, name: str) -> bool:
  359. if self.funcnamefilter(name) or self.isnosetest(obj):
  360. if isinstance(obj, (staticmethod, classmethod)):
  361. # staticmethods and classmethods need to be unwrapped.
  362. obj = safe_getattr(obj, "__func__", False)
  363. return callable(obj) and fixtures.getfixturemarker(obj) is None
  364. else:
  365. return False
  366. def istestclass(self, obj: object, name: str) -> bool:
  367. return self.classnamefilter(name) or self.isnosetest(obj)
  368. def _matches_prefix_or_glob_option(self, option_name: str, name: str) -> bool:
  369. """Check if the given name matches the prefix or glob-pattern defined
  370. in ini configuration."""
  371. for option in self.config.getini(option_name):
  372. if name.startswith(option):
  373. return True
  374. # Check that name looks like a glob-string before calling fnmatch
  375. # because this is called for every name in each collected module,
  376. # and fnmatch is somewhat expensive to call.
  377. elif ("*" in option or "?" in option or "[" in option) and fnmatch.fnmatch(
  378. name, option
  379. ):
  380. return True
  381. return False
  382. def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
  383. if not getattr(self.obj, "__test__", True):
  384. return []
  385. # Avoid random getattrs and peek in the __dict__ instead.
  386. dicts = [getattr(self.obj, "__dict__", {})]
  387. if isinstance(self.obj, type):
  388. for basecls in self.obj.__mro__:
  389. dicts.append(basecls.__dict__)
  390. # In each class, nodes should be definition ordered.
  391. # __dict__ is definition ordered.
  392. seen: Set[str] = set()
  393. dict_values: List[List[Union[nodes.Item, nodes.Collector]]] = []
  394. ihook = self.ihook
  395. for dic in dicts:
  396. values: List[Union[nodes.Item, nodes.Collector]] = []
  397. # Note: seems like the dict can change during iteration -
  398. # be careful not to remove the list() without consideration.
  399. for name, obj in list(dic.items()):
  400. if name in IGNORED_ATTRIBUTES:
  401. continue
  402. if name in seen:
  403. continue
  404. seen.add(name)
  405. res = ihook.pytest_pycollect_makeitem(
  406. collector=self, name=name, obj=obj
  407. )
  408. if res is None:
  409. continue
  410. elif isinstance(res, list):
  411. values.extend(res)
  412. else:
  413. values.append(res)
  414. dict_values.append(values)
  415. # Between classes in the class hierarchy, reverse-MRO order -- nodes
  416. # inherited from base classes should come before subclasses.
  417. result = []
  418. for values in reversed(dict_values):
  419. result.extend(values)
  420. return result
  421. def _genfunctions(self, name: str, funcobj) -> Iterator["Function"]:
  422. modulecol = self.getparent(Module)
  423. assert modulecol is not None
  424. module = modulecol.obj
  425. clscol = self.getparent(Class)
  426. cls = clscol and clscol.obj or None
  427. definition = FunctionDefinition.from_parent(self, name=name, callobj=funcobj)
  428. fixtureinfo = definition._fixtureinfo
  429. # pytest_generate_tests impls call metafunc.parametrize() which fills
  430. # metafunc._calls, the outcome of the hook.
  431. metafunc = Metafunc(
  432. definition=definition,
  433. fixtureinfo=fixtureinfo,
  434. config=self.config,
  435. cls=cls,
  436. module=module,
  437. _ispytest=True,
  438. )
  439. methods = []
  440. if hasattr(module, "pytest_generate_tests"):
  441. methods.append(module.pytest_generate_tests)
  442. if cls is not None and hasattr(cls, "pytest_generate_tests"):
  443. methods.append(cls().pytest_generate_tests)
  444. self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))
  445. if not metafunc._calls:
  446. yield Function.from_parent(self, name=name, fixtureinfo=fixtureinfo)
  447. else:
  448. # Add funcargs() as fixturedefs to fixtureinfo.arg2fixturedefs.
  449. fm = self.session._fixturemanager
  450. fixtures.add_funcarg_pseudo_fixture_def(self, metafunc, fm)
  451. # Add_funcarg_pseudo_fixture_def may have shadowed some fixtures
  452. # with direct parametrization, so make sure we update what the
  453. # function really needs.
  454. fixtureinfo.prune_dependency_tree()
  455. for callspec in metafunc._calls:
  456. subname = f"{name}[{callspec.id}]"
  457. yield Function.from_parent(
  458. self,
  459. name=subname,
  460. callspec=callspec,
  461. fixtureinfo=fixtureinfo,
  462. keywords={callspec.id: True},
  463. originalname=name,
  464. )
  465. class Module(nodes.File, PyCollector):
  466. """Collector for test classes and functions in a Python module."""
  467. def _getobj(self):
  468. return self._importtestmodule()
  469. def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
  470. self._inject_setup_module_fixture()
  471. self._inject_setup_function_fixture()
  472. self.session._fixturemanager.parsefactories(self)
  473. return super().collect()
  474. def _inject_setup_module_fixture(self) -> None:
  475. """Inject a hidden autouse, module scoped fixture into the collected module object
  476. that invokes setUpModule/tearDownModule if either or both are available.
  477. Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
  478. other fixtures (#517).
  479. """
  480. has_nose = self.config.pluginmanager.has_plugin("nose")
  481. setup_module = _get_first_non_fixture_func(
  482. self.obj, ("setUpModule", "setup_module")
  483. )
  484. if setup_module is None and has_nose:
  485. # The name "setup" is too common - only treat as fixture if callable.
  486. setup_module = _get_first_non_fixture_func(self.obj, ("setup",))
  487. if not callable(setup_module):
  488. setup_module = None
  489. teardown_module = _get_first_non_fixture_func(
  490. self.obj, ("tearDownModule", "teardown_module")
  491. )
  492. if teardown_module is None and has_nose:
  493. teardown_module = _get_first_non_fixture_func(self.obj, ("teardown",))
  494. # Same as "setup" above - only treat as fixture if callable.
  495. if not callable(teardown_module):
  496. teardown_module = None
  497. if setup_module is None and teardown_module is None:
  498. return
  499. @fixtures.fixture(
  500. autouse=True,
  501. scope="module",
  502. # Use a unique name to speed up lookup.
  503. name=f"_xunit_setup_module_fixture_{self.obj.__name__}",
  504. )
  505. def xunit_setup_module_fixture(request) -> Generator[None, None, None]:
  506. if setup_module is not None:
  507. _call_with_optional_argument(setup_module, request.module)
  508. yield
  509. if teardown_module is not None:
  510. _call_with_optional_argument(teardown_module, request.module)
  511. self.obj.__pytest_setup_module = xunit_setup_module_fixture
  512. def _inject_setup_function_fixture(self) -> None:
  513. """Inject a hidden autouse, function scoped fixture into the collected module object
  514. that invokes setup_function/teardown_function if either or both are available.
  515. Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
  516. other fixtures (#517).
  517. """
  518. setup_function = _get_first_non_fixture_func(self.obj, ("setup_function",))
  519. teardown_function = _get_first_non_fixture_func(
  520. self.obj, ("teardown_function",)
  521. )
  522. if setup_function is None and teardown_function is None:
  523. return
  524. @fixtures.fixture(
  525. autouse=True,
  526. scope="function",
  527. # Use a unique name to speed up lookup.
  528. name=f"_xunit_setup_function_fixture_{self.obj.__name__}",
  529. )
  530. def xunit_setup_function_fixture(request) -> Generator[None, None, None]:
  531. if request.instance is not None:
  532. # in this case we are bound to an instance, so we need to let
  533. # setup_method handle this
  534. yield
  535. return
  536. if setup_function is not None:
  537. _call_with_optional_argument(setup_function, request.function)
  538. yield
  539. if teardown_function is not None:
  540. _call_with_optional_argument(teardown_function, request.function)
  541. self.obj.__pytest_setup_function = xunit_setup_function_fixture
  542. def _importtestmodule(self):
  543. # We assume we are only called once per module.
  544. importmode = self.config.getoption("--import-mode")
  545. try:
  546. mod = import_path(self.path, mode=importmode, root=self.config.rootpath)
  547. except SyntaxError as e:
  548. raise self.CollectError(
  549. ExceptionInfo.from_current().getrepr(style="short")
  550. ) from e
  551. except ImportPathMismatchError as e:
  552. raise self.CollectError(
  553. "import file mismatch:\n"
  554. "imported module %r has this __file__ attribute:\n"
  555. " %s\n"
  556. "which is not the same as the test file we want to collect:\n"
  557. " %s\n"
  558. "HINT: remove __pycache__ / .pyc files and/or use a "
  559. "unique basename for your test file modules" % e.args
  560. ) from e
  561. except ImportError as e:
  562. exc_info = ExceptionInfo.from_current()
  563. if self.config.getoption("verbose") < 2:
  564. exc_info.traceback = exc_info.traceback.filter(filter_traceback)
  565. exc_repr = (
  566. exc_info.getrepr(style="short")
  567. if exc_info.traceback
  568. else exc_info.exconly()
  569. )
  570. formatted_tb = str(exc_repr)
  571. raise self.CollectError(
  572. "ImportError while importing test module '{path}'.\n"
  573. "Hint: make sure your test modules/packages have valid Python names.\n"
  574. "Traceback:\n"
  575. "{traceback}".format(path=self.path, traceback=formatted_tb)
  576. ) from e
  577. except skip.Exception as e:
  578. if e.allow_module_level:
  579. raise
  580. raise self.CollectError(
  581. "Using pytest.skip outside of a test will skip the entire module. "
  582. "If that's your intention, pass `allow_module_level=True`. "
  583. "If you want to skip a specific test or an entire class, "
  584. "use the @pytest.mark.skip or @pytest.mark.skipif decorators."
  585. ) from e
  586. self.config.pluginmanager.consider_module(mod)
  587. return mod
  588. class Package(Module):
  589. """Collector for files and directories in a Python packages -- directories
  590. with an `__init__.py` file."""
  591. def __init__(
  592. self,
  593. fspath: Optional[LEGACY_PATH],
  594. parent: nodes.Collector,
  595. # NOTE: following args are unused:
  596. config=None,
  597. session=None,
  598. nodeid=None,
  599. path: Optional[Path] = None,
  600. ) -> None:
  601. # NOTE: Could be just the following, but kept as-is for compat.
  602. # nodes.FSCollector.__init__(self, fspath, parent=parent)
  603. session = parent.session
  604. nodes.FSCollector.__init__(
  605. self,
  606. fspath=fspath,
  607. path=path,
  608. parent=parent,
  609. config=config,
  610. session=session,
  611. nodeid=nodeid,
  612. )
  613. self.name = self.path.parent.name
  614. def setup(self) -> None:
  615. # Not using fixtures to call setup_module here because autouse fixtures
  616. # from packages are not called automatically (#4085).
  617. setup_module = _get_first_non_fixture_func(
  618. self.obj, ("setUpModule", "setup_module")
  619. )
  620. if setup_module is not None:
  621. _call_with_optional_argument(setup_module, self.obj)
  622. teardown_module = _get_first_non_fixture_func(
  623. self.obj, ("tearDownModule", "teardown_module")
  624. )
  625. if teardown_module is not None:
  626. func = partial(_call_with_optional_argument, teardown_module, self.obj)
  627. self.addfinalizer(func)
  628. def _recurse(self, direntry: "os.DirEntry[str]") -> bool:
  629. if direntry.name == "__pycache__":
  630. return False
  631. fspath = Path(direntry.path)
  632. ihook = self.session.gethookproxy(fspath.parent)
  633. if ihook.pytest_ignore_collect(collection_path=fspath, config=self.config):
  634. return False
  635. return True
  636. def _collectfile(
  637. self, fspath: Path, handle_dupes: bool = True
  638. ) -> Sequence[nodes.Collector]:
  639. assert (
  640. fspath.is_file()
  641. ), "{!r} is not a file (isdir={!r}, exists={!r}, islink={!r})".format(
  642. fspath, fspath.is_dir(), fspath.exists(), fspath.is_symlink()
  643. )
  644. ihook = self.session.gethookproxy(fspath)
  645. if not self.session.isinitpath(fspath):
  646. if ihook.pytest_ignore_collect(collection_path=fspath, config=self.config):
  647. return ()
  648. if handle_dupes:
  649. keepduplicates = self.config.getoption("keepduplicates")
  650. if not keepduplicates:
  651. duplicate_paths = self.config.pluginmanager._duplicatepaths
  652. if fspath in duplicate_paths:
  653. return ()
  654. else:
  655. duplicate_paths.add(fspath)
  656. return ihook.pytest_collect_file(file_path=fspath, parent=self) # type: ignore[no-any-return]
  657. def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
  658. this_path = self.path.parent
  659. # Always collect the __init__ first.
  660. if path_matches_patterns(self.path, self.config.getini("python_files")):
  661. yield Module.from_parent(self, path=self.path)
  662. pkg_prefixes: Set[Path] = set()
  663. for direntry in visit(str(this_path), recurse=self._recurse):
  664. path = Path(direntry.path)
  665. # We will visit our own __init__.py file, in which case we skip it.
  666. if direntry.is_file():
  667. if direntry.name == "__init__.py" and path.parent == this_path:
  668. continue
  669. parts_ = parts(direntry.path)
  670. if any(
  671. str(pkg_prefix) in parts_ and pkg_prefix / "__init__.py" != path
  672. for pkg_prefix in pkg_prefixes
  673. ):
  674. continue
  675. if direntry.is_file():
  676. yield from self._collectfile(path)
  677. elif not direntry.is_dir():
  678. # Broken symlink or invalid/missing file.
  679. continue
  680. elif path.joinpath("__init__.py").is_file():
  681. pkg_prefixes.add(path)
  682. def _call_with_optional_argument(func, arg) -> None:
  683. """Call the given function with the given argument if func accepts one argument, otherwise
  684. calls func without arguments."""
  685. arg_count = func.__code__.co_argcount
  686. if inspect.ismethod(func):
  687. arg_count -= 1
  688. if arg_count:
  689. func(arg)
  690. else:
  691. func()
  692. def _get_first_non_fixture_func(obj: object, names: Iterable[str]) -> Optional[object]:
  693. """Return the attribute from the given object to be used as a setup/teardown
  694. xunit-style function, but only if not marked as a fixture to avoid calling it twice.
  695. """
  696. for name in names:
  697. meth: Optional[object] = getattr(obj, name, None)
  698. if meth is not None and fixtures.getfixturemarker(meth) is None:
  699. return meth
  700. return None
  701. class Class(PyCollector):
  702. """Collector for test methods (and nested classes) in a Python class."""
  703. @classmethod
  704. def from_parent(cls, parent, *, name, obj=None, **kw):
  705. """The public constructor."""
  706. return super().from_parent(name=name, parent=parent, **kw)
  707. def newinstance(self):
  708. return self.obj()
  709. def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
  710. if not safe_getattr(self.obj, "__test__", True):
  711. return []
  712. if hasinit(self.obj):
  713. assert self.parent is not None
  714. self.warn(
  715. PytestCollectionWarning(
  716. "cannot collect test class %r because it has a "
  717. "__init__ constructor (from: %s)"
  718. % (self.obj.__name__, self.parent.nodeid)
  719. )
  720. )
  721. return []
  722. elif hasnew(self.obj):
  723. assert self.parent is not None
  724. self.warn(
  725. PytestCollectionWarning(
  726. "cannot collect test class %r because it has a "
  727. "__new__ constructor (from: %s)"
  728. % (self.obj.__name__, self.parent.nodeid)
  729. )
  730. )
  731. return []
  732. self._inject_setup_class_fixture()
  733. self._inject_setup_method_fixture()
  734. self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)
  735. return super().collect()
  736. def _inject_setup_class_fixture(self) -> None:
  737. """Inject a hidden autouse, class scoped fixture into the collected class object
  738. that invokes setup_class/teardown_class if either or both are available.
  739. Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
  740. other fixtures (#517).
  741. """
  742. setup_class = _get_first_non_fixture_func(self.obj, ("setup_class",))
  743. teardown_class = _get_first_non_fixture_func(self.obj, ("teardown_class",))
  744. if setup_class is None and teardown_class is None:
  745. return
  746. @fixtures.fixture(
  747. autouse=True,
  748. scope="class",
  749. # Use a unique name to speed up lookup.
  750. name=f"_xunit_setup_class_fixture_{self.obj.__qualname__}",
  751. )
  752. def xunit_setup_class_fixture(cls) -> Generator[None, None, None]:
  753. if setup_class is not None:
  754. func = getimfunc(setup_class)
  755. _call_with_optional_argument(func, self.obj)
  756. yield
  757. if teardown_class is not None:
  758. func = getimfunc(teardown_class)
  759. _call_with_optional_argument(func, self.obj)
  760. self.obj.__pytest_setup_class = xunit_setup_class_fixture
  761. def _inject_setup_method_fixture(self) -> None:
  762. """Inject a hidden autouse, function scoped fixture into the collected class object
  763. that invokes setup_method/teardown_method if either or both are available.
  764. Using a fixture to invoke these methods ensures we play nicely and unsurprisingly with
  765. other fixtures (#517).
  766. """
  767. has_nose = self.config.pluginmanager.has_plugin("nose")
  768. setup_name = "setup_method"
  769. setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
  770. emit_nose_setup_warning = False
  771. if setup_method is None and has_nose:
  772. setup_name = "setup"
  773. emit_nose_setup_warning = True
  774. setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
  775. teardown_name = "teardown_method"
  776. teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,))
  777. emit_nose_teardown_warning = False
  778. if teardown_method is None and has_nose:
  779. teardown_name = "teardown"
  780. emit_nose_teardown_warning = True
  781. teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,))
  782. if setup_method is None and teardown_method is None:
  783. return
  784. @fixtures.fixture(
  785. autouse=True,
  786. scope="function",
  787. # Use a unique name to speed up lookup.
  788. name=f"_xunit_setup_method_fixture_{self.obj.__qualname__}",
  789. )
  790. def xunit_setup_method_fixture(self, request) -> Generator[None, None, None]:
  791. method = request.function
  792. if setup_method is not None:
  793. func = getattr(self, setup_name)
  794. _call_with_optional_argument(func, method)
  795. if emit_nose_setup_warning:
  796. warnings.warn(
  797. NOSE_SUPPORT_METHOD.format(
  798. nodeid=request.node.nodeid, method="setup"
  799. ),
  800. stacklevel=2,
  801. )
  802. yield
  803. if teardown_method is not None:
  804. func = getattr(self, teardown_name)
  805. _call_with_optional_argument(func, method)
  806. if emit_nose_teardown_warning:
  807. warnings.warn(
  808. NOSE_SUPPORT_METHOD.format(
  809. nodeid=request.node.nodeid, method="teardown"
  810. ),
  811. stacklevel=2,
  812. )
  813. self.obj.__pytest_setup_method = xunit_setup_method_fixture
  814. class InstanceDummy:
  815. """Instance used to be a node type between Class and Function. It has been
  816. removed in pytest 7.0. Some plugins exist which reference `pytest.Instance`
  817. only to ignore it; this dummy class keeps them working. This will be removed
  818. in pytest 8."""
  819. def __getattr__(name: str) -> object:
  820. if name == "Instance":
  821. warnings.warn(INSTANCE_COLLECTOR, 2)
  822. return InstanceDummy
  823. raise AttributeError(f"module {__name__} has no attribute {name}")
  824. def hasinit(obj: object) -> bool:
  825. init: object = getattr(obj, "__init__", None)
  826. if init:
  827. return init != object.__init__
  828. return False
  829. def hasnew(obj: object) -> bool:
  830. new: object = getattr(obj, "__new__", None)
  831. if new:
  832. return new != object.__new__
  833. return False
  834. @final
  835. @dataclasses.dataclass(frozen=True)
  836. class IdMaker:
  837. """Make IDs for a parametrization."""
  838. __slots__ = (
  839. "argnames",
  840. "parametersets",
  841. "idfn",
  842. "ids",
  843. "config",
  844. "nodeid",
  845. "func_name",
  846. )
  847. # The argnames of the parametrization.
  848. argnames: Sequence[str]
  849. # The ParameterSets of the parametrization.
  850. parametersets: Sequence[ParameterSet]
  851. # Optionally, a user-provided callable to make IDs for parameters in a
  852. # ParameterSet.
  853. idfn: Optional[Callable[[Any], Optional[object]]]
  854. # Optionally, explicit IDs for ParameterSets by index.
  855. ids: Optional[Sequence[Optional[object]]]
  856. # Optionally, the pytest config.
  857. # Used for controlling ASCII escaping, and for calling the
  858. # :hook:`pytest_make_parametrize_id` hook.
  859. config: Optional[Config]
  860. # Optionally, the ID of the node being parametrized.
  861. # Used only for clearer error messages.
  862. nodeid: Optional[str]
  863. # Optionally, the ID of the function being parametrized.
  864. # Used only for clearer error messages.
  865. func_name: Optional[str]
  866. def make_unique_parameterset_ids(self) -> List[str]:
  867. """Make a unique identifier for each ParameterSet, that may be used to
  868. identify the parametrization in a node ID.
  869. Format is <prm_1_token>-...-<prm_n_token>[counter], where prm_x_token is
  870. - user-provided id, if given
  871. - else an id derived from the value, applicable for certain types
  872. - else <argname><parameterset index>
  873. The counter suffix is appended only in case a string wouldn't be unique
  874. otherwise.
  875. """
  876. resolved_ids = list(self._limit_ids(self._resolve_ids(), limit=500))
  877. # All IDs must be unique!
  878. if len(resolved_ids) != len(set(resolved_ids)):
  879. # Record the number of occurrences of each ID.
  880. id_counts = Counter(resolved_ids)
  881. # Map the ID to its next suffix.
  882. id_suffixes: Dict[str, int] = defaultdict(int)
  883. # Suffix non-unique IDs to make them unique.
  884. for index, id in enumerate(resolved_ids):
  885. if id_counts[id] > 1:
  886. resolved_ids[index] = f"{id}{id_suffixes[id]}"
  887. id_suffixes[id] += 1
  888. return resolved_ids
  889. def _limit_ids(self, ids, limit=500):
  890. prefix_count = {}
  891. limit -= 6
  892. assert limit > 0
  893. for idval in ids:
  894. if len(idval) > limit:
  895. prefix = idval[:limit]
  896. idx = prefix_count.get(prefix, -1) + 1
  897. prefix_count[prefix] = idx
  898. idval = "{}-{}".format(prefix, idx)
  899. yield idval
  900. def _resolve_ids(self) -> Iterable[str]:
  901. """Resolve IDs for all ParameterSets (may contain duplicates)."""
  902. for idx, parameterset in enumerate(self.parametersets):
  903. if parameterset.id is not None:
  904. # ID provided directly - pytest.param(..., id="...")
  905. yield parameterset.id
  906. elif self.ids and idx < len(self.ids) and self.ids[idx] is not None:
  907. # ID provided in the IDs list - parametrize(..., ids=[...]).
  908. yield self._idval_from_value_required(self.ids[idx], idx)
  909. else:
  910. # ID not provided - generate it.
  911. yield "-".join(
  912. self._idval(val, argname, idx)
  913. for val, argname in zip(parameterset.values, self.argnames)
  914. )
  915. def _idval(self, val: object, argname: str, idx: int) -> str:
  916. """Make an ID for a parameter in a ParameterSet."""
  917. idval = self._idval_from_function(val, argname, idx)
  918. if idval is not None:
  919. return idval
  920. idval = self._idval_from_hook(val, argname)
  921. if idval is not None:
  922. return idval
  923. idval = self._idval_from_value(val)
  924. if idval is not None:
  925. return idval
  926. return self._idval_from_argname(argname, idx)
  927. def _idval_from_function(
  928. self, val: object, argname: str, idx: int
  929. ) -> Optional[str]:
  930. """Try to make an ID for a parameter in a ParameterSet using the
  931. user-provided id callable, if given."""
  932. if self.idfn is None:
  933. return None
  934. try:
  935. id = self.idfn(val)
  936. except Exception as e:
  937. prefix = f"{self.nodeid}: " if self.nodeid is not None else ""
  938. msg = "error raised while trying to determine id of parameter '{}' at position {}"
  939. msg = prefix + msg.format(argname, idx)
  940. raise ValueError(msg) from e
  941. if id is None:
  942. return None
  943. return self._idval_from_value(id)
  944. def _idval_from_hook(self, val: object, argname: str) -> Optional[str]:
  945. """Try to make an ID for a parameter in a ParameterSet by calling the
  946. :hook:`pytest_make_parametrize_id` hook."""
  947. if self.config:
  948. id: Optional[str] = self.config.hook.pytest_make_parametrize_id(
  949. config=self.config, val=val, argname=argname
  950. )
  951. return id
  952. return None
  953. def _idval_from_value(self, val: object) -> Optional[str]:
  954. """Try to make an ID for a parameter in a ParameterSet from its value,
  955. if the value type is supported."""
  956. if isinstance(val, STRING_TYPES):
  957. return _ascii_escaped_by_config(val, self.config)
  958. elif val is None or isinstance(val, (float, int, bool, complex)):
  959. return str(val)
  960. elif isinstance(val, Pattern):
  961. return ascii_escaped(val.pattern)
  962. elif val is NOTSET:
  963. # Fallback to default. Note that NOTSET is an enum.Enum.
  964. pass
  965. elif isinstance(val, enum.Enum):
  966. return str(val)
  967. elif isinstance(getattr(val, "__name__", None), str):
  968. # Name of a class, function, module, etc.
  969. name: str = getattr(val, "__name__")
  970. return name
  971. return None
  972. def _idval_from_value_required(self, val: object, idx: int) -> str:
  973. """Like _idval_from_value(), but fails if the type is not supported."""
  974. id = self._idval_from_value(val)
  975. if id is not None:
  976. return id
  977. # Fail.
  978. if self.func_name is not None:
  979. prefix = f"In {self.func_name}: "
  980. elif self.nodeid is not None:
  981. prefix = f"In {self.nodeid}: "
  982. else:
  983. prefix = ""
  984. msg = (
  985. f"{prefix}ids contains unsupported value {saferepr(val)} (type: {type(val)!r}) at index {idx}. "
  986. "Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__."
  987. )
  988. fail(msg, pytrace=False)
  989. @staticmethod
  990. def _idval_from_argname(argname: str, idx: int) -> str:
  991. """Make an ID for a parameter in a ParameterSet from the argument name
  992. and the index of the ParameterSet."""
  993. return str(argname) + str(idx)
  994. @final
  995. @dataclasses.dataclass(frozen=True)
  996. class CallSpec2:
  997. """A planned parameterized invocation of a test function.
  998. Calculated during collection for a given test function's Metafunc.
  999. Once collection is over, each callspec is turned into a single Item
  1000. and stored in item.callspec.
  1001. """
  1002. # arg name -> arg value which will be passed to the parametrized test
  1003. # function (direct parameterization).
  1004. funcargs: Dict[str, object] = dataclasses.field(default_factory=dict)
  1005. # arg name -> arg value which will be passed to a fixture of the same name
  1006. # (indirect parametrization).
  1007. params: Dict[str, object] = dataclasses.field(default_factory=dict)
  1008. # arg name -> arg index.
  1009. indices: Dict[str, int] = dataclasses.field(default_factory=dict)
  1010. # Used for sorting parametrized resources.
  1011. _arg2scope: Dict[str, Scope] = dataclasses.field(default_factory=dict)
  1012. # Parts which will be added to the item's name in `[..]` separated by "-".
  1013. _idlist: List[str] = dataclasses.field(default_factory=list)
  1014. # Marks which will be applied to the item.
  1015. marks: List[Mark] = dataclasses.field(default_factory=list)
  1016. def setmulti(
  1017. self,
  1018. *,
  1019. valtypes: Mapping[str, "Literal['params', 'funcargs']"],
  1020. argnames: Iterable[str],
  1021. valset: Iterable[object],
  1022. id: str,
  1023. marks: Iterable[Union[Mark, MarkDecorator]],
  1024. scope: Scope,
  1025. param_index: int,
  1026. ) -> "CallSpec2":
  1027. funcargs = self.funcargs.copy()
  1028. params = self.params.copy()
  1029. indices = self.indices.copy()
  1030. arg2scope = self._arg2scope.copy()
  1031. for arg, val in zip(argnames, valset):
  1032. if arg in params or arg in funcargs:
  1033. raise ValueError(f"duplicate parametrization of {arg!r}")
  1034. valtype_for_arg = valtypes[arg]
  1035. if valtype_for_arg == "params":
  1036. params[arg] = val
  1037. elif valtype_for_arg == "funcargs":
  1038. funcargs[arg] = val
  1039. else:
  1040. assert_never(valtype_for_arg)
  1041. indices[arg] = param_index
  1042. arg2scope[arg] = scope
  1043. return CallSpec2(
  1044. funcargs=funcargs,
  1045. params=params,
  1046. indices=indices,
  1047. _arg2scope=arg2scope,
  1048. _idlist=[*self._idlist, id],
  1049. marks=[*self.marks, *normalize_mark_list(marks)],
  1050. )
  1051. def getparam(self, name: str) -> object:
  1052. try:
  1053. return self.params[name]
  1054. except KeyError as e:
  1055. raise ValueError(name) from e
  1056. @property
  1057. def id(self) -> str:
  1058. return "-".join(self._idlist)
  1059. @final
  1060. class Metafunc:
  1061. """Objects passed to the :hook:`pytest_generate_tests` hook.
  1062. They help to inspect a test function and to generate tests according to
  1063. test configuration or values specified in the class or module where a
  1064. test function is defined.
  1065. """
  1066. def __init__(
  1067. self,
  1068. definition: "FunctionDefinition",
  1069. fixtureinfo: fixtures.FuncFixtureInfo,
  1070. config: Config,
  1071. cls=None,
  1072. module=None,
  1073. *,
  1074. _ispytest: bool = False,
  1075. ) -> None:
  1076. check_ispytest(_ispytest)
  1077. #: Access to the underlying :class:`_pytest.python.FunctionDefinition`.
  1078. self.definition = definition
  1079. #: Access to the :class:`pytest.Config` object for the test session.
  1080. self.config = config
  1081. #: The module object where the test function is defined in.
  1082. self.module = module
  1083. #: Underlying Python test function.
  1084. self.function = definition.obj
  1085. #: Set of fixture names required by the test function.
  1086. self.fixturenames = fixtureinfo.names_closure
  1087. #: Class object where the test function is defined in or ``None``.
  1088. self.cls = cls
  1089. self._arg2fixturedefs = fixtureinfo.name2fixturedefs
  1090. # Result of parametrize().
  1091. self._calls: List[CallSpec2] = []
  1092. def parametrize(
  1093. self,
  1094. argnames: Union[str, Sequence[str]],
  1095. argvalues: Iterable[Union[ParameterSet, Sequence[object], object]],
  1096. indirect: Union[bool, Sequence[str]] = False,
  1097. ids: Optional[
  1098. Union[Iterable[Optional[object]], Callable[[Any], Optional[object]]]
  1099. ] = None,
  1100. scope: "Optional[_ScopeName]" = None,
  1101. *,
  1102. _param_mark: Optional[Mark] = None,
  1103. ) -> None:
  1104. """Add new invocations to the underlying test function using the list
  1105. of argvalues for the given argnames. Parametrization is performed
  1106. during the collection phase. If you need to setup expensive resources
  1107. see about setting indirect to do it rather than at test setup time.
  1108. Can be called multiple times per test function (but only on different
  1109. argument names), in which case each call parametrizes all previous
  1110. parametrizations, e.g.
  1111. ::
  1112. unparametrized: t
  1113. parametrize ["x", "y"]: t[x], t[y]
  1114. parametrize [1, 2]: t[x-1], t[x-2], t[y-1], t[y-2]
  1115. :param argnames:
  1116. A comma-separated string denoting one or more argument names, or
  1117. a list/tuple of argument strings.
  1118. :param argvalues:
  1119. The list of argvalues determines how often a test is invoked with
  1120. different argument values.
  1121. If only one argname was specified argvalues is a list of values.
  1122. If N argnames were specified, argvalues must be a list of
  1123. N-tuples, where each tuple-element specifies a value for its
  1124. respective argname.
  1125. :param indirect:
  1126. A list of arguments' names (subset of argnames) or a boolean.
  1127. If True the list contains all names from the argnames. Each
  1128. argvalue corresponding to an argname in this list will
  1129. be passed as request.param to its respective argname fixture
  1130. function so that it can perform more expensive setups during the
  1131. setup phase of a test rather than at collection time.
  1132. :param ids:
  1133. Sequence of (or generator for) ids for ``argvalues``,
  1134. or a callable to return part of the id for each argvalue.
  1135. With sequences (and generators like ``itertools.count()``) the
  1136. returned ids should be of type ``string``, ``int``, ``float``,
  1137. ``bool``, or ``None``.
  1138. They are mapped to the corresponding index in ``argvalues``.
  1139. ``None`` means to use the auto-generated id.
  1140. If it is a callable it will be called for each entry in
  1141. ``argvalues``, and the return value is used as part of the
  1142. auto-generated id for the whole set (where parts are joined with
  1143. dashes ("-")).
  1144. This is useful to provide more specific ids for certain items, e.g.
  1145. dates. Returning ``None`` will use an auto-generated id.
  1146. If no ids are provided they will be generated automatically from
  1147. the argvalues.
  1148. :param scope:
  1149. If specified it denotes the scope of the parameters.
  1150. The scope is used for grouping tests by parameter instances.
  1151. It will also override any fixture-function defined scope, allowing
  1152. to set a dynamic scope using test context or configuration.
  1153. """
  1154. argnames, parametersets = ParameterSet._for_parametrize(
  1155. argnames,
  1156. argvalues,
  1157. self.function,
  1158. self.config,
  1159. nodeid=self.definition.nodeid,
  1160. )
  1161. del argvalues
  1162. if "request" in argnames:
  1163. fail(
  1164. "'request' is a reserved name and cannot be used in @pytest.mark.parametrize",
  1165. pytrace=False,
  1166. )
  1167. if scope is not None:
  1168. scope_ = Scope.from_user(
  1169. scope, descr=f"parametrize() call in {self.function.__name__}"
  1170. )
  1171. else:
  1172. scope_ = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)
  1173. self._validate_if_using_arg_names(argnames, indirect)
  1174. arg_values_types = self._resolve_arg_value_types(argnames, indirect)
  1175. # Use any already (possibly) generated ids with parametrize Marks.
  1176. if _param_mark and _param_mark._param_ids_from:
  1177. generated_ids = _param_mark._param_ids_from._param_ids_generated
  1178. if generated_ids is not None:
  1179. ids = generated_ids
  1180. ids = self._resolve_parameter_set_ids(
  1181. argnames, ids, parametersets, nodeid=self.definition.nodeid
  1182. )
  1183. # Store used (possibly generated) ids with parametrize Marks.
  1184. if _param_mark and _param_mark._param_ids_from and generated_ids is None:
  1185. object.__setattr__(_param_mark._param_ids_from, "_param_ids_generated", ids)
  1186. # Create the new calls: if we are parametrize() multiple times (by applying the decorator
  1187. # more than once) then we accumulate those calls generating the cartesian product
  1188. # of all calls.
  1189. newcalls = []
  1190. for callspec in self._calls or [CallSpec2()]:
  1191. for param_index, (param_id, param_set) in enumerate(
  1192. zip(ids, parametersets)
  1193. ):
  1194. newcallspec = callspec.setmulti(
  1195. valtypes=arg_values_types,
  1196. argnames=argnames,
  1197. valset=param_set.values,
  1198. id=param_id,
  1199. marks=param_set.marks,
  1200. scope=scope_,
  1201. param_index=param_index,
  1202. )
  1203. newcalls.append(newcallspec)
  1204. self._calls = newcalls
  1205. def _resolve_parameter_set_ids(
  1206. self,
  1207. argnames: Sequence[str],
  1208. ids: Optional[
  1209. Union[Iterable[Optional[object]], Callable[[Any], Optional[object]]]
  1210. ],
  1211. parametersets: Sequence[ParameterSet],
  1212. nodeid: str,
  1213. ) -> List[str]:
  1214. """Resolve the actual ids for the given parameter sets.
  1215. :param argnames:
  1216. Argument names passed to ``parametrize()``.
  1217. :param ids:
  1218. The `ids` parameter of the ``parametrize()`` call (see docs).
  1219. :param parametersets:
  1220. The parameter sets, each containing a set of values corresponding
  1221. to ``argnames``.
  1222. :param nodeid str:
  1223. The nodeid of the definition item that generated this
  1224. parametrization.
  1225. :returns:
  1226. List with ids for each parameter set given.
  1227. """
  1228. if ids is None:
  1229. idfn = None
  1230. ids_ = None
  1231. elif callable(ids):
  1232. idfn = ids
  1233. ids_ = None
  1234. else:
  1235. idfn = None
  1236. ids_ = self._validate_ids(ids, parametersets, self.function.__name__)
  1237. id_maker = IdMaker(
  1238. argnames,
  1239. parametersets,
  1240. idfn,
  1241. ids_,
  1242. self.config,
  1243. nodeid=nodeid,
  1244. func_name=self.function.__name__,
  1245. )
  1246. return id_maker.make_unique_parameterset_ids()
  1247. def _validate_ids(
  1248. self,
  1249. ids: Iterable[Optional[object]],
  1250. parametersets: Sequence[ParameterSet],
  1251. func_name: str,
  1252. ) -> List[Optional[object]]:
  1253. try:
  1254. num_ids = len(ids) # type: ignore[arg-type]
  1255. except TypeError:
  1256. try:
  1257. iter(ids)
  1258. except TypeError as e:
  1259. raise TypeError("ids must be a callable or an iterable") from e
  1260. num_ids = len(parametersets)
  1261. # num_ids == 0 is a special case: https://github.com/pytest-dev/pytest/issues/1849
  1262. if num_ids != len(parametersets) and num_ids != 0:
  1263. msg = "In {}: {} parameter sets specified, with different number of ids: {}"
  1264. fail(msg.format(func_name, len(parametersets), num_ids), pytrace=False)
  1265. return list(itertools.islice(ids, num_ids))
  1266. def _resolve_arg_value_types(
  1267. self,
  1268. argnames: Sequence[str],
  1269. indirect: Union[bool, Sequence[str]],
  1270. ) -> Dict[str, "Literal['params', 'funcargs']"]:
  1271. """Resolve if each parametrized argument must be considered a
  1272. parameter to a fixture or a "funcarg" to the function, based on the
  1273. ``indirect`` parameter of the parametrized() call.
  1274. :param List[str] argnames: List of argument names passed to ``parametrize()``.
  1275. :param indirect: Same as the ``indirect`` parameter of ``parametrize()``.
  1276. :rtype: Dict[str, str]
  1277. A dict mapping each arg name to either:
  1278. * "params" if the argname should be the parameter of a fixture of the same name.
  1279. * "funcargs" if the argname should be a parameter to the parametrized test function.
  1280. """
  1281. if isinstance(indirect, bool):
  1282. valtypes: Dict[str, Literal["params", "funcargs"]] = dict.fromkeys(
  1283. argnames, "params" if indirect else "funcargs"
  1284. )
  1285. elif isinstance(indirect, Sequence):
  1286. valtypes = dict.fromkeys(argnames, "funcargs")
  1287. for arg in indirect:
  1288. if arg not in argnames:
  1289. fail(
  1290. "In {}: indirect fixture '{}' doesn't exist".format(
  1291. self.function.__name__, arg
  1292. ),
  1293. pytrace=False,
  1294. )
  1295. valtypes[arg] = "params"
  1296. else:
  1297. fail(
  1298. "In {func}: expected Sequence or boolean for indirect, got {type}".format(
  1299. type=type(indirect).__name__, func=self.function.__name__
  1300. ),
  1301. pytrace=False,
  1302. )
  1303. return valtypes
  1304. def _validate_if_using_arg_names(
  1305. self,
  1306. argnames: Sequence[str],
  1307. indirect: Union[bool, Sequence[str]],
  1308. ) -> None:
  1309. """Check if all argnames are being used, by default values, or directly/indirectly.
  1310. :param List[str] argnames: List of argument names passed to ``parametrize()``.
  1311. :param indirect: Same as the ``indirect`` parameter of ``parametrize()``.
  1312. :raises ValueError: If validation fails.
  1313. """
  1314. default_arg_names = set(get_default_arg_names(self.function))
  1315. func_name = self.function.__name__
  1316. for arg in argnames:
  1317. if arg not in self.fixturenames:
  1318. if arg in default_arg_names:
  1319. fail(
  1320. "In {}: function already takes an argument '{}' with a default value".format(
  1321. func_name, arg
  1322. ),
  1323. pytrace=False,
  1324. )
  1325. else:
  1326. if isinstance(indirect, Sequence):
  1327. name = "fixture" if arg in indirect else "argument"
  1328. else:
  1329. name = "fixture" if indirect else "argument"
  1330. fail(
  1331. f"In {func_name}: function uses no {name} '{arg}'",
  1332. pytrace=False,
  1333. )
  1334. def _find_parametrized_scope(
  1335. argnames: Sequence[str],
  1336. arg2fixturedefs: Mapping[str, Sequence[fixtures.FixtureDef[object]]],
  1337. indirect: Union[bool, Sequence[str]],
  1338. ) -> Scope:
  1339. """Find the most appropriate scope for a parametrized call based on its arguments.
  1340. When there's at least one direct argument, always use "function" scope.
  1341. When a test function is parametrized and all its arguments are indirect
  1342. (e.g. fixtures), return the most narrow scope based on the fixtures used.
  1343. Related to issue #1832, based on code posted by @Kingdread.
  1344. """
  1345. if isinstance(indirect, Sequence):
  1346. all_arguments_are_fixtures = len(indirect) == len(argnames)
  1347. else:
  1348. all_arguments_are_fixtures = bool(indirect)
  1349. if all_arguments_are_fixtures:
  1350. fixturedefs = arg2fixturedefs or {}
  1351. used_scopes = [
  1352. fixturedef[0]._scope
  1353. for name, fixturedef in fixturedefs.items()
  1354. if name in argnames
  1355. ]
  1356. # Takes the most narrow scope from used fixtures.
  1357. return min(used_scopes, default=Scope.Function)
  1358. return Scope.Function
  1359. def _ascii_escaped_by_config(val: Union[str, bytes], config: Optional[Config]) -> str:
  1360. if config is None:
  1361. escape_option = False
  1362. else:
  1363. escape_option = config.getini(
  1364. "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
  1365. )
  1366. # TODO: If escaping is turned off and the user passes bytes,
  1367. # will return a bytes. For now we ignore this but the
  1368. # code *probably* doesn't handle this case.
  1369. return val if escape_option else ascii_escaped(val) # type: ignore
  1370. def _pretty_fixture_path(func) -> str:
  1371. cwd = Path.cwd()
  1372. loc = Path(getlocation(func, str(cwd)))
  1373. prefix = Path("...", "_pytest")
  1374. try:
  1375. return str(prefix / loc.relative_to(_PYTEST_DIR))
  1376. except ValueError:
  1377. return bestrelpath(cwd, loc)
  1378. def show_fixtures_per_test(config):
  1379. from _pytest.main import wrap_session
  1380. return wrap_session(config, _show_fixtures_per_test)
  1381. def _show_fixtures_per_test(config: Config, session: Session) -> None:
  1382. import _pytest.config
  1383. session.perform_collect()
  1384. curdir = Path.cwd()
  1385. tw = _pytest.config.create_terminal_writer(config)
  1386. verbose = config.getvalue("verbose")
  1387. def get_best_relpath(func) -> str:
  1388. loc = getlocation(func, str(curdir))
  1389. return bestrelpath(curdir, Path(loc))
  1390. def write_fixture(fixture_def: fixtures.FixtureDef[object]) -> None:
  1391. argname = fixture_def.argname
  1392. if verbose <= 0 and argname.startswith("_"):
  1393. return
  1394. prettypath = _pretty_fixture_path(fixture_def.func)
  1395. tw.write(f"{argname}", green=True)
  1396. tw.write(f" -- {prettypath}", yellow=True)
  1397. tw.write("\n")
  1398. fixture_doc = inspect.getdoc(fixture_def.func)
  1399. if fixture_doc:
  1400. write_docstring(
  1401. tw, fixture_doc.split("\n\n")[0] if verbose <= 0 else fixture_doc
  1402. )
  1403. else:
  1404. tw.line(" no docstring available", red=True)
  1405. def write_item(item: nodes.Item) -> None:
  1406. # Not all items have _fixtureinfo attribute.
  1407. info: Optional[FuncFixtureInfo] = getattr(item, "_fixtureinfo", None)
  1408. if info is None or not info.name2fixturedefs:
  1409. # This test item does not use any fixtures.
  1410. return
  1411. tw.line()
  1412. tw.sep("-", f"fixtures used by {item.name}")
  1413. # TODO: Fix this type ignore.
  1414. tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined]
  1415. # dict key not used in loop but needed for sorting.
  1416. for _, fixturedefs in sorted(info.name2fixturedefs.items()):
  1417. assert fixturedefs is not None
  1418. if not fixturedefs:
  1419. continue
  1420. # Last item is expected to be the one used by the test item.
  1421. write_fixture(fixturedefs[-1])
  1422. for session_item in session.items:
  1423. write_item(session_item)
  1424. def showfixtures(config: Config) -> Union[int, ExitCode]:
  1425. from _pytest.main import wrap_session
  1426. return wrap_session(config, _showfixtures_main)
  1427. def _showfixtures_main(config: Config, session: Session) -> None:
  1428. import _pytest.config
  1429. session.perform_collect()
  1430. curdir = Path.cwd()
  1431. tw = _pytest.config.create_terminal_writer(config)
  1432. verbose = config.getvalue("verbose")
  1433. fm = session._fixturemanager
  1434. available = []
  1435. seen: Set[Tuple[str, str]] = set()
  1436. for argname, fixturedefs in fm._arg2fixturedefs.items():
  1437. assert fixturedefs is not None
  1438. if not fixturedefs:
  1439. continue
  1440. for fixturedef in fixturedefs:
  1441. loc = getlocation(fixturedef.func, str(curdir))
  1442. if (fixturedef.argname, loc) in seen:
  1443. continue
  1444. seen.add((fixturedef.argname, loc))
  1445. available.append(
  1446. (
  1447. len(fixturedef.baseid),
  1448. fixturedef.func.__module__,
  1449. _pretty_fixture_path(fixturedef.func),
  1450. fixturedef.argname,
  1451. fixturedef,
  1452. )
  1453. )
  1454. available.sort()
  1455. currentmodule = None
  1456. for baseid, module, prettypath, argname, fixturedef in available:
  1457. if currentmodule != module:
  1458. if not module.startswith("_pytest."):
  1459. tw.line()
  1460. tw.sep("-", f"fixtures defined from {module}")
  1461. currentmodule = module
  1462. if verbose <= 0 and argname.startswith("_"):
  1463. continue
  1464. tw.write(f"{argname}", green=True)
  1465. if fixturedef.scope != "function":
  1466. tw.write(" [%s scope]" % fixturedef.scope, cyan=True)
  1467. tw.write(f" -- {prettypath}", yellow=True)
  1468. tw.write("\n")
  1469. doc = inspect.getdoc(fixturedef.func)
  1470. if doc:
  1471. write_docstring(tw, doc.split("\n\n")[0] if verbose <= 0 else doc)
  1472. else:
  1473. tw.line(" no docstring available", red=True)
  1474. tw.line()
  1475. def write_docstring(tw: TerminalWriter, doc: str, indent: str = " ") -> None:
  1476. for line in doc.split("\n"):
  1477. tw.line(indent + line)
  1478. class Function(PyobjMixin, nodes.Item):
  1479. """Item responsible for setting up and executing a Python test function.
  1480. :param name:
  1481. The full function name, including any decorations like those
  1482. added by parametrization (``my_func[my_param]``).
  1483. :param parent:
  1484. The parent Node.
  1485. :param config:
  1486. The pytest Config object.
  1487. :param callspec:
  1488. If given, this is function has been parametrized and the callspec contains
  1489. meta information about the parametrization.
  1490. :param callobj:
  1491. If given, the object which will be called when the Function is invoked,
  1492. otherwise the callobj will be obtained from ``parent`` using ``originalname``.
  1493. :param keywords:
  1494. Keywords bound to the function object for "-k" matching.
  1495. :param session:
  1496. The pytest Session object.
  1497. :param fixtureinfo:
  1498. Fixture information already resolved at this fixture node..
  1499. :param originalname:
  1500. The attribute name to use for accessing the underlying function object.
  1501. Defaults to ``name``. Set this if name is different from the original name,
  1502. for example when it contains decorations like those added by parametrization
  1503. (``my_func[my_param]``).
  1504. """
  1505. # Disable since functions handle it themselves.
  1506. _ALLOW_MARKERS = False
  1507. def __init__(
  1508. self,
  1509. name: str,
  1510. parent,
  1511. config: Optional[Config] = None,
  1512. callspec: Optional[CallSpec2] = None,
  1513. callobj=NOTSET,
  1514. keywords: Optional[Mapping[str, Any]] = None,
  1515. session: Optional[Session] = None,
  1516. fixtureinfo: Optional[FuncFixtureInfo] = None,
  1517. originalname: Optional[str] = None,
  1518. ) -> None:
  1519. super().__init__(name, parent, config=config, session=session)
  1520. if callobj is not NOTSET:
  1521. self.obj = callobj
  1522. #: Original function name, without any decorations (for example
  1523. #: parametrization adds a ``"[...]"`` suffix to function names), used to access
  1524. #: the underlying function object from ``parent`` (in case ``callobj`` is not given
  1525. #: explicitly).
  1526. #:
  1527. #: .. versionadded:: 3.0
  1528. self.originalname = originalname or name
  1529. # Note: when FunctionDefinition is introduced, we should change ``originalname``
  1530. # to a readonly property that returns FunctionDefinition.name.
  1531. self.own_markers.extend(get_unpacked_marks(self.obj))
  1532. if callspec:
  1533. self.callspec = callspec
  1534. self.own_markers.extend(callspec.marks)
  1535. # todo: this is a hell of a hack
  1536. # https://github.com/pytest-dev/pytest/issues/4569
  1537. # Note: the order of the updates is important here; indicates what
  1538. # takes priority (ctor argument over function attributes over markers).
  1539. # Take own_markers only; NodeKeywords handles parent traversal on its own.
  1540. self.keywords.update((mark.name, mark) for mark in self.own_markers)
  1541. self.keywords.update(self.obj.__dict__)
  1542. if keywords:
  1543. self.keywords.update(keywords)
  1544. if fixtureinfo is None:
  1545. fixtureinfo = self.session._fixturemanager.getfixtureinfo(
  1546. self, self.obj, self.cls, funcargs=True
  1547. )
  1548. self._fixtureinfo: FuncFixtureInfo = fixtureinfo
  1549. self.fixturenames = fixtureinfo.names_closure
  1550. self._initrequest()
  1551. @classmethod
  1552. def from_parent(cls, parent, **kw): # todo: determine sound type limitations
  1553. """The public constructor."""
  1554. return super().from_parent(parent=parent, **kw)
  1555. def _initrequest(self) -> None:
  1556. self.funcargs: Dict[str, object] = {}
  1557. self._request = fixtures.FixtureRequest(self, _ispytest=True)
  1558. @property
  1559. def function(self):
  1560. """Underlying python 'function' object."""
  1561. return getimfunc(self.obj)
  1562. def _getobj(self):
  1563. assert self.parent is not None
  1564. if isinstance(self.parent, Class):
  1565. # Each Function gets a fresh class instance.
  1566. parent_obj = self.parent.newinstance()
  1567. else:
  1568. parent_obj = self.parent.obj # type: ignore[attr-defined]
  1569. return getattr(parent_obj, self.originalname)
  1570. @property
  1571. def _pyfuncitem(self):
  1572. """(compatonly) for code expecting pytest-2.2 style request objects."""
  1573. return self
  1574. def runtest(self) -> None:
  1575. """Execute the underlying test function."""
  1576. self.ihook.pytest_pyfunc_call(pyfuncitem=self)
  1577. def setup(self) -> None:
  1578. self._request._fillfixtures()
  1579. def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
  1580. if hasattr(self, "_obj") and not self.config.getoption("fulltrace", False):
  1581. code = _pytest._code.Code.from_function(get_real_func(self.obj))
  1582. path, firstlineno = code.path, code.firstlineno
  1583. traceback = excinfo.traceback
  1584. ntraceback = traceback.cut(path=path, firstlineno=firstlineno)
  1585. if ntraceback == traceback:
  1586. ntraceback = ntraceback.cut(path=path)
  1587. if ntraceback == traceback:
  1588. ntraceback = ntraceback.filter(filter_traceback)
  1589. if not ntraceback:
  1590. ntraceback = traceback
  1591. ntraceback = ntraceback.filter(excinfo)
  1592. # issue364: mark all but first and last frames to
  1593. # only show a single-line message for each frame.
  1594. if self.config.getoption("tbstyle", "auto") == "auto":
  1595. if len(ntraceback) > 2:
  1596. ntraceback = Traceback(
  1597. entry
  1598. if i == 0 or i == len(ntraceback) - 1
  1599. else entry.with_repr_style("short")
  1600. for i, entry in enumerate(ntraceback)
  1601. )
  1602. return ntraceback
  1603. return excinfo.traceback
  1604. # TODO: Type ignored -- breaks Liskov Substitution.
  1605. def repr_failure( # type: ignore[override]
  1606. self,
  1607. excinfo: ExceptionInfo[BaseException],
  1608. ) -> Union[str, TerminalRepr]:
  1609. style = self.config.getoption("tbstyle", "auto")
  1610. if style == "auto":
  1611. style = "long"
  1612. return self._repr_failure_py(excinfo, style=style)
  1613. class FunctionDefinition(Function):
  1614. """This class is a stop gap solution until we evolve to have actual function
  1615. definition nodes and manage to get rid of ``metafunc``."""
  1616. def runtest(self) -> None:
  1617. raise RuntimeError("function definitions are not supposed to be run as tests")
  1618. setup = runtest