mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-02-17 16:20:05 +08:00
✨ Fix: 修复 MessageSegment 在有额外数据时报错 (#1055)
This commit is contained in:
parent
c91c9380a7
commit
f11970132c
@ -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)
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user