Merge branch 'dev' into hugo
This commit is contained in:
commit
d5928b42f3
63 files changed
+5759
-1493
No files matched your search
@@ -267,6 +267,11 @@ def test_reports(client, admin_headers):
|
||||
assert 'total' in data
|
||||
assert 'by_user' in data
|
||||
assert 'by_agent' in data
|
||||
assert 'user_total' in data
|
||||
assert 'user_page' in data
|
||||
assert 'user_page_size' in data
|
||||
assert 'user_pages' in data
|
||||
assert 'user_top_limit' in data
|
||||
|
||||
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -127,5 +127,96 @@ def test_update_chat_log_tokens_backfills_after_message_end(app):
|
||||
assert updated is True
|
||||
assert db.session.get(ChatLog, chat_log_id).tokens_used == 3068
|
||||
|
||||
# 不应被更小的值覆盖
|
||||
|
||||
def test_collect_knowledge_retrieval_from_node_finished():
|
||||
"""Chatflow:知识检索来源应从 node_finished.outputs.result 提取。"""
|
||||
retriever_resources: list = []
|
||||
event_data = {
|
||||
'event': 'node_finished',
|
||||
'data': {
|
||||
'node_type': 'knowledge-retrieval',
|
||||
'status': 'succeeded',
|
||||
'outputs': {
|
||||
'result': [
|
||||
{
|
||||
'metadata': {
|
||||
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
|
||||
'dataset_name': '4.人事规章',
|
||||
'document_id': '94b7246a-4daa-4dff-bdef-01510848f985',
|
||||
'document_name': '员工入职须4',
|
||||
'segment_id': '9d10e131-bf02-4add-8ef1-d3098a2ab7a4',
|
||||
'score': 0.8577696681022644,
|
||||
},
|
||||
'title': '员工入职须4',
|
||||
'files': None,
|
||||
'content': '员工入职须知4\n2.上班时间',
|
||||
},
|
||||
{
|
||||
'metadata': {
|
||||
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
|
||||
'document_id': '97eab330-d658-4f9e-aa7f-a24423234ee5',
|
||||
'document_name': '考勤-公司班次信息',
|
||||
},
|
||||
'title': '考勤-公司班次信息',
|
||||
'content': '考勤-公司班次信息',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, event_data)
|
||||
|
||||
assert len(retriever_resources) == 2
|
||||
assert retriever_resources[0]['document_id'] == '94b7246a-4daa-4dff-bdef-01510848f985'
|
||||
assert retriever_resources[0]['document_name'] == '员工入职须4'
|
||||
assert retriever_resources[0]['dataset_id'] == 'ac0cf595-ca91-4f48-a0d1-0d31544c4136'
|
||||
assert retriever_resources[1]['document_id'] == '97eab330-d658-4f9e-aa7f-a24423234ee5'
|
||||
|
||||
|
||||
def test_attach_retriever_resources_to_workflow_finished_event():
|
||||
"""workflow_finished 下发前应携带 retriever_resources 供前端展示源文件。"""
|
||||
resources = [
|
||||
{
|
||||
'dataset_id': 'ds-1',
|
||||
'document_id': 'doc-1',
|
||||
'document_name': '员工入职须知.pdf',
|
||||
'content': '上班时间 8:00',
|
||||
},
|
||||
]
|
||||
event_data = {'event': 'workflow_finished', 'metadata': {}}
|
||||
|
||||
DifyService._attach_retriever_resources_to_event(event_data, resources)
|
||||
|
||||
assert len(event_data['retriever_resources']) == 1
|
||||
assert event_data['retriever_resources'][0]['document_name'] == '员工入职须知.pdf'
|
||||
assert event_data['metadata']['retriever_resources'][0]['document_id'] == 'doc-1'
|
||||
|
||||
|
||||
def test_update_chat_log_tokens_does_not_decrease(app):
|
||||
"""已写入更大 token 后,不应被更小的值覆盖。"""
|
||||
with app.app_context():
|
||||
user = User(username='u3', role='user', email='u3@example.com')
|
||||
agent = Agent(name='wf_agent3', dify_app_id='wf-3')
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
|
||||
first = DifyService._persist_stream_chat_record(
|
||||
data={'event': 'message_end', 'conversation_id': 'conv-wf-3', 'metadata': {}},
|
||||
event_name='message_end',
|
||||
request_id='req-wf-3',
|
||||
user_id=user.id,
|
||||
agent=agent,
|
||||
session_id='sess-wf-3',
|
||||
hxops_turn_id=None,
|
||||
normalized_conversation_id='conv-wf-3',
|
||||
query='test',
|
||||
answer_text='answer',
|
||||
latency=1000,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
chat_log_id = first['chat_log_id']
|
||||
DifyService._update_chat_log_tokens(chat_log_id, 500)
|
||||
assert DifyService._update_chat_log_tokens(chat_log_id, 100) is False
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/tests/test_faq_kb_invalidation.py
|
||||
|
||||
用途:FAQ 与 KB 文档关联解析及失效标记单元测试。
|
||||
"""
|
||||
from app.services.faq_kb_invalidation import (
|
||||
_faq_links_kb_document,
|
||||
extract_dify_id_pairs,
|
||||
merge_source_kb_document_ids,
|
||||
)
|
||||
from app.models import QuickQuestion
|
||||
|
||||
|
||||
def test_extract_dify_id_pairs_from_retriever_resources():
|
||||
resources = [
|
||||
{'dataset_id': 'ds-1', 'document_id': 'doc-1'},
|
||||
{'metadata': {'dify_dataset_id': 'ds-2', 'remote_document_id': 'doc-2'}},
|
||||
]
|
||||
pairs = extract_dify_id_pairs(resources)
|
||||
assert ('ds-1', 'doc-1') in pairs
|
||||
assert ('ds-2', 'doc-2') in pairs
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_source_ids():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
source_kb_document_ids=[10, 20],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 10, None, None) is True
|
||||
assert _faq_links_kb_document(qq, 99, None, None) is False
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_retriever_resources():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
retriever_resources=[{'dataset_id': 'ds-a', 'document_id': 'remote-a'}],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-a', 'remote-a') is True
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-b', 'remote-a') is False
|
||||
|
||||
|
||||
def test_merge_source_kb_document_ids():
|
||||
merged = merge_source_kb_document_ids([1], None)
|
||||
assert merged == [1]
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/tests/test_fixed_assets_snapshot.py
|
||||
|
||||
用途:验证固定资产快照查询服务的核心过滤行为。
|
||||
依赖:pytest、Flask app fixture、FixedAssetsSnapshotService。
|
||||
逻辑关系:覆盖“资产名称+规格型号组合查询”和“本人名下资产查询”两个高频场景。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
|
||||
def _seed_latest_snapshot(root: Path) -> None:
|
||||
"""写入一份最小可用的 latest 快照,供查询服务读取。"""
|
||||
rows = [
|
||||
{
|
||||
"资产编号": "A0827011",
|
||||
"资产名称": "线切割机",
|
||||
"资产名称2": "",
|
||||
"规格型号": "DK7732",
|
||||
"保管人工号": "E1001",
|
||||
"保管人姓名": "张三",
|
||||
"保管部门编号": "D01",
|
||||
"保管部门名称": "制造部",
|
||||
"存放位置名称": "一厂机加区",
|
||||
"资产状态": "折旧中",
|
||||
"资产状态代码": "2",
|
||||
"预留残值": "1000",
|
||||
"供应厂商": "华东设备",
|
||||
"资产性质": "有形资产",
|
||||
"资产性质代码": "1",
|
||||
"本币单价": "60000",
|
||||
"数量": "1",
|
||||
"计量单位": "台",
|
||||
"取得日期": "2024-01-01 00:00:00",
|
||||
"入账日期": "2024-01-10 00:00:00",
|
||||
"营运中心代码": "HXJM",
|
||||
"站点代码": "JM",
|
||||
"备注": "资产编号:A0827011 | 资产名称:线切割机 | 规格型号:DK7732 | 保管人姓名:张三 | 保管部门名称:制造部 | 存放位置名称:一厂机加区 | 资产状态:折旧中 | 供应厂商:华东设备 | 资产性质:有形资产",
|
||||
"备注标准化": "资产编号A0827011资产名称线切割机规格型号DK7732保管人姓名张三保管部门名称制造部存放位置名称一厂机加区资产状态折旧中供应厂商华东设备资产性质有形资产",
|
||||
},
|
||||
{
|
||||
"资产编号": "A0827012",
|
||||
"资产名称": "400吨冲床",
|
||||
"资产名称2": "",
|
||||
"规格型号": "JH21-400",
|
||||
"保管人工号": "E1002",
|
||||
"保管人姓名": "李四",
|
||||
"保管部门编号": "D02",
|
||||
"保管部门名称": "冲压部",
|
||||
"存放位置名称": "二厂冲压区",
|
||||
"资产状态": "折旧中",
|
||||
"资产状态代码": "2",
|
||||
"预留残值": "2000",
|
||||
"供应厂商": "华南设备",
|
||||
"资产性质": "有形资产",
|
||||
"资产性质代码": "1",
|
||||
"本币单价": "200000",
|
||||
"数量": "1",
|
||||
"计量单位": "台",
|
||||
"取得日期": "2023-01-01 00:00:00",
|
||||
"入账日期": "2023-01-10 00:00:00",
|
||||
"营运中心代码": "HTT",
|
||||
"站点代码": "TT",
|
||||
"备注": "资产编号:A0827012 | 资产名称:400吨冲床 | 规格型号:JH21-400 | 保管人姓名:李四 | 保管部门名称:冲压部 | 存放位置名称:二厂冲压区 | 资产状态:折旧中 | 供应厂商:华南设备 | 资产性质:有形资产",
|
||||
"备注标准化": "资产编号A0827012资产名称400吨冲床规格型号JH21400保管人姓名李四保管部门名称冲压部存放位置名称二厂冲压区资产状态折旧中供应厂商华南设备资产性质有形资产",
|
||||
},
|
||||
]
|
||||
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
latest_dir = root / "latest"
|
||||
latest_dir.mkdir(parents=True, exist_ok=True)
|
||||
FixedAssetsSnapshotService._write_snapshot_db(
|
||||
latest_dir / "FixedAssets_latest.db",
|
||||
rows,
|
||||
version="20260622_030000",
|
||||
snapshot_date="2026-06-22",
|
||||
)
|
||||
|
||||
|
||||
def test_query_assets_supports_name_and_spec_combo(app, tmp_path):
|
||||
app.config["FIXED_ASSETS_STORAGE_ROOT"] = str(tmp_path / "fixed_assets")
|
||||
with app.app_context():
|
||||
_seed_latest_snapshot(tmp_path / "fixed_assets")
|
||||
|
||||
columns, rows, total = FixedAssetsSnapshotService.query_assets("查询线切割机 规格型号 DK7732")
|
||||
|
||||
# 断言:组合查询应命中同一台设备,且返回预期中文列头。
|
||||
assert columns[:3] == ["资产编号", "资产名称", "规格型号"]
|
||||
assert total == 1
|
||||
assert rows[0][0] == "A0827011"
|
||||
assert rows[0][1] == "线切割机"
|
||||
assert rows[0][2] == "DK7732"
|
||||
|
||||
|
||||
def test_query_assets_supports_self_scope(app, tmp_path):
|
||||
app.config["FIXED_ASSETS_STORAGE_ROOT"] = str(tmp_path / "fixed_assets")
|
||||
with app.app_context():
|
||||
_seed_latest_snapshot(tmp_path / "fixed_assets")
|
||||
|
||||
columns, rows, total = FixedAssetsSnapshotService.query_assets(
|
||||
"查询我名下固定资产",
|
||||
user_context={"employee_id": "E1001", "real_name": "张三", "username": "zhangsan"},
|
||||
)
|
||||
|
||||
# 断言:本人查询必须按当前用户身份过滤,不能返回其他人的资产。
|
||||
assert columns[0] == "资产编号"
|
||||
assert total == 1
|
||||
assert len(rows) == 1
|
||||
assert rows[0][0] == "A0827011"
|
||||
assert rows[0][3] == "张三"
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_hot_faq_aggregator.py
|
||||
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、答案聚类与代表答案选取。
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、代表答案选取。
|
||||
"""
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator, _LogRow
|
||||
@@ -15,15 +14,19 @@ def test_normalize_faq_query_strips_punctuation_and_space():
|
||||
assert normalize_faq_query('公司几点上班?') == normalize_faq_query('公司 几点上班')
|
||||
|
||||
|
||||
def test_answer_cluster_merges_similar_answers():
|
||||
"""相似度≥阈值的答案应归入同一簇。"""
|
||||
rows = [
|
||||
_LogRow(1, 1, 1, 'q', '工作日8:30到17:30', 100, 10, datetime.utcnow()),
|
||||
_LogRow(2, 2, 1, 'q', '工作日 8:30 到 17:30', 100, 10, datetime.utcnow()),
|
||||
]
|
||||
clusters = HotFaqAggregator._cluster_answers(rows)
|
||||
assert len(clusters) == 1
|
||||
assert len(clusters[0]['rows']) == 2
|
||||
def test_build_candidate_accepts_divergent_answers_when_clustering_disabled(app, monkeypatch):
|
||||
"""答案聚类关闭时,即使答案分歧较大也应生成热点候选。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is not None
|
||||
assert reason is None
|
||||
assert candidate.ask_count_7d == 6
|
||||
|
||||
|
||||
def test_pick_representative_prefers_good_feedback():
|
||||
@@ -37,17 +40,3 @@ def test_pick_representative_prefers_good_feedback():
|
||||
assert picked is not None
|
||||
assert picked.chat_log_id == 2
|
||||
assert picked.answer == 'answer B'
|
||||
|
||||
|
||||
def test_build_candidate_rejects_divergent_answers(app, monkeypatch):
|
||||
"""答案分歧过大时应跳过该热点组。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is None
|
||||
assert reason and reason.startswith('answer_divergence')
|
||||
@@ -1,7 +1,21 @@
|
||||
import pytest
|
||||
from app.models import User
|
||||
from app.models import User, Agent
|
||||
from app import db
|
||||
|
||||
def _error_message(response):
|
||||
body = response.get_json() or {}
|
||||
error = body.get('error')
|
||||
if isinstance(error, dict):
|
||||
return str(error.get('message') or '')
|
||||
return str(error or '')
|
||||
|
||||
def _error_code(response):
|
||||
body = response.get_json() or {}
|
||||
error = body.get('error')
|
||||
if isinstance(error, dict):
|
||||
return str(error.get('code') or '')
|
||||
return ''
|
||||
|
||||
def test_register_fields_validation(client):
|
||||
"""
|
||||
Test user registration field validation
|
||||
@@ -40,7 +54,7 @@ def test_register_fields_validation(client):
|
||||
}
|
||||
response = client.post('/api/user/register', json=dup_user)
|
||||
assert response.status_code == 400
|
||||
assert "Employee ID already exists" in response.json['error']
|
||||
assert "Employee ID already exists" in _error_message(response)
|
||||
|
||||
def test_admin_duplicate_employee_id(client, admin_headers):
|
||||
"""
|
||||
@@ -68,8 +82,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
||||
"phone_number": "13800000012"
|
||||
}
|
||||
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
|
||||
assert response.status_code == 400
|
||||
assert "Employee ID already exists" in response.json['error']
|
||||
assert response.status_code == 409
|
||||
assert "Employee ID already exists" in _error_message(response)
|
||||
|
||||
# 3. Update user to duplicate ID
|
||||
# Create u3 with valid ID
|
||||
@@ -86,5 +100,44 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
||||
|
||||
# Update u3 to ADM001 (which exists)
|
||||
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
|
||||
assert res.status_code == 400
|
||||
assert "Employee ID already exists" in res.json['error']
|
||||
assert res.status_code == 409
|
||||
assert "Employee ID already exists" in _error_message(res)
|
||||
assert _error_code(res) == 'USER.EMPLOYEE_ID_EXISTS'
|
||||
|
||||
def test_admin_duplicate_phone_on_update_with_agent_ids(client, admin_headers):
|
||||
"""
|
||||
编辑用户时若手机号重复且同时提交 agent_ids,应在 autoflush 前返回冲突而非 500。
|
||||
"""
|
||||
existing = {
|
||||
"username": "phone_owner",
|
||||
"password": "pwd",
|
||||
"email": "phone_owner@e.com",
|
||||
"real_name": "Phone Owner",
|
||||
"employee_id": "PHN001",
|
||||
"phone_number": "123456",
|
||||
}
|
||||
target = {
|
||||
"username": "phone_target",
|
||||
"password": "pwd",
|
||||
"email": "phone_target@e.com",
|
||||
"real_name": "Phone Target",
|
||||
"employee_id": "PHN002",
|
||||
"phone_number": "13800009999",
|
||||
}
|
||||
assert client.post('/api/admin/users', json=existing, headers=admin_headers).status_code == 201
|
||||
target_res = client.post('/api/admin/users', json=target, headers=admin_headers)
|
||||
assert target_res.status_code == 201
|
||||
target_id = target_res.json['id']
|
||||
|
||||
agent = Agent(name='Dup Phone Agent', dify_app_id='dup-phone-agent', type='chat')
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
|
||||
res = client.put(
|
||||
f'/api/admin/users/{target_id}',
|
||||
json={'phone_number': '123456', 'agent_ids': [agent.id]},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 409
|
||||
assert _error_code(res) == 'USER.PHONE_EXISTS'
|
||||
assert "Phone number already exists" in _error_message(res)
|
||||
Reference in new issue
Block a user