204 lines
11 KiB
Python
204 lines
11 KiB
Python
"""An operator connects ISSSTELEON's test source through the API, the way the /conectar
|
|
screens do: look into its tables, 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
|
|
|
|
from sqlalchemy import create_engine, make_url, text
|
|
|
|
SQL = "dlt.sources.sql_database:sql_database"
|
|
CYTOLOGY = {"entity": "cervical_cytology"}
|
|
STUDIES = ("cervical_cytology", "cervical_biopsy", "mammography", "breast_biopsy",
|
|
"breast_treatment", "clinical_note") # fmt: skip
|
|
|
|
|
|
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, site, tmp_path):
|
|
truth = site.truth
|
|
database = {"credentials": site.url, "schema": "dbo"}
|
|
|
|
# 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", "ResultadosSubrogados"]
|
|
missing = {"credentials": "mssql+pymssql://sa:x@nowhere.invalid:1433/Pruebas"}
|
|
unreachable = api.post("/ingest/sources/resources", json={"source": SQL, "args": missing})
|
|
assert unreachable.status_code == 422, 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 (a report sent by mail) becomes a source like any other.
|
|
engine = create_engine(site.url)
|
|
with engine.connect() as con:
|
|
pdf = con.execute(text("select Archivo from dbo.ArchivosUni where Id = 1")).scalar()
|
|
engine.dispose()
|
|
uploaded = ok(api.post("/ingest/uploads", files={"file": ("informe.pdf", pdf)}))
|
|
mailed = {
|
|
"id": "mailed",
|
|
"kind": "source",
|
|
"source": "dlt.sources.filesystem:filesystem",
|
|
"args": {"bucket_url": uploaded["bucket_url"]},
|
|
"then": "persistance.readers:read_bytes",
|
|
}
|
|
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=mailed))) == 1
|
|
|
|
# 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(site.drawn)
|
|
missing = api.put("/ingest/pipelines/site", json=drawn)
|
|
assert missing.status_code == 422 and "erick_site" in missing.text
|
|
codes = json.loads(site.concept_map.read_text())
|
|
wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"'))
|
|
refused = api.put("/ingest/concept-maps/erick_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/erick_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.
|
|
shown = ok(api.get("/ingest/pipelines/site"))["pipeline"]
|
|
password = make_url(site.url).password
|
|
assert password not in json.dumps(shown)
|
|
assert ok(api.put("/ingest/pipelines/site", json=shown)) == {"version": 2}
|
|
stored = platform.query(
|
|
"select doc from config.pipelines where pipeline_id = 'site' and version = 2"
|
|
)
|
|
assert site.url in stored[0][0]
|
|
|
|
# Run it, and look at what any node produced.
|
|
run(api, "site")
|
|
record_of = {}
|
|
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
|
|
rows = ok(api.get(f"/ingest/pipelines/site/nodes/{node}/rows?limit=500"))
|
|
record_of |= {f"{table}:{r['id']}": r["_record"] for r in rows}
|
|
assert len(record_of) == len(truth)
|
|
forms = sum(1 for r in truth if r["where"].startswith("ArchivosUni:")
|
|
and r["entity"] == "cervical_cytology") # fmt: skip
|
|
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == forms
|
|
|
|
# Review: reports that contradict each other, rows held because their person is torn
|
|
# (a pathology report that fits two women of one name), and persons that may be one.
|
|
# (a disputed cytology shows all its records: both HPV copies and the form they share)
|
|
disputed = {(r["person"], r["values"]["sample_date"]) for r in truth if r.get("conflict")}
|
|
conflicting = {record_of[r["where"]] for r in truth if r["entity"] == "cervical_cytology"
|
|
and (r["person"], r["values"]["sample_date"]) in disputed} # fmt: skip
|
|
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 = 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)
|
|
# The torn person: the pathology reports without a birth date get the one their woman's
|
|
# other documents show.
|
|
at = {record_of[r["where"]]: r for r in truth}
|
|
for record in persons["torn"][0]["records"]:
|
|
r = at[record["_record"]]
|
|
if "birth_date" not in r["identity"]:
|
|
fix = {"record": record["_record"], "field": "birth_date",
|
|
"value": site.meta["birth_dates"][r["person"]]} # fmt: skip
|
|
ok(api.post("/review/corrections", json=fix), status=201)
|
|
# A row a rule held because a value came out wrong (a scan misread: "lA" for a stage)
|
|
# gets the value the reviewer reads in the document; one with nothing to fix is
|
|
# rejected, but for the torn person's rows, which wait for the correction above.
|
|
misread = []
|
|
for study in STUDIES:
|
|
for h in ok(api.get("/review/held", params={"entity": study})):
|
|
torn = any("disagree on birth date" in why for why in h["_held"])
|
|
r = at[h["_record"]]
|
|
truly = r.get("clinical_note") if study == "clinical_note" else r["values"]
|
|
wrong = {f: v for f, v in truly.items()
|
|
if v is not None and str(h["_raw"].get(f)) != str(v)} # fmt: skip
|
|
for field, v in wrong.items():
|
|
fix = {"entity": study, "record": h["_record"], "field": field, "value": str(v)}
|
|
ok(api.post("/review/corrections", json=fix), status=201)
|
|
if not wrong and not torn:
|
|
decision = {"entity": study, "record": h["_record"], "reason": "misread"}
|
|
ok(api.post("/review/rejections", json=decision), status=201)
|
|
misread.append((h["_record"], study))
|
|
stage = {"entity": "breast_biopsy", "record": "x", "field": "stage", "value": "VII"}
|
|
assert api.post("/review/corrections", json=stage).status_code == 422
|
|
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 cytology but the wrong copies and the misreads.
|
|
run(api, "site")
|
|
assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == []
|
|
for study in STUDIES:
|
|
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
|
left = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"}))
|
|
assert left == {"to_settle": [], "torn": []}
|
|
people = {r["person"] for r in truth}
|
|
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)
|
|
# No person got a new id, but for the woman parted from the torn person (two namesakes
|
|
# one pathology report had joined): her records all come from that person.
|
|
new = set(after.values()) - set(before.values())
|
|
torn_id = persons["torn"][0]["person"]
|
|
assert len(new) <= 1
|
|
assert all(before[r] == torn_id for r, p in after.items() if p in new)
|
|
rejected = {r for r, study in misread if study == "cervical_cytology"}
|
|
rejected |= {record_of[r["where"]] for r in truth if r.get("flipped")}
|
|
cytologies = {(r["person"], r["values"]["sample_date"]) for r in truth
|
|
if r["entity"] == "cervical_cytology"
|
|
and record_of[r["where"]] not in rejected} # fmt: skip
|
|
assert platform.count("silver.cervical_cytology") == len(cytologies)
|