"""IM 服务入口测试:数据库装配、端到端闭环与回复上下文透传。""" from __future__ import annotations import asyncio import json from pathlib import Path from typing import Any, ClassVar import pytest from bot042.channels.base import BaseChannel from bot042.channels.models import ( ChannelConfig, ChannelSubject, InboundMessage, TextContent, ) from bot042.channels.registry import register_channel from bot042.config import Settings from bot042.db import repo from bot042.db.schema import init_db from bot042.flows import builtin, service class RecordingConfig(ChannelConfig): """测试渠道配置:label 用于验证 DB 配置是否传入。""" label: str = "" class RecordingChannel(BaseChannel): """测试渠道:记录每次发送的 (回复上下文, 文本)。""" channel_type = "recording" instances: ClassVar[list[RecordingChannel]] = [] def __init__( self, processor: Any = None, *, config: RecordingConfig | None = None, channel_id: str | None = None, **kwargs: Any, ) -> None: super().__init__(processor, config=config, channel_id=channel_id, **kwargs) self.sent: list[tuple[str, str]] = [] RecordingChannel.instances.append(self) async def start(self) -> None: pass async def stop(self) -> None: pass def parse_inbound(self, raw_payload: Any) -> InboundMessage: if isinstance(raw_payload, InboundMessage): return raw_payload return InboundMessage( channel_id=self.channel_id, channel_type=self.channel_type, channel_subject=ChannelSubject(subject_id="u1"), content=[TextContent(text=str(raw_payload))], ) def get_subject(self, subject_id: str) -> ChannelSubject | None: return ChannelSubject(subject_id=subject_id) async def _send_text(self, subject: ChannelSubject, text: str) -> None: self.sent.append((str((subject.metadata or {}).get("_frame", "")), text)) async def _send_content(self, subject: ChannelSubject, parts: list) -> None: pass async def _send_media(self, subject: ChannelSubject, media: Any) -> None: pass register_channel("recording", RecordingChannel, RecordingConfig) async def _seed_db(db: Path, *, name: str = "im-test", enabled: int = 1) -> None: await init_db(db) await repo.add_channel( db, name=name, kind="recording", config=json.dumps({"label": "from-db"}), enabled=enabled, ) def test_load_channels_reads_enabled_config(tmp_path: Path) -> None: db = tmp_path / "bot.db" async def _run() -> list[BaseChannel]: await _seed_db(db) return await service.load_channels(db, names=["im-test"]) channels = asyncio.run(_run()) assert len(channels) == 1 channel = channels[0] assert channel.channel_id == "im-test" assert isinstance(channel.config, RecordingConfig) assert channel.config.label == "from-db" def test_load_channels_skips_disabled_and_unknown(tmp_path: Path) -> None: db = tmp_path / "bot.db" async def _run() -> None: await _seed_db(db, enabled=0) with pytest.raises(ValueError, match="没有可启动的渠道"): await service.load_channels(db, names=["im-test"]) asyncio.run(_run()) def test_load_channels_skips_unknown_kind(tmp_path: Path) -> None: db = tmp_path / "bot.db" async def _run() -> None: await init_db(db) await repo.add_channel(db, name="ghost", kind="not-registered", config="{}") with pytest.raises(ValueError, match="没有可启动的渠道"): await service.load_channels(db, names=["ghost"]) asyncio.run(_run()) def test_run_service_end_to_end( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """DB 配置 → 渠道入站 → 事件总线 → 任务 → 智能体 → RPC 出站。""" RecordingChannel.instances.clear() async def fake_run_task( task, settings=None, history=None, *, cache=None, steering=None ): assert task == "hello" return {"messages": [{"role": "assistant", "content": "答:" + task}]} monkeypatch.setattr(builtin, "run_task", fake_run_task) db = tmp_path / "bot.db" async def _run() -> tuple[list[tuple[str, str]], list[str], str]: await _seed_db(db) stop = asyncio.Event() started: list[list[str]] = [] task = asyncio.create_task( service.run_service( Settings(home=tmp_path), db=db, names=["im-test"], stop_event=stop, on_started=started.append, drain_timeout=2, ) ) for _ in range(100): if RecordingChannel.instances: break await asyncio.sleep(0.01) channel = RecordingChannel.instances[-1] channel.enqueue("hello") for _ in range(200): if channel.sent: break await asyncio.sleep(0.01) stop.set() returned = await task rows = await repo.list_messages(db, session_id="im-test:u1") content = rows[0]["content"] if rows else "" return channel.sent, returned, content sent, returned, first_message = asyncio.run(_run()) assert returned == ["im-test"] assert sent == [("", "答:hello")] assert first_message == "hello" def test_run_service_passes_reply_context( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """入站带 IM 帧时,出站必须保留该上下文(走 reply 而非 push)。""" RecordingChannel.instances.clear() async def fake_run_task( task, settings=None, history=None, *, cache=None, steering=None ): return {"messages": [{"role": "assistant", "content": "ok"}]} monkeypatch.setattr(builtin, "run_task", fake_run_task) db = tmp_path / "bot.db" async def _run() -> list[tuple[str, str]]: await _seed_db(db) stop = asyncio.Event() task = asyncio.create_task( service.run_service( Settings(home=tmp_path), db=db, names=["im-test"], stop_event=stop, drain_timeout=2, ) ) for _ in range(100): if RecordingChannel.instances: break await asyncio.sleep(0.01) channel = RecordingChannel.instances[-1] channel.enqueue( InboundMessage( channel_id=channel.channel_id, channel_type=channel.channel_type, channel_subject=ChannelSubject(subject_id="u1"), content=[TextContent(text="hi")], metadata={"_frame": {"headers": {"req_id": "r1"}}, "chat_id": "u1"}, ) ) for _ in range(200): if channel.sent: break await asyncio.sleep(0.01) stop.set() await task return channel.sent sent = asyncio.run(_run()) assert len(sent) == 1 frame, text = sent[0] assert text == "ok" assert "req_id" in frame