228 lines
9.6 KiB
Python
228 lines
9.6 KiB
Python
import base64
|
|
import io
|
|
import json
|
|
|
|
import pytest
|
|
from sqlalchemy import create_engine, text
|
|
|
|
|
|
def _patients(client) -> dict[str, dict]:
|
|
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
|
return {row["pac_id_hospital"]: row for row in rows}
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def client(wire_domain):
|
|
wire_domain("cacu")
|
|
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
|
|
|
|
|
|
_PACIENTE_MAPPING = {
|
|
"pac_id_hospital": "pac_id_hospital",
|
|
"pac_sexo": "pac_sexo",
|
|
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
|
}
|
|
|
|
|
|
def _csv_source(csv_bytes: bytes, *, target: str, column_mapping: dict | None = None) -> dict:
|
|
return {
|
|
"source_type": "csv",
|
|
"target": target,
|
|
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
|
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
|
}
|
|
|
|
|
|
def _json_source(records: list[dict], *, target: str, column_mapping: dict | None = None) -> dict:
|
|
raw = json.dumps(records).encode()
|
|
return {
|
|
"source_type": "json",
|
|
"target": target,
|
|
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
|
"payload": {"file_base64": base64.b64encode(raw).decode()},
|
|
}
|
|
|
|
|
|
def test_get_targets_lists_registered_entities(client):
|
|
response = client.get("/imports/targets")
|
|
assert response.status_code == 200
|
|
keys = {t["key"] for t in response.get_json()["targets"]}
|
|
assert {"cacu.Paciente", "tea.Pacientes"} <= keys
|
|
cacu_target = next(t for t in response.get_json()["targets"] if t["key"] == "cacu.Paciente")
|
|
assert cacu_target["conflict_fields"] == ["pac_id_hospital"]
|
|
assert any(f["name"] == "pac_id_hospital" and f["required"] for f in cacu_target["fields"])
|
|
|
|
|
|
def test_file_preview_returns_columns_sample_rows_and_suggested_mapping(client):
|
|
csv_bytes = b"pac_id_hospital,Sexo\nH-PREVIEW-1,F\n"
|
|
data = {
|
|
"file": (io.BytesIO(csv_bytes), "pacientes.csv"),
|
|
"source_kind": "csv",
|
|
"target": "cacu.Paciente",
|
|
}
|
|
response = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data")
|
|
assert response.status_code == 200
|
|
body = response.get_json()
|
|
assert {c["name"] for c in body["columns"]} == {"pac_id_hospital", "Sexo"}
|
|
assert body["total_rows"] == 1
|
|
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
|
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
|
assert suggested["Sexo"] == "pac_sexo"
|
|
|
|
|
|
def test_validate_reports_row_errors_without_writing(client):
|
|
csv_bytes = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-VALIDATE-1,F,1990-01-01\n,M,1990-01-01\n"
|
|
response = client.post("/imports/validate", json={"source": _csv_source(csv_bytes, target="cacu.Paciente")})
|
|
assert response.status_code == 200
|
|
body = response.get_json()
|
|
assert body["total_rows"] == 2
|
|
assert body["valid_count"] == 1
|
|
assert body["error_count"] == 1
|
|
assert body["errors"][0]["field"] == "pac_id_hospital"
|
|
assert "H-VALIDATE-1" not in _patients(client)
|
|
|
|
|
|
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
|
# A batch can mix file and SQL sources targeting the same domain: here a
|
|
# CSV and a live SQL connection both land in cacu.Paciente in one commit.
|
|
# Uses its own SQL fixture (distinct hospital id) because the row in
|
|
# `sql_source_db` is also used by another test against this cacu.db.
|
|
source_db_path = tmp_path / "batch_source.db"
|
|
source_engine = create_engine(f"sqlite:///{source_db_path}")
|
|
with source_engine.begin() as conn:
|
|
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
|
conn.execute(
|
|
text(
|
|
"INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-BATCH-1', 'M', '1990-01-01')"
|
|
)
|
|
)
|
|
|
|
cacu_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-BATCH-1,F,1990-01-01\n"
|
|
csv_source = _csv_source(cacu_csv, target="cacu.Paciente")
|
|
sql_source = {
|
|
"source_type": "sql",
|
|
"target": "cacu.Paciente",
|
|
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
|
"payload": {"connection_string": f"sqlite:///{source_db_path}", "table": "hospital_patients"},
|
|
}
|
|
|
|
response = client.post("/imports/commit", json={"sources": [csv_source, sql_source], "on_conflict": "reject"})
|
|
assert response.status_code == 200
|
|
body = response.get_json()
|
|
assert body["ok"] is True
|
|
assert [r["target"] for r in body["results"]] == ["cacu.Paciente", "cacu.Paciente"]
|
|
assert sum(r["created"] for r in body["results"]) == 2
|
|
assert {"H-BATCH-1", "H-SQL-BATCH-1"} <= set(_patients(client))
|
|
|
|
|
|
def test_commit_rejects_a_batch_mixing_domains(client):
|
|
cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente")
|
|
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes")
|
|
|
|
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
|
assert response.status_code == 400
|
|
assert "dominios" in response.get_json()["error"]
|
|
|
|
|
|
def test_commit_on_conflict_reject_then_upsert(client):
|
|
first_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,F,1990-01-01\n"
|
|
first = client.post(
|
|
"/imports/commit",
|
|
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
|
)
|
|
assert first.get_json()["results"][0]["created"] == 1
|
|
|
|
reject_again = client.post(
|
|
"/imports/commit",
|
|
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
|
)
|
|
reject_body = reject_again.get_json()["results"][0]
|
|
assert reject_body["created"] == 0
|
|
assert reject_body["rejected"] == 1
|
|
|
|
upsert_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,M,1990-01-01\n"
|
|
upsert = client.post(
|
|
"/imports/commit",
|
|
json={"sources": [_csv_source(upsert_csv, target="cacu.Paciente")], "on_conflict": "upsert"},
|
|
)
|
|
upsert_body = upsert.get_json()["results"][0]
|
|
assert upsert_body["created"] == 0
|
|
assert upsert_body["updated"] == 1
|
|
|
|
|
|
def test_commit_upsert_rejected_for_target_without_natural_key(client):
|
|
source = _json_source(
|
|
[{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"}
|
|
)
|
|
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
|
|
assert response.status_code == 400
|
|
|
|
|
|
def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
|
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}
|
|
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}],
|
|
target="tea.Pacientes", column_mapping=mapping)
|
|
body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json()
|
|
assert body["results"][0]["created"] == 1
|
|
|
|
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}],
|
|
target="tea.Pacientes", column_mapping=mapping)
|
|
body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json()
|
|
assert body["results"][0]["created"] == 0
|
|
assert body["results"][0]["updated"] == 1
|
|
|
|
[paciente] = client.get("/data/tea.Pacientes").get_json()["rows"]
|
|
assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1"
|
|
assert paciente["pac_sexo"] == "M"
|
|
|
|
|
|
@pytest.fixture
|
|
def sql_source_db(tmp_path):
|
|
db_path = tmp_path / "external_source.db"
|
|
url = f"sqlite:///{db_path}"
|
|
engine = create_engine(url)
|
|
with engine.begin() as conn:
|
|
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
|
conn.execute(
|
|
text("INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-1', 'F', '1990-01-01')")
|
|
)
|
|
return url
|
|
|
|
|
|
def test_sql_source_introspection_preview_and_commit(client, sql_source_db):
|
|
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": sql_source_db})
|
|
assert test_conn.status_code == 200
|
|
assert test_conn.get_json()["dialect"] == "sqlite"
|
|
|
|
tables = client.post("/imports/sources/sql/tables", json={"connection_string": sql_source_db})
|
|
assert "hospital_patients" in tables.get_json()["tables"]
|
|
|
|
columns = client.post(
|
|
"/imports/sources/sql/columns", json={"connection_string": sql_source_db, "table": "hospital_patients"}
|
|
)
|
|
assert {c["name"] for c in columns.get_json()["columns"]} == {"id_hospital", "sexo", "nacimiento"}
|
|
|
|
preview = client.post(
|
|
"/imports/sources/sql/preview",
|
|
json={"connection_string": sql_source_db, "table": "hospital_patients", "target": "cacu.Paciente"},
|
|
)
|
|
assert preview.status_code == 200
|
|
assert preview.get_json()["total_rows"] == 1
|
|
|
|
sql_import_source = {
|
|
"source_type": "sql",
|
|
"target": "cacu.Paciente",
|
|
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
|
"payload": {"connection_string": sql_source_db, "table": "hospital_patients"},
|
|
}
|
|
commit_response = client.post("/imports/commit", json={"sources": [sql_import_source], "on_conflict": "reject"})
|
|
assert commit_response.status_code == 200
|
|
assert commit_response.get_json()["results"][0]["created"] == 1
|