Created
June 8, 2022 10:38
-
-
Save zhukovgreen/d2ed02db735c2722666c269a00b2cfca to your computer and use it in GitHub Desktop.
Dependency injection for functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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