structures.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. # mypy: allow-untyped-defs
  2. from __future__ import annotations
  3. import collections.abc
  4. from collections.abc import Callable
  5. from collections.abc import Collection
  6. from collections.abc import Iterable
  7. from collections.abc import Iterator
  8. from collections.abc import Mapping
  9. from collections.abc import MutableMapping
  10. from collections.abc import Sequence
  11. import dataclasses
  12. import enum
  13. import inspect
  14. from typing import Any
  15. from typing import final
  16. from typing import NamedTuple
  17. from typing import overload
  18. from typing import TYPE_CHECKING
  19. from typing import TypeVar
  20. from typing import Union
  21. import warnings
  22. from .._code import getfslineno
  23. from ..compat import NOTSET
  24. from ..compat import NotSetType
  25. from _pytest.config import Config
  26. from _pytest.deprecated import check_ispytest
  27. from _pytest.deprecated import MARKED_FIXTURE
  28. from _pytest.outcomes import fail
  29. from _pytest.raises import AbstractRaises
  30. from _pytest.scope import _ScopeName
  31. from _pytest.warning_types import PytestUnknownMarkWarning
  32. if TYPE_CHECKING:
  33. from ..nodes import Node
  34. EMPTY_PARAMETERSET_OPTION = "empty_parameter_set_mark"
  35. # Singleton type for HIDDEN_PARAM, as described in:
  36. # https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
  37. class _HiddenParam(enum.Enum):
  38. token = 0
  39. #: Can be used as a parameter set id to hide it from the test name.
  40. HIDDEN_PARAM = _HiddenParam.token
  41. def istestfunc(func) -> bool:
  42. return callable(func) and getattr(func, "__name__", "<lambda>") != "<lambda>"
  43. def get_empty_parameterset_mark(
  44. config: Config, argnames: Sequence[str], func
  45. ) -> MarkDecorator:
  46. from ..nodes import Collector
  47. argslisting = ", ".join(argnames)
  48. fs, lineno = getfslineno(func)
  49. reason = f"got empty parameter set for ({argslisting})"
  50. requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)
  51. if requested_mark in ("", None, "skip"):
  52. mark = MARK_GEN.skip(reason=reason)
  53. elif requested_mark == "xfail":
  54. mark = MARK_GEN.xfail(reason=reason, run=False)
  55. elif requested_mark == "fail_at_collect":
  56. raise Collector.CollectError(
  57. f"Empty parameter set in '{func.__name__}' at line {lineno + 1}"
  58. )
  59. else:
  60. raise LookupError(requested_mark)
  61. return mark
  62. class ParameterSet(NamedTuple):
  63. """A set of values for a set of parameters along with associated marks and
  64. an optional ID for the set.
  65. Examples::
  66. pytest.param(1, 2, 3)
  67. # ParameterSet(values=(1, 2, 3), marks=(), id=None)
  68. pytest.param("hello", id="greeting")
  69. # ParameterSet(values=("hello",), marks=(), id="greeting")
  70. # Parameter set with marks
  71. pytest.param(42, marks=pytest.mark.xfail)
  72. # ParameterSet(values=(42,), marks=(MarkDecorator(...),), id=None)
  73. # From parametrize mark (parameter names + list of parameter sets)
  74. pytest.mark.parametrize(
  75. ("a", "b", "expected"),
  76. [
  77. (1, 2, 3),
  78. pytest.param(40, 2, 42, id="everything"),
  79. ],
  80. )
  81. # ParameterSet(values=(1, 2, 3), marks=(), id=None)
  82. # ParameterSet(values=(2, 2, 3), marks=(), id="everything")
  83. """
  84. values: Sequence[object | NotSetType]
  85. marks: Collection[MarkDecorator | Mark]
  86. id: str | _HiddenParam | None
  87. @classmethod
  88. def param(
  89. cls,
  90. *values: object,
  91. marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),
  92. id: str | _HiddenParam | None = None,
  93. ) -> ParameterSet:
  94. if isinstance(marks, MarkDecorator):
  95. marks = (marks,)
  96. else:
  97. assert isinstance(marks, collections.abc.Collection)
  98. if any(i.name == "usefixtures" for i in marks):
  99. raise ValueError(
  100. "pytest.param cannot add pytest.mark.usefixtures; see "
  101. "https://docs.pytest.org/en/stable/reference/reference.html#pytest-param"
  102. )
  103. if id is not None:
  104. if not isinstance(id, str) and id is not HIDDEN_PARAM:
  105. raise TypeError(
  106. "Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, "
  107. f"got {type(id)}: {id!r}",
  108. )
  109. return cls(values, marks, id)
  110. @classmethod
  111. def extract_from(
  112. cls,
  113. parameterset: ParameterSet | Sequence[object] | object,
  114. force_tuple: bool = False,
  115. ) -> ParameterSet:
  116. """Extract from an object or objects.
  117. :param parameterset:
  118. A legacy style parameterset that may or may not be a tuple,
  119. and may or may not be wrapped into a mess of mark objects.
  120. :param force_tuple:
  121. Enforce tuple wrapping so single argument tuple values
  122. don't get decomposed and break tests.
  123. """
  124. if isinstance(parameterset, cls):
  125. return parameterset
  126. if force_tuple:
  127. return cls.param(parameterset)
  128. else:
  129. # TODO: Refactor to fix this type-ignore. Currently the following
  130. # passes type-checking but crashes:
  131. #
  132. # @pytest.mark.parametrize(('x', 'y'), [1, 2])
  133. # def test_foo(x, y): pass
  134. return cls(parameterset, marks=[], id=None) # type: ignore[arg-type]
  135. @staticmethod
  136. def _parse_parametrize_args(
  137. argnames: str | Sequence[str],
  138. argvalues: Iterable[ParameterSet | Sequence[object] | object],
  139. *args,
  140. **kwargs,
  141. ) -> tuple[Sequence[str], bool]:
  142. if isinstance(argnames, str):
  143. argnames = [x.strip() for x in argnames.split(",") if x.strip()]
  144. force_tuple = len(argnames) == 1
  145. else:
  146. force_tuple = False
  147. return argnames, force_tuple
  148. @staticmethod
  149. def _parse_parametrize_parameters(
  150. argvalues: Iterable[ParameterSet | Sequence[object] | object],
  151. force_tuple: bool,
  152. ) -> list[ParameterSet]:
  153. return [
  154. ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues
  155. ]
  156. @classmethod
  157. def _for_parametrize(
  158. cls,
  159. argnames: str | Sequence[str],
  160. argvalues: Iterable[ParameterSet | Sequence[object] | object],
  161. func,
  162. config: Config,
  163. nodeid: str,
  164. ) -> tuple[Sequence[str], list[ParameterSet]]:
  165. argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
  166. parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
  167. del argvalues
  168. if parameters:
  169. # Check all parameter sets have the correct number of values.
  170. for param in parameters:
  171. if len(param.values) != len(argnames):
  172. msg = (
  173. '{nodeid}: in "parametrize" the number of names ({names_len}):\n'
  174. " {names}\n"
  175. "must be equal to the number of values ({values_len}):\n"
  176. " {values}"
  177. )
  178. fail(
  179. msg.format(
  180. nodeid=nodeid,
  181. values=param.values,
  182. names=argnames,
  183. names_len=len(argnames),
  184. values_len=len(param.values),
  185. ),
  186. pytrace=False,
  187. )
  188. else:
  189. # Empty parameter set (likely computed at runtime): create a single
  190. # parameter set with NOTSET values, with the "empty parameter set" mark applied to it.
  191. mark = get_empty_parameterset_mark(config, argnames, func)
  192. parameters.append(
  193. ParameterSet(
  194. values=(NOTSET,) * len(argnames), marks=[mark], id="NOTSET"
  195. )
  196. )
  197. return argnames, parameters
  198. @final
  199. @dataclasses.dataclass(frozen=True)
  200. class Mark:
  201. """A pytest mark."""
  202. #: Name of the mark.
  203. name: str
  204. #: Positional arguments of the mark decorator.
  205. args: tuple[Any, ...]
  206. #: Keyword arguments of the mark decorator.
  207. kwargs: Mapping[str, Any]
  208. #: Source Mark for ids with parametrize Marks.
  209. _param_ids_from: Mark | None = dataclasses.field(default=None, repr=False)
  210. #: Resolved/generated ids with parametrize Marks.
  211. _param_ids_generated: Sequence[str] | None = dataclasses.field(
  212. default=None, repr=False
  213. )
  214. def __init__(
  215. self,
  216. name: str,
  217. args: tuple[Any, ...],
  218. kwargs: Mapping[str, Any],
  219. param_ids_from: Mark | None = None,
  220. param_ids_generated: Sequence[str] | None = None,
  221. *,
  222. _ispytest: bool = False,
  223. ) -> None:
  224. """:meta private:"""
  225. check_ispytest(_ispytest)
  226. # Weirdness to bypass frozen=True.
  227. object.__setattr__(self, "name", name)
  228. object.__setattr__(self, "args", args)
  229. object.__setattr__(self, "kwargs", kwargs)
  230. object.__setattr__(self, "_param_ids_from", param_ids_from)
  231. object.__setattr__(self, "_param_ids_generated", param_ids_generated)
  232. def _has_param_ids(self) -> bool:
  233. return "ids" in self.kwargs or len(self.args) >= 4
  234. def combined_with(self, other: Mark) -> Mark:
  235. """Return a new Mark which is a combination of this
  236. Mark and another Mark.
  237. Combines by appending args and merging kwargs.
  238. :param Mark other: The mark to combine with.
  239. :rtype: Mark
  240. """
  241. assert self.name == other.name
  242. # Remember source of ids with parametrize Marks.
  243. param_ids_from: Mark | None = None
  244. if self.name == "parametrize":
  245. if other._has_param_ids():
  246. param_ids_from = other
  247. elif self._has_param_ids():
  248. param_ids_from = self
  249. return Mark(
  250. self.name,
  251. self.args + other.args,
  252. dict(self.kwargs, **other.kwargs),
  253. param_ids_from=param_ids_from,
  254. _ispytest=True,
  255. )
  256. # A generic parameter designating an object to which a Mark may
  257. # be applied -- a test function (callable) or class.
  258. # Note: a lambda is not allowed, but this can't be represented.
  259. Markable = TypeVar("Markable", bound=Union[Callable[..., object], type])
  260. @dataclasses.dataclass
  261. class MarkDecorator:
  262. """A decorator for applying a mark on test functions and classes.
  263. ``MarkDecorators`` are created with ``pytest.mark``::
  264. mark1 = pytest.mark.NAME # Simple MarkDecorator
  265. mark2 = pytest.mark.NAME(name1=value) # Parametrized MarkDecorator
  266. and can then be applied as decorators to test functions::
  267. @mark2
  268. def test_function():
  269. pass
  270. When a ``MarkDecorator`` is called, it does the following:
  271. 1. If called with a single class as its only positional argument and no
  272. additional keyword arguments, it attaches the mark to the class so it
  273. gets applied automatically to all test cases found in that class.
  274. 2. If called with a single function as its only positional argument and
  275. no additional keyword arguments, it attaches the mark to the function,
  276. containing all the arguments already stored internally in the
  277. ``MarkDecorator``.
  278. 3. When called in any other case, it returns a new ``MarkDecorator``
  279. instance with the original ``MarkDecorator``'s content updated with
  280. the arguments passed to this call.
  281. Note: The rules above prevent a ``MarkDecorator`` from storing only a
  282. single function or class reference as its positional argument with no
  283. additional keyword or positional arguments. You can work around this by
  284. using `with_args()`.
  285. """
  286. mark: Mark
  287. def __init__(self, mark: Mark, *, _ispytest: bool = False) -> None:
  288. """:meta private:"""
  289. check_ispytest(_ispytest)
  290. self.mark = mark
  291. @property
  292. def name(self) -> str:
  293. """Alias for mark.name."""
  294. return self.mark.name
  295. @property
  296. def args(self) -> tuple[Any, ...]:
  297. """Alias for mark.args."""
  298. return self.mark.args
  299. @property
  300. def kwargs(self) -> Mapping[str, Any]:
  301. """Alias for mark.kwargs."""
  302. return self.mark.kwargs
  303. @property
  304. def markname(self) -> str:
  305. """:meta private:"""
  306. return self.name # for backward-compat (2.4.1 had this attr)
  307. def with_args(self, *args: object, **kwargs: object) -> MarkDecorator:
  308. """Return a MarkDecorator with extra arguments added.
  309. Unlike calling the MarkDecorator, with_args() can be used even
  310. if the sole argument is a callable/class.
  311. """
  312. mark = Mark(self.name, args, kwargs, _ispytest=True)
  313. return MarkDecorator(self.mark.combined_with(mark), _ispytest=True)
  314. # Type ignored because the overloads overlap with an incompatible
  315. # return type. Not much we can do about that. Thankfully mypy picks
  316. # the first match so it works out even if we break the rules.
  317. @overload
  318. def __call__(self, arg: Markable) -> Markable: # type: ignore[overload-overlap]
  319. pass
  320. @overload
  321. def __call__(self, *args: object, **kwargs: object) -> MarkDecorator:
  322. pass
  323. def __call__(self, *args: object, **kwargs: object):
  324. """Call the MarkDecorator."""
  325. if args and not kwargs:
  326. func = args[0]
  327. is_class = inspect.isclass(func)
  328. # For staticmethods/classmethods, the marks are eventually fetched from the
  329. # function object, not the descriptor, so unwrap.
  330. unwrapped_func = func
  331. if isinstance(func, (staticmethod, classmethod)):
  332. unwrapped_func = func.__func__
  333. if len(args) == 1 and (istestfunc(unwrapped_func) or is_class):
  334. store_mark(unwrapped_func, self.mark, stacklevel=3)
  335. return func
  336. return self.with_args(*args, **kwargs)
  337. def get_unpacked_marks(
  338. obj: object | type,
  339. *,
  340. consider_mro: bool = True,
  341. ) -> list[Mark]:
  342. """Obtain the unpacked marks that are stored on an object.
  343. If obj is a class and consider_mro is true, return marks applied to
  344. this class and all of its super-classes in MRO order. If consider_mro
  345. is false, only return marks applied directly to this class.
  346. """
  347. if isinstance(obj, type):
  348. if not consider_mro:
  349. mark_lists = [obj.__dict__.get("pytestmark", [])]
  350. else:
  351. mark_lists = [
  352. x.__dict__.get("pytestmark", []) for x in reversed(obj.__mro__)
  353. ]
  354. mark_list = []
  355. for item in mark_lists:
  356. if isinstance(item, list):
  357. mark_list.extend(item)
  358. else:
  359. mark_list.append(item)
  360. else:
  361. mark_attribute = getattr(obj, "pytestmark", [])
  362. if isinstance(mark_attribute, list):
  363. mark_list = mark_attribute
  364. else:
  365. mark_list = [mark_attribute]
  366. return list(normalize_mark_list(mark_list))
  367. def normalize_mark_list(
  368. mark_list: Iterable[Mark | MarkDecorator],
  369. ) -> Iterable[Mark]:
  370. """
  371. Normalize an iterable of Mark or MarkDecorator objects into a list of marks
  372. by retrieving the `mark` attribute on MarkDecorator instances.
  373. :param mark_list: marks to normalize
  374. :returns: A new list of the extracted Mark objects
  375. """
  376. for mark in mark_list:
  377. mark_obj = getattr(mark, "mark", mark)
  378. if not isinstance(mark_obj, Mark):
  379. raise TypeError(f"got {mark_obj!r} instead of Mark")
  380. yield mark_obj
  381. def store_mark(obj, mark: Mark, *, stacklevel: int = 2) -> None:
  382. """Store a Mark on an object.
  383. This is used to implement the Mark declarations/decorators correctly.
  384. """
  385. assert isinstance(mark, Mark), mark
  386. from ..fixtures import getfixturemarker
  387. if getfixturemarker(obj) is not None:
  388. warnings.warn(MARKED_FIXTURE, stacklevel=stacklevel)
  389. # Always reassign name to avoid updating pytestmark in a reference that
  390. # was only borrowed.
  391. obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark]
  392. # Typing for builtin pytest marks. This is cheating; it gives builtin marks
  393. # special privilege, and breaks modularity. But practicality beats purity...
  394. if TYPE_CHECKING:
  395. class _SkipMarkDecorator(MarkDecorator):
  396. @overload # type: ignore[override,no-overload-impl]
  397. def __call__(self, arg: Markable) -> Markable: ...
  398. @overload
  399. def __call__(self, reason: str = ...) -> MarkDecorator: ...
  400. class _SkipifMarkDecorator(MarkDecorator):
  401. def __call__( # type: ignore[override]
  402. self,
  403. condition: str | bool = ...,
  404. *conditions: str | bool,
  405. reason: str = ...,
  406. ) -> MarkDecorator: ...
  407. class _XfailMarkDecorator(MarkDecorator):
  408. @overload # type: ignore[override,no-overload-impl]
  409. def __call__(self, arg: Markable) -> Markable: ...
  410. @overload
  411. def __call__(
  412. self,
  413. condition: str | bool = False,
  414. *conditions: str | bool,
  415. reason: str = ...,
  416. run: bool = ...,
  417. raises: None
  418. | type[BaseException]
  419. | tuple[type[BaseException], ...]
  420. | AbstractRaises[BaseException] = ...,
  421. strict: bool = ...,
  422. ) -> MarkDecorator: ...
  423. class _ParametrizeMarkDecorator(MarkDecorator):
  424. def __call__( # type: ignore[override]
  425. self,
  426. argnames: str | Sequence[str],
  427. argvalues: Iterable[ParameterSet | Sequence[object] | object],
  428. *,
  429. indirect: bool | Sequence[str] = ...,
  430. ids: Iterable[None | str | float | int | bool]
  431. | Callable[[Any], object | None]
  432. | None = ...,
  433. scope: _ScopeName | None = ...,
  434. ) -> MarkDecorator: ...
  435. class _UsefixturesMarkDecorator(MarkDecorator):
  436. def __call__(self, *fixtures: str) -> MarkDecorator: # type: ignore[override]
  437. ...
  438. class _FilterwarningsMarkDecorator(MarkDecorator):
  439. def __call__(self, *filters: str) -> MarkDecorator: # type: ignore[override]
  440. ...
  441. @final
  442. class MarkGenerator:
  443. """Factory for :class:`MarkDecorator` objects - exposed as
  444. a ``pytest.mark`` singleton instance.
  445. Example::
  446. import pytest
  447. @pytest.mark.slowtest
  448. def test_function():
  449. pass
  450. applies a 'slowtest' :class:`Mark` on ``test_function``.
  451. """
  452. # See TYPE_CHECKING above.
  453. if TYPE_CHECKING:
  454. skip: _SkipMarkDecorator
  455. skipif: _SkipifMarkDecorator
  456. xfail: _XfailMarkDecorator
  457. parametrize: _ParametrizeMarkDecorator
  458. usefixtures: _UsefixturesMarkDecorator
  459. filterwarnings: _FilterwarningsMarkDecorator
  460. def __init__(self, *, _ispytest: bool = False) -> None:
  461. check_ispytest(_ispytest)
  462. self._config: Config | None = None
  463. self._markers: set[str] = set()
  464. def __getattr__(self, name: str) -> MarkDecorator:
  465. """Generate a new :class:`MarkDecorator` with the given name."""
  466. if name[0] == "_":
  467. raise AttributeError("Marker name must NOT start with underscore")
  468. if self._config is not None:
  469. # We store a set of markers as a performance optimisation - if a mark
  470. # name is in the set we definitely know it, but a mark may be known and
  471. # not in the set. We therefore start by updating the set!
  472. if name not in self._markers:
  473. for line in self._config.getini("markers"):
  474. # example lines: "skipif(condition): skip the given test if..."
  475. # or "hypothesis: tests which use Hypothesis", so to get the
  476. # marker name we split on both `:` and `(`.
  477. marker = line.split(":")[0].split("(")[0].strip()
  478. self._markers.add(marker)
  479. # If the name is not in the set of known marks after updating,
  480. # then it really is time to issue a warning or an error.
  481. if name not in self._markers:
  482. if self._config.option.strict_markers or self._config.option.strict:
  483. fail(
  484. f"{name!r} not found in `markers` configuration option",
  485. pytrace=False,
  486. )
  487. # Raise a specific error for common misspellings of "parametrize".
  488. if name in ["parameterize", "parametrise", "parameterise"]:
  489. __tracebackhide__ = True
  490. fail(f"Unknown '{name}' mark, did you mean 'parametrize'?")
  491. warnings.warn(
  492. f"Unknown pytest.mark.{name} - is this a typo? You can register "
  493. "custom marks to avoid this warning - for details, see "
  494. "https://docs.pytest.org/en/stable/how-to/mark.html",
  495. PytestUnknownMarkWarning,
  496. 2,
  497. )
  498. return MarkDecorator(Mark(name, (), {}, _ispytest=True), _ispytest=True)
  499. MARK_GEN = MarkGenerator(_ispytest=True)
  500. @final
  501. class NodeKeywords(MutableMapping[str, Any]):
  502. __slots__ = ("_markers", "node", "parent")
  503. def __init__(self, node: Node) -> None:
  504. self.node = node
  505. self.parent = node.parent
  506. self._markers = {node.name: True}
  507. def __getitem__(self, key: str) -> Any:
  508. try:
  509. return self._markers[key]
  510. except KeyError:
  511. if self.parent is None:
  512. raise
  513. return self.parent.keywords[key]
  514. def __setitem__(self, key: str, value: Any) -> None:
  515. self._markers[key] = value
  516. # Note: we could've avoided explicitly implementing some of the methods
  517. # below and use the collections.abc fallback, but that would be slow.
  518. def __contains__(self, key: object) -> bool:
  519. return key in self._markers or (
  520. self.parent is not None and key in self.parent.keywords
  521. )
  522. def update( # type: ignore[override]
  523. self,
  524. other: Mapping[str, Any] | Iterable[tuple[str, Any]] = (),
  525. **kwds: Any,
  526. ) -> None:
  527. self._markers.update(other)
  528. self._markers.update(kwds)
  529. def __delitem__(self, key: str) -> None:
  530. raise ValueError("cannot delete key in keywords dict")
  531. def __iter__(self) -> Iterator[str]:
  532. # Doesn't need to be fast.
  533. yield from self._markers
  534. if self.parent is not None:
  535. for keyword in self.parent.keywords:
  536. # self._marks and self.parent.keywords can have duplicates.
  537. if keyword not in self._markers:
  538. yield keyword
  539. def __len__(self) -> int:
  540. # Doesn't need to be fast.
  541. return sum(1 for keyword in self)
  542. def __repr__(self) -> str:
  543. return f"<NodeKeywords for node {self.node}>"