test(app): auth, audit y autoregistro
This commit is contained in:
1 parent
01402abda4
commit
387ed5106c
3 files changed
+611
No files matched your search
@@ -0,0 +1,203 @@
|
||||
"""Audit trail: accesos autenticados, `registrar` y su inmutabilidad (secciones 3 y 6)."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from datetime import UTC, date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app import audit
|
||||
from app.db import BorradoProhibidoError, crear_engine, crear_session_factory
|
||||
from app.main import crear_app
|
||||
from app.models import AuditTrail, Base, Tenant
|
||||
from app.models.usuario import Rol
|
||||
from seed.usuarios_demo import sembrar
|
||||
|
||||
CONTRASENAS = {Rol.ANALISTA: "clave-analista-1", Rol.OFICIAL: "clave-oficial-2"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fabrica(monkeypatch: pytest.MonkeyPatch) -> sessionmaker[Session]:
|
||||
"""Base en memoria propia del test, con el tenant demo y dos usuarios."""
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
fabrica = crear_session_factory(engine)
|
||||
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
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(cliente: TestClient, rol: Rol) -> None:
|
||||
respuesta = cliente.post("/login", data={"usuario": rol.value, "contrasena": CONTRASENAS[rol]})
|
||||
assert respuesta.status_code == 303
|
||||
|
||||
|
||||
def filas_de(fabrica: sessionmaker[Session], entidad: str) -> list[AuditTrail]:
|
||||
with fabrica() as sesion:
|
||||
return list(
|
||||
sesion.scalars(
|
||||
sa.select(AuditTrail).where(AuditTrail.entidad == entidad).order_by(AuditTrail.id)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# --- Accesos -------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_acceso_autenticado_deja_fila_con_usuario(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
assert cliente.get("/inicio?desde=prueba").status_code == 200
|
||||
|
||||
(fila,) = filas_de(fabrica, "http")
|
||||
assert fila.accion == "GET /inicio"
|
||||
assert fila.usuario == "analista"
|
||||
assert fila.created_by == "analista"
|
||||
assert fila.entidad_id is None
|
||||
assert fila.despues == {"ruta": "/inicio", "status": 200, "consulta": "desde=prueba"}
|
||||
assert fila.fecha is not None
|
||||
with fabrica() as sesion:
|
||||
assert fila.tenant_id == sesion.scalar(sa.select(Tenant.id))
|
||||
|
||||
|
||||
def test_rutas_publicas_y_accesos_sin_sesion_no_dejan_fila(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
cliente.get("/api/health")
|
||||
cliente.get("/login")
|
||||
cliente.get("/static/app.css")
|
||||
cliente.get("/")
|
||||
assert cliente.get("/inicio").status_code == 303 # sin sesión
|
||||
|
||||
assert filas_de(fabrica, "http") == []
|
||||
|
||||
|
||||
def test_login_y_logout_quedan_registrados(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
cliente.post("/logout")
|
||||
|
||||
acciones = [(f.accion, f.usuario) for f in filas_de(fabrica, "usuario") if f.usuario != "seed"]
|
||||
assert acciones == [("login", "oficial"), ("logout", "oficial")]
|
||||
|
||||
|
||||
def test_una_ruta_larga_se_recorta_en_accion_y_queda_completa_en_despues() -> None:
|
||||
ruta = "/expediente/123456/documentos/7890/versiones"
|
||||
accion = audit._accion_http("GET", ruta)
|
||||
|
||||
assert len(accion) == audit.LARGO_ACCION
|
||||
assert accion.startswith("GET /expediente/")
|
||||
assert audit._accion_http("GET", "/inicio") == "GET /inicio"
|
||||
|
||||
|
||||
# --- registrar -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_registrar_serializa_fechas_y_decimales(fabrica: sessionmaker[Session]) -> None:
|
||||
with fabrica() as sesion:
|
||||
tenant_id = sesion.scalar(sa.select(Tenant.id))
|
||||
audit.fijar_actor(sesion, "oficial", tenant_id)
|
||||
fila = audit.registrar(
|
||||
sesion,
|
||||
"credito",
|
||||
7,
|
||||
"actualizar",
|
||||
antes={"monto": Decimal("188283.55"), "fecha_disposicion": date(2026, 8, 31)},
|
||||
despues={
|
||||
"monto": Decimal("190000.00"),
|
||||
"revisado_el": datetime(2026, 10, 6, 12, 30, tzinfo=UTC),
|
||||
"rol": Rol.OFICIAL,
|
||||
"pagos": [Decimal("1.10"), None],
|
||||
},
|
||||
motivo="Corrección de captura",
|
||||
)
|
||||
sesion.commit()
|
||||
fila_id = fila.id
|
||||
|
||||
with fabrica() as sesion:
|
||||
guardada = sesion.get(AuditTrail, fila_id)
|
||||
assert guardada.antes == {"monto": "188283.55", "fecha_disposicion": "2026-08-31"}
|
||||
assert guardada.despues == {
|
||||
"monto": "190000.00",
|
||||
"revisado_el": "2026-10-06T12:30:00+00:00",
|
||||
"rol": "oficial",
|
||||
"pagos": ["1.10", None],
|
||||
}
|
||||
assert (guardada.usuario, guardada.tenant_id) == ("oficial", tenant_id)
|
||||
assert (guardada.entidad, guardada.entidad_id) == ("credito", 7)
|
||||
assert guardada.motivo == "Corrección de captura"
|
||||
assert guardada.fecha is not None
|
||||
|
||||
|
||||
def test_registrar_sin_actor_falla(fabrica: sessionmaker[Session]) -> None:
|
||||
with fabrica() as sesion, pytest.raises(ValueError, match="sin actor"):
|
||||
audit.registrar(sesion, "credito", 1, "crear")
|
||||
|
||||
|
||||
def test_registrar_rechaza_un_valor_que_no_sabe_serializar(
|
||||
fabrica: sessionmaker[Session],
|
||||
) -> None:
|
||||
with fabrica() as sesion, pytest.raises(TypeError):
|
||||
audit.registrar(
|
||||
sesion, "credito", 1, "crear", despues={"x": object()}, usuario="oficial", tenant_id=1
|
||||
)
|
||||
|
||||
|
||||
# --- Inmutabilidad -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_borrar_una_fila_de_audit_trail_falla(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
cliente.get("/inicio")
|
||||
|
||||
with fabrica() as sesion:
|
||||
total = sesion.scalar(sa.select(sa.func.count()).select_from(AuditTrail))
|
||||
fila = sesion.scalar(sa.select(AuditTrail).where(AuditTrail.entidad == "http"))
|
||||
|
||||
sesion.delete(fila)
|
||||
with pytest.raises(BorradoProhibidoError):
|
||||
sesion.commit()
|
||||
sesion.rollback()
|
||||
|
||||
with pytest.raises(audit.AuditoriaInmutableError):
|
||||
sesion.execute(sa.delete(AuditTrail).where(AuditTrail.id == fila.id))
|
||||
sesion.rollback()
|
||||
|
||||
assert sesion.scalar(sa.select(sa.func.count()).select_from(AuditTrail)) == total
|
||||
|
||||
|
||||
def test_modificar_una_fila_de_audit_trail_falla(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
|
||||
with fabrica() as sesion:
|
||||
fila = sesion.scalar(sa.select(AuditTrail).where(AuditTrail.accion == "login"))
|
||||
|
||||
fila.usuario = "otro"
|
||||
with pytest.raises(audit.AuditoriaInmutableError):
|
||||
sesion.commit()
|
||||
sesion.rollback()
|
||||
|
||||
with pytest.raises(audit.AuditoriaInmutableError):
|
||||
sesion.execute(sa.update(AuditTrail).values(usuario="otro"))
|
||||
sesion.rollback()
|
||||
|
||||
assert sesion.scalar(sa.select(AuditTrail.usuario).where(AuditTrail.id == fila.id)) == (
|
||||
"analista"
|
||||
)
|
||||
@@ -0,0 +1,314 @@
|
||||
"""Sesión por cookie firmada, roles y alta de los usuarios demo (sección 5 del brief)."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from typing import Annotated
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from fastapi import Depends
|
||||
from fastapi.testclient import TestClient
|
||||
from itsdangerous import URLSafeTimedSerializer
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app.auth import (
|
||||
COOKIE_SESION,
|
||||
hashear_contrasena,
|
||||
requiere_rol,
|
||||
verificar_contrasena,
|
||||
)
|
||||
from app.db import crear_engine, crear_session_factory
|
||||
from app.main import crear_app
|
||||
from app.models import AuditTrail, Base, Tenant, Usuario
|
||||
from app.models.usuario import Rol
|
||||
from app.routers import plantillas
|
||||
from seed.usuarios_demo import TENANT_DEMO_NOMBRE, sembrar
|
||||
|
||||
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 propia del test, con el tenant y los tres usuarios demo."""
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
fabrica = crear_session_factory(engine)
|
||||
monkeypatch.setattr("app.db.SessionLocal", fabrica)
|
||||
with fabrica() as sesion:
|
||||
sembrar(sesion, CONTRASENAS)
|
||||
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(cliente: TestClient, rol: Rol, contrasena: str | None = None):
|
||||
return cliente.post(
|
||||
"/login", data={"usuario": rol.value, "contrasena": contrasena or CONTRASENAS[rol]}
|
||||
)
|
||||
|
||||
|
||||
# --- Login y cookie ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_login_correcto_crea_cookie_firmada(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
respuesta = entrar(cliente, Rol.OFICIAL)
|
||||
|
||||
assert respuesta.status_code == 303
|
||||
assert respuesta.headers["location"] == "/inicio"
|
||||
cabecera = respuesta.headers["set-cookie"].lower()
|
||||
assert cabecera.startswith(f"{COOKIE_SESION}=")
|
||||
assert "httponly" in cabecera
|
||||
assert "samesite=lax" in cabecera
|
||||
assert "secure" not in cabecera # la petición de prueba llega por http
|
||||
|
||||
with fabrica() as sesion:
|
||||
oficial = sesion.scalar(sa.select(Usuario).where(Usuario.usuario == "oficial"))
|
||||
datos = URLSafeTimedSerializer("secreto-de-pruebas", salt="pld.sesion").loads(
|
||||
respuesta.cookies[COOKIE_SESION]
|
||||
)
|
||||
assert datos == {"uid": oficial.id, "tid": oficial.tenant_id}
|
||||
|
||||
|
||||
def test_la_cookie_es_secure_cuando_la_peticion_llega_por_https(
|
||||
fabrica: sessionmaker[Session],
|
||||
) -> None:
|
||||
with TestClient(crear_app(), base_url="https://testserver", follow_redirects=False) as c:
|
||||
respuesta = entrar(c, Rol.ANALISTA)
|
||||
assert "secure" in respuesta.headers["set-cookie"].lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rol", list(Rol))
|
||||
def test_los_tres_usuarios_entran_y_ven_inicio(cliente: TestClient, rol: Rol) -> None:
|
||||
assert entrar(cliente, rol).status_code == 303
|
||||
|
||||
respuesta = cliente.get("/inicio")
|
||||
assert respuesta.status_code == 200
|
||||
assert rol.value in respuesta.text
|
||||
|
||||
|
||||
def test_contrasena_incorrecta_no_crea_cookie(cliente: TestClient) -> None:
|
||||
respuesta = entrar(cliente, Rol.OFICIAL, "no-es-la-clave")
|
||||
|
||||
assert respuesta.status_code == 401
|
||||
assert "set-cookie" not in respuesta.headers
|
||||
assert "Usuario o contraseña incorrectos" in respuesta.text
|
||||
assert cliente.get("/inicio").status_code == 303
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"datos", [{"usuario": "nadie", "contrasena": "x"}, {"usuario": "oficial"}, {}]
|
||||
)
|
||||
def test_usuario_inexistente_o_formulario_incompleto_no_entra(
|
||||
cliente: TestClient, datos: dict[str, str]
|
||||
) -> None:
|
||||
respuesta = cliente.post("/login", data=datos)
|
||||
assert respuesta.status_code == 401
|
||||
assert "set-cookie" not in respuesta.headers
|
||||
|
||||
|
||||
def test_cookie_alterada_se_rechaza(cliente: TestClient) -> None:
|
||||
token = entrar(cliente, Rol.OFICIAL).cookies[COOKIE_SESION]
|
||||
assert cliente.get("/inicio").status_code == 200
|
||||
|
||||
cuerpo, resto = token.split(".", 1)
|
||||
alterada = ("A" if cuerpo[0] != "A" else "B") + cuerpo[1:] + "." + resto
|
||||
cliente.cookies.set(COOKIE_SESION, alterada)
|
||||
|
||||
respuesta = cliente.get("/inicio")
|
||||
assert respuesta.status_code == 303
|
||||
assert respuesta.headers["location"] == "/login"
|
||||
|
||||
|
||||
def test_cookie_firmada_con_otra_clave_se_rechaza(
|
||||
cliente: TestClient, fabrica: sessionmaker[Session]
|
||||
) -> None:
|
||||
with fabrica() as sesion:
|
||||
oficial = sesion.scalar(sa.select(Usuario).where(Usuario.usuario == "oficial"))
|
||||
falsa = URLSafeTimedSerializer("otra-clave", salt="pld.sesion").dumps(
|
||||
{"uid": oficial.id, "tid": oficial.tenant_id}
|
||||
)
|
||||
cliente.cookies.set(COOKIE_SESION, falsa)
|
||||
|
||||
assert cliente.get("/inicio").status_code == 303
|
||||
|
||||
|
||||
def test_logout_cierra_la_sesion(cliente: TestClient) -> None:
|
||||
entrar(cliente, Rol.AUDITOR)
|
||||
assert cliente.get("/inicio").status_code == 200
|
||||
|
||||
respuesta = cliente.post("/logout")
|
||||
assert respuesta.status_code == 303
|
||||
assert respuesta.headers["location"] == "/login"
|
||||
assert cliente.get("/inicio").status_code == 303
|
||||
|
||||
|
||||
# --- Rutas públicas, raíz y roles ----------------------------------------------------------
|
||||
|
||||
|
||||
def test_health_sin_sesion_responde_200(cliente: TestClient) -> None:
|
||||
assert cliente.get("/api/health").status_code == 200
|
||||
|
||||
|
||||
def test_raiz_redirige_segun_haya_sesion(cliente: TestClient) -> None:
|
||||
sin_sesion = cliente.get("/")
|
||||
assert sin_sesion.status_code == 303
|
||||
assert sin_sesion.headers["location"] == "/login"
|
||||
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
con_sesion = cliente.get("/")
|
||||
assert con_sesion.status_code == 303
|
||||
assert con_sesion.headers["location"] == "/inicio"
|
||||
|
||||
|
||||
def test_login_con_sesion_abierta_redirige_a_inicio(cliente: TestClient) -> None:
|
||||
assert cliente.get("/login").status_code == 200
|
||||
entrar(cliente, Rol.ANALISTA)
|
||||
assert cliente.get("/login").headers["location"] == "/inicio"
|
||||
|
||||
|
||||
def test_requiere_rol_devuelve_403_al_rol_equivocado(fabrica: sessionmaker[Session]) -> None:
|
||||
app = crear_app()
|
||||
|
||||
@app.post("/solo-oficial")
|
||||
def solo_oficial(usuario: Annotated[Usuario, Depends(requiere_rol(Rol.OFICIAL))]) -> dict:
|
||||
return {"usuario": usuario.usuario}
|
||||
|
||||
with TestClient(app, follow_redirects=False) as c:
|
||||
assert c.post("/solo-oficial").status_code == 303 # sin sesión: a /login
|
||||
|
||||
entrar(c, Rol.ANALISTA)
|
||||
assert c.post("/solo-oficial").status_code == 403
|
||||
|
||||
c.post("/logout")
|
||||
entrar(c, Rol.OFICIAL)
|
||||
respuesta = c.post("/solo-oficial")
|
||||
assert respuesta.status_code == 200
|
||||
assert respuesta.json() == {"usuario": "oficial"}
|
||||
|
||||
|
||||
def test_api_sin_sesion_responde_401_en_vez_de_redirigir(fabrica: sessionmaker[Session]) -> None:
|
||||
app = crear_app()
|
||||
|
||||
@app.get("/api/privado")
|
||||
def privado(usuario: Annotated[Usuario, Depends(requiere_rol(*Rol))]) -> dict:
|
||||
return {}
|
||||
|
||||
with TestClient(app, follow_redirects=False) as c:
|
||||
assert c.get("/api/privado").status_code == 401
|
||||
|
||||
|
||||
# --- Portada, navegación y componentes ---------------------------------------------------
|
||||
|
||||
|
||||
def test_inicio_muestra_tenant_regimen_actividad_y_los_ocho_pasos(cliente: TestClient) -> None:
|
||||
entrar(cliente, Rol.OFICIAL)
|
||||
html = cliente.get("/inicio").text
|
||||
|
||||
assert TENANT_DEMO_NOMBRE in html
|
||||
assert "LFPIORPI" in html
|
||||
assert "Art. 17 fracción IV" in html
|
||||
|
||||
pasos = [
|
||||
"Expediente",
|
||||
"Beneficiario controlador",
|
||||
"Screening",
|
||||
"Clasificación de riesgo",
|
||||
"Créditos y operaciones",
|
||||
"Alertas y casos",
|
||||
"Evidencia",
|
||||
"Laboratorio",
|
||||
]
|
||||
lateral = html[html.index('<nav class="nav"') : html.index("</nav>")]
|
||||
posiciones = [lateral.index(paso) for paso in pasos]
|
||||
assert posiciones == sorted(posiciones)
|
||||
assert "Cartera" in lateral
|
||||
|
||||
# Lo que aún no existe va deshabilitado y dice en qué fase llega; Inicio ya es enlace.
|
||||
assert lateral.count('aria-disabled="true"') == 9
|
||||
assert "fase 4" in lateral
|
||||
assert 'href="/inicio"' in lateral
|
||||
assert 'href="/expediente"' not in lateral
|
||||
|
||||
|
||||
def test_los_componentes_pintan_niveles_estados_tabla_y_tarjeta() -> None:
|
||||
fuente = """
|
||||
{%- from "_componentes/badges.html" import badge_nivel, badge_estado_alerta -%}
|
||||
{%- from "_componentes/tabla.html" import tabla -%}
|
||||
{%- from "_componentes/tarjeta.html" import tarjeta -%}
|
||||
{{ badge_nivel("alto") }}{{ badge_nivel(1) }}{{ badge_estado_alerta("en_revisión") }}
|
||||
{% call tarjeta("Reglas") %}{{ tabla(["clave", "nombre"], filas) }}{% endcall %}
|
||||
{{ tabla(["clave"], []) }}
|
||||
"""
|
||||
html = plantillas.env.from_string(fuente).render(
|
||||
filas=[{"clave": "A-01", "nombre": "<b>Umbral</b>"}, {"clave": "B-05", "nombre": None}]
|
||||
)
|
||||
|
||||
assert 'class="badge badge--peligro" data-nivel="alto">Alto<' in html
|
||||
assert 'class="badge badge--exito" data-nivel="bajo">Bajo<' in html
|
||||
assert 'data-estado="en_revision">En revisión<' in html
|
||||
assert '<h2 class="tarjeta__titulo">Reglas</h2>' in html
|
||||
assert '<th scope="col">Nombre</th>' in html
|
||||
assert "<b>Umbral</b>" in html # el contenido de las celdas se escapa
|
||||
assert "<td>—</td>" in html
|
||||
assert "Sin registros." in html
|
||||
|
||||
|
||||
# --- Contraseñas y usuarios demo -----------------------------------------------------------
|
||||
|
||||
|
||||
def test_hash_de_contrasena_verifica_y_no_la_contiene() -> None:
|
||||
hash_ = hashear_contrasena("mi-clave-secreta")
|
||||
|
||||
assert "mi-clave-secreta" not in hash_
|
||||
assert len(hash_) <= 255
|
||||
assert verificar_contrasena("mi-clave-secreta", hash_)
|
||||
assert not verificar_contrasena("otra", hash_)
|
||||
assert not verificar_contrasena("mi-clave-secreta", "formato-desconocido")
|
||||
assert hashear_contrasena("mi-clave-secreta") != hash_ # sal distinta en cada hash
|
||||
|
||||
|
||||
def test_sembrar_es_idempotente_y_actualiza_la_contrasena(fabrica: sessionmaker[Session]) -> None:
|
||||
with fabrica() as sesion:
|
||||
assert set(sembrar(sesion, CONTRASENAS).values()) == {"sin_cambios"}
|
||||
|
||||
nuevas = CONTRASENAS | {Rol.OFICIAL: "clave-nueva"}
|
||||
assert sembrar(sesion, nuevas)[Rol.OFICIAL] == "actualizado"
|
||||
sesion.commit()
|
||||
|
||||
assert sesion.scalar(sa.select(sa.func.count()).select_from(Usuario)) == 3
|
||||
assert sesion.scalar(sa.select(sa.func.count()).select_from(Tenant)) == 1
|
||||
oficial = sesion.scalar(sa.select(Usuario).where(Usuario.usuario == "oficial"))
|
||||
assert verificar_contrasena("clave-nueva", oficial.hash)
|
||||
|
||||
|
||||
def test_sembrar_omite_al_usuario_sin_contrasena_y_no_la_filtra(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
|
||||
with caplog.at_level("INFO"), crear_session_factory(engine)() as sesion:
|
||||
resultado = sembrar(sesion, {Rol.ANALISTA: "clave-analista-1", Rol.OFICIAL: ""})
|
||||
sesion.commit()
|
||||
|
||||
assert resultado == {
|
||||
Rol.ANALISTA: "creado",
|
||||
Rol.OFICIAL: "omitido",
|
||||
Rol.AUDITOR: "omitido",
|
||||
}
|
||||
assert sesion.scalars(sa.select(Usuario.usuario)).all() == ["analista"]
|
||||
auditado = str(sesion.execute(sa.select(AuditTrail.antes, AuditTrail.despues)).all())
|
||||
|
||||
assert "DEMO_PASSWORD_OFICIAL" in caplog.text
|
||||
assert "clave-analista-1" not in caplog.text
|
||||
assert "clave-analista-1" not in auditado
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Autoregistro: un módulo con `router` en `app/routers/` queda montado sin tocar `main.py`."""
|
||||
|
||||
import sys
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import app.routers
|
||||
from app.db import crear_engine, crear_session_factory
|
||||
from app.main import crear_app
|
||||
from app.models import Base
|
||||
|
||||
RAIZ = Path(__file__).resolve().parents[1]
|
||||
|
||||
MODULO_PROTEGIDO = """
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/prueba-protegida")
|
||||
def protegida() -> dict:
|
||||
return {"ok": True}
|
||||
"""
|
||||
|
||||
MODULO_PUBLICO = """
|
||||
from fastapi import APIRouter
|
||||
|
||||
PUBLICO = True
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/prueba-publica")
|
||||
def publica() -> dict:
|
||||
return {"ok": True}
|
||||
"""
|
||||
|
||||
MODULO_SIN_ROUTER = '"""Stub de una fase posterior: todavía no expone router."""\n'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_con_modulos_temporales(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> Iterator[FastAPI]:
|
||||
"""La app tal como la arma `main.py`, con tres módulos extra en el paquete de routers."""
|
||||
(tmp_path / "prueba_protegida.py").write_text(MODULO_PROTEGIDO)
|
||||
(tmp_path / "prueba_publica.py").write_text(MODULO_PUBLICO)
|
||||
(tmp_path / "prueba_stub.py").write_text(MODULO_SIN_ROUTER)
|
||||
monkeypatch.setattr(app.routers, "__path__", [*app.routers.__path__, str(tmp_path)])
|
||||
|
||||
engine = crear_engine("sqlite://")
|
||||
Base.metadata.create_all(engine)
|
||||
monkeypatch.setattr("app.db.SessionLocal", crear_session_factory(engine))
|
||||
|
||||
yield crear_app()
|
||||
|
||||
for nombre in ("prueba_protegida", "prueba_publica", "prueba_stub"):
|
||||
sys.modules.pop(f"app.routers.{nombre}", None)
|
||||
|
||||
|
||||
def test_un_modulo_nuevo_queda_montado_sin_tocar_main(app_con_modulos_temporales: FastAPI) -> None:
|
||||
with TestClient(app_con_modulos_temporales, follow_redirects=False) as c:
|
||||
assert c.get("/prueba-publica").json() == {"ok": True}
|
||||
assert c.get("/prueba-protegida").status_code != 404
|
||||
assert c.get("/login").status_code == 200
|
||||
assert c.get("/no-existe").status_code == 404
|
||||
|
||||
|
||||
def test_un_router_queda_detras_de_sesion_salvo_que_se_declare_publico(
|
||||
app_con_modulos_temporales: FastAPI,
|
||||
) -> None:
|
||||
with TestClient(app_con_modulos_temporales, follow_redirects=False) as c:
|
||||
protegida = c.get("/prueba-protegida")
|
||||
assert protegida.status_code == 303
|
||||
assert protegida.headers["location"] == "/login"
|
||||
|
||||
assert c.get("/prueba-publica").status_code == 200
|
||||
|
||||
|
||||
def test_montar_routers_ignora_los_modulos_sin_router() -> None:
|
||||
montados = app.routers.montar_routers(FastAPI())
|
||||
|
||||
assert montados == ["auth", "inicio"]
|
||||
|
||||
|
||||
def test_main_no_registra_routers_a_mano() -> None:
|
||||
fuente = (RAIZ / "app" / "main.py").read_text()
|
||||
|
||||
assert "montar_routers(app)" in fuente
|
||||
assert "include_router" not in fuente
|
||||
assert "from app.routers." not in fuente
|
||||
Reference in new issue
Block a user