🔀 Merge pull request #812

Fix: 修复 DataclassEncoder 嵌套 encode 的问题
This commit is contained in:
Ju4tCode 2022-02-17 15:55:56 +08:00 committed by GitHub
commit daa026cfd7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 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)

19
tests/test_utils.py Normal file
View File

@ -0,0 +1,19 @@
import json
from utils import make_fake_message
def test_dataclass_encoder():
from nonebot.utils import DataclassEncoder
simple = json.dumps("123", cls=DataclassEncoder)
assert simple == '"123"'
Message = make_fake_message()
MessageSegment = Message.get_segment_class()
ms = MessageSegment.nested(Message(MessageSegment.text("text")))
s = json.dumps(ms, cls=DataclassEncoder)
assert (
s
== '{"type": "node", "data": {"content": [{"type": "text", "data": {"text": "text"}}]}}'
)

View File

@ -32,6 +32,10 @@ def make_fake_message():
def image(url: str):
return FakeMessageSegment("image", {"url": url})
@staticmethod
def nested(content: "FakeMessage"):
return FakeMessageSegment("node", {"content": content})
def is_text(self) -> bool:
return self.type == "text"