Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions test/unit/test_inject_from_container_optional_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,30 @@ def make_foo() -> Foo | None:
assert inst is container.get(Foo | None)


def test_optional_factory_with_qualifier() -> None:
# https://github.com/maldoinc/wireup/issues/138
# A factory returning Optional[T] with a qualifier must preserve the qualifier
# on the backwards-compatibility alias factory created for the raw type T.
@wireup.injectable
class AuthContext:
pass

@wireup.injectable
def require_authentication() -> AuthContext:
return AuthContext()

@wireup.injectable(qualifier="optional")
def maybe_get_authentication() -> AuthContext | None:
return None

container = wireup.create_sync_container(
injectables=[require_authentication, maybe_get_authentication],
)

assert isinstance(container.get(AuthContext), AuthContext)
assert container.get(AuthContext | None, qualifier="optional") is None


def test_registering_optional_and_plain_type_raises_duplicate() -> None:
@wireup.injectable
class Foo:
Expand Down
7 changes: 6 additions & 1 deletion wireup/ioc/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,12 +393,17 @@ def compat_fn(raw_type_instance: Any) -> Any:

return raw_type_instance

# The alias factory depends on the normalized Optional[T] instance. When the
# original factory was registered with a qualifier, carry it over so the
# dependency resolves to the qualified factory instead of an unqualified one.
raw_type_annotation = klass if qualifier is None else Annotated[klass, InjectableQualifier(qualifier)]

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no qualifier is equivalent to qualifier = None so you can simplify this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks


compat_fn.__signature__ = inspect.Signature( # type: ignore[attr-defined]
parameters=[
inspect.Parameter(
"raw_type_instance",
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=klass,
annotation=raw_type_annotation,
)
],
)
Expand Down
Loading