""" 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'])