Source types, connection test, server folders, uploads and OAuth sign-in for the Conectar dialog; sign-in for the web app with fastapi-users, the API left open

This commit is contained in:
Roberto Treviño
2026-11-28 09:29:59 -06:00
parent d3f7aeb537
commit b515746406
10 changed files with 749 additions and 26 deletions
+20
View File
@@ -0,0 +1,20 @@
"""In-process API tests: a platform of their own (never the deployed data folder)."""
import pytest
from webapi import sources, users
@pytest.fixture
def own_platform(tmp_path, monkeypatch):
"""The API's data folder, platform database and sign-in in tmp_path."""
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
monkeypatch.setattr(sources, "DATA_DIR", tmp_path)
monkeypatch.setattr(users, "DATA_DIR", tmp_path)
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
monkeypatch.delenv("AUTH_SECRET", raising=False)
users._engine.cache_clear()
users._secret.cache_clear()
yield tmp_path
users._engine.cache_clear()
users._secret.cache_clear()
+1 -1
View File
@@ -53,7 +53,7 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, site,
with engine.connect() as con:
pdf = con.execute(text("select Archivo from dbo.ResultadoSubrogado where Id = 1")).scalar()
engine.dispose()
uploaded = ok(api.post("/ingest/uploads", files={"file": ("informe.pdf", pdf)}))
uploaded = ok(api.post("/ingest/uploads", files={"files": ("informe.pdf", pdf)}))
mailed = {
"id": "mailed",
"kind": "source",
+164
View File
@@ -0,0 +1,164 @@
"""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):
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, "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"
)
+49
View File
@@ -0,0 +1,49 @@
"""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):
for path in ("/health", "/domains", "/ingest/pipelines", "/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
+8 -1
View File
@@ -33,4 +33,11 @@ def test_every_page_loads_from_the_api(api, platform, site):
ok(api.put("/ingest/pipelines/site", json=json.loads(site.drawn)))
run(api, "site")
subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
env={**os.environ, "API_URL": str(api.base_url).rstrip("/")}) # fmt: skip
env={**os.environ, "API_URL": str(api.base_url).rstrip("/"),
"SITE_URL": site.url}) # fmt: skip
# The dialog's source is the one an operator draws by hand for this site.
drawn = json.loads(site.drawn)["nodes"][0]
made = ok(api.get("/ingest/pipelines/asistente"))["pipeline"]["nodes"][0]
assert made["guided"]["type"] == "sqlserver" and made["source"] == drawn["source"]
assert {k: v for k, v in made["args"].items() if k != "credentials"} == {
k: v for k, v in drawn["args"].items() if k != "credentials"} # fmt: skip