Parse pasted server addresses and carry SQL columns as document fields
This commit is contained in:
@@ -57,6 +57,118 @@ 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",
|
||||
|
||||
@@ -9,6 +9,7 @@ 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")
|
||||
@@ -61,6 +62,91 @@ 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