174 lines
7.7 KiB
Python
174 lines
7.7 KiB
Python
"""`DocumentConnector` reading its documents from a SQL source instead of
|
|
uploaded files: one document per row, read from a column that may hold a
|
|
PDF (a binary column) or already be plain text, both without a filesystem
|
|
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
|
plain-text column stops reaching the same field extraction a PDF does.
|
|
"""
|
|
import base64
|
|
|
|
import pytest
|
|
from sqlalchemy import create_engine, text
|
|
|
|
from extraction.testing import text_pdf
|
|
|
|
|
|
@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
|
|
|
|
|
|
REPORT = text_pdf(
|
|
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def sqlite_studies_table(tmp_path):
|
|
"""A source table with one row per study, its
|
|
report in a binary column, plus a plain-text variant of the same
|
|
report in another row, both alongside the row's own key column."""
|
|
db_path = tmp_path / "estudios.db"
|
|
url = f"sqlite:///{db_path}"
|
|
engine = create_engine(url)
|
|
with engine.begin() as conn:
|
|
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
|
conn.execute(
|
|
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
|
{"id": "ROW-1", "reporte": REPORT},
|
|
)
|
|
conn.execute(
|
|
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
|
{
|
|
"id": "ROW-2",
|
|
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
|
},
|
|
)
|
|
return url
|
|
|
|
|
|
def _sql_payload(url: str, **overrides) -> dict:
|
|
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
|
|
|
|
|
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
|
body = client.post(
|
|
"/imports/sources/document/extract",
|
|
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
|
).get_json()
|
|
[first, second] = body["records"]
|
|
assert first["key"] == "SQL-0001"
|
|
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
|
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
|
|
|
|
|
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
|
"""Fails if a source whose bundle is a plain string (not binary at
|
|
all) stops producing fields, since a source's column may not always
|
|
be a PDF (`extraction.readers.TextReader`)."""
|
|
body = client.post(
|
|
"/imports/sources/document/extract",
|
|
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
|
).get_json()
|
|
[_, second] = body["records"]
|
|
assert second["key"] == "SQL-0002"
|
|
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
|
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
|
|
|
|
|
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
|
source = {
|
|
"source_type": "document",
|
|
"target": "cacu.CitologiaCervical",
|
|
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
|
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
|
"label": "estudios",
|
|
}
|
|
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("SQL-")}
|
|
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
|
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
|
|
|
|
|
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
|
response = client.post(
|
|
"/imports/sources/document/extract",
|
|
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
|
)
|
|
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
|
|
|
|
|
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
|
payload = _sql_payload(sqlite_studies_table)
|
|
del payload["column"]
|
|
response = client.post(
|
|
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
|
)
|
|
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
|
|
|
|
|
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
|
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
|
fijador`) but the project's catalog does still reaches the silver
|
|
layer through the open-catalog path, alongside the recognized fields
|
|
`commit_sources` writes as before, when the source asks for it with
|
|
`catalog_fallback`. Fails if `/imports/commit` stops wiring that second
|
|
path in, or runs it for a source that didn't ask.
|
|
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
|
the module's other tests sharing this `client`'s database."""
|
|
from datetime import date
|
|
|
|
from sqlalchemy import create_engine, text as sa_text
|
|
from sqlmodel import select
|
|
|
|
from indicadores_kit.registry import catalogos
|
|
from core.cacu.paciente.model import Paciente
|
|
from persistance.cacu import carga_repository, paciente_repository
|
|
|
|
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
|
catalog = (
|
|
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
|
'[citologia.resultados.tipo_de_fijador]\netiqueta = "Tipo de fijador"\ntipo_valor = "texto"\n'
|
|
)
|
|
(tmp_path / "cacu.toml").write_text(catalog, encoding="utf-8")
|
|
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
|
|
|
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
|
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
|
with create_engine(db_url).begin() as conn:
|
|
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
|
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
|
|
|
source = {
|
|
"source_type": "document",
|
|
"target": "cacu.CitologiaCervical",
|
|
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
|
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
|
"label": "estudios_extra",
|
|
}
|
|
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
|
assert body["results"][0]["created"] == 1, body
|
|
assert not [r for r in body.get("catalog_fallback", []) if r["label"] == "estudios_extra"]
|
|
|
|
body = client.post("/imports/commit", json={"sources": [{**source, "catalog_fallback": True}], "on_conflict": "upsert"}).get_json()
|
|
[fallback] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
|
assert (fallback["records_written"], fallback["fields_matched"], fallback["fields_minted"]) == (1, 1, 0)
|
|
assert (tmp_path / "cacu.toml").read_text(encoding="utf-8") == catalog
|
|
|
|
with carga_repository.open_session() as sesion:
|
|
[written] = list(
|
|
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
|
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
|
)))
|
|
)
|
|
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol" |