feat(插件): 读取附件正文并保留日志文本
新增附件读取测试插件并配置上传路径,记录文件名、提取状态及正文。所有插件日志保留参数和级别,按字节限制截断并转义换行,补充运行时和附件集成测试。
This commit is contained in:
1 parent
4e0d46ff5f
commit
016c43f13e
9 files changed
+174
-9
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from docx import Document
|
||||
from test_attachments import backend, multipart_request
|
||||
from test_proxy import client_for
|
||||
|
||||
from middleware.config import PluginConfig, Settings
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extension", ["txt", "docx", "pdf"])
|
||||
async def test_file_read_log_records_extracted_text_and_forwards_original(extension, caplog):
|
||||
caplog.set_level("INFO", logger="middleware.audit")
|
||||
text = "附件中文正文\n第二行 100%"
|
||||
if extension == "docx":
|
||||
document = Document()
|
||||
document.add_paragraph(text)
|
||||
output = io.BytesIO()
|
||||
document.save(output)
|
||||
content = output.getvalue()
|
||||
elif extension == "pdf":
|
||||
content = b"%PDF-unsupported"
|
||||
else:
|
||||
content = text.encode("utf-8")
|
||||
received = []
|
||||
|
||||
async def handler(request):
|
||||
received.append(await request.read())
|
||||
return web.json_response({"stored": True})
|
||||
|
||||
plugin = PluginConfig(
|
||||
id="file-read-log",
|
||||
file=Path(__file__).resolve().parents[1] / "plugins" / "file_read_log.lua",
|
||||
match={"paths": ["/upload"]},
|
||||
)
|
||||
raw, headers = multipart_request([("file", (f"sample.{extension}", content))])
|
||||
async with backend(handler) as upstream:
|
||||
async with client_for(Settings(upstream=upstream, plugins=[plugin])) as (client, app):
|
||||
response = await client.post("/upload?x=a%2Fb", content=raw, headers=headers)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"stored": True}
|
||||
assert app.state.active_uploads == 0
|
||||
before = len([r for r in caplog.records if r.getMessage().startswith("plugin_log ")])
|
||||
assert (await client.post("/upload", json={"message": "普通请求"})).status_code == 200
|
||||
records = [r.getMessage() for r in caplog.records if r.getMessage().startswith("plugin_log ")]
|
||||
assert len(records) == before == 1
|
||||
assert "plugin=file-read-log" in records[0]
|
||||
assert "truncated=False" in records[0]
|
||||
logged = json.loads(json.loads(records[0].split(" message=", 1)[1]))
|
||||
expected_text = "" if extension == "pdf" else text + ("\n" if extension == "docx" else "")
|
||||
assert logged == {
|
||||
"name": f"sample.{extension}",
|
||||
"extraction_status": "unsupported" if extension == "pdf" else "complete",
|
||||
"text_bytes": len(expected_text.encode("utf-8")),
|
||||
"text": expected_text,
|
||||
}
|
||||
assert received[0] == raw
|
||||
Reference in new issue
Block a user