2023-02-22 23:32:48 +08:00
|
|
|
from nonebot.adapters import MessageTemplate
|
2023-06-19 17:48:59 +08:00
|
|
|
from utils import FakeMessage, FakeMessageSegment, escape_text
|
2022-01-29 23:39:13 +08:00
|
|
|
|
|
|
|
|
2022-02-06 18:55:19 +08:00
|
|
|
def test_template_basis():
|
|
|
|
template = MessageTemplate("{key:.3%}")
|
|
|
|
formatted = template.format(key=0.123456789)
|
|
|
|
assert formatted == "12.346%"
|
|
|
|
|
|
|
|
|
|
|
|
def test_template_message():
|
2023-06-19 17:48:59 +08:00
|
|
|
template = FakeMessage.template("{a:custom}{b:text}{c:image}/{d}")
|
2022-01-29 23:39:13 +08:00
|
|
|
|
|
|
|
@template.add_format_spec
|
|
|
|
def custom(input: str) -> str:
|
2022-08-22 14:39:00 +08:00
|
|
|
return f"{input}-custom!"
|
2022-01-29 23:39:13 +08:00
|
|
|
|
2022-02-06 18:55:19 +08:00
|
|
|
try:
|
|
|
|
template.add_format_spec(custom)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise AssertionError("Should raise ValueError")
|
|
|
|
|
2022-08-22 14:39:00 +08:00
|
|
|
format_args = {
|
|
|
|
"a": "custom",
|
|
|
|
"b": "text",
|
|
|
|
"c": "https://example.com/test",
|
|
|
|
"d": 114,
|
|
|
|
}
|
2022-02-06 18:55:19 +08:00
|
|
|
formatted = template.format(**format_args)
|
|
|
|
|
|
|
|
assert template.format_map(format_args) == formatted
|
2022-08-22 14:39:00 +08:00
|
|
|
assert formatted.extract_plain_text() == "custom-custom!text/114"
|
|
|
|
assert str(formatted) == "custom-custom!text[fake:image]/114"
|
2022-02-10 13:15:59 +08:00
|
|
|
|
|
|
|
|
2022-04-30 09:59:23 +08:00
|
|
|
def test_rich_template_message():
|
|
|
|
pic1, pic2, pic3 = (
|
2023-06-19 17:48:59 +08:00
|
|
|
FakeMessageSegment.image("file:///pic1.jpg"),
|
|
|
|
FakeMessageSegment.image("file:///pic2.jpg"),
|
|
|
|
FakeMessageSegment.image("file:///pic3.jpg"),
|
2022-04-30 09:59:23 +08:00
|
|
|
)
|
|
|
|
|
2023-06-19 17:48:59 +08:00
|
|
|
template = FakeMessage.template("{}{}" + pic2 + "{}")
|
2022-04-30 09:59:23 +08:00
|
|
|
|
|
|
|
result = template.format(pic1, "[fake:image]", pic3)
|
|
|
|
|
2023-06-19 17:48:59 +08:00
|
|
|
assert result["image"] == FakeMessage([pic1, pic2, pic3])
|
2022-04-30 09:59:23 +08:00
|
|
|
assert str(result) == (
|
|
|
|
"[fake:image]" + escape_text("[fake:image]") + "[fake:image]" + "[fake:image]"
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2022-02-10 13:15:59 +08:00
|
|
|
def test_message_injection():
|
2023-06-19 17:48:59 +08:00
|
|
|
template = FakeMessage.template("{name}Is Bad")
|
2022-02-10 13:15:59 +08:00
|
|
|
message = template.format(name="[fake:image]")
|
|
|
|
|
|
|
|
assert message.extract_plain_text() == escape_text("[fake:image]Is Bad")
|