Files
ISSSTELEON/tests/test_cacu_evidence_dates.py
T
edgar ba81ab811f Preparar la evidencia fuente y la elegibilidad CaCu por visita
01a: fechas clínicas, disponibilidad en origen y referencia por campo; evidencia FHIR independiente.
01b (parcial): proyección de elegibilidad por instancia y lector con comprobación del esquema gold.

Pendiente: las exclusiones propias de cada escenario conservan solo el motivo prioritario; fechas FHIR parciales o sin zona, estados de resultado y actualización desde instalaciones anteriores. Ver PLAN_CONTEXTO_CACU.md.
2026-12-02 15:38:10 -06:00

131 lines
6.6 KiB
Python

"""Source evidence dates through the CaCu FHIR and document targets, staging and gold."""
import json
from datetime import date
from core import catalog, fhir_in
from core.pipeline import RECORD, Fhir, Target
from models.graph import run_fhir, run_target
from persistance import destination, gold, nodes, silver
def _coding(system, code):
return {"coding": [{"system": system, "code": code}]}
def _bundle(*resources):
return {"resourceType": "Bundle", "type": "collection", "entry": [
{"resource": resource} for resource in resources
]} # fmt: skip
def test_cacu_source_dates_survive_late_import_and_missing_release(tmp_path, monkeypatch):
"""Replays independent resources, a linked result and extracted notes through gold."""
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
monkeypatch.setenv("DLT_DATA_DIR", str(tmp_path / "dlt"))
monkeypatch.setenv("DBT_TARGET", "sqlite")
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
destination.engine.cache_clear()
engine = destination.engine()
subject = {"reference": "Patient/p1"}
patient = {"resourceType": "Patient", "id": "p1", "birthDate": "1980-01-01"}
observation = {
"resourceType": "Observation", "id": "hpv", "subject": subject, "status": "final",
"code": _coding(fhir_in.FIELD, "cervical_cytology.hpv"), "valueBoolean": True,
"effectiveDateTime": "2025-01-05", "issued": "2025-01-18T12:00:00-06:00",
} # fmt: skip
report = {
"resourceType": "DiagnosticReport", "id": "c1", "subject": subject, "status": "final",
"effectiveDateTime": "2025-01-04", "issued": "2025-01-10T15:00:00Z",
"code": _coding(fhir_in.STUDY, "cervical_cytology"),
"result": [{"reference": "Observation/hpv"}],
} # fmt: skip
condition = {
"resourceType": "Condition", "id": "dx", "subject": subject,
"code": _coding(catalog.systems()["icd-10"].url, "Z90.7"),
"onsetDateTime": "2025-01-02", "recordedDate": "2025-01-12",
} # fmt: skip
exam = {
"resourceType": "Observation", "id": "exam", "subject": subject, "status": "final",
"code": _coding(fhir_in.FIELD, "cervical_cytology.gynecologic_condition"),
"valueCodeableConcept": _coding(catalog.systems()["gynecologic-condition"].url,
"hysterectomy"),
"effectiveDateTime": "2025-01-03", "meta": {"lastUpdated": "2025-01-10T13:00:00Z"},
} # fmt: skip
try:
nodes.write("hospital", "inbox", [
{"doc": json.dumps(_bundle(patient, report)), "received_at": "2025-02-19"},
{"doc": json.dumps(_bundle(observation, condition, exam)), "received_at": "2025-02-20"},
])
kinds = {
"persons": "link", "notes": "extract", "cervical_cytology": "fhir",
fhir_in.EVIDENCE: "fhir",
}
run_fhir("hospital", Fhir(id="identity", label="Identity", inputs=["inbox"],
entity="identity"))
linked = {row[RECORD] for row in nodes.rows("hospital", "identity")}
assert fhir_in.record("hospital", "Condition/dx") in linked
assert fhir_in.record("hospital", "Observation/exam") in linked
nodes.write("hospital", "persons", [
{RECORD: record, "person_id": "p1"} for record in sorted(linked | {"signed-note"})
])
nodes.stage("identity", "hospital", "persons", [{
RECORD: "patient", "person_id": "p1", "record_number": "TEST-P1",
"birth_date": date(1980, 1, 1),
}], silver.identity_columns())
for entity in ("cervical_cytology", fhir_in.EVIDENCE):
run_fhir("hospital", Fhir(id=entity, label=entity, inputs=["inbox"], entity=entity))
run_target("hospital", Target(id=f"{entity}_out", label=entity,
inputs=[entity, "persons"], entity=entity), kinds)
nodes.write("hospital", "notes", [{
RECORD: "signed-note", "note_date": "2025-01-12",
"specialty": "family_medicine", "icd10": "Z90.7",
}])
run_target("hospital", Target(id="notes_out", label="Notes",
inputs=["notes", "persons"], entity="clinical_note"), kinds)
silver.build(
["+cacu_events", "+cacu_eligibility_evidence", "+cacu_eligibility"],
as_of=date(2025, 2, 21),
)
eligibility = gold.cacu_eligibility_report("surveillance", "p1")
# The hysterectomy onset predates the index, but the FHIR Condition was recorded
# after it, so it cannot exclude the patient at that visit.
assert "hysterectomy" not in eligibility["criterion"].tolist()
with engine.connect() as con:
normalized = con.exec_driver_sql(
"select type, value_code, evidence_date, source_available_at "
"from gold.cacu_events where type = 'gynecologic_condition' "
"and value_code = 'hysterectomy' order by evidence_date"
).all()
assert normalized == [
("gynecologic_condition", "hysterectomy", "2025-01-02", "2025-01-12"),
("gynecologic_condition", "hysterectomy", "2025-01-03", None),
("gynecologic_condition", "hysterectomy", "2025-01-12", "2025-01-12"),
]
found = con.exec_driver_sql(
"select date, evidence_date, source_available_at, source_ref, known_at "
"from gold.cacu_events where type in ('hpv', 'note') "
"union all select date, evidence_date, source_available_at, source_ref, known_at "
"from gold.cacu_eligibility_evidence"
).all()
dates = {row[3]: row[:3] for row in found}
assert dates == {
"hospital|Observation/hpv": ("2025-01-10", "2025-01-05",
"2025-01-18T18:00:00.000000+00:00"),
"hospital|Condition/dx": ("2025-01-02", "2025-01-02", "2025-01-12"),
"hospital|Observation/exam": ("2025-01-03", "2025-01-03", None),
"signed-note": ("2025-01-12", "2025-01-12", "2025-01-12"),
}
assert all(str(row[4])[:10] > "2025-02-20" for row in found)
# A Jan 15 evaluation uses what was documented by the source, even with a late import.
assert {ref for ref, (_, clinical, available) in dates.items()
if clinical < "2025-01-15" and available and available[:10] <= "2025-01-15"} == {
"hospital|Condition/dx", "signed-note",
}
finally:
engine.dispose()
destination.engine.cache_clear()