test(textos): catálogo, macro, inicio, agenda y etiquetas en cada pantalla
This commit is contained in:
1 parent
d2c20ab473
commit
7219c257d7
1 file changed
+327
@@ -0,0 +1,327 @@
|
||||
"""Textos finales y pendientes de CHM (Pieza G, PR G2): `app/textos.py`, la macro
|
||||
`pendiente(clave)`, la portada y la agenda `/pendientes-chm`.
|
||||
|
||||
La prueba central recorre `textos.ubicaciones()` (leído de las plantillas) y abre cada pantalla
|
||||
para comprobar que la etiqueta aparece donde la agenda dice que aparece.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from collections.abc import Callable, Iterator
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app import audit, textos
|
||||
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.main import crear_app
|
||||
from app.models import Alerta, Base, Cliente, Coincidencia, Lista, Pep, ReglaAlerta
|
||||
from app.models.usuario import Rol
|
||||
from app.routers import plantillas
|
||||
from app.services import alertas as servicio_alertas
|
||||
from app.services import riesgo as servicio_riesgo
|
||||
from app.services import screening as servicio_screening
|
||||
from seed.usuarios_demo import sembrar
|
||||
from tests.test_expediente import CONTRASENAS, FIXTURE, entrar
|
||||
|
||||
DIR_LISTAS = Path(__file__).parent / "fixtures" / "listas"
|
||||
DIR_PLANTILLAS = Path(__file__).resolve().parents[1] / "app" / "templates"
|
||||
PAIS_GAFI = "Haití"
|
||||
POR_VALIDAR = {
|
||||
"ponderacion_morales",
|
||||
"pep_bajo_nivel",
|
||||
"paises_riesgo_medio",
|
||||
"d04_solo_pagos",
|
||||
"edad_excel",
|
||||
"umbrales_screening",
|
||||
}
|
||||
POR_RATIFICAR = {"preponderancia", "umbral_18", "cuenta_b06", "manuales_b05_b07"}
|
||||
# Plantillas de la línea de riesgo: ella coloca la macro y prueba sus pantallas.
|
||||
DE_OTRA_LINEA = ("riesgo/", "laboratorio/", "evidencia/", "auditoria/")
|
||||
|
||||
|
||||
@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()
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
sesion.commit()
|
||||
importar_esquema(sesion, FIXTURE, "pytest", sal="sal-textos")
|
||||
servicio_riesgo.evaluar_cartera(sesion, "inicial")
|
||||
servicio_alertas.ejecutar_reglas(sesion, usuario="pytest")
|
||||
for nombre, definicion in importador_listas.LISTAS.items():
|
||||
archivo = next(DIR_LISTAS.glob(definicion.patron_archivo))
|
||||
importador_listas.importar_lista(sesion, nombre, archivo, usuario="pytest")
|
||||
sesion.commit()
|
||||
with fabrica() as sesion:
|
||||
audit.fijar_actor(sesion, "pytest", 1)
|
||||
# Lo que la cartera real no trae: una persona moral, un país GAFI (E-02) y una
|
||||
# coincidencia de screening contra una lista cargada.
|
||||
tenant_id = sesion.scalar(sa.select(Cliente.tenant_id).limit(1))
|
||||
sesion.add(
|
||||
Cliente(
|
||||
tenant_id=tenant_id,
|
||||
created_by="pytest",
|
||||
id_externo="moral-textos-0001",
|
||||
tipo_persona="moral",
|
||||
pais="México",
|
||||
)
|
||||
)
|
||||
gafi = sesion.scalar(sa.select(Cliente).order_by(Cliente.id).limit(1))
|
||||
gafi.pais = PAIS_GAFI
|
||||
sesion.flush()
|
||||
servicio_alertas.ejecutar_reglas(sesion, claves=["E-02"], cliente_ids=[gafi.id])
|
||||
lista = sesion.scalar(sa.select(Lista).order_by(Lista.id).limit(1))
|
||||
sesion.add(
|
||||
Coincidencia(
|
||||
tenant_id=tenant_id,
|
||||
created_by="pytest",
|
||||
lista_id=lista.id,
|
||||
persona_id=gafi.id,
|
||||
texto_lista="ENTRADA FICTICIA DE PRUEBA",
|
||||
score=Decimal("91"),
|
||||
decision="pendiente",
|
||||
fuente="screening",
|
||||
)
|
||||
)
|
||||
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 etiquetas(texto: str) -> set[str]:
|
||||
return set(re.findall(r'data-pendiente="([a-z0-9_]+)"', texto))
|
||||
|
||||
|
||||
def renderizar(fuente: str) -> str:
|
||||
return plantillas.env.from_string(fuente).render()
|
||||
|
||||
|
||||
# --- Catálogo y macro --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_catalogo_de_pendientes() -> None:
|
||||
claves = [p.clave for p in textos.PENDIENTES]
|
||||
assert len(claves) == len(set(claves)) == 10
|
||||
assert {p.clave for p in textos.por_validar()} == POR_VALIDAR
|
||||
assert {p.clave for p in textos.por_ratificar()} == POR_RATIFICAR
|
||||
for p in textos.PENDIENTES:
|
||||
assert p.texto and p.hoy and p.referencia
|
||||
assert p.pregunta.strip().endswith("?"), p.clave
|
||||
# Los ratificables son exactamente los que el brief v2.1 da por decididos.
|
||||
assert all("Brief v2.1" in p.referencia for p in textos.por_ratificar())
|
||||
with pytest.raises(KeyError, match="desconocido"):
|
||||
textos.pendiente("no_existe")
|
||||
|
||||
|
||||
def test_la_macro_pinta_solo_los_pendientes_por_validar() -> None:
|
||||
importar = '{% from "_componentes/pendiente.html" import pendiente, pendiente_de_regla %}'
|
||||
salida = renderizar(importar + '{{ pendiente("pep_bajo_nivel") }}')
|
||||
p = textos.pendiente("pep_bajo_nivel")
|
||||
assert etiquetas(salida) == {"pep_bajo_nivel"}
|
||||
assert "pendiente de validación" in salida and 'href="/pendientes-chm#pep_bajo_nivel"' in salida
|
||||
assert html.escape(p.pregunta, quote=True) in salida # la pregunta va en el tooltip
|
||||
for clave in POR_RATIFICAR:
|
||||
assert renderizar(importar + f'{{{{ pendiente("{clave}") }}}}').strip() == ""
|
||||
assert etiquetas(renderizar(importar + '{{ pendiente_de_regla("D-04") }}')) == {
|
||||
"d04_solo_pagos"
|
||||
}
|
||||
assert renderizar(importar + '{{ pendiente_de_regla("B-06") }}').strip() == "" # ratificar
|
||||
assert renderizar(importar + '{{ pendiente_de_regla("A-01") }}').strip() == ""
|
||||
with pytest.raises(KeyError):
|
||||
renderizar(importar + '{{ pendiente("no_existe") }}')
|
||||
|
||||
|
||||
def test_las_plantillas_solo_usan_claves_del_catalogo() -> None:
|
||||
llamada = re.compile(r"""\bpendiente\(\s*["']([a-z0-9_]+)["']""")
|
||||
comentario = re.compile(r"\{#.*?#\}", re.DOTALL)
|
||||
usadas = set()
|
||||
for archivo in DIR_PLANTILLAS.rglob("*.html"):
|
||||
usadas |= set(llamada.findall(comentario.sub("", archivo.read_text(encoding="utf-8"))))
|
||||
assert usadas <= {p.clave for p in textos.PENDIENTES}
|
||||
assert set(textos.PENDIENTES_POR_REGLA.values()) <= {p.clave for p in textos.PENDIENTES}
|
||||
# Cada pendiente por validar aparece al menos en una pantalla.
|
||||
assert POR_VALIDAR <= set(textos.ubicaciones())
|
||||
|
||||
|
||||
def test_marco_regulatorio() -> None:
|
||||
tenant = SimpleNamespace(
|
||||
nombre="Financiera Demo",
|
||||
regimen="LFPIORPI",
|
||||
actividad_vulnerable="Art. 17 fracción IV",
|
||||
uma_vigente=Decimal("117.31"),
|
||||
fecha_corte=date(2026, 8, 31),
|
||||
ventana_meses=6,
|
||||
)
|
||||
marco = textos.marco_regulatorio(tenant, 1605, "v2")
|
||||
assert marco.regimen.sigla == "LFPIORPI" and "Procedencia Ilícita" in marco.regimen.nombre
|
||||
assert marco.actividad == (
|
||||
"Art. 17, fracción IV: otorgamiento de créditos por quien no es entidad financiera"
|
||||
)
|
||||
assert marco.umbral_uma == 1605 and marco.umbral_pesos == Decimal("188282.55")
|
||||
assert marco.regla_umbral == "A-01 v2"
|
||||
assert [h.fecha for h in marco.calendario] == [
|
||||
date(2027, 3, 1),
|
||||
date(2027, 6, 1),
|
||||
date(2028, 1, 1),
|
||||
]
|
||||
sin_regla = textos.marco_regulatorio(tenant, None)
|
||||
assert sin_regla.umbral_uma is None and sin_regla.umbral_pesos is None
|
||||
assert textos.descripcion_actividad("otra cosa") == "otra cosa"
|
||||
|
||||
|
||||
# --- Pantallas ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_inicio_muestra_el_marco_el_calendario_y_los_ocho_pasos(cliente: TestClient) -> None:
|
||||
entrar(cliente, Rol.AUDITOR)
|
||||
pagina = cliente.get("/inicio")
|
||||
assert pagina.status_code == 200
|
||||
texto = html.unescape(pagina.text)
|
||||
for esperado in (
|
||||
"LFPIORPI",
|
||||
"Ley Federal para la Prevención e Identificación de Operaciones con Recursos de "
|
||||
"Procedencia Ilícita",
|
||||
"Art. 17, fracción IV: otorgamiento de créditos por quien no es entidad financiera",
|
||||
"1,605 UMA = $188,282.55",
|
||||
"regla A-01 v2",
|
||||
"31/08/2026",
|
||||
"6 meses",
|
||||
"(28/02/2026, 31/08/2026]",
|
||||
"01/03/2027",
|
||||
"Metodología de riesgo, clasificación de clientes y manual exigibles",
|
||||
"01/06/2027",
|
||||
"Mecanismos automatizados del Art. 41 exigibles",
|
||||
"01/01/2028",
|
||||
"Primer periodo auditable",
|
||||
"Acuerdo 115/2026",
|
||||
):
|
||||
assert esperado in texto, esperado
|
||||
recorrido = texto.split('class="recorrido"')[1].split("</ol>")[0]
|
||||
assert recorrido.count('class="recorrido__paso') == 8
|
||||
assert recorrido.count("es-deshabilitado") == 0
|
||||
assert etiquetas(pagina.text) == POR_VALIDAR
|
||||
assert 'href="/pendientes-chm"' in pagina.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rol", list(Rol))
|
||||
def test_la_agenda_lista_todos_los_pendientes(cliente: TestClient, rol: Rol) -> None:
|
||||
entrar(cliente, rol)
|
||||
pagina = cliente.get("/pendientes-chm")
|
||||
assert pagina.status_code == 200
|
||||
texto = html.unescape(pagina.text)
|
||||
for p in textos.PENDIENTES:
|
||||
assert f'id="{p.clave}"' in pagina.text
|
||||
assert p.pregunta in texto and p.hoy in texto
|
||||
por_ratificar = texto.split("Para ratificar por escrito")[1]
|
||||
assert all(f'id="{clave}"' in por_ratificar for clave in POR_RATIFICAR)
|
||||
assert etiquetas(por_ratificar) == set()
|
||||
for clave, lugares in textos.ubicaciones().items():
|
||||
if clave in POR_VALIDAR:
|
||||
for u in lugares:
|
||||
assert u.pantalla in texto and u.plantilla in texto
|
||||
# La barra lateral lleva a la agenda con el número de temas por validar.
|
||||
assert 'href="/pendientes-chm"' in pagina.text and 'title="Pendientes">6<' in pagina.text
|
||||
|
||||
|
||||
def _urls(sesion: Session) -> dict[str, Callable[[str], str]]:
|
||||
"""Plantilla → cómo abrir una pantalla que la usa con la etiqueta de `clave` visible."""
|
||||
|
||||
def alerta_de(clave: str) -> Alerta:
|
||||
reglas = [r for r, c in textos.PENDIENTES_POR_REGLA.items() if c == clave]
|
||||
alerta = sesion.scalar(
|
||||
sa.select(Alerta)
|
||||
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
||||
.where(ReglaAlerta.clave.in_(reglas))
|
||||
.order_by(Alerta.id)
|
||||
.limit(1)
|
||||
)
|
||||
assert alerta is not None, f"no hay alerta de {reglas} en el fixture"
|
||||
return alerta
|
||||
|
||||
def bandeja(clave: str) -> str:
|
||||
alerta = alerta_de(clave)
|
||||
familia = sesion.get(ReglaAlerta, alerta.regla_id).familia
|
||||
return f"/alertas?familia={familia}&cliente_id={alerta.cliente_id}"
|
||||
|
||||
def ficha(clave: str) -> str:
|
||||
if clave == "ponderacion_morales":
|
||||
consulta = sa.select(Cliente.id).where(Cliente.tipo_persona == "moral")
|
||||
elif clave == "pep_bajo_nivel":
|
||||
consulta = sa.select(Pep.persona_id).where(Pep.tipo == "nacional")
|
||||
else:
|
||||
consulta = sa.select(Cliente.id).where(Cliente.fecha_nacimiento.is_not(None))
|
||||
return f"/clientes/{sesion.scalar(consulta.limit(1))}"
|
||||
|
||||
def coincidencia(_clave: str) -> str:
|
||||
con_lista = sa.select(Coincidencia.id).where(Coincidencia.lista_id.is_not(None))
|
||||
return f"/screening/{sesion.scalar(con_lista.limit(1))}"
|
||||
|
||||
return {
|
||||
"alertas/bandeja.html": bandeja,
|
||||
"alertas/detalle.html": lambda clave: f"/alertas/{alerta_de(clave).id}",
|
||||
"clientes/ficha.html": ficha,
|
||||
"expediente/index.html": lambda _: "/expediente",
|
||||
"expediente/nuevo.html": lambda _: "/clientes/nuevo?tipo=moral",
|
||||
"expediente/_campos_identificacion.html": lambda _: "/clientes/nuevo?tipo=fisica",
|
||||
"screening/index.html": lambda _: "/screening",
|
||||
"screening/listas.html": lambda _: "/screening/listas",
|
||||
"screening/detalle.html": coincidencia,
|
||||
"operaciones/cargas.html": lambda _: "/operaciones/cargas",
|
||||
}
|
||||
|
||||
|
||||
def test_las_etiquetas_aparecen_donde_dice_la_agenda(fabrica, cliente: TestClient) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
revisadas = 0
|
||||
with fabrica() as sesion:
|
||||
urls = _urls(sesion)
|
||||
for clave, lugares in sorted(textos.ubicaciones().items()):
|
||||
if clave not in POR_VALIDAR:
|
||||
continue
|
||||
for plantilla in sorted({u.plantilla for u in lugares}):
|
||||
if plantilla.startswith(DE_OTRA_LINEA):
|
||||
continue
|
||||
assert plantilla in urls, f"agrega a _urls cómo abrir {plantilla}"
|
||||
url = urls[plantilla](clave)
|
||||
pagina = cliente.get(url)
|
||||
assert pagina.status_code == 200, url
|
||||
assert clave in etiquetas(pagina.text), f"{clave} no aparece en {url}"
|
||||
revisadas += 1
|
||||
assert revisadas >= 15
|
||||
|
||||
|
||||
def test_lo_ratificado_no_lleva_etiqueta_en_pantalla(fabrica, cliente: TestClient) -> None:
|
||||
"""B-06 (CUENTA) y B-05/B-07 (manuales) están decididos en el brief: sin etiqueta."""
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
with fabrica() as sesion:
|
||||
b06 = sesion.scalar(
|
||||
sa.select(Alerta)
|
||||
.join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
|
||||
.where(ReglaAlerta.clave == "B-06")
|
||||
.limit(1)
|
||||
)
|
||||
pagina = cliente.get(f"/alertas/{b06.id}")
|
||||
assert pagina.status_code == 200
|
||||
assert not etiquetas(pagina.text) & POR_RATIFICAR
|
||||
Reference in new issue
Block a user