239 lines
9.2 KiB
Python
239 lines
9.2 KiB
Python
"""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
|
|
|
|
|
|
def _make_service(monkeypatch, **overrides):
|
|
settings = {
|
|
'DIFY_API_BASE': 'http://dify.example/v1',
|
|
'DIFY_API_KEY': 'dataset-test-key',
|
|
'KB_DIFY_PERMISSION': 'only_me',
|
|
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
|
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
|
|
'KB_DIFY_DOC_FORM': 'text_model',
|
|
'KB_DIFY_RERANKING_ENABLE': 'true',
|
|
'KB_DIFY_TOP_K': '5',
|
|
'KB_DIFY_SCORE_THRESHOLD_ENABLED': 'true',
|
|
'KB_DIFY_SCORE_THRESHOLD': '0.25',
|
|
'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': '600',
|
|
'KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL': '1200',
|
|
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
|
|
'KB_DIFY_REMOVE_URLS': 'false',
|
|
}
|
|
settings.update(overrides)
|
|
monkeypatch.setattr(dify_sync_module, 'get_kb_dify_settings', lambda: settings)
|
|
return dify_sync_module.KbDifySyncService()
|
|
|
|
|
|
def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
|
|
service = _make_service(monkeypatch)
|
|
rule = service._build_process_rule('xlsx')
|
|
|
|
assert rule['mode'] == 'custom'
|
|
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
|
# 断言完整行仍由空行隔开,避免表格字段在 Dify 中被拆散。
|
|
# Excel 使用独立上限,允许一个 Segment 容纳更多完整表格行。
|
|
assert rule['rules']['segmentation']['max_tokens'] == 1200
|
|
assert rule['rules']['segmentation']['chunk_overlap'] == 100
|
|
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
|
|
|
|
|
|
def test_build_process_rule_docx_uses_custom_semantic_blocks(monkeypatch):
|
|
service = _make_service(monkeypatch)
|
|
rule = service._build_process_rule('docx')
|
|
# 断言制度类文档的标题、规则、例外条件保留在同一个检索片段中。
|
|
assert rule['mode'] == 'custom'
|
|
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
|
|
|
|
|
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
|
service = _make_service(monkeypatch)
|
|
captured: dict = {}
|
|
|
|
def fake_request(method, path, **kwargs):
|
|
captured['method'] = method
|
|
captured['path'] = path
|
|
captured['json'] = kwargs.get('json')
|
|
return {'document': {'id': 'doc-1', 'name': 'demo.xlsx'}}
|
|
|
|
monkeypatch.setattr(service, '_request', fake_request)
|
|
service.create_document_by_text(
|
|
dataset_id='ds-1',
|
|
name='demo.xlsx',
|
|
text='row one\n\nrow two',
|
|
source_ext='xlsx',
|
|
)
|
|
|
|
assert captured['method'] == 'POST'
|
|
assert captured['path'] == '/datasets/ds-1/document/create-by-text'
|
|
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'] == 1200
|
|
|
|
|
|
def test_build_process_rule_uses_configured_segment_limits(monkeypatch):
|
|
service = _make_service(
|
|
monkeypatch,
|
|
KB_DIFY_SEGMENT_MAX_TOKENS='900',
|
|
KB_DIFY_SEGMENT_CHUNK_OVERLAP='150',
|
|
)
|
|
rule = service._build_process_rule('docx')
|
|
|
|
# 断言管理端保存的分段参数会透传给 Dify 文档同步的自定义分段规则。
|
|
assert rule['rules']['segmentation'] == {
|
|
'separator': '\n\n',
|
|
'max_tokens': 900,
|
|
'chunk_overlap': 150,
|
|
}
|
|
|
|
|
|
def test_build_process_rule_keeps_excel_limit_separate_from_documents(monkeypatch):
|
|
service = _make_service(
|
|
monkeypatch,
|
|
KB_DIFY_SEGMENT_MAX_TOKENS='900',
|
|
KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL='1500',
|
|
)
|
|
|
|
# 普通文档仍使用普通配置,Excel 才使用 Excel 专用配置。
|
|
assert service._build_process_rule('docx')['rules']['segmentation']['max_tokens'] == 900
|
|
assert service._build_process_rule('xlsx')['rules']['segmentation']['max_tokens'] == 1500
|
|
|
|
|
|
def test_create_dataset_uses_admin_retrieval_settings(monkeypatch):
|
|
service = _make_service(
|
|
monkeypatch,
|
|
KB_DIFY_RERANKING_ENABLE='true',
|
|
KB_DIFY_TOP_K='8',
|
|
KB_DIFY_SCORE_THRESHOLD_ENABLED='false',
|
|
KB_DIFY_SCORE_THRESHOLD='0.45',
|
|
)
|
|
captured: dict = {}
|
|
|
|
def fake_request(method, path, **kwargs):
|
|
captured['method'] = method
|
|
captured['path'] = path
|
|
captured['json'] = kwargs.get('json')
|
|
return {'id': 'dataset-1', 'name': 'demo'}
|
|
|
|
monkeypatch.setattr(service, '_request', fake_request)
|
|
service.create_dataset(name='demo', description=None)
|
|
|
|
# 断言管理端保存的检索模型参数原样传给新建 Dataset,而不是继续使用代码常量。
|
|
retrieval_model = captured['json']['retrieval_model']
|
|
assert captured['method'] == 'POST'
|
|
assert captured['path'] == '/datasets'
|
|
assert retrieval_model == {
|
|
'search_method': 'hybrid_search',
|
|
'reranking_enable': True,
|
|
'top_k': 8,
|
|
'score_threshold_enabled': False,
|
|
'score_threshold': 0.45,
|
|
}
|
|
|
|
|
|
def test_create_dataset_clamps_legacy_top_k_to_ten(monkeypatch):
|
|
service = _make_service(monkeypatch, KB_DIFY_TOP_K='17')
|
|
captured: dict = {}
|
|
|
|
def fake_request(method, path, **kwargs):
|
|
captured['json'] = kwargs.get('json')
|
|
return {'id': 'dataset-1', 'name': 'demo'}
|
|
|
|
monkeypatch.setattr(service, '_request', fake_request)
|
|
service.create_dataset(name='demo', description=None)
|
|
|
|
# 断言历史配置即使仍为旧上限 20 内的值,也不会向 Dify 发送超过新上限 10 的 Top K。
|
|
assert captured['json']['retrieval_model']['top_k'] == 10
|
|
|
|
|
|
def test_retrieve_dataset_uses_reranking_default(monkeypatch):
|
|
service = _make_service(monkeypatch, KB_DIFY_RERANKING_ENABLE='true')
|
|
captured: dict = {}
|
|
|
|
def fake_request(method, path, **kwargs):
|
|
captured['json'] = kwargs.get('json')
|
|
return {'records': []}
|
|
|
|
monkeypatch.setattr(service, '_request', fake_request)
|
|
service.retrieve_dataset(dataset_id='dataset-1', query='历史报告')
|
|
|
|
# 断言历史检索请求也沿用管理端的默认重排序开关。
|
|
assert captured['json']['retrieval_model']['reranking_enable'] is True
|
|
|
|
|
|
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
|
service = _make_service(monkeypatch, KB_DIFY_REMOVE_URLS='true')
|
|
rule = service._build_process_rule('csv')
|
|
remove_urls = next(
|
|
item for item in rule['rules']['pre_processing_rules']
|
|
if item['id'] == 'remove_urls_emails'
|
|
)
|
|
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
|
|
source_file_name = 'report.XLSX'
|
|
|
|
assert dify_sync_module.resolve_source_file_ext(_Version()) == 'xlsx'
|