Files
WebApi/tests/test_imports_multisource_mysql.py

164 lines
6.2 KiB
Python

"""Fills `cacu.Paciente` from a MySQL legacy table, a CSV and a JSON file in
one batch, through the HTTP endpoints with the `pymysql` driver.
Skipped unless `MYSQL_TEST_URL` is set; see `tests/test_connectors_mysql.py`
for a local setup.
"""
import base64
import json
import os
import pytest
import sqlalchemy as sa
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set")
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")
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(scope="module")
def mysql_legacy_source():
"""A legacy MySQL table whose column names and types are unrelated to
`Core`'s `Paciente`."""
engine = sa.create_engine(MYSQL_TEST_URL)
table_name = "test_multisource_legacy_patients"
with engine.begin() as conn:
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
conn.execute(
sa.text(
f"CREATE TABLE {table_name} ("
" expediente VARCHAR(40) NOT NULL PRIMARY KEY,"
" sexo_paciente ENUM('F','M')"
") ENGINE=InnoDB"
)
)
conn.execute(
sa.text(
f"INSERT INTO {table_name} (expediente, sexo_paciente) VALUES "
"('MYSQL-MULTI-1', 'F'), ('MYSQL-MULTI-2', 'M')"
)
)
yield table_name
with engine.begin() as conn:
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
engine.dispose()
def test_sql_source_http_endpoints_browse_real_mysql_schema(client, mysql_legacy_source):
"""The schema-browsing flow the WebApp SQL wizard drives (test-connection
-> schemas -> tables -> columns -> preview) against MySQL."""
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": MYSQL_TEST_URL})
assert test_conn.status_code == 200
assert test_conn.get_json()["dialect"] == "mysql"
schemas = client.post("/imports/sources/sql/schemas", json={"connection_string": MYSQL_TEST_URL})
assert "hospital_legacy" in schemas.get_json()["schemas"]
tables = client.post(
"/imports/sources/sql/tables", json={"connection_string": MYSQL_TEST_URL, "schema": "hospital_legacy"}
)
assert mysql_legacy_source in tables.get_json()["tables"]
columns = client.post(
"/imports/sources/sql/columns",
json={"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source, "schema": "hospital_legacy"},
)
assert {c["name"] for c in columns.get_json()["columns"]} == {"expediente", "sexo_paciente"}
preview = client.post(
"/imports/sources/sql/preview",
json={
"connection_string": MYSQL_TEST_URL,
"table": mysql_legacy_source,
"schema": "hospital_legacy",
"target": "cacu.Paciente",
},
)
assert preview.status_code == 200
body = preview.get_json()
assert body["total_rows"] == 2
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
# "expediente" is a column_matcher synonym for pac_id_hospital.
assert suggested.get("expediente") == "pac_id_hospital"
def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_legacy_source):
csv_bytes = b"pac_id_hospital,pac_sexo\nCSV-MULTI-1,F\n"
csv_source = {
"source_type": "csv",
"target": "cacu.Paciente",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
}
json_records = [{"id_hospital": "JSON-MULTI-1", "sexo": "M"}]
json_source = {
"source_type": "json",
"target": "cacu.Paciente",
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo"},
"payload": {"file_base64": base64.b64encode(json.dumps(json_records).encode()).decode()},
}
sql_source = {
"source_type": "sql",
"target": "cacu.Paciente",
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
}
response = client.post(
"/imports/commit",
json={"sources": [csv_source, json_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"] * 3
# csv: 1 row, json: 1 row, mysql: 2 rows
assert [r["created"] for r in body["results"]] == [1, 1, 2]
assert {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"} <= set(_patients(client))
def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_legacy_source):
sql_source = {
"source_type": "sql",
"target": "cacu.Paciente",
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
}
assert client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"}).status_code == 200
engine = sa.create_engine(MYSQL_TEST_URL)
with engine.begin() as conn:
conn.execute(
sa.text(f"UPDATE {mysql_legacy_source} SET sexo_paciente = 'M' WHERE expediente = 'MYSQL-MULTI-1'")
)
engine.dispose()
response = client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"})
assert response.status_code == 200
result = response.get_json()["results"][0]
# Upsert reports "updated" for every row that already existed, changed or not.
assert result["updated"] == 2
assert result["created"] == 0
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
assert _patients(client)["MYSQL-MULTI-1"]["pac_sexo"] == "Masculino"