add import audit trail, live indicator recompute, reportes endpoints; production hardening
This commit is contained in:
+4
-16
@@ -13,7 +13,7 @@ import pytest
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql,oracle")
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql")
|
||||
# The import log and the indicator queue write files; keep them out of the tree.
|
||||
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
||||
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
||||
@@ -66,21 +66,9 @@ SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def sembrar_base(proyecto: str, motor) -> None:
|
||||
"""La base de demostración del kit: staging sintético, carga y todos los indicadores calculados.
|
||||
|
||||
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
|
||||
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
|
||||
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
|
||||
meses).
|
||||
"""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
|
||||
base_de_prueba(motor, proyecto)
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Generador para la fixture `client` de un proyecto: una base SQLite temporal ya sembrada."""
|
||||
"""Yields a client over a temporary SQLite database seeded with the kit's demonstration data."""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
from persistance import db
|
||||
from persistance.settings import settings
|
||||
|
||||
@@ -90,7 +78,7 @@ def cliente_de(proyecto: str, tmp_path_factory):
|
||||
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
|
||||
obtener_motor.cache_clear()
|
||||
try:
|
||||
sembrar_base(proyecto, obtener_motor())
|
||||
base_de_prueba(obtener_motor(), proyecto)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
|
||||
@@ -5,19 +5,6 @@ import pytest
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
engine = persistance_db.get_cacu_engine()
|
||||
|
||||
from sqlmodel import Session
|
||||
|
||||
with Session(engine) as session:
|
||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
session.commit()
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
@@ -31,26 +18,3 @@ def test_health(client):
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_get_paciente(client):
|
||||
response = client.get("/cacu/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "H-1"
|
||||
|
||||
|
||||
def test_get_paciente_not_found(client):
|
||||
response = client.get("/cacu/pacientes/999")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_predict_not_implemented(client):
|
||||
response = client.post("/cacu/predict")
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_api_index_lists_routes_with_summaries():
|
||||
from webapi import create_app
|
||||
|
||||
routes = {r["path"]: r for r in create_app().test_client().get("/api").get_json()["routes"]}
|
||||
assert routes["/imports/connectors"]["methods"] == ["GET"]
|
||||
assert routes["/governance/model-versions/<domain>/<scenario>/<version>/promote"]["summary"].startswith("Puts the version in production")
|
||||
|
||||
@@ -13,7 +13,7 @@ from webapi.imports.connectors.sql import SqlConnector
|
||||
def test_csv_connector_reads_columns_and_rows():
|
||||
raw = b"nombre,edad\nAna,30\nLuis,40\n"
|
||||
connector = CsvConnector(raw)
|
||||
columns = {c.name: c.inferred_type for c in connector.get_columns()}
|
||||
columns = {c.name: c.inferred_type for c in connector.preview().columns}
|
||||
assert columns == {"nombre": "string", "edad": "integer"}
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
@@ -26,7 +26,7 @@ def test_csv_connector_reads_columns_and_rows():
|
||||
def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
raw = b"cp,exp\n01000,007\n,H-2\n"
|
||||
connector = CsvConnector(raw)
|
||||
assert {c.name: c.inferred_type for c in connector.get_columns()} == {"cp": "string", "exp": "string"}
|
||||
assert {c.name: c.inferred_type for c in connector.preview().columns} == {"cp": "string", "exp": "string"}
|
||||
rows = list(connector.read_rows({"cp": "pac_codigo_postal", "exp": "pac_id_hospital"}))
|
||||
assert rows == [
|
||||
{"pac_codigo_postal": "01000", "pac_id_hospital": "007"},
|
||||
@@ -36,14 +36,14 @@ def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
|
||||
def test_csv_connector_single_column_file():
|
||||
connector = CsvConnector(b"id\nH3\nH4\n")
|
||||
assert [c.name for c in connector.get_columns()] == ["id"]
|
||||
assert [c.name for c in connector.preview().columns] == ["id"]
|
||||
assert connector.metadata()["delimiter"] == ","
|
||||
|
||||
|
||||
def test_csv_connector_sniffs_semicolons_and_strips_excel_bom():
|
||||
raw = "\ufeffExpediente;Sexo\nH-1;F\n".encode("utf-8")
|
||||
connector = CsvConnector(raw)
|
||||
assert [c.name for c in connector.get_columns()] == ["Expediente", "Sexo"]
|
||||
assert [c.name for c in connector.preview().columns] == ["Expediente", "Sexo"]
|
||||
assert connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_csv_connector_bad_bytes_raise_connector_error():
|
||||
def test_json_connector_reads_list_of_records():
|
||||
raw = b'[{"nombre": "Ana", "edad": 30}, {"nombre": "Luis", "edad": 40}]'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
@@ -69,7 +69,7 @@ def test_json_connector_reads_list_of_records():
|
||||
def test_json_connector_reads_wrapped_data_key():
|
||||
raw = b'{"data": [{"nombre": "Ana"}]}'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre"}
|
||||
|
||||
|
||||
def test_json_connector_bad_json_raises_connector_error():
|
||||
@@ -83,7 +83,7 @@ def test_excel_connector_reads_columns_and_rows():
|
||||
pd.DataFrame({"nombre": ["Ana", "Luis"], "edad": [30, 40]}).to_excel(buffer, index=False, engine="openpyxl")
|
||||
connector = ExcelConnector(buffer.getvalue())
|
||||
assert connector.list_sheets() == ["Sheet1"]
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ def test_select_table_then_connector_abc_roundtrip():
|
||||
candidate = connector.detect_tables()[0]
|
||||
connector.select_table(candidate.page_number, candidate.bbox)
|
||||
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"pac_id_hospital", "pac_sexo"}
|
||||
|
||||
preview = connector.preview(limit=1)
|
||||
@@ -204,7 +204,7 @@ def test_select_table_out_of_range_page_raises_connector_error():
|
||||
def test_read_rows_before_resolution_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.get_columns()
|
||||
connector.preview().columns
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
@@ -288,6 +288,19 @@ def test_two_page_apply_to_every_page_regions():
|
||||
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
|
||||
|
||||
|
||||
def test_regions_on_different_pages_still_give_rectangular_rows():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == 6
|
||||
assert result["age"][3:] == [None, None, None]
|
||||
assert len(list(connector.read_rows({"name": "name", "age": "age"}))) == 6
|
||||
|
||||
|
||||
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
@@ -295,7 +308,7 @@ def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
connector.extract_regions(regions)
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"name", "age"}
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Endpoint tests for `/governance/*` and the `/cacu/predict`,`/cama/predict`
|
||||
MLD-4/MLD-5 wiring through `models.prediction.PredictionService`."""
|
||||
"""Endpoint tests for `/governance/*`."""
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
@@ -43,34 +42,35 @@ def client(wire_domain):
|
||||
del os.environ["MLFLOW_TRACKING_URI"]
|
||||
|
||||
|
||||
def test_predict_without_model_version_is_501(client):
|
||||
"""CaCuModel.predict is not implemented yet; no seeded MLflow version is
|
||||
needed to reach that state."""
|
||||
response = client.post("/cacu/predict", json={"pac_id_hospital": "H-1", "data": {"edad": 40}})
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_list_model_versions_empty(client):
|
||||
response = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "tamizaje-vacio"})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"model_versions": []}
|
||||
|
||||
|
||||
def _cohort(tag: str) -> int:
|
||||
from core.governance.models import CohortVersion
|
||||
from persistance.governance import cohort_version_repository
|
||||
def _armado(tag: str) -> int:
|
||||
"""A CaCu cohort build with one attrition step; returns its `armado_id`."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
cohort = CohortVersion(
|
||||
domain="cacu", scenario="tamizaje", criteria_version="v1", version_hash=f"hash-{tag}",
|
||||
source_table="cacu.episodioclinico", n_source=5, n_included=5,
|
||||
)
|
||||
return cohort_version_repository.create(cohort).cohort_version_id
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
armado = CohorteArmado(
|
||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
||||
datos_as_of=date(2025, 12, 31), huella=f"huella-{tag}", marco_sha="m", n_miembros=5,
|
||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(armado)
|
||||
session.flush()
|
||||
session.add(CohorteExclusion(armado_id=armado.armado_id, orden=1, paso="candidatas", n=5))
|
||||
session.commit()
|
||||
return armado.armado_id
|
||||
|
||||
|
||||
def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
body = {
|
||||
"domain": "cacu", "scenario": scenario, "environment": "PROD",
|
||||
"cohort_version_id": _cohort(tag), "metrics": {"auc": 0.8},
|
||||
"cohorte_armado_id": _armado(tag), "metrics": {"auc": 0.8},
|
||||
"technical_validation_report_uri": "docs/tecnica.pdf",
|
||||
"clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html",
|
||||
@@ -108,12 +108,11 @@ def test_model_version_lifecycle_over_http(client):
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
assert lineage["cohort_version"]["version_hash"] == "hash-v2"
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
|
||||
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
|
||||
assert lineage["artifacts"]
|
||||
|
||||
diff = client.get("/governance/model-versions/cacu/lifecycle/compare", query_string={"a": first["version"], "b": second["version"]}).get_json()
|
||||
assert diff["metrics"][0]["delta"] == pytest.approx(0.06)
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
@@ -136,77 +135,12 @@ def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999").status_code == 404
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_scenarios_and_build(client, monkeypatch):
|
||||
from models import cohort
|
||||
|
||||
class Demo(cohort.CohortBuilder):
|
||||
domain, scenario, criteria_version = "cacu", "demo", "v1"
|
||||
criteria = [cohort.ExclusionCriterion("SIN_CIE", "sin_codigo", lambda e: not e.get("cie10_codigo"), applicable_in_production=True)]
|
||||
|
||||
def fetch_episodes(self):
|
||||
return [{"episodio_id": 1, "pac_id_hospital": "H-1", "cie10_codigo": "C53"}, {"episodio_id": 2, "pac_id_hospital": "H-2"}]
|
||||
|
||||
monkeypatch.setitem(cohort.COHORT_BUILDERS, ("cacu", "demo"), Demo)
|
||||
[scenario] = [s for s in client.get("/governance/cohort-scenarios").get_json()["scenarios"] if s["scenario"] == "demo"]
|
||||
assert scenario["criteria"][0]["code"] == "SIN_CIE"
|
||||
built = client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "demo"})
|
||||
assert built.status_code == 201 and built.get_json()["n_included"] == 1
|
||||
assert client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "nope"}).status_code == 404
|
||||
|
||||
|
||||
def test_promote_unknown_model_version_is_404(client):
|
||||
assert client.post("/governance/model-versions/cacu/no-existe/999/promote").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_version_exclusions_endpoint(client):
|
||||
from core.governance.models import CohortExclusion, CohortExclusionCount, CohortVersion
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
)
|
||||
|
||||
cohort = cohort_version_repository.create(
|
||||
CohortVersion(
|
||||
domain="cacu",
|
||||
scenario="tamizaje",
|
||||
criteria_version="v1",
|
||||
version_hash="hash123",
|
||||
source_table="cacu.episodioclinico",
|
||||
n_source=10,
|
||||
n_included=8,
|
||||
)
|
||||
)
|
||||
cohort_exclusion_repository.create(
|
||||
CohortExclusion(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
pac_id_hospital="H-9",
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
)
|
||||
)
|
||||
cohort_exclusion_count_repository.create(
|
||||
CohortExclusionCount(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
count=2,
|
||||
)
|
||||
)
|
||||
|
||||
response = client.get(f"/governance/cohort-versions/{cohort.cohort_version_id}/exclusions")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["counts"][0]["count"] == 2
|
||||
assert body["detail"][0]["pac_id_hospital"] == "H-9"
|
||||
|
||||
|
||||
def test_ocr_run_unknown_job_is_400(client):
|
||||
def test_ocr_run_unknown_job_is_404(client):
|
||||
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
|
||||
assert response.status_code == 400
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "nothing was written" in response.get_json()["error"]
|
||||
assert "no se escribió nada" in response.get_json()["error"]
|
||||
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ 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")
|
||||
@@ -81,8 +86,7 @@ def test_validate_reports_row_errors_without_writing(client):
|
||||
assert body["valid_count"] == 1
|
||||
assert body["error_count"] == 1
|
||||
assert body["errors"][0]["field"] == "pac_id_hospital"
|
||||
# not written
|
||||
assert client.get("/cacu/pacientes/999").status_code == 404
|
||||
assert "H-VALIDATE-1" not in _patients(client)
|
||||
|
||||
|
||||
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
||||
@@ -115,12 +119,7 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client,
|
||||
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
|
||||
|
||||
# First test in this file to write into cacu.Paciente, so autoincrement
|
||||
# ids 1/2 are deterministic (pytest runs this module's tests in
|
||||
# definition order).
|
||||
created_hospital_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in (1, 2)}
|
||||
assert created_hospital_ids == {"H-BATCH-1", "H-SQL-BATCH-1"}
|
||||
assert {"H-BATCH-1", "H-SQL-BATCH-1"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
@@ -129,7 +128,7 @@ def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
assert "domain" in response.get_json()["error"].lower()
|
||||
assert "dominios" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_commit_on_conflict_reject_then_upsert(client):
|
||||
@@ -179,8 +178,8 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
assert body["results"][0]["created"] == 0
|
||||
assert body["results"][0]["updated"] == 1
|
||||
|
||||
paciente = client.get("/tea/pacientes/9001").get_json()
|
||||
assert paciente["pac_id_hospital"] == "T-SRC-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"
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,12 @@ 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 — no real MySQL server to test against")
|
||||
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")
|
||||
@@ -129,13 +134,18 @@ def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_leg
|
||||
# csv: 1 row, json: 1 row, mysql: 2 rows
|
||||
assert [r["created"] for r in body["results"]] == [1, 1, 2]
|
||||
|
||||
all_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in range(1, 5)}
|
||||
assert all_ids == {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-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):
|
||||
# MYSQL-MULTI-1 already exists (created above with sexo 'F'). Mutate the
|
||||
# source row and re-import with on_conflict=upsert.
|
||||
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(
|
||||
@@ -143,22 +153,11 @@ def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_l
|
||||
)
|
||||
engine.dispose()
|
||||
|
||||
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": [sql_source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 200
|
||||
result = response.get_json()["results"][0]
|
||||
# Both rows already exist from the previous test. Upsert reports
|
||||
# "updated" for every conflicting row whether or not its values changed,
|
||||
# per Repository.bulk_upsert's contract.
|
||||
# Upsert reports "updated" for every row that already existed, changed or not.
|
||||
assert result["updated"] == 2
|
||||
assert result["created"] == 0
|
||||
|
||||
updated = client.get("/cacu/pacientes/3").get_json()
|
||||
assert updated["pac_id_hospital"] == "MYSQL-MULTI-1"
|
||||
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
|
||||
assert updated["pac_sexo"] == "Masculino"
|
||||
assert _patients(client)["MYSQL-MULTI-1"]["pac_sexo"] == "Masculino"
|
||||
|
||||
@@ -18,6 +18,11 @@ from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
|
||||
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")
|
||||
@@ -166,10 +171,7 @@ def test_pdf_table_round_trip_detect_preview_validate_commit(client):
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 2
|
||||
|
||||
# this is the first write into cacu.Paciente in this module's temp DB
|
||||
created = client.get("/cacu/pacientes/1")
|
||||
assert created.status_code == 200
|
||||
assert created.get_json()["pac_id_hospital"] == "H-PDF-TAB-1"
|
||||
assert "H-PDF-TAB-1" in _patients(client)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
@@ -120,14 +120,6 @@ def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, quer
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_paciente_por_id_entero(client):
|
||||
response = client.get("/tea/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "T-01"
|
||||
|
||||
assert client.get("/tea/pacientes/abc").status_code == 404
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
"""The Hamilton pipeline computes exactly what Orquestacion's own executor does."""
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Session
|
||||
|
||||
|
||||
def _seed_and_run(proyecto, tmp_path, run):
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.conexion import apuntar
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
url = f"sqlite:///{tmp_path / f'{proyecto}.db'}"
|
||||
apuntar(proyecto, url)
|
||||
ctx = Contexto(proyecto, 2025, 2025, permitir_sin_definir=True, repos=repositorios_de(proyecto))
|
||||
correr_orquestacion(ctx, solo=["migrar"])
|
||||
with Session(sa.create_engine(url)) as sesion:
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
run(ctx)
|
||||
engine = sa.create_engine(url)
|
||||
with engine.connect() as conn:
|
||||
reports = conn.execute(sa.text(
|
||||
"SELECT measure_url, periodo_id, status, tipo FROM measure_report ORDER BY 1, 2, 3, 4")).all()
|
||||
units = conn.execute(sa.text(
|
||||
"SELECT r.measure_url, r.periodo_id, u.grupo, u.unidad_id, u.resultado_id, u.valor_id, u.numero "
|
||||
"FROM measure_report_unidad u JOIN measure_report r USING (report_id) ORDER BY 1, 2, 3, 4, 5")).all()
|
||||
engine.dispose()
|
||||
return reports, units
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "tea"])
|
||||
def test_hamilton_matches_the_orquestacion_executor(proyecto, tmp_path_factory):
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
|
||||
from webapi.pipeline import correr as correr_hamilton
|
||||
|
||||
nombres = None
|
||||
|
||||
def by_executor(ctx):
|
||||
nonlocal nombres
|
||||
nombres = [p.arista for p in correr_orquestacion(ctx) if p.arista != "migrar"]
|
||||
|
||||
expected = _seed_and_run(proyecto, tmp_path_factory.mktemp("orquestacion"), by_executor)
|
||||
got = _seed_and_run(proyecto, tmp_path_factory.mktemp("hamilton"),
|
||||
lambda ctx: correr_hamilton(ctx, solo=nombres))
|
||||
assert expected[0] and expected[1]
|
||||
assert got == expected
|
||||
+1
-22
@@ -105,7 +105,7 @@ def test_indicators_recompute_from_imported_rows(client):
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["arista"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert client.get("/cacu/indicadores").get_json()
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
@@ -136,24 +136,3 @@ def test_headerless_csv_logs_shapes(client):
|
||||
raw = json.dumps(_log()[-1])
|
||||
assert "N-0001" not in raw and "1980-01-01" not in raw
|
||||
assert "A-9999" in raw
|
||||
|
||||
|
||||
def test_hamilton_pipeline_orders_the_kit_steps_like_the_graph():
|
||||
"""Same steps, same dependency order as Orquestacion's own graph."""
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.aristas import FUENTES, aristas_de
|
||||
from orquestacion.grafo import orden
|
||||
|
||||
from webapi.pipeline import _order, modulo
|
||||
from hamilton import driver
|
||||
|
||||
for proyecto in ("tea", "cacu", "cama"):
|
||||
aristas = aristas_de(proyecto)
|
||||
dr = driver.Builder().with_modules(modulo(Contexto(proyecto, 2025, 2025), aristas)).build()
|
||||
nombres = [a.nombre for a in aristas]
|
||||
hamilton_order = _order(dr, nombres)
|
||||
graph_order = [a.nombre for a in orden(aristas, FUENTES)]
|
||||
assert set(hamilton_order) == set(graph_order)
|
||||
for arista in aristas:
|
||||
for anterior in dr.graph.nodes[arista.nombre].dependencies:
|
||||
assert hamilton_order.index(anterior.name) < hamilton_order.index(arista.nombre)
|
||||
|
||||
+14
-17
@@ -1,7 +1,7 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.mapping.column_matcher import suggest_mapping
|
||||
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema
|
||||
from webapi.imports.schemas.classify import ErrorCategory, classify_error
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
@@ -88,10 +88,9 @@ def test_validate_rows_never_aborts_on_a_bad_row():
|
||||
|
||||
|
||||
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
||||
|
||||
suggestions = matcher.suggest(
|
||||
suggestions = suggest_mapping(
|
||||
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
||||
)
|
||||
by_source = {s.source_column: s for s in suggestions}
|
||||
@@ -110,9 +109,8 @@ def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
|
||||
|
||||
def test_column_matcher_enforces_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
# two source columns that would both match "pac_sexo" exactly-ish
|
||||
suggestions = matcher.suggest(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
suggestions = suggest_mapping(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
matched_targets = [s.target_field for s in suggestions if s.target_field]
|
||||
assert matched_targets == ["pac_sexo"] # only the first claims it
|
||||
|
||||
@@ -134,14 +132,14 @@ def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dat
|
||||
|
||||
def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns():
|
||||
from core.cacu.enums import SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
assert coerce_alias(" femenino ", catalog) == "Femenino"
|
||||
assert coerce_alias("m", catalog) == "Masculino"
|
||||
assert coerce_alias("", catalog) is None
|
||||
assert catalog.coerce(" femenino ") == "Femenino"
|
||||
assert catalog.coerce("m") == "Masculino"
|
||||
assert catalog.coerce("") is None
|
||||
with pytest.raises(ValueError, match="no está en el catálogo"):
|
||||
coerce_alias("X", catalog)
|
||||
catalog.coerce("X")
|
||||
|
||||
|
||||
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
@@ -150,11 +148,11 @@ def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
only models the base B0-B6 categories; without an alias for them, every
|
||||
such report was silently unimportable."""
|
||||
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
||||
assert coerce_alias(value, catalog) == "B4"
|
||||
assert catalog.coerce(value) == "B4"
|
||||
|
||||
|
||||
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
@@ -167,11 +165,10 @@ def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
|
||||
|
||||
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
||||
by_source = {
|
||||
s.source_column: s
|
||||
for s in matcher.suggest(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
for s in suggest_mapping(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
}
|
||||
assert by_source["Género"].target_field == "pac_sexo"
|
||||
assert by_source["C.P."].target_field == "pac_codigo_postal"
|
||||
@@ -183,7 +180,7 @@ def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
|
||||
|
||||
def test_column_matcher_matches_names_without_the_table_prefix():
|
||||
suggestion = ColumnMatcher().suggest(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
suggestion = suggest_mapping(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
assert [(s.target_field, s.reason) for s in suggestion] == [("hemoglobina_g_dl", "exact"), ("mast_birads", "unprefixed")]
|
||||
|
||||
|
||||
@@ -206,14 +203,14 @@ def test_column_matcher_real_world_headers(target, source, expected):
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY[target].schema.model_fields)
|
||||
assert ColumnMatcher().suggest([source], fields)[0].target_field == expected
|
||||
assert suggest_mapping([source], fields)[0].target_field == expected
|
||||
|
||||
|
||||
def test_column_matcher_does_not_guess_from_shared_letters_alone():
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY["cacu.NotaMedica"].schema.model_fields)
|
||||
assert ColumnMatcher().suggest(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
assert suggest_mapping(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
|
||||
|
||||
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
|
||||
@@ -31,36 +31,6 @@ def test_every_registered_schema_is_constructible(entity_key):
|
||||
schema_cls()
|
||||
|
||||
|
||||
def test_entity_registry_has_twenty_four_entries():
|
||||
assert len(ENTITY_REGISTRY) == 24
|
||||
|
||||
|
||||
def test_entity_registry_keys_cover_all_three_domains():
|
||||
keys = set(ENTITY_REGISTRY.keys())
|
||||
assert "cacu.Paciente" in keys
|
||||
assert "cacu.OrdenesEstudio" in keys
|
||||
assert "cacu.CitologiaCervical" in keys
|
||||
assert "cacu.BiopsiaCervical" in keys
|
||||
assert "cacu.NotaMedica" in keys
|
||||
assert "cacu.BiometriaHematica" in keys
|
||||
assert "cacu.EpisodioClinico" in keys
|
||||
assert "cama.Paciente" in keys
|
||||
assert "cama.OrdenesEstudio" in keys
|
||||
assert "cama.Mastografia" in keys
|
||||
assert "cama.BiopsiaMama" in keys
|
||||
assert "cama.NotaMedica" in keys
|
||||
assert "cama.BiometriaHematica" in keys
|
||||
assert "cama.EpisodioClinico" in keys
|
||||
assert "tea.Pacientes" in keys
|
||||
assert "tea.OrdenesEstudio" in keys
|
||||
assert "tea.NotaMedica" in keys
|
||||
assert "tea.EvaluacionPsicologica" in keys
|
||||
assert "tea.PotencialesEvocadosAuditivos" in keys
|
||||
assert "tea.EegEstudio" in keys
|
||||
assert "tea.AntecedentesMaternosGestacion" in keys
|
||||
assert "tea.PartoNeonatal" in keys
|
||||
|
||||
|
||||
# --- Spot checks -----------------------------------------------------------
|
||||
# CaMa entity with a required, unique integer ord_numero_hospital and an
|
||||
# *_ALIAS-backed enum field.
|
||||
|
||||
@@ -59,3 +59,48 @@ def test_natural_key_wins_over_a_foreign_internal_id(client):
|
||||
paciente = next(p for p in paciente_repository.list() if p.pac_id_hospital == "CSV-1")
|
||||
nota = next(n for n in nota_medica_repository.list() if n.nm_id_hospital == "N-1")
|
||||
assert nota.pac_id == paciente.pac_id != 999
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tea_client(wire_domain):
|
||||
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
|
||||
|
||||
|
||||
def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
|
||||
sources = [
|
||||
_json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"),
|
||||
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
|
||||
_json([{"psi_id": "psi-1", "psi_ord_id": "ord-1", "psi_pac_id": 1}], "tea.EvaluacionPsicologica"),
|
||||
_json([{"ins_psi_id": "psi-1", "ins_instrumento": "ADOS-2"}], "tea.InstrumentoAplicado"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.EegEstudio"),
|
||||
_json([{"seg_eeg_id": "eeg-1", "seg_duracion_s": 30}], "tea.EegSegmento"),
|
||||
]
|
||||
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.tea import (
|
||||
eeg_estudio_repository,
|
||||
eeg_segmento_repository,
|
||||
evaluacion_psicologica_repository,
|
||||
instrumento_aplicado_repository,
|
||||
)
|
||||
|
||||
assert eeg_estudio_repository.get(eeg_segmento_repository.list()[0].seg_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
evaluacion = evaluacion_psicologica_repository.get(instrumento_aplicado_repository.list()[0].ins_psi_id)
|
||||
assert evaluacion.psi_ord_id == "ord-1"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio")
|
||||
assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
[fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
assert len(fila.eeg_id) == 36
|
||||
|
||||
@@ -9,18 +9,18 @@ from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
|
||||
PRODUCTION_POLICY = SqlSourcePolicy(
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql", "oracle"}), allowed_hosts=None
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql"}), allowed_hosts=None
|
||||
)
|
||||
|
||||
|
||||
def test_sqlite_is_refused_by_default_policy(tmp_path):
|
||||
with pytest.raises(ConnectorError, match="dialect 'sqlite' is not allowed"):
|
||||
with pytest.raises(ConnectorError, match="'sqlite' no está permitido"):
|
||||
SqlConnector(f"sqlite:///{tmp_path / 'x.db'}", policy=PRODUCTION_POLICY)
|
||||
|
||||
|
||||
def test_host_allowlist_is_enforced():
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=frozenset({"10.0.10.50"}))
|
||||
with pytest.raises(ConnectorError, match="not in the allowed"):
|
||||
with pytest.raises(ConnectorError, match="no está entre los permitidos"):
|
||||
policy.check_url("mysql+pymysql://u:p@evil.example.com/db")
|
||||
assert policy.check_url("mysql+pymysql://u:p@10.0.10.50/db").host == "10.0.10.50"
|
||||
|
||||
@@ -31,16 +31,25 @@ def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
|
||||
own = tmp_path / "cacu.db"
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", f"sqlite:///{own}")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"sqlite"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url(f"sqlite:///{own}")
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cama_database_url", "mysql+pymysql://app:pw@db.internal:3306/isss_cama")
|
||||
mysql_policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
mysql_policy.check_url("mysql+pymysql://someone_else:pw@DB.internal:3306/isss_cama")
|
||||
mysql_policy.check_url("mysql+pymysql://app:pw@db.internal:3306/hospital_legacy")
|
||||
|
||||
|
||||
def test_an_explicit_default_port_does_not_bypass_the_own_database_check(monkeypatch):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", "mysql+pymysql://app:pw@db/isss_cacu")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url("mysql+pymysql://app:pw@db:3306/isss_cacu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user