"""An operator connects a messy site through the API, the way the /conectar screens will: look into its sources, save the drawn pipeline, run it, read what came out, and settle what review shows. Real API and Dagster processes; nothing faked.""" import json import time SQL = "dlt.sources.sql_database:sql_database" CYTOLOGY = {"entity": "cervical_cytology"} def ok(response, status=200): assert response.status_code == status, response.text return response.json() def wait_for(api, run_id: str, seconds: int = 900) -> None: deadline = time.monotonic() + seconds while (status := ok(api.get(f"/runs/{run_id}"))["status"]) not in ("SUCCESS", "FAILURE"): assert time.monotonic() < deadline, f"run {run_id} still {status}" time.sleep(2) assert status == "SUCCESS" def run(api, pipeline: str) -> None: wait_for(api, ok(api.post(f"/ingest/pipelines/{pipeline}/runs", json={}))["run_id"]) def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy_site, tmp_path): site, truth = messy_site.path, messy_site.truth database = {"credentials": f"sqlite:///{site}/site.db"} # What the site has, and what one of its tables holds (documents shown by size). found = ok(api.post("/ingest/sources/resources", json={"source": SQL, "args": database})) assert found == ["ArchivosUni", "pacientes_his"] missing = {"credentials": f"sqlite:///{tmp_path}/nowhere/site.db"} unreachable = api.post("/ingest/sources/resources", json={"source": SQL, "args": missing}) assert unreachable.status_code == 422 and "unable to open" in unreachable.text reports = {"id": "reports", "kind": "source", "source": SQL, "args": database} sample = ok( api.post("/ingest/sources/preview?limit=3", json=reports | {"resource": "ArchivosUni"}) ) assert len(sample) == 3 and all(r["Archivo"].endswith(" bytes>") for r in sample) # A file someone uploads becomes a source like any other. csv = (site / "files" / "consultas.csv").read_bytes() uploaded = ok(api.post("/ingest/uploads", files={"file": ("consultas.csv", csv)})) notes = { "id": "notes", "kind": "source", "source": "dlt.sources.filesystem:readers", "resource": "read_csv", "args": {"bucket_url": uploaded["bucket_url"]}, } assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5 # Saving a drawing: broken ones are refused with the reason; good ones get versions. drawn = json.loads(messy_site.drawn) broken = { "nodes": [ *drawn["nodes"], {"id": "loose", "kind": "read", "inputs": ["gone"], "column": "x"}, ] } assert "no node" in api.put("/ingest/pipelines/site", json=broken).text assert ok(api.put("/ingest/pipelines/site", json=drawn)) == {"version": 1} assert ok(api.get("/ingest/pipelines/site"))["version"] == 1 # A password is never shown, and survives the UI sending the masked drawing back. secret = "postgresql://isss:S3cret@10.0.10.9/his" hidden = { "nodes": [{"id": "his", "kind": "source", "source": SQL, "args": {"credentials": secret}}] } ok(api.put("/ingest/pipelines/his", json=hidden)) shown = ok(api.get("/ingest/pipelines/his"))["pipeline"] assert "S3cret" not in json.dumps(shown) assert ok(api.put("/ingest/pipelines/his", json=shown)) == {"version": 2} stored = platform.query( "select doc from config.pipelines where pipeline_id = 'his' and version = 2" ) assert secret in stored[0][0] # Run it, and look at what any node produced. run(api, "site") reports_read = ok(api.get("/ingest/pipelines/site/nodes/archivos/rows?limit=500")) record_of = {f"ArchivosUni:{r['id']}": r["_record"] for r in reports_read} his = { r["_record"]: f"pacientes_his:{r['num']}" for r in ok(api.get("/ingest/pipelines/site/nodes/his_patients/rows?limit=500")) } assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == 53 # Review: reports that contradict each other, rows held because their person is torn # (a record number shared by two patients), and persons that may be one patient. conflicting = {record_of[r["where"]] for r in truth if r.get("conflict")} shown = {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))} assert shown and shown <= conflicting persons = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"})) assert persons["to_settle"] and len(persons["torn"]) == 1 # The reviewer settles all of it, checking each case against the source documents. patient = messy_site.patients(platform.query) whose = {} for record, person in platform.query("select _record, person_id from bronze.n__site__persons"): whose.setdefault(person, set()).add(patient[record]) for r in truth: if r.get("flipped"): decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"} ok(api.post("/review/rejections", json=decision), status=201) for entry in persons["to_settle"]: for c in entry["candidates"]: same = whose[entry["person"]] == whose[c["candidate"]] decision = {"person": entry["person"], "candidate": c["candidate"], "same": same} ok(api.post("/review/persons", json=decision), status=201) collision = {r["where"]: r for r in truth if r.get("collision")} for record in persons["torn"][0]["records"]: if (where := his.get(record["_record"])) in collision: fix = { "record": record["_record"], "field": "record_number", "value": collision[where]["true_record_number"], } ok(api.post("/review/corrections", json=fix), status=201) bad = {"record": "x", "field": "birth_date", "value": "not a date"} assert api.post("/review/corrections", json=bad).status_code == 422 # The next run applies every decision: one person per patient, nothing left to review, # and silver holds every report except the wrong copies. run(api, "site") assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == [] assert ok(api.get("/review/held", params=CYTOLOGY)) == [] left = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"})) assert left == {"to_settle": [], "torn": []} people = {r["person"] for r in truth if r["entity"] == "identity"} groups = {} for record, person in platform.query("select _record, person_id from bronze.n__site__persons"): groups.setdefault(person, set()).add(patient[record]) assert sorted(map(sorted, groups.values())) == sorted([p] for p in people) placed = platform.count("silver.cervical_cytology") assert placed == sum( 1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped") )