structures.py 20 KB

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