🐛 fix union validation error (#1001)

This commit is contained in:
Ju4tCode
2022-05-22 19:42:30 +08:00
committed by GitHub
parent fe43cc92a5
commit 6feed0610b
7 changed files with 144 additions and 24 deletions

View File

@ -1,4 +1,5 @@
import abc
from typing import Any, Type, TypeVar
from pydantic import BaseModel
@ -6,6 +7,8 @@ from nonebot.utils import DataclassEncoder
from .message import Message
E = TypeVar("E", bound="Event")
class Event(abc.ABC, BaseModel):
"""Event 基类。提供获取关键信息的方法,其余信息可直接获取。"""
@ -14,6 +17,12 @@ class Event(abc.ABC, BaseModel):
extra = "allow"
json_encoders = {Message: DataclassEncoder}
@classmethod
def validate(cls: Type["E"], value: Any) -> "E":
if isinstance(value, Event) and not isinstance(value, cls):
raise TypeError(f"{value} is incompatible with Event type {cls}")
return super().validate(value)
@abc.abstractmethod
def get_type(self) -> str:
"""获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。"""

View File

@ -9,6 +9,7 @@ from pydantic.fields import Required, Undefined, ModelField
from nonebot.log import logger
from nonebot.exception import TypeMisMatch
from nonebot.dependencies.utils import check_field_type
from nonebot.dependencies import Param, Dependent, CustomConfig
from nonebot.typing import T_State, T_Handler, T_DependencyCache
from nonebot.utils import (
@ -159,14 +160,14 @@ class DependParam(Param):
class _BotChecker(Param):
async def _solve(self, bot: "Bot", **kwargs: Any) -> Any:
field: ModelField = self.extra["field"]
if isinstance(bot, field.type_):
return bot
else:
try:
return check_field_type(field, bot)
except TypeMisMatch:
logger.debug(
f"Bot type {type(bot)} not match "
f"annotation {field._type_display()}, ignored"
)
raise TypeMisMatch(field, bot)
raise
class BotParam(Param):
@ -205,14 +206,14 @@ class BotParam(Param):
class _EventChecker(Param):
async def _solve(self, event: "Event", **kwargs: Any) -> Any:
field: ModelField = self.extra["field"]
if isinstance(event, field.type_):
return event
else:
try:
return check_field_type(field, event)
except TypeMisMatch:
logger.debug(
f"Event type {type(event)} not match "
f"annotation {field._type_display()}, ignored"
)
raise TypeMisMatch(field, event)
raise
class EventParam(Param):