You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1690 lines
63KB

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