mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-30 07:56:21 +08:00
fix: preserve directed messaging and channel interaction contracts (#7148)
* fix: retain plugin lifecycle ownership and recover installation state * fix: preserve directed messaging and channel interaction contracts * test: cover plugin rollback and uninstall lifecycle boundaries --------- Co-authored-by: jxxghp <jxxghp@gmail.com>
This commit is contained in:
@@ -85,7 +85,6 @@
|
||||
"app/domain/projection/anilist.py:project": 17,
|
||||
"app/domain/projection/douban.py:project": 25,
|
||||
"app/modules/discord/discord.py:Discord._build_embed": 26,
|
||||
"app/modules/discord/discord.py:Discord._resolve_channel": 20,
|
||||
"app/modules/emby/emby.py:Emby.get_tv_episodes": 18,
|
||||
"app/modules/emby/emby.py:Emby.get_webhook_message": 18,
|
||||
"app/modules/filemanager/storages/alipan.py:AliPan.upload": 16,
|
||||
|
||||
@@ -481,14 +481,13 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "app.modules.discord.discord",
|
||||
"target": "discord",
|
||||
"kind": "network_sdk",
|
||||
"bindings": [
|
||||
"from:discord.app_commands as app_commands",
|
||||
"import:discord as discord"
|
||||
],
|
||||
"fingerprint": "a46a1d6da767a51eb4e1085de5fb936490fc8360c2f3a814635d408468c1b150",
|
||||
"kind": "network_sdk",
|
||||
"source": "app.modules.discord.discord",
|
||||
"target": "discord",
|
||||
"uses": [
|
||||
"Discord.__init__|call:Client",
|
||||
"Discord.__init__|call:Intents.default",
|
||||
@@ -515,8 +514,6 @@
|
||||
"Discord._register_events|call:event",
|
||||
"Discord._resolve_channel|call:fetch_channel",
|
||||
"Discord._resolve_channel|call:fetch_channel",
|
||||
"Discord._resolve_channel|call:fetch_channel",
|
||||
"Discord._resolve_channel|call:get_channel",
|
||||
"Discord._resolve_channel|call:get_channel",
|
||||
"Discord._resolve_channel|call:get_channel",
|
||||
"Discord._resolve_channel|call:get_guild",
|
||||
@@ -531,7 +528,8 @@
|
||||
"Discord._sync_registered_commands|call:sync",
|
||||
"Discord._sync_registered_commands|call:wait_until_ready",
|
||||
"Discord.stop|call:close"
|
||||
]
|
||||
],
|
||||
"fingerprint": "2761ef9a9e5a805bfb20ea832c5d34edea12db21ca3eb27c3db7ce512a5ee7f5"
|
||||
},
|
||||
{
|
||||
"bindings": [
|
||||
|
||||
@@ -138,7 +138,7 @@
|
||||
{"source": "app.agent.llm.discovery", "target": "google.genai", "kind": "network_sdk", "fingerprint": "5b87a7bb210b521bd21971fb6e3d19ca450658548670106e3c756c0ce3a83cad"},
|
||||
{"source": "app.agent.llm.discovery", "target": "openai", "kind": "network_sdk", "fingerprint": "fff154461ff3fdfdf1daea0530dcb68589d6ad7a67f3966e3b86338b483e6dfd"},
|
||||
{"source": "app.agent.tools.impl.search_web", "target": "ddgs", "kind": "network_sdk", "fingerprint": "377e73bb3be804b825d60ad6e792344ca633de107f8c4dbb45d50a34a4dfa04b"},
|
||||
{"source": "app.modules.discord.discord", "target": "discord", "kind": "network_sdk", "fingerprint": "a46a1d6da767a51eb4e1085de5fb936490fc8360c2f3a814635d408468c1b150"},
|
||||
{"source": "app.modules.discord.discord", "target": "discord", "kind": "network_sdk", "fingerprint": "2761ef9a9e5a805bfb20ea832c5d34edea12db21ca3eb27c3db7ce512a5ee7f5"},
|
||||
{"source": "app.modules.filemanager.storages.smb", "target": "smbclient", "kind": "network_sdk", "fingerprint": "37619f050b03598fa559c6ae2df94bda6adf7cffd1cc42d9db9059f1fb41af47"},
|
||||
{"source": "app.modules.filemanager.storages.u115", "target": "oss2", "kind": "network_sdk", "fingerprint": "f7b89c8ae6dad2603f0a9e0caaa159769aef5b3581d7e728f62445b979366eae"},
|
||||
{"source": "app.modules.plex.plex", "target": "plexapi", "kind": "network_sdk", "fingerprint": "6109de36f963b5c6193ed60941a88856cbee9c37303dedf13da3a3be94478543"},
|
||||
|
||||
@@ -120,8 +120,8 @@ FROZEN_EGRESS_FINGERPRINT_BY_EDGE = {
|
||||
("app.cli", "urllib.request"): "71b3e5be2a7d85fdc7a207d15c0e690d7ab96b335b882a3eaec03a1cb4ec1d1b",
|
||||
("app.doctor.checks", "socket.create_connection"): "dfb34d4710353029dcc06e0e0ce3b299bae1a7e71a5743de1d253ac26380f9b6",
|
||||
("app.doctor.checks", "urllib.request"): "d8dd2279263ef58c3b4c59c70451533a4fc27d2ccd76960ca3aff29cd73f3354",
|
||||
# 事件装饰器改为等价的显式注册;未增加事件或网络调用。
|
||||
("app.modules.discord.discord", "discord"): "a46a1d6da767a51eb4e1085de5fb936490fc8360c2f3a814635d408468c1b150",
|
||||
# 删除用户历史频道回落的get_channel/fetch_channel各一次;未新增网络能力或其它SDK调用。
|
||||
("app.modules.discord.discord", "discord"): "2761ef9a9e5a805bfb20ea832c5d34edea12db21ca3eb27c3db7ce512a5ee7f5",
|
||||
("app.modules.emby.emby", "requests"): "6c4c17fe170226ea1272f5859bc119c2775442cabe8ce2a9edcabaf9c37bec31",
|
||||
("app.adapters.network.feishu", "websocket"): "95aca65eed288e0c7654ab49aad6c535d9313d5e38c44b1cb1768dcdfc772453",
|
||||
("app.modules.filemanager.storages.smb", "smbclient"): "37619f050b03598fa559c6ae2df94bda6adf7cffd1cc42d9db9059f1fb41af47",
|
||||
|
||||
189
tests/test_messaging_review_attachments.py
Normal file
189
tests/test_messaging_review_attachments.py
Normal file
@@ -0,0 +1,189 @@
|
||||
"""
|
||||
通过真实网关回调、附件密码协议及交互入口验证消息修复,隔离所有外部发送。
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from lxml import etree
|
||||
|
||||
from app.agent.skills.registry import SkillInfo
|
||||
from app.application.messaging.media import media_interaction_manager
|
||||
from app.application.messaging.skill import PendingSkillInteraction, SkillInteractionHandler, skill_interaction_manager
|
||||
from app.chain.interaction import MediaInteractionChain
|
||||
from app.domain.context import Context, MediaInfo, TorrentInfo
|
||||
from app.modules.qqbot import gateway
|
||||
from app.modules.telegram.telegram import Telegram
|
||||
from app.modules.wechat.wechatbot import WeChatBot
|
||||
from app.modules.wechatclawbot.wechatclawbot import ILinkClient, WechatClawBot
|
||||
from app.schemas.types import NotificationChannel
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", ["C2C_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE"])
|
||||
@pytest.mark.parametrize("text", ["", "Attached review"])
|
||||
def test_qq_gateway_preserves_attachments(monkeypatch, event, text):
|
||||
"""
|
||||
两种网关事件均转交纯附件及带文字附件,实际回调处理保留原附件字段。
|
||||
"""
|
||||
stop = threading.Event()
|
||||
attachments = [{"url": "https://files.invalid/review.pdf", "content_type": "application/pdf"}]
|
||||
received = []
|
||||
message = {"op": 0, "t": event, "d": {"id": "M1", "content": text,
|
||||
"author": {"user_openid": "U1", "member_openid": "U1"}, "group_openid": "G1",
|
||||
"attachments": attachments}}
|
||||
|
||||
def websocket(_url, **callbacks):
|
||||
"""
|
||||
仅把固定事件交回真实网关处理函数,不创建网络连接。
|
||||
"""
|
||||
def receive(**_kwargs):
|
||||
"""
|
||||
将固定附件事件交给网关回调并结束隔离的接收循环。
|
||||
"""
|
||||
callbacks["on_message"](None, json.dumps(message))
|
||||
stop.set()
|
||||
return SimpleNamespace(run_forever=receive)
|
||||
|
||||
monkeypatch.setattr(gateway.websocket, "WebSocketApp", websocket)
|
||||
gateway.run_gateway("id", "secret", "review", lambda *_args: "token",
|
||||
lambda _token: "wss://gateway.invalid", received.append, stop, [])
|
||||
assert received[0]["attachments"] == attachments
|
||||
assert received[0]["content"] == text
|
||||
|
||||
|
||||
def test_wechat_bot_gateway_forwards_supported_file(monkeypatch):
|
||||
"""
|
||||
企业微信支持的文件报文经过真实网关过滤仍能进入统一入口。
|
||||
"""
|
||||
client = object.__new__(WeChatBot)
|
||||
client._config_name = "review"
|
||||
client._admins = []
|
||||
forwarded = Mock()
|
||||
monkeypatch.setattr(client, "_remember_target", Mock())
|
||||
monkeypatch.setattr(client, "_forward_to_message_chain", forwarded)
|
||||
payload = {"body": {"from": {"userid": "U1"}, "msgtype": "file", "chattype": "single",
|
||||
"file": {"download_url": "https://files.invalid/review.pdf", "name": "review.pdf"}}}
|
||||
client._handle_callback_message(payload)
|
||||
forwarded.assert_called_once_with(payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content,mime", [(b"%PDF-1.7 review", "application/pdf"),
|
||||
(b"plain review text", "text/plain"), (b"\x89PNG\r\n\x1a\nreview", "image/png")])
|
||||
def test_clawbot_roundtrips_protocol_cipher_without_file_header_guess(content, mime):
|
||||
"""
|
||||
真实发送端协议生成的密文,接收端必须完整解密并去填充,未知文件头也支持。
|
||||
"""
|
||||
key = bytes(range(16))
|
||||
ciphertext = ILinkClient._encrypt_aes_ecb(content, key)
|
||||
assert WechatClawBot._decrypt_if_needed(ciphertext, ILinkClient._encode_media_aes_key(key), mime) == content
|
||||
|
||||
|
||||
def test_clawbot_invalid_cipher_is_not_returned_as_plaintext():
|
||||
"""
|
||||
已声明密钥但长度无效的密文必须拒绝,不能当作合法附件返回。
|
||||
"""
|
||||
with pytest.raises(ValueError):
|
||||
WechatClawBot._decrypt_if_needed(b"broken", bytes(range(16)).hex(), "application/pdf")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("limit", [1024, 4096])
|
||||
def test_telegram_long_html_remains_valid_and_complete(limit):
|
||||
"""
|
||||
跨长文本边界的嵌套标签与实体必须合法配平且不丢失换行。
|
||||
"""
|
||||
client = object.__new__(Telegram)
|
||||
client._bot = Mock()
|
||||
body = "😀&正文\n" * 1000
|
||||
html = '<b><a href="https://example.invalid/?a=1&b=2">' + body + '</a></b>'
|
||||
client._Telegram__send_long_plain_message(image=None, caption=html, caption_limit=limit,
|
||||
chat_id="U1", parse_mode="HTML")
|
||||
texts = []
|
||||
for call in client._api.send_message.call_args_list:
|
||||
root = etree.fromstring(("<root>" + call.kwargs["text"] + "</root>").encode())
|
||||
text = "".join(root.itertext())
|
||||
assert len(text.encode("utf-16-le")) // 2 <= limit
|
||||
texts.append(text)
|
||||
assert "".join(texts) == ("😀&正文\n" * 1000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("market", [False, True])
|
||||
def test_skill_actions_bind_displayed_item_identity(monkeypatch, market):
|
||||
"""
|
||||
列表显示后删除首项,再按原序号操作第二项,目标仍是展示时的技能。
|
||||
"""
|
||||
skills = [SkillInfo(id=key, name=key, description="review", removable=True) for key in ("A", "B", "C")]
|
||||
catalog = SimpleNamespace(list_local_skills=lambda: list(skills), list_market_skills=lambda **_kw: list(skills),
|
||||
remove_local_skill=Mock(return_value=(True, "removed")), install_market_skill=Mock(return_value=(True, "installed")))
|
||||
handler = SkillInteractionHandler(messenger=Mock(), skill_catalog=catalog)
|
||||
request = PendingSkillInteraction("request", "U1", NotificationChannel.Telegram, "review", "user")
|
||||
if market:
|
||||
handler._build_market_view(request)
|
||||
else:
|
||||
handler._build_installed_view(request)
|
||||
skills.pop(0)
|
||||
if market:
|
||||
assert handler._install_market_skill(request, 2)[0]
|
||||
assert catalog.install_market_skill.call_args.args[0].id == "B"
|
||||
else:
|
||||
assert handler._remove_local_skill(request, 2)[0]
|
||||
catalog.remove_local_skill.assert_called_once_with("B")
|
||||
|
||||
|
||||
def test_stale_media_button_cannot_select_torrent_as_media(monkeypatch):
|
||||
"""
|
||||
已进入资源阶段的旧媒体按钮不得读取新列表或覆盖已选媒体身份。
|
||||
"""
|
||||
request = media_interaction_manager.create_or_replace("U1", NotificationChannel.Telegram, "review", "user",
|
||||
action="Search", keyword="Review", items=[])
|
||||
request.phase = "torrent"
|
||||
selected = MediaInfo(title="Selected")
|
||||
request.current_media = selected
|
||||
request.items = [Context(torrent_info=TorrentInfo(title="Resource"))]
|
||||
chain = object.__new__(MediaInteractionChain)
|
||||
monkeypatch.setattr(chain, "post_message", Mock())
|
||||
search = Mock()
|
||||
monkeypatch.setattr(chain, "_search_media_resources", search)
|
||||
try:
|
||||
assert chain.handle_callback_interaction(f"media:{request.request_id}:select:1",
|
||||
NotificationChannel.Telegram, "review", "U1", "user")
|
||||
assert request.current_media is selected
|
||||
search.assert_not_called()
|
||||
finally:
|
||||
media_interaction_manager.clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encrypt_type,key", [(1, None), (2, bytes(range(16)).hex())])
|
||||
def test_clawbot_declared_encryption_requires_supported_protocol(monkeypatch, encrypt_type, key):
|
||||
"""
|
||||
已声明加密但缺密钥或模式不支持时,真实附件下载入口必须拒绝返回内容。
|
||||
"""
|
||||
client = object.__new__(WechatClawBot)
|
||||
payload = {"url": "https://files.invalid/encrypted", "aeskey": key, "encrypt_type": encrypt_type}
|
||||
monkeypatch.setattr(client, "_decode_ref_payload", lambda **_kw: payload)
|
||||
ciphertext = ILinkClient._encrypt_aes_ecb(b"%PDF review", bytes(range(16)))
|
||||
monkeypatch.setattr("app.modules.wechatclawbot.wechatclawbot.RequestUtils", lambda **_kw: SimpleNamespace(
|
||||
get_res=lambda _url: SimpleNamespace(content=ciphertext, headers={})))
|
||||
assert client._download_ref_bytes("wxclaw://file/review", "file") is None
|
||||
|
||||
|
||||
def test_skill_old_render_button_cannot_operate_new_page():
|
||||
"""
|
||||
同一会话刷新列表后,旧按钮携带的展示标识必须过期。
|
||||
"""
|
||||
catalog = SimpleNamespace(list_local_skills=lambda: [
|
||||
SkillInfo(id="A", name="A", description="review", removable=True)], remove_local_skill=Mock())
|
||||
handler = SkillInteractionHandler(messenger=Mock(), skill_catalog=catalog)
|
||||
request = skill_interaction_manager.create_or_replace("U1", NotificationChannel.Telegram, "review", "user")
|
||||
request.view = "installed"
|
||||
try:
|
||||
_, _, buttons = handler._build_installed_view(request)
|
||||
callback = next(button["callback_data"] for row in buttons for button in row if button["text"] == "删除 1")
|
||||
assert len(callback.encode()) <= 64
|
||||
handler._build_installed_view(request)
|
||||
assert handler.handle_callback_interaction(callback, NotificationChannel.Telegram, "review", "U1", "user")
|
||||
catalog.remove_local_skill.assert_not_called()
|
||||
finally:
|
||||
skill_interaction_manager.clear()
|
||||
115
tests/test_messaging_review_boundaries.py
Normal file
115
tests/test_messaging_review_boundaries.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
独立复核消息修复的真实回调、附件解密和图片说明分片边界。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from Crypto.Cipher import AES
|
||||
from lxml import etree
|
||||
|
||||
from app.agent.skills.registry import SkillInfo
|
||||
from app.application.messaging.skill import SkillInteractionHandler, skill_interaction_manager
|
||||
from app.modules.telegram.telegram import Telegram
|
||||
from app.modules.wechatclawbot.wechatclawbot import ILinkClient, WechatClawBot
|
||||
from app.schemas.types import NotificationChannel
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plaintext", [b"x" * 15 + b"\x00", b"x" * 14 + b"\x01\x02"])
|
||||
def test_claw_attachment_rejects_full_length_cipher_with_invalid_padding(monkeypatch, plaintext):
|
||||
"""
|
||||
长度合法但PKCS7尾部非法的密文不得从真实资源引用入口返回。
|
||||
"""
|
||||
key = bytes(range(16))
|
||||
client = object.__new__(WechatClawBot)
|
||||
ref = ILinkClient._encode_ref_payload("file", {
|
||||
"url": "https://files.invalid/review", "aeskey": ILinkClient._encode_media_aes_key(key),
|
||||
"encrypt_type": 1, "name": "review.bin",
|
||||
})
|
||||
ciphertext = AES.new(key, AES.MODE_ECB).encrypt(plaintext)
|
||||
monkeypatch.setattr("app.modules.wechatclawbot.wechatclawbot.RequestUtils", lambda **_kwargs: SimpleNamespace(
|
||||
get_res=lambda _url: SimpleNamespace(content=ciphertext, headers={}),
|
||||
))
|
||||
assert client._download_ref_bytes(ref, "file") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encrypted", [False, True])
|
||||
def test_claw_attachment_real_reference_preserves_complete_content_and_metadata(monkeypatch, encrypted):
|
||||
"""
|
||||
真实内部引用同时支持未加密文件和协议密文,并完整保留名称及MIME。
|
||||
"""
|
||||
key = bytes(range(16))
|
||||
content = bytes(range(64)) + b"\x00\x01\x02"
|
||||
client = object.__new__(WechatClawBot)
|
||||
ref = ILinkClient._encode_ref_payload("file", {
|
||||
"url": "https://files.invalid/review", "name": "review.bin", "mime_type": "application/custom",
|
||||
"aeskey": ILinkClient._encode_media_aes_key(key) if encrypted else None,
|
||||
"encrypt_type": 1 if encrypted else None,
|
||||
})
|
||||
downloaded = ILinkClient._encrypt_aes_ecb(content, key) if encrypted else content
|
||||
monkeypatch.setattr("app.modules.wechatclawbot.wechatclawbot.RequestUtils", lambda **_kwargs: SimpleNamespace(
|
||||
get_res=lambda _url: SimpleNamespace(content=downloaded, headers={}),
|
||||
))
|
||||
assert client._download_ref_bytes(ref, "file") == (content, "application/custom", "review.bin")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("market", [False, True])
|
||||
def test_skill_real_callback_keeps_displayed_identity_after_reordering(market):
|
||||
"""
|
||||
合法展示按钮经过公开回调入口仍定位原第二项,其他用户不能复用该按钮。
|
||||
"""
|
||||
skills = [SkillInfo(id=name, name=name, description="复核技能", removable=True) for name in ("A", "B", "C")]
|
||||
catalog = SimpleNamespace(list_local_skills=lambda: list(skills),
|
||||
list_market_skills=lambda **_kwargs: list(skills),
|
||||
remove_local_skill=Mock(return_value=(True, "已删除")),
|
||||
install_market_skill=Mock(return_value=(True, "已安装")))
|
||||
handler = SkillInteractionHandler(messenger=Mock(), skill_catalog=catalog)
|
||||
request = skill_interaction_manager.create_or_replace("review-owner", NotificationChannel.Telegram,
|
||||
"review-source", "review")
|
||||
request.view = "market" if market else "installed"
|
||||
action = "install" if market else "remove"
|
||||
try:
|
||||
if market:
|
||||
_, _, buttons = handler._build_market_view(request)
|
||||
else:
|
||||
_, _, buttons = handler._build_installed_view(request)
|
||||
callback = next(button["callback_data"] for row in buttons for button in row
|
||||
if f":{action}:2:" in button.get("callback_data", ""))
|
||||
assert handler.handle_callback_interaction(callback, NotificationChannel.Telegram,
|
||||
"review-source", "other-user", "other")
|
||||
catalog.install_market_skill.assert_not_called()
|
||||
catalog.remove_local_skill.assert_not_called()
|
||||
skills.pop(0)
|
||||
assert handler.handle_callback_interaction(callback, NotificationChannel.Telegram,
|
||||
"review-source", "review-owner", "review")
|
||||
if market:
|
||||
selected = catalog.install_market_skill.call_args.args[0]
|
||||
assert selected.id == "B" and selected is not skills[0]
|
||||
else:
|
||||
catalog.remove_local_skill.assert_called_once_with("B")
|
||||
finally:
|
||||
skill_interaction_manager.clear()
|
||||
|
||||
|
||||
def test_telegram_photo_caption_chunks_preserve_numeric_entities_and_first_keyboard():
|
||||
"""
|
||||
图片首块与后续文本保持合法HTML和UTF16上限,键盘只附在首条。
|
||||
"""
|
||||
client = object.__new__(Telegram)
|
||||
client._bot = Mock()
|
||||
body = "😀&<正文\n" * 500
|
||||
markup = {"inline_keyboard": [[{"text": "复核", "callback_data": "review"}]]}
|
||||
client._Telegram__send_long_plain_message(image=b"image", caption=f"<b><i>{body}</i></b>",
|
||||
caption_limit=1024, chat_id="review", parse_mode="HTML", reply_markup=markup)
|
||||
photo = client._api.send_photo.call_args.kwargs
|
||||
messages = [call.kwargs for call in client._api.send_message.call_args_list]
|
||||
assert messages and photo["reply_markup"] == markup
|
||||
assert all(message["reply_markup"] is None for message in messages)
|
||||
restored = []
|
||||
for chunk in [photo["caption"], *(message["text"] for message in messages)]:
|
||||
root = etree.fromstring(("<root>" + chunk + "</root>").encode())
|
||||
visible = "".join(root.itertext())
|
||||
assert len(visible.encode("utf-16-le")) // 2 <= 1024
|
||||
restored.append(visible)
|
||||
assert "".join(restored) == "😀&<正文\n" * 500
|
||||
160
tests/test_messaging_review_regressions.py
Normal file
160
tests/test_messaging_review_regressions.py
Normal file
@@ -0,0 +1,160 @@
|
||||
"""
|
||||
消息渠道审查发现的真实路由、身份与文本边界回归,外部渠道均用替身隔离。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.endpoints import notification as notification_endpoint
|
||||
from app.api.endpoints.notification import _normalize_configs
|
||||
from app.chain.music_interaction.music import resolve_media_action
|
||||
from app.chain.system import SystemChain
|
||||
from app.domain.context import MediaInfo
|
||||
from app.modules.discord import DiscordModule
|
||||
from app.modules.discord.discord import Discord
|
||||
from app.modules.slack import SlackModule
|
||||
from app.modules.slack.slack import Slack
|
||||
from app.schemas.system import NotificationConf
|
||||
from app.schemas.types import NotificationChannel
|
||||
|
||||
|
||||
@pytest.mark.parametrize("available", [True, False])
|
||||
def test_discord_explicit_recipient_never_uses_broadcast(available):
|
||||
"""
|
||||
指定用户的通知只能到私聊;DM不可用时明确失败,不回落公共频道。
|
||||
"""
|
||||
client = object.__new__(Discord)
|
||||
private = object() if available else None
|
||||
client._broadcast_channel = object()
|
||||
client._channel_id = 456
|
||||
client._guild_id = None
|
||||
client._get_user_chat_id = Mock(return_value=None)
|
||||
client._get_dm_channel = AsyncMock(return_value=private)
|
||||
client._client = Mock()
|
||||
assert asyncio.run(client._resolve_channel(userid="123")) is private
|
||||
client._get_dm_channel.assert_awaited_once_with("123")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("result,expected", [((False, None), False), ((True, {}), True), (False, False)])
|
||||
def test_discord_edit_reports_tuple_status(monkeypatch, result, expected):
|
||||
"""
|
||||
编辑返回失败tuple时不能凭容器真值误报成功。
|
||||
"""
|
||||
module = object.__new__(DiscordModule)
|
||||
module._channel = NotificationChannel.Discord
|
||||
monkeypatch.setattr(module, "get_configs", lambda: {"review": SimpleNamespace(name="review")})
|
||||
monkeypatch.setattr(module, "get_instance", lambda _name: SimpleNamespace(send_msg=lambda **_kw: result))
|
||||
assert module.edit_message(NotificationChannel.Discord, "review", "1", "2", "text") is expected
|
||||
|
||||
|
||||
def test_slack_slash_command_preserves_arguments(monkeypatch):
|
||||
"""
|
||||
原生命令和text参数一起传给统一命令处理器。
|
||||
"""
|
||||
module = object.__new__(SlackModule)
|
||||
monkeypatch.setattr(module, "get_config", lambda _source: SimpleNamespace(name="review", config={}))
|
||||
monkeypatch.setattr(module, "get_instance", lambda _name: Mock())
|
||||
monkeypatch.setattr(module, "_should_reject_admin_command", lambda *_args: False)
|
||||
message = module.message_parser("review", json.dumps({"command": "/search", "text": "Review title",
|
||||
"user_id": "U1", "user_name": "review", "channel_id": "C1"}), None, None)
|
||||
assert message.text == "/search Review title"
|
||||
|
||||
|
||||
def test_slack_media_buttons_keep_original_positions():
|
||||
"""
|
||||
前项无海报时,后项卡片仍对应原列表第二项。
|
||||
"""
|
||||
client = object.__new__(Slack)
|
||||
client._client = Mock()
|
||||
media = [MediaInfo(title="No poster"), MediaInfo(title="With poster", poster_path="https://img.invalid/p.jpg")]
|
||||
assert client.send_medias_msg(media, userid="U1", title="Review")
|
||||
blocks = client._client.chat_postMessage.call_args.kwargs["blocks"]
|
||||
values = [button["value"] for block in blocks if block["type"] == "actions" for button in block["elements"]]
|
||||
assert values[-1] == "2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("repeat", [800, 3000])
|
||||
def test_slack_plain_text_preserves_complete_long_body(repeat):
|
||||
"""
|
||||
没有富文本blocks的普通通知也必须完整发送,长文本不能截断。
|
||||
"""
|
||||
client = object.__new__(Slack)
|
||||
client._client = Mock()
|
||||
body = "完整正文" * repeat
|
||||
assert client.send_msg(title="Review", text=body, userid="U1")[0]
|
||||
sent = [call.kwargs for call in client._client.chat_postMessage.call_args_list]
|
||||
assert "".join(item["text"] for item in sent) == "Review\n" + body
|
||||
assert all(len(item["text"]) <= 4000 for item in sent)
|
||||
|
||||
|
||||
def test_notification_config_ids_are_unique():
|
||||
"""
|
||||
不同显示名不能共享同一稳定身份,以免复用另一配置的登录凭据。
|
||||
"""
|
||||
with pytest.raises(ValueError, match="身份|ID|id"):
|
||||
_normalize_configs([NotificationConf(id="stable", name="A", type="wechatclawbot"),
|
||||
NotificationConf(id="stable", name="B", type="wechatclawbot")])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_notification_config_can_repair_legacy_duplicate_ids(monkeypatch):
|
||||
"""
|
||||
拒绝新重复身份的同时,允许管理员把旧重复数据修复为唯一身份。
|
||||
"""
|
||||
service = SimpleNamespace(get=lambda _key: [
|
||||
{"id": "legacy-duplicate", "name": "A", "type": "wechatclawbot"},
|
||||
{"id": "legacy-duplicate", "name": "B", "type": "wechatclawbot"}], async_set=AsyncMock(return_value=True))
|
||||
monkeypatch.setattr(notification_endpoint, "get_configured_system_config", lambda: service)
|
||||
reconcile = Mock(return_value={"success": True})
|
||||
monkeypatch.setattr(notification_endpoint, "NotificationChain", lambda: SimpleNamespace(manage_channel=reconcile))
|
||||
response = await notification_endpoint.save_config([
|
||||
NotificationConf(id="unique-A", name="A", type="wechatclawbot"),
|
||||
NotificationConf(id="unique-B", name="B", type="wechatclawbot")], None)
|
||||
assert response.success
|
||||
service.async_set.assert_awaited_once()
|
||||
|
||||
|
||||
def test_discord_invalid_explicit_chat_does_not_fall_back_to_broadcast():
|
||||
"""
|
||||
指定原频道不可访问时拒绝发送,不能泄漏到默认广播频道。
|
||||
"""
|
||||
client = object.__new__(Discord)
|
||||
client._broadcast_channel = object()
|
||||
client._channel_id = 456
|
||||
client._guild_id = None
|
||||
client._client = SimpleNamespace(get_channel=lambda _id: None,
|
||||
fetch_channel=AsyncMock(side_effect=RuntimeError("channel unavailable")))
|
||||
assert asyncio.run(client._resolve_channel(chat_id="789")) is None
|
||||
|
||||
|
||||
def test_remote_restart_preserves_source_in_cache_and_receipt(monkeypatch):
|
||||
"""
|
||||
普通重启的前后通知保持同一配置来源。
|
||||
"""
|
||||
chain = object.__new__(SystemChain)
|
||||
messages = []
|
||||
saved = {}
|
||||
monkeypatch.setattr(chain, "post_message", messages.append)
|
||||
monkeypatch.setattr(chain, "save_cache", lambda data, key: saved.update({key: data}))
|
||||
monkeypatch.setattr(chain, "load_cache", lambda key: saved.get(key))
|
||||
monkeypatch.setattr(chain, "remove_cache", lambda key: saved.pop(key, None))
|
||||
monkeypatch.setattr(chain, "backup_plugins", lambda: None)
|
||||
monkeypatch.setattr(chain, "_SystemChain__get_version_message", lambda: "review")
|
||||
monkeypatch.setattr("app.chain.system.SystemHelper.restart", lambda: None)
|
||||
chain.restart(NotificationChannel.Telegram, "U1", source="specific-config")
|
||||
assert saved[chain._restart_file]["source"] == "specific-config"
|
||||
chain.restart_finish()
|
||||
assert [message.source for message in messages] == ["specific-config", "specific-config"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", ["搜索", "下载", "订阅", "洗版"])
|
||||
def test_media_command_removes_only_leading_command(prefix):
|
||||
"""
|
||||
作品名中的同名命令词必须作为检索词保留。
|
||||
"""
|
||||
_, query = resolve_media_action(f"{prefix}:搜索中的订阅与下载洗版")
|
||||
assert query == "搜索中的订阅与下载洗版"
|
||||
@@ -641,7 +641,7 @@ def test_skills_chain_installed_view_builds_remove_buttons() -> None:
|
||||
assert "builtin" in text
|
||||
assert "custom" in text
|
||||
assert buttons
|
||||
assert {"text": "删除 2", "callback_data": f"skills:{request.request_id}:remove:2"} in [
|
||||
assert {"text": "删除 2", "callback_data": f"skills:{request.request_id}:remove:2:{request.selection_id}"} in [
|
||||
button for row in buttons for button in row
|
||||
]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user