Skip to content

Instantly share code, notes, and snippets.

@zhukovgreen
Created June 8, 2022 10:38
Show Gist options
  • Save zhukovgreen/d2ed02db735c2722666c269a00b2cfca to your computer and use it in GitHub Desktop.
Save zhukovgreen/d2ed02db735c2722666c269a00b2cfca to your computer and use it in GitHub Desktop.
Dependency injection for functions
import functools
import inspect
from typing import Any, Callable, Dict
import pytest
class feature:
fixtures: Dict[str, Callable[[], Any]] = {}
@classmethod
def register(cls, fn):
cls.fixtures[fn.__name__] = fn
@functools.wraps(fn)
def fn_wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return fn_wrapper
@classmethod
def inject(cls, fn):
@functools.wraps(fn)
def wrapper_fn(*args, **kwargs):
for param in inspect.signature(fn).parameters:
try:
kwargs[param] = cls.fixtures[param]
except KeyError:
pass
return fn(*args, **kwargs)
return wrapper_fn
def test_feature_should_work():
@feature.register
def my_feature():
return "my feature"
@feature.inject
def some_function(
text,
my_feature=None,
):
return f"{text} {my_feature()}"
actual = some_function("hello")
assert "hello my feature" == actual
@feature.inject
def some_other_function(
text,
wrong_name_feature=None,
):
return f"{text} {wrong_name_feature()}"
with pytest.raises(TypeError, match="object is not callable"):
some_other_function("hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment