nonebot2/tests/utils.py

92 lines
2.3 KiB
Python
Raw Normal View History

from typing import TYPE_CHECKING, Type, Union, Mapping, Iterable, Optional
2021-12-16 23:22:25 +08:00
from pydantic import create_model
if TYPE_CHECKING:
2021-12-16 23:22:25 +08:00
from nonebot.adapters import Event, Message
2021-12-20 00:28:02 +08:00
def make_fake_message() -> Type["Message"]:
from nonebot.adapters import Message, MessageSegment
class FakeMessageSegment(MessageSegment):
@classmethod
def get_message_class(cls):
return FakeMessage
def __str__(self) -> str:
return self.data["text"] if self.type == "text" else f"[fake:{self.type}]"
2021-12-20 00:28:02 +08:00
@classmethod
def text(cls, text: str):
return cls("text", {"text": text})
@staticmethod
def image(url: str):
return FakeMessageSegment("image", {"url": url})
2021-12-20 00:28:02 +08:00
def is_text(self) -> bool:
return self.type == "text"
2021-12-20 00:28:02 +08:00
class FakeMessage(Message):
@classmethod
def get_segment_class(cls):
return FakeMessageSegment
@staticmethod
def _construct(msg: Union[str, Iterable[Mapping]]):
if isinstance(msg, str):
yield FakeMessageSegment.text(msg)
else:
for seg in msg:
yield FakeMessageSegment(**seg)
return
2021-12-20 00:28:02 +08:00
return FakeMessage
2021-12-16 23:22:25 +08:00
def make_fake_event(
_type: str = "message",
_name: str = "test",
_description: str = "test",
_user_id: str = "test",
2022-01-20 03:16:04 +08:00
_session_id: Optional[str] = "test",
2021-12-16 23:22:25 +08:00
_message: Optional["Message"] = None,
_to_me: bool = True,
**fields,
) -> Type["Event"]:
from nonebot.adapters import Event
_Fake = create_model("_Fake", __base__=Event, **fields)
class FakeEvent(_Fake):
def get_type(self) -> str:
return _type
def get_event_name(self) -> str:
return _name
def get_event_description(self) -> str:
return _description
def get_user_id(self) -> str:
return _user_id
def get_session_id(self) -> str:
2022-01-20 03:16:04 +08:00
if _session_id is not None:
return _session_id
raise NotImplementedError
2021-12-16 23:22:25 +08:00
def get_message(self) -> "Message":
if _message is not None:
return _message
raise NotImplementedError
def is_tome(self) -> bool:
return _to_me
class Config:
extra = "forbid"
return FakeEvent