فهرست منبع

test: conftest 增加 init_checkpointer fixture,修复 chat/auto_tag 的 checkpointer 未初始化与跨测试绑定问题

pytest(httpx ASGITransport) 不触发 FastAPI startup,chat_graph 依赖的
AsyncSqliteSaver 单例未初始化,get_checkpointer() 抛 RuntimeError 500;
auto_tag 测试复用 /api/v1/chat 同样受影响。

pytest-asyncio strict 模式每测试独立事件循环,而 chat.py 模块级缓存图在
编译期绑定 saver 单例,跨测试复用旧 loop 的 saver 会报
"no active connection"。fixture teardown 因此:关闭连接、重置 saver 单例、
清空 chat._graph 缓存,使下一测试在自己的 loop 内重建图。

tests/test_auto_tag.py 与 tests/test_chat.py 应用该 fixture。
zxyj-langgraph 1 هفته پیش
والد
کامیت
7604d06dd8
3فایلهای تغییر یافته به همراه44 افزوده شده و 0 حذف شده
  1. 37 0
      cfc-langgraph/conftest.py
  2. 4 0
      cfc-langgraph/tests/test_auto_tag.py
  3. 3 0
      cfc-langgraph/tests/test_chat.py

+ 37 - 0
cfc-langgraph/conftest.py

@@ -15,3 +15,40 @@ class _MockCTranslate2:
 # Install mock before any real import of ctranslate2
 if "ctranslate2" not in sys.modules:
     sys.modules["ctranslate2"] = _MockCTranslate2()
+
+
+import pytest_asyncio  # noqa: E402
+
+
+@pytest_asyncio.fixture
+async def init_checkpointer():
+    """为测试初始化 LangGraph checkpointer(等价于 app startup 中的 init_checkpointer())。
+
+    pytest(httpx ASGITransport)不触发 FastAPI startup,导致依赖
+    get_checkpointer() 的图(chat/health_coach)抛 "checkpointer 未初始化"。
+
+    pytest-asyncio strict 模式每个测试独立事件循环,而 chat.py 模块级缓存图在
+    编译期绑定 saver 单例。因此 teardown 必须:① 关闭连接并重置 saver 单例;
+    ② 清空 chat._graph 缓存,让下一个测试在自己的 loop 内重建图,
+    否则跨测试复用旧 loop 的 saver 会报 "no active connection"。
+    """
+    import app.api.chat as chat_mod
+    from app import checkpointer as cp
+
+    await cp.init_checkpointer()
+    yield
+    if cp._saver is not None:
+        closer = getattr(cp._saver, "aclose", None)
+        if closer is not None:
+            try:
+                await closer()
+            except Exception:
+                pass
+        conn = getattr(cp._saver, "conn", None)
+        if conn is not None:
+            try:
+                await conn.close()
+            except Exception:
+                pass
+    cp._saver = None
+    chat_mod._graph = None

+ 4 - 0
cfc-langgraph/tests/test_auto_tag.py

@@ -31,6 +31,10 @@ from httpx import AsyncClient, ASGITransport
 from app.main import app
 
 
+# auto_tag 复用 /api/v1/chat(chat_graph 依赖 AsyncSqliteSaver checkpointer)
+pytestmark = pytest.mark.usefixtures("init_checkpointer")
+
+
 # ============================================================
 # 测试数据
 # ============================================================

+ 3 - 0
cfc-langgraph/tests/test_chat.py

@@ -3,6 +3,9 @@ from httpx import AsyncClient, ASGITransport
 from app.main import app
 
 
+pytestmark = pytest.mark.usefixtures("init_checkpointer")
+
+
 @pytest.mark.asyncio
 async def test_chat_endpoint():
     transport = ASGITransport(app=app)