2808f955c4
Adapted from Angel Capetillo Zavala commit 4934f99. Roboto notices are included; institutional logo authorization remains pending.
140 lines
5.8 KiB
Python
140 lines
5.8 KiB
Python
"""CaCu's PDF and Excel exports: what the WebApp sends already formatted is laid out, never
|
|
computed; limits are enforced; every cell is text (nothing becomes a formula); a long query
|
|
runs over several pages with the institutional frame on each; absent values stay absent."""
|
|
|
|
import re
|
|
from io import BytesIO
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
from openpyxl import load_workbook
|
|
|
|
from webapi import exports, pdf_report
|
|
|
|
COLUMNS = ["Paciente", "Edad", "Estatus", "Etapas", "Última citología", "VPH", "Biopsia",
|
|
"Riesgo", "Riesgo cáncer", "Días a diagnóstico"] # fmt: skip
|
|
STAGES = [
|
|
{"state": "Registrada", "date": "2026-11-01"},
|
|
{"state": "Desconocida"},
|
|
{"state": "Pendiente"},
|
|
{"state": "Ambigua"},
|
|
{"state": "Registrada", "date": "2026-11-09", "provenance": "Inferida temporalmente"},
|
|
]
|
|
|
|
|
|
def pages(pdf: bytes) -> int:
|
|
return len(re.findall(rb"/Type\s*/Page\b", pdf))
|
|
|
|
|
|
def listing(n: int, **extra) -> exports.Document:
|
|
rows = [[f"Paciente {i}\nCURP{i}", "40", "Precolposcopia", "x", "—", "—", "—",
|
|
"No disponible", "0.0 %", "—"] for i in range(n)] # fmt: skip
|
|
return exports.Document(
|
|
title="Resultados de seguimiento",
|
|
parameters=[["Fecha de corte", "2026-11-22"]],
|
|
columns=COLUMNS,
|
|
rows=rows,
|
|
row_stages=[STAGES] * n,
|
|
**extra,
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
app = FastAPI()
|
|
app.include_router(exports.router)
|
|
return TestClient(app)
|
|
|
|
|
|
def test_the_assets_ship_with_the_package():
|
|
for name in ("isssteleon-logo.png", "fonts/Roboto-Regular.ttf", "fonts/Roboto-Medium.ttf",
|
|
"fonts/Roboto-Italic.ttf", "fonts/Roboto-MediumItalic.ttf",
|
|
"fonts/LICENSE-Roboto-OFL.txt"): # fmt: skip
|
|
assert (pdf_report.ASSETS / name).is_file(), name
|
|
|
|
|
|
def test_the_limits_are_published(client):
|
|
assert client.get("/cacu/exports/capabilities").json() == {
|
|
"xlsx_limit": 5000, "pdf_limit": 1000, "version": 1} # fmt: skip
|
|
|
|
|
|
def test_excel_cells_are_text_so_nothing_runs_as_a_formula():
|
|
doc = exports.Document(title="x", parameters=[["Filtro", "=1+1"]], columns=["=2+2"],
|
|
rows=[["=1+1"], ["+cmd"], ["@SUM(A1)"]]) # fmt: skip
|
|
book = load_workbook(BytesIO(exports.export("xlsx", doc).body))
|
|
assert book.sheetnames == ["Resultados", "Parámetros"]
|
|
cells = [book["Resultados"]["A1"], book["Resultados"]["A2"], book["Resultados"]["A4"],
|
|
book["Parámetros"]["B2"]] # fmt: skip
|
|
assert {c.data_type for c in cells} == {"s"}
|
|
assert book["Resultados"]["A2"].value == "=1+1"
|
|
|
|
|
|
def test_excel_keeps_every_row_of_the_query_up_to_its_limit():
|
|
doc = listing(5000).model_copy(update={"row_stages": []})
|
|
sheet = load_workbook(BytesIO(exports.export("xlsx", doc).body))["Resultados"]
|
|
assert sheet.max_row == 5001 # the header and every patient
|
|
with pytest.raises(ValueError): # the model itself refuses more
|
|
exports.Document.model_validate({**doc.model_dump(), "rows": doc.rows + [doc.rows[0]]})
|
|
|
|
|
|
def test_pdf_stops_at_a_thousand_records_and_columns_must_agree():
|
|
too_many = exports.Document(title="x", parameters=[], columns=["a"], rows=[["x"]] * 1001)
|
|
with pytest.raises(exports.HTTPException) as caught:
|
|
exports.export("pdf", too_many)
|
|
assert caught.value.status_code == 422
|
|
with pytest.raises(exports.HTTPException):
|
|
exports.export("xlsx", exports.Document(title="x", parameters=[], columns=["a"],
|
|
rows=[["x", "y"]])) # fmt: skip
|
|
with pytest.raises(exports.HTTPException) as unknown:
|
|
exports.export("docx", too_many)
|
|
assert unknown.value.status_code == 404
|
|
|
|
|
|
def test_a_long_listing_runs_over_several_pages_and_keeps_its_rows_and_stages():
|
|
body = exports.export("pdf", listing(120)).body
|
|
assert body.startswith(b"%PDF")
|
|
assert pages(body) > 4
|
|
short = exports.export("pdf", listing(2)).body
|
|
assert pages(short) < pages(body)
|
|
with pytest.raises(exports.HTTPException): # one stage line per row, or none
|
|
exports.export("pdf", listing(5).model_copy(update={"row_stages": [STAGES] * 3}))
|
|
|
|
|
|
def test_a_listing_with_nothing_found_and_with_absent_values_still_renders():
|
|
empty = exports.Document(title="Resultados de seguimiento", parameters=[], columns=COLUMNS,
|
|
rows=[]) # fmt: skip
|
|
assert exports.export("pdf", empty).body.startswith(b"%PDF")
|
|
blank = listing(3).model_copy(update={"row_stages": [[{}] * 5] * 3})
|
|
assert exports.export("pdf", blank).body.startswith(b"%PDF")
|
|
|
|
|
|
def test_the_record_pdf_draws_extreme_and_absent_risks():
|
|
scales = [
|
|
{"label": "a", "value": v, "outcome": "Cáncer", "model": "M", "horizon": "Inmediato"}
|
|
for v in (0, 0.02, 0.5, 0.98, 1)
|
|
]
|
|
scales.append({"label": "Riesgo a 5 años: No disponible"})
|
|
doc = exports.Document(
|
|
title="Ficha individual",
|
|
parameters=[],
|
|
columns=["Sección", "Información"],
|
|
rows=[
|
|
["Identificador", "1"],
|
|
["Historial", "2026-01-01 · Diagnóstico · " + "texto " * 300],
|
|
],
|
|
timeline=[{"state": "Registrada", "label": "Toma de muestra", "date": "2026-01-01"}] * 5,
|
|
risk_scales=scales,
|
|
)
|
|
assert exports.export("pdf", doc).body.startswith(b"%PDF")
|
|
|
|
|
|
def test_the_http_route_returns_the_documents(client):
|
|
payload = listing(3).model_dump()
|
|
pdf = client.post("/cacu/exports/pdf", json=payload)
|
|
assert pdf.status_code == 200 and pdf.headers["content-type"] == "application/pdf"
|
|
xlsx = client.post("/cacu/exports/xlsx", json=payload)
|
|
assert xlsx.status_code == 200 and "spreadsheetml" in xlsx.headers["content-type"]
|
|
assert client.post("/cacu/exports/csv", json=payload).status_code == 404
|
|
assert client.post("/cacu/exports/pdf", json={**payload, "columns": []}).status_code == 422
|