326 lines
13 KiB
Python
326 lines
13 KiB
Python
"""
|
|
backend/tests/test_benefits_and_reception.py - Suite de pruebas para SDD-012.
|
|
Valida:
|
|
1. Modelo InstitutionalBenefit y AccessLogQR.
|
|
2. Emisión y decodificación de tokens QR en QRSecurityService.
|
|
3. Endpoints RESTful de Beneficios (/api/v1/benefits): permisos, CRUD y validación.
|
|
4. Endpoints de Recepción (/api/v1/reception): verificación de acceso, registro de logs y cronograma del día.
|
|
5. Inyección de convenios en LiveContextService para UdeCi.
|
|
"""
|
|
from datetime import date, timedelta
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app import db
|
|
from main import app
|
|
from app.models.user import User
|
|
from app.models.building import Building
|
|
from app.models.classroom import Classroom
|
|
from app.models.subject import Subject, Commission
|
|
from app.models.enrollment import StudentEnrollment
|
|
from app.models.reservation import Reservation
|
|
from app.models.institutional_benefit import InstitutionalBenefit
|
|
from app.models.access_log_qr import AccessLogQR
|
|
from app.services.jwt_service import JWTService
|
|
from app.services.qr_security_service import QRSecurityService
|
|
from app.services.live_context_service import LiveContextService
|
|
|
|
|
|
def _get_or_create_user(email: str, name: str, role: str) -> User:
|
|
user = User.query.filter_by(email=email).first()
|
|
if not user:
|
|
doc_num = f"38{abs(hash(email)) % 1000000:06d}"
|
|
user = User(
|
|
email=email,
|
|
name=name,
|
|
role=role,
|
|
document_number=doc_num,
|
|
is_active=True
|
|
)
|
|
user.set_password("Secret123!")
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
return user
|
|
|
|
|
|
def test_institutional_benefit_model_and_validity(init_database):
|
|
"""Verifica lógica de dominio del modelo InstitutionalBenefit."""
|
|
today = date.today()
|
|
benefit = InstitutionalBenefit(
|
|
title="20% en Cafetería Central",
|
|
partner_name="Café UniCABA",
|
|
category="GASTRONOMIA",
|
|
discount_label="20% OFF",
|
|
target_roles="ALUMNO,DOCENTE",
|
|
valid_from=today,
|
|
valid_until=today + timedelta(days=30),
|
|
is_active=True
|
|
)
|
|
assert benefit.is_currently_valid is True
|
|
assert benefit.applies_to_role("alumno") is True
|
|
assert benefit.applies_to_role("docente") is True
|
|
assert benefit.applies_to_role("bedelia") is False
|
|
|
|
# Desactivar
|
|
benefit.is_active = False
|
|
assert benefit.is_currently_valid is False
|
|
|
|
# Vencido
|
|
benefit.is_active = True
|
|
benefit.valid_until = today - timedelta(days=1)
|
|
assert benefit.is_currently_valid is False
|
|
|
|
|
|
def test_qr_security_service_generate_and_decode(init_database):
|
|
"""Verifica emisión criptográfica de tokens QR y resolución tolerante."""
|
|
student = _get_or_create_user("test_student_qr@unicaba.edu.ar", "Ana Gómez", "ALUMNO")
|
|
token = QRSecurityService.generate_qr_token(student, hours_valid=48)
|
|
assert token and token.count(".") == 2
|
|
|
|
# Decodificación de token institucional válido
|
|
resolved_user, status, reason = QRSecurityService.decode_and_resolve_user(token)
|
|
assert status == "AUTORIZADO"
|
|
assert resolved_user is not None
|
|
assert resolved_user.id == student.id
|
|
|
|
# Con prefijo institucional UNICABA:QR:
|
|
prefixed = f"UNICABA:QR:{token}"
|
|
resolved_pref, status_p, _ = QRSecurityService.decode_and_resolve_user(prefixed)
|
|
assert status_p == "AUTORIZADO"
|
|
assert resolved_pref.id == student.id
|
|
|
|
# Fallback por DNI
|
|
if student.document_number:
|
|
resolved_dni, status_d, _ = QRSecurityService.decode_and_resolve_user(f"DNI:{student.document_number}")
|
|
assert status_d == "AUTORIZADO"
|
|
assert resolved_dni.id == student.id
|
|
|
|
# Fallback por formato institucional UNICABA:USR:<id>:DNI:<doc>
|
|
res_fallback, status_fb, _ = QRSecurityService.decode_and_resolve_user(f"UNICABA:USR:{student.id}:DNI:{student.document_number}")
|
|
assert status_fb == "AUTORIZADO"
|
|
assert res_fallback.id == student.id
|
|
|
|
# Pistola óptica en teclado en español (sustituye : por Ñ)
|
|
res_gun, status_gun, _ = QRSecurityService.decode_and_resolve_user(f"UNICABAÑUSRÑ{student.id}ÑDNIÑ{student.document_number}")
|
|
assert status_gun == "AUTORIZADO"
|
|
assert res_gun.id == student.id
|
|
|
|
# Pistola óptica con DNI vacío
|
|
res_gun_nodni, status_gn, _ = QRSecurityService.decode_and_resolve_user(f"UNICABAÑUSRÑ{student.id}ÑDNIÑ")
|
|
assert status_gn == "AUTORIZADO"
|
|
assert res_gun_nodni.id == student.id
|
|
|
|
# Token corrupto o inválido
|
|
res_fake, status_f, reason_f = QRSecurityService.decode_and_resolve_user("token_invalido_corrupto")
|
|
assert status_f == "DENEGADO"
|
|
assert res_fake is None
|
|
|
|
|
|
def test_benefits_crud_api_flow(init_database):
|
|
"""Verifica operaciones CRUD del endpoint /api/v1/benefits con permisos de Bedelía."""
|
|
client = TestClient(app)
|
|
admin = _get_or_create_user("test_admin_benefits@unicaba.edu.ar", "Admin General", "ADMIN")
|
|
tokens = JWTService.generate_tokens(admin)
|
|
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
|
|
|
# 1. Crear nuevo beneficio (POST 201)
|
|
payload = {
|
|
"title": "15% en Librería Universitaria",
|
|
"partner_name": "Librería CABA",
|
|
"category": "LIBRERIA",
|
|
"discount_label": "15% OFF",
|
|
"description": "Descuento en apuntes y libros presentando credencial.",
|
|
"target_roles": "ALL",
|
|
"valid_from": str(date.today()),
|
|
"valid_until": str(date.today() + timedelta(days=60)),
|
|
"is_active": True,
|
|
"coupon_code": "LIBRO15"
|
|
}
|
|
create_resp = client.post("/api/v1/benefits", json=payload, headers=headers)
|
|
assert create_resp.status_code == 201
|
|
created_data = create_resp.json()
|
|
benefit_id = created_data["id"]
|
|
assert created_data["title"] == payload["title"]
|
|
assert created_data["discount_label"] == "15% OFF"
|
|
|
|
# 2. Listar beneficios (GET 200)
|
|
list_resp = client.get("/api/v1/benefits")
|
|
assert list_resp.status_code == 200
|
|
list_data = list_resp.json()
|
|
assert list_data["total"] >= 1
|
|
assert any(b["id"] == benefit_id for b in list_data["items"])
|
|
|
|
# 3. Consultar por ID (GET 200)
|
|
get_resp = client.get(f"/api/v1/benefits/{benefit_id}")
|
|
assert get_resp.status_code == 200
|
|
assert get_resp.json()["coupon_code"] == "LIBRO15"
|
|
|
|
# 4. Actualizar beneficio (PUT 200)
|
|
update_resp = client.put(
|
|
f"/api/v1/benefits/{benefit_id}",
|
|
json={"discount_label": "25% OFF", "title": "25% en Librería Universitaria"},
|
|
headers=headers
|
|
)
|
|
assert update_resp.status_code == 200
|
|
assert update_resp.json()["discount_label"] == "25% OFF"
|
|
|
|
# 5. Toggle de estado activo (PATCH 200)
|
|
toggle_resp = client.patch(f"/api/v1/benefits/{benefit_id}/toggle-status", headers=headers)
|
|
assert toggle_resp.status_code == 200
|
|
assert toggle_resp.json()["is_active"] is False
|
|
|
|
# 6. Eliminar (DELETE 204)
|
|
del_resp = client.delete(f"/api/v1/benefits/{benefit_id}", headers=headers)
|
|
assert del_resp.status_code == 204
|
|
|
|
# 7. Verificar que ya no existe (GET 404)
|
|
check_resp = client.get(f"/api/v1/benefits/{benefit_id}")
|
|
assert check_resp.status_code == 404
|
|
|
|
|
|
def test_benefits_role_access_control(init_database):
|
|
"""Verifica que un Alumno no pueda crear ni modificar convenios (403 Forbidden)."""
|
|
client = TestClient(app)
|
|
student = _get_or_create_user("test_student_forbidden@unicaba.edu.ar", "Alumno Prueba", "ALUMNO")
|
|
tokens = JWTService.generate_tokens(student)
|
|
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
|
|
|
payload = {
|
|
"title": "Intento Ilegal",
|
|
"partner_name": "Hack",
|
|
"discount_label": "99% OFF",
|
|
"valid_from": str(date.today())
|
|
}
|
|
resp = client.post("/api/v1/benefits", json=payload, headers=headers)
|
|
assert resp.status_code == 403
|
|
|
|
|
|
def test_reception_verify_qr_authorized_and_denied(init_database):
|
|
"""Verifica escaneo de código QR en Recepción con registro de log y cronograma."""
|
|
client = TestClient(app)
|
|
staff = _get_or_create_user("test_receptionist@unicaba.edu.ar", "Mesa Entrada", "BEDELIA")
|
|
tokens = JWTService.generate_tokens(staff)
|
|
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
|
|
|
student = _get_or_create_user("test_student_access@unicaba.edu.ar", "Lucas Martín", "ALUMNO")
|
|
qr_token = QRSecurityService.generate_qr_token(student)
|
|
|
|
# 1. Escaneo válido
|
|
scan_payload = {
|
|
"qr_token": qr_token,
|
|
"building_id": None,
|
|
"notes": "Ingreso por puerta principal"
|
|
}
|
|
resp = client.post("/api/v1/reception/verify-qr", json=scan_payload, headers=headers)
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["status"] == "AUTORIZADO"
|
|
assert data["user_name"] == "Lucas Martín"
|
|
assert "todays_classes" in data
|
|
|
|
# 2. Verificar que se persistió en AccessLogQR
|
|
log = AccessLogQR.query.filter_by(user_id=student.id).order_by(AccessLogQR.scanned_at.desc()).first()
|
|
assert log is not None
|
|
assert log.status == "AUTORIZADO"
|
|
assert log.scanned_by_user_id == staff.id
|
|
|
|
# 3. Escaneo de código corrupto
|
|
bad_resp = client.post("/api/v1/reception/verify-qr", json={"qr_token": "token_falso"}, headers=headers)
|
|
assert bad_resp.status_code == 200
|
|
bad_data = bad_resp.json()
|
|
assert bad_data["status"] == "DENEGADO"
|
|
|
|
|
|
def test_reception_my_qr_token_endpoint(init_database):
|
|
"""Verifica que el endpoint /api/v1/reception/my-qr-token entregue el token del usuario autenticado."""
|
|
client = TestClient(app)
|
|
student = _get_or_create_user("test_my_qr@unicaba.edu.ar", "Valeria Paz", "ALUMNO")
|
|
tokens = JWTService.generate_tokens(student)
|
|
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
|
|
|
resp = client.get("/api/v1/reception/my-qr-token", headers=headers)
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["status"] == "success"
|
|
assert "qr_token" in data
|
|
assert data["user_name"] == "Valeria Paz"
|
|
assert "renewal_interval_seconds" in data
|
|
assert data["renewal_interval_seconds"] == 3
|
|
assert data["grace_period_seconds"] == 6
|
|
|
|
# Verificar que el token expire y sea rechazado ante capturas de pantalla viejas (> 6s)
|
|
expired_token = QRSecurityService.generate_qr_token(student, valid_seconds=1)
|
|
import time
|
|
time.sleep(1.1)
|
|
exp_user, exp_status, exp_reason = QRSecurityService.decode_and_resolve_user(expired_token)
|
|
assert exp_status == "DENEGADO"
|
|
assert "expirado" in exp_reason.lower()
|
|
|
|
|
|
def test_security_qr_settings_configuration(init_database):
|
|
"""Verifica que el Administrador pueda configurar el tiempo de renovación desde Configuración Global."""
|
|
client = TestClient(app)
|
|
admin = _get_or_create_user("test_admin_qr_config@unicaba.edu.ar", "Admin General", "ADMIN")
|
|
admin_tokens = JWTService.generate_tokens(admin)
|
|
admin_headers = {"Authorization": f"Bearer {admin_tokens['access_token']}"}
|
|
|
|
# 1. Modificar parámetro a 5 segundos de rotación y 90 de gracia
|
|
resp = client.post(
|
|
"/api/v1/settings/security-qr",
|
|
json={"renewal_interval_seconds": 5, "grace_period_seconds": 90},
|
|
headers=admin_headers
|
|
)
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["status"] == "success"
|
|
assert data["security_qr"]["renewal_interval_seconds"] == 5
|
|
assert data["security_qr"]["grace_period_seconds"] == 90
|
|
|
|
# 2. Verificar que /settings/all reporte el nuevo valor
|
|
all_resp = client.get("/api/v1/settings/all", headers=admin_headers)
|
|
assert all_resp.status_code == 200
|
|
all_settings = all_resp.json()["settings"]
|
|
assert "security_qr" in all_settings
|
|
assert all_settings["security_qr"]["renewal_interval_seconds"] == 5
|
|
|
|
# 3. Verificar que /reception/my-qr-token refleje los 5 segundos
|
|
student = _get_or_create_user("test_student_renew@unicaba.edu.ar", "Martín Fierro", "ALUMNO")
|
|
student_tokens = JWTService.generate_tokens(student)
|
|
token_resp = client.get("/api/v1/reception/my-qr-token", headers={"Authorization": f"Bearer {student_tokens['access_token']}"})
|
|
assert token_resp.status_code == 200
|
|
assert token_resp.json()["renewal_interval_seconds"] == 5
|
|
|
|
# 4. Restaurar a 3 segundos (default)
|
|
client.post(
|
|
"/api/v1/settings/security-qr",
|
|
json={"renewal_interval_seconds": 3, "grace_period_seconds": 60},
|
|
headers=admin_headers
|
|
)
|
|
|
|
|
|
def test_live_context_benefit_search_integration(init_database):
|
|
"""Verifica que LiveContextService inyecte convenios reales ante consultas de cafetería o descuentos."""
|
|
benefit = InstitutionalBenefit(
|
|
title="20% en Cafetería Central",
|
|
partner_name="Café Martínez",
|
|
category="GASTRONOMIA",
|
|
discount_label="20% OFF",
|
|
description="Válido en desayunos y meriendas",
|
|
target_roles="ALL",
|
|
coupon_code="UNICABA20",
|
|
valid_from=date.today(),
|
|
is_active=True
|
|
)
|
|
db.session.add(benefit)
|
|
db.session.commit()
|
|
|
|
context_output = LiveContextService.get_system_snapshot(
|
|
role="alumno",
|
|
query="¿Qué descuentos hay en cafetería hoy?"
|
|
)
|
|
|
|
assert "CONVENIOS Y BENEFICIOS INSTITUCIONALES ACTIVOS" in context_output
|
|
assert "Café Martínez" in context_output
|
|
assert "20% OFF" in context_output
|
|
assert "UNICABA20" in context_output
|