Files
syops/backend/tests/test_kb_migration_flow.py
2026-05-12 08:16:42 +08:00

401 lines
15 KiB
Python

import io
from pathlib import Path
from app import db
from app.auth_jwt import issue_local_access_token
from app.models import KbDocument, KbDifySyncRecord, User
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
from app.services.knowledge_cleaning import tasks as kb_tasks_module
def _configure_app(app, tmp_path):
app.config.update(
SECRET_KEY='test-secret-key-with-sufficient-length-123456',
KB_STORAGE_ROOT=str(tmp_path / 'kb-storage'),
WECOM_PUBLIC_BASE_URL='https://ai.example.com',
INTEGRATION_API_KEY='test-integration-key',
INTEGRATION_API_MODE='local',
)
def _ensure_user(username: str, role: str) -> User:
user = db.session.query(User).filter_by(username=username).first()
if user:
return user
user = User(
username=username,
email=f'{username}@example.com',
role=role,
status='active',
)
user.set_password('password123')
db.session.add(user)
db.session.commit()
return user
def _auth_headers_for(app, username: str) -> dict[str, str]:
with app.app_context():
user = db.session.query(User).filter_by(username=username).first()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
}
def _create_group(client, headers: dict[str, str], *, name: str) -> int:
response = client.post(
'/api/kb/groups',
json={'name': name, 'description': 'test group'},
headers=headers,
)
assert response.status_code == 201, response.get_json()
return response.get_json()['id']
def _create_document(client, headers: dict[str, str], group_id: int, *, title: str) -> int:
response = client.post(
f'/api/kb/groups/{group_id}/files',
json={'title': title, 'description': 'test doc'},
headers=headers,
)
assert response.status_code == 201, response.get_json()
return response.get_json()['id']
def _upload_document(client, headers: dict[str, str], document_id: int, *, content: str, filename: str):
response = client.post(
f'/api/kb/documents/{document_id}/upload',
headers=headers,
data={'file': (io.BytesIO(content.encode('utf-8')), filename)},
content_type='multipart/form-data',
)
assert response.status_code == 201, response.get_json()
return response.get_json()
def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path):
_configure_app(app, tmp_path)
with app.app_context():
_ensure_user('admin', 'admin')
admin_headers = _auth_headers_for(app, 'admin')
group_id = _create_group(client, admin_headers, name='知识库测试分组')
document_id = _create_document(client, admin_headers, group_id, title='员工手册')
version_payload = _upload_document(
client,
admin_headers,
document_id,
content='第一行\n第二行\n第三行',
filename='employee-handbook.txt',
)
assert version_payload['version_no'] == 1
assert version_payload['status'] == 'cleaned'
assert version_payload['source_file_name'] == 'employee-handbook.txt'
groups_response = client.get('/api/kb/groups', headers=admin_headers)
assert groups_response.status_code == 200
groups_payload = groups_response.get_json()
assert groups_payload[0]['document_count'] == 1
documents_response = client.get(f'/api/kb/groups/{group_id}/files', headers=admin_headers)
assert documents_response.status_code == 200
documents_payload = documents_response.get_json()
assert len(documents_payload) == 1
assert documents_payload[0]['latest_version']['status'] == 'cleaned'
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'ensure_dataset',
lambda self, group: ('ds_test_001', 'Test Dataset'),
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'create_document_by_text',
lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}},
)
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
assert sync_response.status_code == 200, sync_response.get_json()
sync_job_payload = sync_response.get_json()
assert sync_job_payload['job_type'] == 'sync_dify'
assert sync_job_payload['status'] == 'success'
sync_records_response = client.get(f'/api/kb/documents/{document_id}/sync-records', headers=admin_headers)
assert sync_records_response.status_code == 200
sync_records_payload = sync_records_response.get_json()
assert len(sync_records_payload) == 1
assert sync_records_payload[0]['dataset_id'] == 'ds_test_001'
assert sync_records_payload[0]['remote_document_id'] == 'doc_test_001'
def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_path):
_configure_app(app, tmp_path)
with app.app_context():
_ensure_user('admin', 'admin')
admin_headers = _auth_headers_for(app, 'admin')
integration_headers = {'X-Integration-Key': app.config['INTEGRATION_API_KEY']}
group_id = _create_group(client, admin_headers, name='集成测试分组')
document_id = _create_document(client, admin_headers, group_id, title='集成文件')
_upload_document(
client,
admin_headers,
document_id,
content='integration file content',
filename='integration-source.txt',
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'ensure_dataset',
lambda self, group: ('ds_integration_001', 'Integration Dataset'),
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'create_document_by_text',
lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}},
)
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
assert sync_response.status_code == 200, sync_response.get_json()
dify_file_response = client.get(
'/api/integration/dify-file',
headers=integration_headers,
query_string={
'dataset_id': 'ds_integration_001',
'remote_document_id': 'doc_integration_001',
},
)
assert dify_file_response.status_code == 200
dify_file_payload = dify_file_response.get_json()
assert dify_file_payload['document_id'] == document_id
assert dify_file_payload['source_filename'] == 'integration-source.txt'
assert dify_file_payload['source_download_url'].endswith(
f'/api/integration/files/{document_id}/download?kind=source'
)
resolve_response = client.post(
'/api/integration/dify-files/resolve',
headers=integration_headers,
json={'items': [{'dataset_id': 'ds_integration_001', 'remote_document_id': 'doc_integration_001'}]},
)
assert resolve_response.status_code == 200
resolve_payload = resolve_response.get_json()['data']
assert len(resolve_payload) == 1
assert resolve_payload[0]['found'] is True
assert resolve_payload[0]['document']['document_id'] == document_id
download_response = client.get(
f'/api/integration/files/{document_id}/download',
headers=integration_headers,
query_string={'kind': 'source'},
)
assert download_response.status_code == 200
assert download_response.data == b'integration file content'
with app.app_context():
document = db.session.get(KbDocument, document_id)
assert document is not None
assert db.session.query(KbDifySyncRecord).filter_by(document_id=document_id).count() == 1
def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monkeypatch, tmp_path):
_configure_app(app, tmp_path)
with app.app_context():
_ensure_user('admin', 'admin')
admin_headers = _auth_headers_for(app, 'admin')
group_id = _create_group(client, admin_headers, name='同步补偿分组')
document_id = _create_document(client, admin_headers, group_id, title='同步补偿文档')
_upload_document(
client,
admin_headers,
document_id,
content='same content for repeated sync',
filename='sync-recreate.txt',
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'ensure_dataset',
lambda self, group: ('ds_recreate_001', 'Recreate Dataset'),
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'create_document_by_text',
lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}},
)
first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
assert first_sync_response.status_code == 200, first_sync_response.get_json()
def _missing_remote_document(self, *, dataset_id: str, document_id: str):
raise dify_sync_module.KbDifySyncError(
'Dify API GET /datasets/ds_recreate_001/documents/doc_old_001 failed: '
'404 {"code":"not_found","message":"Document not found."}'
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'get_document',
_missing_remote_document,
)
monkeypatch.setattr(
dify_sync_module.KbDifySyncService,
'create_document_by_text',
lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}},
)
second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
assert second_sync_response.status_code == 200, second_sync_response.get_json()
with app.app_context():
records = (
db.session.query(KbDifySyncRecord)
.filter_by(document_id=document_id)
.order_by(KbDifySyncRecord.id.asc())
.all()
)
assert len(records) == 2
assert records[0].remote_document_id == 'doc_old_001'
assert records[1].remote_document_id == 'doc_new_001'
assert records[1].status == 'synced'
def test_document_markdown_can_be_viewed_and_saved(app, client, tmp_path):
_configure_app(app, tmp_path)
with app.app_context():
_ensure_user('admin', 'admin')
admin_headers = _auth_headers_for(app, 'admin')
group_id = _create_group(client, admin_headers, name='Markdown 编辑分组')
document_id = _create_document(client, admin_headers, group_id, title='Markdown 编辑文档')
_upload_document(
client,
admin_headers,
document_id,
content='第一行\n第二行\n第三行',
filename='editable.txt',
)
read_response = client.get(f'/api/kb/documents/{document_id}/markdown', headers=admin_headers)
assert read_response.status_code == 200, read_response.get_json()
read_payload = read_response.get_json()
assert read_payload['kind'] == 'markdown'
assert '第二行' in read_payload['content']
updated_content = '# 手工修订\n\n这是一段修改后的 Markdown。'
save_response = client.patch(
f'/api/kb/documents/{document_id}/markdown',
headers=admin_headers,
json={'content': updated_content},
)
assert save_response.status_code == 200, save_response.get_json()
save_payload = save_response.get_json()
assert save_payload['content'] == updated_content
assert save_payload['version']['cleaned_file_path'].endswith('document.md')
with app.app_context():
document = db.session.get(KbDocument, document_id)
version = next(item for item in document.versions if item.is_current)
markdown_path = Path(version.cleaned_file_path)
assert markdown_path.exists()
assert markdown_path.read_text(encoding='utf-8') == updated_content
def test_document_markdown_save_upgrades_preview_to_markdown(app, client, monkeypatch, tmp_path):
_configure_app(app, tmp_path)
with app.app_context():
_ensure_user('admin', 'admin')
admin_headers = _auth_headers_for(app, 'admin')
group_id = _create_group(client, admin_headers, name='Preview 编辑分组')
document_id = _create_document(client, admin_headers, group_id, title='Preview 编辑文档')
def _raise_build_clean_result(source_path, target_dir):
raise RuntimeError('forced preview fallback')
monkeypatch.setattr(kb_tasks_module, 'build_clean_result', _raise_build_clean_result)
_upload_document(
client,
admin_headers,
document_id,
content='原始文本内容',
filename='preview-source.txt',
)
read_response = client.get(f'/api/kb/documents/{document_id}/markdown', headers=admin_headers)
assert read_response.status_code == 200, read_response.get_json()
read_payload = read_response.get_json()
assert read_payload['kind'] == 'preview'
assert 'forced preview fallback' in read_payload['content']
updated_content = '# 兜底转正\n\n预览文件已改为正式 Markdown。'
save_response = client.patch(
f'/api/kb/documents/{document_id}/markdown',
headers=admin_headers,
json={'content': updated_content},
)
assert save_response.status_code == 200, save_response.get_json()
save_payload = save_response.get_json()
assert save_payload['kind'] == 'markdown'
with app.app_context():
document = db.session.get(KbDocument, document_id)
version = next(item for item in document.versions if item.is_current)
assert version.cleaned_file_path is not None
assert version.cleaned_file_path.endswith('document.md')
assert version.cleaned_preview_path == version.cleaned_file_path
markdown_path = Path(version.cleaned_file_path)
assert markdown_path.exists()
assert markdown_path.read_text(encoding='utf-8') == updated_content
def test_upload_preserves_excel_extension_for_non_ascii_filename(app, client, monkeypatch, tmp_path):
_configure_app(app, tmp_path)
with app.app_context():
_ensure_user('admin', 'admin')
admin_headers = _auth_headers_for(app, 'admin')
group_id = _create_group(client, admin_headers, name='中文文件名分组')
document_id = _create_document(client, admin_headers, group_id, title='中文 Excel 文档')
captured = {}
def _fake_build_clean_result(source_path, target_dir):
captured['source_name'] = source_path.name
cleaned_path = target_dir / 'document.md'
cleaned_path.write_text('# ok', encoding='utf-8')
return {
'mode': 'edkb_system',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(cleaned_path),
'word_count': 1,
}
monkeypatch.setattr(kb_tasks_module, 'build_clean_result', _fake_build_clean_result)
version_payload = _upload_document(
client,
admin_headers,
document_id,
content='fake excel bytes',
filename='能源管理体系文件清单.xlsx',
)
assert version_payload['source_file_name'].endswith('.xlsx')
assert captured['source_name'].endswith('.xlsx')