🐛 fix DataclassEncoder bug and add test case

This commit is contained in:
AkiraXie 2022-02-17 15:06:26 +08:00
parent 9dd989c627
commit c48ddaf0a2
3 changed files with 29 additions and 1 deletions

View File

@ -145,7 +145,7 @@ class DataclassEncoder(json.JSONEncoder):
@overrides(json.JSONEncoder)
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return {f.name: getattr(o, f.name) for f in dataclasses.fields(o)}
return super().default(o)

18
tests/test_utils.py Normal file
View File

@ -0,0 +1,18 @@
import json
from utils import make_fake_message
def test_dataclass_encoder():
from nonebot.utils import DataclassEncoder
MessageSegment = make_fake_message().get_segment_class()
ms = MessageSegment.node_custom(
"1234", "testtest", "test" + MessageSegment.image("url")
)
s = json.dumps(ms, cls = DataclassEncoder)
assert (
s
== '{"type": "node", "data": {"user_id": "1234", "nickname": "testtest", "content": [{"type": "text", "data": {"text": "test"}}, {"type": "image", "data": {"url": "url"}}]}}'
)
s1 = json.dumps("123", cls = DataclassEncoder)
assert s1 == '"123"'

View File

@ -32,6 +32,16 @@ def make_fake_message():
def image(url: str):
return FakeMessageSegment("image", {"url": url})
@staticmethod
def node_custom(
user_id: str,
nickname: str,
content: Union["FakeMessage", "FakeMessageSegment", str],
):
return FakeMessageSegment(
"node", {"user_id": user_id, "nickname": nickname, "content": content}
)
def is_text(self) -> bool:
return self.type == "text"