test(ui): humo de todas las pantallas GET
Con el oficial demo, cada pantalla GET (las de detalle con un id de una base con el fixture, listas, casos plantados, matriz v1, una carga incremental y un caso, Screening incluido) responde 200 y pinta la estructura común. El acceso, sin ella.
This commit is contained in:
1 parent
a829525bba
commit
467dfde0d7
1 file changed
+186
@@ -0,0 +1,186 @@
|
||||
"""Humo del rediseño: con el usuario demo, cada pantalla GET de la app responde 200 y pinta la
|
||||
estructura común (barra lateral, sprite de íconos, hoja de estilos).
|
||||
|
||||
Una sola base para todas las rutas, porque importar el fixture es lo caro: esquema con la sal de
|
||||
la carga incremental, evaluación y reglas, identidades sintéticas, listas, casos plantados, matriz
|
||||
v1, una carga incremental confirmada y un caso. Screening entra aunque su plantilla no se
|
||||
rediseña: tiene que seguir pintando con la hoja nueva.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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 import audit
|
||||
from app.config import get_settings
|
||||
from app.db import crear_engine, crear_session_factory
|
||||
from app.importers import lists as importador_listas
|
||||
from app.importers.chm_schema import importar_esquema
|
||||
from app.importers.matrix_v1 import importar_matriz_v1
|
||||
from app.main import crear_app
|
||||
from app.models import (
|
||||
Alerta,
|
||||
AuditTrail,
|
||||
Base,
|
||||
Cliente,
|
||||
Coincidencia,
|
||||
Credito,
|
||||
EvaluacionRiesgo,
|
||||
ModeloRiesgo,
|
||||
)
|
||||
from app.models.usuario import Rol
|
||||
from app.services import alertas as servicio_alertas
|
||||
from app.services import casos as servicio_casos
|
||||
from app.services import operaciones as servicio_operaciones
|
||||
from app.services import riesgo as servicio_riesgo
|
||||
from app.services import screening as servicio_screening
|
||||
from seed import plantar_casos
|
||||
from seed.identidades_sinteticas import sembrar as sembrar_identidades
|
||||
from seed.usuarios_demo import sembrar
|
||||
from tests.fixtures import generar_operaciones_incremental as generador
|
||||
from tests.test_expediente import CONTRASENAS, FIXTURE, entrar
|
||||
from tests.test_operaciones import bytes_sin_fila_invalida
|
||||
|
||||
DIR_LISTAS = Path(__file__).parent / "fixtures" / "listas"
|
||||
FECHA_EVIDENCIA = "2026-10-08"
|
||||
|
||||
|
||||
def _con_actor(fabrica: sessionmaker[Session]) -> Session:
|
||||
sesion = fabrica()
|
||||
audit.fijar_actor(sesion, "pytest", 1)
|
||||
return sesion
|
||||
|
||||
|
||||
@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)
|
||||
monkeypatch.setattr(get_settings(), "data_dir", tmp_path)
|
||||
servicio_screening.vaciar_cache()
|
||||
servicio_operaciones._PREPARADAS.clear()
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
sesion.commit()
|
||||
importar_esquema(sesion, FIXTURE, "pytest", sal=generador.SAL)
|
||||
servicio_riesgo.evaluar_cartera(sesion, "inicial")
|
||||
servicio_alertas.ejecutar_reglas(sesion, usuario="pytest")
|
||||
sembrar_identidades(sesion)
|
||||
for nombre, lista in importador_listas.LISTAS.items():
|
||||
archivo = next(DIR_LISTAS.glob(lista.patron_archivo))
|
||||
importador_listas.importar_lista(sesion, nombre, archivo, usuario="pytest")
|
||||
sesion.commit()
|
||||
with _con_actor(fabrica) as sesion:
|
||||
plantar_casos.plantar(sesion)
|
||||
importar_matriz_v1(sesion)
|
||||
sesion.commit()
|
||||
with _con_actor(fabrica) as sesion:
|
||||
preparada = servicio_operaciones.preparar_carga(
|
||||
sesion, "carga.xlsx", bytes_sin_fila_invalida(), "pytest"
|
||||
)
|
||||
sesion.commit()
|
||||
with _con_actor(fabrica) as sesion:
|
||||
servicio_operaciones.confirmar_carga(sesion, preparada.token, "pytest")
|
||||
sesion.commit()
|
||||
with _con_actor(fabrica) as sesion:
|
||||
abierta = sesion.scalar(
|
||||
sa.select(Alerta.id).where(Alerta.estado != "cerrada").order_by(Alerta.id)
|
||||
)
|
||||
servicio_casos.abrir_caso(sesion, [abierta], responsable="analista", usuario="pytest")
|
||||
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 _rutas(fabrica: sessionmaker[Session]) -> list[str]:
|
||||
"""Todas las pantallas GET (las de detalle, con un id que existe en la base de prueba)."""
|
||||
with fabrica() as s:
|
||||
uno = lambda consulta: s.scalar(consulta.limit(1)) # noqa: E731
|
||||
cliente_id = uno(sa.select(EvaluacionRiesgo.cliente_id).order_by(EvaluacionRiesgo.id))
|
||||
moral_id = uno(sa.select(Cliente.id).where(Cliente.tipo_persona == "moral"))
|
||||
credito_id = uno(sa.select(Credito.id).order_by(Credito.id))
|
||||
alerta_id = uno(sa.select(Alerta.id).order_by(Alerta.id))
|
||||
# La primera alerta abierta ya está en el caso de la fixture: escalar otra.
|
||||
sin_caso_id = uno(
|
||||
sa.select(Alerta.id).where(Alerta.estado != "cerrada").order_by(Alerta.id.desc())
|
||||
)
|
||||
coincidencia_id = uno(sa.select(Coincidencia.id).order_by(Coincidencia.id))
|
||||
auditoria_id = uno(sa.select(AuditTrail.id).order_by(AuditTrail.id))
|
||||
modelos = s.scalars(sa.select(ModeloRiesgo.id).order_by(ModeloRiesgo.id)).all()
|
||||
caso_id = s.scalar(sa.text("SELECT max(id) FROM caso"))
|
||||
lote_id = s.scalar(sa.text("SELECT max(id) FROM lote_carga"))
|
||||
assert None not in (cliente_id, moral_id, credito_id, alerta_id, sin_caso_id, caso_id)
|
||||
assert None not in (coincidencia_id, auditoria_id, lote_id)
|
||||
assert len(modelos) >= 2
|
||||
a, b = modelos[0], modelos[-1]
|
||||
return [
|
||||
"/inicio",
|
||||
"/cartera",
|
||||
"/expediente",
|
||||
"/clientes/nuevo?tipo=fisica",
|
||||
"/clientes/nuevo?tipo=moral",
|
||||
f"/clientes/{cliente_id}",
|
||||
f"/clientes/{moral_id}",
|
||||
f"/clientes/{cliente_id}/identificacion",
|
||||
"/beneficiario-controlador",
|
||||
f"/clientes/{moral_id}/beneficiario",
|
||||
"/screening",
|
||||
"/screening/listas",
|
||||
f"/screening/{coincidencia_id}",
|
||||
"/riesgo",
|
||||
"/riesgo?nivel=alto",
|
||||
f"/riesgo/{cliente_id}",
|
||||
"/creditos",
|
||||
f"/creditos/{credito_id}",
|
||||
"/operaciones",
|
||||
"/operaciones/cargas",
|
||||
f"/operaciones/cargas/{lote_id}",
|
||||
"/operaciones/cierre",
|
||||
"/alertas",
|
||||
f"/alertas/{alerta_id}",
|
||||
"/casos",
|
||||
f"/casos/nuevo?alerta_id={sin_caso_id}",
|
||||
f"/casos/{caso_id}",
|
||||
"/evidencia",
|
||||
f"/evidencia/{cliente_id}?fecha={FECHA_EVIDENCIA}",
|
||||
"/auditoria",
|
||||
f"/auditoria/{auditoria_id}",
|
||||
"/laboratorio",
|
||||
f"/laboratorio/versiones/{a}",
|
||||
"/laboratorio/comparar",
|
||||
f"/laboratorio/comparar?a={a}&b={b}",
|
||||
]
|
||||
|
||||
|
||||
def test_cada_pantalla_responde_y_pinta_la_estructura(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
assert cliente.get("/login").status_code == 200
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
estructura = ('<nav class="nav"', 'id="i-home"', "/static/app.css")
|
||||
fallas = []
|
||||
for ruta in _rutas(fabrica):
|
||||
respuesta = cliente.get(ruta)
|
||||
if respuesta.status_code != 200:
|
||||
fallas.append(f"{ruta}: {respuesta.status_code}")
|
||||
elif not all(pieza in respuesta.text for pieza in estructura):
|
||||
fallas.append(f"{ruta}: falta la estructura común")
|
||||
assert fallas == []
|
||||
|
||||
|
||||
def test_el_acceso_no_pinta_la_estructura_con_sesion(client: TestClient) -> None:
|
||||
html = client.get("/login").text
|
||||
assert '<nav class="nav"' not in html and 'class="lateral"' not in html
|
||||
assert "/static/app.css" in html
|
||||
Reference in new issue
Block a user