import mlflow.pyfunc import pytest def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str): import importlib from persistance import db as persistance_db from persistance import settings as persistance_settings monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}") engine = getattr(persistance_db, f"get_{domain}_engine") engine.cache_clear() importlib.import_module(f"core.{domain}.models") if domain != "governance": importlib.import_module(f"core.{domain}.indicadores.models") base = getattr(importlib.import_module(base_module), base_class) base.metadata.create_all(engine()) return engine @pytest.fixture def governance_db(tmp_path, monkeypatch): engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel") yield engine.cache_clear() @pytest.fixture def cacu_db(tmp_path, monkeypatch): engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel") yield engine.cache_clear() @pytest.fixture def tea_db(tmp_path, monkeypatch): engine = _wire(monkeypatch, tmp_path, "tea", "core.tea.base", "TeaModel") yield engine.cache_clear() @pytest.fixture def mlflow_tracking(tmp_path, monkeypatch): """A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`.""" import mlflow uri = f"sqlite:///{tmp_path / 'mlflow.db'}" monkeypatch.setenv("MLFLOW_TRACKING_URI", uri) mlflow.set_tracking_uri(uri) monkeypatch.chdir(tmp_path) yield class Echo(mlflow.pyfunc.PythonModel): """A model whose class lives in a module, as a PROD run requires: it returns its input.""" def predict(self, context, model_input, params=None): return model_input def trained_run(domain: str, scenario: str, armado_id: int | None, metrics: dict, *, routines=None, model: bool = True): """A finished PROD run as training leaves it: each routine's record (all of them unless `routines` names some) and, with `model`, a saved model.""" from core.governance.enums import Environment from models.io.tracking import ROUTINE_KINDS, TrainingRun run = TrainingRun(domain=domain, scenario=scenario, environment=Environment.PROD, cohorte_armado_id=armado_id) for kind in ROUTINE_KINDS if routines is None else routines: run.log_routine(kind, {"method": "prueba", "n": 8}) if model: run.log_model(Echo()) return run.finish(metrics=metrics) @pytest.fixture def production_ready(governance_db, cacu_db, mlflow_tracking): """Factory: registers a PROD version whose run recorded every routine and its model, with the three reports, so it passes every promotion check; returns (domain, scenario, version).""" from models.io.registry import registry def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None): run = trained_run(domain, scenario, armado(f"huella-{tag}"), metrics or {"auc": 0.8}) version = registry.register_run( run, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf", interpretability_report_uri="docs/interpretabilidad.html", ) return domain, scenario, version return make def armado(huella: str) -> int: """A CaCu cohort build with two attrition steps; returns its `armado_id`.""" from datetime import date, datetime, timezone from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion from persistance.db import get_cacu_session with get_cacu_session() as session: fila = CohorteArmado( url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}", datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc)) session.add(fila) session.flush() session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10), CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)]) session.commit() return fila.armado_id