Files
WebApi/tests/test_conectar.py
T

178 lines
9.0 KiB
Python

"""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
# The site's codes in platform terms: a ConceptMap, saved before the drawing that names
# it. One that maps onto a code no field allows is refused, saying which.
drawn = json.loads(messy_site.drawn)
missing = api.put("/ingest/pipelines/site", json=drawn)
assert missing.status_code == 422 and "messy_site" in missing.text
codes = json.loads(messy_site.concept_map.read_text())
wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"'))
refused = api.put("/ingest/concept-maps/messy_site", json=wrong)
assert refused.status_code == 422 and "BIRADS-7 is not an allowed code" in refused.text
assert ok(api.put("/ingest/concept-maps/messy_site", json=codes)) == {"version": 1}
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
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"))
}
reports = sum(1 for r in truth if r["where"].startswith("ArchivosUni:"))
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == reports
# 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, before = {}, {}
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
whose.setdefault(person, set()).add(patient[record])
before[record] = person
# A queued person or candidate is one of its records (decisions are kept by record).
whose |= {record: whose[person] for record, person in before.items()}
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)
merges = 0
for entry in persons["to_settle"]:
for c in entry["candidates"]:
same = whose[entry["person"]] == whose[c["candidate"]]
merges += same
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)
# A row a rule held because its value is wrong (a scan misread) is rejected after a look
# at the document; rows of the torn person wait for the correction above.
misread = [
h for h in ok(api.get("/review/held", params=CYTOLOGY))
if not any("disagree on birth date" in why for why in h["_held"])
] # fmt: skip
for h in misread:
decision = CYTOLOGY | {"record": h["_record"], "reason": "misread in the scan"}
ok(api.post("/review/rejections", json=decision), 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)
# Person ids are stable: a person keeps an id her records had, and an id that went
# away (merged by the review) resolves to the person that replaced it.
after = dict(platform.query("select _record, person_id from bronze.n__site__persons"))
gone = set(before.values()) - set(after.values())
replaced = dict(platform.query("select person_id, replaced_by from silver.person_link"))
assert merges and len(gone) == merges and set(replaced) == gone
for old, new in replaced.items():
assert new in set(after.values())
assert any(before[r] == old and after[r] == new for r in before)
assert set(after.values()) <= set(before.values()) # no person got a new id
placed = platform.count("silver.cervical_cytology")
reports = sum(1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped"))
assert placed == reports - len(misread)