mirror of
https://github.com/nonebot/nonebot2.git
synced 2024-11-24 17:15:05 +08:00
commit
daa026cfd7
@ -145,7 +145,7 @@ class DataclassEncoder(json.JSONEncoder):
|
|||||||
@overrides(json.JSONEncoder)
|
@overrides(json.JSONEncoder)
|
||||||
def default(self, o):
|
def default(self, o):
|
||||||
if dataclasses.is_dataclass(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)
|
return super().default(o)
|
||||||
|
|
||||||
|
|
||||||
|
19
tests/test_utils.py
Normal file
19
tests/test_utils.py
Normal 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"}}]}}'
|
||||||
|
)
|
@ -32,6 +32,10 @@ def make_fake_message():
|
|||||||
def image(url: str):
|
def image(url: str):
|
||||||
return FakeMessageSegment("image", {"url": url})
|
return FakeMessageSegment("image", {"url": url})
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def nested(content: "FakeMessage"):
|
||||||
|
return FakeMessageSegment("node", {"content": content})
|
||||||
|
|
||||||
def is_text(self) -> bool:
|
def is_text(self) -> bool:
|
||||||
return self.type == "text"
|
return self.type == "text"
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user