From 905ed04eb0ed7b973e8f91a5ada9a518c77de57a Mon Sep 17 00:00:00 2001 From: Alex <60134319+alexanderlazarev0@users.noreply.github.com> Date: Tue, 29 Oct 2024 16:51:50 +0100 Subject: [PATCH] Fix overriding injections in sync functions. (#110) Co-authored-by: Alexander --- tests/test_injection.py | 10 ++++++---- that_depends/injection.py | 8 ++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/test_injection.py b/tests/test_injection.py index 17104ea..b9a8a6b 100644 --- a/tests/test_injection.py +++ b/tests/test_injection.py @@ -64,15 +64,17 @@ def test_sync_injection( assert fixture_one == 1 -def test_wrong_sync_injection() -> None: +def test_overriden_sync_injection() -> None: @inject def inner( _: container.SimpleFactory = Provide[container.DIContainer.simple_factory], - ) -> None: + ) -> container.SimpleFactory: """Do nothing.""" + return _ - with pytest.raises(RuntimeError, match="Injected arguments must not be redefined"): - inner(_=container.SimpleFactory(dep1="1", dep2=2)) + factory = container.SimpleFactory(dep1="1", dep2=2) + with pytest.warns(RuntimeWarning, match="Expected injection, but nothing found. Remove @inject decorator."): + assert inner(_=factory) == factory def test_sync_empty_injection() -> None: diff --git a/that_depends/injection.py b/that_depends/injection.py index 6a440a7..b4661c4 100644 --- a/that_depends/injection.py +++ b/that_depends/injection.py @@ -56,13 +56,13 @@ def _inject_to_sync( @functools.wraps(func) def inner(*args: P.args, **kwargs: P.kwargs) -> T: injected = False - for field_name, field_value in signature.parameters.items(): + for i, (field_name, field_value) in enumerate(signature.parameters.items()): + if i < len(args): + continue if not isinstance(field_value.default, AbstractProvider): continue if field_name in kwargs: - msg = f"Injected arguments must not be redefined, {field_name=}" - raise RuntimeError(msg) - + continue kwargs[field_name] = field_value.default.sync_resolve() injected = True