Files
collina-pld/tests/test_laboratorio.py
T
Jorem Juárez 03c4687007 feat(textos): pendientes de CHM fuera de la interfaz de la financiera
La app es la que ven las financieras: sin etiquetas «pendiente de
validación» ni pantalla /pendientes-chm (ni su paso en la barra ni su
tarjeta en inicio). La macro pendiente(clave) marca la pantalla sin
pintar nada y la agenda para CHM pasa a docs/agenda_chm.md, generada
con python -m app.textos --agenda; un test exige que esté al día.
Se quitan también las etiquetas de preponderancia en riesgo y
laboratorio (validada por CHM en v2.1).
2026-10-08 12:36:02 -06:00

349 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Pantallas de riesgo y laboratorio con el cliente de prueba (Fase 2, PR 3)."""
import time
from collections.abc import Iterator
from pathlib import Path
import pytest
import sqlalchemy as sa
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session, sessionmaker
from app.db import crear_engine, crear_session_factory
from app.importers.chm_schema import importar_esquema
from app.main import crear_app
from app.models import (
AgregadoCliente,
AuditTrail,
Base,
Cliente,
EvaluacionRiesgo,
Indicador,
ModeloRiesgo,
NivelIndicador,
Umbral,
)
from app.models.usuario import Rol
from app.services.riesgo import evaluar_cartera
from seed.usuarios_demo import sembrar
from tests.fixtures.oraculo import FIXTURE
CONTRASENAS = {
Rol.ANALISTA: "clave-analista-1",
Rol.OFICIAL: "clave-oficial-2",
Rol.AUDITOR: "clave-auditor-3",
}
COMPENSADO = {"ponderaciones": {"T1": "0.25", "T3": "0.05"}}
TABLAS_DEL_MODELO = (
ModeloRiesgo,
Indicador,
NivelIndicador,
Umbral,
EvaluacionRiesgo,
AgregadoCliente,
)
@pytest.fixture
def fabrica(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> sessionmaker[Session]:
engine = crear_engine("sqlite://")
Base.metadata.create_all(engine)
fabrica = crear_session_factory(engine)
monkeypatch.setattr("app.db.SessionLocal", fabrica)
with fabrica() as sesion:
importar_esquema(sesion, FIXTURE, "pytest", sal="sal", ruta_reglas=tmp_path / "no.json")
sembrar(sesion, CONTRASENAS)
evaluar_cartera(sesion, "inicial")
sesion.commit()
return fabrica
@pytest.fixture
def cliente(fabrica: sessionmaker[Session]) -> Iterator[TestClient]:
with TestClient(crear_app(), follow_redirects=False) as c:
yield c
def entrar(c: TestClient, rol: Rol) -> None:
respuesta = c.post("/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]})
assert respuesta.status_code == 303
def conteos(fabrica: sessionmaker[Session]) -> dict[str, int]:
with fabrica() as sesion:
return {
t.__tablename__: sesion.scalar(sa.select(sa.func.count()).select_from(t))
for t in TABLAS_DEL_MODELO
}
def v2_id(fabrica: sessionmaker[Session]) -> int:
with fabrica() as sesion:
return sesion.scalar(sa.select(ModeloRiesgo.id).where(ModeloRiesgo.version == "v2"))
# --- Pantallas de riesgo -------------------------------------------------------------------
def test_riesgo_lista_la_cartera_y_se_habilita_en_la_navegacion(cliente: TestClient) -> None:
entrar(cliente, Rol.AUDITOR)
respuesta = cliente.get("/riesgo")
assert respuesta.status_code == 200
assert "30 clientes evaluados" in respuesta.text
lateral = respuesta.text[respuesta.text.index('<nav class="nav"') :]
assert 'href="/riesgo"' in lateral and 'href="/laboratorio"' in lateral
assert cliente.get("/riesgo?nivel=alto").status_code == 200
def test_riesgo_de_un_cliente_muestra_detalle_e_historial(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
with fabrica() as sesion:
forzada = sesion.scalar(
sa.select(EvaluacionRiesgo).where(EvaluacionRiesgo.forzado_por.is_not(None))
)
entrar(cliente, Rol.AUDITOR)
html = cliente.get(f"/riesgo/{forzada.cliente_id}").text
for texto in ("Evaluación vigente", "Detalle por indicador", "Historial", "Preponderancia"):
assert texto in html
assert "pendiente de validación" not in html # la financiera no ve los pendientes de CHM
assert "crédito más reciente" in html # cómo se calculó T2, en el detalle del indicador
assert "a la fecha de corte" in html # C1
assert "Reevaluar" not in html # el auditor no reevalúa
def test_un_cliente_de_otro_tenant_o_inexistente_da_404(cliente: TestClient) -> None:
entrar(cliente, Rol.AUDITOR)
assert cliente.get("/riesgo/999999").status_code == 404
def test_reevaluar_exige_oficial_o_analista(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
with fabrica() as sesion:
cliente_id = sesion.scalar(sa.select(Cliente.id).limit(1))
entrar(cliente, Rol.AUDITOR)
assert cliente.post(f"/riesgo/{cliente_id}/reevaluar").status_code == 403
cliente.post("/logout")
entrar(cliente, Rol.ANALISTA)
respuesta = cliente.post(
f"/riesgo/{cliente_id}/reevaluar", data={"evento": "Cambio de domicilio"}
)
assert respuesta.status_code == 303
with fabrica() as sesion:
ultima = sesion.scalar(
sa.select(EvaluacionRiesgo)
.where(EvaluacionRiesgo.cliente_id == cliente_id)
.order_by(EvaluacionRiesgo.id.desc())
)
assert (ultima.motivo, ultima.detalle["evento"], ultima.created_by) == (
"extraordinaria",
"Cambio de domicilio",
"analista",
)
# --- Laboratorio ---------------------------------------------------------------------------
def test_el_laboratorio_muestra_el_modelo_vigente(cliente: TestClient) -> None:
entrar(cliente, Rol.ANALISTA)
html = cliente.get("/laboratorio").text
assert "Laboratorio de calibración" in html
assert "pendiente de validación" not in html # la financiera no ve los pendientes de CHM
assert html.count("data-ponderacion=") == 10
# Impacto libre 0–100 por nivel, no un selector de tres valores.
assert html.count('type="number" min="0" max="100" step="1"') == 30
assert "<select data-impacto" not in html
assert "chart.umd.min.js" in html and "/static/laboratorio.js" in html
assert "Solo el oficial de cumplimiento guarda versiones" in html
def test_chart_js_solo_se_carga_en_el_laboratorio(cliente: TestClient) -> None:
entrar(cliente, Rol.ANALISTA)
assert "chart.umd" not in cliente.get("/riesgo").text
assert "chart.umd" not in cliente.get("/inicio").text
def test_simular_no_escribe_en_la_base(cliente: TestClient, fabrica: sessionmaker[Session]) -> None:
entrar(cliente, Rol.ANALISTA)
antes = conteos(fabrica)
respuesta = cliente.post("/laboratorio/simular", json={"cambios": COMPENSADO})
assert respuesta.status_code == 200
datos = respuesta.json()
assert conteos(fabrica) == antes
assert sum(datos["distribucion_vigente"].values()) == datos["clientes"] == 30
assert sum(datos["distribucion_simulada"].values()) == 30
assert datos["alertas_d01"]["vigente"] == datos["distribucion_vigente"]["alto"]
assert datos["alertas_d01"]["simulada"] == datos["distribucion_simulada"]["alto"]
assert datos["cambian"] > 0
assert datos["errores"] == []
with fabrica() as sesion:
assert not sesion.scalar(
sa.select(sa.func.count())
.select_from(AuditTrail)
.where(AuditTrail.entidad != "http")
.where(AuditTrail.accion == "crear_version")
)
def test_simular_sin_cambios_no_cambia_a_nadie(cliente: TestClient) -> None:
entrar(cliente, Rol.ANALISTA)
datos = cliente.post("/laboratorio/simular", json={}).json()
assert datos["cambian"] == 0
assert datos["distribucion_simulada"] == datos["distribucion_vigente"]
def test_simular_reporta_errores_de_validacion_sin_fallar(cliente: TestClient) -> None:
entrar(cliente, Rol.ANALISTA)
hueco = {
"umbrales": [
{"nivel": "bajo", "minimo": 0, "maximo": 15},
{"nivel": "medio", "minimo": 16, "maximo": 28},
{"nivel": "alto", "minimo": 28},
]
}
datos = cliente.post("/laboratorio/simular", json={"cambios": hueco}).json()
assert any("hueco" in e for e in datos["errores"])
def test_simular_responde_rapido(cliente: TestClient) -> None:
entrar(cliente, Rol.ANALISTA)
inicio = time.perf_counter()
cliente.post("/laboratorio/simular", json={"cambios": COMPENSADO})
assert time.perf_counter() - inicio < 2
def test_simular_con_un_cuerpo_invalido_da_400(cliente: TestClient) -> None:
entrar(cliente, Rol.ANALISTA)
respuesta = cliente.post("/laboratorio/simular", json={"cambios": {"inventado": 1}})
assert respuesta.status_code == 400
assert respuesta.json()["detail"]["errores"]
def test_simular_y_guardar_con_impactos_libres(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.OFICIAL)
libres = {"impactos": {"C2": {"1": 20, "2": 30, "3": 40}}}
simulacion = cliente.post("/laboratorio/simular", json={"cambios": libres}).json()
assert simulacion["errores"] == []
guardada = cliente.post(
"/laboratorio/guardar",
json={"base_id": v2_id(fabrica), "cambios": libres, "justificacion": "Impactos v1"},
)
assert guardada.status_code == 201
fuera = cliente.post(
"/laboratorio/guardar",
json={
"base_id": v2_id(fabrica),
"cambios": {"impactos": {"C2": {"3": 150}}},
"justificacion": "x",
},
)
assert fuera.status_code == 400
assert any("impacto 150" in e for e in fuera.json()["errores"])
def test_guardar_sin_rol_oficial_da_403(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.ANALISTA)
cuerpo = {"base_id": v2_id(fabrica), "cambios": COMPENSADO, "justificacion": "x"}
assert cliente.post("/laboratorio/guardar", json=cuerpo).status_code == 403
def test_guardar_ponderaciones_invalidas_da_400_con_mensajes(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.OFICIAL)
antes = conteos(fabrica)
cuerpo = {
"base_id": v2_id(fabrica),
"cambios": {"ponderaciones": {"T1": "0.5"}},
"justificacion": "prueba",
}
respuesta = cliente.post("/laboratorio/guardar", json=cuerpo)
assert respuesta.status_code == 400
assert any("deben sumar 1.0" in e for e in respuesta.json()["errores"])
assert conteos(fabrica) == antes
def test_guardar_sin_justificacion_da_400(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.OFICIAL)
cuerpo = {"base_id": v2_id(fabrica), "cambios": COMPENSADO, "justificacion": " "}
respuesta = cliente.post("/laboratorio/guardar", json=cuerpo)
assert respuesta.status_code == 400
assert "justificación" in respuesta.json()["errores"][0]
def test_el_oficial_guarda_una_version_y_ambas_quedan_consultables(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.OFICIAL)
base = v2_id(fabrica)
respuesta = cliente.post(
"/laboratorio/guardar",
json={"base_id": base, "cambios": COMPENSADO, "justificacion": "Más peso al instrumento"},
)
assert respuesta.status_code == 201
datos = respuesta.json()
assert datos["version"] == "v3"
nueva = cliente.get(datos["url"])
assert nueva.status_code == 200 and "solo lectura" in nueva.text
assert cliente.get(f"/laboratorio/versiones/{base}").status_code == 200
assert "v3 · Calibración v3 sobre v2" in cliente.get("/laboratorio").text # queda vigente
with fabrica() as sesion:
fila = sesion.scalar(sa.select(AuditTrail).where(AuditTrail.accion == "crear_version"))
assert (fila.usuario, fila.motivo) == ("oficial", "Más peso al instrumento")
def test_comparar_dos_versiones_trae_las_tres_secciones(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.OFICIAL)
base = v2_id(fabrica)
nueva = cliente.post(
"/laboratorio/guardar",
json={"base_id": base, "cambios": COMPENSADO, "justificacion": "Calibración"},
).json()["id"]
respuesta = cliente.get(f"/laboratorio/comparar?a={base}&b={nueva}")
assert respuesta.status_code == 200
for seccion in (
"Distribución por nivel",
"Matriz de transición",
"Clientes que cambian de nivel",
):
assert seccion in respuesta.text
assert 'href="/riesgo/' in respuesta.text
def test_comparar_sin_versiones_elegidas_muestra_el_selector(cliente: TestClient) -> None:
entrar(cliente, Rol.AUDITOR)
respuesta = cliente.get("/laboratorio/comparar")
assert respuesta.status_code == 200
assert "Matriz de transición" not in respuesta.text
def test_comparar_una_version_inexistente_da_404(
cliente: TestClient, fabrica: sessionmaker[Session]
) -> None:
entrar(cliente, Rol.AUDITOR)
assert cliente.get(f"/laboratorio/comparar?a={v2_id(fabrica)}&b=9999").status_code == 404