192 lines
7.7 KiB
Python
192 lines
7.7 KiB
Python
"""Lote de carga: el archivo original se guarda por empresa y lote, se descarga solo con la huella
|
|
verificada (cada descarga y cada intento bloqueado en el audit trail), lo descargan el oficial,
|
|
el analista y el auditor pero no el administrador de plataforma, y Evidencia liga cada dato con el
|
|
lote y el archivo que le dio origen."""
|
|
|
|
# ruff: noqa: F811 (las fixtures vienen de tests/test_plataforma)
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
from pathlib import Path
|
|
|
|
import sqlalchemy as sa
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
from app.auth import COOKIE_SESION
|
|
from app.config import get_settings
|
|
from app.models import AuditTrail, LoteCarga
|
|
from app.models.usuario import Rol
|
|
from app.services import operaciones as servicio
|
|
from tests.test_carga import COMPLETO, actor, xlsx
|
|
from tests.test_plataforma import ( # noqa: F401
|
|
administrador,
|
|
cliente,
|
|
entrar_empresa,
|
|
entrar_plataforma,
|
|
fabrica,
|
|
token,
|
|
)
|
|
|
|
NOMBRE = "cartera de octubre.xlsx"
|
|
|
|
|
|
def subir(cliente: TestClient, contenido: bytes, nombre: str = NOMBRE) -> int:
|
|
r = cliente.post(
|
|
"/carga",
|
|
files={"archivo": (nombre, contenido, "application/octet-stream")},
|
|
)
|
|
assert r.status_code == 303, r.text
|
|
return int(r.headers["location"].split("/")[3].split("?")[0])
|
|
|
|
|
|
def lote(fabrica: sessionmaker[Session], lote_id: int) -> LoteCarga:
|
|
with fabrica() as sesion:
|
|
return sesion.get(LoteCarga, lote_id)
|
|
|
|
|
|
def bitacora(fabrica: sessionmaker[Session], accion: str) -> list[AuditTrail]:
|
|
with fabrica() as sesion:
|
|
return list(
|
|
sesion.scalars(
|
|
sa.select(AuditTrail)
|
|
.where(AuditTrail.entidad == "lote_carga", AuditTrail.accion == accion)
|
|
.order_by(AuditTrail.id)
|
|
)
|
|
)
|
|
|
|
|
|
def test_el_original_se_guarda_por_empresa_y_lote_y_se_descarga_identico(
|
|
fabrica, cliente: TestClient
|
|
) -> None:
|
|
contenido = xlsx(COMPLETO())
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
lote_id = subir(cliente, contenido)
|
|
guardado = lote(fabrica, lote_id)
|
|
data_dir = Path(get_settings().data_dir)
|
|
# Fuera de la base, en el volumen de datos, con nombre por empresa y lote.
|
|
assert guardado.ruta_archivo == f"cargas/empresa-{guardado.tenant_id}/lote-{lote_id}.xlsx"
|
|
assert (data_dir / guardado.ruta_archivo).read_bytes() == contenido
|
|
assert not list((data_dir / "cargas" / servicio.CARPETA_RECIBIDOS).iterdir())
|
|
|
|
r = cliente.get(f"/carga/lotes/{lote_id}/original")
|
|
assert r.status_code == 200
|
|
assert r.content == contenido # byte a byte
|
|
huella = hashlib.sha256(r.content).hexdigest()
|
|
assert huella == guardado.archivo_hash == r.headers["X-Huella-Verificada"]
|
|
assert "cartera%20de%20octubre.xlsx" in r.headers["content-disposition"]
|
|
|
|
# Quién, cuándo y qué lote.
|
|
(fila,) = bitacora(fabrica, servicio.ACCION_DESCARGA)
|
|
assert fila.usuario == "oficial" and fila.entidad_id == lote_id and fila.fecha is not None
|
|
assert fila.despues["huella"] == huella
|
|
|
|
|
|
def test_el_mismo_archivo_otra_vez_no_deja_una_copia_suelta(fabrica, cliente: TestClient) -> None:
|
|
contenido = xlsx(COMPLETO())
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
primero = subir(cliente, contenido)
|
|
with actor(fabrica) as sesion:
|
|
servicio.confirmar_carga(sesion, primero, "oficial")
|
|
sesion.commit()
|
|
r = cliente.post("/carga", files={"archivo": (NOMBRE, contenido, "application/octet-stream")})
|
|
assert r.headers["location"] == f"/carga/lotes/{primero}?ya_cargado=1"
|
|
cargas = Path(get_settings().data_dir) / "cargas"
|
|
assert [p.name for p in cargas.rglob("*") if p.is_file()] == [f"lote-{primero}.xlsx"]
|
|
|
|
|
|
def test_un_archivo_alterado_no_se_entrega_y_queda_en_la_bitacora(
|
|
fabrica, cliente: TestClient
|
|
) -> None:
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
lote_id = subir(cliente, xlsx(COMPLETO()))
|
|
ruta = Path(get_settings().data_dir) / lote(fabrica, lote_id).ruta_archivo
|
|
ruta.write_bytes(ruta.read_bytes() + b" ") # un solo carácter
|
|
|
|
r = cliente.get(f"/carga/lotes/{lote_id}/original")
|
|
assert r.status_code == 303 and "error=" in r.headers["location"]
|
|
pagina = cliente.get(r.headers["location"]).text
|
|
assert "no coincide con la registrada" in pagina
|
|
# Pedido desde la página (fetch): 409 con el mensaje, sin el archivo.
|
|
r = cliente.get(f"/carga/lotes/{lote_id}/original", headers={"X-Solicitud": "fetch"})
|
|
assert r.status_code == 409 and "no coincide" in r.json()["error"]
|
|
|
|
bloqueadas = bitacora(fabrica, servicio.ACCION_DESCARGA_BLOQUEADA)
|
|
assert len(bloqueadas) == 2 and bloqueadas[0].entidad_id == lote_id
|
|
assert bloqueadas[0].despues["huella_registrada"] != bloqueadas[0].despues["huella_calculada"]
|
|
assert not bitacora(fabrica, servicio.ACCION_DESCARGA)
|
|
|
|
ruta.unlink() # y si falta, tampoco
|
|
r = cliente.get(f"/carga/lotes/{lote_id}/original", headers={"X-Solicitud": "fetch"})
|
|
assert r.status_code == 409 and "no está" in r.json()["error"]
|
|
|
|
|
|
def test_lo_descargan_oficial_analista_y_auditor_y_no_el_administrador_de_plataforma(
|
|
fabrica, cliente: TestClient, administrador
|
|
) -> None:
|
|
contenido = xlsx(COMPLETO())
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
lote_id = subir(cliente, contenido)
|
|
for rol in (Rol.ANALISTA, Rol.AUDITOR):
|
|
cliente.post("/logout")
|
|
entrar_empresa(cliente, rol)
|
|
assert "Descargar archivo original" in cliente.get(f"/carga/lotes/{lote_id}").text
|
|
r = cliente.get(f"/carga/lotes/{lote_id}/original")
|
|
assert r.status_code == 200 and r.content == contenido
|
|
assert [f.usuario for f in bitacora(fabrica, servicio.ACCION_DESCARGA)] == [
|
|
"analista",
|
|
"auditor",
|
|
]
|
|
|
|
cliente.post("/logout")
|
|
cliente.cookies.delete(COOKIE_SESION)
|
|
assert entrar_plataforma(cliente).status_code == 303
|
|
assert cliente.get(f"/carga/lotes/{lote_id}/original").status_code == 403
|
|
assert len(bitacora(fabrica, servicio.ACCION_DESCARGA)) == 2
|
|
|
|
|
|
def test_la_pagina_del_lote_explica_la_huella_y_la_deja_copiar(
|
|
fabrica, cliente: TestClient
|
|
) -> None:
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
lote_id = subir(cliente, xlsx(COMPLETO()))
|
|
huella = lote(fabrica, lote_id).archivo_hash
|
|
pagina = cliente.get(f"/carga/lotes/{lote_id}").text
|
|
assert (
|
|
"Huella digital del archivo. Si se modifica un solo carácter, deja de coincidir." in pagina
|
|
)
|
|
assert f'data-copiar="{huella}"' in pagina
|
|
assert f'href="/carga/lotes/{lote_id}/original"' in pagina
|
|
|
|
|
|
def test_evidencia_liga_cada_dato_con_su_lote_y_su_archivo(fabrica, cliente: TestClient) -> None:
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
lote_id = subir(cliente, xlsx(COMPLETO()))
|
|
with actor(fabrica) as sesion:
|
|
servicio.confirmar_carga(sesion, lote_id, "oficial")
|
|
sesion.commit()
|
|
cliente_id = sesion.scalar(
|
|
sa.select(AuditTrail.entidad_id)
|
|
.where(AuditTrail.entidad == "cliente", AuditTrail.accion == "alta")
|
|
.order_by(AuditTrail.id)
|
|
.limit(1)
|
|
)
|
|
pagina = cliente.get(f"/evidencia/{cliente_id}").text
|
|
assert "Origen de los datos" in pagina
|
|
assert f'href="/carga/lotes/{lote_id}"' in pagina
|
|
assert f'data-original-lote="{lote_id}"' in pagina
|
|
assert NOMBRE in pagina
|
|
assert "alta del cliente, 1 crédito, 1 pago" in pagina
|
|
|
|
|
|
def test_el_historial_de_cargas_descarga_el_original(fabrica, cliente: TestClient) -> None:
|
|
contenido = xlsx(COMPLETO())
|
|
entrar_empresa(cliente, Rol.OFICIAL)
|
|
lote_id = subir(cliente, contenido)
|
|
for rol in (Rol.OFICIAL, Rol.ANALISTA, Rol.AUDITOR):
|
|
cliente.post("/logout")
|
|
entrar_empresa(cliente, rol)
|
|
historial = cliente.get("/carga").text
|
|
assert f'href="/carga/lotes/{lote_id}/original"' in historial
|
|
assert cliente.get(f"/carga/lotes/{lote_id}/original").content == contenido
|