267 lines
11 KiB
Python
267 lines
11 KiB
Python
# ==============================================================================
|
|
# Pruebas de Paridad Avanzada (Bloques 2 y 3 - OnEverControl)
|
|
# Preautorizados, Búsqueda de Personas, Patentes, Salida Masiva y Cierre Hardware
|
|
# ==============================================================================
|
|
import time
|
|
from datetime import datetime, timedelta
|
|
import pytest
|
|
from httpx import AsyncClient, ASGITransport
|
|
from app.main import app
|
|
from app.core.database import db_session
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hardware_barrier_forced_close():
|
|
"""Valida el comando de cierre forzado de barrera en hardware (tramas C0..C6)."""
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
login_res = await client.post(
|
|
"/api/v1/auth/login",
|
|
json={"username": "guardia", "password": "guardia"},
|
|
)
|
|
token = login_res.cookies.get("access_token")
|
|
|
|
res = await client.post(
|
|
"/api/v1/hardware/modules/100009/close",
|
|
json={"modulo_id": 100009, "motivo": "TEST_FORCED_CLOSE"},
|
|
cookies={"access_token": token},
|
|
)
|
|
assert res.status_code == 200
|
|
data = res.json()
|
|
assert data["status"] == "ok"
|
|
assert data["modulo_id"] == 100009
|
|
assert data["payload"] in ("C0", "C1", "C2", "C3", "C4", "C5", "C6")
|
|
|
|
# Verificar en pdtmdl
|
|
with db_session() as conn:
|
|
cursor = conn.cursor(as_dict=True)
|
|
cursor.execute("SELECT TOP 1 * FROM pdtmdl WHERE ModuloID IN (100009, 100002) ORDER BY PdtMdlID DESC")
|
|
row = cursor.fetchone()
|
|
assert row is not None
|
|
assert data["payload"] in row["Comando"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_preauthorizations_flow_and_atomic_consumption():
|
|
"""Valida la consulta de preautorizaciones y su consumo atómico al registrar ingreso."""
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
login_res = await client.post(
|
|
"/api/v1/auth/login",
|
|
json={"username": "guardia", "password": "guardia"},
|
|
)
|
|
token = login_res.cookies.get("access_token")
|
|
|
|
suffix = str(int(time.time()))[-5:]
|
|
doc_pre = f"77{suffix}"
|
|
pre_id = 9988000 + int(suffix)
|
|
|
|
# 1. Crear preautorización en tabla pre
|
|
f_ini = (datetime.now() - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
|
|
f_fin = (datetime.now() + timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
with db_session() as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute(
|
|
"""
|
|
INSERT INTO pre (PreautorizadoID, LoteID, Entidad, Apellido, Nombre, Motivo, FechaInicio, FechaFin)
|
|
VALUES (%s, 100000, 'TEST CORP', 'PRETEST', 'GABRIEL', %s, %s, %s)
|
|
""",
|
|
(pre_id, doc_pre, f_ini, f_fin),
|
|
)
|
|
|
|
try:
|
|
# 2. Consultar por API
|
|
pre_res = await client.get(
|
|
f"/api/v1/access/preauthorizations?q={doc_pre}",
|
|
cookies={"access_token": token},
|
|
)
|
|
assert pre_res.status_code == 200
|
|
lista = pre_res.json()
|
|
assert len(lista) >= 1
|
|
item = next((p for p in lista if p["id"] == pre_id), None)
|
|
assert item is not None
|
|
assert item["apellido"] == "PRETEST"
|
|
assert item["documento"] == doc_pre
|
|
|
|
# 3. Registrar ingreso proveyendo preautorizado_id
|
|
entry_res = await client.post(
|
|
"/api/v1/access/entry",
|
|
json={
|
|
"modulo_ingreso_id": 100009,
|
|
"documento": doc_pre,
|
|
"apellido": "PRETEST",
|
|
"nombre": "GABRIEL",
|
|
"sexo": "M",
|
|
"patente": "PRE111",
|
|
"lote_codigo": "100",
|
|
"tipo_ingreso": "CONDUCTOR",
|
|
"preautorizado_id": pre_id,
|
|
"abrir_barrera": False,
|
|
},
|
|
cookies={"access_token": token},
|
|
)
|
|
assert entry_res.status_code == 200
|
|
tck_id = entry_res.json()["ticket_id"]
|
|
|
|
# 4. Verificar que la preautorización fue consumida (eliminada de tabla pre)
|
|
with db_session() as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT 1 FROM pre WHERE PreautorizadoID = %s", (pre_id,))
|
|
assert cursor.fetchone() is None
|
|
|
|
# Limpiar ticket de prueba
|
|
await client.post(
|
|
"/api/v1/access/exit",
|
|
json={
|
|
"ticket_id": tck_id,
|
|
"modulo_salida_id": 100010,
|
|
"patente_salida": "PRE111",
|
|
"tipo_salida": "CONDUCTOR",
|
|
"abrir_barrera": False,
|
|
},
|
|
cookies={"access_token": token},
|
|
)
|
|
|
|
finally:
|
|
with db_session() as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute("DELETE FROM pre WHERE PreautorizadoID = %s", (pre_id,))
|
|
cursor.execute("DELETE FROM PerDocCatVal WHERE Documento = %s", (doc_pre,))
|
|
cursor.execute("DELETE FROM Per WHERE Apellido = 'PRETEST'")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_people_and_vehicles_advanced_search_apis():
|
|
"""Valida los endpoints de búsqueda predictiva / avanzada de personas y vehículos."""
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
login_res = await client.post(
|
|
"/api/v1/auth/login",
|
|
json={"username": "guardia", "password": "guardia"},
|
|
)
|
|
token = login_res.cookies.get("access_token")
|
|
|
|
# 1. Búsqueda avanzada de personas
|
|
p_res = await client.get(
|
|
"/api/v1/access/people/advanced-search?q=a&limite=10",
|
|
cookies={"access_token": token},
|
|
)
|
|
assert p_res.status_code == 200
|
|
personas = p_res.json()
|
|
assert isinstance(personas, list)
|
|
|
|
# 2. Búsqueda de vehículos en Entrada (Padrón)
|
|
v_res = await client.get(
|
|
"/api/v1/access/vehicles/search?es_salida=false&limite=10",
|
|
cookies={"access_token": token},
|
|
)
|
|
assert v_res.status_code == 200
|
|
vehiculos = v_res.json()
|
|
assert isinstance(vehiculos, list)
|
|
|
|
# 3. Búsqueda de vehículos en Salida (Predio)
|
|
v_sal_res = await client.get(
|
|
"/api/v1/access/vehicles/search?es_salida=true&limite=10",
|
|
cookies={"access_token": token},
|
|
)
|
|
assert v_sal_res.status_code == 200
|
|
vehiculos_sal = v_sal_res.json()
|
|
assert isinstance(vehiculos_sal, list)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mass_exit_transactional():
|
|
"""Valida el proceso atómico de salida masiva de múltiples tickets."""
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
login_res = await client.post(
|
|
"/api/v1/auth/login",
|
|
json={"username": "guardia", "password": "guardia"},
|
|
)
|
|
token = login_res.cookies.get("access_token")
|
|
|
|
suffix = str(int(time.time()))[-4:]
|
|
doc1 = f"66{suffix}1"
|
|
doc2 = f"66{suffix}2"
|
|
|
|
# 1. Registrar 2 ingresos
|
|
res1 = await client.post(
|
|
"/api/v1/access/entry",
|
|
json={
|
|
"modulo_ingreso_id": 100009,
|
|
"documento": doc1,
|
|
"apellido": "MASIVA_UNO",
|
|
"nombre": "JUAN",
|
|
"lote_codigo": "100",
|
|
"tipo_ingreso": "PEATON",
|
|
"abrir_barrera": False,
|
|
},
|
|
cookies={"access_token": token},
|
|
)
|
|
assert res1.status_code == 200
|
|
tck1 = res1.json()["ticket_id"]
|
|
|
|
res2 = await client.post(
|
|
"/api/v1/access/entry",
|
|
json={
|
|
"modulo_ingreso_id": 100009,
|
|
"documento": doc2,
|
|
"apellido": "MASIVA_DOS",
|
|
"nombre": "PEDRO",
|
|
"lote_codigo": "100",
|
|
"tipo_ingreso": "CONDUCTOR",
|
|
"patente": f"MAS{suffix}",
|
|
"abrir_barrera": False,
|
|
},
|
|
cookies={"access_token": token},
|
|
)
|
|
assert res2.status_code == 200
|
|
tck2 = res2.json()["ticket_id"]
|
|
|
|
try:
|
|
# 2. Ejecutar Salida Masiva
|
|
mass_res = await client.post(
|
|
"/api/v1/access/mass-exit",
|
|
json={
|
|
"ticket_ids": [tck1, tck2],
|
|
"modulo_salida_id": 100010,
|
|
"motivo": "Toque de queda / Cierre de jornada",
|
|
"observaciones": "Prueba automatizada de egreso masivo",
|
|
},
|
|
cookies={"access_token": token},
|
|
)
|
|
assert mass_res.status_code == 200
|
|
data_mass = mass_res.json()
|
|
assert data_mass["status"] == "ok"
|
|
assert data_mass["egresados_count"] == 2
|
|
salida_id = data_mass["salida_masiva_id"]
|
|
assert salida_id > 0
|
|
|
|
# 3. Validar que no sigan en tck y estén en tckhst
|
|
with db_session() as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute("SELECT 1 FROM tck WHERE TicketID IN (%s, %s)", (tck1, tck2))
|
|
assert cursor.fetchone() is None
|
|
|
|
cursor.execute("SELECT COUNT(*) FROM tckhst WHERE TicketID IN (%s, %s)", (tck1, tck2))
|
|
assert cursor.fetchone()[0] == 2
|
|
|
|
# Validar tabla salida_masiva
|
|
cursor.execute("SELECT CantidadPersonas FROM dbo.salida_masiva WHERE SalidaMasivaID = %s", (salida_id,))
|
|
row_sm = cursor.fetchone()
|
|
assert row_sm is not None
|
|
assert row_sm[0] == 2
|
|
|
|
finally:
|
|
with db_session() as conn:
|
|
cursor = conn.cursor()
|
|
cursor.execute("DELETE FROM PerDocCatVal WHERE Documento IN (%s, %s)", (doc1, doc2))
|
|
cursor.execute("DELETE FROM Per WHERE Apellido IN ('MASIVA_UNO', 'MASIVA_DOS')")
|
|
cursor.execute("DELETE FROM mvthist WHERE TicketID IN (%s, %s)", (tck1, tck2))
|
|
cursor.execute("DELETE FROM tckhst WHERE TicketID IN (%s, %s)", (tck1, tck2))
|
|
if 'salida_id' in locals() and salida_id > 0:
|
|
cursor.execute("DELETE FROM dbo.salida_masiva_detalle WHERE SalidaMasivaID = %s", (salida_id,))
|
|
cursor.execute("DELETE FROM dbo.salida_masiva WHERE SalidaMasivaID = %s", (salida_id,))
|
|
|