python.py 67 KB

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