"""WeCom 渠道测试(全部离线:假 ws_client + 假帧)。""" from __future__ import annotations import asyncio import pytest from bot042.channels.base import ChannelCredentialsError from bot042.channels.im.wecom import WeComChannel, WeComConfig from bot042.channels.models import ChannelSubject, ImageContent from bot042.channels.registry import create_channel, known_kinds, probe_channel class FakeWSClient: def __init__(self) -> None: self.stream_calls: list[dict] = [] self.sent: list[tuple] = [] self.handlers: dict[str, object] = {} def on(self, event: str, handler) -> None: self.handlers[event] = handler async def reply_stream(self, *, frame, stream_id, content, finish): self.stream_calls.append({"content": content, "finish": finish}) async def send_message(self, chat_id, payload): self.sent.append(("message", chat_id, payload["msgtype"])) async def upload_media(self, data, type, filename): return {"media_id": "M1"} async def reply_media(self, frame, media_type, media_id): self.sent.append(("reply_media", media_type, media_id)) async def send_media_message(self, chat_id, media_type, media_id): self.sent.append(("send_media", chat_id, media_type, media_id)) def _text_body(**extra) -> dict: body = { "msgid": "m1", "msgtype": "text", "chattype": "single", "from": {"userid": "U1"}, "text": {"content": "你好"}, "response_url": "https://example.invalid/r", "chatid": "", } body.update(extra) return body def _make_channel() -> WeComChannel: return WeComChannel(config=WeComConfig(bot_id="bot1", secret="s3cret")) def test_registry_has_wecom() -> None: assert "wecom" in known_kinds() ch = create_channel("wecom", {"bot_id": "b", "secret": "s"}) assert isinstance(ch, WeComChannel) assert ch.config.bot_id == "b" def test_config_required_credentials() -> None: assert WeComConfig().missing_credentials() == ["bot_id", "secret"] cfg = WeComConfig.from_dict({"bot_id": " b1 ", "secret": "s", "ws_url": "w", "nope": 1}) assert cfg.bot_id == "b1" assert cfg.missing_credentials() == [] def test_parse_inbound_text() -> None: ch = _make_channel() frame = {"cmd": "aibot_msg_callback", "body": _text_body()} payload = dict(frame["body"]) payload["_frame"] = frame msg = ch.parse_inbound(payload) assert msg.text == "你好" assert msg.channel_subject is not None assert msg.channel_subject.subject_id == "U1" assert msg.channel_session_id == "U1" assert msg.metadata["to_handle"] == "U1" assert msg.metadata["response_url"] == "https://example.invalid/r" assert msg.metadata["_frame"] is frame def test_parse_inbound_group_session_uses_chat_id() -> None: ch = _make_channel() body = _text_body(chattype="group", chatid="G9") msg = ch.parse_inbound({**body, "_frame": {"body": body}}) assert msg.channel_session_id == "G9" assert msg.metadata["chat_id"] == "G9" # 群聊的会话主体是群:回复目标 / 会话锁键 / 历史会话键三者一致 assert msg.channel_subject is not None assert msg.channel_subject.subject_id == "G9" assert ch.get_session_key(msg) == "G9" assert msg.db_session_id == "G9" # 发送者仍保留在元数据里(用于归属展示) assert msg.metadata["to_handle"] == "U1" def test_parse_inbound_image_records_aes_key() -> None: ch = _make_channel() body = _text_body(msgtype="image", text=None) del body["text"] body["image"] = {"url": "https://img/a.png", "aeskey": "KEY"} msg = ch.parse_inbound({**body, "_frame": {"body": body}}) assert isinstance(msg.content[0], ImageContent) assert msg.metadata["_media_aes_keys"] == {"https://img/a.png": "KEY"} def test_on_message_enqueues_supported_types() -> None: ch = _make_channel() enqueued: list = [] ch.attach(lambda payload: enqueued.append(payload)) frame = {"body": _text_body()} asyncio.run(ch._on_message(frame)) assert len(enqueued) == 1 assert enqueued[0]["_frame"] is frame asyncio.run(ch._on_message({"body": {"msgtype": "event"}})) assert len(enqueued) == 1 # 非消息类型被忽略 def test_send_text_prefers_reply_stream() -> None: ch = _make_channel() ws = FakeWSClient() ch._ws_client = ws body = _text_body() msg = ch.parse_inbound({**body, "_frame": {"body": body}}) subject = msg.channel_subject subject.metadata = dict(msg.metadata) # type: ignore[union-attr] asyncio.run(ch.reply_text(subject, "回复")) assert ws.stream_calls == [{"content": "回复", "finish": True}] def test_send_text_falls_back_to_send_message() -> None: ch = _make_channel() ws = FakeWSClient() ch._ws_client = ws subject = ChannelSubject(subject_id="U1", metadata={"chat_id": "G1"}) asyncio.run(ch.reply_text(subject, "推送")) assert ws.sent == [("message", "G1", "markdown")] def test_send_text_requires_route() -> None: ch = _make_channel() ch._ws_client = FakeWSClient() subject = ChannelSubject(subject_id="", metadata={}) with pytest.raises(RuntimeError, match="缺 chat_id"): asyncio.run(ch.reply_text(subject, "x")) def test_push_strips_ephemeral_meta() -> None: ch = _make_channel() ws = FakeWSClient() ch._ws_client = ws ch._known_subjects["U1"] = ChannelSubject( subject_id="U1", metadata={"chat_id": "G1", "_frame": {"x": 1}, "response_url": "https://r"}, ) asyncio.run(ch.push_text(ChannelSubject(subject_id="U1"), "主动")) # _frame/response_url 被剥离后走 send_message 而不是帧内回复 assert ws.stream_calls == [] assert ws.sent == [("message", "G1", "markdown")] def test_send_media_uploads_and_replies() -> None: ch = _make_channel() ws = FakeWSClient() ch._ws_client = ws body = _text_body() msg = ch.parse_inbound({**body, "_frame": {"body": body}}) subject = msg.channel_subject subject.metadata = dict(msg.metadata) # type: ignore[union-attr] media = ImageContent(data="aW1n", mime_type="image/png") # base64("img") asyncio.run(ch.reply_media(subject, media)) assert ws.sent == [("reply_media", "image", "M1")] def test_start_missing_credentials_raises() -> None: ch = WeComChannel(config=WeComConfig()) async def _run() -> None: await ch.start() with pytest.raises(ChannelCredentialsError, match="缺少必要凭据"): asyncio.run(_run()) def test_probe_missing_credentials_is_incomplete() -> None: st = asyncio.run(probe_channel("wecom", {})) assert st.connected is False assert st.reason == "error" assert "探测未完成" in st.detail assert "bot_id" in st.detail