Files
vector/backend/tests/test_parse_doc_api.py
T
2026-06-06 20:59:23 +00:00

74 lines
3.0 KiB
Python

from io import BytesIO
import zipfile
from backend.main import app
from fastapi.testclient import TestClient
client = TestClient(app)
def build_docx(paragraphs: list[str]) -> BytesIO:
document_xml = """<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
{paras}
<w:sectPr>
<w:pgSz w:w="11906" w:h="16838"/>
<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>
</w:sectPr>
</w:body>
</w:document>
"""
paras = "\n".join(f"<w:p><w:r><w:t>{paragraph}</w:t></w:r></w:p>" for paragraph in paragraphs)
buffer = BytesIO()
with zipfile.ZipFile(buffer, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
archive.writestr('[Content_Types].xml', """<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>
""")
archive.writestr('_rels/.rels', """<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>
""")
archive.writestr('word/document.xml', document_xml.format(paras=paras))
buffer.seek(0)
buffer.name = 'sample-report.docx'
return buffer
def test_admin_parse_doc_extracts_case_preview_from_docx() -> None:
file_obj = build_docx([
'Case ID: 124',
'Age: 16',
'Gender: female',
'Status: analyzed',
'Found alive: yes',
'Found distance km: 3.5',
'Who found: Search team 4',
'Notes: Found near the logging road',
])
response = client.post(
'/api/v1/admin/parse-doc',
files={'file': ('sample-report.docx', file_obj, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')},
)
assert response.status_code == 200
payload = response.json()
assert payload['parsed'] is True
assert payload['filename'] == 'sample-report.docx'
assert payload['preview']['case_id'] == '124'
assert payload['preview']['case']['age'] == 16
assert payload['preview']['case']['gender'] == 'female'
assert payload['preview']['case']['status'] == 'analyzed'
assert payload['preview']['case']['found_alive'] is True
assert payload['preview']['case']['found_distance_km'] == 3.5
assert payload['preview']['case']['who_found'] == 'Search team 4'
assert payload['preview']['case']['notes'] == 'Found near the logging road'
assert 'Case ID: 124' in payload['raw_text']