diff --git a/magicbot/inject.py b/magicbot/inject.py index 3af0ce8..1a4198a 100644 --- a/magicbot/inject.py +++ b/magicbot/inject.py @@ -39,10 +39,12 @@ def get_injection_requests( # If the type is not actually a type, give a meaningful error if not isinstance(inject_type, type): - raise TypeError( - f"Component {cname} has a non-type annotation {n}: {inject_type}\n" - "Lone non-injection variable annotations are disallowed, did you want to assign a static variable?" + message = ( + f"Component {cname} has a non-type annotation {n}: {inject_type!r}" ) + if component is not None: + message += "\nLone non-injection variable annotations are disallowed. Did you mean to assign a static variable?" + raise TypeError(message) requests[n] = inject_type diff --git a/tests/test_magicbot_inject.py b/tests/test_magicbot_inject.py new file mode 100644 index 0000000..55faf07 --- /dev/null +++ b/tests/test_magicbot_inject.py @@ -0,0 +1,20 @@ +import typing + +import pytest + +from magicbot.inject import get_injection_requests + + +def test_ctor_invalid_type_hint_message(): + """ + class Component: + def __init__(self, foo: 1): ... + """ + type_hints = { + "foo": typing.cast(type, 1), + } + + with pytest.raises(TypeError) as exc_info: + get_injection_requests(type_hints, "bar") + + assert exc_info.value.args[0] == "Component bar has a non-type annotation foo: 1"