lazy_fixture.py 839 B

12345678910111213141516171819202122232425262728293031323334
  1. from dataclasses import dataclass
  2. from operator import attrgetter
  3. from typing import Optional
  4. import pytest
  5. @dataclass
  6. class LazyFixtureWrapper:
  7. name: str
  8. @property
  9. def fixture_name(self) -> str:
  10. return self.name.split(".", maxsplit=1)[0]
  11. def _get_attr(self, fixture) -> Optional[str]:
  12. splitted = self.name.split(".", maxsplit=1)
  13. if len(splitted) == 1:
  14. return fixture
  15. return attrgetter(splitted[1])(fixture)
  16. def __repr__(self) -> str:
  17. return self.name
  18. def load_fixture(self, request: pytest.FixtureRequest):
  19. return self._get_attr(request.getfixturevalue(self.fixture_name))
  20. def __hash__(self) -> int:
  21. return hash(self.name)
  22. def lf(name: str) -> LazyFixtureWrapper:
  23. """lf is a lazy fixture."""
  24. return LazyFixtureWrapper(name)