abfd2b29ca
The CaCu catalog holds fourteen measures. A fixture adds H-007, who goes the whole route in order, and a test pins the population, the cases and the median of each of the five new times.
143 lines
6.0 KiB
Python
143 lines
6.0 KiB
Python
"""The aggregate import log and the live indicator recomputation."""
|
|
import base64
|
|
import json
|
|
|
|
import pytest
|
|
|
|
MAPPING = {
|
|
"pac_id_hospital": "pac_id_hospital",
|
|
"pac_sexo": "pac_sexo",
|
|
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
|
"pac_codigo_postal": "pac_codigo_postal",
|
|
}
|
|
|
|
|
|
def _csv(rows: list[str]) -> dict:
|
|
body = "\n".join(["pac_id_hospital,pac_sexo,pac_fecha_nacimiento,pac_codigo_postal", *rows]).encode()
|
|
return {
|
|
"source_type": "csv",
|
|
"target": "cacu.Paciente",
|
|
"column_mapping": MAPPING,
|
|
"payload": {"file_base64": base64.b64encode(body).decode(), "options": {"file_name": "Garcia_Lopez.csv"}},
|
|
}
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def client(wire_domain, tmp_path_factory):
|
|
wire_domain("cacu")
|
|
import os
|
|
|
|
os.environ["WEBAPI_REPORT_DIR"] = str(tmp_path_factory.mktemp("reportes"))
|
|
os.environ["INDICADORES_DIR"] = str(tmp_path_factory.mktemp("indicadores"))
|
|
os.environ["INDICADORES_DESDE"] = "2025"
|
|
os.environ["INDICADORES_HASTA"] = "2025"
|
|
from webapi import create_app
|
|
|
|
app = create_app()
|
|
app.config.update(TESTING=True)
|
|
with app.test_client() as test_client:
|
|
yield test_client
|
|
|
|
|
|
def _log():
|
|
from webapi.imports.audit import default_sink
|
|
|
|
return default_sink().read()
|
|
|
|
|
|
def test_commit_is_logged_as_aggregates_only(client):
|
|
rows = [f"RPT-{i},F,1980-01-0{i % 9 + 1},64000" for i in range(4)]
|
|
rows += [f"RPT-BAD-{i},POSITIVO,15/13/1980,64000" for i in range(6)]
|
|
rows += ["RPT-RARE,QWERTY,1980-01-01,"]
|
|
response = client.post("/imports/commit", json={"sources": [_csv(rows)], "on_conflict": "reject"})
|
|
body = response.get_json()
|
|
assert response.status_code == 200
|
|
assert body["results"][0]["created"] == 4
|
|
assert body["indicadores_en_recalculo"] is True
|
|
|
|
record = _log()[-1]
|
|
assert record["id"] == body["audit_id"]
|
|
assert (record["operacion"], record["dominio"], record["resultado"]) == ("carga", "cacu", "completada")
|
|
source = record["fuentes"][0]
|
|
assert source["origen"] == {"tipo": "csv", "extensiones": [".csv"]}
|
|
assert source["filas"]["leidas"] == 11
|
|
assert source["filas"]["insertadas"] == 4
|
|
assert source["filas"]["rechazadas_en_validacion"] == 7
|
|
sexo = source["campos"]["pac_sexo"]
|
|
assert sexo["valores_fuera_de_catalogo"] == {"POSITIVO": 6}
|
|
assert sexo["valores_fuera_de_catalogo_poco_frecuentes"] == 1
|
|
assert source["campos"]["pac_fecha_nacimiento"]["formatos_rechazados"] == {"99/99/9999": 6}
|
|
assert source["campos"]["pac_codigo_postal"]["vacios"] == 1
|
|
|
|
raw = json.dumps(record)
|
|
for secret in ("RPT-", "Garcia", "QWERTY", "15/13/1980"):
|
|
assert secret not in raw
|
|
|
|
|
|
def test_failed_request_and_validation_are_logged(client):
|
|
bad = _csv(["RPT-X,F,1980-01-01,64000"])
|
|
bad["target"] = "cacu.NoExiste"
|
|
assert client.post("/imports/commit", json={"sources": [bad]}).status_code == 400
|
|
assert _log()[-1]["resultado"] == "solicitud_invalida"
|
|
|
|
assert client.post("/imports/validate", json={"source": _csv(["RPT-V,F,1980-01-01,64000"])}).status_code == 200
|
|
last = _log()[-1]
|
|
assert (last["operacion"], last["resultado"]) == ("validacion", "completada")
|
|
assert last["fuentes"][0]["filas"]["validas"] == 1
|
|
|
|
|
|
def test_report_endpoints(client):
|
|
body = client.get("/reportes/importaciones").get_json()
|
|
paciente = body["resumen"]["destinos"]["cacu.Paciente"]
|
|
assert paciente["cargas_completadas"] == 1
|
|
assert paciente["filas_en_cargas_completadas"]["insertadas"] == 4
|
|
assert body["intentos"][0]["operacion"] == "validacion"
|
|
download = client.get("/reportes/importaciones/descarga")
|
|
assert len(download.get_data(as_text=True).strip().splitlines()) == len(_log())
|
|
|
|
|
|
def test_indicators_recompute_from_imported_rows(client):
|
|
from webapi.recomputation import RecomputationQueue
|
|
|
|
cola = RecomputationQueue()
|
|
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
|
assert cola.serve() == ["cacu"]
|
|
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
|
assert estado["estado"] == "ok", estado
|
|
assert estado["pendiente"] is False
|
|
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
|
|
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
|
|
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
|
|
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
|
|
"CACU_DIAS_TOMA_COLPOSCOPIA", "CACU_DIAS_TOMA_BIOPSIA", "CACU_DIAS_RESULTADO_COLPOSCOPIA",
|
|
"CACU_DIAS_COLPOSCOPIA_BIOPSIA", "CACU_DIAS_BIOPSIA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
|
|
|
|
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
|
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
|
|
|
|
|
def test_headerless_file_does_not_leak_its_first_record():
|
|
"""Without a header row the first record becomes the column names."""
|
|
from webapi.imports.audit import column_label
|
|
|
|
for header in ("pac_id_hospital", "fecha_nacimiento", "cit_vph_genotipo_16", "Sexo", "Código postal"):
|
|
assert column_label(header) == header
|
|
for value, shape in (("N-0001", "A-9999"), ("1980-01-01", "9999-99-99"), ("64000", "99999"),
|
|
("H123", "A999"), ("ana@x.mx", "AAA@A.AA")):
|
|
assert column_label(value) == shape
|
|
note = "Paciente refiere dolor pélvico desde hace tres semanas"
|
|
assert note not in column_label(note)
|
|
|
|
|
|
def test_headerless_csv_logs_shapes(client):
|
|
body = "N-0001,F,1980-01-01\nN-0002,F,1981-02-02\n".encode()
|
|
source = {
|
|
"source_type": "csv", "target": "cacu.Paciente",
|
|
"column_mapping": {"N-0001": "pac_id_hospital", "F": "pac_sexo", "1980-01-01": "pac_fecha_nacimiento"},
|
|
"payload": {"file_base64": base64.b64encode(body).decode()},
|
|
}
|
|
client.post("/imports/validate", json={"source": source})
|
|
raw = json.dumps(_log()[-1])
|
|
assert "N-0001" not in raw and "1980-01-01" not in raw
|
|
assert "A-9999" in raw
|