test_graph_store.py
8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""图谱存储:按文档溯源与删除、实体合并、噪声过滤。"""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from app.extract import typing_pass as typing_mod # noqa: E402
from app.extract.normalize import TypeNormalizer, is_noise_entity # noqa: E402
from app.store.graph_store import GraphStore, canon_key # noqa: E402
@pytest.fixture()
def graph(tmp_path: Path) -> GraphStore:
return GraphStore(tmp_path / "graph.json")
class TestCanonKey:
@pytest.mark.parametrize("a,b", [
("盯防周期T", "盯防周期 T"),
("5分钟", "5 分钟"),
("生态+自然", "生态 + 自然"),
("UI达标参考线", "UI 达标参考线"),
("上月26日~当天", "上月 26 日~当天"),
])
def test_whitespace_and_punct_duplicates_collapse(self, a, b):
"""这 5 组都是 v1 图谱里实际存在的重复实体。"""
assert canon_key(a) == canon_key(b)
def test_distinct_terms_stay_distinct(self):
assert canon_key("生态月") != canon_key("自然月")
assert canon_key("转化率") != canon_key("达标转化率")
class TestDocumentProvenance:
def test_delete_document_reclaims_exclusive_entities(self, graph: GraphStore):
src1 = {"chunk_id": "d1:c0", "doc_id": 1, "heading": "A", "snippet": "x"}
src2 = {"chunk_id": "d2:c0", "doc_id": 2, "heading": "B", "snippet": "y"}
graph.add_entity("门店", "门店", "线下网点", src1, doc_id=1)
graph.add_entity("门店", "门店", "线下网点", src2, doc_id=2) # 两篇文档共享
graph.add_entity("兜底协议", "协议", "", src1, doc_id=1) # 仅文档 1
graph.add_relation("门店", "兜底协议", "签署", "", src1, doc_id=1)
assert graph.g.number_of_nodes() == 2
stats = graph.delete_document(1)
assert stats["removed_entities"] == 1 # 兜底协议被回收
assert stats["removed_relations"] == 1
assert graph.has_node("门店") # 文档 2 还在支撑它
assert not graph.has_node("兜底协议")
def test_delete_last_document_clears_everything(self, graph: GraphStore):
src = {"chunk_id": "d1:c0", "doc_id": 1, "heading": "", "snippet": ""}
graph.add_entity("A", "其他", "", src, doc_id=1)
graph.add_relation("A", "B", "关联", "", src, doc_id=1)
graph.delete_document(1)
assert graph.g.number_of_nodes() == 0
class TestMerge:
def test_merge_redirects_edges_and_keeps_alias(self, graph: GraphStore):
graph.add_entity("主机厂", "集团", "整车厂", doc_id=1)
graph.add_entity("主机厂侧", "集团", "整车厂一侧", doc_id=1)
graph.add_relation("主机厂侧", "门店", "下发", "下发策略", doc_id=1)
assert graph.merge_nodes("主机厂", "主机厂侧")
assert not graph.has_node("主机厂侧")
detail = graph.node_detail("主机厂")
assert "主机厂侧" in detail["aliases"]
assert any(e["target"] == "门店" for e in detail["out_edges"])
def test_merge_accumulates_occurrence(self, graph: GraphStore):
graph.add_relation("A", "C", "关联", doc_id=1)
graph.add_relation("B", "C", "关联", doc_id=1)
graph.merge_nodes("A", "B")
edge = graph.edge_detail("A", "C", "关联")
assert edge is not None and edge["occurrence"] == 2
def test_merge_missing_node_is_noop(self, graph: GraphStore):
graph.add_entity("A", "其他", doc_id=1)
assert graph.merge_nodes("A", "不存在") is False
class TestManualEdit:
def test_add_manual_entity_is_marked_and_isolated(self, graph: GraphStore):
nid = graph.add_manual_entity("安心包专岗", "组织角色", "人工补录的岗位", "安心包专岗")
assert nid == "安心包专岗"
detail = graph.node_detail(nid)
assert detail["origin"] == "manual"
assert detail["verified"] is True
assert detail["occurrence"] == 0
assert detail["doc_ids"] == []
assert graph._node_payload(nid, graph.g.nodes[nid], 0)["attributes"]["origin"] == "manual"
def test_manual_entity_rejects_duplicate_name(self, graph: GraphStore):
graph.add_entity("门店", "门店", "", doc_id=1)
assert graph.add_manual_entity(" 门店 ", "门店", "人工") == ""
def test_manual_relation_requires_existing_endpoints(self, graph: GraphStore):
graph.add_manual_entity("A", "其他", "人工")
assert graph.add_manual_relation("A", "B", "关联", "") is None
def test_manual_relation_rejects_duplicate(self, graph: GraphStore):
graph.add_entity("A", "其他", doc_id=1)
graph.add_entity("B", "其他", doc_id=1)
graph.add_manual_entity("C", "其他")
assert graph.add_manual_relation("A", "B", "关联", "人工") == ("A", "B", "关联")
assert graph.add_manual_relation("A", "B", " 关联 ", "再插一次") is None
def test_manual_content_survives_document_reclaim(self, graph: GraphStore):
src = {"chunk_id": "d1:c0", "doc_id": 1, "heading": "A", "snippet": "x"}
graph.add_entity("门店", "门店", "", src, doc_id=1)
graph.add_manual_entity("手工节点", "其他", "人工")
graph.delete_document(1)
assert not graph.has_node("门店")
assert graph.has_node("手工节点")
class TestManualNodesAutomaticPasses:
def test_complete_types_skips_manual(self, graph: GraphStore, monkeypatch):
graph.add_entity("真实点", "其他", "", doc_id=1)
graph.add_manual_entity("人工点", "其他", "人工")
monkeypatch.setattr(typing_mod.llm, "embed",
lambda texts: np.zeros((len(texts), 4), dtype=np.float32))
msgs: list[str] = []
stats = typing_mod.complete_types(graph, ["指标"], progress=msgs.append)
assert stats["candidates"] == 1
assert any("1 个未分类实体" in m for m in msgs)
def test_describe_orphans_skips_manual(self, graph: GraphStore, monkeypatch):
graph.add_manual_entity("人工点1", "其他", "")
graph.add_manual_entity("人工点2", "其他", "")
graph.add_manual_relation("人工点1", "人工点2", "关联", "")
monkeypatch.setattr(typing_mod.llm, "chat", lambda *a, **kw: "")
msgs: list[str] = []
stats = typing_mod.describe_orphans(graph, concurrency=1, progress=msgs.append)
assert stats["candidates"] == 0
class TestNoiseFilter:
@pytest.mark.parametrize("name", [
"10分钟", "4小时", "120分钟", "5 分钟", "2小时", # v1 真实抽出的噪声
"验证码", "文件名", "日志", "数据", "系统", "表", "率",
"30%", "2024年", "1", "a",
])
def test_rejects_noise(self, name):
assert is_noise_entity(name)
@pytest.mark.parametrize("name", [
"生态系数", "兜底协议", "生态月", "策略盯防", "达标转化率",
"主机厂数据", "盯防列表", "安心包",
])
def test_keeps_real_business_entities(self, name):
assert not is_noise_entity(name)
def test_rejects_whole_sentence(self):
assert is_noise_entity("门店未达标时需要按照差额进行赔付并在次月结算")
class TestTypeNormalizer:
def test_maps_alias_to_closed_set(self):
n = TypeNormalizer(use_embedding=False)
assert n.entity_type("未分类") == "其他"
assert n.entity_type("KPI") == "指标"
assert n.entity_type("岗位") == "角色"
assert n.entity_type("业务规则") == "规则"
def test_unknown_falls_back_to_other_and_is_recorded(self):
n = TypeNormalizer(use_embedding=False)
assert n.entity_type("薛定谔的猫") == "其他"
assert "薛定谔的猫" in n.unmapped_types
def test_relation_normalization_keeps_raw(self):
n = TypeNormalizer(use_embedding=False)
mapped, raw = n.relation_type("属于")
assert mapped == "隶属" and raw == "属于"
def test_known_type_passes_through(self):
n = TypeNormalizer(use_embedding=False)
assert n.entity_type("指标") == "指标"