Files
WebApi/tests/test_cama_scenarios.py
T

109 lines
6.0 KiB
Python

"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`,
rules in `cama.escenarios`) and carried by her timeline with the evidence that started it and its level: screening from
her first mammogram before a diagnosis, control from a note with a malignant breast tumour ICD-10, post-treatment from
a discharge note after that diagnosis.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
(`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30,
H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30),
H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a
type: the tests that need a discharge write `nota_medica.tipo_nota` themselves.
"""
import os
from datetime import date
from pathlib import Path
import pytest
from conftest import base_de
from sqlalchemy import text
@pytest.fixture
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture
def base(tmp_path, manifest):
base = base_de("cama", tmp_path)
base.run("catalogs", "load", "views", "event_models")
yield base
base.motor.dispose()
def scenarios(base) -> dict[str, set[tuple[str, date, str, int]]]:
"""Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence, level)."""
with base.motor.connect() as con:
rows = con.execute(text(
"select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo, l.valor_numerico from cama_linea_de_tiempo l "
"join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all()
found: dict[str, set[tuple[str, date, str, int]]] = {}
for r in rows:
found.setdefault(r.pac_id_hospital, set()).add(
(r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo, int(r.valor_numerico)))
return found
def discharge(base, hospital_id: str) -> None:
"""Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would."""
with base.motor.begin() as con:
con.execute(text(
"insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) "
"select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' "
"from procedimiento p join paciente x on x.pac_id = p.pac_id "
"where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id})
def test_each_patient_s_scenario_follows_the_hierarchy(base):
"""Pins down: a first mammogram starts screening only before a diagnosis; a dated C50 note, whoever wrote it, starts
control; an invasive biopsy alone doesn't (control asks for the ICD-10); an in situ carcinoma (D05) and a note
without a date start nothing; with no discharge note nobody is in post-treatment. Fails if `cama.escenarios`
changes an evidence list or a code, or screening stops ending at the diagnosis."""
assert scenarios(base) == {
"H-001": {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1)},
"H-003": {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1),
("escenario_control", date(2025, 8, 4), "cie", 2)},
"H-101": {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)},
"H-102": {("escenario_tamizaje", date(2025, 2, 20), "mastografia", 1),
("escenario_control", date(2025, 9, 30), "cie", 2)},
"H-103": {("escenario_tamizaje", date(2025, 7, 1), "mastografia", 1),
("escenario_control", date(2025, 7, 20), "cie", 2)},
"H-104": {("escenario_tamizaje", date(2025, 11, 11), "mastografia", 1)},
}
def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base):
"""Pins down: a discharge note that carries a malignant tumour's ICD-10 starts post-treatment at its date, at level 3,
above the control the same note starts. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops
reading the note's type."""
discharge(base, "H-003")
assert scenarios(base)["H-003"] == {("escenario_tamizaje", date(2025, 6, 30), "mastografia", 1),
("escenario_control", date(2025, 8, 4), "cie", 2),
("escenario_postratamiento", date(2025, 8, 4), "egreso", 3)}
def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base):
"""Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her in
screening: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it."""
discharge(base, "H-101")
assert scenarios(base)["H-101"] == {("escenario_tamizaje", date(2025, 1, 15), "mastografia", 1)}
def test_a_diagnosis_after_screening_keeps_both_levels(base):
"""Pins down: a patient in screening whose malignant diagnosis comes later keeps both facts, so her timeline reads the
step from screening to control, the event that validates the screening models. Fails if a later diagnosis erases
the screening that preceded it."""
with base.motor.begin() as con:
con.execute(text(
"update observacion_clinica set valor_texto = 'C509' where resultado_id = 'nota_medica.diagnostico' and "
"pac_id = (select pac_id from paciente where pac_id_hospital = 'H-001')"))
con.execute(text(
"update procedimiento set fecha = '2025-06-01' where estudio_id = 'nota_medica' and pac_id = "
"(select pac_id from paciente where pac_id_hospital = 'H-001')"))
assert scenarios(base)["H-001"] == {("escenario_tamizaje", date(2025, 3, 10), "mastografia", 1),
("escenario_control", date(2025, 6, 1), "cie", 2)}