195 lines
10 KiB
Python
195 lines
10 KiB
Python
"""What this module covers: `GET /cama/modelo/curvas` and `GET /cama/modelo/desarrollo` (`webapi.model_analysis`): they serve the production version's
|
||
population record with the version it comes from, and answers 404 while there is no version in production or the
|
||
version has no such record.
|
||
|
||
Fixtures: `client`, the app with the registry's `resolve` and `artifact` replaced by what the test says a production
|
||
version holds, so no MLflow is needed; the CaMa survival record is a small stand-in for what a run publishes.
|
||
"""
|
||
|
||
import json
|
||
from types import SimpleNamespace
|
||
|
||
import pytest
|
||
|
||
RECORD = {"horizons_months": [6, 12, 18], "points": {"COMB": {"S": [0.9, 0.8, 0.7], "low": [0.8, 0.7, 0.6], "high": [0.95, 0.9, 0.8]}}}
|
||
|
||
|
||
@pytest.fixture
|
||
def client(monkeypatch):
|
||
from flask import Flask
|
||
|
||
from models.io import registry as registry_module
|
||
from webapi.model_analysis import model_analysis_blueprint
|
||
|
||
app = Flask(__name__)
|
||
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
|
||
monkeypatch.setenv("DEV_REVISION", "pruebas")
|
||
holder = SimpleNamespace(files={"analisis/curvas.json": json.dumps(RECORD).encode()}, production="3")
|
||
|
||
def resolve(domain, scenario, version=None):
|
||
if holder.production is None:
|
||
raise LookupError("no hay una versión en producción")
|
||
return SimpleNamespace(version=holder.production, run_id="run-1")
|
||
|
||
def artifact(domain, scenario, version, path):
|
||
if path not in holder.files:
|
||
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
|
||
return path.rsplit("/", 1)[-1], holder.files[path]
|
||
|
||
monkeypatch.setattr(registry_module.registry, "resolve", resolve)
|
||
monkeypatch.setattr(registry_module.registry, "artifact", artifact)
|
||
with app.test_client() as test_client:
|
||
test_client.holder = holder
|
||
yield test_client
|
||
|
||
|
||
def test_it_serves_the_production_versions_record_and_names_the_version(client):
|
||
"""Pins down: the answer carries the record unchanged, the model and version it comes from and the simulated-data
|
||
flag. Fails if the record is altered on the way or the answer stops saying which version it is."""
|
||
body = client.get("/cama/modelo/curvas").get_json()
|
||
|
||
assert body["curvas"] == RECORD and body["simulado"] is True
|
||
assert body["modelo"] == {"nombre": "cama-survival", "version": "3", "mlflow_run_id": "run-1"}
|
||
|
||
|
||
def test_without_a_version_in_production_or_a_record_it_is_a_404(client):
|
||
"""Pins down: no production version, and a version whose run published no `analisis/curvas.json`, are both a 404
|
||
with the reason, never an empty record. Fails if either becomes a 200 or a 500."""
|
||
client.holder.files.clear()
|
||
missing_record = client.get("/cama/modelo/curvas")
|
||
client.holder.production = None
|
||
no_version = client.get("/cama/modelo/curvas")
|
||
|
||
assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"]
|
||
assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"]
|
||
|
||
|
||
def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none(client):
|
||
"""Pins down: `GET /cama/modelo/desarrollo` returns `analisis/desarrollo.json` with the version it comes from, and a
|
||
version trained before that record existed is a 404, not an empty page. Fails if the route reads another file or
|
||
answers 200 without a record."""
|
||
record = {"tablas": {"or_lr_balanceada": [{"variable": "Grado"}]}, "figuras": {}}
|
||
client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode()
|
||
found = client.get("/cama/modelo/desarrollo")
|
||
del client.holder.files["analisis/desarrollo.json"]
|
||
missing = client.get("/cama/modelo/desarrollo")
|
||
|
||
assert found.status_code == 200 and found.get_json()["desarrollo"] == record
|
||
assert found.get_json()["modelo"]["version"] == "3"
|
||
assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"]
|
||
|
||
|
||
@pytest.fixture
|
||
def live_client(client, monkeypatch):
|
||
"""`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, so the routes run
|
||
without MLflow or a cohort build; `live.curves` answers from the stand-in or raises what the test sets."""
|
||
from models.cama.survival import live
|
||
from webapi import model_analysis
|
||
|
||
holder = SimpleNamespace(calls=0, error=None)
|
||
|
||
def context(domain, scenario):
|
||
return "spec", "model", "labelled", "3"
|
||
|
||
def curves(spec, model, labelled, name):
|
||
holder.calls += 1
|
||
if holder.error:
|
||
raise live.QueryError(holder.error)
|
||
return {"n": 100, "escenario": name or "Toda la cohorte"}
|
||
|
||
def patient_scenarios(labelled, pac_id):
|
||
if pac_id == 404:
|
||
raise live.QueryError("La paciente no está en la cohorte del modelo.")
|
||
return ["< 45 años"] if pac_id == 7 else ["Toda la cohorte"]
|
||
|
||
monkeypatch.setattr(model_analysis, "_live_context", context)
|
||
monkeypatch.setattr(live, "curves", curves)
|
||
monkeypatch.setattr(live, "patient_scenarios", patient_scenarios)
|
||
model_analysis._ANSWERS.clear()
|
||
client.holder = holder
|
||
return client
|
||
|
||
|
||
def test_a_scenarios_figure_is_asked_by_name_and_the_answer_is_kept(live_client):
|
||
"""Pins down: `POST /cama/modelo/curvas/consulta` returns the record of the named scenario with the version that scored it,
|
||
and the same scenario a second time is answered without computing again. Fails if the answer lacks the version, or every
|
||
request recomputes (the figure takes seconds each time a patient's record opens)."""
|
||
first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"})
|
||
second = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"})
|
||
|
||
assert first.status_code == 200 and first.get_json()["modelo"]["version"] == "3"
|
||
assert first.get_json()["curvas"]["escenario"] == "< 45 años" and second.get_json() == first.get_json()
|
||
assert live_client.holder.calls == 1
|
||
|
||
|
||
def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client):
|
||
"""Pins down: an unknown scenario or one too small is a 422 with the message, not a 500 or an empty record. Fails if the
|
||
reader sees a server error instead of why the scenario says nothing."""
|
||
live_client.holder.error = "El escenario tiene 3 pacientes"
|
||
answer = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Estadio IV"})
|
||
|
||
assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"]
|
||
|
||
|
||
def test_the_scenarios_of_a_patient_are_listed_and_a_stranger_is_refused(live_client):
|
||
"""Pins down: `GET /cama/modelo/escenarios?paciente=7` lists her scenarios, one in none gets the whole cohort, and a patient
|
||
outside the cohort or no patient is a 422. Fails if the patient parameter is ignored, which would draw the same figure for
|
||
every patient."""
|
||
assert live_client.get("/cama/modelo/escenarios?paciente=7").get_json()["escenarios"] == ["< 45 años"]
|
||
assert live_client.get("/cama/modelo/escenarios?paciente=8").get_json()["escenarios"] == ["Toda la cohorte"]
|
||
assert live_client.get("/cama/modelo/escenarios?paciente=404").status_code == 422
|
||
assert live_client.get("/cama/modelo/escenarios").status_code == 422
|
||
|
||
|
||
@pytest.fixture
|
||
def recurrence_client(monkeypatch):
|
||
"""The recurrence route on a bare app, with the registry's production version, its recurrence record and the labelled members
|
||
replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor."""
|
||
import pandas as pd
|
||
from flask import Flask
|
||
|
||
from models.io import registry as registry_module
|
||
from webapi import model_analysis
|
||
|
||
record = {"horizons_months": [12, 36, 60], "escenarios": [
|
||
{"cohorte": "metabric", "escenario": "< 45 años", "condiciones": {"Edad": ["<45"]}, "n": 100},
|
||
{"cohorte": "metabric", "escenario": "RE− · grado 3", "condiciones": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, "n": 300},
|
||
{"cohorte": "metabric", "escenario": "Ganglios 4+", "condiciones": {"Ganglios_positivos": ["4+"]}, "n": 80},
|
||
{"cohorte": "scanb", "escenario": "Grado 3", "condiciones": {"Grado_histologico": ["3"]}, "n": 900}]}
|
||
labelled = pd.DataFrame({"pac_id": [7], "age_years": [40.0], "size_mm": [None], "grade": ["G3"], "er": ["NEGATIVO"], "pr": ["NEGATIVO"], "her2": ["H2"]})
|
||
holder = SimpleNamespace(production="2")
|
||
|
||
def resolve(domain, scenario, version=None):
|
||
if holder.production is None:
|
||
raise LookupError("no hay una versión en producción")
|
||
return SimpleNamespace(version=holder.production, run_id="run-2")
|
||
|
||
monkeypatch.setattr(registry_module.registry, "resolve", resolve)
|
||
monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: ("recurrencia.json", json.dumps(record).encode()))
|
||
monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3"))
|
||
app = Flask(__name__)
|
||
app.register_blueprint(model_analysis.recurrence_blueprint(), url_prefix="/cama")
|
||
with app.test_client() as client:
|
||
client.holder = holder
|
||
yield client
|
||
|
||
|
||
def test_a_patient_gets_the_recurrence_scenarios_her_covariates_meet(recurrence_client):
|
||
"""Pins down: `GET /cama/modelo/recurrencia?paciente=7` returns the scenarios whose every condition her age, grade and
|
||
receptors meet (one that needs the nodes, which the hospital does not report, is left out), the larger first within a
|
||
cohort, with the version that published them. Fails if a scenario she does not meet is returned, a missing covariate counts
|
||
as met, or the version is not named."""
|
||
body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json()
|
||
|
||
assert [(s["cohorte"], s["escenario"]) for s in body["escenarios"]] == [("metabric", "RE− · grado 3"), ("metabric", "< 45 años"), ("scanb", "Grado 3")]
|
||
assert body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60]
|
||
|
||
|
||
def test_without_a_recurrence_version_or_for_a_stranger_it_says_so(recurrence_client):
|
||
"""Pins down: no recurrence version in production is a 404, a patient outside the cohort or no patient is a 422 with a reason.
|
||
Fails if either becomes a 200 with nothing or a 500."""
|
||
assert recurrence_client.get("/cama/modelo/recurrencia?paciente=99").status_code == 422
|
||
assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 422
|
||
recurrence_client.holder.production = None
|
||
assert recurrence_client.get("/cama/modelo/recurrencia?paciente=7").status_code == 404
|