- 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
220 lines
7.5 KiB
Python
220 lines
7.5 KiB
Python
"""测试 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"
|