61 lines
2.4 KiB
Python
61 lines
2.4 KiB
Python
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
|