Debian Codegraph @

src/_pytest/python.py

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