test_graph.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """qna 引擎单测:用 fake LLM 返回固定 JSON,验证图节点输出"""
  2. import json
  3. import sys
  4. from pathlib import Path
  5. sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # cfc-langgraph 根
  6. import pytest # noqa: E402
  7. # B-255-1:`cfc-langgraph/src/qna/` 尚未入库(src 下仅有 graphs/llm/prompts/schemas),
  8. # 模块级 `from src.qna import ...` 会让 `pytest tests` 在收集期 Interrupted、0 例执行(假绿风险)。
  9. # 改用 importorskip:qna 落地后本模块自动恢复执行,未落地时只跳过本模块而不阻断全量收集。
  10. pytest.importorskip("src.qna", reason="src/qna 尚未入库(B-255-1),跳过 qna 引擎单测")
  11. from src.qna import schemas, graph, prompts # noqa: E402
  12. class FakeLLM:
  13. """返回固定决策 JSON 的假 LLM"""
  14. def __init__(self, decisions):
  15. self.decisions = list(decisions)
  16. self.calls = []
  17. def invoke(self, messages):
  18. self.calls.append(messages)
  19. d = self.decisions.pop(0) if len(self.decisions) > 1 else self.decisions[0]
  20. return type("R", (), {"content": json.dumps(d, ensure_ascii=False)})()
  21. def make_scene(**kw):
  22. base = {
  23. "scene_key": "microbiome",
  24. "opening_prompt": "了解您的肠道健康状况",
  25. "dimensions_json": {"user": ["肠道状态"], "need": ["营养需求"]},
  26. "kb_scope": ["microbiome"],
  27. "max_questions": 12,
  28. }
  29. base.update(kw)
  30. return base
  31. def test_decide_next_ask():
  32. llm = FakeLLM([{"action": "ask", "question": {
  33. "id": "q1", "type": "single", "text": "您多久吃一次蔬菜?",
  34. "options": [{"id": "a", "label": "每天"}]}, "reason": "了解饮食"}])
  35. state = graph.decide_next(llm, make_scene(), [], prompt_fn=prompts.build_decide_prompt)
  36. assert state["action"] == "ask"
  37. assert state["question"]["text"].startswith("您多久")
  38. def test_decide_next_force_finish_when_max_reached():
  39. llm = FakeLLM([{"action": "ask", "question": {"id": "q9", "type": "text", "text": "x"}}])
  40. history = [{"question": {"text": f"q{i}"}, "answer": "a"} for i in range(12)]
  41. state = graph.decide_next(llm, make_scene(max_questions=12), history, prompt_fn=prompts.build_decide_prompt)
  42. assert state["action"] == "finish"
  43. def test_decide_next_invalid_json_retries_once():
  44. llm = FakeLLM(["not json", {"action": "finish", "reason": "信息足够"}])
  45. state = graph.decide_next(llm, make_scene(), [], prompt_fn=prompts.build_decide_prompt)
  46. assert state["action"] == "finish"
  47. assert len(llm.calls) == 2 # 重试了一次
  48. def test_generate_profile_structure():
  49. llm = FakeLLM([{"user_profile": [{"dimension": "肠道状态", "score": 70, "description": "偏健康",
  50. "evidence": ["答1"]}],
  51. "need_profile": [{"dimension": "营养需求", "description": "补纤维",
  52. "evidence": ["答1"], "suggestion": "多吃粗粮"}]}])
  53. history = [{"question": {"text": "q1"}, "answer": "a"}]
  54. profile, kb_used = graph.generate_profile(llm, make_scene(), history, kb_context=[{"content": "菌属知识"}],
  55. prompt_fn=prompts.build_profile_prompt)
  56. assert "user_profile" in profile and "need_profile" in profile
  57. assert profile["user_profile"][0]["dimension"] == "肠道状态"
  58. assert 0 <= profile["user_profile"][0]["score"] <= 100
  59. assert kb_used is True