""" SQLite 连接生命周期测试 ======================= 【功能说明】 验证 open_connection 修复连接泄漏后,语义与裸 `with sqlite3.connect()` 完全一致,并且**连接一定被关闭**。 【技术选型理由】 1. 「是否关闭」用「关闭后继续操作必抛 ProgrammingError」来断言, 比检查引用计数可靠; 2. 提交/回滚用真实读写验证,不 mock; 3. 覆盖 `with` 块内 return 的路径(delete() 就是这么写的), 那是 @contextmanager 最容易出错的地方。 【实现思路】 - open_connection 四条语义:close / commit / rollback / return-in-with; - 四个 Store 各做一个 create→get 往返,确认调用点零改动仍可用。 【潜在风险与应对】 风险1:临时库被占用删不掉。 应对:teardown 忽略 PermissionError(Windows 文件锁),用例结论不依赖清理。 """ from __future__ import annotations import gc import shutil import sqlite3 from pathlib import Path from typing import Generator from uuid import uuid4 import pytest from app.store.sqlite_util import open_connection @pytest.fixture() def db_path(tmp_path: Path) -> Generator[Path, None, None]: p = tmp_path / f"lc_{uuid4().hex[:8]}.db" path_str = str(p) # 先固化路径,避免后面释放引用时取不到 yield p gc.collect() # 连接已被 open_connection 正常关闭,这里通常能删掉; # 仍失败则忽略——用例结论不依赖清理结果。 for suffix in ("", "-wal", "-shm"): f = Path(path_str + suffix) try: if f.is_dir(): shutil.rmtree(f, ignore_errors=True) elif f.exists(): f.unlink() except (PermissionError, OSError): pass def _create_table(db_path: Path) -> None: with open_connection(db_path) as conn: conn.execute("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, v TEXT)") conn.commit() class TestConnectionClosed: """核心修复:连接必须被关闭""" def test_connection_is_closed_after_with(self, db_path: Path): captured: dict[str, sqlite3.Connection] = {} with open_connection(db_path) as conn: captured["c"] = conn # 用完即关 → 再操作必抛 ProgrammingError with pytest.raises(sqlite3.ProgrammingError): captured["c"].execute("SELECT 1") def test_connection_closed_even_on_exception(self, db_path: Path): captured: dict[str, sqlite3.Connection] = {} with pytest.raises(RuntimeError): with open_connection(db_path) as conn: captured["c"] = conn raise RuntimeError("boom") with pytest.raises(sqlite3.ProgrammingError): captured["c"].execute("SELECT 1") def test_connection_closed_when_returning_inside_with(self, db_path: Path): """`with` 块内 return 也必须 close(delete() 就是这种写法)""" captured: dict[str, sqlite3.Connection] = {} def _delete_like() -> bool: with open_connection(db_path) as conn: captured["c"] = conn cur = conn.execute("DELETE FROM t WHERE id = ?", (1,)) conn.commit() return cur.rowcount > 0 _create_table(db_path) assert _delete_like() is False # 表是空的,rowcount=0 with pytest.raises(sqlite3.ProgrammingError): captured["c"].execute("SELECT 1") class TestCommitAndRollback: """语义等价:成功提交、异常回滚""" def test_commit_on_clean_exit(self, db_path: Path): """未显式 commit 的写入,靠 with 退出时的 commit 也要落库(与旧语义一致)""" _create_table(db_path) with open_connection(db_path) as conn: conn.execute("INSERT INTO t (v) VALUES ('hello')") # 故意不调 conn.commit() # 重开连接验证已持久化 with open_connection(db_path) as conn: row = conn.execute("SELECT v FROM t").fetchone() assert row is not None assert row["v"] == "hello" def test_explicit_commit_still_works(self, db_path: Path): """调用点显式 commit(现有写法)不能被破坏""" _create_table(db_path) with open_connection(db_path) as conn: conn.execute("INSERT INTO t (v) VALUES ('world')") conn.commit() with open_connection(db_path) as conn: assert conn.execute("SELECT COUNT(*) AS n FROM t").fetchone()["n"] == 1 def test_rollback_on_exception(self, db_path: Path): _create_table(db_path) with pytest.raises(ValueError): with open_connection(db_path) as conn: conn.execute("INSERT INTO t (v) VALUES ('ghost')") raise ValueError("rollback me") with open_connection(db_path) as conn: assert conn.execute("SELECT COUNT(*) AS n FROM t").fetchone()["n"] == 0 def test_row_factory_is_row(self, db_path: Path): """row_factory 必须是 sqlite3.Row,否则 dict 式取值全挂""" with open_connection(db_path) as conn: assert conn.row_factory is sqlite3.Row class TestStoreIntegration: """四个 Store 调用点零改动,仍可正常读写""" def test_task_store_roundtrip(self, db_path: Path): from app.schemas.task import TaskCreate from app.tasks.task_store import SqliteTaskStore store = SqliteTaskStore(db_path) task = store.create( TaskCreate(project_id="p1", requirement_text="r1", execution_mode="direct_claude"), thread_id="th1", ) assert store.get(task.id) is not None store.update_session_id(task.id, "sess-x") assert store.get(task.id).session_id == "sess-x" # delete 内部是 `with` 块内 return,必须不丢提交 assert store.delete(task.id) is True assert store.get(task.id) is None def test_project_store_roundtrip(self, db_path: Path): from app.schemas.project import ProjectCreate from app.store.project_store import SqliteProjectStore store = SqliteProjectStore(db_path) proj = store.create( ProjectCreate(name="proj_x", code_root_path=r"D:\tmp\x") ) assert store.get(proj.id) is not None assert store.get(proj.id).name == "proj_x" def test_model_config_store_roundtrip(self, db_path: Path): from app.schemas.model_config import ModelConfigCreate from app.store.model_config_store import SqliteModelConfigStore store = SqliteModelConfigStore(db_path) cfg = store.create( ModelConfigCreate( display_name="m1", model_id="mimo-v2.6-pro", provider_key="ccswitch", ) ) assert store.get(cfg.id) is not None def test_db_connection_store_roundtrip(self, db_path: Path): from app.schemas.database import DatabaseConnectionCreate from app.store.db_connection_store import SqliteDatabaseConnectionStore store = SqliteDatabaseConnectionStore(db_path) item = store.create( DatabaseConnectionCreate( name="db1", db_type="sqlite", host="localhost", port=0, database="x" ) ) assert store.get(item.id) is not None class TestServiceLayerConn: """ services / store 层的 _conn() 泄漏修复(同款 _connect 问题)。 每个用例两件事: 1. `_conn()` 退出后连接必须已关闭(这是本轮修的东西) 2. 读写往返仍然正常(证明换连接方式没破坏业务逻辑) """ @staticmethod def _assert_closed(store) -> None: """用完 _conn() 后,连接必须不可再操作。""" captured: list[sqlite3.Connection] = [] with store._conn() as conn: captured.append(conn) with pytest.raises(sqlite3.ProgrammingError): captured[0].execute("SELECT 1") def test_memory_store(self, db_path: Path): from app.services.memory_service import MemoryStore store = MemoryStore(db_path) self._assert_closed(store) mem_id = store.remember("编码规范统一用中文注释", project_id="p1", category="规范") assert mem_id assert len(store.list_memories(project_id="p1")) == 1 assert store.delete(mem_id) is True def test_template_store(self, db_path: Path): from app.services.template_service import TemplateStore store = TemplateStore(db_path) self._assert_closed(store) tpl = store.create(name="t1", category="修复", content="修 xxx") assert store.get(tpl.id) is not None assert store.delete(tpl.id) is True def test_workspace_store(self, db_path: Path): from app.services.workspace_service import WorkspaceStore store = WorkspaceStore(db_path) self._assert_closed(store) ws = store.create(name="ws1", description="测试空间") assert store.get(ws["id"]) is not None assert store.delete(ws["id"]) is True def test_knowledge_graph_store(self, db_path: Path): from app.services.knowledge_graph_service import KnowledgeGraphStore store = KnowledgeGraphStore(db_path) self._assert_closed(store) triple_id = store.add_triple("Agent", "使用", "SQLite", source="测试") assert triple_id assert len(store.query_by_subject("Agent")) == 1 def test_provider_store(self, db_path: Path): from app.store.provider_store import ProviderStore store = ProviderStore(db_path) self._assert_closed(store) p = store.create(name="p_custom", base_url="http://localhost:1", api_key="k") assert store.get_by_name("p_custom") is not None assert store.delete(p["id"]) is True def test_platform_account_store(self, db_path: Path): from app.store.platform_account_store import PlatformAccountStore store = PlatformAccountStore(db_path) self._assert_closed(store) acc = store.create( brand="测试品牌", account_name="a1", plan_name="基础版", console_url="http://x" ) assert store.get(acc["id"]) is not None assert store.delete(acc["id"]) is True class TestHealthAndBackupFinally: """health / backup 的 close 必须在 finally(异常路径不泄漏)。""" def test_health_check_database_closes_conn(self, db_path: Path): """health 的 close 在 finally 中:成功路径连接也必须已关闭。""" import app.services.health_service as hs _create_table(db_path) captured: list[sqlite3.Connection] = [] real_connect = sqlite3.connect def _spy_connect(*args, **kwargs): conn = real_connect(*args, **kwargs) captured.append(conn) return conn real_settings = hs.load_settings try: hs.load_settings = lambda: type("S", (), {"sqlite_db_path": db_path})() hs.sqlite3.connect = _spy_connect result = hs._check_database() finally: hs.load_settings = real_settings hs.sqlite3.connect = real_connect assert result["status"] == "healthy" assert captured, "应当建立过连接" # 【核心断言】连接必须已关闭 with pytest.raises(sqlite3.ProgrammingError): captured[0].execute("SELECT 1")