userver: Fixture markers
Loading...
Searching...
No Matches
Fixture markers

pytest_userver.fixture_markers lets plugins and tests attach typed metadata to fixture functions and discover marked fixtures visible to a pytest request. The implementation belongs to userver and only depends on pytest fixture definitions; it does not require a running service.

For the common userver use cases, prefer the existing decorators:

For custom discovery, such as database initializers or mock setup, use pytest_userver.fixture_markers.mark and pytest_userver.fixture_markers.get_infos directly as described below. See also Functional service tests (testsuite).

Marking a fixture

Apply the mark to the original function, below the pytest fixture decorator. pytest_userver.fixture_markers.mark returns the same function without executing or wrapping it. Applying it above the fixture decorator is an error.

Each exact metadata type can be attached only once to a function; a duplicate raises ValueError. Distinct metadata types can coexist on the same function. Metadata subclasses are independent types, not matches for their base class.

The following example defines metadata and a decorator for initialization priority. To keep the example self-contained, the fixtures record initialized table names in a list rather than connecting to a database.

import dataclasses
import pytest
from pytest_userver import fixture_markers
@dataclasses.dataclass(frozen=True)
class PgInitializer:
order: int
def pg_init(*, order: int = 0):
def decorate(function):
return fixture_markers.mark(function, PgInitializer(order=order))
return decorate

Both ordinary and explicitly named fixtures can carry the mark:

@pytest.fixture
@pg_init(order=1)
def init_users(initialized_tables):
initialized_tables.append('users')
@pytest.fixture(name='init_orders')
@pg_init(order=2)
def _init_orders(initialized_tables):
initialized_tables.append('orders')

Querying marks

pytest_userver.fixture_markers.get_infos returns a dictionary mapping effective pytest fixture names to metadata, including fixture aliases. It includes fixtures that:

  • are visible to the requesting test: a plugin, an ancestor conftest, the test module, or its class; unrelated modules, sibling classes, and child conftests are excluded;
  • carry or inherit metadata of the exact requested type;
  • have a winning definition whose scope is at least as wide as the request. In increasing scope order: function, class, module, package, session.

Discovery does not execute fixtures. Fixtures need not appear among the test's arguments to be discovered. The consumer explicitly requests their values when needed. Each query returns a fresh dictionary; changing its entries does not change stored metadata. Metadata objects themselves are not deep-copied.

def test_initializers(request, initialized_tables):
initializers = fixture_markers.get_infos(request, PgInitializer)
assert initialized_tables == [] # Discovery does not execute fixtures.
assert initializers == {
'init_users': PgInitializer(order=1),
'init_orders': PgInitializer(order=2),
}
# A consumer can choose an explicit priority instead of definition order.
for name, info in sorted(initializers.items(), key=lambda item: item[1].order):
request.getfixturevalue(name)
assert initialized_tables == ['users', 'orders']

The explicit priority sort in this example is a consumer policy, not behavior of pytest_userver.fixture_markers.get_infos. Without that sort, the dictionary uses the definition order described below.

Overriding a marked fixture

An override inherits the mark. There is no need to repeat pytest_userver.config.patch, pytest_userver.service.dependency, or a custom marker decorator on an overriding fixture.

pytest_userver.fixture_markers.get_infos examines the definition pytest would call. If it has no metadata of the requested type, discovery searches the override chain from nearest to farthest and uses the first matching mark. Metadata inheritance is independent for each type.

The following test-class override extends the marked module fixture above. The same rule applies when a module fixture overrides a conftest or plugin fixture:

@pytest.fixture
def init_users(self, init_users, initialized_tables):
initialized_tables.append('guests')
def test_inherited_mark(self, request, initialized_tables):
infos = fixture_markers.get_infos(request, PgInitializer)
assert infos['init_users'] == PgInitializer(order=1)
request.getfixturevalue('init_users')
assert initialized_tables == ['users', 'guests']

Requesting the original fixture is optional. An override may replace its behavior entirely and still inherit the mark. Normal pytest lookup always executes the winning override, not the original implementation merely because it owns the metadata.

A mark on the override replaces metadata of that type. Other metadata types remain inherited. The following override replaces both metadata and fixture behavior, while keeping its original dictionary position:

@pytest.fixture
@pg_init(order=10)
def init_users(self, initialized_tables):
initialized_tables.append('replacement-users')
def test_replaced_mark(self, request, initialized_tables):
infos = fixture_markers.get_infos(request, PgInitializer)
assert infos['init_users'] == PgInitializer(order=10)
# Replacing metadata does not move the fixture's original position.
assert list(infos) == ['init_users', 'init_orders']
request.getfixturevalue('init_users')
assert initialized_tables == ['replacement-users']
Note
An unmarked override cannot remove an inherited mark. There is no unmark operation. Narrowing the override's scope can exclude it from a wider-scoped request, but does not remove its metadata.

Ordering guarantees

The result of pytest_userver.fixture_markers.get_infos is ordered:

  1. Definition sites follow pytest visibility: non-conftest plugins, ancestor conftests from outer to inner, the test module, then the test class.
  2. Within a module, fixtures follow definition/decorator order, not alphabetical fixture-name order. Non-conftest plugins follow registration order.
  3. An override retains the position of the first marked definition of the requested metadata type. Repeating a marker to replace metadata does not move that fixture to the overriding module's or class's position.

Thus metadata can come from the nearest marked override while the ordering position comes from the original marked definition. A fixture name appears only once in the result.

Using markers with userver

pytest_userver.config.patch and pytest_userver.service.dependency use these inheritance and discovery rules. Both must be applied below the pytest fixture decorator. A config-patch fixture returns a callable accepting the static config and config variables; a service-dependency fixture performs its setup when requested before service startup.

Legacy config-hook lists and pytest_userver.plugins.service.extra_client_deps remain supported. Legacy USERVER_CONFIG_HOOKS run before all marked config patches, including the built-in userver patches. Hooks passed through uservice_oneshot(config_hooks=...) run last.

To run a custom patch after the built-in HTTP client, logging, or other config patches, apply pytest_userver.config.patch below its @pytest.fixture decorator and remove its name from USERVER_CONFIG_HOOKS. Keep the fixture session-scoped and define it in a conftest that covers the affected tests. Within that conftest, define marked fixtures in their required execution order.

An override of a fixture registered only through a legacy hook list does not inherit a marker: legacy registration and marker discovery are distinct. Overrides of built-in marked fixtures inherit their markers and keep their original positions; do not also list those overrides in USERVER_CONFIG_HOOKS, which would apply them twice.

API reference


Adapted from the upstream testsuite fixture-marker guide for userver's implementation and Doxygen documentation.