Merge origin/rebuild into parity/T1-merge (WebApi)
- main.py: both routers sets (execution, preview from tea/parity; sources, users from
rebuild).
- runs.py: tea/parity's cancel, history and execution config; rebuild's /terminate is the
same action and is not kept twice.
- eeg.py: tea/parity's (the record reads per-child FHIR resources, not rebuild's EEG
detail with zones and relation).
- fhir.py: tea/parity's patient rows with TEA filters, plus rebuild's name/identifier
search applied to whatever rows the request selects.
- models.py: tea/parity's endpoints; /models/{domain} returns rebuild's name + title.
- tests: P7 deletions kept (test_cacu, test_cama, test_conectar, test_synthea*, test_tea);
test_webapp keeps tea/parity's runner, now with the first administrator (sign-in).
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
"""Backups (persistance.backup): a platform's data backed up while it holds a site's
|
||||
configuration comes back whole into an empty platform, on SQLite and PostgreSQL; a damaged
|
||||
backup restores nothing; restoring over a platform needs --force and keeps what was there."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures"
|
||||
STORED = "select pipeline_id, version, doc from config.{kind} order by pipeline_id, version"
|
||||
|
||||
|
||||
def _stored(platform) -> list:
|
||||
"""Every saved version of every pipeline and concept map (a kind never saved: none)."""
|
||||
found = []
|
||||
for kind in ("pipelines", "concept_maps"):
|
||||
try:
|
||||
found += [tuple(r) for r in platform.query(STORED.format(kind=kind))]
|
||||
except Exception as e: # its table appears with its first save
|
||||
if "no such table" not in str(e) and "does not exist" not in str(e):
|
||||
raise
|
||||
return found
|
||||
|
||||
|
||||
def _backup(platform, cli: str, *args: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["python", "-m", "persistance.backup", cli, *args],
|
||||
env=platform.env, cwd=platform.env["ISSSTELEON_DATA"], capture_output=True, text=True,
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _made(platform, tmp_path_factory) -> Path:
|
||||
"""A backup of the platform, outside its data folder; its folder."""
|
||||
made = _backup(platform, "create", "--to", str(tmp_path_factory.mktemp("backups")))
|
||||
assert made.returncode == 0, made.stderr
|
||||
return Path(made.stdout.strip())
|
||||
|
||||
|
||||
def _reset(platform) -> None:
|
||||
"""The platform emptied, as on a new machine: its data folder and (PostgreSQL) schemas."""
|
||||
data = Path(platform.env["ISSSTELEON_DATA"])
|
||||
for p in data.iterdir():
|
||||
if p.name.startswith("platform") or p.name in ("dlt", "mlflow.db"):
|
||||
subprocess.run(["rm", "-rf", str(p)], check=True)
|
||||
if "postgres" in platform.env["PLATFORM_DATABASE_URL"]:
|
||||
for schema in ("bronze", "silver", "gold", "config"):
|
||||
subprocess.run(["psql", platform.env["PLATFORM_DATABASE_URL"], "-qc",
|
||||
f"drop schema if exists {schema} cascade"], check=True) # fmt: skip
|
||||
|
||||
|
||||
def test_a_backup_restores_the_site_whole(platform, tmp_path_factory):
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json")
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") # v2
|
||||
platform.save("concept_maps", "erick_site", FIXTURES / "concept_maps" / "erick_site.json")
|
||||
before = _stored(platform)
|
||||
assert len(before) == 3
|
||||
|
||||
made = _backup(platform, "create", "--to", str(tmp_path_factory.mktemp("backups")))
|
||||
assert made.returncode == 0, made.stderr
|
||||
folder = Path(made.stdout.strip())
|
||||
manifest = json.loads((folder / "manifest.json").read_text())
|
||||
assert all(len(f["sha256"]) == 64 for f in manifest["files"].values())
|
||||
assert _backup(platform, "verify", str(folder)).stdout.strip() == "ok"
|
||||
|
||||
# over a platform: refused without --force
|
||||
refused = _backup(platform, "restore", str(folder))
|
||||
assert refused.returncode != 0 and "--force" in refused.stderr
|
||||
|
||||
_reset(platform)
|
||||
assert not any(n.startswith("platform") for n in
|
||||
(p.name for p in Path(platform.env["ISSSTELEON_DATA"]).iterdir())) # fmt: skip
|
||||
restored = _backup(platform, "restore", str(folder))
|
||||
assert restored.returncode == 0, restored.stderr
|
||||
assert _stored(platform) == before
|
||||
|
||||
|
||||
def test_a_damaged_backup_restores_nothing(platform, tmp_path_factory):
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json")
|
||||
folder = _made(platform, tmp_path_factory)
|
||||
damaged = next(p for p in folder.rglob("*") if p.is_file() and p.name != "manifest.json")
|
||||
damaged.write_bytes(damaged.read_bytes() + b"\0") # one byte more
|
||||
checked = _backup(platform, "verify", str(folder))
|
||||
assert checked.returncode == 1 and "changed since the backup" in checked.stdout
|
||||
|
||||
restored = _backup(platform, "restore", str(folder), "--force")
|
||||
assert restored.returncode != 0 and "damaged" in restored.stderr
|
||||
assert len(_stored(platform)) == 1 # the platform as it was
|
||||
|
||||
|
||||
def test_restoring_over_a_platform_keeps_what_was_there(fresh_platform, tmp_path_factory):
|
||||
"""SQLite: what the data folder held is set aside, not mixed with the backup's."""
|
||||
platform = fresh_platform
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json")
|
||||
folder = _made(platform, tmp_path_factory)
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") # newer
|
||||
assert _backup(platform, "restore", str(folder), "--force").returncode == 0
|
||||
assert len(_stored(platform)) == 1 # the backup's moment, nothing newer mixed in
|
||||
aside = list(Path(platform.env["ISSSTELEON_DATA"]).glob(".before-restore-*"))
|
||||
assert len(aside) == 1 and any(aside[0].glob("platform__config.db"))
|
||||
@@ -0,0 +1,165 @@
|
||||
"""The Conectar dialog's API: an operator who knows nothing of dlt picks a kind of source,
|
||||
answers its questions, and "Probar conexión" says in plain words what it found."""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import make_url
|
||||
|
||||
from webapi import sources
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared"))
|
||||
(own_platform / "shared" / "reportes" / "2026").mkdir(parents=True)
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def probe(client, kind, **answers):
|
||||
response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers})
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_the_dialog_lists_every_kind_with_its_questions(client):
|
||||
found = client.get("/ingest/sources/types").json()
|
||||
assert {"database", "files", "cloud", "web"} <= set(found["groups"])
|
||||
assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password"
|
||||
|
||||
|
||||
def test_erick_sql_server_through_the_dialog(client, site):
|
||||
url = make_url(site.url)
|
||||
answers = {"host": url.host, "port": url.port, "database": url.database,
|
||||
"user": url.username, "password": url.password} # fmt: skip
|
||||
found = probe(client, "sqlserver", **answers)
|
||||
assert found["ok"] and found["tables"] == ["ResultadoSubrogado"]
|
||||
rows = probe(client, "sqlserver", **answers, table="ResultadoSubrogado")["rows"]
|
||||
assert rows and all(r["Archivo"].endswith(" bytes>") for r in rows)
|
||||
wrong = probe(client, "sqlserver", **answers | {"password": "not-it"})
|
||||
assert not wrong["ok"] and "contraseña" in wrong["message"] and wrong["detail"]
|
||||
|
||||
|
||||
def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client):
|
||||
gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u",
|
||||
password="p") # fmt: skip
|
||||
assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no"))
|
||||
assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not os.environ.get("POSTGRES_TEST_URL"), reason="needs PostgreSQL")
|
||||
def test_postgresql_through_the_dialog(client):
|
||||
url = make_url(os.environ["POSTGRES_TEST_URL"])
|
||||
found = probe(client, "postgresql", host=url.host, port=url.port or 5432,
|
||||
database=url.database, user=url.username, password=url.password) # fmt: skip
|
||||
assert found["ok"], found
|
||||
|
||||
|
||||
def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform):
|
||||
path = own_platform / "shared" / "hospital.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("create table pacientes (id int, nombre text)")
|
||||
con.execute("insert into pacientes values (1, 'Ana')")
|
||||
assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"]
|
||||
rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"]
|
||||
assert rows == [{"id": 1, "nombre": "Ana"}]
|
||||
|
||||
|
||||
def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform):
|
||||
roots = client.get("/ingest/sources/browse").json()["entries"]
|
||||
assert [e["name"] for e in roots] == ["shared"]
|
||||
inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json()
|
||||
assert [e["name"] for e in inside["entries"]] == ["reportes"]
|
||||
assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404
|
||||
escape = str(own_platform / "shared" / ".." / "data")
|
||||
assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404
|
||||
|
||||
|
||||
def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client):
|
||||
sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")),
|
||||
("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip
|
||||
uploaded = client.post("/ingest/uploads", files=sent).json()
|
||||
assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"]
|
||||
more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))],
|
||||
data={"folder": uploaded["bucket_url"]}).json() # fmt: skip
|
||||
assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"]
|
||||
other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"})
|
||||
assert other.status_code == 422
|
||||
rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv",
|
||||
read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip
|
||||
assert rows == [{"folio": 1, "resultado": "NEGATIVO"}]
|
||||
files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"]
|
||||
assert [f["file_name"] for f in files] == ["b.pdf"]
|
||||
|
||||
|
||||
def test_an_empty_folder_says_what_to_check(client, own_platform):
|
||||
found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes"))
|
||||
assert found["ok"] and "Revise la ruta" in found["message"]
|
||||
|
||||
|
||||
def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client):
|
||||
found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"})
|
||||
assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"]
|
||||
|
||||
|
||||
def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path):
|
||||
from authlib.integrations.httpx_client import OAuth2Client, oauth2_client
|
||||
|
||||
httpx = oauth2_client.httpx2 # the HTTP library this authlib is built on
|
||||
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
||||
exchanged = {}
|
||||
|
||||
def provider(request: httpx.Request) -> httpx.Response: # the token endpoint
|
||||
exchanged["body"] = request.content.decode()
|
||||
return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt",
|
||||
"token_type": "Bearer", "expires_in": 3600}) # fmt: skip
|
||||
|
||||
def client_for(found, env, redirect_uri):
|
||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope,
|
||||
redirect_uri=redirect_uri, code_challenge_method="S256",
|
||||
transport=httpx.MockTransport(provider)) # fmt: skip
|
||||
|
||||
monkeypatch.setattr(sources, "_client", client_for)
|
||||
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending") # any worker's callback
|
||||
monkeypatch.setattr(sources, "account", lambda p, token, env: {
|
||||
"user": "ana@hospital.mx", "drive_id": "d1",
|
||||
"oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip
|
||||
start = client.get("/ingest/sources/oauth/microsoft/start",
|
||||
params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip
|
||||
assert start["url"].startswith("https://login.microsoftonline.com/organizations/")
|
||||
assert "code_challenge=" in start["url"] and "client_id=app" in start["url"]
|
||||
back = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert back.status_code == 200
|
||||
assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text
|
||||
assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"]
|
||||
again = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert again.status_code == 400 # a sign-in is used once
|
||||
|
||||
|
||||
def test_a_saved_account_shows_who_but_never_its_tokens():
|
||||
from core.pipeline import MASK, Pipeline, redacted, restored
|
||||
|
||||
params = {"client_id": "app", "client_secret": "app-secret-xyz",
|
||||
"token": {"refresh_token": "refresh-xyz"}} # fmt: skip
|
||||
account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params}
|
||||
saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": {
|
||||
"type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip
|
||||
shown = redacted(saved)
|
||||
answer = shown.nodes[0].guided.answers["account"]
|
||||
assert answer["user"] == "ana@hospital.mx"
|
||||
dumped = shown.model_dump_json()
|
||||
assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped
|
||||
assert answer["oauth2_client_params"]["client_secret"] == MASK
|
||||
back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0]
|
||||
assert (
|
||||
back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"]
|
||||
== "refresh-xyz"
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Sign-in for the web app: an administrator from the environment, users who see some
|
||||
domains, a session cookie, and an API that answers everyone as before."""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx")
|
||||
monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga")
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def login(client, email, password):
|
||||
return client.post("/auth/login", data={"username": email, "password": password})
|
||||
|
||||
|
||||
def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
||||
assert client.get("/users/me").status_code == 401
|
||||
assert login(client, "admin@isssteleon.mx", "mala").status_code == 400
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
me = client.get("/users/me").json()
|
||||
assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"]
|
||||
team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu",
|
||||
"domains": ["cacu"]} # fmt: skip
|
||||
assert client.post("/users/register", json=team).status_code == 201
|
||||
client.post("/auth/logout")
|
||||
assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204
|
||||
assert client.get("/users/me").json()["domains"] == ["cacu"]
|
||||
other = {"email": "x@isssteleon.mx", "password": "otra-clave"}
|
||||
assert client.post("/users/register", json=other).status_code == 403 # not an admin
|
||||
|
||||
|
||||
def test_the_api_answers_without_a_session(client):
|
||||
# routes that read no platform data (the in-process app's database is the default one)
|
||||
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
||||
assert client.get(path).status_code == 200, path
|
||||
|
||||
|
||||
def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform):
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
secret = (own_platform / "auth_secret").read_text()
|
||||
with TestClient(app): # the app starts again on the same data
|
||||
pass
|
||||
assert (own_platform / "auth_secret").read_text() == secret
|
||||
assert client.get("/users/me").status_code == 200 # the session still holds
|
||||
@@ -78,6 +78,8 @@ def _platform(data: Path):
|
||||
"MLFLOW_DISABLE_AGENT_HINT": "1",
|
||||
"EXECUTION_MODE": "sync",
|
||||
"TEA_REFERENCE_ROOT": str(data / "reference"),
|
||||
"AUTH_ADMIN_EMAIL": "admin@isssteleon.mx",
|
||||
"AUTH_ADMIN_PASSWORD": "solo-para-pruebas",
|
||||
}
|
||||
webserver = subprocess.Popen(
|
||||
["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1",
|
||||
|
||||
Reference in New Issue
Block a user