feat: 重构为 agent / channels / flows / db 分层架构

- agent: 新增 base.py 执行基类、execution.py 执行器、web.py 网络工具,
  middlewares/steering.py 中间件;移除旧的 agent.py
- channels: 新增 ChannelManager、registry、models 与 IM 渠道(企业微信),
  扩展 base.py
- flows: 新增 agent_task / bus / cron / scheduler / service / stream / rpc /
  processor / tasks / model_settings / builtin;移除旧的 task.py
- db: 新增 sqlite schema 与 repo 层
- docs: 新增架构说明、Channel × EventBus 设计、任务编写教程
- 依赖新增 aiosqlite / httpx / langgraph / primp / pydantic / ripgrep /
  wecom-aibot-sdk;新增 bot 命令入口
- 测试:232 passed
This commit is contained in:
openbot committed 2026-11-09 20:32:25 +08:00
1 parent 94421e5c2b
commit fbb01c4c83
65 files changed
+15322 -173

No files matched your search

+45 -10
View File
@@ -2,11 +2,13 @@
from __future__ import annotations
import asyncio
import pytest
from bot042.agent import get_tools as agent_get_tools
from bot042.agent import reset_robot
from bot042.agent.tools import get_tools, move, perceive, robot, speak
from bot042.agent.middlewares import get_tools, move, perceive, robot, speak
from bot042.channels import CliChannel
from bot042.config import Settings
@@ -27,32 +29,65 @@ def test_tools_registered() -> None:
def test_move_updates_state() -> None:
reset_robot()
result = move.invoke({"direction": "北", "distance": 2})
result = asyncio.run(move.ainvoke({"direction": "北", "distance": 2}))
assert robot.y == pytest.approx(2.0)
assert robot.facing == "north"
assert "[移动]" in result
bad = move.invoke({"direction": "up", "distance": 1})
bad = asyncio.run(move.ainvoke({"direction": "up", "distance": 1}))
assert "[移动失败]" in bad
def test_perceive_and_speak() -> None:
reset_robot()
assert "[感知]" in perceive.invoke({})
assert "[播报]" in speak.invoke({"text": "hello"})
assert "[感知]" in asyncio.run(perceive.ainvoke({}))
assert "[播报]" in asyncio.run(speak.ainvoke({"text": "hello"}))
assert robot.log == ["speak: hello"]
def test_cli_channel(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
def test_cli_channel(capsys: pytest.CaptureFixture[str]) -> None:
channel = CliChannel()
monkeypatch.setattr("builtins.input", lambda _prompt="": "hello")
assert channel.receive() == "hello"
channel.send("hi")
msg = channel.parse_inbound("hello")
assert msg.text == "hello"
assert msg.channel_subject is not None
assert msg.channel_subject.subject_id == "local"
async def _send() -> None:
await channel.reply_text(msg.channel_subject, "hi")
asyncio.run(_send())
assert capsys.readouterr().out.strip() == "hi"
def test_cli_channel_input_pump(monkeypatch: pytest.MonkeyPatch) -> None:
channel = CliChannel()
enqueued: list[str] = []
channel.attach(lambda payload: enqueued.append(payload))
inputs = iter(["ping", "exit"])
monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs))
async def _run() -> None:
await channel.start()
await channel.wait_closed()
await channel.stop()
asyncio.run(_run())
assert enqueued == ["ping"]
def test_cli_channel_eof_closes(monkeypatch: pytest.MonkeyPatch) -> None:
channel = CliChannel()
def raise_eof(_prompt: str = "") -> str:
raise EOFError
monkeypatch.setattr("builtins.input", raise_eof)
assert channel.receive() is None
async def _run() -> None:
await channel.start()
await channel.wait_closed()
await channel.stop()
asyncio.run(_run())
+211
View File
@@ -0,0 +1,211 @@
"""内置任务 AgentReply 测试:会话分区、落库、RPC 回复与失败提示。"""
from __future__ import annotations
import asyncio
from datetime import datetime
from pathlib import Path
from typing import Any
import pytest
from bot042.channels.base import BaseChannel
from bot042.channels.manager import ChannelManager
from bot042.channels.models import (
ChannelMessage,
ChannelSubject,
InboundMessage,
TextContent,
)
from bot042.config import Settings
from bot042.db import repo
from bot042.flows import builtin
from bot042.flows.builtin import ERROR_REPLY, RPC_SEND, AgentReply, ChannelServices
from bot042.flows.bus import EventBus
from bot042.flows.rpc import RpcHub
from bot042.flows.scheduler import CN_TZ
from bot042.flows.tasks import EventTrigger, RunStatus, TaskContext, TaskRunner
class EchoChannel(BaseChannel):
"""测试渠道:任何 subject 都视为已登记,发送记录在内存。"""
channel_type = "echo"
def __init__(self) -> None:
super().__init__(channel_id="c1")
self.sent: list[str] = []
async def start(self) -> None:
pass
async def stop(self) -> None:
pass
def parse_inbound(self, raw_payload: Any) -> InboundMessage:
assert isinstance(raw_payload, InboundMessage)
return 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(text)
async def _send_content(self, subject: ChannelSubject, parts: list) -> None:
pass
async def _send_media(self, subject: ChannelSubject, media: Any) -> None:
pass
def _envelope(
text: str, *, session: str | None = "s1", subject: str = "u1"
) -> ChannelMessage:
message = InboundMessage(
channel_id="c1",
channel_type="echo",
channel_session_id=session,
channel_subject=ChannelSubject(subject_id=subject),
content=[TextContent(text=text)],
)
return ChannelMessage.of(message, session_key=session or "")
def test_partition_key_matches_db_session_id() -> None:
"""分区键必须与会话历史使用的 session_id 一致。"""
ctx = TaskContext(
run_id="r1",
task=AgentReply.name,
event="channel.inbound",
fired_at=datetime.now(CN_TZ),
payload=_envelope("hi"),
)
assert AgentReply.partition_key(ctx) == "s1"
# 群聊:渠道锁键是发送者(user-a),历史会话键是群(chat-9),分区跟历史走
group = _envelope("hi", session="chat-9").model_copy(
update={"session_key": "user-a", "subject_id": "user-a"}
)
ctx2 = ctx.model_copy(update={"payload": group})
assert AgentReply.partition_key(ctx2) == "chat-9"
# 没有平台会话 ID 时回退「渠道:主体」,与 run() 的落库表达式一致
ctx3 = ctx.model_copy(update={"payload": _envelope("hi", session=None)})
assert AgentReply.partition_key(ctx3) == "c1:u1"
def test_db_session_id_property() -> None:
"""db_session_id 是落库与分区共用的唯一来源(消息本体与总线载荷一致)。"""
group = _envelope("hi", session="chat-9")
assert group.db_session_id == "chat-9"
assert group.message.db_session_id == "chat-9"
direct = _envelope("hi", session=None)
assert direct.db_session_id == "c1:u1"
assert direct.message.db_session_id == "c1:u1"
def test_agent_reply_persists_and_replies_via_rpc(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
calls: list[tuple[str, list]] = []
async def fake_run_task(
task, settings=None, history=None, *, cache=None, steering=None
):
calls.append((task, list(history or [])))
return {"messages": [{"role": "assistant", "content": "答:" + task}]}
monkeypatch.setattr(builtin, "run_task", fake_run_task)
async def _run() -> tuple[list[str], list[str], list[str]]:
bus = EventBus()
bus.bind_loop()
hub = RpcHub(bus)
manager = ChannelManager()
channel = EchoChannel()
await manager.add_channel(channel)
await manager.start()
_ = hub.serve(RPC_SEND, manager.rpc_send)
services = ChannelServices(
channels=manager,
settings=Settings(),
db=tmp_path / "bot.db",
hub=hub,
)
runner = TaskRunner(bus, deps=services)
runner.register(AgentReply)
_ = runner.add_task(AgentReply.name, EventTrigger(event="channel.inbound"))
await runner.start()
bus.emit("channel.inbound", _envelope("第一句"))
bus.emit("channel.inbound", _envelope("第二句"))
await runner.wait_idle(timeout=2)
await bus.wait_for_complete()
runs = runner.runs(AgentReply.name)
keys = [run.key for run in runs]
statuses = [run.status.value for run in runs]
await runner.stop()
hub.close()
await manager.stop()
return channel.sent, keys, statuses
sent, keys, statuses = asyncio.run(_run())
assert sent == ["答:第一句", "答:第二句"]
assert keys == ["s1", "s1"]
assert statuses == ["succeeded", "succeeded"]
# 第二轮上下文里有第一轮问答
assert calls[1][1] == [
{"role": "user", "content": "第一句"},
{"role": "assistant", "content": "答:第一句"},
]
rows = asyncio.run(repo.list_messages(tmp_path / "bot.db", session_id="s1"))
assert [(r["role"], r["content"]) for r in rows] == [
("user", "第一句"),
("assistant", "答:第一句"),
("user", "第二句"),
("assistant", "答:第二句"),
]
def test_agent_reply_sends_error_hint_on_failure(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
async def boom(task, settings=None, history=None, *, cache=None):
raise RuntimeError("agent down")
monkeypatch.setattr(builtin, "run_task", boom)
async def _run() -> tuple[list[str], list[RunStatus]]:
bus = EventBus()
bus.bind_loop()
hub = RpcHub(bus)
manager = ChannelManager()
channel = EchoChannel()
await manager.add_channel(channel)
await manager.start()
_ = hub.serve(RPC_SEND, manager.rpc_send)
services = ChannelServices(
channels=manager, settings=Settings(), db=tmp_path / "bot.db", hub=hub
)
runner = TaskRunner(bus, deps=services)
runner.register(AgentReply)
_ = runner.add_task(AgentReply.name, EventTrigger(event="channel.inbound"))
await runner.start()
bus.emit("channel.inbound", _envelope("会失败"))
await runner.wait_idle(timeout=2)
await bus.wait_for_complete()
statuses = [run.status for run in runner.runs(AgentReply.name)]
await runner.stop()
hub.close()
await manager.stop()
return channel.sent, statuses
sent, statuses = asyncio.run(_run())
assert sent == [ERROR_REPLY]
assert statuses == [RunStatus.FAILED]
+193
View File
@@ -0,0 +1,193 @@
"""事件总线测试:纯异步 handler 的调度、once 与 error 路由。"""
from __future__ import annotations
import asyncio
import pytest
from bot042.flows.bus import BusError, EventBus
def test_emit_schedules_async_handlers() -> None:
async def main() -> None:
bus = EventBus()
got: list[tuple[str, int]] = []
async def handler(name: str, n: int) -> None:
await asyncio.sleep(0)
got.append((name, n))
bus.on("evt", handler)
assert bus.emit("evt", "a", 1) is True
assert bus.complete is False
await bus.wait_for_complete()
assert got == [("a", 1)]
assert bus.complete is True
asyncio.run(main())
def test_once_handler_runs_single_time() -> None:
async def main() -> None:
bus = EventBus()
calls: list[int] = []
async def handler(n: int) -> None:
calls.append(n)
bus.once("evt", handler)
bus.emit("evt", 1)
bus.emit("evt", 2)
await bus.wait_for_complete()
assert calls == [1]
asyncio.run(main())
def test_handler_error_routed_to_error_event() -> None:
async def main() -> None:
bus = EventBus()
errors: list[BaseException] = []
async def on_error(exc: BaseException) -> None:
errors.append(exc)
async def boom() -> None:
raise ValueError("boom")
bus.on("error", on_error)
bus.on("go", boom)
bus.emit("go")
await bus.wait_for_complete()
assert len(errors) == 1
assert isinstance(errors[0], ValueError)
asyncio.run(main())
def test_sync_handler_rejected_at_registration() -> None:
bus = EventBus()
with pytest.raises(BusError):
bus.on("ping", lambda: None)
def test_unhandled_error_event_raises() -> None:
bus = EventBus()
with pytest.raises(ValueError):
bus.emit("error", ValueError("x"))
with pytest.raises(BusError):
bus.emit("error", "not an exception")
def test_handler_sync_failure_never_escapes_emit() -> None:
"""handler 调用时元数不匹配(同步 TypeError)不能从 emit 冒出来。"""
async def main() -> None:
bus = EventBus()
async def no_args() -> None:
pass
bus.on("evt", no_args)
assert bus.emit("evt", 1) is True # 没有 error 监听者也不抛
await bus.wait_for_complete()
errors: list[BaseException] = []
async def on_error(exc: BaseException) -> None:
errors.append(exc)
bus.on("error", on_error)
assert bus.emit("evt", 2) is True
await bus.wait_for_complete()
assert len(errors) == 1
assert isinstance(errors[0], TypeError)
asyncio.run(main())
def test_publish_subscribe_aliases() -> None:
async def main() -> None:
bus = EventBus()
got: list[int] = []
async def handler(n: int) -> None:
got.append(n)
bus.subscribe("evt", handler)
assert bus.publish("evt", 1) is True
await bus.wait_for_complete()
assert got == [1]
async def once_handler(n: int) -> None:
got.append(n * 10)
bus.subscribe_once("evt2", once_handler)
bus.publish("evt2", 2)
bus.publish("evt2", 3)
await bus.wait_for_complete()
assert got == [1, 20]
asyncio.run(main())
def test_publish_threadsafe_same_thread() -> None:
async def main() -> None:
bus = EventBus()
bus.bind_loop()
got: list[int] = []
async def handler(n: int) -> None:
got.append(n)
bus.on("evt", handler)
bus.publish_threadsafe("evt", 7)
await bus.wait_for_complete()
assert got == [7]
asyncio.run(main())
def test_publish_threadsafe_cross_thread() -> None:
import threading
async def main() -> None:
bus = EventBus()
bus.bind_loop()
got: list[int] = []
async def handler(n: int) -> None:
got.append(n)
bus.on("evt", handler)
thread = threading.Thread(target=lambda: bus.publish_threadsafe("evt", 42))
thread.start()
await asyncio.sleep(0.05)
thread.join()
await bus.wait_for_complete()
assert got == [42]
asyncio.run(main())
def test_publish_threadsafe_without_loop_raises() -> None:
bus = EventBus()
with pytest.raises(BusError, match="bind_loop"):
bus.publish_threadsafe("evt", 1)
def test_duplicate_handler_registration_rejected() -> None:
"""同一事件重复注册同一 handler 会静默覆盖并让 once 失效,注册时应报错。"""
async def main() -> None:
bus = EventBus()
async def handler() -> None:
pass
bus.once("evt", handler)
with pytest.raises(BusError):
bus.on("evt", handler)
asyncio.run(main())
+312
View File
@@ -0,0 +1,312 @@
"""channels 协议对象与 BaseChannel 模板测试。"""
from __future__ import annotations
import asyncio
import base64
from typing import Any
import pytest
from bot042.channels.base import (
ERROR_FALLBACK_TEXT,
BaseChannel,
ChannelCredentialsError,
)
from bot042.channels.models import (
ChannelConfig,
ChannelRuntimeStatus,
ChannelSubject,
ImageContent,
InboundMessage,
MessageEvent,
MessageEventType,
TextContent,
)
class DummyChannel(BaseChannel):
channel_type = "dummy"
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.sent: list[tuple[str, str]] = []
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,
content=[TextContent(text=str(raw_payload))],
channel_subject=ChannelSubject(subject_id="u1"),
)
async def _send_text(self, subject: ChannelSubject, text: str) -> None:
self.sent.append(("text", text))
async def _send_content(self, subject: ChannelSubject, parts: list) -> None:
self.sent.append(("content", str(len(parts))))
async def _send_media(self, subject: ChannelSubject, media: Any) -> None:
self.sent.append(("media", media.type))
def _message(text: str = "hi") -> InboundMessage:
return InboundMessage(
channel_id="dummy",
content=[TextContent(text=text)],
channel_subject=ChannelSubject(subject_id="u1", display_name="U"),
)
# --------------------------------------------------------------------- models
def test_inbound_message_text_and_media() -> None:
msg = InboundMessage(
channel_id="c1",
content=[TextContent(text="hi"), TextContent(text="there"), ImageContent(url="u")],
)
assert msg.text == "hi\nthere"
assert msg.has_media is True
def test_message_event_factories() -> None:
assert MessageEvent.text("x").type == MessageEventType.MESSAGE
assert MessageEvent.delta("x").type == MessageEventType.DELTA
assert MessageEvent.typing().type == MessageEventType.TYPING
assert MessageEvent.flush().type == MessageEventType.FLUSH
assert MessageEvent.thinking("t").type == MessageEventType.THINKING
assert MessageEvent.thinking_delta("t").type == MessageEventType.THINKING_DELTA
assert MessageEvent.tool_start("t").metadata["tool_name"] == "t"
assert MessageEvent.tool_end("t").metadata["tool_name"] == "t"
assert MessageEvent.completed().type == MessageEventType.COMPLETED
assert MessageEvent.error_event("boom").error == "boom"
def test_channel_config_from_dict_and_credentials() -> None:
class DemoConfig(ChannelConfig):
api_key: str = ""
required_credentials = ("api_key",)
cfg = DemoConfig.from_dict({"api_key": " k ", "unknown": 1})
assert cfg.api_key == "k"
assert cfg.missing_credentials() == []
assert DemoConfig().missing_credentials() == ["api_key"]
def test_credentials_error_fields() -> None:
exc = ChannelCredentialsError("wecom", ["bot_id", "secret"])
assert exc.kind == "wecom"
assert exc.missing == ["bot_id", "secret"]
assert isinstance(exc, ValueError)
def test_runtime_status_defaults() -> None:
st = ChannelRuntimeStatus()
assert st.connected is False
assert st.reason is None
# ----------------------------------------------------------------- BaseChannel
def test_handle_inbound_accumulates_deltas() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.delta("Hello ")
yield MessageEvent.delta("World")
yield MessageEvent.completed()
channel = DummyChannel(processor=processor)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent == [("text", "Hello World")]
assert channel.get_subject("u1") is not None
def test_handle_inbound_flush_splits_messages() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.delta("part1")
yield MessageEvent.flush()
yield MessageEvent.delta("part2")
yield MessageEvent.completed()
channel = DummyChannel(processor=processor)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent == [("text", "part1"), ("text", "part2")]
def test_handle_inbound_message_event_immediate() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.delta("buffered")
yield MessageEvent.text("now")
yield MessageEvent.completed()
channel = DummyChannel(processor=processor)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent == [("text", "buffered"), ("text", "now")]
def test_handle_inbound_thinking_gated_by_config() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.thinking("why")
yield MessageEvent.thinking_delta("why2")
yield MessageEvent.text("answer")
yield MessageEvent.completed()
hidden = DummyChannel(processor=processor)
asyncio.run(hidden.handle_inbound(_message()))
assert hidden.sent == [("text", "answer")]
shown = DummyChannel(processor=processor, config=ChannelConfig(show_thinking=True))
asyncio.run(shown.handle_inbound(_message()))
assert ("text", "[思考] why") in shown.sent
assert ("text", "[思考] why2") in shown.sent
def test_handle_inbound_tool_hints() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.tool_start("t1")
yield MessageEvent.tool_end("t1")
yield MessageEvent.completed()
channel = DummyChannel(processor=processor)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent == [("text", "[工具] t1 开始执行"), ("text", "[工具] t1 执行完成")]
def test_handle_inbound_error_event_stops_stream() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.delta("leftover")
yield MessageEvent.error_event("出错了")
yield MessageEvent.text("never")
yield MessageEvent.completed()
channel = DummyChannel(processor=processor)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent == [("text", "leftover"), ("text", "出错了")]
def test_handle_inbound_processor_exception_falls_back() -> None:
async def processor(msg: InboundMessage):
yield MessageEvent.delta("partial")
raise RuntimeError("boom")
channel = DummyChannel(processor=processor)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent == [
("text", "partial"),
("text", "处理消息时出错,请稍后再试。"),
]
def test_handle_inbound_requires_processor() -> None:
channel = DummyChannel()
with pytest.raises(RuntimeError, match="未配置消息处理器"):
asyncio.run(channel.handle_inbound(_message()))
def test_merge_inbound_and_session_key() -> None:
channel = DummyChannel()
m1 = InboundMessage(
channel_id="d",
content=[TextContent(text="a")],
channel_subject=ChannelSubject(subject_id="u1"),
)
m2 = InboundMessage(
channel_id="d",
content=[TextContent(text="b")],
channel_subject=ChannelSubject(subject_id="u1"),
)
merged = channel.merge_inbound([m1, m2])
assert merged.text == "a\nb"
assert channel.get_session_key(m1) == "u1"
assert channel.should_batch_inbound(m1) is True
def test_merge_inbound_keeps_runtime_metadata_by_reference() -> None:
"""合批不能深拷贝 metadata:里面可能挂着不可拷贝的渠道运行时对象。"""
channel = DummyChannel()
class LiveClient:
def __deepcopy__(self, memo: dict) -> LiveClient:
raise TypeError("live client cannot be deep-copied")
client = LiveClient()
m1 = InboundMessage(
channel_id="d",
content=[TextContent(text="a")],
channel_subject=ChannelSubject(subject_id="u1"),
metadata={"client": client},
timestamp=2.0,
)
m2 = InboundMessage(
channel_id="d",
content=[TextContent(text="b")],
channel_subject=ChannelSubject(subject_id="u1"),
timestamp=1.0,
)
merged = channel.merge_inbound([m1, m2])
assert merged.text == "a\nb"
assert merged.timestamp == 1.0
assert merged.metadata["client"] is client # 运行时对象按引用保留
assert merged.metadata is not m1.metadata # 映射本身独立,改合批结果不影响原消息
def test_load_media_bytes_priority(tmp_path) -> None:
channel = DummyChannel()
inline = ImageContent(data=base64.b64encode(b"img-bytes").decode(), mime_type="image/png")
raw, mime = asyncio.run(channel.load_media_bytes(inline))
assert raw == b"img-bytes"
assert mime == "image/png"
file_part = ImageContent(local_path=str(tmp_path / "x.png"))
(tmp_path / "x.png").write_bytes(b"file-bytes")
raw, _mime = asyncio.run(channel.load_media_bytes(file_part))
assert raw == b"file-bytes"
with pytest.raises(ValueError, match="data/local_path/url"):
asyncio.run(channel.load_media_bytes(ImageContent()))
def test_push_subject_merges_known_metadata() -> None:
channel = DummyChannel()
known = ChannelSubject(subject_id="u1", display_name="U", chat_type="direct", metadata={"k": "v"})
channel._known_subjects["u1"] = known
resolved = channel.resolve_push_subject(ChannelSubject(subject_id="u1"))
assert resolved.metadata["k"] == "v"
assert resolved.display_name == "U"
assert resolved.chat_type == "direct"
def test_notify_closed_wakes_waiters() -> None:
channel = DummyChannel()
async def _run() -> bool:
waiter = asyncio.create_task(channel.wait_closed())
channel.notify_closed()
await asyncio.wait_for(waiter, timeout=1)
return True
assert asyncio.run(_run()) is True
def test_process_inbound_tolerates_sync_processor_error() -> None:
"""处理器同步抛出:走统一兜底(不发散异常),并给出兜底提示。"""
def boom(_msg: InboundMessage):
raise RuntimeError("boom")
channel = DummyChannel(typing_keepalive_interval=0.01)
channel.attach(lambda payload: None, processor=boom)
asyncio.run(channel.handle_inbound(_message()))
assert channel.sent[-1] == ("text", ERROR_FALLBACK_TEXT)
+533
View File
@@ -0,0 +1,533 @@
"""ChannelManager-lite 运行时测试。"""
from __future__ import annotations
import asyncio
from typing import Any
import pytest
from bot042.channels.base import BaseChannel
from bot042.channels.manager import ChannelManager
from bot042.channels.models import (
ChannelMessage,
ChannelSubject,
InboundMessage,
MessageEvent,
OutboundContent,
OutboundText,
TextContent,
)
from bot042.flows.bus import EventBus
from bot042.flows.rpc import RpcHub
class CollectChannel(BaseChannel):
channel_type = "collect"
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.processed: list[str] = []
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,
content=[TextContent(text=str(raw_payload))],
channel_subject=ChannelSubject(subject_id="u1"),
)
async def _send_text(self, subject: ChannelSubject, text: str) -> None:
pass
async def _send_content(self, subject: ChannelSubject, parts: list) -> None:
pass
async def _send_media(self, subject: ChannelSubject, media: Any) -> None:
pass
async def _echo(msg: InboundMessage):
yield MessageEvent.text("echo:" + msg.text)
def _msg(text: str, session: str = "u1") -> InboundMessage:
return InboundMessage(
channel_id="c1",
content=[TextContent(text=text)],
channel_subject=ChannelSubject(subject_id=session),
)
async def _drain(manager: ChannelManager, timeout: float = 2.0) -> None:
await manager.wait_idle(timeout=timeout)
def test_enqueue_processes_messages() -> None:
async def _run() -> tuple[list[str], list[str]]:
received: list[str] = []
sent: list[str] = []
async def processor(msg: InboundMessage):
received.append(msg.text)
yield MessageEvent.text("echo:" + msg.text)
async def fake_send(subject: ChannelSubject, text: str) -> None:
sent.append(text)
manager = ChannelManager(processor=processor)
channel = CollectChannel(channel_id="c1")
channel._send_text = fake_send # type: ignore[method-assign]
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "ping")
await manager.wait_idle(timeout=2)
await manager.stop()
return received, sent
received, sent = asyncio.run(_run())
assert received == ["ping"]
assert sent == ["echo:ping"]
def test_publish_inbound_records_latest_and_emits() -> None:
async def _run() -> ChannelMessage:
envelopes: list[ChannelMessage] = []
manager = ChannelManager(publisher=envelopes.append)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "hello")
await _drain(manager)
latest = manager.get_latest_message("c1")
assert latest is not None
first = latest.content[0]
assert isinstance(first, TextContent)
first.text = "被改掉"
# 深拷贝:外部改动不影响管理器内部状态
copied = manager.get_latest_message("c1")
assert copied is not None and copied.text == "hello"
by_subject = manager.get_latest_message("c1", subject_id="u1")
assert by_subject is not None and by_subject.text == "hello"
assert manager.get_latest_message("nope") is None
await manager.stop()
return envelopes[0]
envelope = asyncio.run(_run())
assert envelope.channel_id == "c1"
assert envelope.subject_id == "u1"
assert envelope.session_key == "u1"
assert envelope.message.text == "hello"
def test_send_text_routes_and_rejects_unknown() -> None:
async def _run() -> list[str]:
sent: list[str] = []
async def fake_send(subject: ChannelSubject, text: str) -> None:
sent.append(f"{subject.subject_id}:{text}")
manager = ChannelManager()
channel = CollectChannel(channel_id="c1")
channel._send_text = fake_send # type: ignore[method-assign]
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "seed") # 先登记 subject
await _drain(manager)
await manager.send_text("c1", "u1", "主动推送")
assert [s.subject_id for s in manager.list_subjects("c1")] == ["u1"]
with pytest.raises(LookupError, match="未登记主体"):
await manager.send_text("c1", "ghost", "x")
with pytest.raises(ValueError, match="渠道不存在"):
await manager.send_text("nope", "u1", "x")
await manager.stop()
return sent
assert asyncio.run(_run()) == ["u1:主动推送"]
def test_rpc_send_dispatches_text_and_content() -> None:
async def _run() -> tuple[object, object, list[str]]:
sent: list[str] = []
rich: list[int] = []
async def fake_send(subject: ChannelSubject, text: str) -> None:
sent.append(text)
async def fake_content(subject: ChannelSubject, parts: list) -> None:
rich.append(len(parts))
manager = ChannelManager()
channel = CollectChannel(channel_id="c1")
channel._send_text = fake_send # type: ignore[method-assign]
channel._send_content = fake_content # type: ignore[method-assign]
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "seed")
await _drain(manager)
text_result = await manager.rpc_send(
OutboundText(channel_id="c1", subject_id="u1", text="hi")
)
content_result = await manager.rpc_send(
OutboundContent(
channel_id="c1",
subject_id="u1",
parts=[TextContent(text="rich")],
)
)
with pytest.raises(TypeError, match="不支持的出站载荷"):
await manager.rpc_send("bad")
await manager.stop()
return text_result, content_result, sent
text_result, content_result, sent = asyncio.run(_run())
assert text_result == {"sent": True}
assert content_result == {"sent": True}
assert sent == ["hi"]
def test_rpc_channel_send_over_bus() -> None:
"""端到端:任务侧通过 RPC 发消息,registry 作为 server 收到并发送。"""
async def _run() -> tuple[object, list[str]]:
bus = EventBus()
hub = RpcHub(bus)
sent: list[str] = []
async def fake_send(subject: ChannelSubject, text: str) -> None:
sent.append(text)
manager = ChannelManager()
channel = CollectChannel(channel_id="c1")
channel._send_text = fake_send # type: ignore[method-assign]
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "seed")
await _drain(manager)
hub.serve("channel.send", manager.rpc_send)
result = await hub.call(
"channel.send",
OutboundText(channel_id="c1", subject_id="u1", text="来自 RPC"),
timeout=2,
)
hub.close()
await manager.stop()
return result, sent
result, sent = asyncio.run(_run())
assert result == {"sent": True}
assert sent == ["来自 RPC"]
def test_same_session_batch_merged() -> None:
async def _run() -> list[str]:
texts: list[str] = []
async def collect(msg: InboundMessage):
texts.append(msg.text)
yield MessageEvent.text("ok")
manager = ChannelManager(processor=collect)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "a")
manager.enqueue("c1", "b")
manager.enqueue("c1", "c")
await _drain(manager)
await manager.stop()
return texts
texts = asyncio.run(_run())
# 同会话连发合批为一回合(内容拼接)
assert texts == ["a\nb\nc"]
def test_session_lock_serializes_run_in_session() -> None:
async def _run() -> list[str]:
order: list[str] = []
manager = ChannelManager(processor=_echo)
channel = CollectChannel(channel_id="c1")
async def slow(msg: InboundMessage):
order.append("msg-start")
await asyncio.sleep(0.05)
order.append("msg-end")
yield MessageEvent.text("ok")
await manager.add_channel(channel, processor=slow)
await manager.start()
async def operation() -> None:
order.append("op-start")
await asyncio.sleep(0.08)
order.append("op-end")
task = asyncio.create_task(manager.run_in_session("c1", "u1", operation))
await asyncio.sleep(0.01)
manager.enqueue("c1", "x")
await task
await _drain(manager)
await manager.stop()
return order
order = asyncio.run(_run())
# 操作与消息不会交错:要么全 op 先,要么全 msg 先(同一会话锁)
assert order in (
["op-start", "op-end", "msg-start", "msg-end"],
["msg-start", "msg-end", "op-start", "op-end"],
)
def test_wait_idle_flushes_pending() -> None:
async def _run() -> int:
count = 0
async def slow(msg: InboundMessage):
nonlocal count
await asyncio.sleep(0.02)
count += 1
yield MessageEvent.text("ok")
manager = ChannelManager(processor=slow)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
for i in range(3):
manager.enqueue("c1", _msg(f"m{i}", session=f"u{i}"))
await manager.wait_idle(timeout=2)
await manager.stop()
return count
assert asyncio.run(_run()) == 3
def test_status_transitions() -> None:
async def _run() -> None:
manager = ChannelManager(processor=_echo)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
assert manager.status("c1").reason is None
assert manager.status("ghost").reason == "unregistered"
await manager.start()
await manager.disable_channel("c1")
st = manager.status("c1")
assert st.connected is False
assert st.reason == "disabled"
await manager.enable_channel("c1")
assert manager.status("c1").reason is None
await manager.remove_channel("c1")
assert manager.status("c1").reason == "unregistered"
await manager.stop()
asyncio.run(_run())
def test_pre_lock_handler_called() -> None:
async def _run() -> list[str]:
seen: list[str] = []
async def hook(channel_id: str, message: InboundMessage) -> None:
seen.append(message.text)
manager = ChannelManager(processor=_echo)
manager.set_pre_lock_handler(hook)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", "hello")
await _drain(manager)
await manager.stop()
return seen
assert asyncio.run(_run()) == ["hello"]
def test_add_channel_duplicate_rejected() -> None:
async def _run() -> None:
manager = ChannelManager(processor=_echo)
await manager.add_channel(CollectChannel(channel_id="c1"))
try:
await manager.add_channel(CollectChannel(channel_id="c1"))
except ValueError as exc:
assert "已注册" in str(exc)
else: # pragma: no cover
raise AssertionError("重复注册应当报错")
await manager.stop()
asyncio.run(_run())
def test_push_text_routes_to_channel() -> None:
async def _run() -> list[str]:
sent: list[str] = []
manager = ChannelManager(processor=_echo)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
async def fake_send(subject: ChannelSubject, text: str) -> None:
sent.append(text)
channel._send_text = fake_send # type: ignore[method-assign]
await manager.push_text("c1", ChannelSubject(subject_id="u1"), "pushed")
await manager.stop()
return sent
assert asyncio.run(_run()) == ["pushed"]
def test_session_lock_reclaimed_when_idle() -> None:
"""会话结束后锁条目立即回收,锁表规模不随历史会话数增长。"""
async def _run() -> tuple[int, int, int]:
manager = ChannelManager(processor=_echo)
await manager.add_channel(CollectChannel(channel_id="c1"))
async def noop() -> None:
return None
for i in range(200):
await manager.run_in_session("c1", f"u{i}", noop)
after_idle = len(manager._session_locks)
gate = asyncio.Event()
async def holder_op() -> None:
await gate.wait()
holder = asyncio.create_task(manager.run_in_session("c1", "busy", holder_op))
await asyncio.sleep(0.01)
while_busy = len(manager._session_locks)
gate.set()
await holder
return after_idle, while_busy, len(manager._session_locks)
# 200 个已结束会话不留残留;在途会话只占 1 个条目,结束后归零
assert asyncio.run(_run()) == (0, 1, 0)
def test_session_lock_kept_while_waiter_pending() -> None:
"""有条目被等待时不能回收,否则新协程会拿到新锁破坏互斥。"""
async def _run() -> tuple[list[str], int]:
manager = ChannelManager(processor=_echo)
await manager.add_channel(CollectChannel(channel_id="c1"))
order: list[str] = []
gate = asyncio.Event()
async def holder_op() -> None:
order.append("holder-enter")
await gate.wait()
order.append("holder-exit")
async def waiter_op() -> None:
order.append("waiter-enter")
holder = asyncio.create_task(manager.run_in_session("c1", "u1", holder_op))
await asyncio.sleep(0.01)
waiter = asyncio.create_task(manager.run_in_session("c1", "u1", waiter_op))
await asyncio.sleep(0.01)
# 等待者阻塞期间条目必须仍在,且两者严格串行
assert len(manager._session_locks) == 1
gate.set()
await asyncio.gather(holder, waiter)
return order, len(manager._session_locks)
order, remaining = asyncio.run(_run())
assert order == ["holder-enter", "holder-exit", "waiter-enter"]
assert remaining == 0
def test_batching_keeps_channel_fifo_across_sessions() -> None:
"""合批探测到的跨会话消息不能被推回队尾(渠道内保持 FIFO)。"""
async def _run() -> list[str]:
processed: list[str] = []
async def processor(msg: InboundMessage):
processed.append(msg.text)
yield MessageEvent.text("ok")
manager = ChannelManager(processor=processor)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
for text, session in (("a", "u1"), ("b", "u2"), ("c", "u1"), ("d", "u2")):
manager.enqueue("c1", _msg(text, session))
await manager.wait_idle(timeout=2)
await manager.stop()
return processed
assert asyncio.run(_run()) == ["a", "b", "c", "d"]
def test_deferred_counter_released_when_channel_stops() -> None:
"""禁用渠道取消 worker 时,暂存计数必须归还(否则 wait_idle 永不返回)。"""
async def _run() -> tuple[int, int]:
gate = asyncio.Event()
async def processor(msg: InboundMessage):
if msg.text == "slow":
await gate.wait()
yield MessageEvent.text("ok")
manager = ChannelManager(processor=processor)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
manager.enqueue("c1", _msg("slow", "u1"))
manager.enqueue("c1", _msg("carried", "u2"))
# 等 worker 取走 u1(u2 被合批探测暂存)并卡在 slow 上
for _ in range(200):
if manager._deferred:
break
await asyncio.sleep(0.01)
assert manager._deferred == 1
await manager.disable_channel("c1")
leaked = manager._deferred
await manager.wait_idle(timeout=2)
await manager.stop()
return leaked, manager._deferred
assert asyncio.run(_run()) == (0, 0)
def test_enable_channel_is_idempotent() -> None:
"""重复启用不能叠加 worker 组(否则消息会被重复处理)。"""
async def _run() -> tuple[int, list[str]]:
processed: list[str] = []
async def processor(msg: InboundMessage):
processed.append(msg.text)
yield MessageEvent.text("ok")
manager = ChannelManager(processor=processor)
channel = CollectChannel(channel_id="c1")
await manager.add_channel(channel)
await manager.start()
await manager.enable_channel("c1")
await manager.enable_channel("c1")
workers = len(manager._workers["c1"])
manager.enqueue("c1", _msg("hi", "u1"))
await manager.wait_idle(timeout=2)
await manager.stop()
return workers, processed
workers, processed = asyncio.run(_run())
assert workers == 1
assert processed == ["hi"]
+203
View File
@@ -0,0 +1,203 @@
"""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
+79
View File
@@ -0,0 +1,79 @@
"""cron 解析与下次触发计算测试。"""
from __future__ import annotations
from datetime import datetime
import pytest
from bot042.flows.cron import CronError, parse_cron
def _next(expr: str, after: datetime) -> datetime | None:
return parse_cron(expr).next_after(after)
def test_star_step() -> None:
assert _next("*/15 * * * *", datetime(2026, 11, 6, 10, 7)) == datetime(2026, 11, 6, 10, 15)
assert _next("*/15 * * * *", datetime(2026, 11, 6, 10, 15)) == datetime(2026, 11, 6, 10, 30)
def test_daily_time() -> None:
assert _next("0 9 * * *", datetime(2026, 11, 6, 10, 0)) == datetime(2026, 11, 7, 9, 0)
assert _next("0 9 * * *", datetime(2026, 11, 6, 8, 0)) == datetime(2026, 11, 6, 9, 0)
def test_dow_names() -> None:
# 2026-11-06 是周五;当天 8:30 已过,下一次工作日 8:30 是周一 2026-11-09
assert _next("30 8 * * MON-FRI", datetime(2026, 11, 6, 9, 0)) == datetime(2026, 11, 9, 8, 30)
def test_dom_dow_or_semantics() -> None:
# 日与周同时受限时按“或”:最近的是周一 2026-11-16,而非 12-01
assert _next("0 0 1 * 1", datetime(2026, 11, 15, 0, 0)) == datetime(2026, 11, 16, 0, 0)
# 只约束周:2026-11-30 是周一,严格晚于它的是 2026-12-07
assert _next("0 0 * * 1", datetime(2026, 11, 30, 0, 0)) == datetime(2026, 12, 7, 0, 0)
def test_dow_seven_is_sunday() -> None:
assert _next("0 0 * * 7", datetime(2026, 11, 6)) == datetime(2026, 11, 8)
assert _next("0 0 * * 0", datetime(2026, 11, 6)) == datetime(2026, 11, 8)
def test_leap_day() -> None:
assert _next("0 0 29 2 *", datetime(2026, 3, 1)) == datetime(2028, 2, 29)
def test_impossible_returns_none() -> None:
assert _next("0 0 30 2 *", datetime(2026, 1, 1)) is None
def test_yearly() -> None:
assert _next("0 0 1 1 *", datetime(2026, 11, 6)) == datetime(2027, 1, 1)
def test_range_with_step() -> None:
assert _next("0-30/10 12 * * *", datetime(2026, 11, 6, 12, 0)) == datetime(2026, 11, 6, 12, 10)
def test_full_range_counts_as_star() -> None:
"""`0-6`、`*/1`、`1-31` 语义等价于 `*`,不应触发 DOM/DOW 的 OR 规则。"""
after = datetime(2026, 11, 15, 12, 0)
assert _next("0 0 1 * 0-6", after) == datetime(2026, 12, 1)
assert _next("0 0 1 * */1", after) == datetime(2026, 12, 1)
assert _next("0 0 1-31 * 1", after) == datetime(2026, 11, 16) # 周受限 → 仍是"或"
def test_invalid_expressions() -> None:
with pytest.raises(CronError):
parse_cron("* * * *")
with pytest.raises(CronError):
parse_cron("61 * * * *")
with pytest.raises(CronError):
parse_cron("* * * * 8")
with pytest.raises(CronError):
parse_cron("*/0 * * * *")
with pytest.raises(CronError):
parse_cron("b-x * * * *")
with pytest.raises(CronError):
parse_cron("1-0 * * * *")
+195
View File
@@ -0,0 +1,195 @@
"""数据库 CRUD 与关联同步测试(aiosqlite 异步)。"""
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
from bot042.db import repo
from bot042.home import db_path, init_home
@pytest.fixture()
def db(tmp_path: Path) -> Path:
return db_path(asyncio.run(init_home(tmp_path / "home")))
def test_provider_crud_and_cascade(db: Path) -> None:
pid = asyncio.run(repo.add_provider(db, name="testp", base_url="https://x/v1", api_key="sk-abc12345678"))
row = asyncio.run(repo.get_provider(db, name="testp"))
assert row["id"] == pid
assert row["api_key"] == "sk-abc12345678"
asyncio.run(repo.update_provider(db, pid, base_url="https://y/v1", enabled=0))
row = asyncio.run(repo.get_provider(db, provider_id=pid))
assert row["base_url"] == "https://y/v1"
assert row["enabled"] == 0
mid = asyncio.run(repo.add_model(db, provider="testp", name="m1"))
sid = asyncio.run(repo.add_session(db, model_id=mid))
asyncio.run(repo.delete_provider(db, pid))
assert asyncio.run(repo.get_provider(db, provider_id=pid)) is None
assert asyncio.run(repo.list_models(db, provider="testp")) == []
assert asyncio.run(repo.get_session(db, sid))["model_id"] is None
def test_model_default_is_exclusive(db: Path) -> None:
asyncio.run(repo.add_provider(db, name="p1"))
m1 = asyncio.run(repo.add_model(db, provider="p1", name="a", is_default=True))
m2 = asyncio.run(repo.add_model(db, provider="p1", name="b", is_default=True))
rows = {row["name"]: row for row in asyncio.run(repo.list_models(db, provider="p1"))}
assert rows["a"]["is_default"] == 0
assert rows["b"]["is_default"] == 1
asyncio.run(repo.update_model(db, m1, is_default=1))
rows = {row["name"]: row for row in asyncio.run(repo.list_models(db, provider="p1"))}
assert rows["a"]["is_default"] == 1
assert rows["b"]["is_default"] == 0
assert m2 != m1
def test_delete_model_detaches_sessions(db: Path) -> None:
mid = asyncio.run(repo.add_model(db, provider="openai", name="tmp-model"))
sid = asyncio.run(repo.add_session(db, model_id=mid))
asyncio.run(repo.delete_model(db, mid))
assert asyncio.run(repo.get_model(db, mid)) is None
assert asyncio.run(repo.get_session(db, sid))["model_id"] is None
def test_session_crud(db: Path) -> None:
sid = asyncio.run(repo.add_session(db, channel="cli", title="第一次", model_id=None))
assert asyncio.run(repo.get_session(db, sid))["title"] == "第一次"
asyncio.run(repo.update_session(db, sid, status="closed", title="改名"))
row = asyncio.run(repo.get_session(db, sid))
assert row["status"] == "closed"
assert row["title"] == "改名"
assert [r["id"] for r in asyncio.run(repo.list_sessions(db, status="closed"))] == [sid]
assert asyncio.run(repo.list_sessions(db, status="active")) == []
asyncio.run(repo.delete_session(db, sid))
assert asyncio.run(repo.get_session(db, sid)) is None
def test_message_crud_and_cascade(db: Path) -> None:
sid = asyncio.run(repo.add_session(db, channel="cli", title="消息测试"))
mid = asyncio.run(repo.add_message(db, session_id=sid, role="user", content="hello"))
assert mid > 0
asyncio.run(repo.add_message(db, session_id=sid, role="assistant", content="world", channel="cli"))
rows = asyncio.run(repo.list_messages(db, session_id=sid))
assert [(r["role"], r["content"]) for r in rows] == [("user", "hello"), ("assistant", "world")]
# limit 取最近 N 条,仍按时间正序返回
rows = asyncio.run(repo.list_messages(db, session_id=sid, limit=1))
assert [r["content"] for r in rows] == ["world"]
# 会话不存在 → 外键拒绝
with pytest.raises(ValueError, match="会话不存在"):
asyncio.run(repo.add_message(db, session_id="nope", role="user", content="x"))
# 删除会话 → 消息级联删除
asyncio.run(repo.delete_session(db, sid))
assert asyncio.run(repo.list_messages(db, session_id=sid)) == []
def test_ensure_session_idempotent(db: Path) -> None:
sid = asyncio.run(repo.ensure_session(db, session_id="s-fixed", channel="cli", title="T"))
assert sid == "s-fixed"
sid = asyncio.run(repo.ensure_session(db, session_id="s-fixed", channel="cli"))
assert sid == "s-fixed"
sessions = asyncio.run(repo.list_sessions(db))
assert [s["id"] for s in sessions] == ["s-fixed"]
def test_channel_crud(db: Path) -> None:
cid = asyncio.run(repo.add_channel(db, name="http", kind="http", config='{"port": 8000}'))
assert asyncio.run(repo.get_channel(db, name="http"))["id"] == cid
asyncio.run(repo.update_channel(db, name="http", enabled=0))
assert asyncio.run(repo.get_channel(db, channel_id=cid))["enabled"] == 0
asyncio.run(repo.update_channel(db, name="web", channel_id=cid))
assert asyncio.run(repo.get_channel(db, channel_id=cid))["name"] == "web"
asyncio.run(repo.delete_channel(db, channel_id=cid))
assert asyncio.run(repo.get_channel(db, channel_id=cid)) is None
def test_setting_crud(db: Path) -> None:
asyncio.run(repo.add_setting(db, key="demo.key", value="1", description="演示"))
assert asyncio.run(repo.get_setting(db, "demo.key"))["value"] == "1"
asyncio.run(repo.update_setting(db, "demo.key", value="2"))
assert asyncio.run(repo.get_setting(db, "demo.key"))["value"] == "2"
asyncio.run(repo.delete_setting(db, "demo.key"))
assert asyncio.run(repo.get_setting(db, "demo.key")) is None
def test_invalid_operations(db: Path) -> None:
with pytest.raises(ValueError, match="提供商不存在"):
asyncio.run(repo.add_model(db, provider="nope", name="x"))
asyncio.run(repo.add_provider(db, name="dup"))
with pytest.raises(ValueError, match="提供商已存在"):
asyncio.run(repo.add_provider(db, name="dup"))
with pytest.raises(ValueError, match="没有需要更新的字段"):
asyncio.run(repo.update_provider(db, 1))
with pytest.raises(ValueError, match="模型不存在"):
asyncio.run(repo.add_session(db, model_id=99999))
with pytest.raises(ValueError, match="参数不存在"):
asyncio.run(repo.delete_setting(db, "nope"))
def test_cli_db_add_and_list(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys) -> None:
monkeypatch.setenv("BOT042_HOME", str(tmp_path / "home"))
asyncio.run(init_home(tmp_path / "home"))
from bot042.__main__ import main
assert main(["db", "--provider", "--add", "--name", "clip", "--base-url", "https://c/v1"]) == 0
assert "已新增 provider" in capsys.readouterr().out
assert main(["db", "--provider", "--list"]) == 0
out = capsys.readouterr().out
assert "clip" in out
pid = asyncio.run(repo.get_provider(db_path(tmp_path / "home"), name="clip"))["id"]
assert main(["db", "--provider", "--delete", "--id", str(pid)]) == 0
assert "已删除 provider" in capsys.readouterr().out
assert main(["db", "--setting", "--add", "--key", "k1", "--value", "v1"]) == 0
assert "已新增 setting" in capsys.readouterr().out
assert main(["db", "--model", "--list"]) == 0
assert "gpt-4o-mini" in capsys.readouterr().out
def test_cli_channel_add_requires_kind(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys
) -> None:
"""省略 --kind 时必须报错,不能把渠道名当成类型落库。"""
monkeypatch.setenv("BOT042_HOME", str(tmp_path / "home"))
asyncio.run(init_home(tmp_path / "home"))
from bot042.__main__ import main
assert main(["db", "--channel", "--add", "--name", "wecom-main"]) == 1
assert "缺少参数 --kind" in capsys.readouterr().out
assert (
asyncio.run(repo.get_channel(db_path(tmp_path / "home"), name="wecom-main")) is None
)
assert main(["db", "--channel", "--add", "--name", "wecom-main", "--kind", "wecom"]) == 0
row = asyncio.run(repo.get_channel(db_path(tmp_path / "home"), name="wecom-main"))
assert row is not None and row["kind"] == "wecom"
+71
View File
@@ -0,0 +1,71 @@
"""本地执行能力测试:run_python 与无沙箱 shell 后端。"""
from __future__ import annotations
import asyncio
from pathlib import Path
from bot042.agent.base import _build_backend
from bot042.agent.execution import run_python
from bot042.agent.tools import get_tools
from bot042.config import Settings
def test_run_python_prints_stdout() -> None:
out = asyncio.run(run_python.ainvoke({"code": "print(1 + 1)"}))
assert "[退出码 0]" in out
assert "2" in out
def test_run_python_multiline_and_unicode() -> None:
code = "def f(n):\n return n * 2\n\nprint('结果', f(3))"
out = asyncio.run(run_python.ainvoke({"code": code}))
assert "[退出码 0]" in out
assert "结果 6" in out
def test_run_python_reports_stderr_and_exit_code() -> None:
code = "import sys\nprint('bad', file=sys.stderr)\nsys.exit(3)"
out = asyncio.run(run_python.ainvoke({"code": code}))
assert "[退出码 3]" in out
assert "[stderr]" in out
assert "bad" in out
def test_run_python_times_out() -> None:
out = asyncio.run(run_python.ainvoke({"code": "import time\ntime.sleep(10)", "timeout": 1}))
assert "执行超时" in out
def test_run_python_rejects_empty_code() -> None:
out = asyncio.run(run_python.ainvoke({"code": " "}))
assert "[执行失败]" in out
def test_get_tools_includes_run_python() -> None:
names = {tool.name for tool in get_tools()}
assert "run_python" in names
def test_backend_is_local_shell_with_home_root(tmp_path: Path) -> None:
backend = _build_backend(Settings(home=tmp_path))
assert backend.cwd == tmp_path.resolve()
assert tmp_path.is_dir()
def test_backend_executes_shell_command(tmp_path: Path) -> None:
backend = _build_backend(Settings(home=tmp_path))
result = backend.execute("echo hello")
assert result.exit_code == 0
assert "hello" in result.output
+143
View File
@@ -0,0 +1,143 @@
"""异步链路测试:run_task / run_session 走 ainvoke。"""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
from bot042.channels.base import BaseChannel
from bot042.channels.models import ChannelSubject, InboundMessage, TextContent
from bot042.config import Settings
from bot042.flows.agent_task import last_message_text, run_task
from bot042.flows.session import run_session
class FakeAgent:
"""只实现异步入口的假智能体;调用同步 invoke 视为失败。"""
def __init__(self, reply: str = "ok") -> None:
self.reply = reply
self.calls: list[tuple[dict[str, Any], dict[str, Any] | None]] = []
async def ainvoke(
self,
state: dict[str, Any],
config: dict[str, Any] | None = None,
) -> dict[str, Any]:
self.calls.append((state, config))
return {"messages": [{"role": "assistant", "content": self.reply}]}
def invoke(self, *args: Any, **kwargs: Any) -> dict[str, Any]: # pragma: no cover
raise AssertionError("不应调用同步 invoke")
class FakeChannel(BaseChannel):
"""测试用虚拟渠道:start() 时把全部输入入队并关闭会话。"""
channel_type = "fake"
def __init__(self, inputs: list[str | None]) -> None:
super().__init__()
self._inputs = [i for i in inputs if i is not None]
self.sent: list[str] = []
async def start(self) -> None:
for line in self._inputs:
if line.lower() in {"exit", "quit"}:
break
self.enqueue(line)
self.notify_closed()
async def stop(self) -> None:
pass
def should_batch_inbound(self, message: InboundMessage) -> bool:
return False
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"),
channel_session_id="s1",
content=[TextContent(text=str(raw_payload))],
)
async def _send_text(self, subject: ChannelSubject, text: str) -> None:
self.sent.append(text)
async def _send_content(self, subject: ChannelSubject, parts: list) -> None:
pass
async def _send_media(self, subject: ChannelSubject, media: Any) -> None:
pass
def test_run_task_uses_async_ainvoke(monkeypatch) -> None:
fake = FakeAgent("done")
monkeypatch.setattr("bot042.flows.agent_task.create_agent", lambda settings=None: fake)
settings = Settings(max_steps=7)
result = asyncio.run(run_task("hi", settings))
assert last_message_text(result) == "done"
state, config = fake.calls[0]
assert state["messages"][-1] == {"role": "user", "content": "hi"}
assert config == {"recursion_limit": 7}
def test_last_message_text_multimodal_content() -> None:
result = {
"messages": [
{
"role": "assistant",
"content": [
{"type": "text", "text": "你好"},
{"type": "image_url", "image_url": "https://example.com/a.png"},
],
}
]
}
assert last_message_text(result) == "你好"
assert last_message_text({"messages": []}) == ""
# 多个文本块之间用换行分隔,不粘连
multi = {"messages": [{"content": [{"text": "第一段"}, {"text": "第二段"}]}]}
assert last_message_text(multi) == "第一段\n第二段"
def test_run_session_reuses_agent(monkeypatch, tmp_path: Path) -> None:
"""会话内多条消息只构建一次智能体。"""
fake = FakeAgent("pong")
built: list[Any] = []
def factory(settings=None):
built.append(settings)
return fake
monkeypatch.setattr("bot042.flows.agent_task.create_agent", factory)
channel = FakeChannel(["a", "b", "c", "exit"])
asyncio.run(run_session(channel, db=tmp_path / "bot.db"))
assert len(built) == 1 # 只构建一次
assert len(fake.calls) == 3
def test_run_session_async_loop(monkeypatch, tmp_path: Path) -> None:
fake = FakeAgent("pong")
monkeypatch.setattr("bot042.flows.agent_task.create_agent", lambda settings=None: fake)
channel = FakeChannel(["ping", "again", "exit"])
asyncio.run(run_session(channel, db=tmp_path / "bot.db"))
assert channel.sent == ["pong", "pong"]
assert len(fake.calls) == 2
# 第二轮带上了第一轮的 messages 历史
history, _config = fake.calls[1]
assert [m["role"] for m in history["messages"]] == ["user", "assistant", "user"]
assert history["messages"][0] == {"role": "user", "content": "ping"}
assert history["messages"][-1] == {"role": "user", "content": "again"}
+219
View File
@@ -0,0 +1,219 @@
"""测试 home 目录与数据库初始化(aiosqlite 异步)。"""
from __future__ import annotations
import asyncio
import sqlite3
import pytest
from bot042.db import SCHEMA_VERSION, connect, repo
from bot042.db.schema import init_db
from bot042.home import HOME_SUBDIRS, db_path, init_home, resolve_home
_EXPECTED_TABLES = {"providers", "models", "sessions", "channels", "settings", "messages"}
def _query(db_file, sql: str) -> list[dict]:
async def _run() -> list[dict]:
conn = await connect(db_file)
try:
cur = await conn.execute(sql)
return [dict(row) for row in await cur.fetchall()]
finally:
await conn.close()
return asyncio.run(_run())
def _tables(db_file) -> set[str]:
return {row["name"] for row in _query(db_file, "SELECT name FROM sqlite_master WHERE type = 'table'")}
def test_resolve_default_home() -> None:
assert resolve_home().name == ".bot042"
assert resolve_home("~/custom").is_absolute()
def test_init_home_creates_db(tmp_path) -> None:
root = asyncio.run(init_home(tmp_path / "home"))
assert root.is_dir()
db_file = db_path(root)
assert db_file.is_file()
assert db_file.name == "bot.db"
assert _EXPECTED_TABLES <= _tables(db_file)
def test_init_home_creates_subdirs(tmp_path) -> None:
root = asyncio.run(init_home(tmp_path / "home"))
for name in HOME_SUBDIRS:
assert (root / name).is_dir(), name
assert HOME_SUBDIRS == ("wiki", "logs", "tmp", "data", "scripts")
def test_legacy_db_is_migrated(tmp_path) -> None:
root = tmp_path / "home"
root.mkdir()
(root / "bot042.db").write_bytes(b"")
asyncio.run(init_home(root))
assert (root / "bot.db").is_file()
assert not (root / "bot042.db").exists()
def test_migrate_v1_api_key_env_to_api_key(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "sk-env-key-123")
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
root = tmp_path / "home"
root.mkdir()
db_file = db_path(root)
conn = sqlite3.connect(db_file)
conn.executescript(
"""
CREATE TABLE providers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL DEFAULT 'openai',
base_url TEXT,
api_key_env TEXT,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
"""
)
conn.execute("INSERT INTO providers (name, api_key_env) VALUES ('openai', 'OPENAI_API_KEY')")
conn.execute("INSERT INTO providers (name, api_key_env) VALUES ('deepseek', 'DEEPSEEK_API_KEY')")
conn.execute("PRAGMA user_version = 1")
conn.commit()
conn.close()
asyncio.run(init_home(root))
rows = {row["name"]: row["api_key"] for row in _query(db_file, "SELECT name, api_key FROM providers")}
assert rows["openai"] == "sk-env-key-123" # 环境变量值回填
assert rows["deepseek"] is None # 环境变量不存在则置空
assert _query(db_file, "PRAGMA user_version")[0]["user_version"] == 3
def test_init_home_seeds_defaults(tmp_path) -> None:
root = asyncio.run(init_home(tmp_path / "home"))
db_file = db_path(root)
providers = {row["name"] for row in _query(db_file, "SELECT name FROM providers")}
assert {"openai", "deepseek"} <= providers
models = {row["name"] for row in _query(db_file, "SELECT name FROM models")}
assert {"gpt-4o-mini", "deepseek-chat"} <= models
channels = {row["name"] for row in _query(db_file, "SELECT name FROM channels")}
assert "cli" in channels
rows = _query(db_file, "SELECT value FROM settings WHERE key = 'agent.default_model'")
assert rows[0]["value"] == "openai:gpt-4o-mini"
version = _query(db_file, "PRAGMA user_version")[0]["user_version"]
assert version == SCHEMA_VERSION
def test_init_home_is_idempotent(tmp_path) -> None:
root = asyncio.run(init_home(tmp_path / "home"))
asyncio.run(init_home(root))
db_file = db_path(root)
provider_count = _query(db_file, "SELECT COUNT(*) AS n FROM providers")[0]["n"]
model_count = _query(db_file, "SELECT COUNT(*) AS n FROM models")[0]["n"]
assert provider_count == 2
assert model_count == 2
def test_cli_init(tmp_path, capsys: pytest.CaptureFixture[str]) -> None:
from bot042.__main__ import main
target = tmp_path / "bot_home"
assert main(["init", str(target)]) == 0
assert db_path(target).is_file()
out = capsys.readouterr().out
assert "初始化完成" in out
assert "schema v" in out
assert "wiki/" in out
def test_reinit_does_not_resurrect_deleted_seeds(tmp_path) -> None:
"""再次初始化不能把用户删掉的种子行补回来(也不能多出一个默认模型)。"""
db_file = tmp_path / "bot.db"
async def _run() -> None:
await init_db(db_file)
provider = await repo.get_provider(db_file, name="openai")
assert provider is not None
await repo.delete_provider(db_file, provider_id=provider["id"])
await init_db(db_file)
await init_db(db_file)
asyncio.run(_run())
providers = {row["name"] for row in _query(db_file, "SELECT name FROM providers")}
assert providers == {"deepseek"}
models = {row["name"] for row in _query(db_file, "SELECT name FROM models")}
assert "gpt-4o-mini" not in models
defaults = _query(db_file, "SELECT name FROM models WHERE is_default = 1")
assert defaults == []
def test_seed_creates_single_default_model(tmp_path) -> None:
"""种子数据只产生一个默认模型(“至多一个默认”不变量)。"""
db_file = tmp_path / "bot.db"
asyncio.run(init_db(db_file))
defaults = _query(db_file, "SELECT name FROM models WHERE is_default = 1")
assert [row["name"] for row in defaults] == ["gpt-4o-mini"]
def test_init_seeds_when_tables_exist_but_empty(tmp_path) -> None:
"""上次初始化在建表后失败(无数据、无标记)时,下次仍要补写默认数据。"""
db_file = tmp_path / "bot.db"
async def _prepare() -> None:
conn = await connect(db_file)
try:
from bot042.db.schema import DDL
await conn.executescript(DDL)
await conn.commit()
finally:
await conn.close()
asyncio.run(_prepare())
asyncio.run(init_db(db_file))
providers = {row["name"] for row in _query(db_file, "SELECT name FROM providers")}
assert {"openai", "deepseek"} <= providers
marker = _query(db_file, "SELECT value FROM settings WHERE key = 'db.seeded'")
assert marker and marker[0]["value"] == "1"
def test_init_marks_legacy_db_without_reseeding(tmp_path) -> None:
"""没有标记但有数据的老库:只补标记,不再塞一遍种子。"""
db_file = tmp_path / "bot.db"
async def _prepare() -> None:
conn = await connect(db_file)
try:
from bot042.db.schema import DDL
await conn.executescript(DDL)
await conn.execute(
"INSERT INTO providers (name, kind) VALUES ('custom', 'openai')"
)
await conn.commit()
finally:
await conn.close()
asyncio.run(_prepare())
asyncio.run(init_db(db_file))
providers = {row["name"] for row in _query(db_file, "SELECT name FROM providers")}
assert providers == {"custom"}
marker = _query(db_file, "SELECT value FROM settings WHERE key = 'db.seeded'")
assert marker and marker[0]["value"] == "1"
+115
View File
@@ -0,0 +1,115 @@
"""模型配置解析测试:数据库默认模型与凭据注入、环境变量优先级。"""
from __future__ import annotations
import asyncio
from pathlib import Path
from bot042.agent.base import _build_model
from bot042.config import Settings
from bot042.db import repo
from bot042.db.schema import init_db
from bot042.flows.model_settings import resolve_model_settings
async def _seed(db: Path) -> None:
await init_db(db)
await repo.update_provider(
db,
provider_id=1,
base_url="https://gw.example.com/v1",
api_key="sk-from-db",
)
await repo.add_model(db, provider="openai", name="gw-model", is_default=True)
def test_db_config_fills_model_and_credentials(tmp_path: Path) -> None:
db = tmp_path / "bot.db"
async def _run() -> Settings:
await _seed(db)
return await resolve_model_settings(Settings(home=tmp_path), db)
resolved = asyncio.run(_run())
assert resolved.model == "openai:gw-model"
assert resolved.api_key == "sk-from-db"
assert resolved.base_url == "https://gw.example.com/v1"
def test_env_model_wins_and_skips_mismatched_credentials(tmp_path: Path) -> None:
db = tmp_path / "bot.db"
async def _run() -> Settings:
await _seed(db)
settings = Settings(
home=tmp_path,
model="openai:gpt-4o-mini",
model_explicit=True,
)
return await resolve_model_settings(settings, db)
resolved = asyncio.run(_run())
# 模型以环境变量为准;库里的 key 属于另一个模型,不能挪用
assert resolved.model == "openai:gpt-4o-mini"
assert resolved.api_key is None
assert resolved.base_url is None
def test_db_sets_agent_max_steps(tmp_path: Path) -> None:
db = tmp_path / "bot.db"
async def _run() -> Settings:
await _seed(db)
await repo.update_setting(db, "agent.max_steps", value="77")
return await resolve_model_settings(Settings(home=tmp_path), db)
assert asyncio.run(_run()).max_steps == 77
def test_env_max_steps_wins_over_db(tmp_path: Path) -> None:
db = tmp_path / "bot.db"
async def _run() -> Settings:
await _seed(db)
await repo.update_setting(db, "agent.max_steps", value="77")
settings = Settings(home=tmp_path, max_steps=5, max_steps_explicit=True)
return await resolve_model_settings(settings, db)
assert asyncio.run(_run()).max_steps == 5
def test_invalid_db_max_steps_keeps_default(tmp_path: Path) -> None:
db = tmp_path / "bot.db"
async def _run() -> Settings:
await _seed(db)
await repo.update_setting(db, "agent.max_steps", value="abc")
return await resolve_model_settings(Settings(home=tmp_path), db)
assert asyncio.run(_run()).max_steps == 200
def test_missing_db_keeps_env_settings(tmp_path: Path) -> None:
settings = Settings(home=tmp_path, api_key="sk-env")
resolved = asyncio.run(resolve_model_settings(settings, tmp_path / "none.db"))
assert resolved == settings
def test_build_model_uses_credentials(tmp_path: Path) -> None:
settings = Settings(
home=tmp_path,
model="openai:gw-model",
api_key="sk-x",
base_url="https://gw.example.com/v1",
)
model = _build_model(settings)
assert model.model_name == "gw-model"
if hasattr(model, "openai_api_base"):
assert model.openai_api_base == "https://gw.example.com/v1"
def test_build_model_falls_back_to_string(tmp_path: Path) -> None:
settings = Settings(home=tmp_path, model="openai:gpt-4o-mini")
assert _build_model(settings) == "openai:gpt-4o-mini"
+228
View File
@@ -0,0 +1,228 @@
"""make_processor 测试:messages 历史、事件流与错误分支(stub run_task)。"""
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
from bot042.channels.models import (
ChannelSubject,
ImageContent,
InboundMessage,
MessageEventType,
TextContent,
)
from bot042.db import repo
from bot042.flows import processor as processor_mod
from bot042.flows.processor import make_processor
def _message(text: str, *, session: str = "cli", media: bool = False) -> InboundMessage:
content = []
if text:
content.append(TextContent(text=text))
if media:
content.append(ImageContent(url="https://img/x.png"))
return InboundMessage(
channel_id="cli",
channel_type="cli",
channel_subject=ChannelSubject(subject_id="local"),
channel_session_id=session,
content=content or [TextContent(text="")],
)
def _events(processor, message) -> list:
async def _collect() -> list:
return [event async for event in processor(message)]
return asyncio.run(_collect())
def test_processor_persists_and_reuses_history(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
calls: list[tuple[str, list]] = []
async def fake_run_task(task, settings=None, history=None, *, cache=None):
calls.append((task, list(history or [])))
return {"messages": [{"role": "assistant", "content": "答复:" + task}]}
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
db = tmp_path / "bot.db"
processor = make_processor(db=db)
events = _events(processor, _message("第一句"))
assert [e.type for e in events] == [
MessageEventType.TYPING,
MessageEventType.MESSAGE,
MessageEventType.COMPLETED,
]
assert events[1].content[0].text == "答复:第一句" # type: ignore[union-attr]
events = _events(processor, _message("第二句"))
assert events[1].content[0].text == "答复:第二句" # type: ignore[union-attr]
# 第二轮的历史包含第一轮问答
assert calls[0] == ("第一句", [])
assert calls[1][0] == "第二句"
assert calls[1][1] == [
{"role": "user", "content": "第一句"},
{"role": "assistant", "content": "答复:第一句"},
]
rows = asyncio.run(repo.list_messages(db, session_id="cli"))
assert [(r["role"], r["content"]) for r in rows] == [
("user", "第一句"),
("assistant", "答复:第一句"),
("user", "第二句"),
("assistant", "答复:第二句"),
]
sessions = asyncio.run(repo.list_sessions(db))
assert [s["id"] for s in sessions] == ["cli"]
def test_processor_session_isolated_per_key(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
async def fake_run_task(task, settings=None, history=None, *, cache=None):
return {"messages": [{"role": "assistant", "content": "ok"}]}
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
db = tmp_path / "bot.db"
processor = make_processor(db=db)
_events(processor, _message("a", session="s1"))
_events(processor, _message("b", session="s2"))
assert len(asyncio.run(repo.list_messages(db, session_id="s1"))) == 2
assert len(asyncio.run(repo.list_messages(db, session_id="s2"))) == 2
def test_processor_error_event_on_failure(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
async def fake_run_task(task, settings=None, history=None, *, cache=None):
raise RuntimeError("boom")
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
processor = make_processor(db=tmp_path / "bot.db")
events = _events(processor, _message("会失败"))
assert [e.type for e in events] == [MessageEventType.TYPING, MessageEventType.ERROR]
assert events[1].error == "处理消息时出错,请稍后再试。"
# 用户消息已落库,但没有助手回复
rows = asyncio.run(repo.list_messages(tmp_path / "bot.db", session_id="cli"))
assert [r["role"] for r in rows] == ["user"]
def test_processor_failed_turn_excluded_from_history(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""上一轮失败的悬空 user 消息不进上下文,但仍在库里留痕。"""
calls: list[list] = []
async def fake_run_task(task, settings=None, history=None, *, cache=None):
calls.append(list(history or []))
if task == "会失败":
raise RuntimeError("boom")
return {"messages": [{"role": "assistant", "content": "好的"}]}
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
db = tmp_path / "bot.db"
processor = make_processor(db=db)
_events(processor, _message("会失败"))
_events(processor, _message("再来一次"))
# 第二次的上下文里没有上一轮那条无回复的 user 消息
assert calls[1] == []
rows = asyncio.run(repo.list_messages(db, session_id="cli"))
assert [(r["role"], r["content"]) for r in rows] == [
("user", "会失败"),
("user", "再来一次"),
("assistant", "好的"),
]
def test_processor_empty_reply_not_persisted(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""空回复只展示占位文案,不写进 messages 表(避免污染后续上下文)。"""
async def fake_run_task(task, settings=None, history=None, *, cache=None):
return {"messages": [{"role": "assistant", "content": []}]}
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
db = tmp_path / "bot.db"
processor = make_processor(db=db)
events = _events(processor, _message("hi"))
assert events[1].content[0].text == "(无输出)" # type: ignore[union-attr]
rows = asyncio.run(repo.list_messages(db, session_id="cli"))
assert [(r["role"], r["content"]) for r in rows] == [("user", "hi")]
def test_processor_reuses_agent_cache(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""同一个处理器的多轮消息复用同一个 AgentCache。"""
seen: list[object] = []
async def fake_run_task(task, settings=None, history=None, *, cache=None):
seen.append(cache)
return {"messages": [{"role": "assistant", "content": "ok"}]}
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
processor = make_processor(db=tmp_path / "bot.db")
_events(processor, _message("a"))
_events(processor, _message("b"))
assert seen[0] is not None
assert seen[0] is seen[1]
def test_build_history_rules() -> None:
rows = [
{"role": "assistant", "content": "开场白"},
{"role": "user", "content": "第一问"},
{"role": "assistant", "content": "第一答"},
{"role": "user", "content": "无回复的残留"},
]
assert processor_mod.build_history(rows) == [
{"role": "user", "content": "第一问"},
{"role": "assistant", "content": "第一答"},
]
# 字符预算从新到旧累加,超预算的旧消息被丢弃
rows = [
{"role": "user", "content": "x" * 100},
{"role": "assistant", "content": "y" * 10},
{"role": "user", "content": "z" * 10},
{"role": "assistant", "content": "w" * 10},
]
assert processor_mod.build_history(rows, max_chars=30) == [
{"role": "user", "content": "z" * 10},
{"role": "assistant", "content": "w" * 10},
]
def test_processor_rejects_empty_and_media(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
async def fake_run_task(task, settings=None, history=None, *, cache=None): # pragma: no cover
raise AssertionError("不应执行任务")
monkeypatch.setattr(processor_mod, "run_task", fake_run_task)
processor = make_processor(db=tmp_path / "bot.db")
events = _events(processor, _message(""))
assert events[-1].type == MessageEventType.ERROR
assert "空消息" in (events[-1].error or "")
events = _events(processor, _message("", media=True))
assert events[-1].type == MessageEventType.ERROR
assert "仅支持文本" in (events[-1].error or "")
+173
View File
@@ -0,0 +1,173 @@
"""RpcHub 测试:往返、超时、远端异常、未注册方法、并发与中止。"""
from __future__ import annotations
import asyncio
import pytest
from bot042.flows.bus import EventBus
from bot042.flows.rpc import (
RpcAborted,
RpcError,
RpcHub,
RpcRemoteError,
RpcTimeoutError,
)
def test_rpc_roundtrip() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus)
async def add(payload: object) -> object:
assert isinstance(payload, dict)
return payload["a"] + payload["b"]
hub.serve("math.add", add)
assert hub.served() == ["math.add"]
assert await hub.call("math.add", {"a": 1, "b": 2}) == 3
assert hub.pending == 0
hub.close()
asyncio.run(main())
def test_rpc_remote_error_is_mapped() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus)
async def boom(payload: object) -> object:
_ = payload
raise ValueError("bad input")
hub.serve("boom", boom)
with pytest.raises(RpcRemoteError) as info:
await hub.call("boom")
assert info.value.remote_type == "ValueError"
assert "bad input" in info.value.remote_message
hub.close()
asyncio.run(main())
def test_rpc_method_not_found() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus)
with pytest.raises(RpcError, match="未注册的 RPC 方法"):
await hub.call("ghost")
hub.close()
asyncio.run(main())
def test_rpc_timeout_drops_late_reply() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus)
gate = asyncio.Event()
async def slow(payload: object) -> object:
await gate.wait()
return payload
hub.serve("slow", slow)
with pytest.raises(RpcTimeoutError):
await hub.call("slow", 1, timeout=0.01)
assert hub.pending == 0
gate.set() # 迟到响应必须被丢弃,不能污染后续调用
await bus.wait_for_complete()
assert hub.pending == 0
hub.close()
asyncio.run(main())
def test_rpc_concurrent_calls() -> None:
async def main() -> int:
bus = EventBus()
hub = RpcHub(bus)
async def double(payload: object) -> object:
await asyncio.sleep(0)
assert isinstance(payload, int)
return payload * 2
hub.serve("double", double)
results = await asyncio.gather(*(hub.call("double", i) for i in range(50)))
hub.close()
return sum(1 for i, value in enumerate(results) if value == i * 2)
assert asyncio.run(main()) == 50
def test_rpc_duplicate_serve_rejected() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus)
async def handler(payload: object) -> object:
return payload
hub.serve("m", handler)
with pytest.raises(ValueError, match="已注册"):
hub.serve("m", handler)
hub.unserve("m")
assert hub.served() == []
hub.close()
asyncio.run(main())
def test_rpc_pending_limit() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus, pending_limit=1)
gate = asyncio.Event()
async def slow(payload: object) -> object:
await gate.wait()
return payload
hub.serve("slow", slow)
first = asyncio.create_task(hub.call("slow", 1, timeout=None))
await asyncio.sleep(0)
with pytest.raises(RpcError, match="上限"):
await hub.call("slow", 2, timeout=None)
gate.set()
assert await first == 1
hub.close()
await bus.wait_for_complete()
asyncio.run(main())
def test_rpc_close_aborts_pending() -> None:
async def main() -> None:
bus = EventBus()
hub = RpcHub(bus)
gate = asyncio.Event()
async def slow(payload: object) -> object:
await gate.wait()
return payload
hub.serve("slow", slow)
task = asyncio.create_task(hub.call("slow", 1, timeout=None))
await asyncio.sleep(0)
hub.close()
with pytest.raises(RpcAborted):
await task
gate.set()
await bus.wait_for_complete()
with pytest.raises(RpcAborted):
await hub.call("slow", 2)
asyncio.run(main())
+187
View File
@@ -0,0 +1,187 @@
"""调度器测试:窗口语义、三类触发器与 EventBus 事件触发。"""
from __future__ import annotations
import asyncio
from datetime import datetime, timedelta
import pytest
from bot042.flows.bus import EventBus
from bot042.flows.scheduler import (
CN_TZ,
CronTrigger,
Fire,
IntervalTrigger,
OnceTrigger,
Schedule,
Scheduler,
)
NOW = datetime(2026, 11, 6, 10, 0, tzinfo=CN_TZ) # 周五
def test_once_inside_and_outside_window() -> None:
s = Schedule(
name="once-in",
trigger=OnceTrigger(at=datetime(2026, 11, 6, 12, 0)),
start_time=datetime(2026, 11, 6, 9, 0),
end_time=datetime(2026, 11, 6, 18, 0),
)
assert s.next_fire_after(NOW) == datetime(2026, 11, 6, 12, 0, tzinfo=CN_TZ)
# 早于 start_time 的 once 永不触发(即使 after 早于 at)
s2 = Schedule(
name="once-before-start",
trigger=OnceTrigger(at=datetime(2026, 11, 6, 8, 0)),
start_time=datetime(2026, 11, 6, 9, 0),
)
assert s2.next_fire_after(datetime(2026, 11, 6, 7, 0, tzinfo=CN_TZ)) is None
# 晚于 end_time 的 once 不触发
s3 = Schedule(
name="once-after-end",
trigger=OnceTrigger(at=datetime(2026, 11, 6, 20, 0)),
end_time=datetime(2026, 11, 6, 18, 0),
)
assert s3.next_fire_after(NOW) is None
# 已过触发时刻不再触发
s4 = Schedule(name="once-past", trigger=OnceTrigger(at=datetime(2026, 11, 6, 9, 30)))
assert s4.next_fire_after(NOW) is None
def test_cron_respects_window() -> None:
s = Schedule(
name="cron1",
trigger=CronTrigger(expr="0 9 * * *"),
start_time=datetime(2026, 11, 6, 10, 0),
end_time=datetime(2026, 11, 7, 9, 30),
)
assert s.next_fire_after(NOW) == datetime(2026, 11, 7, 9, 0, tzinfo=CN_TZ)
# after 早于 start_time 时抬升:首次触发即 start_time 当刻的匹配
s2 = Schedule(
name="cron2",
trigger=CronTrigger(expr="0 9 * * *"),
start_time=datetime(2026, 11, 7, 9, 0),
)
assert s2.next_fire_after(NOW) == datetime(2026, 11, 7, 9, 0, tzinfo=CN_TZ)
# end_time 截止后无触发
s3 = Schedule(
name="cron3",
trigger=CronTrigger(expr="0 9 * * *"),
end_time=datetime(2026, 11, 6, 23, 0),
)
assert s3.next_fire_after(NOW) is None
def test_interval_aligned_to_start() -> None:
s = Schedule(
name="iv",
trigger=IntervalTrigger(every=timedelta(minutes=15)),
start_time=datetime(2026, 11, 6, 9, 0),
)
assert s.next_fire_after(datetime(2026, 11, 6, 10, 7, tzinfo=CN_TZ)) == datetime(
2026, 11, 6, 10, 15, tzinfo=CN_TZ
)
# 无 start_time 时从 after 起算
s2 = Schedule(name="iv2", trigger=IntervalTrigger(every=timedelta(minutes=15)))
assert s2.next_fire_after(NOW) == datetime(2026, 11, 6, 10, 15, tzinfo=CN_TZ)
def test_interval_grid_anchored_to_first_anchor() -> None:
"""调度器固化 anchor 后,间隔不随每次重算漂移。"""
s = Schedule(name="iv3", trigger=IntervalTrigger(every=timedelta(seconds=10)))
anchor = datetime(2026, 11, 6, 10, 0, 0, tzinfo=CN_TZ)
first = s.next_fire_after(datetime(2026, 11, 6, 10, 0, 0, 300000, tzinfo=CN_TZ), anchor=anchor)
# 触发开销 0.3s 后再算下一次,仍落在同一网格上
assert first == datetime(2026, 11, 6, 10, 0, 10, tzinfo=CN_TZ)
second = s.next_fire_after(first + timedelta(seconds=0.3), anchor=anchor)
assert second == datetime(2026, 11, 6, 10, 0, 20, tzinfo=CN_TZ)
assert (second - first).total_seconds() == 10.0
def test_schedule_event_name() -> None:
s = Schedule(name="daily.1", trigger=OnceTrigger(at=NOW))
assert s.event == "schedule.daily.1"
def test_schedule_validation() -> None:
with pytest.raises(ValueError):
Schedule(name="bad name!", trigger=OnceTrigger(at=NOW))
with pytest.raises(ValueError):
Schedule(
name="window",
trigger=OnceTrigger(at=NOW),
start_time=datetime(2026, 11, 6, 18, 0),
end_time=datetime(2026, 11, 6, 9, 0),
)
with pytest.raises(ValueError):
IntervalTrigger(every=timedelta(0))
sched = Scheduler(EventBus())
sched.add(Schedule(name="dup", trigger=OnceTrigger(at=NOW)))
with pytest.raises(ValueError):
sched.add(Schedule(name="dup", trigger=OnceTrigger(at=NOW)))
def test_scheduler_fires_events_and_stops() -> None:
async def main() -> None:
bus = EventBus()
fired: list[Fire] = []
seen: list[str] = []
async def on_fire(fire: Fire) -> None:
fired.append(fire)
async def on_named(fire: Fire) -> None:
seen.append(fire.name)
bus.on("schedule.fired", on_fire)
bus.on("schedule.tick", on_named)
sched = Scheduler(bus)
sched.add(Schedule(name="tick", trigger=IntervalTrigger(every=timedelta(milliseconds=30))))
async with sched:
await asyncio.sleep(0.25)
await bus.wait_for_complete()
assert len(fired) >= 2
assert seen == ["tick"] * len(fired)
assert all(f.scheduled_time.tzinfo is not None for f in fired)
# stop 后不再触发
count = len(fired)
await asyncio.sleep(0.1)
assert len(fired) == count
asyncio.run(main())
def test_once_fires_exactly_once() -> None:
async def main() -> None:
bus = EventBus()
count = 0
async def on_fire(fire: Fire) -> None:
nonlocal count
count += 1
bus.on("schedule.fired", on_fire)
sched = Scheduler(bus)
sched.add(
Schedule(
name="one",
trigger=OnceTrigger(at=datetime.now(CN_TZ) + timedelta(milliseconds=40)),
)
)
async with sched:
await asyncio.sleep(0.3)
await bus.wait_for_complete()
assert count == 1
asyncio.run(main())
+239
View File
@@ -0,0 +1,239 @@
"""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
+169
View File
@@ -0,0 +1,169 @@
"""插话(steer)测试:缓冲、中间件注入、运行器派发与 AgentReply 汇点。"""
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any
from bot042.agent.middlewares.steering import (
STEER_PREFIX,
SteeringBuffer,
SteeringMiddleware,
bind,
unbind,
)
from bot042.channels.models import (
ChannelMessage,
ChannelSubject,
InboundMessage,
TextContent,
)
from bot042.flows.builtin import AgentReply
from bot042.flows.bus import EventBus
from bot042.flows.scheduler import CN_TZ
from bot042.flows.tasks import (
EventTrigger,
OverlapPolicy,
Task,
TaskContext,
TaskRunner,
)
def test_buffer_ignores_blank_and_drains() -> None:
buffer = SteeringBuffer()
assert buffer.push(" ") is False
assert buffer.push("补充一句") is True
assert len(buffer) == 1
assert buffer.drain() == ["补充一句"]
assert not buffer
def test_middleware_injects_buffer_into_messages() -> None:
buffer = SteeringBuffer()
buffer.push("改用英语回答")
token = bind(buffer)
try:
update = asyncio.run(SteeringMiddleware().abefore_model({}, None)) # type: ignore[arg-type]
finally:
unbind(token)
assert update is not None
messages = update["messages"]
assert len(messages) == 1
assert messages[0].content == STEER_PREFIX + "改用英语回答"
assert not buffer
def test_middleware_noop_without_buffer() -> None:
assert asyncio.run(SteeringMiddleware().abefore_model({}, None)) is None # type: ignore[arg-type]
def test_runner_steers_running_task_instead_of_queueing() -> None:
async def _run() -> tuple[list[object], int]:
bus = EventBus()
bus.bind_loop()
runner = TaskRunner(bus)
seen: list[object] = []
class Demo(Task):
name = "steer.demo"
overlap = OverlapPolicy.QUEUE
supports_steer = True
def steer(self, payload: object) -> bool:
seen.append(payload)
return True
async def run(self) -> None:
await asyncio.sleep(0.1)
runner.register(Demo)
_ = runner.add_task("steer.demo", EventTrigger(event="pulse"))
await runner.start()
bus.emit("pulse", 1)
await asyncio.sleep(0.02)
bus.emit("pulse", 2) # 运行中 → 注入,不排队
await asyncio.sleep(0.15)
await runner.wait_idle()
await runner.stop()
return seen, len(runner.runs("steer.demo"))
seen, total = asyncio.run(_run())
assert seen == [2]
assert total == 1 # 没有产生第二次运行
def _message(text: str = "你好") -> ChannelMessage:
return ChannelMessage.of(
InboundMessage(
channel_id="c1",
channel_type="stream-test",
channel_subject=ChannelSubject(subject_id="u1"),
content=[TextContent(text=text)],
)
)
def test_agent_reply_steer_collects_text() -> None:
payload = _message()
ctx = TaskContext(
run_id="r1",
task=AgentReply.name,
event="channel.inbound",
fired_at=datetime.now(CN_TZ),
payload=payload,
)
task = AgentReply(ctx)
assert task.steer(payload) is True
assert task.steering.drain() == ["你好"]
# 非消息载荷交给运行器按原策略处理
assert task.steer(object()) is False
def test_agent_reply_steer_rejects_empty_text() -> None:
payload = _message(" ")
ctx = TaskContext(
run_id="r2",
task=AgentReply.name,
event="channel.inbound",
fired_at=datetime.now(CN_TZ),
payload=payload,
)
assert AgentReply(ctx).steer(payload) is False
def test_slot_sink_cleared_after_run() -> None:
"""运行结束后汇点必须清空,否则空闲任务会被持续注入。"""
async def _run() -> tuple[int, Any]:
bus = EventBus()
bus.bind_loop()
runner = TaskRunner(bus)
class Demo(Task):
name = "steer.cleanup"
supports_steer = True
def steer(self, payload: object) -> bool: # pragma: no cover - 不应被调用
return True
async def run(self) -> None:
return
runner.register(Demo)
_ = runner.add_task("steer.cleanup", EventTrigger(event="go"))
await runner.start()
bus.emit("go", None)
await asyncio.sleep(0.05)
await runner.wait_idle()
sink = runner._slots[("steer.cleanup", "")].steer_sink
await runner.stop()
return len(runner.runs("steer.cleanup")), sink
total, sink = asyncio.run(_run())
assert total == 1
assert sink is None
+238
View File
@@ -0,0 +1,238 @@
"""流式回复测试:节流、去重、超时续流,以及 AgentReply 的流式链路。"""
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.manager import ChannelManager
from bot042.channels.models import (
ChannelConfig,
ChannelMessage,
ChannelSubject,
InboundMessage,
OutboundStream,
TextContent,
)
from bot042.channels.registry import register_channel
from bot042.config import Settings
from bot042.flows import builtin
from bot042.flows.builtin import RPC_STREAM, AgentReply, ChannelServices
from bot042.flows.bus import EventBus
from bot042.flows.rpc import RpcHub
from bot042.flows.stream import ReplyStream
from bot042.flows.tasks import EventTrigger, TaskRunner
def test_stream_sends_ack_and_throttles() -> None:
sent: list[tuple[str, str, bool]] = []
now = [0.0]
async def _send(text: str, *, stream_id: str, finish: bool) -> None:
sent.append((stream_id, text, finish))
stream = ReplyStream(
_send, min_interval=1.0, segment_seconds=540, clock=lambda: now[0]
)
async def _run() -> None:
await stream.update("收到", force=True) # 首帧立即发
now[0] = 0.5
await stream.update("收到,正在") # 节流窗口内被跳过
now[0] = 1.2
await stream.update("收到,正在处理") # 发出
await stream.update("收到,正在处理") # 内容未变,跳过
await stream.finish()
asyncio.run(_run())
assert [t[1] for t in sent] == ["收到", "收到,正在处理", "收到,正在处理"]
assert [t[2] for t in sent] == [False, False, True]
assert len({t[0] for t in sent}) == 1
def test_stream_rollover_after_segment_limit() -> None:
"""超过平台存活上限时,结束旧流并另起一段。"""
sent: list[tuple[str, str, bool]] = []
now = [0.0]
async def _send(text: str, *, stream_id: str, finish: bool) -> None:
sent.append((stream_id, text, finish))
stream = ReplyStream(
_send, min_interval=0.0, segment_seconds=10, clock=lambda: now[0]
)
async def _run() -> None:
await stream.update("第一段", force=True)
now[0] = 11.0
await stream.update("第一段第二段") # 触发续流
await stream.finish()
asyncio.run(_run())
assert stream.segments == 2
stream_ids = {sid for sid, _, _ in sent}
assert len(stream_ids) == 2
# 旧段以 finish 收尾,新段首帧立刻铺上已有内容
first_id = sent[0][0]
assert (first_id, "第一段第二段", True) in sent
assert sent[-1][2] is True
def test_stream_ignores_send_failure() -> None:
"""单次推送失败不能打断生成。"""
sent: list[str] = []
async def _send(text: str, *, stream_id: str, finish: bool) -> None:
if not finish:
raise RuntimeError("boom")
sent.append(text)
stream = ReplyStream(_send, min_interval=0.0)
async def _run() -> None:
await stream.update("一半", force=True)
await stream.finish("完整答案")
asyncio.run(_run())
assert sent == ["完整答案"]
class StreamConfig(ChannelConfig):
pass
class StreamChannel(BaseChannel):
"""支持流式的测试渠道:记录每次 reply_stream 调用。"""
channel_type = "stream-test"
supports_stream = True
instances: ClassVar[list[StreamChannel]] = []
def __init__(
self,
processor: Any = None,
*,
config: StreamConfig | None = None,
channel_id: str | None = None,
**kwargs: Any,
) -> None:
super().__init__(processor, config=config, channel_id=channel_id, **kwargs)
self.frames: list[tuple[str, bool]] = []
StreamChannel.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 reply_stream(
self, subject: ChannelSubject, text: str, *, stream_id: str, finish: bool = False
) -> None:
self.frames.append((text, finish))
async def _send_text(self, subject: ChannelSubject, text: str) -> None:
self.frames.append((text, True))
async def _send_content(self, subject: ChannelSubject, parts: list) -> None:
pass
async def _send_media(self, subject: ChannelSubject, media: Any) -> None:
pass
register_channel("stream-test", StreamChannel, StreamConfig)
def test_agent_reply_acks_then_streams(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""收到消息先 ack,随后逐步覆盖,最后以 finish 收尾。"""
StreamChannel.instances.clear()
async def fake_stream(task, settings=None, history=None, *, cache=None, steering=None):
for text in ("你", "你好"):
yield text
monkeypatch.setattr(builtin, "stream_task", fake_stream)
async def _run() -> list[tuple[str, bool]]:
bus = EventBus()
bus.bind_loop()
hub = RpcHub(bus)
manager = ChannelManager()
channel = StreamChannel(channel_id="s1")
await manager.add_channel(channel)
await manager.start()
_ = hub.serve(RPC_STREAM, manager.rpc_stream)
services = ChannelServices(
channels=manager,
settings=Settings(),
db=tmp_path / "bot.db",
hub=hub,
)
runner = TaskRunner(bus, deps=services)
runner.register(AgentReply)
_ = runner.add_task(AgentReply.name, EventTrigger(event="channel.inbound"))
await runner.start()
bus.emit(
"channel.inbound",
ChannelMessage.of(
InboundMessage(
channel_id="s1",
channel_type="stream-test",
channel_subject=ChannelSubject(subject_id="u1"),
content=[TextContent(text="你好")],
)
),
)
await asyncio.sleep(0.05) # 等 handler 真正开始派发
await runner.wait_idle()
await runner.stop()
hub.close()
await manager.stop()
return channel.frames
frames = asyncio.run(_run())
# 首帧 ack,首段内容立即覆盖(跳过节流),最后以 finish 收尾
assert frames[0] == (builtin.ACK_TEXT, False)
assert frames[1] == ("你", False)
assert frames[-1] == ("你好", True)
def test_outbound_stream_payload_defaults() -> None:
payload = OutboundStream(
channel_id="c", subject_id="u", stream_id="s", text="x"
)
assert payload.finish is False
assert payload.metadata == {}
def test_manager_rejects_unknown_stream_payload() -> None:
manager = ChannelManager()
async def _run() -> None:
with pytest.raises(TypeError):
await manager.rpc_stream(json.dumps({"x": 1}))
asyncio.run(_run())
+1192
View File
File diff suppressed because it is too large. Load diff
+295
View File
@@ -0,0 +1,295 @@
"""联网工具测试:URL 归一、截断、HTML 转 Markdown、必应解析与失败降级。"""
from __future__ import annotations
import asyncio
from typing import Any, Self
import pytest
from bot042.agent import web
from bot042.agent.web import (
WebError,
_BingParser,
_html_to_markdown,
_normalize_url,
_truncate,
fetch_page,
search_web,
web_fetch,
web_search,
wrap_untrusted,
)
BING_HTML = """
<html><body>
<li class="b_algo">
<h2><a href="https://www.python.org">Welcome to <strong>Python</strong></a></h2>
<div class="b_caption"><p>The mission of the Python Software Foundation is to promote Python.</p></div>
</li>
<li class="b_algo">
<h2><a href="https://docs.python.org/3/">Python 3 Documentation</a></h2>
<p>Official documentation for Python.</p>
</li>
</body></html>
"""
ARTICLE_HTML = """
<html>
<head><title>示例</title><style>p { color: red; }</style><script>alert(1)</script></head>
<body>
<nav><a href="/menu">站点菜单</a></nav>
<article>
<h1>标题一</h1>
<p>第一段,含 <strong>强调</strong> 与 <a href="/docs/x.html">相对链接</a>。</p>
<h2>小节<a class="headerlink" href="#sec">¶</a></h2>
<ul><li>甲</li><li>乙</li></ul>
<ol><li>一</li><li>二</li></ol>
<pre><code>print("hi")</code></pre>
<blockquote>引用的话</blockquote>
</article>
<footer>版权所有</footer>
</body>
</html>
"""
class _FakeResponse:
def __init__(
self,
*,
status_code: int = 200,
text: str = "",
markdown: str = "",
plain: str = "",
content_type: str = "text/html; charset=utf-8",
url: str = "https://example.com/page",
) -> None:
self.status_code = status_code
self.text = text
self.text_markdown = markdown
self.text_plain = plain
self.headers = {"content-type": content_type}
self.url = url
class _FakeClient:
def __init__(self, response: _FakeResponse) -> None:
self.response = response
self.calls: list[dict[str, Any]] = []
async def __aenter__(self) -> Self:
return self
async def __aexit__(self, *args: object) -> bool:
return False
async def get(self, url: str, **_kwargs: Any) -> _FakeResponse:
self.calls.append({"url": url, **_kwargs})
return self.response
def test_normalize_url() -> None:
assert _normalize_url("example.com") == "https://example.com"
assert _normalize_url(" http://a.b/c ") == "http://a.b/c"
with pytest.raises(ValueError):
_normalize_url(" ")
with pytest.raises(ValueError):
_normalize_url("ftp://example.com/x")
def test_truncate() -> None:
assert _truncate("abc", 10) == "abc"
out = _truncate("abcdef", 3)
assert out.startswith("abc")
assert "已截断" in out
def test_bing_parser_extracts_results() -> None:
parser = _BingParser()
parser.feed(BING_HTML)
assert len(parser.results) == 2
assert parser.results[0]["url"] == "https://www.python.org"
assert parser.results[0]["title"] == "Welcome to Python"
assert "Software Foundation" in parser.results[0]["snippet"]
assert parser.results[1]["url"] == "https://docs.python.org/3/"
def test_html_to_markdown_keeps_readable_structure() -> None:
md = _html_to_markdown(ARTICLE_HTML, base_url="https://example.com/page")
assert "# 标题一" in md
assert "## 小节" in md
assert "**强调**" in md
assert "[相对链接](https://example.com/docs/x.html)" in md
assert "- 甲" in md and "- 乙" in md
assert "1. 一" in md and "2. 二" in md
assert "```" in md and 'print("hi")' in md
assert "> 引用的话" in md
assert "<h1>" not in md and "&amp;" not in md
def test_html_to_markdown_drops_noise() -> None:
md = _html_to_markdown(ARTICLE_HTML, base_url="https://example.com/page")
assert "站点菜单" not in md # nav 整棵子树丢弃
assert "版权所有" not in md # footer 丢弃
assert "alert(1)" not in md # 脚本丢弃
assert "color: red" not in md # 样式丢弃
assert "" not in md # 标题锚点没有阅读价值
def test_html_to_markdown_drops_navigation_containers() -> None:
html = (
'<div role="navigation">面包屑导航</div>'
'<div class="sidebar">侧栏目录</div>'
'<div id="site-menu">站点菜单</div>'
"<p>正文</p>"
)
md = _html_to_markdown(html)
assert "正文" in md
assert "面包屑导航" not in md
assert "侧栏目录" not in md
assert "站点菜单" not in md
def test_html_to_markdown_keeps_list_items_compact() -> None:
md = _html_to_markdown("<ul><li><p>甲</p></li><li><p>乙</p></li></ul>")
assert md == "- 甲\n- 乙"
def test_html_to_markdown_indents_nested_list() -> None:
md = _html_to_markdown("<ul><li>甲<ul><li>甲一</li></ul></li></ul>")
assert "- 甲" in md
assert " - 甲一" in md
def test_html_to_markdown_keeps_code_indent() -> None:
md = _html_to_markdown("<pre><code>def f():\n return 1</code></pre>")
assert "def f():" in md
assert " return 1" in md # 代码缩进不能被折叠
def test_html_to_markdown_collapses_whitespace() -> None:
md = _html_to_markdown("<p>a b\n\tc</p><p>d</p>")
assert "a b c" in md
assert "\n\n\n" not in md
def test_fetch_page_converts_html_to_markdown(monkeypatch: pytest.MonkeyPatch) -> None:
client = _FakeClient(_FakeResponse(text=ARTICLE_HTML))
monkeypatch.setattr(web, "_client", lambda: client)
out = asyncio.run(fetch_page("example.com"))
assert "# 标题一" in out
assert "<p>" not in out
assert client.calls[0]["url"] == "https://example.com"
def test_fetch_page_keeps_plain_text_as_is(monkeypatch: pytest.MonkeyPatch) -> None:
response = _FakeResponse(text="a\nb", content_type="text/plain; charset=utf-8")
monkeypatch.setattr(web, "_client", lambda: _FakeClient(response))
assert asyncio.run(fetch_page("https://example.com/x.txt")) == "a\nb"
def test_fetch_page_wraps_json_in_code_block(monkeypatch: pytest.MonkeyPatch) -> None:
response = _FakeResponse(text='{"ok":true}', content_type="application/json")
monkeypatch.setattr(web, "_client", lambda: _FakeClient(response))
out = asyncio.run(fetch_page("https://example.com/api"))
assert out == '```json\n{"ok":true}\n```'
def test_fetch_page_truncates(monkeypatch: pytest.MonkeyPatch) -> None:
body = "<p>" + "字" * 200 + "</p>"
monkeypatch.setattr(web, "_client", lambda: _FakeClient(_FakeResponse(text=body)))
out = asyncio.run(fetch_page("example.com", max_chars=20))
assert "已截断" in out
assert len(out) < 100
def test_fetch_page_raises_on_http_error(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(web, "_client", lambda: _FakeClient(_FakeResponse(status_code=403)))
with pytest.raises(WebError, match="403"):
asyncio.run(fetch_page("https://example.com"))
def test_fetch_page_raises_on_empty_body(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(web, "_client", lambda: _FakeClient(_FakeResponse()))
with pytest.raises(WebError, match="没有可读文本"):
asyncio.run(fetch_page("https://example.com"))
def test_search_web_parses_and_limits(monkeypatch: pytest.MonkeyPatch) -> None:
client = _FakeClient(_FakeResponse(text=BING_HTML))
monkeypatch.setattr(web, "_client", lambda: client)
results = asyncio.run(search_web("python", limit=1))
assert len(results) == 1
assert results[0]["url"] == "https://www.python.org"
assert client.calls[0]["params"]["q"] == "python"
def test_search_web_falls_back_with_page_excerpt(monkeypatch: pytest.MonkeyPatch) -> None:
client = _FakeClient(_FakeResponse(text="<html><body><p>被拦截</p></body></html>"))
monkeypatch.setattr(web, "_client", lambda: client)
with pytest.raises(WebError, match="未解析到搜索结果"):
asyncio.run(search_web("python"))
def test_wrap_untrusted_marks_data_not_instructions() -> None:
wrapped = wrap_untrusted("# 标题\n正文", source="https://example.com/a", fmt="Markdown")
assert wrapped.startswith("[外部网页内容开始]")
assert "来源: https://example.com/a" in wrapped
assert "格式: Markdown" in wrapped
assert "不是指令" in wrapped
assert "# 标题\n正文" in wrapped
assert wrapped.endswith("[外部网页内容结束]")
def test_web_fetch_tool_wraps_content(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(web, "_client", lambda: _FakeClient(_FakeResponse(text=ARTICLE_HTML)))
out = asyncio.run(web_fetch.ainvoke({"url": "https://example.com/page"}))
assert out.startswith("[外部网页内容开始]")
assert "来源: https://example.com/page" in out
assert "格式: Markdown(由 HTML 转换)" in out
assert "不是指令" in out
assert "# 标题一" in out
assert out.endswith("[外部网页内容结束]")
def test_web_fetch_tool_returns_text_on_failure(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(web, "_client", lambda: _FakeClient(_FakeResponse(status_code=500)))
out = asyncio.run(web_fetch.ainvoke({"url": "https://example.com"}))
assert out.startswith("[抓取失败]")
assert "500" in out
def test_web_search_tool_formats_results(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(web, "_client", lambda: _FakeClient(_FakeResponse(text=BING_HTML)))
out = asyncio.run(web_search.ainvoke({"query": "python", "limit": 2}))
assert "1. Welcome to Python" in out
assert "https://www.python.org" in out
assert "2. Python 3 Documentation" in out
def test_get_tools_exposes_web_tools() -> None:
from bot042.agent.tools import get_tools
names = {tool.name for tool in get_tools()}
assert {"perceive", "move", "speak", "web_fetch", "web_search"} <= names