Files
bot042/tests/test_service.py
T
openbot 2dde0d1160 feat(flows): 媒体入站进出站链路接线(issue #1 P0)
上一轮提交 9ce0ba0 把 media.py / outbox.py 的骨架铺好了,但没有任何调用方:
入站附件进不了上下文,出站 MediaOutbox 从不被创建,send_image / send_file
两个工具因此恒定返回「当前不在渠道会话中」。本次把链路接上。

入站:
- AgentReply 改用 prepare_inbound 整理分片:小图内联为 image_url 块,
  大图与音视频退化为「路径 + 元信息」,文本类文件抽取正文进上下文
- 附件全部失败时回「附件未能接收:<原因>」,不再误报成「(无输出)」
- 正文用 prepared.summary(正文 + 附件清单),历史只存清单不存字节
- 只有正文发纯文本,带附件才发 content blocks(is_multimodal)

出站:
- 每轮创建一个 MediaOutbox 传给 run_task / stream_task,工具往里登记分片,
  跑完 drain() 出来与正文合成一条 OutboundContent
- 只有媒体没有正文时不再补「(无输出)」;流式通道文本定稿后单独补发媒体
- ChannelServices.send_content 统一走「先文本、再逐个媒体」

解密钩子的抽象层:
- BaseChannel.media_transform(part, raw) 默认原样返回
- BaseChannel.make_media_transform(metadata) 按单条消息构造钩子。密钥随消息
  而来,挂在渠道实例上会让并发处理的两条消息串用彼此的密钥
- ChannelServices.media_transform 从渠道取钩子,渠道未注册时返回 None
  (不解密,但也不跳过后续的类型与大小校验)
- media.py 新增 MediaTransform 类型与 store_media(transform=)。钩子在类型嗅探
  与大小判定之前执行——对密文嗅魔数只会得到 octet-stream——并在转换后对明文
  再量一次上限,因为密文没超不等于明文没超

测试:test_builtin 增加 6 条媒体用例(文本+图、纯图、附件全失败、出站下发、
仅媒体不补空文案、流式补发),test_service / test_stream 的 fake_run_task 补
outbox 形参。全量 250 passed,ruff 全绿。

P0 边界说明:本提交只做接线与抽象,不含企业微信的具体解密实现、下载限长、
CLI 媒体命令与 docs 更新,这些在下一个提交(P1)。
2026-11-10 09:46:16 +08:00

240 lines
7.1 KiB
Python

"""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, outbox=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, outbox=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