Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/python.py

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