userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/fixture_markers.py Source File
Loading...
Searching...
No Matches
fixture_markers.py
1"""
2Utilities for attaching typed marks to pytest fixture functions
3and querying those marks during a test session.
4
5Use @ref pytest_userver.fixture_markers.mark to store an info object on the original function.
6Use @ref pytest_userver.fixture_markers.get_infos to retrieve fixtures tagged with a particular
7info type among those visible to a request.
8
9Marks are independent of `@pytest.fixture`: apply the mark to the
10original function, then wrap with `@pytest.fixture`.
11
12@ingroup userver_testsuite
13@see @ref scripts/docs/en/userver/fixture_markers.md
14"""
15
16from __future__ import annotations
17
18from collections.abc import Callable
19from collections.abc import Iterator
20from collections.abc import Sequence
21from dataclasses import dataclass
22import functools
23import inspect
24import itertools
25from typing import Any
26from typing import cast
27from typing import Generic
28from typing import TypeVar
29
30import pytest
31
32try:
33 from _pytest.fixtures import is_visibility_more_specific
34except ImportError: # pragma: no cover
35 is_visibility_more_specific = None
36
37__all__ = [
38 'get_infos',
39 'mark',
40]
41
42I = TypeVar('I') # noqa: E741
43
44_MARKS_ATTR = '_testsuite_fixture_marks'
45_MARKS_ORDER_ATTR = '_testsuite_fixture_marks_order'
46_mark_order_counter = itertools.count()
47_SCOPE_RANK = {
48 'function': 0,
49 'class': 1,
50 'module': 2,
51 'package': 3,
52 'session': 4,
53}
54
55
56@dataclass(frozen=True)
57class _MarkedFixture(Generic[I]):
58 origin: pytest.FixtureDef[object]
59 stamp: int
60 name: str
61 info: I
62
63
64def mark(
65 func: Callable[..., object],
66 info: object,
67 /,
68) -> Callable[..., object]:
69 """
70 Attach *info* to the original function *func*.
71
72 Creates the marks dict if it is missing, otherwise updates it.
73 The *info* type is the lookup key for @ref pytest_userver.fixture_markers.get_infos. Each type
74 may be attached at most once.
75
76 *func* must be the original function, not a `@pytest.fixture`
77 wrapper. Apply the mark under `@pytest.fixture`.
78
79 @see @ref scripts/docs/en/userver/fixture_markers.md
80
81 @param func The original fixture function.
82 @param info Metadata instance to store.
83 @returns *func*, unchanged.
84 """
85 if _is_pytest_fixture_wrapper(func):
86 name = getattr(func, '__qualname__', func.__name__)
87 raise ValueError(
88 f'{name!r} is already wrapped by @pytest.fixture; apply the mark under @pytest.fixture, not above it',
89 )
90
91 marks = getattr(func, _MARKS_ATTR, None)
92 if marks is None:
93 marks = {}
94 setattr(func, _MARKS_ATTR, marks)
95 info_type = type(info)
96 if (existing := marks.get(info_type)) is not None:
97 name = getattr(func, '__qualname__', func.__name__)
98 raise ValueError(
99 f'{name!r} already has a {info_type.__name__} mark ({existing!r}); cannot attach another ({info!r})',
100 )
101 marks[info_type] = info
102 # Decorations run in definition order within a module; pytest later
103 # registers fixtures via dir(), which is alphabetical — stamp order here.
104 if getattr(func, _MARKS_ORDER_ATTR, None) is None:
105 setattr(func, _MARKS_ORDER_ATTR, next(_mark_order_counter))
106 return func
107
108
110 request: pytest.FixtureRequest,
111 info_type: type[I],
112 /,
113) -> dict[str, I]:
114 """
115 Return marked fixtures of *info_type* that are visible to a request.
116
117 Walks fixture definitions known to pytest, keeps those applicable to
118 the requesting test, and skips fixtures whose scope is narrower than
119 `request.scope`. Metadata is matched by its exact type, not subclasses.
120 Discovery does not execute fixtures or require them to be test arguments.
121
122 The winning fixture definition is the one pytest would call. If it
123 has no mark of *info_type*, the mark is inherited from the nearest
124 overridden definition that has one. A mark on the winner replaces
125 the inherited mark. There is no way to drop an inherited mark.
126
127 Fixtures within a single module are ordered by definition order. An
128 override takes the position of the original fixture in that order — it
129 is inserted in place of the fixture it overrides.
130
131 Fixtures from different modules follow the usual pytest definition-site
132 priorities: non-conftest plugins (registration order), then conftest
133 modules from outer to inner (less specific first, same as pytest
134 override chains), then test modules, then test classes.
135
136 @see @ref scripts/docs/en/userver/fixture_markers.md
137
138 @param request The pytest fixture request object.
139 @param info_type The info class whose tagged fixtures you want
140 to look up.
141 @returns `dict[str, I]` mapping each tagged fixture's name to the
142 *info* object that was passed to @ref pytest_userver.fixture_markers.mark.
143 The dict is a fresh copy; mutating it has no effect on stored
144 data.
145 """
146 fixture_manager = request.session._fixturemanager
147 item = request._pyfuncitem
148 params = inspect.signature(fixture_manager.getfixturedefs).parameters
149 key = item if list(params)[1] == 'node' else item.nodeid
150
151 collected: list[_MarkedFixture[I]] = []
152 for fixturedef in _iter_visible_fixtures(request, key):
153 marked = _marked_fixture_for_name(request, fixturedef.argname, info_type, key)
154 if marked is not None:
155 collected.append(marked)
156 plugin_key_order: dict[str, int] = {}
157 for i, item in enumerate(collected):
158 pk = _plugin_key(item.origin.func)
159 if pk not in plugin_key_order:
160 plugin_key_order[pk] = i
161 collected.sort(
162 key=functools.cmp_to_key(
163 lambda lhs, rhs: _cmp_marked_fixtures(lhs, rhs, plugin_key_order),
164 ),
165 )
166 return {item.name: item.info for item in collected}
167
168
169def _is_pytest_fixture_wrapper(func: object) -> bool:
170 if getattr(func, '_pytestfixturefunction', None):
171 return True
172 return type(func).__name__ == 'FixtureFunctionDefinition'
173
174
175def _get_fixturedefs(
176 fixture_manager: Any,
177 name: str,
178 key: Any,
179) -> Sequence[pytest.FixtureDef[object]] | None:
180 return fixture_manager.getfixturedefs(name, key)
181
182
183def _iter_visible_fixtures(
184 request: pytest.FixtureRequest,
185 key: Any,
186) -> Iterator[pytest.FixtureDef[object]]:
187 fixture_manager = request.session._fixturemanager
188 invoking_rank = _SCOPE_RANK[request.scope]
189
190 # pytest 9.2 splits node-based and legacy nodeid-based registrations.
191 get_all_fixture_defs = getattr(fixture_manager, '_get_all_fixture_defs', None)
192 if get_all_fixture_defs is not None:
193 fixture_names = dict.fromkeys(fixturedef.argname for fixturedef in get_all_fixture_defs())
194 else:
195 fixture_names = fixture_manager._arg2fixturedefs
196
197 for name in fixture_names:
198 matched = _get_fixturedefs(fixture_manager, name, key)
199 if not matched:
200 continue
201 winning = matched[-1]
202 if _SCOPE_RANK[winning.scope] < invoking_rank:
203 continue
204 yield winning
205
206
207def _marked_fixture_for_name(
208 request: pytest.FixtureRequest,
209 name: str,
210 info_type: type[I],
211 key: Any,
212) -> _MarkedFixture[I] | None:
213 fixture_manager = request.session._fixturemanager
214 matched = _get_fixturedefs(fixture_manager, name, key)
215 if not matched:
216 return None
217 info = _inherited_info(matched, info_type)
218 if info is None:
219 return None
220 origin = next(fixturedef for fixturedef in matched if _mark_info(fixturedef, info_type) is not None)
221 return _MarkedFixture(
222 origin=origin,
223 stamp=getattr(origin.func, _MARKS_ORDER_ATTR),
224 name=name,
225 info=info,
226 )
227
228
229def _inherited_info(
230 matched: Sequence[pytest.FixtureDef[object]],
231 info_type: type[I],
232) -> I | None:
233 # matched is ordered from the least specific definition to the winner.
234 for fixturedef in reversed(matched):
235 info = _mark_info(fixturedef, info_type)
236 if info is not None:
237 return info
238 return None
239
240
241def _cmp_from_lt(a: Any, b: Any) -> int:
242 return (a > b) - (a < b)
243
244
245def _cmp_marked_fixtures(
246 left: _MarkedFixture[Any],
247 right: _MarkedFixture[Any],
248 plugin_key_order: dict[str, int],
249) -> int:
250 # Less specific definition site first.
251 site = _cmp_sites(left.origin, right.origin)
252 if site:
253 return site
254 # Same site: order by plugin registration, then by decoration stamp.
255 left_key = _plugin_key(left.origin.func)
256 right_key = _plugin_key(right.origin.func)
257 if left_key != right_key:
258 return _cmp_from_lt(plugin_key_order[left_key], plugin_key_order[right_key])
259 return _cmp_from_lt(left.stamp, right.stamp)
260
261
262def _plugin_key(func: Any) -> str:
263 module: str = getattr(func, '__module__', '') or ''
264 qualname: str = getattr(func, '__qualname__', '') or ''
265 class_part = qualname.rsplit('.', 1)[0] if '.' in qualname else ''
266 return f'{module}.{class_part}' if class_part else module
267
268
269def _cmp_sites(
270 left: pytest.FixtureDef[object],
271 right: pytest.FixtureDef[object],
272) -> int:
273 more_specific = is_visibility_more_specific or _legacy_more_specific
274 if more_specific(left, right):
275 return 1
276 if more_specific(right, left):
277 return -1
278 return 0
279
280
281def _legacy_more_specific(
282 candidate: pytest.FixtureDef[object],
283 other: pytest.FixtureDef[object],
284) -> bool:
285 # pytest without is_visibility_more_specific: plugins, then outer → inner.
286 if _has_location(candidate) != _has_location(other):
287 return _has_location(candidate)
288 inner, outer = candidate.baseid, other.baseid
289 if _is_nested_baseid(outer, inner):
290 return True
291 if inner == outer or _is_nested_baseid(inner, outer):
292 return False
293 raise AssertionError(
294 f'expected nested fixture baseids, got {inner!r} and {outer!r}',
295 )
296
297
298def _has_location(fixturedef: pytest.FixtureDef[object]) -> bool:
299 return bool(getattr(fixturedef, '_has_location', fixturedef.has_location))
300
301
302def _is_nested_baseid(prefix: str, full: str) -> bool:
303 return prefix != full and (prefix == '' or (full.startswith(prefix) and full[len(prefix)] in '/:'))
304
305
306def _mark_info(
307 fixturedef: pytest.FixtureDef[object],
308 info_type: type[I],
309) -> I | None:
310 marks = getattr(fixturedef.func, _MARKS_ATTR, None)
311 if not marks:
312 return None
313 info = marks.get(info_type)
314 if type(info) is info_type:
315 return cast(I, info)
316 return None