From 9d4edf00899296def23cb0e46ec0ef69e1c59ab6 Mon Sep 17 00:00:00 2001 From: Mani Mozaffar Date: Thu, 23 May 2024 20:11:58 +0200 Subject: [PATCH] Implemented external API to run functions with dependency being injected (#12) * Add external API on aioclock to run any task with deps injected * Add test --- aioclock/__init__.py | 3 ++- aioclock/app.py | 27 +++++++++++++++++++++++++++ tests/test_di.py | 21 +++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 tests/test_di.py diff --git a/aioclock/__init__.py b/aioclock/__init__.py index 3f20e48..8b72b3f 100644 --- a/aioclock/__init__.py +++ b/aioclock/__init__.py @@ -1,6 +1,6 @@ from fast_depends import Depends -from .app import AioClock +from .app import AioClock, run_with_injected_deps from .group import Group from .triggers import At, Every, Forever, Once, OnShutDown, OnStartUp @@ -14,4 +14,5 @@ "Group", "AioClock", "At", + "run_with_injected_deps", ] diff --git a/aioclock/app.py b/aioclock/app.py index 3ddd218..8d6829b 100644 --- a/aioclock/app.py +++ b/aioclock/app.py @@ -178,3 +178,30 @@ async def serve(self) -> None: finally: shutdown_tasks = self._get_shutdown_task() await asyncio.gather(*(task.run() for task in shutdown_tasks), return_exceptions=False) + + +async def run_with_injected_deps(func: Callable[P, Awaitable[T]]) -> T: + """Runs an aioclock decorated function, with all the dependencies injected. + + Example: + + ```python + from aioclock import run_with_injected_deps, Once, AioClock, Depends + + app = AioClock() + + def some_dependency(): + return 1 + + @app.task(trigger=Once()) + async def main(bar: int = Depends(some_dependency)): + print("Hello World") + return bar + + async def some_other_func(): + foo = await run_with_injected_deps(main) + assert foo == 1 + ``` + + """ + return await inject(func, dependency_overrides_provider=get_provider())() # type: ignore diff --git a/tests/test_di.py b/tests/test_di.py new file mode 100644 index 0000000..e834158 --- /dev/null +++ b/tests/test_di.py @@ -0,0 +1,21 @@ +import pytest + +from aioclock import AioClock, Depends, Once, run_with_injected_deps + +app = AioClock() + + +def some_dependency(): + return 1 + + +@app.task(trigger=Once()) +async def main(bar: int = Depends(some_dependency)): + print("Hello World") + return bar + + +@pytest.mark.asyncio +async def test_run_manual(): + foo = await run_with_injected_deps(main) + assert foo == 1