structures.py 21 KB

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