Debian Codegraph @

src/_pytest/mark/__init__.py

raw
1 """Generic mechanism for marking and selecting python functions."""
2
3 from __future__ import annotations
4
5 import collections
6 from collections.abc import Collection
7 from collections.abc import Iterable
8 from collections.abc import Set as AbstractSet
9 import dataclasses
10 from typing import TYPE_CHECKING
11
12 from .expression import Expression
13 from .structures import _HiddenParam
14 from .structures import EMPTY_PARAMETERSET_OPTION
15 from .structures import get_empty_parameterset_mark
16 from .structures import HIDDEN_PARAM
17 from .structures import Mark
18 from .structures import MARK_GEN
19 from .structures import MarkDecorator
20 from .structures import MarkGenerator
21 from .structures import ParameterSet
22 from _pytest.compat import NOTSET
23 from _pytest.config import Config
24 from _pytest.config import ExitCode
25 from _pytest.config import hookimpl
26 from _pytest.config import UsageError
27 from _pytest.config.argparsing import Parser
28 from _pytest.stash import StashKey
29
30
31 if TYPE_CHECKING:
32 from _pytest.nodes import Item
33
34
35 __all__ = [
36 "HIDDEN_PARAM",
37 "MARK_GEN",
38 "Mark",
39 "MarkDecorator",
40 "MarkGenerator",
41 "ParameterSet",
42 "get_empty_parameterset_mark",
43 ]
44
45
46 old_mark_config_key = StashKey[Config | None]()
47
48
49 def param(
50 *values: object,
51 marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),
52 id: str | _HiddenParam | None = None,
53 ) -> ParameterSet:
54 """Specify a parameter in `pytest.mark.parametrize`_ calls or
55 :ref:`parametrized fixtures <fixture-parametrize-marks>`.
56
57 .. code-block:: python
58
59 @pytest.mark.parametrize(
60 "test_input,expected",
61 [
62 ("3+5", 8),
63 pytest.param("6*9", 42, marks=pytest.mark.xfail),
64 ],
65 )
66 def test_eval(test_input, expected):
67 assert eval(test_input) == expected
68
69 :param values: Variable args of the values of the parameter set, in order.
70
71 :param marks:
72 A single mark or a list of marks to be applied to this parameter set.
73
74 :ref:`pytest.mark.usefixtures <pytest.mark.usefixtures ref>` cannot be added via this parameter.
75
76 :type id: str | Literal[pytest.HIDDEN_PARAM] | None
77 :param id:
78 The id to attribute to this parameter set.
79
80 .. versionadded:: 8.4
81 :ref:`hidden-param` means to hide the parameter set
82 from the test name. Can only be used at most 1 time, as
83 test names need to be unique.
84 """
85 return ParameterSet.param(*values, marks=marks, id=id)
86
87
88 def pytest_addoption(parser: Parser) -> None:
89 group = parser.getgroup("general")
90 group._addoption( # private to use reserved lower-case short option
91 "-k",
92 action="store",
93 dest="keyword",
94 default="",
95 metavar="EXPRESSION",
96 help="Only run tests which match the given substring expression. "
97 "An expression is a Python evaluable expression "
98 "where all names are substring-matched against test names "
99 "and their parent classes. Example: -k 'test_method or test_"
100 "other' matches all test functions and classes whose name "
101 "contains 'test_method' or 'test_other', while -k 'not test_method' "
102 "matches those that don't contain 'test_method' in their names. "
103 "-k 'not test_method and not test_other' will eliminate the matches. "
104 "Additionally keywords are matched to classes and functions "
105 "containing extra names in their 'extra_keyword_matches' set, "
106 "as well as functions which have names assigned directly to them. "
107 "The matching is case-insensitive.",
108 )
109
110 group._addoption( # private to use reserved lower-case short option
111 "-m",
112 action="store",
113 dest="markexpr",
114 default="",
115 metavar="MARKEXPR",
116 help="Only run tests matching given mark expression. "
117 "For example: -m 'mark1 and not mark2'.",
118 )
119
120 group.addoption(
121 "--markers",
122 action="store_true",
123 help="show markers (builtin, plugin and per-project ones).",
124 )
125
126 parser.addini("markers", "Register new markers for test functions", "linelist")
127 parser.addini(EMPTY_PARAMETERSET_OPTION, "Default marker for empty parametersets")
128
129
130 @hookimpl(tryfirst=True)
131 def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
132 import _pytest.config
133
134 if config.option.markers:
135 config._do_configure()
136 tw = _pytest.config.create_terminal_writer(config)
137 for line in config.getini("markers"):
138 parts = line.split(":", 1)
139 name = parts[0]
140 rest = parts[1] if len(parts) == 2 else ""
141 tw.write(f"@pytest.mark.{name}:", bold=True)
142 tw.line(rest)
143 tw.line()
144 config._ensure_unconfigure()
145 return 0
146
147 return None
148
149
150 @dataclasses.dataclass
151 class KeywordMatcher:
152 """A matcher for keywords.
153
154 Given a list of names, matches any substring of one of these names. The
155 string inclusion check is case-insensitive.
156
157 Will match on the name of colitem, including the names of its parents.
158 Only matches names of items which are either a :class:`Class` or a
159 :class:`Function`.
160
161 Additionally, matches on names in the 'extra_keyword_matches' set of
162 any item, as well as names directly assigned to test functions.
163 """
164
165 __slots__ = ("_names",)
166
167 _names: AbstractSet[str]
168
169 @classmethod
170 def from_item(cls, item: Item) -> KeywordMatcher:
171 mapped_names = set()
172
173 # Add the names of the current item and any parent items,
174 # except the Session and root Directory's which are not
175 # interesting for matching.
176 import pytest
177
178 for node in item.listchain():
179 if isinstance(node, pytest.Session):
180 continue
181 if isinstance(node, pytest.Directory) and isinstance(
182 node.parent, pytest.Session
183 ):
184 continue
185 mapped_names.add(node.name)
186
187 # Add the names added as extra keywords to current or parent items.
188 mapped_names.update(item.listextrakeywords())
189
190 # Add the names attached to the current function through direct assignment.
191 function_obj = getattr(item, "function", None)
192 if function_obj:
193 mapped_names.update(function_obj.__dict__)
194
195 # Add the markers to the keywords as we no longer handle them correctly.
196 mapped_names.update(mark.name for mark in item.iter_markers())
197
198 return cls(mapped_names)
199
200 def __call__(self, subname: str, /, **kwargs: str | int | bool | None) -> bool:
201 if kwargs:
202 raise UsageError("Keyword expressions do not support call parameters.")
203 subname = subname.lower()
204 return any(subname in name.lower() for name in self._names)
205
206
207 def deselect_by_keyword(items: list[Item], config: Config) -> None:
208 keywordexpr = config.option.keyword.lstrip()
209 if not keywordexpr:
210 return
211
212 expr = _parse_expression(keywordexpr, "Wrong expression passed to '-k'")
213
214 remaining = []
215 deselected = []
216 for colitem in items:
217 if not expr.evaluate(KeywordMatcher.from_item(colitem)):
218 deselected.append(colitem)
219 else:
220 remaining.append(colitem)
221
222 if deselected:
223 config.hook.pytest_deselected(items=deselected)
224 items[:] = remaining
225
226
227 @dataclasses.dataclass
228 class MarkMatcher:
229 """A matcher for markers which are present.
230
231 Tries to match on any marker names, attached to the given colitem.
232 """
233
234 __slots__ = ("own_mark_name_mapping",)
235
236 own_mark_name_mapping: dict[str, list[Mark]]
237
238 @classmethod
239 def from_markers(cls, markers: Iterable[Mark]) -> MarkMatcher:
240 mark_name_mapping = collections.defaultdict(list)
241 for mark in markers:
242 mark_name_mapping[mark.name].append(mark)
243 return cls(mark_name_mapping)
244
245 def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool:
246 if not (matches := self.own_mark_name_mapping.get(name, [])):
247 return False
248
249 for mark in matches: # pylint: disable=consider-using-any-or-all
250 if all(mark.kwargs.get(k, NOTSET) == v for k, v in kwargs.items()):
251 return True
252 return False
253
254
255 def deselect_by_mark(items: list[Item], config: Config) -> None:
256 matchexpr = config.option.markexpr
257 if not matchexpr:
258 return
259
260 expr = _parse_expression(matchexpr, "Wrong expression passed to '-m'")
261 remaining: list[Item] = []
262 deselected: list[Item] = []
263 for item in items:
264 if expr.evaluate(MarkMatcher.from_markers(item.iter_markers())):
265 remaining.append(item)
266 else:
267 deselected.append(item)
268 if deselected:
269 config.hook.pytest_deselected(items=deselected)
270 items[:] = remaining
271
272
273 def _parse_expression(expr: str, exc_message: str) -> Expression:
274 try:
275 return Expression.compile(expr)
276 except SyntaxError as e:
277 raise UsageError(
278 f"{exc_message}: {e.text}: at column {e.offset}: {e.msg}"
279 ) from None
280
281
282 def pytest_collection_modifyitems(items: list[Item], config: Config) -> None:
283 deselect_by_keyword(items, config)
284 deselect_by_mark(items, config)
285
286
287 def pytest_configure(config: Config) -> None:
288 config.stash[old_mark_config_key] = MARK_GEN._config
289 MARK_GEN._config = config
290
291 empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION)
292
293 if empty_parameterset not in ("skip", "xfail", "fail_at_collect", None, ""):
294 raise UsageError(
295 f"{EMPTY_PARAMETERSET_OPTION!s} must be one of skip, xfail or fail_at_collect"
296 f" but it is {empty_parameterset!r}"
297 )
298
299
300 def pytest_unconfigure(config: Config) -> None:
301 MARK_GEN._config = config.stash.get(old_mark_config_key, None)