81 lines
2.7 KiB
Python
81 lines
2.7 KiB
Python
import json
|
|
|
|
import pytest
|
|
|
|
from models.base import ScreeningModel
|
|
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
|
from models.registry import registry
|
|
|
|
|
|
class StubModel(ScreeningModel):
|
|
domain = "cacu"
|
|
|
|
def train(self, data=None):
|
|
raise NotImplementedError
|
|
|
|
def predict(self, data):
|
|
return {"label": "positivo", "confianza": 0.73}
|
|
|
|
|
|
def never_applicable(row: dict) -> bool:
|
|
return False
|
|
|
|
|
|
def _promote_a_version(production_ready):
|
|
domain, scenario, version = production_ready("v1-prod")
|
|
return registry.promote(domain, scenario, version)
|
|
|
|
|
|
def test_predict_and_record_persists_prediction_tagged_with_active_version(production_ready):
|
|
version = _promote_a_version(production_ready)
|
|
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
|
|
|
|
prediction = service.predict_and_record(
|
|
{"edad": 40},
|
|
pac_id_hospital="H-1",
|
|
interpretability=Interpretability(odds_ratio=1.8),
|
|
)
|
|
|
|
assert prediction.mlflow_run_id == version.run_id
|
|
assert prediction.modelo_version == str(version.version)
|
|
assert prediction.applicability_passed is True
|
|
assert json.loads(prediction.output)["label"] == "positivo"
|
|
assert json.loads(prediction.interpretability)["odds_ratio"] == 1.8
|
|
|
|
|
|
def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
|
|
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
|
|
with pytest.raises(RuntimeError, match="no hay una versión en producción"):
|
|
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
|
|
|
|
|
def test_applicability_gate_flags_but_does_not_block_by_default(production_ready):
|
|
_promote_a_version(production_ready)
|
|
service = PredictionService(
|
|
StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable
|
|
)
|
|
|
|
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
|
assert prediction.applicability_passed is False
|
|
|
|
|
|
def test_applicability_gate_can_reject_outright(production_ready):
|
|
_promote_a_version(production_ready)
|
|
service = PredictionService(
|
|
StubModel(),
|
|
domain="cacu",
|
|
scenario="tamizaje",
|
|
aplicable=never_applicable,
|
|
reject_inapplicable=True,
|
|
)
|
|
|
|
with pytest.raises(ApplicabilityRejected):
|
|
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
|
|
|
|
|
|
def test_applicability_gate_needs_a_dict(production_ready):
|
|
_promote_a_version(production_ready)
|
|
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje", aplicable=never_applicable)
|
|
with pytest.raises(TypeError):
|
|
service.predict_and_record([40], pac_id_hospital="H-1")
|