Files
WebApi/tests/test_new_sources.py
T
2026-11-12 01:13:34 -06:00

458 lines
21 KiB
Python

"""Connector catalog, SQL Server, EEG files and clinical documents, end to end."""
import base64
import io
from datetime import date
import numpy as np
import pytest
import sqlalchemy as sa
from sqlalchemy.dialects import mssql
from extraction.testing import edf_file, scanned_pdf, text_pdf
from webapi.imports.connectors.errors import ConnectorError
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
wire_domain("cama")
wire_domain("tea")
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 eeg(seconds: int = 8, rate: int = 128, **kwargs) -> bytes:
t = np.arange(rate * seconds) / rate
alpha = 40 * np.sin(2 * np.pi * 10 * t)
return edf_file(signals={"EEG O1-REF": alpha, "EEG O2-REF": alpha, "EEG Fp1-REF": 20 * np.sin(2 * np.pi * 20 * t)}, sample_rate=rate, **kwargs)
# -- catalog ------------------------------------------------------------------------
def test_catalog_lists_every_connector(client):
connectors = {c["kind"]: c for c in client.get("/imports/connectors").get_json()["connectors"]}
assert {"csv", "excel", "json", "pdf", "document", "edf", "sql"} <= set(connectors)
assert connectors["edf"]["extensions"] == ["edf"]
assert "pdf" in connectors["document"]["extensions"] and "tif" in connectors["document"]["extensions"]
assert {s["id"] for s in connectors["document"]["segmentations"]} == {"auto", "document", "pages", "key"}
engines = {e["id"]: e for e in connectors["sql"]["engines"]}
assert engines["mssql"]["label"] == "SQL Server" and engines["mssql"]["default_port"] == 1433
assert engines["mssql"]["available"] is True
# -- SQL Server ----------------------------------------------------------------------
def test_sql_server_url_is_built_from_form_fields():
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mssql", "host": "his.local", "database": "HIS", "user": "lector", "password": "p@ss:/w"})
assert url.drivername == "mssql+pymssql"
assert url.port == 1433
assert url.password == "p@ss:/w"
@pytest.mark.parametrize(
"raw,expected",
[
# bare host, nothing to pull apart
("10.56.0.45", ("10.56.0.45", None, None)),
(" 10.56.0.45 ", ("10.56.0.45", None, None)),
# SQL Server named instance, as the hospital's IT contact pasted it
("10.56.0.45\\SQLMAIN", ("10.56.0.45", "SQLMAIN", None)),
# the SSMS "Connect to Database Engine" convention: comma before the port
("10.56.0.45,1433", ("10.56.0.45", None, 1433)),
("10.56.0.45\\SQLMAIN,1433", ("10.56.0.45", "SQLMAIN", 1433)),
# a colon is also tolerated, as long as it isn't an IPv6 literal
("10.56.0.45:1433", ("10.56.0.45", None, 1433)),
# a copied connection string: scheme prefix and a trailing database/property list
("jdbc:sqlserver://10.56.0.45\\SQLMAIN;databaseName=Pruebas", ("10.56.0.45", "SQLMAIN", None)),
("tcp:10.56.0.45,1433", ("10.56.0.45", None, 1433)),
("postgresql://10.56.0.45:5432/Pruebas", ("10.56.0.45", None, 5432)),
# an IPv6 literal has more than one colon: left alone rather than mis-split
("fe80::1", ("fe80::1", None, None)),
],
)
def test_parse_server_address_tolerates_pasted_formats(raw, expected):
"""Pins the address parser against every way Erick (the hospital's IT
contact) is known to paste a server address — plain host, a SQL Server
named instance, the SSMS `host,port` convention and a copied JDBC/URI
string — plus an IPv6 literal that must NOT be mistaken for a
`host:port` pair. Fails if a future change stops stripping one of these
shapes, or starts mangling an IPv6 address."""
from webapi.imports.connectors.sql import _parse_server_address
assert _parse_server_address(raw) == expected
def test_sql_server_named_instance_leaves_port_unset_for_browser_resolution():
"""A named instance with no port given anywhere must reach pymssql as
`host\\instance` with no port appended, so FreeTDS can resolve the
instance's real port through SQL Server Browser (UDP 1434) instead of
being forced onto the wrong default port. Fails if `server_url` goes
back to always filling in `engine.default_port`."""
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mssql", "host": "10.56.0.45\\SQLMAIN", "database": "Pruebas", "user": "enlace", "password": "Enlace"})
assert url.host == "10.56.0.45\\SQLMAIN"
assert url.port is None
def test_sql_server_named_instance_with_explicit_port_is_appended_after_the_backslash():
"""When the instance's real static port IS known (typed in Puerto, or
pasted as `host\\instance,port`), it must still reach the driver
attached to the instance name, not silently dropped. Fails if the
explicit-port path stops composing `host\\instance` before handing off
to SQLAlchemy."""
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url(
{"engine": "mssql", "host": "10.56.0.45\\SQLMAIN", "port": "52001", "database": "Pruebas", "user": "enlace", "password": "Enlace"}
)
assert url.host == "10.56.0.45\\SQLMAIN"
assert url.port == 52001
def test_mysql_tolerates_an_embedded_port_with_no_explicit_port_field():
"""Any engine, not just SQL Server, benefits from the same parser: a
host pasted as `host:port` must still work when the Puerto field is
left blank. Fails if the fix regresses to engine-specific handling that
only covers mssql."""
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mysql", "host": "10.56.0.45:3307", "database": "hospital_legacy"})
assert url.host == "10.56.0.45"
assert url.port == 3307
def test_mysql_rejects_a_named_instance_it_cannot_speak():
"""MySQL/MariaDB/PostgreSQL have no concept of a named instance; a
backslash in the host for one of them is a mistake (e.g. the address
was meant for a different engine), and must be reported rather than
sent on as a garbled hostname. Fails if `server_url` stops validating
`supports_instance_name` per engine."""
from webapi.imports.connectors.sql import SqlConnector
with pytest.raises(ConnectorError, match="instancia"):
SqlConnector.server_url({"engine": "mysql", "host": "10.56.0.45\\SQLMAIN", "database": "hospital_legacy"})
def test_sql_server_preview_compiles_to_top(monkeypatch):
from webapi.imports.connectors.sql import _text_subquery
statement = sa.select(_text_subquery("SELECT * FROM pacientes")).limit(5)
compiled = str(statement.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}))
assert "TOP 5" in compiled and "LIMIT" not in compiled
def test_unknown_engine_and_missing_host_are_rejected(client):
assert client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "db2", "host": "x", "database": "y"}}).status_code == 400
response = client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "mssql", "database": "y"}})
assert response.status_code == 400 and "host" in response.get_json()["error"]
# -- EEG -----------------------------------------------------------------------------
def test_edf_preview_maps_onto_eeg_estudio(client):
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"}
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
[row] = body["sample_rows"]
assert row["id_registro_laboratorio"] == "LAB-778"
assert row["paciente"] == "EXP-0042"
assert row["fecha_estudio"] == "2024-01-15"
assert row["edad_meses"] == 56.0
assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3)
assert "3 canales a 128 Hz" in row["descripcion_senal"]
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
assert suggested["estudio"] == "eeg_estudio"
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia"
def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
source = {
"source_type": "edf",
"target": "tea.EegEstudio",
"column_mapping": {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"fecha_estudio": "eeg_fecha_estudio",
"duracion_min": "eeg_duracion_min",
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
"estudio": "eeg_estudio",
},
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
}
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.tea import eeg_estudio_repository
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()}
assert set(stored) == {"LAB-778", "b"}
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
def test_eeg_estudio_rejects_a_file_mne_cannot_read():
from webapi.imports.schemas.service import validate_rows
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
[row] = result.rejected
assert row.errors[0].field == "eeg_estudio"
# -- clinical documents -----------------------------------------------------------------
def _document_source(files: list[tuple[str, bytes]], target: str, mapping: dict, **options) -> dict:
return {
"source_type": "document",
"target": target,
"column_mapping": mapping,
"payload": {"files": [{"name": n, "file_base64": b64(r)} for n, r in files], **options},
"label": "documentos",
}
REPORTS = text_pdf(
[
["HOSPITAL REGIONAL - LABORATORIO DE PATOLOGIA", "Expediente: DOC-0001 Sexo: Femenino", "Fecha de nacimiento: 12/03/1981",
"VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"],
["Observaciones: muestra adecuada,", "con escaso moco cervical."],
["Expediente: DOC-0002 Sexo: F", "Fecha de nacimiento: 1 de mayo de 1975",
"Se identifica ADN de virus del papiloma humano de alto riesgo: NEGATIVO"],
],
image_on_page=2,
)
def test_document_extract_reports_records_evidence_and_images(client):
body = client.post(
"/imports/sources/document/extract",
json={"files": [{"name": "lote.pdf", "file_base64": b64(REPORTS)}], "target": "cacu.CitologiaCervical"},
).get_json()
assert body["key_field"] == "pac_id_hospital"
first, second = body["records"]
assert first["key"] == "DOC-0001" and first["sources"] == [{"document": "lote.pdf", "page_numbers": [1, 2]}]
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert first["fields"]["cit_vph_genotipo_16"]["value"] == 0
assert first["fields"]["cit_vph_genotipo_18"]["value"] == 1
assert first["fields"]["cit_observaciones"]["value"] == "muestra adecuada, con escaso moco cervical."
assert first["fields"]["cit_vph_resultado"]["page_number"] == 1
assert [image["page_number"] for image in first["images"]] == [2]
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
assert second["fields"]["cit_vph_resultado"]["method"] == "texto_libre"
def test_document_page_and_image_render(client):
data = {"file": (io.BytesIO(REPORTS), "lote.pdf"), "page_number": "2", "bbox": "[0.4, 0.4, 0.8, 0.7]"}
response = client.post("/imports/sources/document/page-image", data=data, content_type="multipart/form-data")
assert response.status_code == 200 and response.mimetype == "image/png"
def test_documents_commit_with_overrides_and_the_record_pdf(client):
mapping = {
"pac_id_hospital": "pac_id_hospital",
"cit_vph_resultado": "cit_vph_resultado",
"cit_vph_genotipo_18": "cit_vph_genotipo_18",
"documento": "cit_vph_pdf_blob",
}
source = _document_source([("lote.pdf", REPORTS)], "cacu.CitologiaCervical", mapping, overrides={"1": {"cit_vph_resultado": "INDETERMINADO"}})
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.cacu import citologia_cervical_repository
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("DOC-")}
assert rows["DOC-0001"].cit_vph_resultado == "POSITIVO"
assert rows["DOC-0002"].cit_vph_resultado == "INDETERMINADO"
assert rows["DOC-0001"].cit_vph_pdf_blob.startswith(b"%PDF")
def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
csv = b"expediente,sexo,codigo_postal\nMIX-0001,F,64000\nMIX-0002,M,01000\n"
scan = scanned_pdf([["FICHA DE IDENTIFICACION", "Expediente: MIX-0001", "Fecha de nacimiento: 15/08/1979", "Sexo: Masculino"]])
sources = [
{
"source_type": "csv",
"target": "cacu.Paciente",
"label": "padron.csv",
"column_mapping": {"expediente": "pac_id_hospital", "sexo": "pac_sexo", "codigo_postal": "pac_codigo_postal"},
"payload": {"file_base64": b64(csv)},
},
_document_source(
[("ficha.pdf", scan)],
"cacu.Paciente",
{"pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento", "pac_sexo": "pac_sexo"},
),
]
# On its own the CSV lacks the required birth date.
assert client.post("/imports/validate", json={"source": sources[0]}).get_json()["error_count"] == 2
padron, ficha = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
assert (padron["created"], padron["rejected"]) == (1, 1) # MIX-0002 has no birth date anywhere
assert (ficha["merged"], ficha["created"]) == (1, 0)
assert [(w["field"], w["raw_value"]) for w in ficha["warnings"]] == [("pac_sexo", "Masculino")]
from persistance.cacu import paciente_repository
[patient] = paciente_repository.list(pac_id_hospital="MIX-0001")
assert patient.pac_fecha_nacimiento == date(1979, 8, 15)
assert patient.pac_codigo_postal == "64000"
EEG_REPORT = text_pdf(
[
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024",
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
],
image_on_page=2,
)
# A second study id, distinct from LAB-778 (already used by an earlier test
# against this module-scoped client/database), for the merge test below.
EEG_REPORT_2 = text_pdf(
[
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024",
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
],
)
def test_eeg_report_scattered_across_pages_merges_into_one_record(client):
"""The report's demographics are on page 1, its conclusion on page 2 —
non-contiguous fields the same way a multi-file upload would be, just
without the file boundary. Proves the extractor merges by the lab's own
study id, not by page adjacency."""
body = client.post(
"/imports/sources/document/extract",
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"},
).get_json()
assert body["key_field"] == "eeg_id_registro_laboratorio"
[record] = body["records"]
assert record["key"] == "LAB-778"
assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}]
assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO"
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"]
assert [image["page_number"] for image in record["images"]] == [2]
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
"""The EDF connector computes signal fields from the file itself; the
report PDF (read with NLP, across two pages) carries the clinician's
interpretation. Different sources, same study — `eeg_id_registro_
laboratorio` (the lab's own code, read from the EDF header by one side
and from the report text by the other) is what lets them land on one
`eeg_estudio` row instead of two half-populated ones."""
edf_source = {
"source_type": "edf",
"target": "tea.EegEstudio",
"label": "estudio.edf",
"column_mapping": {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"fecha_estudio": "eeg_fecha_estudio",
"duracion_min": "eeg_duracion_min",
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
"estudio": "eeg_estudio",
},
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
}
document_source = _document_source(
[("reporte.pdf", EEG_REPORT_2)],
"tea.EegEstudio",
{
"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio",
"eeg_simetria": "eeg_simetria",
"eeg_conclusion_texto": "eeg_conclusion_texto",
"eeg_medico_interpreta": "eeg_medico_interpreta",
},
)
body = client.post(
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
).get_json()
edf_result, doc_result = body["results"]
assert edf_result["created"] == 1, body
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
from persistance.tea import eeg_estudio_repository
[row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900")
# From the EDF file itself:
assert row.eeg_duracion_min is not None
assert row.eeg_estudio[:8].strip() == b"0"
# From the scanned report, on the very same row:
assert row.eeg_simetria == "SIMETRICO"
assert "sin eventos epileptiformes" in row.eeg_conclusion_texto
assert row.eeg_medico_interpreta == "Dra. Ruiz"
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
"""The order/date come from a structured table (a CSV export of the lab's
own HIS); the VPH result comes from NLP over the scanned report PDF.
`(pac_id_hospital, ord_numero_hospital)` is what lets them land on one
`citologiacervical` row instead of two half-populated ones."""
csv = b"expediente,orden,fecha_toma\nMRG-0001,5001,2024-03-01\n"
report = text_pdf([["LABORATORIO DE CITOLOGIA", "Expediente: MRG-0001", "No. de orden: 5001", "VPH alto riesgo: POSITIVO"]])
sources = [
{
"source_type": "csv",
"target": "cacu.CitologiaCervical",
"label": "padron.csv",
"column_mapping": {"expediente": "pac_id_hospital", "orden": "ord_numero_hospital", "fecha_toma": "cit_fecha_toma"},
"payload": {"file_base64": b64(csv)},
},
_document_source(
[("reporte.pdf", report)],
"cacu.CitologiaCervical",
{"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital", "cit_vph_resultado": "cit_vph_resultado"},
),
]
tabla, documento = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
assert tabla["created"] == 1, tabla
assert documento["merged"] == 1, documento # absorbed into the table row, not inserted again
from persistance.cacu import citologia_cervical_repository
[row] = citologia_cervical_repository.list(pac_id_hospital="MRG-0001")
# From the structured table:
assert row.ord_numero_hospital == 5001
assert row.cit_fecha_toma == date(2024, 3, 1)
# From the scanned report, on the very same row:
assert row.cit_vph_resultado == "POSITIVO"
def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
"""The report has a picture of the mammogram alongside its narrative
text; `imagen` (like `documento`, the combined PDF) is mappable onto any
target column, so it lands in `mast_dicom_blob` next to the fields read
from the surrounding text."""
report = text_pdf(
[["LABORATORIO DE IMAGENOLOGIA", "Expediente: IMG-0001", "Interpretación: nódulo circunscrito en cuadrante superior externo."]],
image_on_page=1,
)
mapping = {"pac_id_hospital": "pac_id_hospital", "mast_interpretacion": "mast_interpretacion", "imagen": "mast_dicom_blob"}
source = _document_source([("reporte.pdf", report)], "cama.Mastografia", mapping)
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 1, result
from persistance.cama import mastografia_repository
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
assert "nódulo circunscrito" in row.mast_interpretacion
assert row.mast_dicom_blob.startswith(b"\x89PNG")