Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: 修复依赖注入对 Literal 检查报错 #2433

Merged
merged 4 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 11 additions & 2 deletions nonebot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
overload,
)

from pydantic.typing import is_union, is_none_type
from pydantic.typing import is_union, is_none_type, is_literal_type, all_literal_values

from nonebot.log import logger

Expand Down Expand Up @@ -75,9 +75,18 @@ def generic_check_issubclass(
is_none_type(type_) or generic_check_issubclass(type_, class_or_tuple)
for type_ in get_args(cls)
)
elif is_literal_type(cls):
return all(
is_none_type(value) or isinstance(value, class_or_tuple)
for value in all_literal_values(cls)
)
# ensure generic List, Dict can be checked
elif origin:
return issubclass(origin, class_or_tuple)
# avoid class check error (typing.Final, typing.ClassVar, etc...)
try:
return issubclass(origin, class_or_tuple)
except TypeError:
return False
elif isinstance(cls, TypeVar):
if cls.__constraints__:
return all(
Expand Down
5 changes: 4 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from typing import Dict, List, Union, TypeVar
from typing import Dict, List, Union, Literal, TypeVar, ClassVar

from utils import FakeMessage, FakeMessageSegment
from nonebot.utils import (
Expand All @@ -24,8 +24,11 @@ def test_generic_check_issubclass():
assert generic_check_issubclass(int, (int, float))
assert not generic_check_issubclass(str, (int, float))
assert generic_check_issubclass(Union[int, float, None], (int, float))
assert generic_check_issubclass(Literal[1, 2, 3], int)
assert not generic_check_issubclass(Literal[1, 2, "3"], int)
assert generic_check_issubclass(List[int], list)
assert generic_check_issubclass(Dict[str, int], dict)
assert not generic_check_issubclass(ClassVar[int], int)
assert generic_check_issubclass(TypeVar("T", int, float), (int, float))
assert generic_check_issubclass(TypeVar("T", bound=int), (int, float))

Expand Down