202 lines
7.7 KiB
Python
202 lines
7.7 KiB
Python
"""Pantalla `/cartera`: filtros, conteos, paginación, roles y tiempo de respuesta."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
from collections.abc import Iterator
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
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.esquema_origen import importar_esquema
|
|
from app.main import crear_app
|
|
from app.models import Base, Cliente, EvaluacionRiesgo, ModeloRiesgo, Tenant
|
|
from app.models.usuario import Rol
|
|
from app.services.alertas import ejecutar_reglas
|
|
from seed.usuarios_demo import sembrar
|
|
|
|
FIXTURE = Path(__file__).parent / "fixtures" / "esquema_mini.xlsx"
|
|
CONTRASENAS = {
|
|
Rol.ANALISTA: "clave-analista-1",
|
|
Rol.OFICIAL: "clave-oficial-2",
|
|
Rol.AUDITOR: "clave-auditor-3",
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def fabrica(monkeypatch: pytest.MonkeyPatch) -> sessionmaker[Session]:
|
|
"""Base en memoria con usuarios demo, el fixture importado y las reglas ejecutadas."""
|
|
engine = crear_engine("sqlite://")
|
|
Base.metadata.create_all(engine)
|
|
fabrica = crear_session_factory(engine)
|
|
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
|
# Estas pruebas son de pantallas: la reevaluación por alerta crítica (Pieza C) se desactiva
|
|
# para que el nivel vigente lo controle cada test.
|
|
monkeypatch.setattr(
|
|
"app.services.riesgo.solicitar_reevaluacion", lambda session, cliente_id, evento: None
|
|
)
|
|
with fabrica() as sesion:
|
|
sembrar(sesion, CONTRASENAS)
|
|
sesion.commit()
|
|
importar_esquema(sesion, FIXTURE, "pytest", sal="sal-cartera")
|
|
ejecutar_reglas(sesion, 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 enlaces(html: str) -> int:
|
|
"""Enlaces a fichas de cliente (no cuenta el botón «Nuevo cliente»)."""
|
|
return len(re.findall(r'href="/clientes/\d', html))
|
|
|
|
|
|
def entrar(cliente: TestClient, rol: Rol) -> None:
|
|
assert (
|
|
cliente.post(
|
|
"/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]}
|
|
).status_code
|
|
== 303
|
|
)
|
|
|
|
|
|
def evaluar(fabrica: sessionmaker[Session], cliente_id: int, nivel: str) -> None:
|
|
"""Simula una evaluación de la Pieza C: una fila en `evaluacion_riesgo` (A escribe, B lee)."""
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
modelo = sesion.scalar(sa.select(ModeloRiesgo))
|
|
sesion.add(
|
|
EvaluacionRiesgo(
|
|
tenant_id=tenant.id,
|
|
created_by="pytest",
|
|
cliente_id=cliente_id,
|
|
modelo_id=modelo.id,
|
|
score_inherente=Decimal("30"),
|
|
score_residual=Decimal("30"),
|
|
nivel=nivel,
|
|
detalle=[],
|
|
motivo="inicial",
|
|
)
|
|
)
|
|
sesion.commit()
|
|
|
|
|
|
def test_sin_sesion_redirige_al_login(cliente: TestClient) -> None:
|
|
respuesta = cliente.get("/cartera")
|
|
assert respuesta.status_code == 303 and respuesta.headers["location"] == "/login"
|
|
|
|
|
|
@pytest.mark.parametrize("rol", list(Rol))
|
|
def test_los_tres_roles_ven_la_cartera(cliente: TestClient, rol: Rol) -> None:
|
|
entrar(cliente, rol)
|
|
respuesta = cliente.get("/cartera")
|
|
assert respuesta.status_code == 200
|
|
assert "30 clientes" in respuesta.text
|
|
assert enlaces(respuesta.text) == 30
|
|
assert "Sin evaluar" in respuesta.text
|
|
|
|
|
|
def test_filtro_por_nivel_usa_la_ultima_evaluacion(cliente: TestClient, fabrica) -> None:
|
|
with fabrica() as sesion:
|
|
ids = sesion.scalars(sa.select(Cliente.id).order_by(Cliente.id)).all()
|
|
evaluar(fabrica, ids[0], "bajo")
|
|
evaluar(fabrica, ids[0], "alto") # la última manda
|
|
evaluar(fabrica, ids[1], "medio")
|
|
entrar(cliente, Rol.ANALISTA)
|
|
|
|
alto = cliente.get("/cartera?nivel=alto")
|
|
assert alto.status_code == 200
|
|
assert enlaces(alto.text) == 1 and f'href="/clientes/{ids[0]}"' in alto.text
|
|
assert enlaces(cliente.get("/cartera?nivel=bajo").text) == 0
|
|
assert enlaces(cliente.get("/cartera?nivel=sin_evaluar").text) == 28
|
|
assert "1 coincidencias" in alto.text
|
|
|
|
|
|
def test_el_expediente_filtra_por_nivel_como_la_cartera(cliente: TestClient, fabrica) -> None:
|
|
with fabrica() as sesion:
|
|
clientes = sesion.scalars(sa.select(Cliente).order_by(Cliente.id)).all()
|
|
evaluar(fabrica, clientes[0].id, "bajo")
|
|
evaluar(fabrica, clientes[0].id, "alto") # la última manda
|
|
evaluar(fabrica, clientes[1].id, "medio")
|
|
entrar(cliente, Rol.AUDITOR)
|
|
|
|
alto = cliente.get("/expediente?nivel=alto")
|
|
assert alto.status_code == 200
|
|
assert clientes[0].id_externo in alto.text
|
|
assert all(c.id_externo not in alto.text for c in clientes[1:])
|
|
medio = cliente.get(f"/expediente?nivel=medio&q={clientes[1].id_externo[:8]}")
|
|
assert clientes[1].id_externo in medio.text and clientes[0].id_externo not in medio.text
|
|
sin_evaluar = cliente.get("/expediente?nivel=sin_evaluar").text
|
|
assert clientes[0].id_externo not in sin_evaluar and clientes[2].id_externo in sin_evaluar
|
|
assert cliente.get("/expediente?nivel=").status_code == 200
|
|
assert cliente.get("/expediente?nivel=altisimo").status_code == 422
|
|
|
|
|
|
def test_busqueda_por_id_externo_y_filtro_vacio(cliente: TestClient, fabrica) -> None:
|
|
with fabrica() as sesion:
|
|
primero = sesion.scalar(sa.select(Cliente).order_by(Cliente.id))
|
|
entrar(cliente, Rol.OFICIAL)
|
|
respuesta = cliente.get(f"/cartera?q={primero.id_externo[:8]}&nivel=&estado_relacion=")
|
|
assert respuesta.status_code == 200
|
|
assert primero.id_externo in respuesta.text
|
|
assert enlaces(respuesta.text) >= 1
|
|
assert enlaces(cliente.get("/cartera?q=no-existe-zzz").text) == 0
|
|
assert "Ningún cliente cumple los filtros" in cliente.get("/cartera?q=no-existe-zzz").text
|
|
|
|
|
|
def test_conteo_de_alertas_abiertas(cliente: TestClient, fabrica) -> None:
|
|
entrar(cliente, Rol.AUDITOR)
|
|
respuesta = cliente.get("/cartera")
|
|
assert "124 alertas abiertas" in respuesta.text
|
|
|
|
|
|
def test_pagina_fuera_de_rango_y_parametros_invalidos(cliente: TestClient) -> None:
|
|
entrar(cliente, Rol.ANALISTA)
|
|
assert cliente.get("/cartera?pagina=99").status_code == 200
|
|
assert cliente.get("/cartera?pagina=0").status_code == 422
|
|
assert cliente.get("/cartera?nivel=altisimo").status_code == 422
|
|
|
|
|
|
def test_responde_en_menos_de_un_segundo_con_1023_clientes(cliente: TestClient, fabrica) -> None:
|
|
with fabrica() as sesion:
|
|
tenant = sesion.scalar(sa.select(Tenant))
|
|
existentes = sesion.scalar(sa.select(sa.func.count(Cliente.id)))
|
|
sesion.execute(
|
|
sa.insert(Cliente),
|
|
[
|
|
{
|
|
"tenant_id": tenant.id,
|
|
"created_by": "pytest",
|
|
"id_externo": f"sintetico{i:06d}",
|
|
"tipo_persona": "fisica",
|
|
"fecha_nacimiento": date(1980, 1, 1),
|
|
"estado": "Jalisco",
|
|
"pais": "México",
|
|
"estado_relacion": "activa",
|
|
}
|
|
for i in range(1023 - existentes)
|
|
],
|
|
)
|
|
sesion.commit()
|
|
entrar(cliente, Rol.ANALISTA)
|
|
inicio = time.perf_counter()
|
|
respuesta = cliente.get("/cartera")
|
|
duracion = time.perf_counter() - inicio
|
|
assert respuesta.status_code == 200
|
|
assert "1023 clientes" in respuesta.text
|
|
assert enlaces(respuesta.text) == 50 # paginada
|
|
assert duracion < 1.0, f"{duracion:.2f}s"
|
|
assert "Página 1 de 21" in respuesta.text
|
|
assert enlaces(cliente.get("/cartera?estado_relacion=activa").text) == 50
|