integration layer; merge work on indicators from forks with existing ingestion pipeline

This commit is contained in:
Roberto Treviño Cervantes
2026-10-23 00:00:13 -06:00
parent c1444e2b8d
commit 043f7635f4
80 changed files with 7766 additions and 38 deletions
+56
View File
@@ -0,0 +1,56 @@
"""Shared test wiring.
`persistance.settings.settings` is a module-level singleton and the
`persistance.db.get_<domain>_engine` functions are `@lru_cache`d, so changing
`<DOMAIN>_DATABASE_URL` alone has no effect once an engine exists.
`wire_domain` resets all three (env var, singleton, cache).
"""
import os
import tempfile
from pathlib import Path
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")
@pytest.fixture(scope="module")
def wire_domain():
"""Factory fixture: `wire_domain("cacu")` points the domain at a fresh temp
SQLite file for this module and returns its path. Temp files are removed
when the module finishes."""
created_paths: list[str] = []
def _wire(domain: str) -> str:
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
url = f"sqlite:///{db_path}"
os.environ[f"{domain.upper()}_DATABASE_URL"] = url
from persistance import db as persistance_db
from persistance import settings as persistance_settings
setattr(persistance_settings.settings, f"{domain}_database_url", url)
getattr(persistance_db, f"get_{domain}_engine").cache_clear()
created_paths.append(db_path)
_migrate(domain)
return db_path
yield _wire
for path in created_paths:
os.unlink(path)
def _migrate(domain: str) -> None:
"""Builds the schema with the Alembic migrations rather than
`metadata.create_all`, so tests run against the deployed schema and a
broken migration fails the suite."""
from alembic import command
from alembic.config import Config
import persistance
ini = Path(persistance.__file__).parent / domain / "alembic.ini"
command.upgrade(Config(str(ini)), "head")
+15 -13
View File
@@ -1,25 +1,21 @@
import os
import tempfile
import pytest
@pytest.fixture(scope="module")
def client():
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
os.environ["CACU_DATABASE_URL"] = f"sqlite:///{db_path}"
def client(wire_domain):
wire_domain("cacu")
from datetime import date
from core.cacu.base import CaCuModel
from core.cacu.models import Paciente
from persistance.db import get_cacu_engine
from persistance import db as persistance_db
engine = get_cacu_engine()
CaCuModel.metadata.create_all(engine)
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"))
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
@@ -29,8 +25,6 @@ def client():
with app.test_client() as client:
yield client
os.unlink(db_path)
def test_health(client):
response = client.get("/health")
@@ -52,3 +46,11 @@ def test_get_paciente_not_found(client):
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")
+127
View File
@@ -0,0 +1,127 @@
import io
import pytest
from sqlalchemy import create_engine, text
from webapi.imports.connectors.csv_ import CsvConnector
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.excel import ExcelConnector
from webapi.imports.connectors.json_ import JsonConnector
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()}
assert columns == {"nombre": "string", "edad": "integer"}
preview = connector.preview(limit=1)
assert preview.total_rows == 2
assert len(preview.sample_rows) == 1
# Cells stay text; typing is the import schema's job (see CsvConnector).
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
assert rows == [{"pac_nombre": "Ana", "pac_edad": "30"}, {"pac_nombre": "Luis", "pac_edad": "40"}]
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"}
rows = list(connector.read_rows({"cp": "pac_codigo_postal", "exp": "pac_id_hospital"}))
assert rows == [
{"pac_codigo_postal": "01000", "pac_id_hospital": "007"},
{"pac_codigo_postal": None, "pac_id_hospital": "H-2"},
]
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 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 connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
def test_csv_connector_falls_back_to_cp1252():
raw = "nombre\nPeña\n".encode("cp1252")
connector = CsvConnector(raw)
assert list(connector.read_rows({"nombre": "n"})) == [{"n": "Peña"}]
def test_csv_connector_bad_bytes_raise_connector_error():
with pytest.raises(ConnectorError):
CsvConnector(b"\xff\xfe\x00\x01not valid utf-8 csv bytes")
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"}
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
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"}
def test_json_connector_bad_json_raises_connector_error():
with pytest.raises(ConnectorError):
JsonConnector(b"{not valid json")
def test_excel_connector_reads_columns_and_rows():
pd = pytest.importorskip("pandas")
buffer = io.BytesIO()
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"}
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
def test_excel_connector_bad_bytes_raise_connector_error():
with pytest.raises(ConnectorError):
ExcelConnector(b"not an excel file")
@pytest.fixture
def sqlite_source_url(tmp_path):
db_path = tmp_path / "source.db"
url = f"sqlite:///{db_path}"
engine = create_engine(url)
with engine.begin() as conn:
conn.execute(text("CREATE TABLE patients (nombre TEXT, edad INTEGER)"))
conn.execute(text("INSERT INTO patients (nombre, edad) VALUES ('Ana', 30), ('Luis', 40)"))
return url
def test_sql_connector_introspection_and_rows(sqlite_source_url):
connector = SqlConnector(sqlite_source_url)
connector.test_connection()
assert connector.get_dialect() == "sqlite"
assert "patients" in connector.list_tables()
columns = {c.name for c in connector.list_columns("patients")}
assert columns == {"nombre", "edad"}
connector.select_table("patients")
preview = connector.preview()
assert preview.total_rows == 2
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
assert rows == [{"pac_nombre": "Ana", "pac_edad": 30}, {"pac_nombre": "Luis", "pac_edad": 40}]
def test_sql_connector_bad_connection_string_raises_connector_error():
# may fail either at construction (unknown dialect) or at connect time;
# both must surface as ConnectorError rather than a raw sqlalchemy error
with pytest.raises(ConnectorError):
connector = SqlConnector("not-a-real://connection-string")
connector.test_connection()
+91
View File
@@ -0,0 +1,91 @@
"""Exercises `SqlConnector` against a real MySQL server, covering
MySQL-specific reflection (native `ENUM` columns, `pymysql` quirks, DATE
types) that the SQLite-based tests don't reach. Skipped unless
`MYSQL_TEST_URL` is set.
To stand one up locally:
docker run -d --name isssteleon-mysql-test \
-e MYSQL_ROOT_PASSWORD=<root_pw> -e MYSQL_DATABASE=hospital_legacy \
-e MYSQL_USER=<user> -e MYSQL_PASSWORD=<pw> -p 3307:3306 mysql:8.0
export MYSQL_TEST_URL="mysql+pymysql://<user>:<pw>@127.0.0.1:3307/hospital_legacy"
"""
import os
import pytest
import sqlalchemy as sa
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.sql import SqlConnector
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")
@pytest.fixture(scope="module")
def legacy_table():
"""A legacy table whose columns are unrelated to Core's naming, as in a
third-party database we don't control."""
engine = sa.create_engine(MYSQL_TEST_URL)
table_name = "test_connectors_mysql_fixture"
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} ("
" legacy_id VARCHAR(40) NOT NULL PRIMARY KEY,"
" legacy_sexo ENUM('F','M'),"
" legacy_nacimiento DATE"
") ENGINE=InnoDB"
)
)
conn.execute(
sa.text(
f"INSERT INTO {table_name} (legacy_id, legacy_sexo, legacy_nacimiento) VALUES "
"('MYFIX-1', 'F', '1990-01-15'), ('MYFIX-2', 'M', '1985-06-20')"
)
)
yield table_name
with engine.begin() as conn:
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
engine.dispose()
def test_connects_and_reports_mysql_dialect():
connector = SqlConnector(MYSQL_TEST_URL)
connector.test_connection()
assert connector.get_dialect() == "mysql"
def test_introspects_real_mysql_schema(legacy_table):
connector = SqlConnector(MYSQL_TEST_URL)
assert legacy_table in connector.list_tables()
columns = {c.name: c.inferred_type for c in connector.list_columns(legacy_table)}
assert columns["legacy_id"] == "string"
assert columns["legacy_nacimiento"] == "date"
# A native MySQL ENUM column is reflected as a string-like type.
assert columns["legacy_sexo"] == "string"
def test_reads_rows_with_column_mapping_against_real_mysql(legacy_table):
connector = SqlConnector(MYSQL_TEST_URL)
connector.select_table(legacy_table)
preview = connector.preview()
assert preview.total_rows == 2
rows = list(
connector.read_rows({"legacy_id": "pac_id_hospital", "legacy_sexo": "pac_sexo", "legacy_nacimiento": "pac_fecha_nacimiento"})
)
by_id = {r["pac_id_hospital"]: r for r in rows}
assert by_id["MYFIX-1"]["pac_sexo"] == "F"
# Rows come straight from the driver, so a MySQL DATE is a `date`.
import datetime as _dt
assert by_id["MYFIX-1"]["pac_fecha_nacimiento"] == _dt.date(1990, 1, 15)
def test_bad_mysql_credentials_raise_connector_error():
bad_url = MYSQL_TEST_URL.rsplit("@", 1)[-1]
connector = SqlConnector(f"mysql+pymysql://nobody:wrongpassword@{bad_url}")
with pytest.raises(ConnectorError):
connector.test_connection()
+314
View File
@@ -0,0 +1,314 @@
"""Tests for `PdfConnector`. PDF fixtures are generated at test time with
reportlab.
- `build_table_pdf()`: a ruled table with selectable text, for the table
detection path.
- `build_scanned_like_pdf()` / `build_three_column_pdf()`: text rendered into
an image that fills the page, so there is no text layer and only the
OCR/region path applies. The three-column variant uses known values per
row so alignment can be checked.
"""
import difflib
import io
import pytest
from PIL import Image, ImageDraw, ImageFont
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
# The synthetic "scanned" pages are drawn onto an image this size, then
# stretched to fill the whole (letter-size) PDF page, so a normalized
# 0..1 bbox computed from these pixel coordinates lines up with the region
# regardless of the DPI used to re-render the page for OCR.
IMG_W, IMG_H = 900, 1200
COL_X = {"name": 40, "age": 340, "city": 620}
COL_WIDTH = 260
ROW_YS = [120, 320, 520]
ROW_HEIGHT = 100
def _font(size: int = 34) -> ImageFont.ImageFont:
for path in (
"/System/Library/Fonts/Helvetica.ttc",
"/System/Library/Fonts/Supplemental/Arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
):
try:
return ImageFont.truetype(path, size)
except Exception:
continue
return ImageFont.load_default()
def build_table_pdf(rows: list[tuple[str, str]]) -> bytes:
buffer = io.BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter)
data = [["pac_id_hospital", "pac_sexo"], *[[a, b] for a, b in rows]]
table = Table(data)
table.setStyle(
TableStyle(
[
("GRID", (0, 0), (-1, -1), 1, colors.black),
("FONTSIZE", (0, 0), (-1, -1), 12),
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
("TOPPADDING", (0, 0), (-1, -1), 8),
]
)
)
doc.build([table])
return buffer.getvalue()
def _page_image(lines: list[str]) -> Image.Image:
img = Image.new("RGB", (IMG_W, IMG_H), "white")
draw = ImageDraw.Draw(img)
font = _font()
y = 40
for line in lines:
draw.text((40, y), line, fill="black", font=font)
y += 60
return img
def build_scanned_like_pdf(pages_lines: list[list[str]]) -> bytes:
buffer = io.BytesIO()
c = canvas.Canvas(buffer, pagesize=letter)
page_w, page_h = letter
for lines in pages_lines:
img = _page_image(lines)
reader_buf = io.BytesIO()
img.save(reader_buf, format="PNG")
reader_buf.seek(0)
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
c.showPage()
c.save()
return buffer.getvalue()
def _three_column_page_image(rows: list[tuple[str, str, str]]) -> Image.Image:
img = Image.new("RGB", (IMG_W, IMG_H), "white")
draw = ImageDraw.Draw(img)
font = _font()
for y, (name, age, city) in zip(ROW_YS, rows):
draw.text((COL_X["name"], y), name, fill="black", font=font)
draw.text((COL_X["age"], y), age, fill="black", font=font)
draw.text((COL_X["city"], y), city, fill="black", font=font)
return img
def build_three_column_pdf(pages_rows: list[list[tuple[str, str, str]]]) -> bytes:
buffer = io.BytesIO()
c = canvas.Canvas(buffer, pagesize=letter)
page_w, page_h = letter
for rows in pages_rows:
img = _three_column_page_image(rows)
reader_buf = io.BytesIO()
img.save(reader_buf, format="PNG")
reader_buf.seek(0)
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
c.showPage()
c.save()
return buffer.getvalue()
def _norm_bbox(field: str) -> tuple[float, float, float, float]:
x0 = COL_X[field]
x1 = x0 + COL_WIDTH
y0 = ROW_YS[0] - 60
y1 = ROW_YS[-1] + ROW_HEIGHT
return (x0 / IMG_W, y0 / IMG_H, x1 / IMG_W, y1 / IMG_H)
def _similar(a: str, b: str, threshold: float = 0.7) -> bool:
return difflib.SequenceMatcher(None, a.strip().lower(), b.strip().lower()).ratio() >= threshold
ROWS = [("Ana Garcia", "30", "Monterrey"), ("Luis Perez", "40", "Saltillo"), ("Marta Ruiz", "50", "Torreon")]
ROWS_PAGE_2 = [("Elena Diaz", "60", "Chihuahua"), ("Jorge Nava", "22", "Durango"), ("Sofia Reyes", "35", "Culiacan")]
# ---------------------------------------------------------------------
# Classification
# ---------------------------------------------------------------------
def test_has_text_layer_true_for_table_pdf():
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
assert connector.has_text_layer() is True
def test_has_text_layer_false_for_scanned_pdf():
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
assert connector.has_text_layer() is False
def test_malformed_pdf_bytes_raise_connector_error():
with pytest.raises(ConnectorError):
PdfConnector(b"not a pdf at all")
# ---------------------------------------------------------------------
# Ruled table detection
# ---------------------------------------------------------------------
def test_detect_tables_finds_candidate_with_right_shape_on_table_pdf():
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M"), ("H-TAB-3", "F")]))
candidates = connector.detect_tables()
assert len(candidates) == 1
candidate = candidates[0]
assert candidate.page_number == 1
assert len(candidate.grid) == 4 # header + 3 data rows
assert len(candidate.grid[0]) == 2
assert candidate.grid[0] == ["pac_id_hospital", "pac_sexo"]
assert candidate.grid[1][0] == "H-TAB-1"
def test_detect_tables_empty_on_scanned_pdf():
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
assert connector.detect_tables() == []
def test_select_table_then_connector_abc_roundtrip():
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
candidate = connector.detect_tables()[0]
connector.select_table(candidate.page_number, candidate.bbox)
columns = {c.name for c in connector.get_columns()}
assert columns == {"pac_id_hospital", "pac_sexo"}
preview = connector.preview(limit=1)
assert preview.total_rows == 2
assert len(preview.sample_rows) == 1
rows = list(connector.read_rows({"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}))
assert rows == [
{"pac_id_hospital": "H-TAB-1", "pac_sexo": "F"},
{"pac_id_hospital": "H-TAB-2", "pac_sexo": "M"},
]
def test_select_table_out_of_range_page_raises_connector_error():
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
with pytest.raises(ConnectorError):
connector.select_table(99, (0, 0, 100, 100))
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()
# ---------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------
def test_render_page_image_returns_valid_png_with_expected_aspect_ratio():
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
png_bytes = connector.render_page_image(1, dpi=150)
image = Image.open(io.BytesIO(png_bytes))
assert image.format == "PNG"
page_w, page_h = letter
expected_ratio = page_w / page_h
actual_ratio = image.width / image.height
assert abs(actual_ratio - expected_ratio) < 0.01
def test_render_page_image_out_of_range_raises_connector_error():
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
with pytest.raises(ConnectorError):
connector.render_page_image(7)
# ---------------------------------------------------------------------
# OCR / region path
# ---------------------------------------------------------------------
def test_single_region_ocr_matches_known_column():
connector = PdfConnector(build_three_column_pdf([ROWS]))
region = RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name"))
result = connector.extract_regions([region])
assert len(result["name"]) == 3
for actual, (expected, _, _) in zip(result["name"], ROWS):
assert _similar(actual, expected), f"{actual!r} not close enough to {expected!r}"
def test_multi_region_row_alignment_matches_ground_truth():
"""Three columns OCR'd independently must recombine into the rows they
came from."""
connector = PdfConnector(build_three_column_pdf([ROWS]))
regions = [
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
RegionSpec(target_field="city", page_numbers=[1], bbox=_norm_bbox("city")),
]
result = connector.extract_regions(regions)
assert len(result["name"]) == len(result["age"]) == len(result["city"]) == 3
for i, (expected_name, expected_age, expected_city) in enumerate(ROWS):
assert _similar(result["name"][i], expected_name), f"row {i} name mismatch: {result['name'][i]!r}"
assert _similar(result["age"][i], expected_age), f"row {i} age mismatch: {result['age'][i]!r}"
assert _similar(result["city"][i], expected_city), f"row {i} city mismatch: {result['city'][i]!r}"
rows = list(
connector.read_rows({"name": "name", "age": "age", "city": "city"})
)
assert len(rows) == 3
assert _similar(rows[0]["name"], ROWS[0][0])
def test_two_page_apply_to_every_page_regions():
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, 2], bbox=_norm_bbox("age")),
RegionSpec(target_field="city", page_numbers=[1, 2], bbox=_norm_bbox("city")),
]
result = connector.extract_regions(regions)
all_rows = ROWS + ROWS_PAGE_2
assert len(result["name"]) == 6
for i, (expected_name, expected_age, expected_city) in enumerate(all_rows):
assert _similar(result["name"][i], expected_name), f"row {i}: {result['name']}"
assert _similar(result["age"][i], expected_age)
assert _similar(result["city"][i], expected_city)
# page 1's rows precede page 2's, not just correct as a set
assert _similar(result["name"][0], ROWS[0][0])
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
connector = PdfConnector(build_three_column_pdf([ROWS]))
regions = [
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
]
connector.extract_regions(regions)
columns = {c.name for c in connector.get_columns()}
assert columns == {"name", "age"}
def test_split_conflict_records_warning_without_dropping_data():
connector = PdfConnector(build_three_column_pdf([ROWS]))
connector.warnings = []
lines = [
{"target_field": "a", "y": 100, "height": 20, "text": "A1"},
{"target_field": "b", "y": 108, "height": 20, "text": "B1"},
{"target_field": "a", "y": 116, "height": 20, "text": "A2"},
]
rows = connector._cluster_rows(lines, page_number=1)
total_values = sum(len(row) for row in rows)
assert total_values == 3 # nothing silently dropped
assert len(connector.warnings) == 1
assert connector.warnings[0].page_number == 1
+309
View File
@@ -0,0 +1,309 @@
"""Endpoint tests for `/governance/*` and the `/cacu/predict`,`/cama/predict`
MLD-4/MLD-5 wiring through `models.prediction.PredictionService`."""
import os
import tempfile
from datetime import date
import pytest
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
wire_domain("governance")
# A local, SQLite-backed MLflow tracking store for this module — no
# server, no network. `chdir` into the same temp dir: an experiment with
# no explicit artifact_location falls back to `./mlruns` relative to the
# CWD (production never sets one either; the real MLflow server picks it).
import mlflow
tmp_dir = tempfile.mkdtemp()
uri = f"sqlite:///{os.path.join(tmp_dir, 'mlflow.db')}"
os.environ["MLFLOW_TRACKING_URI"] = uri
mlflow.set_tracking_uri(uri)
previous_cwd = os.getcwd()
os.chdir(tmp_dir)
from core.cacu.models import Paciente
from persistance import db as persistance_db
with __import__("sqlmodel").Session(persistance_db.get_cacu_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()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
os.chdir(previous_cwd)
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
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
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},
"technical_validation_report_uri": "docs/tecnica.pdf",
"clinical_validation_report_uri": "docs/clinica.pdf",
"interpretability_report_uri": "docs/interpretabilidad.html",
**extra,
}
response = client.post("/governance/model-versions", json=body)
assert response.status_code == 201, response.get_json()
return response.get_json()
def _upload(client, domain: str, scenario: str, version: str, kind: str = "BALANCE_CLASES", name: str = "smote.json", data: bytes = b"{}"):
files = {"file": (__import__("io").BytesIO(data), name), "kind": kind}
return client.post(f"/governance/model-versions/{domain}/{scenario}/{version}/artifacts", data=files, content_type="multipart/form-data")
def test_model_version_lifecycle_over_http(client):
first = _register(client, "v1", scenario="lifecycle")
assert first["status"] == "candidata"
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{first['version']}/checks").get_json()
assert checks["ready"] is False
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote")
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
uploaded = _upload(client, "cacu", "lifecycle", first["version"])
assert uploaded.status_code == 201
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote").get_json()["status"] == "produccion"
second = _register(client, "v2", scenario="lifecycle", metrics={"auc": 0.86})
_upload(client, "cacu", "lifecycle", second["version"])
client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/promote")
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
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["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"
def test_reports_can_be_attached_later(client):
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
response = client.patch(
f"/governance/model-versions/cacu/reportes/{version['version']}/reports",
json={"clinical_validation_report_uri": "docs/clinica-v3.pdf"},
)
assert response.get_json()["tags"]["clinical_validation_report_uri"] == "docs/clinica-v3.pdf"
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
def test_bad_registrations_and_uploads_are_rejected(client):
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
dev = client.post("/governance/model-versions", json={"domain": "cacu", "scenario": "malas-subidas", "environment": "DEV"}).get_json()
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="NOPE").status_code == 400
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="ONNX_CHECKPOINT", name="m.onnx", data=b"junk").status_code == 400
def test_model_version_not_found(client):
assert client.get("/governance/model-versions/cacu/no-existe/999").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):
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
assert response.status_code == 400
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
from core.cacu.models import CitologiaCervical
from extraction.testing import text_pdf
from persistance.cacu import citologia_cervical_repository
from persistance.governance import extraction_run_repository
report = text_pdf([["LABORATORIO DE BIOLOGIA MOLECULAR", "Expediente: H-OCR-1", "VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"]])
good = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-1", cit_vph_pdf_blob=report))
bad = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-2", cit_vph_pdf_blob=b"%PDF-fake"))
body = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
assert body["processed"] >= 1 and body["failed"] >= 1
good = citologia_cervical_repository.get(good.cit_id)
assert (good.cit_vph_resultado, good.cit_vph_genotipo_16, good.cit_vph_genotipo_18) == ("POSITIVO", 0, 1)
assert good.cit_vph_ocr_estatus == "REALIZADO" and good.cit_vph_ocr_requiere_revision is False
assert good.cit_vph_ocr_metodo_principal == "pdf-texto" and good.cit_vph_ocr_confianza >= 0.8
bad = citologia_cervical_repository.get(bad.cit_id)
assert bad.cit_vph_ocr_estatus == "FALLIDO" and bad.cit_vph_ocr_requiere_revision is True
assert extraction_run_repository.count(entity_pk=str(good.cit_id)) == 1
again = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
assert again["skipped_already_done"] >= 1
def test_list_ocr_jobs(client):
body = client.get("/governance/ocr/jobs").get_json()
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
assert ("cacu", "citologia_cervical") in keys
assert ("cacu", "biopsia_cervical") in keys
assert ("cama", "biopsia_mama") in keys
cacu_vph = next(j for j in body["jobs"] if (j["domain"], j["entity"]) == ("cacu", "citologia_cervical"))
assert set(cacu_vph["result_fields"]) == {"cit_vph_resultado", "cit_vph_genotipo_16", "cit_vph_genotipo_18"}
def test_ocr_rows_unknown_job_is_404(client):
assert client.get("/governance/ocr/cacu/no_such_entity/rows").status_code == 404
def test_ocr_review_queue_blob_and_manual_correction(client):
from core.cacu.models import CitologiaCervical
from persistance.cacu import citologia_cervical_repository
row = citologia_cervical_repository.create(
CitologiaCervical(
pac_id_hospital="H-1",
cit_vph_pdf_blob=b"%PDF-review-me",
cit_vph_ocr_estatus="FALLIDO",
cit_vph_ocr_requiere_revision=True,
)
)
review = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
assert review.status_code == 200
review_body = review.get_json()
assert row.cit_id in {r["id"] for r in review_body["rows"]}
blob_response = client.get(f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/blob")
assert blob_response.status_code == 200
assert blob_response.data == b"%PDF-review-me"
assert blob_response.content_type == "application/pdf"
correction = client.post(
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
json={"values": {"cit_vph_resultado": "POSITIVO"}, "confianza": 1.0},
)
assert correction.status_code == 200
corrected = correction.get_json()
assert corrected["cit_vph_resultado"] == "POSITIVO"
assert corrected["cit_vph_ocr_estatus"] == "REALIZADO"
assert corrected["cit_vph_ocr_requiere_revision"] is False
assert corrected["cit_vph_ocr_metodo_principal"] == "manual"
done = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
assert row.cit_id not in {r["id"] for r in done.get_json()["rows"]}
from persistance.governance import extraction_run_repository
runs = extraction_run_repository.list(entity="citologia_cervical")
assert any("manual" in (r.transform_description or "").lower() for r in runs)
def test_ocr_correct_rejects_unknown_column(client):
from core.cacu.models import CitologiaCervical
from persistance.cacu import citologia_cervical_repository
row = citologia_cervical_repository.create(
CitologiaCervical(pac_id_hospital="H-2", cit_vph_pdf_blob=b"%PDF-2")
)
response = client.post(
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
json={"values": {"pac_id_hospital": "HACKED"}},
)
assert response.status_code == 400
def test_ocr_blob_not_found_for_unknown_row(client):
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
+265
View File
@@ -0,0 +1,265 @@
"""End-to-end tests (Flask test client, SQLite) of how a batch fills the
database from several sources: strict catalogs, upserts that keep unmapped
columns, defaults, atomic batches, itemized conflicts, and 400s for malformed
requests."""
import base64
import io
import json
import openpyxl
import pytest
@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(text: str, mapping: dict, *, target="cacu.Paciente", **extra) -> dict:
return {"source_type": "csv", "target": target, "column_mapping": mapping, "payload": {"file_base64": _b64(text.encode())}, **extra}
def _rows(client, target):
return {r["pac_id_hospital"]: r for r in client.get(f"/data/{target}?limit=500").get_json()["rows"]}
def test_catalog_values_are_enforced_and_aliases_resolved(client):
source = _csv(
"exp,sexo,dep,nac\nCAT-1,f,calles y caminos,1990-01-01\nCAT-2,GARBAGE,,1990-01-01\nCAT-3,Masculino,SECRETARIA DE SALUD,1990-01-01\n",
{"exp": "pac_id_hospital", "sexo": "pac_sexo", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
)
body = client.post("/imports/validate", json={"source": source}).get_json()
assert body["valid_count"] == 2
assert [(e["row_index"], e["field"], e["category"], e["raw_value"]) for e in body["errors"]] == [
(1, "pac_sexo", "out_of_catalog", "GARBAGE")
]
client.post("/imports/commit", json={"sources": [source]})
rows = _rows(client, "cacu.Paciente")
assert rows["CAT-1"]["pac_sexo"] == "Femenino"
assert rows["CAT-1"]["pac_dependencia"] == "CALLES Y CAMINOS" # alias normalized
# Dependencia is a tentative catalog in Core, so unknown values are kept.
assert rows["CAT-3"]["pac_dependencia"] == "SECRETARIA DE SALUD"
def test_postal_codes_keep_leading_zeros_and_are_validated(client):
source = _csv(
"exp,cp,nac\nCP-1,01000,1990-01-01\nCP-2,6400,1990-01-01\nCP-3,64000a,1990-01-01\n",
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
)
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
assert body["results"][0]["created"] == 1
rows = _rows(client, "cacu.Paciente")
assert rows["CP-1"]["pac_codigo_postal"] == "01000"
assert "CP-2" not in rows and "CP-3" not in rows # 4 digits / non-digit
def test_upsert_only_touches_mapped_columns(client):
client.post(
"/imports/commit",
json={"sources": [_csv("exp,sexo,nac\nUP-1,F,15/01/1990\n", {"exp": "pac_id_hospital", "sexo": "pac_sexo", "nac": "pac_fecha_nacimiento"})]},
)
# pac_fecha_nacimiento is required (IND-01), so every row, insert or
# upsert, must carry it. pac_sexo is the field that must stay untouched
# when a later source doesn't map it.
body = client.post(
"/imports/commit",
json={
"sources": [
_csv(
"exp,cp,nac\nUP-1,64000,15/01/1990\n",
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
)
],
"on_conflict": "upsert",
},
).get_json()
assert body["results"][0]["updated"] == 1
row = _rows(client, "cacu.Paciente")["UP-1"]
assert (row["pac_sexo"], row["pac_fecha_nacimiento"], row["pac_codigo_postal"]) == ("Femenino", "1990-01-15", "64000")
def test_defaults_fill_unmapped_fields_and_blank_cells(client):
source = _csv(
"exp,dep,nac\nDEF-1,,1990-01-01\nDEF-2,GOBIERNO,1990-01-01\n",
{"exp": "pac_id_hospital", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
defaults={"pac_dependencia": "CALLES Y CAMINOS", "pac_parentesco": "afiliado"},
)
assert client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]["created"] == 2
rows = _rows(client, "cacu.Paciente")
assert rows["DEF-1"]["pac_dependencia"] == "CALLES Y CAMINOS"
assert rows["DEF-2"]["pac_dependencia"] == "GOBIERNO"
# Defaults go through the same validation/normalization as mapped cells.
assert rows["DEF-1"]["pac_parentesco"] == rows["DEF-2"]["pac_parentesco"] == "Afiliado"
def test_several_sources_compose_several_tables_in_one_batch(client):
"""One Excel workbook feeds two tables (a source per sheet), a CSV adds
more patients, and a JSON source feeds a third table, all in one batch
and one transaction."""
workbook = openpyxl.Workbook()
pacientes = workbook.active
pacientes.title = "Pacientes"
pacientes.append(["Expediente", "Sexo", "Nacimiento"])
pacientes.append(["MIX-1", "F", "1990-01-01"])
ordenes = workbook.create_sheet("Ordenes")
ordenes.append(["Folio", "Expediente", "Tipo"])
ordenes.append([9001, "MIX-1", "Solicitud de Papanicolao en Base Liquida"])
buffer = io.BytesIO()
workbook.save(buffer)
xlsx = _b64(buffer.getvalue())
preview = client.post(
"/imports/sources/file/preview",
data={"file": (io.BytesIO(buffer.getvalue()), "libro.xlsx"), "source_kind": "excel", "target": "cacu.OrdenesEstudio", "options": json.dumps({"sheet_name": "Ordenes"})},
content_type="multipart/form-data",
).get_json()
assert preview["source_metadata"] == {"sheets": ["Pacientes", "Ordenes"], "sheet_name": "Ordenes"}
assert [c["name"] for c in preview["columns"]] == ["Folio", "Expediente", "Tipo"]
batch = [
{"source_type": "excel", "label": "libro.xlsx › Pacientes", "target": "cacu.Paciente", "column_mapping": {"Expediente": "pac_id_hospital", "Sexo": "pac_sexo", "Nacimiento": "pac_fecha_nacimiento"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Pacientes"}}},
_csv("id,genero,nac\nMIX-2,M,1990-01-01\n", {"id": "pac_id_hospital", "genero": "pac_sexo", "nac": "pac_fecha_nacimiento"}, label="extra.csv"),
{"source_type": "excel", "target": "cacu.OrdenesEstudio", "column_mapping": {"Folio": "ord_numero_hospital", "Expediente": "pac_id_hospital", "Tipo": "ord_tipo_estudio"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Ordenes"}}},
{"source_type": "json", "target": "cacu.BiometriaHematica", "column_mapping": {"paciente.exp": "pac_id_hospital", "hb": "hemoglobina_g_dl"}, "payload": {"file_base64": _b64(json.dumps([{"paciente": {"exp": "MIX-1"}, "hb": 13.5}]).encode())}},
]
body = client.post("/imports/commit", json={"sources": batch}).get_json()
assert body["ok"] is True
assert [(r["label"], r["target"], r["created"]) for r in body["results"]] == [
("libro.xlsx › Pacientes", "cacu.Paciente", 1),
("extra.csv", "cacu.Paciente", 1),
(None, "cacu.OrdenesEstudio", 1),
(None, "cacu.BiometriaHematica", 1),
]
assert {"MIX-1", "MIX-2"} <= set(_rows(client, "cacu.Paciente"))
orden = client.get("/data/cacu.OrdenesEstudio").get_json()["rows"][0]
assert orden["ord_numero_hospital"] == 9001
def test_conflicts_are_itemized_with_their_row(client):
body = client.post(
"/imports/commit",
json={
"sources": [
_csv(
"exp,nac\nDUP-1,1990-01-01\nDUP-1,1990-01-01\n",
{"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"},
)
]
},
).get_json()
result = body["results"][0]
assert (result["created"], result["rejected"]) == (1, 1)
assert result["errors"] == [
{"row_index": 1, "field": "pac_id_hospital", "category": "conflict", "message": "conflict on ('pac_id_hospital',)", "raw_value": "DUP-1"}
]
def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
from sqlalchemy.exc import OperationalError
from persistance.repository import Repository
original = Repository.bulk_upsert
calls = {"n": 0}
def flaky(self, objs, **kwargs):
calls["n"] += 1
if calls["n"] == 2:
raise OperationalError("INSERT ...", {}, Exception("disk full"))
return original(self, objs, **kwargs)
monkeypatch.setattr(Repository, "bulk_upsert", flaky)
response = client.post(
"/imports/commit",
json={
"sources": [
_csv("exp,nac\nATOM-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
_csv("exp,nac\nATOM-2,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
]
},
)
assert response.status_code == 400
assert "nothing was written" in response.get_json()["error"]
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
@pytest.mark.parametrize(
"payload",
[
{"sources": [{"source_type": "csv", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ=="}}]},
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": "YQ=="}}]},
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "%%%not-base64"}}]},
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "no_such_field"}, "payload": {"file_base64": "YQ=="}}]},
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_sexo", "b": "pac_sexo"}, "payload": {"file_base64": "YQ=="}}]},
{"sources": "nope"},
{"sources": [{"source_type": "pdf", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ==", "mode": "regions", "regions": [], "dpi": 5000}}]},
],
)
def test_malformed_commits_are_400_not_500(client, payload):
response = client.post("/imports/commit", json=payload)
assert response.status_code == 400, response.get_json()
assert response.get_json()["error"]
def test_page_image_rejects_absurd_dpi(client):
from reportlab.pdfgen import canvas
buffer = io.BytesIO()
pdf = canvas.Canvas(buffer)
pdf.drawString(72, 720, "hola")
pdf.save()
response = client.post(
"/imports/sources/pdf/page-image",
data={"file": (io.BytesIO(buffer.getvalue()), "a.pdf"), "page_number": "1", "dpi": "5000"},
content_type="multipart/form-data",
)
assert response.status_code == 400
assert "dpi" in response.get_json()["error"]
def test_data_endpoint_pages_through_the_repository(client):
body = client.get("/data/cacu.Paciente?limit=2").get_json()
assert body["limit"] == 2 and len(body["rows"]) == 2 and body["total"] >= 2
assert client.get("/data/cacu.Nope").status_code == 404
def test_children_are_linked_to_parents_loaded_in_the_same_batch_whatever_the_order(client):
"""Biopsies listed before their patients still get `pac_id` filled, since
parents are written first within the batch's transaction. A child whose
patient doesn't exist keeps a null FK."""
from webapi.imports.services.link_resolver import dependency_rank, links_for
assert [link.fk_field for link in links_for("cacu.BiopsiaCervical")] == ["pac_id"]
assert links_for("cacu.Paciente") == ()
assert [link.fk_field for link in links_for("cama.Mastografia")] == ["pac_id", "ord_id"]
assert dependency_rank("cama.Paciente") < dependency_rank("cama.OrdenesEstudio") < dependency_rank("cama.Mastografia")
batch = [
_csv("exp,grado\nLINK-1,NORMAL\nNO-SUCH-PATIENT,NORMAL\n", {"exp": "pac_id_hospital", "grado": "bx_cin_grado"}, target="cacu.BiopsiaCervical"),
_csv("exp,nac\nLINK-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
]
body = client.post("/imports/commit", json={"sources": batch}).get_json()
assert [r["target"] for r in body["results"]] == ["cacu.BiopsiaCervical", "cacu.Paciente"]
assert body["results"][0]["linked"] == {"pac_id": 1}
patient = _rows(client, "cacu.Paciente")["LINK-1"]
biopsies = {r["pac_id_hospital"]: r for r in client.get("/data/cacu.BiopsiaCervical?limit=500").get_json()["rows"]}
assert biopsies["LINK-1"]["pac_id"] == patient["pac_id"]
assert biopsies["NO-SUCH-PATIENT"]["pac_id"] is None
def test_data_endpoint_reports_columns_in_table_order(client):
body = client.get("/data/cacu.Paciente?limit=1").get_json()
assert body["columns"][:2] == ["pac_id", "pac_id_hospital"]
+208
View File
@@ -0,0 +1,208 @@
import base64
import io
import json
import pytest
from sqlalchemy import create_engine, text
@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"
# not written
assert client.get("/cacu/pacientes/999").status_code == 404
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
# 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"}
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 "domain" in response.get_json()["error"].lower()
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([{"pac_id_hospital": "T-NOKEY-1"}], target="tea.Pacientes")
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
assert response.status_code == 400
@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
+164
View File
@@ -0,0 +1,164 @@
"""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 — no real MySQL server to test against")
@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]
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"}
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.
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()
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.
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"
+273
View File
@@ -0,0 +1,273 @@
"""Endpoint tests for the PDF routes. One round trip per resolution path:
- detect -> table/preview -> validate -> commit, for the ruled-table
path, writing into `cacu.Paciente`.
- detect -> page-image -> regions/extract -> validate -> commit, for the
OCR/region path, writing into `tea.Pacientes`.
"""
import base64
import io
import json
import pytest
from PIL import Image, ImageDraw, ImageFont
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
@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
# ---------------------------------------------------------------------
# Fixture PDFs
# ---------------------------------------------------------------------
def _build_table_pdf(rows: list[tuple[str, str, str]]) -> bytes:
buffer = io.BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=letter)
data = [["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"], *[list(row) for row in rows]]
table = Table(data)
table.setStyle(
TableStyle(
[
("GRID", (0, 0), (-1, -1), 1, colors.black),
("FONTSIZE", (0, 0), (-1, -1), 12),
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
("TOPPADDING", (0, 0), (-1, -1), 8),
]
)
)
doc.build([table])
return buffer.getvalue()
_IMG_W, _IMG_H = 900, 1200
def _font(size: int = 34):
for path in (
"/System/Library/Fonts/Helvetica.ttc",
"/System/Library/Fonts/Supplemental/Arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
):
try:
return ImageFont.truetype(path, size)
except Exception:
continue
return ImageFont.load_default()
def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
"""A scanned-like page with two text blocks at known pixel positions and
no text layer, so only the OCR/region path applies."""
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
draw = ImageDraw.Draw(img)
font = _font()
draw.text((40, 100), id_hospital, fill="black", font=font)
draw.text((400, 100), sexo, fill="black", font=font)
buffer = io.BytesIO()
c = canvas.Canvas(buffer, pagesize=letter)
page_w, page_h = letter
reader_buf = io.BytesIO()
img.save(reader_buf, format="PNG")
reader_buf.seek(0)
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
c.showPage()
c.save()
return buffer.getvalue()
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
# ---------------------------------------------------------------------
# Table path: detect -> table/preview -> validate -> commit (cacu.Paciente)
# ---------------------------------------------------------------------
def test_pdf_table_round_trip_detect_preview_validate_commit(client):
pdf_bytes = _build_table_pdf([("H-PDF-TAB-1", "F", "1990-01-01"), ("H-PDF-TAB-2", "M", "1985-06-15")])
detect_response = client.post(
"/imports/sources/pdf/detect",
data={"file": (io.BytesIO(pdf_bytes), "table.pdf")},
content_type="multipart/form-data",
)
assert detect_response.status_code == 200
detect_body = detect_response.get_json()
assert detect_body["page_count"] == 1
assert detect_body["has_text_layer"] is True
assert len(detect_body["table_candidates"]) == 1
candidate = detect_body["table_candidates"][0]
assert candidate["row_count"] == 2
assert candidate["column_count"] == 3
preview_response = client.post(
"/imports/sources/pdf/table/preview",
data={
"file": (io.BytesIO(pdf_bytes), "table.pdf"),
"page_number": str(candidate["page_number"]),
"bbox": json.dumps(candidate["bbox"]),
"target": "cacu.Paciente",
},
content_type="multipart/form-data",
)
assert preview_response.status_code == 200
preview_body = preview_response.get_json()
assert {c["name"] for c in preview_body["columns"]} == {"pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"}
assert preview_body["total_rows"] == 2
suggested = {m["source_column"]: m["target_field"] for m in preview_body["suggested_mapping"]}
assert suggested["pac_id_hospital"] == "pac_id_hospital"
source = {
"source_type": "pdf",
"target": "cacu.Paciente",
"column_mapping": {
"pac_id_hospital": "pac_id_hospital",
"pac_sexo": "pac_sexo",
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
},
"payload": {
"file_base64": base64.b64encode(pdf_bytes).decode(),
"mode": "table",
"page_number": candidate["page_number"],
"bbox": candidate["bbox"],
},
}
validate_response = client.post("/imports/validate", json={"source": source})
assert validate_response.status_code == 200
validate_body = validate_response.get_json()
assert validate_body["total_rows"] == 2
assert validate_body["valid_count"] == 2
assert validate_body["error_count"] == 0
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
assert commit_response.status_code == 200
commit_body = commit_response.get_json()
assert commit_body["ok"] is True
result = commit_body["results"][0]
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"
# ---------------------------------------------------------------------
# page-image endpoint
# ---------------------------------------------------------------------
def test_pdf_page_image_returns_png(client):
pdf_bytes = _build_scanned_form_pdf("H-IMG-1", "F")
response = client.post(
"/imports/sources/pdf/page-image",
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
content_type="multipart/form-data",
)
assert response.status_code == 200
assert response.content_type == "image/png"
image = Image.open(io.BytesIO(response.data))
assert image.format == "PNG"
def test_pdf_page_image_missing_file_returns_400(client):
response = client.post(
"/imports/sources/pdf/page-image", data={"page_number": "1"}, content_type="multipart/form-data"
)
assert response.status_code == 400
# ---------------------------------------------------------------------
# OCR/region path: detect -> page-image -> regions/extract -> validate ->
# commit (tea.Pacientes)
# ---------------------------------------------------------------------
def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
pdf_bytes = _build_scanned_form_pdf("H-PDF-OCR-1", "F")
detect_response = client.post(
"/imports/sources/pdf/detect",
data={"file": (io.BytesIO(pdf_bytes), "form.pdf")},
content_type="multipart/form-data",
)
assert detect_response.status_code == 200
detect_body = detect_response.get_json()
assert detect_body["has_text_layer"] is False
assert detect_body["table_candidates"] == []
image_response = client.post(
"/imports/sources/pdf/page-image",
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
content_type="multipart/form-data",
)
assert image_response.status_code == 200
assert Image.open(io.BytesIO(image_response.data)).format == "PNG"
regions = [
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
]
extract_response = client.post(
"/imports/sources/pdf/regions/extract",
json={"file_base64": base64.b64encode(pdf_bytes).decode(), "regions": regions},
)
assert extract_response.status_code == 200
extract_body = extract_response.get_json()
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}]
assert extract_body["warnings"] == []
source = {
"source_type": "pdf",
"target": "tea.Pacientes",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
"payload": {
"file_base64": base64.b64encode(pdf_bytes).decode(),
"mode": "regions",
"regions": regions,
},
}
validate_response = client.post("/imports/validate", json={"source": source})
assert validate_response.status_code == 200
validate_body = validate_response.get_json()
assert validate_body["total_rows"] == 1
assert validate_body["valid_count"] == 1
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
assert commit_response.status_code == 200
commit_body = commit_response.get_json()
assert commit_body["ok"] is True
result = commit_body["results"][0]
assert result["target"] == "tea.Pacientes"
assert result["created"] == 1
def test_pdf_detect_missing_file_returns_400(client):
response = client.post("/imports/sources/pdf/detect", data={}, content_type="multipart/form-data")
assert response.status_code == 400
def test_pdf_regions_extract_missing_field_returns_400(client):
response = client.post("/imports/sources/pdf/regions/extract", json={"regions": []})
assert response.status_code == 400
+183
View File
@@ -0,0 +1,183 @@
"""Endpoint tests for `/tea/indicadores`, `/cacu/indicadores` and
`/cama/indicadores`: the read side of the bronze/silver/gold pipeline
(Persistance/persistance/aristas, indicadores_kit). Seeds one patient,
runs the real `cargar`/`registro`/`definiciones`/`calcular` steps, then
hits the HTTP layer."""
from datetime import date
from functools import partial
import pytest
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("tea")
from core.tea.models import Pacientes
from persistance import db as persistance_db
from persistance.tea import (
staging_repository, carga_repository, def_parametro_repository,
dim_periodo_repository, indicador_definicion_repository, calculo_repository,
)
from indicadores_kit.tea import etl
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
from indicadores_kit.registry.periodos import periodos_de_tipos
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
from indicadores_kit.serving.definiciones import leer_definiciones
from indicadores_kit.mart.calculo import medir_con_unidades
from indicadores_kit.tablas import tablas_de
with __import__("sqlmodel").Session(persistance_db.get_tea_engine()) as session:
session.add(Pacientes(pac_id_hospital="H-1", pac_fecha_nacimiento=date(2020, 1, 1), pac_sexo="F"))
session.commit()
staging = staging_repository.leer(etl.STAGING)
lote = etl.lote_de_estudios(**staging)
carga_repository.guardar_lote(**lote.para_guardar())
tablas = tablas_de("tea")
measures = measures_de("tea")
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2024, 2024, tablas=tablas))
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("tea"), tablas=tablas))
nombre, medida = next(iter(measures.items()))
for tipo in medida.extension.publicacion.tipos_periodo:
for periodo_id in calculo_repository.periodos(tipo, date(2024, 1, 1), date(2025, 1, 1)):
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
corte=None, permitir_sin_definir=True)
calculo_repository.calcular(medir)
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_list_indicadores(client):
"""Only the 5 TEA measures not marked `oculto` in their own TOML publish
to the catalog (the K01-K08/M02-M19 family is draft/internal); a hidden
id still answers `/datos` directly, see `test_indicador_datos_...`."""
response = client.get("/tea/indicadores")
assert response.status_code == 200
indicadores = response.get_json()
assert isinstance(indicadores, list)
assert len(indicadores) == 5
assert {"id", "titulo", "contrato", "unidad", "sentido", "tipos_periodo", "estratos", "figuras"} <= indicadores[0].keys()
def test_indicador_datos_returns_valid_json_no_bare_nan(client):
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2024-S1,2024-S2")
assert response.status_code == 200
# Pandas renders missing scores as NaN; the response must not leak the
# bare (invalid-JSON) token -- it has to come through as `null`.
assert "NaN" not in response.get_data(as_text=True)
body = response.get_json()
assert body["id"] == "K01_evaluacion_3_meses"
assert set(body["periodos"]) == {"2024-S1", "2024-S2"}
assert {row["periodo"] for row in body["filas"]} == {"2024-S1", "2024-S2"}
def test_indicador_datos_without_periodos_defaults_to_available_ones(client):
"""Unlike the old endpoint, omitting `periodos` is not an error: it
reports whatever periods already have a computed report."""
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos")
assert response.status_code == 200
assert response.get_json()["periodos"]
def test_indicador_datos_unknown_indicador_is_404(client):
response = client.get("/tea/indicadores/NOPE/datos?periodos=2024-S1")
assert response.status_code == 404
def test_indicador_datos_malformed_periodo_is_400(client):
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=no-es-un-periodo")
assert response.status_code == 400
def test_indicador_periodos_endpoint(client):
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/periodos")
assert response.status_code == 200
body = response.get_json()
assert body["id"] == "K01_evaluacion_3_meses"
assert isinstance(body["periodos"], list)
@pytest.fixture(scope="module")
def cacu_client(wire_domain):
"""CaCu reproduces a real id mismatch TEA's fixture doesn't: some of its
TOML files are named in lowercase (`cacu_biopsias.toml`, the
`measures_de` dict key) while their `measure.url` ends in uppercase
(`cacu/CACU_BIOPSIAS`, the id `indicador_definicion.indicador` and the
catalog publish) -- caught live by driving the WebApp dashboard against
a real CaCu indicator, not by the TEA-only fixture above."""
wire_domain("cacu")
from sqlmodel import Session
from persistance import db as persistance_db
from persistance.cacu import (
staging_repository, carga_repository, def_parametro_repository as cacu_def_parametro_repository,
dim_periodo_repository, indicador_definicion_repository, calculo_repository, vistas_repository,
)
from indicadores_kit.cacu import etl, fixtures
from indicadores_kit.cdm.etl import lote_de_resultados
from indicadores_kit.esquema import ddl_de_vistas
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
from indicadores_kit.registry.periodos import periodos_de_tipos
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
from indicadores_kit.serving.definiciones import leer_definiciones
from indicadores_kit.mart.calculo import medir_con_unidades
from indicadores_kit.tablas import tablas_de
with Session(persistance_db.get_cacu_engine()) as session:
fixtures.insertar(session)
session.commit()
tablas = tablas_de("cacu")
staging = staging_repository.leer(etl.STAGING)
lote = etl.lote_de_estudios(**staging)
carga_repository.guardar_lote(**lote.para_guardar())
pacientes = staging_repository.leer({"pacientes": etl.STAGING["pacientes"]})["pacientes"]
lote_resultados = lote_de_resultados(
pacientes, staging_repository.leer(etl.STAGING_DE_RESULTADOS), etl.FUENTES_DE_RESULTADOS, tablas=tablas,
)
carga_repository.guardar_lote(**lote_resultados.para_guardar())
vistas_repository.construir(ddl_de_vistas("cacu"))
measures = measures_de("cacu")
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
cacu_def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2025, 2025, tablas=tablas))
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("cacu"), tablas=tablas))
for medida in measures.values():
for tipo in medida.extension.publicacion.tipos_periodo:
for periodo_id in calculo_repository.periodos(tipo, date(2025, 1, 1), date(2026, 1, 1)):
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
corte=None, permitir_sin_definir=True)
calculo_repository.calcular(medir)
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_indicador_datos_uses_the_toml_key_not_measure_url(cacu_client):
"""`cacu_biopsias`'s own `measure.url` ends in `CACU_BIOPSIAS` (uppercase),
but `registrar_indicadores` publishes and looks measures up by
`measures_de()`'s dict key (the lowercase TOML file stem) throughout, so
the mismatch never reaches a client -- unlike the old, since-replaced
`webapi.indicadores`, which published the uppercase `measure.url` id and
needed its own `_measure_por_indicador` lookup to reconcile the two."""
catalogo = cacu_client.get("/cacu/indicadores").get_json()
assert any(i["id"] == "cacu_biopsias" for i in catalogo)
assert not any(i["id"] == "CACU_BIOPSIAS" for i in catalogo)
response = cacu_client.get("/cacu/indicadores/cacu_biopsias/datos?periodos=2025-S1,2025-S2")
assert response.status_code == 200
assert response.get_json()["filas"]
+48
View File
@@ -0,0 +1,48 @@
"""WebApi and `models` talk to each other through the database, both ways,
over the same Repository objects: rows imported over HTTP are what a
model trains on, and rows a model writes are what the API serves."""
import base64
import pytest
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cama")
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_imported_rows_are_what_models_reads_and_model_writes_are_what_the_api_serves(client):
from core.cama.models import Mastografia
from models.cama import CaMaModel
csv = b"Expediente,BIRADS\nRT-1,BI-RADS 4\nRT-2,2\n"
response = client.post(
"/imports/commit",
json={
"sources": [
{
"source_type": "csv",
"target": "cama.Mastografia",
"column_mapping": {"Expediente": "pac_id_hospital", "BIRADS": "mast_birads"},
"payload": {"file_base64": base64.b64encode(csv).decode()},
}
]
},
)
assert response.get_json()["results"][0]["created"] == 2
model = CaMaModel()
seen = {row["pac_id_hospital"]: row["mast_birads"] for row in model.dataset("mastografia")}
assert seen == {"RT-1": "B4", "RT-2": "B2"}
model.repository("mastografia").create(Mastografia(pac_id_hospital="RT-FROM-MODEL", mast_birads="B1"))
served = client.get("/data/cama.Mastografia").get_json()
assert served["total"] == 3
assert "RT-FROM-MODEL" in {row["pac_id_hospital"] for row in served["rows"]}
+372
View File
@@ -0,0 +1,372 @@
"""Connector catalog, SQL Server, EEG files and clinical documents, end to end."""
import base64
import io
from datetime import date
import numpy as np
import pytest
import sqlalchemy as sa
from sqlalchemy.dialects import mssql
from extraction.testing import edf_file, scanned_pdf, text_pdf
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
wire_domain("cama")
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 b64(raw: bytes) -> str:
return base64.b64encode(raw).decode()
def eeg(seconds: int = 8, rate: int = 128, **kwargs) -> bytes:
t = np.arange(rate * seconds) / rate
alpha = 40 * np.sin(2 * np.pi * 10 * t)
return edf_file(signals={"EEG O1-REF": alpha, "EEG O2-REF": alpha, "EEG Fp1-REF": 20 * np.sin(2 * np.pi * 20 * t)}, sample_rate=rate, **kwargs)
# -- catalog ------------------------------------------------------------------------
def test_catalog_lists_every_connector(client):
connectors = {c["kind"]: c for c in client.get("/imports/connectors").get_json()["connectors"]}
assert {"csv", "excel", "json", "pdf", "document", "edf", "sql"} <= set(connectors)
assert connectors["edf"]["extensions"] == ["edf"]
assert "pdf" in connectors["document"]["extensions"] and "tif" in connectors["document"]["extensions"]
assert {s["id"] for s in connectors["document"]["segmentations"]} == {"auto", "document", "pages", "key"}
engines = {e["id"]: e for e in connectors["sql"]["engines"]}
assert engines["mssql"]["label"] == "SQL Server" and engines["mssql"]["default_port"] == 1433
assert engines["mssql"]["available"] is True
# -- SQL Server ----------------------------------------------------------------------
def test_sql_server_url_is_built_from_form_fields():
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mssql", "host": "his.local", "database": "HIS", "user": "lector", "password": "p@ss:/w"})
assert url.drivername == "mssql+pymssql"
assert url.port == 1433
assert url.password == "p@ss:/w"
def test_sql_server_preview_compiles_to_top(monkeypatch):
from webapi.imports.connectors.sql import _text_subquery
statement = sa.select(_text_subquery("SELECT * FROM pacientes")).limit(5)
compiled = str(statement.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}))
assert "TOP 5" in compiled and "LIMIT" not in compiled
def test_unknown_engine_and_missing_host_are_rejected(client):
assert client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "db2", "host": "x", "database": "y"}}).status_code == 400
response = client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "mssql", "database": "y"}})
assert response.status_code == 400 and "host" in response.get_json()["error"]
# -- EEG -----------------------------------------------------------------------------
def test_edf_preview_maps_onto_eeg_estudio(client):
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"}
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
[row] = body["sample_rows"]
assert row["id_registro_laboratorio"] == "LAB-778"
assert row["paciente"] == "EXP-0042"
assert row["fecha_estudio"] == "2024-01-15"
assert row["edad_meses"] == 56.0
assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3)
assert "3 canales a 128 Hz" in row["descripcion_senal"]
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
assert suggested["estudio"] == "eeg_estudio"
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia"
def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
source = {
"source_type": "edf",
"target": "tea.EegEstudio",
"column_mapping": {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"paciente": "eeg_pac_id",
"fecha_estudio": "eeg_fecha_estudio",
"duracion_min": "eeg_duracion_min",
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
"estudio": "eeg_estudio",
},
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
}
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.tea import eeg_estudio_repository
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()}
assert set(stored) == {"LAB-778", "b"}
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
def test_eeg_estudio_rejects_a_file_mne_cannot_read():
from webapi.imports.schemas.service import validate_rows
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
[row] = result.rejected
assert row.errors[0].field == "eeg_estudio"
# -- clinical documents -----------------------------------------------------------------
def _document_source(files: list[tuple[str, bytes]], target: str, mapping: dict, **options) -> dict:
return {
"source_type": "document",
"target": target,
"column_mapping": mapping,
"payload": {"files": [{"name": n, "file_base64": b64(r)} for n, r in files], **options},
"label": "documentos",
}
REPORTS = text_pdf(
[
["HOSPITAL REGIONAL - LABORATORIO DE PATOLOGIA", "Expediente: DOC-0001 Sexo: Femenino", "Fecha de nacimiento: 12/03/1981",
"VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"],
["Observaciones: muestra adecuada,", "con escaso moco cervical."],
["Expediente: DOC-0002 Sexo: F", "Fecha de nacimiento: 1 de mayo de 1975",
"Se identifica ADN de virus del papiloma humano de alto riesgo: NEGATIVO"],
],
image_on_page=2,
)
def test_document_extract_reports_records_evidence_and_images(client):
body = client.post(
"/imports/sources/document/extract",
json={"files": [{"name": "lote.pdf", "file_base64": b64(REPORTS)}], "target": "cacu.CitologiaCervical"},
).get_json()
assert body["key_field"] == "pac_id_hospital"
first, second = body["records"]
assert first["key"] == "DOC-0001" and first["sources"] == [{"document": "lote.pdf", "page_numbers": [1, 2]}]
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert first["fields"]["cit_vph_genotipo_16"]["value"] == 0
assert first["fields"]["cit_vph_genotipo_18"]["value"] == 1
assert first["fields"]["cit_observaciones"]["value"] == "muestra adecuada, con escaso moco cervical."
assert first["fields"]["cit_vph_resultado"]["page_number"] == 1
assert [image["page_number"] for image in first["images"]] == [2]
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
assert second["fields"]["cit_vph_resultado"]["method"] == "texto_libre"
def test_document_page_and_image_render(client):
data = {"file": (io.BytesIO(REPORTS), "lote.pdf"), "page_number": "2", "bbox": "[0.4, 0.4, 0.8, 0.7]"}
response = client.post("/imports/sources/document/page-image", data=data, content_type="multipart/form-data")
assert response.status_code == 200 and response.mimetype == "image/png"
def test_documents_commit_with_overrides_and_the_record_pdf(client):
mapping = {
"pac_id_hospital": "pac_id_hospital",
"cit_vph_resultado": "cit_vph_resultado",
"cit_vph_genotipo_18": "cit_vph_genotipo_18",
"documento": "cit_vph_pdf_blob",
}
source = _document_source([("lote.pdf", REPORTS)], "cacu.CitologiaCervical", mapping, overrides={"1": {"cit_vph_resultado": "INDETERMINADO"}})
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.startswith("DOC-")}
assert rows["DOC-0001"].cit_vph_resultado == "POSITIVO"
assert rows["DOC-0002"].cit_vph_resultado == "INDETERMINADO"
assert rows["DOC-0001"].cit_vph_pdf_blob.startswith(b"%PDF")
def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
csv = b"expediente,sexo,codigo_postal\nMIX-0001,F,64000\nMIX-0002,M,01000\n"
scan = scanned_pdf([["FICHA DE IDENTIFICACION", "Expediente: MIX-0001", "Fecha de nacimiento: 15/08/1979", "Sexo: Masculino"]])
sources = [
{
"source_type": "csv",
"target": "cacu.Paciente",
"label": "padron.csv",
"column_mapping": {"expediente": "pac_id_hospital", "sexo": "pac_sexo", "codigo_postal": "pac_codigo_postal"},
"payload": {"file_base64": b64(csv)},
},
_document_source(
[("ficha.pdf", scan)],
"cacu.Paciente",
{"pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento", "pac_sexo": "pac_sexo"},
),
]
# On its own the CSV lacks the required birth date.
assert client.post("/imports/validate", json={"source": sources[0]}).get_json()["error_count"] == 2
padron, ficha = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
assert (padron["created"], padron["rejected"]) == (1, 1) # MIX-0002 has no birth date anywhere
assert (ficha["merged"], ficha["created"]) == (1, 0)
assert [(w["field"], w["raw_value"]) for w in ficha["warnings"]] == [("pac_sexo", "Masculino")]
from persistance.cacu import paciente_repository
[patient] = paciente_repository.list(pac_id_hospital="MIX-0001")
assert patient.pac_fecha_nacimiento == date(1979, 8, 15)
assert patient.pac_codigo_postal == "64000"
EEG_REPORT = text_pdf(
[
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024",
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
],
image_on_page=2,
)
# A second study id, distinct from LAB-778 (already used by an earlier test
# against this module-scoped client/database), for the merge test below.
EEG_REPORT_2 = text_pdf(
[
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024",
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
],
)
def test_eeg_report_scattered_across_pages_merges_into_one_record(client):
"""The report's demographics are on page 1, its conclusion on page 2 —
non-contiguous fields the same way a multi-file upload would be, just
without the file boundary. Proves the extractor merges by the lab's own
study id, not by page adjacency."""
body = client.post(
"/imports/sources/document/extract",
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"},
).get_json()
assert body["key_field"] == "eeg_id_registro_laboratorio"
[record] = body["records"]
assert record["key"] == "LAB-778"
assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}]
assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO"
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"]
assert [image["page_number"] for image in record["images"]] == [2]
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
"""The EDF connector computes signal fields from the file itself; the
report PDF (read with NLP, across two pages) carries the clinician's
interpretation. Different sources, same study — `eeg_id_registro_
laboratorio` (the lab's own code, read from the EDF header by one side
and from the report text by the other) is what lets them land on one
`eeg_estudio` row instead of two half-populated ones."""
edf_source = {
"source_type": "edf",
"target": "tea.EegEstudio",
"label": "estudio.edf",
"column_mapping": {
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
"fecha_estudio": "eeg_fecha_estudio",
"duracion_min": "eeg_duracion_min",
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
"estudio": "eeg_estudio",
},
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
}
document_source = _document_source(
[("reporte.pdf", EEG_REPORT_2)],
"tea.EegEstudio",
{
"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio",
"eeg_simetria": "eeg_simetria",
"eeg_conclusion_texto": "eeg_conclusion_texto",
"eeg_medico_interpreta": "eeg_medico_interpreta",
},
)
body = client.post(
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
).get_json()
edf_result, doc_result = body["results"]
assert edf_result["created"] == 1, body
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
from persistance.tea import eeg_estudio_repository
[row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900")
# From the EDF file itself:
assert row.eeg_duracion_min is not None
assert row.eeg_estudio[:8].strip() == b"0"
# From the scanned report, on the very same row:
assert row.eeg_simetria == "SIMETRICO"
assert "sin eventos epileptiformes" in row.eeg_conclusion_texto
assert row.eeg_medico_interpreta == "Dra. Ruiz"
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
"""The order/date come from a structured table (a CSV export of the lab's
own HIS); the VPH result comes from NLP over the scanned report PDF.
`(pac_id_hospital, ord_numero_hospital)` is what lets them land on one
`citologiacervical` row instead of two half-populated ones."""
csv = b"expediente,orden,fecha_toma\nMRG-0001,5001,2024-03-01\n"
report = text_pdf([["LABORATORIO DE CITOLOGIA", "Expediente: MRG-0001", "No. de orden: 5001", "VPH alto riesgo: POSITIVO"]])
sources = [
{
"source_type": "csv",
"target": "cacu.CitologiaCervical",
"label": "padron.csv",
"column_mapping": {"expediente": "pac_id_hospital", "orden": "ord_numero_hospital", "fecha_toma": "cit_fecha_toma"},
"payload": {"file_base64": b64(csv)},
},
_document_source(
[("reporte.pdf", report)],
"cacu.CitologiaCervical",
{"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital", "cit_vph_resultado": "cit_vph_resultado"},
),
]
tabla, documento = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
assert tabla["created"] == 1, tabla
assert documento["merged"] == 1, documento # absorbed into the table row, not inserted again
from persistance.cacu import citologia_cervical_repository
[row] = citologia_cervical_repository.list(pac_id_hospital="MRG-0001")
# From the structured table:
assert row.ord_numero_hospital == 5001
assert row.cit_fecha_toma == date(2024, 3, 1)
# From the scanned report, on the very same row:
assert row.cit_vph_resultado == "POSITIVO"
def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
"""The report has a picture of the mammogram alongside its narrative
text; `imagen` (like `documento`, the combined PDF) is mappable onto any
target column, so it lands in `mast_dicom_blob` next to the fields read
from the surrounding text."""
report = text_pdf(
[["LABORATORIO DE IMAGENOLOGIA", "Expediente: IMG-0001", "Interpretación: nódulo circunscrito en cuadrante superior externo."]],
image_on_page=1,
)
mapping = {"pac_id_hospital": "pac_id_hospital", "mast_interpretacion": "mast_interpretacion", "imagen": "mast_dicom_blob"}
source = _document_source([("reporte.pdf", report)], "cama.Mastografia", mapping)
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 1, result
from persistance.cama import mastografia_repository
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
assert "nódulo circunscrito" in row.mast_interpretacion
assert row.mast_dicom_blob.startswith(b"\x89PNG")
+233
View File
@@ -0,0 +1,233 @@
import pytest
from pydantic import ValidationError
from webapi.imports.mapping.column_matcher import ColumnMatcher
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
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
def test_paciente_schema_required_field_missing():
with pytest.raises(ValidationError) as excinfo:
PacienteImportSchema(pac_sexo="F")
errors = excinfo.value.errors()
assert any(e["loc"] == ("pac_id_hospital",) for e in errors)
def test_paciente_schema_coerces_sexo_alias():
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="f", pac_fecha_nacimiento="1990-01-15")
assert schema.pac_sexo == "Femenino"
schema2 = PacienteImportSchema(pac_id_hospital="H-2", pac_sexo="MASCULINO", pac_fecha_nacimiento="1990-01-15")
assert schema2.pac_sexo == "Masculino"
def test_paciente_schema_rejects_unknown_sexo():
with pytest.raises(ValidationError):
# pac_sexo has no enum constraint on the storage model, but this is
# still a plain string field; feed something structurally invalid
# (a date field) to prove type validation happens
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
def test_paciente_schema_coerces_date_from_iso_string():
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="2020-01-15")
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
def test_paciente_schema_coerces_date_from_datetime_object():
from datetime import datetime
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento=datetime(2020, 1, 15, 10, 30))
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
def test_tea_pacientes_schema_is_fully_optional():
schema = PacientesImportSchema()
assert schema.pac_id_hospital is None
def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict():
schema = PacientesImportSchema(pac_sexo="f")
assert schema.pac_sexo == "F"
def test_tea_pacientes_schema_coerces_parentesco():
schema = PacientesImportSchema(pac_parentesco="hijo")
assert schema.pac_parentesco == "HIJO"
def test_classify_error_missing():
try:
PacienteImportSchema(pac_sexo="F")
except ValidationError as exc:
classified = [classify_error(e) for e in exc.errors()]
assert any(c.category == ErrorCategory.MISSING and c.field == "pac_id_hospital" for c in classified)
def test_classify_error_type_invalid():
try:
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
except ValidationError as exc:
classified = [classify_error(e) for e in exc.errors()]
assert any(c.category == ErrorCategory.TYPE_INVALID for c in classified)
def test_validate_rows_never_aborts_on_a_bad_row():
rows = [
{"pac_id_hospital": "H-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1990-01-15"},
{"pac_sexo": "M"}, # missing required fields
{"pac_id_hospital": "H-3", "pac_fecha_nacimiento": "1990-01-15"},
]
result = validate_rows(PacienteImportSchema, rows)
assert result.total_rows == 3
assert result.valid_count == 2
assert result.error_count == 1
assert result.rejected[0].row_index == 1
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
matcher = ColumnMatcher()
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
suggestions = matcher.suggest(
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
)
by_source = {s.source_column: s for s in suggestions}
assert by_source["pac_id_hospital"].reason == "exact"
assert by_source["pac_id_hospital"].target_field == "pac_id_hospital"
assert by_source["Sexo"].reason == "synonym"
assert by_source["Sexo"].target_field == "pac_sexo"
assert by_source["fecha_nacimiento"].reason in ("synonym", "fuzzy")
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
assert by_source["columna_sin_relacion_xyz"].target_field is None
assert by_source["columna_sin_relacion_xyz"].reason == "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"])
matched_targets = [s.target_field for s in suggestions if s.target_field]
assert matched_targets == ["pac_sexo"] # only the first claims it
def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dates():
from datetime import date, datetime
from webapi.imports.schemas.coercion import coerce_date
assert coerce_date("1990-01-15") == date(1990, 1, 15)
assert coerce_date("15/01/1990") == date(1990, 1, 15)
assert coerce_date("15-01-1990") == date(1990, 1, 15)
assert coerce_date("1990-01-15 00:00:00") == date(1990, 1, 15)
assert coerce_date(datetime(1990, 1, 15, 8, 30)) == date(1990, 1, 15)
assert coerce_date(" ") is None
with pytest.raises(ValueError, match="no es una fecha válida"):
coerce_date("31/02/1990")
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
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
assert coerce_alias(" femenino ", catalog) == "Femenino"
assert coerce_alias("m", catalog) == "Masculino"
assert coerce_alias("", catalog) is None
with pytest.raises(ValueError, match="no está en el catálogo"):
coerce_alias("X", catalog)
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
"""`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C
from narrative text (a standard ACR BI-RADS subcategory), but the schema
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
catalog = Catalog(BIRADS, BIRADS_ALIAS)
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
assert coerce_alias(value, catalog) == "B4"
def test_postal_code_restores_leading_zero_from_numeric_sources():
from webapi.imports.schemas.coercion import coerce_postal_code
assert coerce_postal_code(1000) == "01000"
assert coerce_postal_code(64000.0) == "64000"
assert coerce_postal_code(" 01000 ") == "01000"
assert coerce_postal_code("") is None
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)
}
assert by_source["Género"].target_field == "pac_sexo"
assert by_source["C.P."].target_field == "pac_codigo_postal"
assert by_source["Expediente"].target_field == "pac_id_hospital"
# The synonym "fecha_nacimiento" wins pac_fecha_nacimiento even
# though the weaker fuzzy "Fech nacim" comes first in the file.
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
assert by_source["Fech nacim"].target_field is None
def test_column_matcher_matches_names_without_the_table_prefix():
suggestion = ColumnMatcher().suggest(["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")]
@pytest.mark.parametrize(
"target, source, expected",
[
# Match on shared meaning, not shared suffixes ("solicitaDO" vs "solicitaNTE").
("cacu.OrdenesEstudio", "Estudio solicitado", "ord_tipo_estudio"),
("cacu.OrdenesEstudio", "Paciente", "pac_id_hospital"),
("cacu.NotaMedica", "Servicio", "nm_especialidad"),
("cacu.NotaMedica", "Fecha consulta", "nm_fecha"),
("cacu.NotaMedica", "Peso (kg)", "nm_masa_corporal"),
# Flattened JSON paths match by their last segment; unprefixed fields by their words.
("cacu.BiometriaHematica", "paciente.expediente", "pac_id_hospital"),
("cacu.BiometriaHematica", "resultados.hemoglobina", "hemoglobina_g_dl"),
("cacu.BiopsiaCervical", "Fecha de reporte", "bx_fecha_reporte"),
],
)
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
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
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
from webapi.imports.schemas.coercion import Catalog
catalog = PacienteImportSchema.catalog_for("pac_sexo")
assert isinstance(catalog, Catalog)
assert catalog.choices["F"] == "Femenino"
assert PacienteImportSchema.catalog_for("pac_codigo_postal") is None
with pytest.raises(ValidationError) as excinfo:
PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="X", pac_fecha_nacimiento="1990-01-15")
(error,) = excinfo.value.errors()
classified = classify_error(error)
assert classified.field == "pac_sexo"
assert classified.category == ErrorCategory.OUT_OF_CATALOG
assert "no está en el catálogo" in classified.message
+92
View File
@@ -0,0 +1,92 @@
"""Smoke-tests that every `ENTITY_REGISTRY` import schema is importable and
constructible, plus spot checks of enum-alias coercion."""
import pytest
from pydantic import ValidationError
from webapi.imports.schemas.registry import ENTITY_REGISTRY
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
# Domains whose Core layer is fully permissive (every field Optional);
# see `tea/pacientes.py`'s docstring. CaCu/CaMa entities all carry at least
# one business-required field (`pac_id_hospital` and friends).
_FULLY_OPTIONAL_PREFIXES = ("tea.",)
@pytest.mark.parametrize("entity_key", list(ENTITY_REGISTRY.keys()))
def test_every_registered_schema_is_constructible(entity_key):
spec = ENTITY_REGISTRY[entity_key]
schema_cls = spec.schema
if entity_key.startswith(_FULLY_OPTIONAL_PREFIXES):
# Fully permissive: an empty row must construct cleanly.
instance = schema_cls()
assert instance is not None
else:
# Has at least one required field: an empty row must be rejected.
with pytest.raises(ValidationError):
schema_cls()
def test_entity_registry_has_twenty_two_entries():
assert len(ENTITY_REGISTRY) == 22
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 "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 "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.
def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio():
with pytest.raises(ValidationError) as excinfo:
CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1")
errors = excinfo.value.errors()
assert any(e["loc"] == ("ord_numero_hospital",) for e in errors)
schema = CamaOrdenesEstudioImportSchema(
pac_id_hospital="H-1", ord_numero_hospital=12345, ord_tipo_estudio="biopsia chica"
)
assert schema.ord_tipo_estudio == "BIOPSIA_CHICA"
# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds
# a Catalog from the Enum alone, as in tea/pacientes.py.
def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict():
schema = EegEstudioImportSchema(eeg_simetria="simetrico")
assert schema.eeg_simetria == "SIMETRICO"
# CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS).
def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
schema = BiopsiaCervicalImportSchema(
pac_id_hospital="H-1",
bx_cin_grado="LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO",
)
assert schema.bx_cin_grado == "LIEBG"
with pytest.raises(ValidationError):
BiopsiaCervicalImportSchema(bx_cin_grado="LIEBG") # pac_id_hospital missing
+96
View File
@@ -0,0 +1,96 @@
"""The SQL connector is the one import path where the client chooses what
the server connects to; these tests pin its guard rails (see
webapi.imports.connectors.sql_policy)."""
import pytest
import sqlalchemy as sa
from webapi.imports.connectors.errors import ConnectorError
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
)
def test_sqlite_is_refused_by_default_policy(tmp_path):
with pytest.raises(ConnectorError, match="dialect 'sqlite' is not allowed"):
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"):
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"
def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
from persistance import settings as persistance_settings
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"):
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"):
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")
@pytest.mark.parametrize(
"query",
[
"DELETE FROM paciente",
"select 1; drop table paciente",
"UPDATE t SET a = 1",
"-- harmless\nDROP TABLE t",
"",
],
)
def test_only_single_select_queries_pass(query):
with pytest.raises(ConnectorError):
SqlSourcePolicy.check_query(query)
@pytest.mark.parametrize("query", ["SELECT * FROM t;", " with x as (select 1 as a) select a from x", "/* c */ SELECT 1"])
def test_select_queries_pass(query):
assert SqlSourcePolicy.check_query(query)
def test_connection_is_read_only_even_for_a_select_shaped_write(tmp_path):
db = tmp_path / "src.db"
engine = sa.create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(sa.text("CREATE TABLE t (a INTEGER)"))
conn.execute(sa.text("INSERT INTO t VALUES (1), (2)"))
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None))
with pytest.raises(ConnectorError):
# Passes the keyword check, but the read-only connection refuses it.
connector.select_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d").preview()
with engine.connect() as conn:
assert conn.execute(sa.text("SELECT COUNT(*) FROM t")).scalar_one() == 2
def test_preview_only_fetches_the_limit_but_counts_everything(tmp_path):
db = tmp_path / "big.db"
engine = sa.create_engine(f"sqlite:///{db}")
with engine.begin() as conn:
conn.execute(sa.text("CREATE TABLE t (id INTEGER, cp TEXT)"))
conn.execute(sa.text("INSERT INTO t VALUES " + ",".join(f"({i}, '0{i:04d}')" for i in range(500))))
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_table("t")
preview = connector.preview(limit=5)
assert len(preview.sample_rows) == 5
assert preview.total_rows == 500
assert {c.name: c.inferred_type for c in preview.columns} == {"id": "integer", "cp": "string"}
custom = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_query(
"SELECT id AS expediente FROM t WHERE id < 10"
)
assert custom.preview(limit=3).total_rows == 10
assert list(custom.read_rows({"expediente": "pac_id_hospital"}))[:2] == [{"pac_id_hospital": 0}, {"pac_id_hospital": 1}]