python.py 65 KB

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