Files
projectAIpopular/tests/test_classifier.py
tzt b2fa8c3c81 feat(v2): 架构与算法优化——语义缓存 2.37x、拓扑排序 O(V+E)、分类器确定性决胜
算法:
- RouterCache:语义条目写入时预计算向量范数、语义查找单遍完成(消除命中后二次 O(N) 查找)、
  相似度=1.0 提前终止;微基准(3000 条目×200 查询):3986ms -> 1685ms,2.37x
- TaskGraph.topo_order:O(V²logV) 重排序/成员扫描 -> 邻接表+deque 的 O(V+E) Kahn,
  输出顺序契约不变(初始就绪层按插入序、循环依赖按插入序兜底、未知依赖忽略)
- RuleClassifier:同分决胜按领域名字典序(与规则表排列无关),次高分 O(n) 扫描

工程卫生:
- .mimosa/(扫描器工作目录)加入 .gitignore 并移出索引
- test_review 抽样测试改用内联确定性 LCG,消除 2 个低危(不安全随机数)

测试:新增 11 项(topo 契约 6 + 缓存回归 3 + 分类器 2)
pytest 230 passed(基线 219 全绿 + 11)
2026-09-18 08:35:36 +08:00

64 lines
2.0 KiB
Python

"""分类器单元测试。"""
from router_system.classifier import RuleClassifier
def test_tie_break_is_deterministic():
"""同分决胜:按领域名字典序,与规则表排列顺序无关。"""
clf = RuleClassifier()
clf.rules = {"zeta": [("x", 1.0)], "alpha": [("x", 1.0)]}
r = clf.classify("x")
assert r.domain == "alpha"
def test_distinctiveness_penalty():
"""次高分占比高(语义含混)时置信度被压低;单一领域命中不受影响。"""
clf = RuleClassifier()
clf.rules = {"a": [("kw", 1.0)], "b": [("kw", 0.9)]}
r_ambiguous = clf.classify("kw")
clf_clear = RuleClassifier()
clf_clear.rules = {"a": [("kw", 1.0)], "b": [("other", 0.1)]}
r_clear = clf_clear.classify("kw")
assert r_clear.confidence > r_ambiguous.confidence
def test_code_classification():
clf = RuleClassifier()
r = clf.classify("用 Python 写一个快速排序函数")
assert r.domain == "code"
assert r.confidence > 0.7
def test_math_classification():
clf = RuleClassifier()
r = clf.classify("求解方程 x^2 - 5x + 6 = 0")
assert r.domain == "math"
assert r.confidence > 0.7
def test_legal_classification():
clf = RuleClassifier()
r = clf.classify("劳动合同到期不续签需要支付经济补偿吗")
assert r.domain == "legal"
def test_medical_classification():
clf = RuleClassifier()
r = clf.classify("高血压患者日常饮食需要注意什么")
assert r.domain == "medical"
def test_general_low_confidence():
clf = RuleClassifier()
r = clf.classify("你好呀")
# 未命中任何领域 -> general,低置信度,触发 should_fallback
assert r.domain == "general"
assert clf.should_fallback(r, 0.6) is True
def test_difficulty_estimation():
clf = RuleClassifier()
easy = clf.classify("1 + 1 = ?")
hard = clf.classify("证明费马大定理并推导其推论,给出详细步骤")
assert hard.difficulty in ("medium", "hard")
assert easy.difficulty == "easy"