fix(platform): 合并本地修复到测试环境
This commit is contained in:
commit
975e8bbcf5
41 files changed
+4564
-768
No files matched your search
@@ -1,4 +1,4 @@
|
||||
"""Tests for Dify sync process_rule selection (Excel custom vs default automatic)."""
|
||||
"""Tests for Dify sync process_rule selection (all document types preserve complete semantic blocks)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
@@ -10,14 +10,14 @@ def _make_service(monkeypatch, **overrides):
|
||||
'DIFY_API_KEY': 'dataset-test-key',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
'KB_DIFY_PROCESS_MODE': 'automatic',
|
||||
'KB_DIFY_PROCESS_MODE': 'custom',
|
||||
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
|
||||
'KB_DIFY_REMOVE_URLS': 'false',
|
||||
}
|
||||
settings.update(overrides)
|
||||
@@ -31,15 +31,18 @@ def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
|
||||
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 50
|
||||
# 断言完整行仍由空行隔开,避免表格字段在 Dify 中被拆散。
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 600
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 100
|
||||
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
|
||||
|
||||
|
||||
def test_build_process_rule_docx_defaults_to_automatic(monkeypatch):
|
||||
def test_build_process_rule_docx_uses_custom_semantic_blocks(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
rule = service._build_process_rule('docx')
|
||||
assert rule == {'mode': 'automatic'}
|
||||
# 断言制度类文档的标题、规则、例外条件保留在同一个检索片段中。
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
|
||||
|
||||
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
@@ -65,7 +68,7 @@ def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
process_rule = captured['json']['process_rule']
|
||||
assert process_rule['mode'] == 'custom'
|
||||
assert process_rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 600
|
||||
|
||||
|
||||
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
@@ -78,6 +81,59 @@ def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
assert remove_urls['enabled'] is True
|
||||
|
||||
|
||||
def test_wait_for_document_indexing_rejects_dify_error(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
|
||||
try:
|
||||
service.wait_for_document_indexing(
|
||||
dataset_id='dataset-001',
|
||||
document_id='document-001',
|
||||
initial_payload={
|
||||
'document': {
|
||||
'id': 'document-001',
|
||||
'indexing_status': 'error',
|
||||
'error': 'embedding credential invalid',
|
||||
},
|
||||
},
|
||||
)
|
||||
except dify_sync_module.KbDifySyncError as exc:
|
||||
# 断言 Dify 的原始原因被保留,供工作台展示而不是误报同步成功。
|
||||
assert 'embedding credential invalid' in str(exc)
|
||||
else:
|
||||
raise AssertionError('Dify indexing error must fail the local sync')
|
||||
|
||||
|
||||
def test_wait_for_document_indexing_accepts_completed_status(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
result = service.wait_for_document_indexing(
|
||||
dataset_id='dataset-001',
|
||||
document_id='document-001',
|
||||
initial_payload={'document': {'id': 'document-001', 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
# completed 是唯一可将本地同步记录写为 synced 的终态。
|
||||
assert result['indexing_status'] == 'completed'
|
||||
|
||||
|
||||
def test_remote_document_not_available_is_recreated(monkeypatch):
|
||||
"""400 invalid_param 的不可用文档错误必须触发创建新远端文档的恢复流程。"""
|
||||
error = (
|
||||
'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text '
|
||||
'failed: 400 {"code":"invalid_param","message":"Document is not available","status":400}'
|
||||
)
|
||||
|
||||
# 断言该 Dify 版本特有的 400 响应不会被当成不可恢复的同步失败。
|
||||
assert dify_sync_module._is_remote_document_missing(error) is True
|
||||
|
||||
|
||||
def test_remote_document_other_invalid_parameter_is_not_treated_as_missing():
|
||||
"""非文档失效的参数错误仍应原样失败,避免错误地重复创建文档。"""
|
||||
error = 'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text failed: 400 {"code":"invalid_param","message":"Invalid process rule","status":400}'
|
||||
|
||||
# 断言只有精确的“文档不可用”语义才走自动恢复分支。
|
||||
assert dify_sync_module._is_remote_document_missing(error) is False
|
||||
|
||||
|
||||
def test_resolve_source_file_ext_from_filename():
|
||||
class _Version:
|
||||
source_file_ext = None
|
||||
|
||||
@@ -78,6 +78,16 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen
|
||||
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
||||
|
||||
|
||||
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
||||
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
||||
message = DifyService._friendly_upstream_error_message(
|
||||
400,
|
||||
'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank',
|
||||
agent_name='通用入口',
|
||||
)
|
||||
assert message == '通用入口的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。'
|
||||
|
||||
|
||||
def test_persist_stream_chat_record_uses_workflow_finished_tokens(app):
|
||||
"""workflow_finished 首次落库应写入 data.total_tokens。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -18,6 +18,14 @@ def test_word_still_uses_word_timeout(monkeypatch):
|
||||
assert _file_timeout_sec(Path('manual.docx')) == 420
|
||||
|
||||
|
||||
def test_pdf_uses_dedicated_timeout_for_figure_rich_handbooks(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '300')
|
||||
monkeypatch.setenv('EDKB_PDF_FILE_TIMEOUT_SEC', '900')
|
||||
|
||||
# 断言大型图文手册不会被通用 300 秒时限提前终止。
|
||||
assert _file_timeout_sec(Path('mechanical-design-handbook.pdf')) == 900
|
||||
|
||||
|
||||
def test_other_formats_use_global_timeout(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
|
||||
assert _file_timeout_sec(Path('slides.pptx')) == 180
|
||||
@@ -1527,7 +1527,7 @@ def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeyp
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
|
||||
@@ -16,6 +16,13 @@ def test_supports_rejects_leave_process_questions():
|
||||
assert not HRLeaveSQLServerService.supports("年假制度是什么")
|
||||
|
||||
|
||||
def test_supports_rejects_salary_calculation_questions():
|
||||
# 断言:制度扣薪问题必须走 FAQ/Dify,不能触发 HR 假期余额查询。
|
||||
assert not HRLeaveSQLServerService.supports("请病假怎么扣钱")
|
||||
assert not HRLeaveSQLServerService.supports("请假扣多少薪资")
|
||||
assert not HRLeaveSQLServerService.supports("请假扣款计算公式")
|
||||
|
||||
|
||||
def test_supports_other_person_leave_queries_for_guardrail():
|
||||
assert HRLeaveSQLServerService.supports("张三还有多少假期")
|
||||
assert HRLeaveSQLServerService.supports("曹惠鹏还有多少假期")
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
backend/tests/test_integration_source_fallback.py
|
||||
|
||||
用途:验证源文件缺失时 integration 下载与序列化回退到清洗 Markdown。
|
||||
依赖:pytest、kb 模型与 integration 路由。
|
||||
逻辑:模拟磁盘无 source、有 cleaned md,断言 kind=source 仍可读且序列化返回 .md。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, User
|
||||
|
||||
|
||||
def _configure(app, tmp_path: Path) -> Path:
|
||||
root = tmp_path / 'kb-storage'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
app.config.update(
|
||||
SECRET_KEY='test-secret-key-with-sufficient-length-123456',
|
||||
KB_STORAGE_ROOT=str(root),
|
||||
WECOM_PUBLIC_BASE_URL='https://ai.example.com',
|
||||
INTEGRATION_API_KEY='test-integration-key',
|
||||
INTEGRATION_API_MODE='local',
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
def _ensure_admin() -> User:
|
||||
user = db.session.query(User).filter_by(username='admin').first()
|
||||
if user:
|
||||
return user
|
||||
user = User(username='admin', email='admin@example.com', role='admin', status='active')
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _seed_doc_with_missing_source(root: Path) -> tuple[KbDocument, KbDocumentVersion]:
|
||||
"""创建文档:source_file_path 指向不存在文件,cleaned md 真实存在。"""
|
||||
_ensure_admin()
|
||||
group = KbGroup(name='fallback-group', description='t', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.flush()
|
||||
|
||||
document = KbDocument(
|
||||
group_id=group.id,
|
||||
title='员工入职须知',
|
||||
status='ready',
|
||||
source_type='upload',
|
||||
is_deleted=False,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
|
||||
missing_source = root / 'docs' / 'missing-source.pdf'
|
||||
cleaned = root / 'docs' / 'cleaned.md'
|
||||
cleaned.parent.mkdir(parents=True, exist_ok=True)
|
||||
cleaned.write_text('# 入职须知\n\n欢迎加入。', encoding='utf-8')
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=1,
|
||||
status='ready',
|
||||
is_current=True,
|
||||
source_file_name='员工入职须知.pdf',
|
||||
source_file_path=str(missing_source),
|
||||
source_file_ext='pdf',
|
||||
source_file_size=12,
|
||||
sha256='abc',
|
||||
cleaned_file_path=str(cleaned),
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
sync = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id='ds-fallback',
|
||||
remote_document_id='remote-fallback',
|
||||
status='synced',
|
||||
)
|
||||
db.session.add(sync)
|
||||
db.session.commit()
|
||||
return document, version
|
||||
|
||||
|
||||
def test_download_source_falls_back_to_markdown(app, client, tmp_path):
|
||||
"""断言:kind=source 时源文件不存在,仍返回清洗 Markdown 内容。"""
|
||||
root = _configure(app, tmp_path)
|
||||
with app.app_context():
|
||||
document, version = _seed_doc_with_missing_source(root)
|
||||
document_id = document.id
|
||||
version_id = version.id
|
||||
|
||||
response = client.get(
|
||||
f'/api/integration/files/{document_id}/download',
|
||||
headers={'X-Integration-Key': 'test-integration-key'},
|
||||
query_string={'kind': 'source', 'version_id': version_id},
|
||||
)
|
||||
assert response.status_code == 200, response.get_data(as_text=True)
|
||||
body = response.get_data(as_text=True)
|
||||
assert '入职须知' in body
|
||||
assert '欢迎加入' in body
|
||||
|
||||
|
||||
def test_serialize_prefers_markdown_when_source_missing(app, client, tmp_path):
|
||||
"""断言:dify-file 在源文件缺失时返回 kind=md 与 .md 扩展名。"""
|
||||
root = _configure(app, tmp_path)
|
||||
with app.app_context():
|
||||
_seed_doc_with_missing_source(root)
|
||||
|
||||
response = client.get(
|
||||
'/api/integration/dify-file',
|
||||
headers={'X-Integration-Key': 'test-integration-key'},
|
||||
query_string={
|
||||
'dataset_id': 'ds-fallback',
|
||||
'remote_document_id': 'remote-fallback',
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
payload = response.get_json()
|
||||
assert payload['source_ext'] == 'md'
|
||||
assert str(payload['source_filename']).endswith('.md')
|
||||
assert 'kind=md' in str(payload['source_download_url'])
|
||||
@@ -115,7 +115,7 @@ def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_test_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -159,7 +159,7 @@ def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_integration_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -232,7 +232,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_old_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -252,7 +252,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_new_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
|
||||
Reference in new issue
Block a user