improve ingestion system to match isssteleon setup
This commit is contained in:
@@ -65,24 +65,21 @@ def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, know
|
||||
assert procedimiento.fuente_id == known_patient
|
||||
|
||||
|
||||
def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient):
|
||||
def test_an_unmatched_field_is_counted_and_the_catalog_left_untouched(cacu_catalog, known_patient):
|
||||
"""A caption the catalog doesn't know is counted, not written, and the
|
||||
catalog file isn't edited: it's versioned with the code. Fails if the
|
||||
import path mints catalog entries again."""
|
||||
before = cacu_catalog.read_text(encoding="utf-8")
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert result.fields_minted == 1
|
||||
nombres = set(catalogos._leer(cacu_catalog)["citologia"]["resultados"])
|
||||
assert nombres == {"calidad_muestra", "tipo_de_fijador"} # the fixture's field, plus the minted one
|
||||
minted_id = "citologia.tipo_de_fijador"
|
||||
|
||||
catalogo = catalogos.catalogo_desde_toml(cacu_catalog, tablas=tablas_de("cacu"))
|
||||
assert minted_id in {r.resultado_id for r in catalogo.resultados}
|
||||
assert (result.records_written, result.fields_minted, result.fields_unmatched) == (0, 0, 1)
|
||||
assert cacu_catalog.read_text(encoding="utf-8") == before
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == minted_id
|
||||
assert observacion.valor_texto == "Formol"
|
||||
assert sesion.exec(select(carga_repository.observacion)).all() == []
|
||||
|
||||
|
||||
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Options that let one document source cope with however its rows are
|
||||
stored: columns carried through as field values, a column grouping rows
|
||||
into records, filters that pick which documents feed a target, documents
|
||||
kept as hex or base64 text, unreadable rows, and queries that a derived
|
||||
table can't hold as written.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database) and
|
||||
`documents_table`, a SQLite table built per test whose rows carry two
|
||||
reports of one order, a third report of the same patient under another
|
||||
order, and an unrelated kind of report.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.document import document_bytes
|
||||
from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def documents_table(tmp_path):
|
||||
"""Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is
|
||||
a report of order 11 of the same patient, and row 4 is a report of a
|
||||
kind the CaCu cytology target doesn't take. No body prints the
|
||||
patient id the structured columns hold."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
rows = [
|
||||
(1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"),
|
||||
(2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"),
|
||||
(3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"),
|
||||
(4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"),
|
||||
]
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)"))
|
||||
for row in rows:
|
||||
conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row)))
|
||||
return url
|
||||
|
||||
|
||||
def _payload(url: str, **sql) -> dict:
|
||||
base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}
|
||||
return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"}
|
||||
|
||||
|
||||
def _extract(client, payload: dict) -> dict:
|
||||
response = client.post("/imports/sources/document/extract", json=payload)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table):
|
||||
"""Rows sharing `group_column` become one record; the same patient's
|
||||
other order stays its own record. Fails if `group_column` stops
|
||||
reaching `record_keys`."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(
|
||||
documents_table,
|
||||
fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"},
|
||||
group_column="order_ref",
|
||||
)
|
||||
| {"exclude_pattern": "otra especialidad"},
|
||||
)
|
||||
by_key = {record["key"]: record for record in body["records"]}
|
||||
assert set(by_key) == {"10", "11"}
|
||||
assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1"
|
||||
|
||||
|
||||
def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table):
|
||||
"""`include_pattern` keeps only matching documents, matched without
|
||||
regard to case or accents, and the rest are listed as skipped. Fails
|
||||
if the filters stop applying or `skipped` stops reporting them."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"},
|
||||
)
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["4"]
|
||||
|
||||
|
||||
def test_a_filter_that_matches_nothing_is_an_error(client, documents_table):
|
||||
"""Filtering out every document is reported instead of returning an
|
||||
empty import. Fails if `_extract` stops refusing an empty selection."""
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_an_invalid_filter_is_a_bad_request(client, documents_table):
|
||||
"""A filter that isn't a valid regular expression is rejected with a
|
||||
message naming it. Fails if `_compile_filter` lets `re.error` through."""
|
||||
response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("})
|
||||
assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_documents_stored_as_hex_or_base64_text_are_decoded():
|
||||
"""A PDF kept in a text column as hex (with or without `0x`) or base64
|
||||
reaches the readers as the PDF itself, and ordinary text stays text.
|
||||
Fails if `document_bytes` stops recognizing either encoding."""
|
||||
pdf = text_pdf([["Expediente: X-1"]])
|
||||
assert document_bytes("0x" + pdf.hex()) == pdf
|
||||
assert document_bytes(pdf.hex().upper()) == pdf
|
||||
assert document_bytes(base64.b64encode(pdf).decode()) == pdf
|
||||
assert document_bytes("Expediente: X-1") == b"Expediente: X-1"
|
||||
|
||||
|
||||
def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path):
|
||||
"""One corrupt document among readable ones is listed as skipped while
|
||||
the rest are extracted. Fails if a single unreadable row aborts the
|
||||
whole source again."""
|
||||
url = f"sqlite:///{tmp_path / 'mixed.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"})
|
||||
conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])})
|
||||
body = _extract(client, _payload(url))
|
||||
assert [record["key"] for record in body["records"]] == ["X-2"]
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["1"]
|
||||
|
||||
|
||||
def test_repeated_key_column_values_still_name_rows_apart(tmp_path):
|
||||
"""Two rows with the same `key_column` value get distinct names, so
|
||||
neither one's fields or pages overwrite the other's. Fails if
|
||||
`_files_from_sql` stops suffixing repeated names."""
|
||||
from webapi.imports.connectors.document import _files_from_sql
|
||||
|
||||
url = f"sqlite:///{tmp_path / 'r.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')"))
|
||||
documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"})
|
||||
assert [name for name, _ in documents.files] == ["7", "7#2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query,kept",
|
||||
[
|
||||
("SELECT a FROM t ORDER BY a", "SELECT a FROM t"),
|
||||
("SELECT TOP 5 a FROM t ORDER BY a", None),
|
||||
("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None),
|
||||
("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None),
|
||||
("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"),
|
||||
],
|
||||
)
|
||||
def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept):
|
||||
"""SQL Server refuses `ORDER BY` inside a derived table unless TOP or
|
||||
OFFSET goes with it, so one that only sorts is dropped; one that picks
|
||||
rows, or sits inside a subquery or a string, stays. Fails if
|
||||
`_without_trailing_order_by` drops an `ORDER BY` that chooses rows or
|
||||
keeps one that would make the wrapped query invalid."""
|
||||
assert _without_trailing_order_by(query, "mssql") == (kept or query)
|
||||
|
||||
|
||||
def test_a_named_instance_or_embedded_port_reaches_the_driver():
|
||||
"""`host\\instance` leaves the port unset for the server to resolve,
|
||||
and `host,port` or `host:port` fill it in. Fails if `server_url` stops
|
||||
parsing addresses or goes back to forcing the default port on a named
|
||||
instance."""
|
||||
named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"})
|
||||
assert (named.host, named.port) == ("db.example\\INST", None)
|
||||
comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"})
|
||||
assert (comma.host, comma.port) == ("db.example", 1500)
|
||||
colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"})
|
||||
assert (colon.host, colon.port) == ("db.example", 6543)
|
||||
@@ -1,6 +1,6 @@
|
||||
"""`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 (`varbinary(max)`) or already be plain text, both without a filesystem
|
||||
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.
|
||||
"""
|
||||
@@ -31,7 +31,7 @@ REPORT = text_pdf(
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table shaped like ISSSTELEON's: one row per study, its
|
||||
"""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"
|
||||
@@ -57,118 +57,6 @@ def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_archivos_uni_table(tmp_path):
|
||||
"""Shaped exactly like the hospital's own `ArchivosUni` table (`Id`,
|
||||
`PacienteId`, `OrdenServicioId`, `Archivo`): no column prints a
|
||||
recognizable "Expediente" label anywhere, and two rows (the same
|
||||
order's cover page and its result) share one `PacienteId`, the way the
|
||||
source's own export does. Proves a table with no text-parseable key at
|
||||
all can still be read correctly through `sql.fields`."""
|
||||
db_path = tmp_path / "archivos_uni.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE ArchivosUni (Id INTEGER, PacienteId INTEGER, OrdenServicioId INTEGER, Archivo BLOB)"))
|
||||
rows = [
|
||||
(1, 115220, 297914, "VPH alto riesgo: POSITIVO"),
|
||||
(2, 115220, 297914, "Genotipo 18: DETECTADO"),
|
||||
(3, 209622, 298182, "VPH alto riesgo: NEGATIVO"),
|
||||
]
|
||||
for id_, paciente_id, orden_id, archivo in rows:
|
||||
conn.execute(
|
||||
text("INSERT INTO ArchivosUni (Id, PacienteId, OrdenServicioId, Archivo) VALUES (:id, :pid, :oid, :archivo)"),
|
||||
{"id": id_, "pid": paciente_id, "oid": orden_id, "archivo": archivo},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _archivos_uni_payload(url: str, **overrides) -> dict:
|
||||
return {
|
||||
"connection_string": url,
|
||||
"table": "ArchivosUni",
|
||||
"column": "Archivo",
|
||||
"key_column": "Id",
|
||||
"fields": {"pac_id_hospital": "PacienteId"},
|
||||
**overrides,
|
||||
}
|
||||
|
||||
|
||||
def test_rows_with_no_text_label_are_keyed_from_a_structured_column(client, sqlite_archivos_uni_table):
|
||||
"""Neither row prints "Expediente" anywhere; `sql.fields` is the only
|
||||
way these rows can be keyed at all. Fails if `fields` stops reaching
|
||||
the key computation through `DocumentConnector.source_fields`."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
by_key = {r["key"]: r for r in body["records"]}
|
||||
assert set(by_key) == {"115220", "209622"}
|
||||
assert by_key["115220"]["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
|
||||
|
||||
def test_rows_sharing_a_patient_id_merge_into_one_record(client, sqlite_archivos_uni_table):
|
||||
"""Rows 1 and 2 are two blob parts of the same order (same
|
||||
`PacienteId` and `OrdenServicioId`, the way the hospital stores a
|
||||
split report) and must land on a single record, not two. Fails if
|
||||
`fields` stops being enough to merge documents that share no text in
|
||||
common at all."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[record] = [r for r in body["records"] if r["key"] == "115220"]
|
||||
assert record["fields"]["pac_id_hospital"]["value"] == "115220"
|
||||
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert record["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert {s["document"] for s in record["sources"]} == {"1", "2"}
|
||||
|
||||
|
||||
def test_sql_fields_value_wins_over_a_conflicting_text_label(client, sqlite_archivos_uni_table):
|
||||
"""If a row's own text happens to print a different "Expediente" than
|
||||
its `PacienteId`, the structured column must still be trusted — it is
|
||||
the hospital's real join key. Fails if a text-derived reading is ever
|
||||
allowed to outrank `sql.fields`."""
|
||||
engine = create_engine(sqlite_archivos_uni_table)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text("INSERT INTO ArchivosUni (Id, PacienteId, OrdenServicioId, Archivo) VALUES (4, 300000, 400000, :archivo)"),
|
||||
{"archivo": "Expediente: WRONG-LABEL\nVPH alto riesgo: NEGATIVO"},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[record] = [r for r in body["records"] if r["key"] == "300000"]
|
||||
assert record["fields"]["pac_id_hospital"]["value"] == "300000"
|
||||
|
||||
|
||||
def test_an_unknown_sql_field_is_a_bad_request(client, sqlite_archivos_uni_table):
|
||||
payload = _archivos_uni_payload(sqlite_archivos_uni_table, fields={"campo_inexistente": "PacienteId"})
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "campo_inexistente" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_sql_fields_source_commits_like_a_text_derived_key(client, sqlite_archivos_uni_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _archivos_uni_payload(sqlite_archivos_uni_table)},
|
||||
"label": "archivos_uni",
|
||||
}
|
||||
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 in ("115220", "209622")}
|
||||
assert rows["115220"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["209622"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
@@ -182,7 +70,7 @@ def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table)
|
||||
|
||||
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 ISSSTELEON's column may not always
|
||||
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",
|
||||
@@ -231,9 +119,11 @@ def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
|
||||
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`) still reaches the silver layer through the open-catalog
|
||||
path, alongside the recognized fields `commit_sources` writes as
|
||||
before. Fails if `/imports/commit` stops wiring that second path in.
|
||||
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
|
||||
@@ -246,7 +136,11 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text('[citologia]\netiqueta = "Citología cervical"\n', encoding="utf-8")
|
||||
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'}"
|
||||
@@ -264,14 +158,17 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
|
||||
}
|
||||
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"]
|
||||
|
||||
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert report["records_written"] == 1 and report["fields_minted"] == 1
|
||||
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:
|
||||
[minted] = list(
|
||||
[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 minted.resultado_id == "citologia.tipo_de_fijador" and minted.valor_texto == "Formol"
|
||||
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Derived fields and document columns inside an ordinary mapping: target
|
||||
fields computed from several source columns (joined, split, picked, read
|
||||
out of a longer text or translated), files kept in a column of a CSV or
|
||||
SQL source read for the fields the plain mapping left empty, and the
|
||||
captions nothing used, as the import report lists them.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database). Sources are
|
||||
built inline: CSV text through `_csv`, SQLite tables under `tmp_path`.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.mapping.derived import build_derivation, parse_derived
|
||||
|
||||
|
||||
@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(content: str, **source) -> dict:
|
||||
return {"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": _b64(content.encode())}, **source}
|
||||
|
||||
|
||||
ROW = {"nombre": " ana maría ", "paterno": "Pérez", "materno": "", "completo": "Ana María Pérez López", "dir": "Calle 5, CP 64000"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rule,expected",
|
||||
[
|
||||
({"op": "concat", "columns": ["nombre", "paterno", "materno"]}, "ana maría Pérez"),
|
||||
({"op": "concat", "columns": ["paterno", "nombre"], "separator": ", ", "case": "upper"}, "PÉREZ, ANA MARÍA"),
|
||||
({"op": "template", "template": "{paterno} {materno} / {nombre}"}, "Pérez / ana maría"),
|
||||
({"op": "split", "column": "completo", "start": 0, "stop": -2}, "Ana María"),
|
||||
({"op": "split", "column": "completo", "start": -2, "stop": -1}, "Pérez"),
|
||||
({"op": "coalesce", "columns": ["materno", "paterno"]}, "Pérez"),
|
||||
({"op": "extract", "column": "dir", "pattern": r"CP\s*(\d{5})", "group": 1}, "64000"),
|
||||
({"op": "map", "column": "paterno", "values": {"pérez": "P"}}, "P"),
|
||||
({"op": "map", "column": "nombre", "values": {"x": "y"}, "keep_unmatched": False}, None),
|
||||
({"op": "column", "column": "paterno"}, "Pérez"),
|
||||
],
|
||||
)
|
||||
def test_each_operation_computes_its_value(rule, expected):
|
||||
"""Pins what every registered operation returns for one row, blanks
|
||||
skipped and spaces collapsed. Fails if an operation's semantics change
|
||||
(`start`/`stop` counting, separators, `case`, unmatched values)."""
|
||||
assert build_derivation(rule).apply(ROW) == expected
|
||||
|
||||
|
||||
def test_rules_are_checked_before_any_row_is_read():
|
||||
"""Unknown operations, missing parameters, bad patterns and fields the
|
||||
target lacks are refused up front. Fails if `parse_derived` lets a
|
||||
malformed rule through to fail row by row."""
|
||||
for bad in ({"op": "nope"}, {"op": "concat"}, {"op": "extract", "column": "a", "pattern": "("}, {"op": "split", "column": "a", "case": "x"}):
|
||||
with pytest.raises(ConnectorError):
|
||||
build_derivation(bad)
|
||||
with pytest.raises(ConnectorError):
|
||||
parse_derived({"no_such_field": "a"}, {"pac_sexo"})
|
||||
|
||||
|
||||
def test_short_forms_name_a_column_or_join_several():
|
||||
"""A rule given as a column name reads it; a list of columns joins them.
|
||||
Fails if `rule_from` stops accepting the short forms."""
|
||||
rules = parse_derived({"a": "paterno", "b": ["nombre", "paterno"]}, {"a", "b"})
|
||||
assert rules["a"].apply(ROW) == "Pérez" and rules["b"].apply(ROW) == "ana maría Pérez"
|
||||
|
||||
|
||||
def test_derived_fields_reach_validation_and_the_mapped_preview(client):
|
||||
"""A source whose id is split over two columns and whose sex comes
|
||||
coded validates cleanly once `derived` joins and translates them, and
|
||||
`/imports/mapped-preview` shows the rows as they would be written.
|
||||
Fails if `ImportSource.rows` stops applying `derived`."""
|
||||
source = _csv(
|
||||
"serie,numero,sx,cp,nac\nA,001,1,64000,1980-01-02\nB,002,2,64100,1975-03-04\n",
|
||||
column_mapping={"cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_id_hospital": {"op": "concat", "columns": ["serie", "numero"], "separator": "-"},
|
||||
"pac_sexo": {"op": "map", "column": "sx", "values": {"1": "F", "2": "M"}},
|
||||
},
|
||||
)
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert [(r["pac_id_hospital"], r["pac_sexo"]) for r in rows] == [("A-001", "F"), ("B-002", "M")]
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def test_a_field_cannot_be_both_mapped_and_derived(client):
|
||||
"""Fails if a field fed twice (mapping and `derived`) stops being refused."""
|
||||
source = _csv("a\n1\n", column_mapping={"a": "pac_id_hospital"}, derived={"pac_id_hospital": "a"})
|
||||
assert client.post("/imports/validate", json={"source": source}).status_code == 400
|
||||
|
||||
|
||||
def test_the_operations_are_listed_for_clients(client):
|
||||
"""`/imports/derivations` lists every operation with its parameters, so
|
||||
the import screen builds its forms from the server. Fails if an
|
||||
operation is registered without being described."""
|
||||
body = client.get("/imports/derivations").get_json()
|
||||
ops = {d["op"]: d for d in body["derivations"]}
|
||||
assert {"column", "concat", "template", "split", "coalesce", "extract", "map"} <= set(ops)
|
||||
assert [p["name"] for p in ops["split"]["params"]] == ["column", "separator", "start", "stop"]
|
||||
assert body["cases"] == ["upper", "lower", "title"]
|
||||
|
||||
|
||||
def _documents_table(tmp_path) -> str:
|
||||
"""Two rows of one order of patient P-7, one with its report as a PDF
|
||||
and one as base64 text, and a third row with no document."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
report = text_pdf([["VPH alto riesgo: POSITIVO"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, orden INTEGER, archivo BLOB, texto TEXT)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-7', 5, :f, NULL)"), {"f": report})
|
||||
conn.execute(
|
||||
text("INSERT INTO t VALUES ('P-7', 5, NULL, :t)"), {"t": _b64(text_pdf([["Genotipo 16: DETECTADO"]]))}
|
||||
)
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-8', 6, NULL, NULL)"))
|
||||
return url
|
||||
|
||||
|
||||
def _sql_source(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"column_mapping": {"pid": "pac_id_hospital", "orden": "ord_numero_hospital"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_a_sql_preview_flags_the_columns_that_hold_documents(client, tmp_path):
|
||||
"""Binary files and files written as base64 text are both flagged;
|
||||
plain values aren't. Fails if `document_columns` stops reaching the
|
||||
preview."""
|
||||
url = _documents_table(tmp_path)
|
||||
body = client.post("/imports/sources/sql/preview", json={"connection_string": url, "table": "t"}).get_json()
|
||||
assert set(body["document_columns"]) == {"archivo", "texto"}
|
||||
|
||||
|
||||
def test_document_columns_fill_what_the_mapping_leaves_empty(client, tmp_path):
|
||||
"""The mapped id and order are kept; the documents of both rows of the
|
||||
order add the fields they print; a row without documents passes
|
||||
through mapped. Fails if `documents` stops reading cells of an
|
||||
ordinary mapping, or loses the rows that have none."""
|
||||
source = _sql_source(_documents_table(tmp_path), documents={"columns": ["archivo", "texto"], "group_by": "orden"})
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
by_patient = {row["pac_id_hospital"]: row for row in rows}
|
||||
assert by_patient["P-7"]["ord_numero_hospital"] == 5
|
||||
assert by_patient["P-7"]["cit_vph_resultado"] == "POSITIVO"
|
||||
assert by_patient["P-7"]["cit_vph_genotipo_16"] == 1
|
||||
assert by_patient["P-8"]["ord_numero_hospital"] == 6
|
||||
|
||||
|
||||
def test_documents_of_a_mapping_can_be_reviewed_and_committed(client, tmp_path):
|
||||
"""`/imports/sources/document/extract` with `{source}` reviews the same
|
||||
records the commit writes, with the record's pages in `file_field`.
|
||||
Fails if the review and the commit read document columns differently."""
|
||||
source = _sql_source(
|
||||
_documents_table(tmp_path),
|
||||
documents={"columns": "archivo", "group_by": "orden", "file_field": "cit_pdf_blob"},
|
||||
label="t",
|
||||
)
|
||||
report = client.post("/imports/sources/document/extract", json={"source": source}).get_json()
|
||||
[record] = report["records"]
|
||||
assert record["fields"]["pac_id_hospital"]["method"] == "columna_fuente"
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
stored = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100)}
|
||||
assert stored["P-7"].cit_vph_resultado == "POSITIVO"
|
||||
assert stored["P-7"].cit_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_a_csv_column_of_base64_documents_is_read_like_a_sql_one(client):
|
||||
"""Document columns are not tied to SQL: a CSV whose column carries
|
||||
base64 PDFs feeds the same extraction. Fails if `documents` only works
|
||||
for one kind of source."""
|
||||
report = _b64(text_pdf([["VPH alto riesgo: NEGATIVO"]]))
|
||||
source = _csv(
|
||||
f"exp,doc\nC-1,{report}\n",
|
||||
target="cacu.CitologiaCervical",
|
||||
column_mapping={"exp": "pac_id_hospital"},
|
||||
documents={"columns": "doc"},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert row["pac_id_hospital"] == "C-1" and row["cit_vph_resultado"] == "NEGATIVO"
|
||||
|
||||
|
||||
def _id_and_file_table(tmp_path) -> str:
|
||||
"""Each row has only an id and a file; every other value is printed
|
||||
in the file under captions no target field knows."""
|
||||
url = f"sqlite:///{tmp_path / 'files.db'}"
|
||||
report = text_pdf([["Tipo de persona: Mujer", "Domicilio actual: Calle 5, C.P. 64000", "Nacida el: 02/01/1980"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, archivo BLOB)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('Q-1', :f)"), {"f": report})
|
||||
return url
|
||||
|
||||
|
||||
def _paciente_from_file(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"documents": {"columns": "archivo"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_captions_printed_in_documents_are_offered_as_columns(client, tmp_path):
|
||||
"""`/imports/sources/document/columns` lists the source's own columns
|
||||
and every caption its documents print, with their values. Fails if
|
||||
discovered captions stop becoming columns of the source."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/columns", json={"source": _paciente_from_file(_id_and_file_table(tmp_path))}
|
||||
).get_json()
|
||||
names = [column["name"] for column in body["columns"]]
|
||||
assert {"pid", "Tipo de persona", "Domicilio actual", "Nacida el"} <= set(names)
|
||||
[row] = body["sample_rows"]
|
||||
assert row["Tipo de persona"] == "Mujer"
|
||||
|
||||
|
||||
def test_mapping_and_rules_reach_what_the_documents_print(client, tmp_path):
|
||||
"""A caption maps onto a field like a column does, and derived rules
|
||||
translate or cut values read from the page. Fails if the mapping and
|
||||
`derived` stop running over the record's document values."""
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path),
|
||||
column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_sexo": {"op": "map", "column": "Tipo de persona", "values": {"mujer": "F", "hombre": "M"}},
|
||||
"pac_codigo_postal": {"op": "extract", "column": "Domicilio actual", "pattern": r"\d{5}"},
|
||||
},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert (row["pac_id_hospital"], row["pac_sexo"], row["pac_codigo_postal"]) == ("Q-1", "F", "64000")
|
||||
assert row["pac_fecha_nacimiento"] == "02/01/1980"
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def _last_report() -> dict:
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()[-1]
|
||||
|
||||
|
||||
def test_the_import_report_lists_unused_captions_never_their_values(client, tmp_path, monkeypatch):
|
||||
"""Captions the documents print that nothing in the import used are
|
||||
listed with how many records print them, and none of their values
|
||||
reaches the report. Below the minimum count they are only counted.
|
||||
Fails if `unused_captions` stops reaching the audit, lists a caption
|
||||
the mapping uses, or lets a value through."""
|
||||
import json
|
||||
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path), column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"}
|
||||
)
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "1")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {"Tipo de persona": 1, "Domicilio actual": 1}
|
||||
text = json.dumps(_last_report(), ensure_ascii=False)
|
||||
assert "Mujer" not in text and "64000" not in text and "02/01/1980" not in text
|
||||
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "2")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {} and report["etiquetas_sin_usar_poco_frecuentes"] == 2
|
||||
@@ -9,7 +9,6 @@ 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")
|
||||
@@ -62,91 +61,6 @@ def test_sql_server_url_is_built_from_form_fields():
|
||||
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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user