Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Block 5+6: 12 integration tests for LLM+RAG, 64/64 full regression, moved complete import to module level

whfa8e154fc18a3
diff --git a/.hermes_block5_spec.md b/.hermes_block5_spec.md
new file mode 100644
index 000000000..b802fc0a3
--- /dev/null
+++ b/.hermes_block5_spec.md
@@ -0,0 +1,156 @@
+# Block 5+6: 集成测试 + 全量回归
+
+## Block 5: 新建集成测试
+
+### 新建文件
+`deeptutor/learning/tests/test_llm_integration.py`
+
+### 测试用例
+
+```python
+"""Integration tests for guided_learning LLM + RAG integration."""
+
+import pytest
+from unittest.mock import AsyncMock, patch, MagicMock
+from deeptutor.capabilities.guided_learning import GuidedLearningCapability
+from deeptutor.learning.models import LearningProgress, LearningStage
+
+
+class TestLLMIntegration:
+ """Verify _call_llm calls real LLM factory."""
+
+ @pytest.mark.asyncio
+ async def test_call_llm_calls_complete(self):
+ """_call_llm should call deeptutor.services.llm.complete."""
+ cap = GuidedLearningCapability()
+ with patch("deeptutor.capabilities.guided_learning.complete",
+ new_callable=AsyncMock) as mock_complete:
+ mock_complete.return_value = "LLM response"
+ result = await cap._call_llm("system", "user")
+ mock_complete.assert_called_once()
+ assert result == "LLM response"
+
+ @pytest.mark.asyncio
+ async def test_call_llm_network_error(self):
+ """_call_llm returns error JSON on failure, never raises."""
+ cap = GuidedLearningCapability()
+ with patch("deeptutor.capabilities.guided_learning.complete",
+ new_callable=AsyncMock, side_effect=Exception("Network down")):
+ result = await cap._call_llm("system", "user")
+ assert "error" in result
+ assert "Network down" in result
+
+ def test_call_llm_exists_and_is_async(self):
+ """_call_llm should be an async method."""
+ import inspect
+ cap = GuidedLearningCapability()
+ assert hasattr(cap, "_call_llm")
+ assert inspect.iscoroutinefunction(cap._call_llm)
+
+
+class TestRAGIntegration:
+ """Verify RAG retrieval is called and injected."""
+
+ @pytest.mark.asyncio
+ async def test_retrieve_context_no_kb(self):
+ """Without kb_name, _retrieve_context returns empty string."""
+ cap = GuidedLearningCapability()
+ result = await cap._retrieve_context("test query")
+ assert result == ""
+
+ def test_kb_params_stored(self):
+ """kb_name and kb_base_dir should be stored as instance attrs."""
+ cap = GuidedLearningCapability(kb_name="my_kb", kb_base_dir="/tmp/kb")
+ assert cap._kb_name == "my_kb"
+ assert cap._kb_base_dir == "/tmp/kb"
+
+ def test_default_kb_is_none(self):
+ """Default kb_name should be None."""
+ cap = GuidedLearningCapability()
+ assert cap._kb_name is None
+ assert cap._kb_base_dir is None
+
+ @pytest.mark.asyncio
+ async def test_call_llm_injects_rag_context(self):
+ """_call_llm should call _retrieve_context and inject results."""
+ cap = GuidedLearningCapability(kb_name="test_kb")
+ with patch.object(cap, "_retrieve_context", new_callable=AsyncMock,
+ return_value="\n\n参考教材内容:\nSome content") as mock_rag:
+ with patch("deeptutor.capabilities.guided_learning.complete",
+ new_callable=AsyncMock) as mock_complete:
+ mock_complete.return_value = "response"
+ await cap._call_llm("system", "user")
+ mock_rag.assert_called_once_with("user")
+ # The system_prompt passed to complete should contain RAG context
+ called_system = mock_complete.call_args[1]["system_prompt"]
+ assert "参考教材内容" in called_system
+ assert "Some content" in called_system
+
+
+class TestNoMockRemnants:
+ """Verify no _mock_llm code remains."""
+
+ def test_no_mock_llm_on_instance(self):
+ """_mock_llm should not exist on any instance."""
+ cap = GuidedLearningCapability()
+ assert not hasattr(cap, "_mock_llm")
+
+ def test_no_mock_llm_in_source(self):
+ """_mock_llm should not appear anywhere in the module source."""
+ import inspect
+ src = inspect.getsource(GuidedLearningCapability)
+ assert "_mock_llm" not in src
+
+
+class TestJSONParse:
+ """Existing _safe_json_parse should still work."""
+
+ def test_valid_json(self):
+ cap = GuidedLearningCapability()
+ result = cap._safe_json_parse('{"key": "value"}')
+ assert result == {"key": "value"}
+
+ def test_invalid_json_fallback(self):
+ cap = GuidedLearningCapability()
+ result = cap._safe_json_parse("not json", default={"fallback": True})
+ assert result == {"fallback": True}
+
+ def test_invalid_json_empty_default(self):
+ cap = GuidedLearningCapability()
+ result = cap._safe_json_parse("garbage")
+ assert result == {}
+```
+
+### 验收
+```bash
+cd D:\Project\DeepTutor && .venv\Scripts\python.exe -m pytest deeptutor/learning/tests/test_llm_integration.py -v
+# 预期: 10 passed
+```
+
+---
+
+## Block 6: 全量回归
+
+### 验收
+```bash
+# 1. 全量测试 (原 52 + 新 10 = 62)
+cd D:\Project\DeepTutor && .venv\Scripts\python.exe -m pytest deeptutor/learning/tests/ -v
+# 预期: 62 passed
+
+# 2. Python 语法
+cd D:\Project\DeepTutor && .venv\Scripts\python.exe -m py_compile deeptutor/capabilities/guided_learning.py deeptutor/learning/prompts.py
+# 预期: 无输出
+
+# 3. Import 链
+cd D:\Project\DeepTutor && .venv\Scripts\python.exe -c "
+from deeptutor.capabilities.guided_learning import GuidedLearningCapability
+from deeptutor.learning.prompts import EXPLAIN_SYSTEM
+from deeptutor.learning.models import LearningProgress
+from deeptutor.learning.service import LearningService
+from deeptutor.learning.storage import LearningStore
+from deeptutor.learning.scheduler import SpacedRepetitionScheduler
+print('ALL IMPORTS OK')
+"
+```
+
+完成后报告结果:总测试数、通过数、失败数。
diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.py
index 098704b11..c171cf2a3 100644
--- a/deeptutor/capabilities/guided_learning.py
+++ b/deeptutor/capabilities/guided_learning.py
@@ -19,6 +19,7 @@ from deeptutor.learning.models import (
from deeptutor.learning.scheduler import SpacedRepetitionScheduler
from deeptutor.learning.service import LearningService
from deeptutor.learning.storage import LearningStore
+from deeptutor.services.llm import complete
class GuidedLearningCapability(BaseCapability):
@@ -131,7 +132,6 @@ class GuidedLearningCapability(BaseCapability):
async def _call_llm(self, system_prompt: str, user_message: str) -> str:
"""Call real LLM via DeepTutor's complete() function."""
try:
- from deeptutor.services.llm import complete
# RAG retrieval
rag_context = await self._retrieve_context(user_message)
if rag_context:
diff --git a/deeptutor/learning/tests/test_llm_integration.py b/deeptutor/learning/tests/test_llm_integration.py
new file mode 100644
index 000000000..830256165
--- /dev/null
+++ b/deeptutor/learning/tests/test_llm_integration.py
@@ -0,0 +1,111 @@
+"""Integration tests for guided_learning LLM + RAG integration."""
+
+import pytest
+from unittest.mock import AsyncMock, patch, MagicMock
+from deeptutor.capabilities.guided_learning import GuidedLearningCapability
+from deeptutor.learning.models import LearningProgress, LearningStage
+
+
+class TestLLMIntegration:
+ """Verify _call_llm calls real LLM factory."""
+
+ @pytest.mark.asyncio
+ async def test_call_llm_calls_complete(self):
+ """_call_llm should call deeptutor.services.llm.complete."""
+ cap = GuidedLearningCapability()
+ with patch("deeptutor.capabilities.guided_learning.complete",
+ new_callable=AsyncMock) as mock_complete:
+ mock_complete.return_value = "LLM response"
+ result = await cap._call_llm("system", "user")
+ mock_complete.assert_called_once()
+ assert result == "LLM response"
+
+ @pytest.mark.asyncio
+ async def test_call_llm_network_error(self):
+ """_call_llm returns error JSON on failure, never raises."""
+ cap = GuidedLearningCapability()
+ with patch("deeptutor.capabilities.guided_learning.complete",
+ new_callable=AsyncMock, side_effect=Exception("Network down")):
+ result = await cap._call_llm("system", "user")
+ assert "error" in result
+ assert "Network down" in result
+
+ def test_call_llm_exists_and_is_async(self):
+ """_call_llm should be an async method."""
+ import inspect
+ cap = GuidedLearningCapability()
+ assert hasattr(cap, "_call_llm")
+ assert inspect.iscoroutinefunction(cap._call_llm)
+
+
+class TestRAGIntegration:
+ """Verify RAG retrieval is called and injected."""
+
+ @pytest.mark.asyncio
+ async def test_retrieve_context_no_kb(self):
+ """Without kb_name, _retrieve_context returns empty string."""
+ cap = GuidedLearningCapability()
+ result = await cap._retrieve_context("test query")
+ assert result == ""
+
+ def test_kb_params_stored(self):
+ """kb_name and kb_base_dir should be stored as instance attrs."""
+ cap = GuidedLearningCapability(kb_name="my_kb", kb_base_dir="/tmp/kb")
+ assert cap._kb_name == "my_kb"
+ assert cap._kb_base_dir == "/tmp/kb"
+
+ def test_default_kb_is_none(self):
+ """Default kb_name should be None."""
+ cap = GuidedLearningCapability()
+ assert cap._kb_name is None
+ assert cap._kb_base_dir is None
+
+ @pytest.mark.asyncio
+ async def test_call_llm_injects_rag_context(self):
+ """_call_llm should call _retrieve_context and inject results."""
+ cap = GuidedLearningCapability(kb_name="test_kb")
+ with patch.object(cap, "_retrieve_context", new_callable=AsyncMock,
+ return_value="\n\n参考教材内容:\nSome content") as mock_rag:
+ with patch("deeptutor.capabilities.guided_learning.complete",
+ new_callable=AsyncMock) as mock_complete:
+ mock_complete.return_value = "response"
+ await cap._call_llm("system", "user")
+ mock_rag.assert_called_once_with("user")
+ # The system_prompt passed to complete should contain RAG context
+ called_system = mock_complete.call_args[1]["system_prompt"]
+ assert "参考教材内容" in called_system
+ assert "Some content" in called_system
+
+
+class TestNoMockRemnants:
+ """Verify no _mock_llm code remains."""
+
+ def test_no_mock_llm_on_instance(self):
+ """_mock_llm should not exist on any instance."""
+ cap = GuidedLearningCapability()
+ assert not hasattr(cap, "_mock_llm")
+
+ def test_no_mock_llm_in_source(self):
+ """_mock_llm should not appear anywhere in the module source."""
+ import inspect
+ src = inspect.getsource(GuidedLearningCapability)
+ assert "_mock_llm" not in src
+
+
+class TestJSONParse:
+ """Existing _safe_json_parse should still work."""
+
+ def test_valid_json(self):
+ cap = GuidedLearningCapability()
+ result = cap._safe_json_parse('{"key": "value"}')
+ assert result == {"key": "value"}
+
+ def test_invalid_json_fallback(self):
+ cap = GuidedLearningCapability()
+ result = cap._safe_json_parse("not json", default={"fallback": True})
+ assert result == {"fallback": True}
+
+ def test_invalid_json_empty_default(self):
+ cap = GuidedLearningCapability()
+ result = cap._safe_json_parse("garbage")
+ assert result == {}