aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/pytest-lazy-fixtures/pytest_lazy_fixtures/lazy_fixture.py
blob: 28fc00d52999b07cb14c4427c3c9b12d40afe495 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from dataclasses import dataclass
from operator import attrgetter
from typing import Optional

import pytest


@dataclass
class LazyFixtureWrapper:
    name: str

    @property
    def fixture_name(self) -> str:
        return self.name.split(".", maxsplit=1)[0]

    def _get_attr(self, fixture) -> Optional[str]:
        splitted = self.name.split(".", maxsplit=1)
        if len(splitted) == 1:
            return fixture
        return attrgetter(splitted[1])(fixture)

    def __repr__(self) -> str:
        return self.name

    def load_fixture(self, request: pytest.FixtureRequest):
        return self._get_attr(request.getfixturevalue(self.fixture_name))

    def __hash__(self) -> int:
        return hash(self.name)


def lf(name: str) -> LazyFixtureWrapper:
    """lf is a lazy fixture."""
    return LazyFixtureWrapper(name)