"""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_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_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 中被拆散。 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_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'] == 600 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'