From a598e08d0ca5997a152f21a0b74d8a0e34bbdab2 Mon Sep 17 00:00:00 2001 From: David Vo Date: Sun, 5 Nov 2023 01:24:13 +1100 Subject: [PATCH] magicbot: Fix non-type annotation error for init --- magicbot/inject.py | 8 +++++--- tests/test_magicbot_inject.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 tests/test_magicbot_inject.py 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"