Files
Atrium/backend/tests/test_attachments_unit.py
T
tobayahandClaude Opus 5.5 bf46fb5724 Czat: załączniki (PDF, DOCX, TXT/MD/CSV) jako źródła pytania
POST /chat/attachments zwraca tekst pliku i niczego nie zapisuje (audyt: nazwa i rozmiar,
bez treści). PDF przez pypdf (BSD-3), DOCX biblioteką standardową z odmową DTD, tekst
UTF-8 albo cp1250. Konsola: spinacz i upuszczenie pliku na stronie głównej, etykiety
plików, każdy plik jako ponumerowane źródło (przypis [n], sprawdzanie cytatów). Tekst
przycinany do pamięci modelu (context_window z listy modeli) z uczciwym „do strony X z Y”.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqL6AphKDyHPDToUMin
2026-11-18 15:07:19 +01:00

115 lines
4.9 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""A file attached to a Home chat question: its text back, nothing stored, and the refusals by code."""
from __future__ import annotations
import io
import types
import uuid
import zipfile
import pytest
from fastapi import Request
from fastapi.testclient import TestClient
from app import deps
from app.db import get_db
from app.errors import ValidationError
from app.services import attachments, audit
def _pdf(*pages: str) -> bytes:
"""A real PDF with one text line per page (Helvetica, WinAnsi), xref offsets computed."""
objs = ["<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages)))
+ f"] /Count {len(pages)} >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"]
for i, text in enumerate(pages):
stream = f"BT /F1 12 Tf 72 720 Td ({text}) Tj ET" if text else ""
objs.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> "
f"/Contents {5 + 2 * i} 0 R >>")
objs.append(f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream")
out, offsets = io.BytesIO(), []
out.write(b"%PDF-1.4\n")
for n, body in enumerate(objs, 1):
offsets.append(out.tell())
out.write(f"{n} 0 obj\n{body}\nendobj\n".encode("latin-1"))
xref = out.tell()
out.write(f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode())
for o in offsets:
out.write(f"{o:010d} 00000 n \n".encode())
out.write(f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode())
return out.getvalue()
def _docx(xml: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("word/document.xml", xml)
return buf.getvalue()
W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
def test_a_pdf_comes_back_page_by_page():
out = attachments.extract("Umowa.PDF", _pdf("Okres wypowiedzenia 3 miesiace", "Kara umowna 10 procent"))
assert out["kind"] == "pdf" and out["pages"] == 2
assert "[strona 1]\nOkres wypowiedzenia 3 miesiace" in out["text"]
assert "[strona 2]\nKara umowna 10 procent" in out["text"]
def test_a_scan_is_refused_with_its_reason():
with pytest.raises(ValidationError) as refused:
attachments.extract("skan.pdf", _pdf("", ""))
assert refused.value.extra["code"] == "attachment_no_text"
def test_a_docx_keeps_its_paragraphs_tabs_and_breaks():
xml = (f'<w:document {W}><w:body><w:p><w:r><w:t>§ 1. Strony</w:t></w:r></w:p>'
'<w:p><w:r><w:t>Najemca</w:t><w:tab/><w:t>ABC</w:t><w:br/><w:t>sp. z o.o.</w:t></w:r></w:p></w:body></w:document>')
out = attachments.extract("najem.docx", _docx(xml))
assert out["kind"] == "docx" and out["text"] == "§ 1. Strony\nNajemca\tABC\nsp. z o.o."
def test_a_docx_with_a_dtd_is_refused_before_parsing():
bomb = f'<!DOCTYPE w [<!ENTITY a "aaaa">]><w:document {W}><w:body><w:p><w:r><w:t>&a;</w:t></w:r></w:p></w:body></w:document>'
with pytest.raises(ValidationError) as refused:
attachments.extract("bomba.docx", _docx(bomb))
assert refused.value.extra["code"] == "attachment_unreadable"
def test_plain_text_falls_back_to_windows_1250():
assert attachments.extract("notatka.txt", "Zażółć gęślą jaźń".encode("cp1250"))["text"] == "Zażółć gęślą jaźń"
assert attachments.extract("a.md", "# Tytuł".encode("utf-8"))["text"] == "# Tytuł"
@pytest.mark.parametrize(("name", "data", "code"), [
("obraz.png", b"\x89PNG\r\n", "attachment_type"),
("udaje.pdf", b"PK\x03\x04 not a pdf", "attachment_type"), # the name says PDF, the bytes do not
("binarny.txt", b"MZ\x00\x00", "attachment_type"),
("pusty.txt", b" \n", "attachment_empty"),
("duzy.txt", b"a" * (attachments.MAX_BYTES + 1), "attachment_too_large"),
])
def test_refusals_carry_a_code(name, data, code):
with pytest.raises(ValidationError) as refused:
attachments.extract(name, data)
assert refused.value.extra["code"] == code and refused.value.extra["en"]
def test_the_route_returns_the_text_and_audits_only_the_name(monkeypatch):
from app.main import app
audited = []
monkeypatch.setattr(audit, "record", lambda *a, **k: audited.append(k))
def signed_in(request: Request):
request.state.credential_id, request.state.credential_kind = uuid.uuid4(), "session"
return types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
app.dependency_overrides[deps.get_current_user] = signed_in
app.dependency_overrides[get_db] = lambda: types.SimpleNamespace(commit=lambda: None)
try:
r = TestClient(app).post("/api/v1/chat/attachments?name=tajne.txt", content="Treść poufna".encode())
finally:
app.dependency_overrides.clear()
assert r.status_code == 200 and r.json()["text"] == "Treść poufna"
assert audited[0]["detail"] == "tajne.txt" and "Treść" not in repr(audited)