""" tests/test_kb_source_file_download.py 用途:知识库源文件下载的 Content-Disposition 与中文文件名。 依赖:kb.common.build_content_disposition、documents 路由、kb 模型。 逻辑:纯函数校验 RFC 5987 头;API 用例确认 ?download=1 返回原名且正文为原件。 """ from pathlib import Path from urllib.parse import quote from app import db from app.api.kb.common import build_content_disposition from app.core.auth.jwt import issue_local_access_token from app.models import KbDocument, KbDocumentVersion, KbGroup, User def test_build_content_disposition_quotes_ascii_and_keeps_utf8_filename(): """ ASCII 回退名必须加引号,真实中文名在 filename* 段。 关键断言:不得出现无引号的 `filename=docx; filename*=...`,否则浏览器会把两段拼成怪名。 """ filename = '企业文化.docx' header = build_content_disposition(filename, as_attachment=True) assert header.startswith('attachment; filename="download.docx"; filename*=UTF-8\'\'') assert quote(filename, safe='') in header assert 'filename=docx;' not in header def test_source_file_download_uses_original_filename(app, client, tmp_path): """ 工作台源文件下载应以下载附件返回,且 Content-Disposition 含原始中文文件名。 关键断言:响应体是原件字节;filename* 为 企业文化.docx;ASCII 回退名带引号。 """ storage_root = tmp_path / 'kb-storage' storage_root.mkdir() source_name = '企业文化.docx' source_path = storage_root / 'corp-culture.docx' source_bytes = b'PK\x03\x04fake-docx' source_path.write_bytes(source_bytes) app.config['KB_STORAGE_ROOT'] = str(storage_root) with app.app_context(): user = User( username='kb-download-admin', email='kb-download-admin@example.com', role='admin', status='active', ) user.set_password('password123') group = KbGroup(name='源文件下载分组') document = KbDocument(group=group, title='企业文化', status='uploaded') version = KbDocumentVersion( document=document, version_no=1, status='uploaded', is_current=True, source_file_name=source_name, source_file_path=str(source_path), source_file_ext='docx', source_file_size=len(source_bytes), ) db.session.add_all([user, group, document, version]) db.session.commit() version_id = version.id token = issue_local_access_token(user) res = client.get( f'/api/kb/document-versions/{version_id}/source-file?download=1', headers={'Authorization': f'Bearer {token}'}, ) assert res.status_code == 200 assert res.data == source_bytes disposition = res.headers.get('Content-Disposition', '') assert 'attachment' in disposition assert f'filename*=UTF-8\'\'{quote(source_name, safe="")}' in disposition assert 'filename="download.docx"' in disposition assert 'filename=docx;' not in disposition