lazy_fixture_callable.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from inspect import isfunction
  2. from typing import Callable, Optional, Union
  3. import pytest
  4. from .lazy_fixture import LazyFixtureWrapper
  5. class LazyFixtureCallableWrapper(LazyFixtureWrapper):
  6. _func: Optional[Callable]
  7. args: tuple
  8. kwargs: dict
  9. def __init__(self, callable_or_name: Union[Callable, str], *args, **kwargs):
  10. if callable(callable_or_name):
  11. self._func = callable_or_name
  12. self.name = (
  13. callable_or_name.__name__ if isfunction(callable_or_name) else callable_or_name.__class__.__name__
  14. )
  15. else:
  16. self.name = callable_or_name
  17. self._func = None
  18. self.args = args
  19. self.kwargs = kwargs
  20. def get_func(self, request: pytest.FixtureRequest) -> Callable:
  21. func = self._func
  22. if func is None:
  23. func = self.load_fixture(request)
  24. assert callable(func)
  25. return func
  26. def lfc(name: Union[Callable, str], *args, **kwargs) -> LazyFixtureCallableWrapper:
  27. """lfc is a lazy fixture callable."""
  28. return LazyFixtureCallableWrapper(name, *args, **kwargs)