2Utilities for attaching typed marks to pytest fixture functions
3and querying those marks during a test session.
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.
9Marks are independent of `@pytest.fixture`: apply the mark to the
10original function, then wrap with `@pytest.fixture`.
12@ingroup userver_testsuite
13@see @ref scripts/docs/en/userver/fixture_markers.md
16from __future__
import annotations
21from dataclasses
import dataclass
26from typing
import cast
27from typing
import Generic
28from typing
import TypeVar
33 from _pytest.fixtures
import is_visibility_more_specific
35 is_visibility_more_specific =
None
44_MARKS_ATTR =
'_testsuite_fixture_marks'
45_MARKS_ORDER_ATTR =
'_testsuite_fixture_marks_order'
46_mark_order_counter = itertools.count()
56@dataclass(frozen=True)
58 origin: pytest.FixtureDef[object]
65 func: Callable[..., object],
68) -> Callable[..., object]:
70 Attach *info* to the original function *func*.
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.
76 *func* must be the original function, not a `@pytest.fixture`
77 wrapper. Apply the mark under `@pytest.fixture`.
79 @see @ref scripts/docs/en/userver/fixture_markers.md
81 @param func The original fixture function.
82 @param info Metadata instance to store.
83 @returns *func*, unchanged.
85 if _is_pytest_fixture_wrapper(func):
86 name = getattr(func,
'__qualname__', func.__name__)
88 f
'{name!r} is already wrapped by @pytest.fixture; apply the mark under @pytest.fixture, not above it',
91 marks = getattr(func, _MARKS_ATTR,
None)
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__)
99 f
'{name!r} already has a {info_type.__name__} mark ({existing!r}); cannot attach another ({info!r})',
101 marks[info_type] = info
104 if getattr(func, _MARKS_ORDER_ATTR,
None)
is None:
105 setattr(func, _MARKS_ORDER_ATTR, next(_mark_order_counter))
110 request: pytest.FixtureRequest,
115 Return marked fixtures of *info_type* that are visible to a request.
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.
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.
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.
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.
136 @see @ref scripts/docs/en/userver/fixture_markers.md
138 @param request The pytest fixture request object.
139 @param info_type The info class whose tagged fixtures you want
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
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
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
162 key=functools.cmp_to_key(
163 lambda lhs, rhs: _cmp_marked_fixtures(lhs, rhs, plugin_key_order),
166 return {item.name: item.info
for item
in collected}
169def _is_pytest_fixture_wrapper(func: object) -> bool:
170 if getattr(func,
'_pytestfixturefunction',
None):
172 return type(func).__name__ ==
'FixtureFunctionDefinition'
176 fixture_manager: Any,
179) -> Sequence[pytest.FixtureDef[object]] |
None:
180 return fixture_manager.getfixturedefs(name, key)
183def _iter_visible_fixtures(
184 request: pytest.FixtureRequest,
186) -> Iterator[pytest.FixtureDef[object]]:
187 fixture_manager = request.session._fixturemanager
188 invoking_rank = _SCOPE_RANK[request.scope]
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())
195 fixture_names = fixture_manager._arg2fixturedefs
197 for name
in fixture_names:
198 matched = _get_fixturedefs(fixture_manager, name, key)
201 winning = matched[-1]
202 if _SCOPE_RANK[winning.scope] < invoking_rank:
207def _marked_fixture_for_name(
208 request: pytest.FixtureRequest,
212) -> _MarkedFixture[I] |
None:
213 fixture_manager = request.session._fixturemanager
214 matched = _get_fixturedefs(fixture_manager, name, key)
217 info = _inherited_info(matched, info_type)
220 origin = next(fixturedef
for fixturedef
in matched
if _mark_info(fixturedef, info_type)
is not None)
223 stamp=getattr(origin.func, _MARKS_ORDER_ATTR),
230 matched: Sequence[pytest.FixtureDef[object]],
234 for fixturedef
in reversed(matched):
235 info = _mark_info(fixturedef, info_type)
241def _cmp_from_lt(a: Any, b: Any) -> int:
242 return (a > b) - (a < b)
245def _cmp_marked_fixtures(
246 left: _MarkedFixture[Any],
247 right: _MarkedFixture[Any],
248 plugin_key_order: dict[str, int],
251 site = _cmp_sites(left.origin, right.origin)
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)
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
270 left: pytest.FixtureDef[object],
271 right: pytest.FixtureDef[object],
273 more_specific = is_visibility_more_specific
or _legacy_more_specific
274 if more_specific(left, right):
276 if more_specific(right, left):
281def _legacy_more_specific(
282 candidate: pytest.FixtureDef[object],
283 other: pytest.FixtureDef[object],
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):
291 if inner == outer
or _is_nested_baseid(inner, outer):
293 raise AssertionError(
294 f
'expected nested fixture baseids, got {inner!r} and {outer!r}',
298def _has_location(fixturedef: pytest.FixtureDef[object]) -> bool:
299 return bool(getattr(fixturedef,
'_has_location', fixturedef.has_location))
302def _is_nested_baseid(prefix: str, full: str) -> bool:
303 return prefix != full
and (prefix ==
'' or (full.startswith(prefix)
and full[len(prefix)]
in '/:'))
307 fixturedef: pytest.FixtureDef[object],
310 marks = getattr(fixturedef.func, _MARKS_ATTR,
None)
313 info = marks.get(info_type)
314 if type(info)
is info_type: