python.py 66 KB

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