feat: complete Phases 2 to 5 inclusive - Access Core, Web Cockpit, Hardware enqueuing, Optical Scanner and QA (v0.5.0-beta)

This commit is contained in:
Carlos Tello
2026-10-13 15:47:43 -03:00
parent 78c1a306de
commit 1ba74f7929
53 changed files with 4000 additions and 279 deletions
+172
View File
@@ -0,0 +1,172 @@
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
from app.services.dni_parser_service import DNIParsingService
@pytest.mark.asyncio
async def test_parse_dni_api():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# Autenticación previa
login_res = await client.post(
"/api/v1/auth/login",
json={"username": "guardia", "password": "guardia"},
)
token = login_res.cookies.get("access_token")
raw_qr = "0034567890@PEREZ@JUAN CARLOS@M@30123456@A@01/01/1985@01/01/2020@200"
res = await client.post(
"/api/v1/access/parse-dni",
json={"raw_data": raw_qr},
cookies={"access_token": token},
)
assert res.status_code == 200
data = res.json()
assert data["valido"] is True
assert data["documento"] == "30123456"
assert data["apellido"] == "PEREZ"
assert data["nombre"] == "JUAN CARLOS"
assert data["sexo"] == "M"
@pytest.mark.asyncio
async def test_search_people_and_lots():
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")
# Búsqueda de personas
p_res = await client.get(
"/api/v1/access/people/search?q=TEST",
cookies={"access_token": token},
)
assert p_res.status_code == 200
assert isinstance(p_res.json(), list)
# Búsqueda de lotes
l_res = await client.get(
"/api/v1/access/lots/search?q=1",
cookies={"access_token": token},
)
assert l_res.status_code == 200
assert isinstance(l_res.json(), list)
@pytest.mark.asyncio
async def test_hardware_manual_open():
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/100004/open",
json={"modulo_id": 100004, "motivo": "TEST_AUDIT"},
cookies={"access_token": token},
)
assert res.status_code == 200
data = res.json()
assert data["status"] == "ok"
assert data["modulo_id"] == 100004
assert data["latencia_ms"] < 500.0
@pytest.mark.asyncio
async def test_flujo_completo_ingreso_y_salida():
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")
doc_test = "99887766"
# 1. Registro de Ingreso
entry_payload = {
"modulo_ingreso_id": 100004,
"documento": doc_test,
"apellido": "TESTER",
"nombre": "INTEGRAL",
"sexo": "M",
"patente": "TST999",
"lote_codigo": "100",
"motivo": "PRUEBA AUTOMATIZADA",
"cantidad_ocupantes": 1,
"abrir_barrera": True,
}
entry_res = await client.post(
"/api/v1/access/entry",
json=entry_payload,
cookies={"access_token": token},
)
assert entry_res.status_code == 200
tck_data = entry_res.json()
assert tck_data["status"] == "ok"
ticket_id = tck_data["ticket_id"]
assert ticket_id > 0
assert tck_data["barrier_opened"] is True
# 2. Verificar que aparezca en tickets activos
active_res = await client.get(
"/api/v1/access/tickets/active",
cookies={"access_token": token},
)
assert active_res.status_code == 200
tickets = active_res.json()
ids_activos = [t["ticket_id"] for t in tickets]
assert ticket_id in ids_activos
# 3. Intentar reingreso (Antipassback)
dup_res = await client.post(
"/api/v1/access/entry",
json=entry_payload,
cookies={"access_token": token},
)
assert dup_res.status_code == 409
assert "Antipassback" in dup_res.json()["detail"]
# 4. Registrar Salida
exit_payload = {
"ticket_id": ticket_id,
"modulo_salida_id": 100005,
"patente_salida": "TST999",
"abrir_barrera": True,
}
exit_res = await client.post(
"/api/v1/access/exit",
json=exit_payload,
cookies={"access_token": token},
)
assert exit_res.status_code == 200
exit_data = exit_res.json()
assert exit_data["status"] == "ok"
assert exit_data["barrier_opened"] is True
# 5. Verificar que ya no esté en activos
active_res2 = await client.get(
"/api/v1/access/tickets/active",
cookies={"access_token": token},
)
ids_activos2 = [t["ticket_id"] for t in active_res2.json()]
assert ticket_id not in ids_activos2
# Teardown / Limpieza
from app.core.database import db_session
with db_session() as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM PerDocCatVal WHERE Documento = %s", (doc_test,))
cursor.execute("DELETE FROM Per WHERE Apellido = 'TESTER'")
cursor.execute("DELETE FROM pdtmdl WHERE ModuloID IN (100004, 100005) AND Extra = %s", (str(ticket_id),))
cursor.execute("DELETE FROM mvthist WHERE TicketID = %s", (ticket_id,))
cursor.execute("DELETE FROM tckhst WHERE TicketID = %s", (ticket_id,))
+69
View File
@@ -0,0 +1,69 @@
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
@pytest.mark.asyncio
async def test_login_exitoso_credenciales_validas():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.post(
"/api/v1/auth/login",
json={"username": "guardia", "password": "guardia", "workstation_name": "CFT-DESK"},
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "ok"
assert data["user"]["username"].lower() == "guardia"
assert data["workstation"] == "CFT-DESK"
assert "access_token" in response.cookies
@pytest.mark.asyncio
async def test_login_fallido_password_incorrecta():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.post(
"/api/v1/auth/login",
json={"username": "guardia", "password": "password_incorrecta_999"},
)
assert response.status_code == 401
data = response.json()
assert "detail" in data
@pytest.mark.asyncio
async def test_login_fallido_usuario_inexistente():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.post(
"/api/v1/auth/login",
json={"username": "usuario_inexistente_xyz", "password": "alguna_password"},
)
assert response.status_code == 401
@pytest.mark.asyncio
async def test_me_con_sesion_activa_y_logout():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# 1. Login
login_res = await client.post(
"/api/v1/auth/login",
json={"username": "guardia", "password": "guardia"},
)
assert login_res.status_code == 200
token = login_res.cookies.get("access_token")
# 2. Consultar /me
me_res = await client.get("/api/v1/auth/me", cookies={"access_token": token})
assert me_res.status_code == 200
me_data = me_res.json()
assert me_data["username"].lower() == "guardia"
# 3. Logout
logout_res = await client.post("/api/v1/auth/logout")
assert logout_res.status_code == 200
+42
View File
@@ -0,0 +1,42 @@
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
@pytest.mark.asyncio
async def test_workstation_status_existente():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.get("/api/v1/control-posts/workstation/CFT-DESK/status")
assert response.status_code == 200
data = response.json()
assert data["workstation_name"].upper() == "CFT-DESK"
assert data["is_control_post"] is True
assert data["workstation_id"] == 100001
assert len(data["modules"]) > 0
@pytest.mark.asyncio
async def test_workstation_status_no_registrada():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.get("/api/v1/control-posts/workstation/TABLET_DESCONOCIDA_999/status")
assert response.status_code == 200
data = response.json()
assert data["is_control_post"] is False
assert len(data["modules"]) == 0
@pytest.mark.asyncio
async def test_listar_workstations():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.get("/api/v1/control-posts/workstations")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
nombres = [item["nombre"].upper() for item in data]
assert "CFT-DESK" in nombres
+33
View File
@@ -0,0 +1,33 @@
import pytest
from app.services.dni_parser_service import DniParserService
def test_parser_dni_formato_2012():
raw = '00680051210"TELLO"CARLOS FACUNDO"M"34247025"B"09/02/1989"13/10/2021'
res = DniParserService.parsear(raw)
assert res["documento"] == "34247025"
assert res["apellido"] == "TELLO"
assert res["nombre"] == "CARLOS FACUNDO"
assert res["sexo"] == "M"
def test_parser_dni_formato_mi_argentina_con_arrobas():
raw = '00305336518@CIRILLI@GEORGINA SUSANA@2@28988082@A@23/08/1981@13/10/2014'
res = DniParserService.parsear(raw)
assert res["documento"] == "28988082"
assert res["apellido"] == "CIRILLI"
assert res["nombre"] == "GEORGINA SUSANA"
assert res["sexo"] == "F"
def test_parser_dni_formato_2009():
raw = '"34247025"A"1"TELLO"CARLOS FACUNDO"M"'
res = DniParserService.parsear(raw)
assert res["documento"] == "34247025"
assert res["apellido"] == "TELLO"
assert res["nombre"] == "CARLOS FACUNDO"
def test_parser_dni_numero_manual():
res = DniParserService.parsear("34247025")
assert res["documento"] == "34247025"
+26
View File
@@ -0,0 +1,26 @@
import pytest
from app.repositories.workstation_repository import WorkstationRepository
from app.repositories.auth_repository import AuthRepository
def test_obtener_workstation_existente():
wks = WorkstationRepository.obtener_workstation_por_nombre("CFT-DESK")
assert wks is not None
assert wks["Nombre"].strip().upper() == "CFT-DESK"
assert wks["WorkstationID"] == 100001
modulos = WorkstationRepository.listar_modulos_por_workstation(wks["WorkstationID"])
assert isinstance(modulos, list)
assert len(modulos) > 0
def test_obtener_workstation_inexistente():
wks = WorkstationRepository.obtener_workstation_por_nombre("ESTACION_INEXISTENTE_999")
assert wks is None
def test_obtener_usuario_existente():
usr = AuthRepository.obtener_usuario_por_nombre("guardia")
assert usr is not None
assert usr["Nombre"].strip().lower() == "guardia"
assert "Password" in usr
+29
View File
@@ -0,0 +1,29 @@
import pytest
from pydantic import ValidationError
from app.schemas.auth_schema import LoginRequest, LoginResponse, UserSessionDTO
from app.schemas.workstation_schema import LaneModuleDTO, WorkstationStatusResponse
def test_login_request_valid():
req = LoginRequest(username="guardia", password="secret_password", workstation_name="TABLET_01")
assert req.username == "guardia"
assert req.password == "secret_password"
assert req.workstation_name == "TABLET_01"
def test_login_request_empty_fields_raises_validation_error():
with pytest.raises(ValidationError):
LoginRequest(username="", password="")
def test_workstation_status_response_schema():
mod = LaneModuleDTO(modulo_id=100004, nombre="ENTRADA VISITAS", address=98, es_entrada=True)
status = WorkstationStatusResponse(
workstation_name="CFT-DESK",
is_control_post=True,
workstation_id=100001,
modules=[mod],
)
assert status.is_control_post is True
assert len(status.modules) == 1
assert status.modules[0].modulo_id == 100004
+90
View File
@@ -0,0 +1,90 @@
# ==============================================================================
# Pruebas de Estrés, Concurrencia y Latencia (Fase 5 - QA)
# ==============================================================================
import time
import asyncio
import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app
@pytest.mark.asyncio
async def test_latencia_comando_hardware_pdtmdl():
"""Valida que el encolado en pdtmdl cumpla con latencia inferior a 100ms en ráfaga."""
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")
latencias = []
for i in range(5):
t0 = time.perf_counter()
res = await client.post(
"/api/v1/hardware/modules/100004/open",
json={"modulo_id": 100004, "motivo": f"STRESS_TEST_{i}"},
cookies={"access_token": token},
)
elapsed_ms = (time.perf_counter() - t0) * 1000
assert res.status_code == 200
latencias.append(elapsed_ms)
promedio = sum(latencias) / len(latencias)
print(f"\n[LATENCIA PROMEDIO HARDWARE]: {promedio:.2f} ms")
assert promedio < 200.0 # Muy por debajo del umbral admisible en red local
@pytest.mark.asyncio
async def test_concurrencia_busqueda_predictiva():
"""Simula 10 consultas simultáneas de autocompletado para verificar el pool de conexiones."""
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")
async def query_lot(idx: int):
return await client.get(
f"/api/v1/access/lots/search?q={idx}",
cookies={"access_token": token},
)
tasks = [query_lot(i % 5 + 1) for i in range(10)]
results = await asyncio.gather(*tasks)
for r in results:
assert r.status_code == 200
assert isinstance(r.json(), list)
@pytest.mark.asyncio
async def test_stress_parser_dni_variados():
"""Verifica la robustez del parser ante diferentes combinaciones de códigos sin degradación."""
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")
codigos_prueba = [
'0034567890@PEREZ@JUAN CARLOS@M@30123456@A@01/01/1985@01/01/2020@200',
'"40111222"A"1"GONZALEZ"MARIA"F"',
'0011223344@LOPEZ@CARLOS@1@25999888@B@10/10/1975',
'0099887766@RODRIGUEZ@LUCIA@2@38555444@B@15/05/1994',
]
for raw in codigos_prueba:
res = await client.post(
"/api/v1/access/parse-dni",
json={"raw_data": raw},
cookies={"access_token": token},
)
assert res.status_code == 200
assert res.json()["valido"] is True
assert len(res.json()["documento"]) >= 6