From 8e565076d669035413e181e9755422de0caa33db Mon Sep 17 00:00:00 2001 From: Vasily <89313005745@mail.ru> Date: Mon, 31 Jul 2023 23:32:59 +0300 Subject: [PATCH] Raise `AsyncDependencyForbiddenError ` on async function provided as a dependency (#11) * Raise `AsyncDependencyProvided` on async function provided as dependency. * `AsyncDependencyForbiddenError` on injector.register if dep is async --------- Co-authored-by: isaev-vs --- giveme/injector.py | 6 ++++++ tests.py | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/giveme/injector.py b/giveme/injector.py index 1c18fc8..618238b 100644 --- a/giveme/injector.py +++ b/giveme/injector.py @@ -10,6 +10,10 @@ class DependencyNotFoundError(Exception): pass +class AsyncDependencyForbiddenError(Exception): + pass + + class DependencyNotFoundWarning(RuntimeWarning): pass @@ -83,6 +87,8 @@ def _set(self, name, factory, singleton=False, threadlocal=False): Same functionality as ``singleton`` except :class:`Threading.local` is used to cache return values. """ + if iscoroutinefunction(factory): + raise AsyncDependencyForbiddenError(name) name = name or factory.__name__ factory._giveme_registered_name = name dep = Dependency(name, factory, singleton, threadlocal) diff --git a/tests.py b/tests.py index ca73a47..d7dc208 100644 --- a/tests.py +++ b/tests.py @@ -5,6 +5,7 @@ from multiprocessing.pool import ThreadPool from giveme import register, inject, DependencyNotFoundError +from giveme.injector import AsyncDependencyForbiddenError def test_inject(): @@ -236,6 +237,10 @@ def simple_dep(): return 42 +async def async_simple_dep(): + return 566 + + def double_dep(simple_dep): return simple_dep*2 @@ -451,3 +456,9 @@ def f(list_dep): with pytest.raises(TypeError): f() + + +@pytest.mark.asyncio +async def test_inject_async_dep(gm): + with pytest.raises(AsyncDependencyForbiddenError): + gm.register(async_simple_dep)