"""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" )