mirror of
https://github.com/nonebot/nonebot2.git
synced 2024-11-30 17:15:08 +08:00
🐛 fix DataclassEncoder bug and add test case
This commit is contained in:
parent
9dd989c627
commit
c48ddaf0a2
@ -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
18
tests/test_utils.py
Normal 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"'
|
@ -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"
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user