"""数据库 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"