"""End-to-end tests (Flask test client, SQLite) of how a batch fills the database from several sources: strict catalogs, upserts that keep unmapped columns, defaults, atomic batches, itemized conflicts, and 400s for malformed requests.""" import base64 import io import json import openpyxl import pytest @pytest.fixture(scope="module") def client(wire_domain): wire_domain("cacu") from webapi import create_app app = create_app() app.config.update(TESTING=True) with app.test_client() as test_client: yield test_client def _b64(raw: bytes) -> str: return base64.b64encode(raw).decode() def _csv(text: str, mapping: dict, *, target="cacu.Paciente", **extra) -> dict: return {"source_type": "csv", "target": target, "column_mapping": mapping, "payload": {"file_base64": _b64(text.encode())}, **extra} def _rows(client, target): return {r["pac_id_hospital"]: r for r in client.get(f"/data/{target}?limit=500").get_json()["rows"]} def test_catalog_values_are_enforced_and_aliases_resolved(client): source = _csv( "exp,sexo,dep,nac\nCAT-1,f,calles y caminos,1990-01-01\nCAT-2,GARBAGE,,1990-01-01\nCAT-3,Masculino,SECRETARIA DE SALUD,1990-01-01\n", {"exp": "pac_id_hospital", "sexo": "pac_sexo", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"}, ) body = client.post("/imports/validate", json={"source": source}).get_json() assert body["valid_count"] == 2 assert [(e["row_index"], e["field"], e["category"], e["raw_value"]) for e in body["errors"]] == [ (1, "pac_sexo", "out_of_catalog", "GARBAGE") ] client.post("/imports/commit", json={"sources": [source]}) rows = _rows(client, "cacu.Paciente") assert rows["CAT-1"]["pac_sexo"] == "Femenino" assert rows["CAT-1"]["pac_dependencia"] == "CALLES Y CAMINOS" # alias normalized # Dependencia is a tentative catalog in Core, so unknown values are kept. assert rows["CAT-3"]["pac_dependencia"] == "SECRETARIA DE SALUD" def test_postal_codes_keep_leading_zeros_and_are_validated(client): source = _csv( "exp,cp,nac\nCP-1,01000,1990-01-01\nCP-2,6400,1990-01-01\nCP-3,64000a,1990-01-01\n", {"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"}, ) body = client.post("/imports/commit", json={"sources": [source]}).get_json() assert body["results"][0]["created"] == 1 rows = _rows(client, "cacu.Paciente") assert rows["CP-1"]["pac_codigo_postal"] == "01000" assert "CP-2" not in rows and "CP-3" not in rows # 4 digits / non-digit def test_upsert_only_touches_mapped_columns(client): client.post( "/imports/commit", json={"sources": [_csv("exp,sexo,nac\nUP-1,F,15/01/1990\n", {"exp": "pac_id_hospital", "sexo": "pac_sexo", "nac": "pac_fecha_nacimiento"})]}, ) # pac_fecha_nacimiento is required (IND-01), so every row, insert or # upsert, must carry it. pac_sexo is the field that must stay untouched # when a later source doesn't map it. body = client.post( "/imports/commit", json={ "sources": [ _csv( "exp,cp,nac\nUP-1,64000,15/01/1990\n", {"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"}, ) ], "on_conflict": "upsert", }, ).get_json() assert body["results"][0]["updated"] == 1 row = _rows(client, "cacu.Paciente")["UP-1"] assert (row["pac_sexo"], row["pac_fecha_nacimiento"], row["pac_codigo_postal"]) == ("Femenino", "1990-01-15", "64000") def test_defaults_fill_unmapped_fields_and_blank_cells(client): source = _csv( "exp,dep,nac\nDEF-1,,1990-01-01\nDEF-2,GOBIERNO,1990-01-01\n", {"exp": "pac_id_hospital", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"}, defaults={"pac_dependencia": "CALLES Y CAMINOS", "pac_parentesco": "afiliado"}, ) assert client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]["created"] == 2 rows = _rows(client, "cacu.Paciente") assert rows["DEF-1"]["pac_dependencia"] == "CALLES Y CAMINOS" assert rows["DEF-2"]["pac_dependencia"] == "GOBIERNO" # Defaults go through the same validation/normalization as mapped cells. assert rows["DEF-1"]["pac_parentesco"] == rows["DEF-2"]["pac_parentesco"] == "Afiliado" def test_several_sources_compose_several_tables_in_one_batch(client): """One Excel workbook feeds two tables (a source per sheet), a CSV adds more patients, and a JSON source feeds a third table, all in one batch and one transaction.""" workbook = openpyxl.Workbook() pacientes = workbook.active pacientes.title = "Pacientes" pacientes.append(["Expediente", "Sexo", "Nacimiento"]) pacientes.append(["MIX-1", "F", "1990-01-01"]) ordenes = workbook.create_sheet("Ordenes") ordenes.append(["Folio", "Expediente", "Tipo"]) ordenes.append([9001, "MIX-1", "Solicitud de Papanicolao en Base Liquida"]) buffer = io.BytesIO() workbook.save(buffer) xlsx = _b64(buffer.getvalue()) preview = client.post( "/imports/sources/file/preview", data={"file": (io.BytesIO(buffer.getvalue()), "libro.xlsx"), "source_kind": "excel", "target": "cacu.OrdenesEstudio", "options": json.dumps({"sheet_name": "Ordenes"})}, content_type="multipart/form-data", ).get_json() assert preview["source_metadata"] == {"sheets": ["Pacientes", "Ordenes"], "sheet_name": "Ordenes"} assert [c["name"] for c in preview["columns"]] == ["Folio", "Expediente", "Tipo"] batch = [ {"source_type": "excel", "label": "libro.xlsx › Pacientes", "target": "cacu.Paciente", "column_mapping": {"Expediente": "pac_id_hospital", "Sexo": "pac_sexo", "Nacimiento": "pac_fecha_nacimiento"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Pacientes"}}}, _csv("id,genero,nac\nMIX-2,M,1990-01-01\n", {"id": "pac_id_hospital", "genero": "pac_sexo", "nac": "pac_fecha_nacimiento"}, label="extra.csv"), {"source_type": "excel", "target": "cacu.OrdenesEstudio", "column_mapping": {"Folio": "ord_numero_hospital", "Expediente": "pac_id_hospital", "Tipo": "ord_tipo_estudio"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Ordenes"}}}, {"source_type": "json", "target": "cacu.BiometriaHematica", "column_mapping": {"paciente.exp": "pac_id_hospital", "hb": "hemoglobina_g_dl"}, "payload": {"file_base64": _b64(json.dumps([{"paciente": {"exp": "MIX-1"}, "hb": 13.5}]).encode())}}, ] body = client.post("/imports/commit", json={"sources": batch}).get_json() assert body["ok"] is True assert [(r["label"], r["target"], r["created"]) for r in body["results"]] == [ ("libro.xlsx › Pacientes", "cacu.Paciente", 1), ("extra.csv", "cacu.Paciente", 1), (None, "cacu.OrdenesEstudio", 1), (None, "cacu.BiometriaHematica", 1), ] assert {"MIX-1", "MIX-2"} <= set(_rows(client, "cacu.Paciente")) orden = client.get("/data/cacu.OrdenesEstudio").get_json()["rows"][0] assert orden["ord_numero_hospital"] == 9001 def test_conflicts_are_itemized_with_their_row(client): body = client.post( "/imports/commit", json={ "sources": [ _csv( "exp,nac\nDUP-1,1990-01-01\nDUP-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}, ) ] }, ).get_json() result = body["results"][0] assert (result["created"], result["rejected"]) == (1, 1) assert result["errors"] == [ {"row_index": 1, "field": "pac_id_hospital", "category": "conflict", "message": "conflict on ('pac_id_hospital',)", "raw_value": "DUP-1"} ] def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch): from sqlalchemy.exc import OperationalError from persistance.repository import Repository original = Repository.bulk_upsert calls = {"n": 0} def flaky(self, objs, **kwargs): calls["n"] += 1 if calls["n"] == 2: raise OperationalError("INSERT ...", {}, Exception("disk full")) return original(self, objs, **kwargs) monkeypatch.setattr(Repository, "bulk_upsert", flaky) response = client.post( "/imports/commit", json={ "sources": [ _csv("exp,nac\nATOM-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}), _csv("exp,nac\nATOM-2,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}), ] }, ) assert response.status_code == 400 assert "no se escribió nada" in response.get_json()["error"] assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente")) @pytest.mark.parametrize( "payload", [ {"sources": [{"source_type": "csv", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ=="}}]}, {"sources": [{"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": "YQ=="}}]}, {"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "%%%not-base64"}}]}, {"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "no_such_field"}, "payload": {"file_base64": "YQ=="}}]}, {"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_sexo", "b": "pac_sexo"}, "payload": {"file_base64": "YQ=="}}]}, {"sources": "nope"}, {"sources": [{"source_type": "pdf", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ==", "mode": "regions", "regions": [], "dpi": 5000}}]}, ], ) def test_malformed_commits_are_400_not_500(client, payload): response = client.post("/imports/commit", json=payload) assert response.status_code == 400, response.get_json() assert response.get_json()["error"] def test_page_image_rejects_absurd_dpi(client): from reportlab.pdfgen import canvas buffer = io.BytesIO() pdf = canvas.Canvas(buffer) pdf.drawString(72, 720, "hola") pdf.save() response = client.post( "/imports/sources/pdf/page-image", data={"file": (io.BytesIO(buffer.getvalue()), "a.pdf"), "page_number": "1", "dpi": "5000"}, content_type="multipart/form-data", ) assert response.status_code == 400 assert "dpi" in response.get_json()["error"] def test_data_endpoint_pages_through_the_repository(client): body = client.get("/data/cacu.Paciente?limit=2").get_json() assert body["limit"] == 2 and len(body["rows"]) == 2 and body["total"] >= 2 assert client.get("/data/cacu.Nope").status_code == 404 def test_children_are_linked_to_parents_loaded_in_the_same_batch_whatever_the_order(client): """Biopsies listed before their patients still get `pac_id` filled, since parents are written first within the batch's transaction. A child whose patient doesn't exist keeps a null FK.""" from webapi.imports.services.link_resolver import dependency_rank, links_for assert [link.fk_field for link in links_for("cacu.BiopsiaCervical")] == ["pac_id"] assert links_for("cacu.Paciente") == () assert [link.fk_field for link in links_for("cama.Mastografia")] == ["pac_id", "ord_id"] assert dependency_rank("cama.Paciente") < dependency_rank("cama.OrdenesEstudio") < dependency_rank("cama.Mastografia") batch = [ _csv("exp,grado\nLINK-1,NORMAL\nNO-SUCH-PATIENT,NORMAL\n", {"exp": "pac_id_hospital", "grado": "bx_cin_grado"}, target="cacu.BiopsiaCervical"), _csv("exp,nac\nLINK-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}), ] body = client.post("/imports/commit", json={"sources": batch}).get_json() assert [r["target"] for r in body["results"]] == ["cacu.BiopsiaCervical", "cacu.Paciente"] assert body["results"][0]["linked"] == {"pac_id": 1} patient = _rows(client, "cacu.Paciente")["LINK-1"] biopsies = {r["pac_id_hospital"]: r for r in client.get("/data/cacu.BiopsiaCervical?limit=500").get_json()["rows"]} assert biopsies["LINK-1"]["pac_id"] == patient["pac_id"] assert biopsies["NO-SUCH-PATIENT"]["pac_id"] is None def test_data_endpoint_reports_columns_in_table_order(client): body = client.get("/data/cacu.Paciente?limit=1").get_json() assert body["columns"][:2] == ["pac_id", "pac_id_hospital"]