"""Tests for Dify sync process_rule selection (Excel custom vs default automatic).""" 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': 'semantic_search', 'KB_DIFY_DOC_FORM': 'text_model', 'KB_DIFY_PROCESS_MODE': 'automatic', '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_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' assert rule['rules']['segmentation']['max_tokens'] == 800 assert rule['rules']['segmentation']['chunk_overlap'] == 50 assert rule['rules']['pre_processing_rules'][1]['enabled'] is False def test_build_process_rule_docx_defaults_to_automatic(monkeypatch): service = _make_service(monkeypatch) rule = service._build_process_rule('docx') assert rule == {'mode': 'automatic'} 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'] == 800 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_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'