Fix: 修复 MessageSegment 在有额外数据时报错 (#1055)

This commit is contained in:
Ju4tCode 2022-06-20 15:52:12 +08:00 committed by GitHub
parent c91c9380a7
commit f11970132c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 14 deletions

View File

@ -66,7 +66,11 @@ class MessageSegment(abc.ABC, Generic[TM]):
return value
if not isinstance(value, dict):
raise ValueError(f"Expected dict for MessageSegment, got {type(value)}")
return cls(**value)
if "type" not in value:
raise ValueError(
f"Expected dict with 'type' for MessageSegment, got {value}"
)
return cls(type=value["type"], data=value.get("data", {}))
def get(self, key: str, default: Any = None):
return asdict(self).get(key, default)

View File

@ -61,6 +61,10 @@ all = ["quart", "aiohttp", "httpx", "websockets"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
addopts = "--cov=nonebot --cov-report=term-missing"
filterwarnings = [
"error",
"ignore::DeprecationWarning",
]
[tool.black]
line-length = 88

View File

@ -1,3 +1,4 @@
import pytest
from pydantic import ValidationError, parse_obj_as
from utils import make_fake_message
@ -29,14 +30,15 @@ def test_segment_validate():
MessageSegment = Message.get_segment_class()
assert parse_obj_as(
MessageSegment, {"type": "text", "data": {"text": "text"}}
MessageSegment,
{"type": "text", "data": {"text": "text"}, "extra": "should be ignored"},
) == MessageSegment.text("text")
try:
with pytest.raises(ValidationError):
parse_obj_as(MessageSegment, "some str")
assert False
except ValidationError:
assert True
with pytest.raises(ValidationError):
parse_obj_as(MessageSegment, {"data": {}})
def test_segment():
@ -129,11 +131,8 @@ def test_message_validate():
assert parse_obj_as(Message, Message([])) == Message([])
try:
with pytest.raises(ValidationError):
parse_obj_as(Message, Message_([]))
assert False
except ValidationError:
assert True
assert parse_obj_as(Message, "text") == Message([MessageSegment.text("text")])
@ -146,8 +145,5 @@ def test_message_validate():
[MessageSegment.text("text"), {"type": "text", "data": {"text": "text"}}],
) == Message([MessageSegment.text("text"), MessageSegment.text("text")])
try:
with pytest.raises(ValidationError):
parse_obj_as(Message, object())
assert False
except ValidationError:
assert True