- Agregar 46 tests de integración (auth, multi-tenancy, tickets) - Crear estructura organizada tests/integration/ y tests/unit/ - Implementar fixtures completas para testing con BD separada - Agregar conftest_integration.py con setup async - Mover scripts PowerShell de testing a tests/scripts/ - Actualizar pytest.ini con markers y configuración - Crear run_tests.sh script ejecutable para testing - Documentación completa en README_TESTS.md - Fix: Remover opciones obsoletas de TypeScript (importsNotUsedAsValues) Tests implementados: - Authentication: 15 tests (login, refresh, permisos, seguridad) - Multi-tenancy: 13 tests (aislamiento, validaciones, seguridad B2B) - Tickets: 18 tests (CRUD, filtros, permisos por rol) - Unit: 10 tests básicos - Verificación: 8 tests de setup Base de datos de testing: servicemanager_test (separada de producción) Cobertura estimada: ~40% (desde 5%) Próximos pasos: Agregar tests de SLA, attachments, auditoría
261 lines
6.7 KiB
Markdown
261 lines
6.7 KiB
Markdown
# Tests de Integración - ServiceManagerWeb
|
|
|
|
Suite completa de tests de integración para validar funcionalidad crítica del sistema.
|
|
|
|
## 📋 Estructura de Tests
|
|
|
|
```
|
|
tests/
|
|
├── conftest.py # Fixtures básicas (original)
|
|
├── conftest_integration.py # Fixtures para tests de integración
|
|
├── test_auth_integration.py # Tests de autenticación
|
|
├── test_multitenant_integration.py # Tests de aislamiento multi-tenant
|
|
├── test_tickets_integration.py # Tests CRUD de tickets
|
|
├── test_basic.py # Tests unitarios básicos (original)
|
|
└── test_health.py # Tests de health checks (original)
|
|
```
|
|
|
|
## 🚀 Ejecutar Tests
|
|
|
|
### Prerequisitos
|
|
|
|
1. **Servicios Docker corriendo:**
|
|
```bash
|
|
docker-compose up -d postgres redis
|
|
```
|
|
|
|
2. **Base de datos de testing:**
|
|
```bash
|
|
# Se crea automáticamente, pero si necesitas crearla manualmente:
|
|
docker-compose exec postgres psql -U servicemanager -c "CREATE DATABASE servicemanager_test;"
|
|
```
|
|
|
|
### Ejecución Rápida
|
|
|
|
```bash
|
|
# Dar permisos de ejecución al script
|
|
chmod +x backend/run_tests.sh
|
|
|
|
# Ejecutar todos los tests
|
|
cd backend
|
|
./run_tests.sh all
|
|
|
|
# Ejecutar solo tests de autenticación
|
|
./run_tests.sh auth
|
|
|
|
# Ejecutar solo tests de multi-tenancy
|
|
./run_tests.sh multitenant
|
|
|
|
# Ejecutar solo tests de tickets
|
|
./run_tests.sh tickets
|
|
|
|
# Ejecutar con reporte de cobertura
|
|
./run_tests.sh coverage
|
|
```
|
|
|
|
### Ejecución Manual con pytest
|
|
|
|
```bash
|
|
cd backend
|
|
|
|
# Todos los tests de integración
|
|
pytest -v -m integration tests/
|
|
|
|
# Tests específicos por archivo
|
|
pytest -v tests/test_auth_integration.py
|
|
pytest -v tests/test_multitenant_integration.py
|
|
pytest -v tests/test_tickets_integration.py
|
|
|
|
# Con cobertura
|
|
pytest --cov=app --cov-report=html tests/test_*_integration.py
|
|
|
|
# Tests específicos por clase
|
|
pytest -v tests/test_auth_integration.py::TestAuthentication
|
|
|
|
# Test individual
|
|
pytest -v tests/test_auth_integration.py::TestAuthentication::test_login_success
|
|
```
|
|
|
|
## 🧪 Cobertura de Tests
|
|
|
|
### Tests de Autenticación (`test_auth_integration.py`)
|
|
- ✅ Login exitoso con credenciales válidas
|
|
- ✅ Login fallido (contraseña incorrecta, tenant inválido, usuario inactivo)
|
|
- ✅ Refresh tokens (generación y revocación)
|
|
- ✅ Logout y invalidación de tokens
|
|
- ✅ Autorización por roles (ADMIN, AGENT, CLIENT)
|
|
- ✅ Protección de endpoints
|
|
- ✅ Seguridad de passwords (hashing, no exposición)
|
|
|
|
**Total: 15 tests**
|
|
|
|
### Tests de Multi-Tenancy (`test_multitenant_integration.py`)
|
|
- ✅ Aislamiento de datos entre tenants
|
|
- ✅ Usuario no puede ver tickets de otro tenant
|
|
- ✅ Usuario no puede acceder por ID directo a datos de otro tenant
|
|
- ✅ Usuario no puede modificar datos de otro tenant
|
|
- ✅ Validación de X-Tenant-ID header
|
|
- ✅ Validación de UUIDs
|
|
- ✅ Permisos administrativos de tenants
|
|
- ✅ Prevención de suplantación de tenant
|
|
|
|
**Total: 13 tests** (CRÍTICOS para seguridad B2B)
|
|
|
|
### Tests de Tickets (`test_tickets_integration.py`)
|
|
- ✅ Crear ticket con validaciones
|
|
- ✅ Listar tickets (vacío y con datos)
|
|
- ✅ Obtener ticket por ID
|
|
- ✅ Actualizar ticket (status, prioridad, asignación)
|
|
- ✅ Filtros (por status, prioridad)
|
|
- ✅ Permisos por rol:
|
|
- Cliente solo ve sus tickets
|
|
- Agente ve todos los tickets del tenant
|
|
- Admin tiene acceso completo
|
|
|
|
**Total: 18 tests**
|
|
|
|
## 📊 Métricas Objetivo
|
|
|
|
```
|
|
Cobertura actual: ~5% ❌
|
|
Cobertura con estos tests: ~40% 🟡
|
|
Cobertura objetivo: >70% ⭐
|
|
|
|
Tests totales: 46 tests de integración
|
|
Tiempo ejecución: ~15-30 segundos
|
|
```
|
|
|
|
## 🔧 Configuración
|
|
|
|
### Variables de Entorno para Testing
|
|
|
|
El archivo `conftest_integration.py` usa:
|
|
```python
|
|
TEST_DATABASE_URL = "postgresql+asyncpg://servicemanager:servicemanager123@localhost:5432/servicemanager_test"
|
|
```
|
|
|
|
Para personalizar:
|
|
```bash
|
|
export TEST_DATABASE_URL="postgresql+asyncpg://user:pass@host:port/db_test"
|
|
```
|
|
|
|
### Markers de pytest
|
|
|
|
Usa markers para ejecutar subconjuntos:
|
|
```bash
|
|
# Solo tests de integración
|
|
pytest -m integration
|
|
|
|
# Solo tests que usan BD
|
|
pytest -m db
|
|
|
|
# Solo tests de auth
|
|
pytest -m auth
|
|
|
|
# Excluir tests lentos
|
|
pytest -m "not slow"
|
|
```
|
|
|
|
## 🐛 Troubleshooting
|
|
|
|
### Error: "Database not found"
|
|
```bash
|
|
docker-compose exec postgres psql -U servicemanager -c "CREATE DATABASE servicemanager_test;"
|
|
```
|
|
|
|
### Error: "Connection refused"
|
|
```bash
|
|
# Verificar que servicios estén corriendo
|
|
docker-compose ps
|
|
|
|
# Reiniciar servicios
|
|
docker-compose restart postgres redis
|
|
```
|
|
|
|
### Tests lentos
|
|
```bash
|
|
# Ver tests más lentos
|
|
pytest --durations=10
|
|
|
|
# Ejecutar en paralelo (requiere pytest-xdist)
|
|
pip install pytest-xdist
|
|
pytest -n auto
|
|
```
|
|
|
|
### Limpiar base de datos de testing
|
|
```bash
|
|
./run_tests.sh clean
|
|
```
|
|
|
|
## 📝 Agregar Nuevos Tests
|
|
|
|
### Template para nuevo test
|
|
|
|
```python
|
|
import pytest
|
|
from httpx import AsyncClient
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
pytest_plugins = ['tests.conftest_integration']
|
|
|
|
@pytest.mark.integration
|
|
@pytest.mark.db
|
|
class TestNuevaFuncionalidad:
|
|
"""Descripción de la funcionalidad."""
|
|
|
|
async def test_caso_exitoso(
|
|
self,
|
|
client: AsyncClient,
|
|
test_tenant: Tenant,
|
|
auth_headers_admin: dict
|
|
):
|
|
"""Test del caso exitoso."""
|
|
response = await client.get(
|
|
"/v1/endpoint/",
|
|
headers={
|
|
**auth_headers_admin,
|
|
"X-Tenant-ID": str(test_tenant.id)
|
|
}
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
# Más assertions...
|
|
```
|
|
|
|
## 🎯 Próximos Pasos
|
|
|
|
### Tests Pendientes (Prioridad Media)
|
|
- [ ] Tests de SLA (cálculos, violaciones)
|
|
- [ ] Tests de comentarios en tickets
|
|
- [ ] Tests de attachments (uploads)
|
|
- [ ] Tests de auditoría
|
|
- [ ] Tests de notificaciones email
|
|
- [ ] Tests de categorías y sistemas
|
|
- [ ] Tests de usuarios CRUD
|
|
|
|
### Mejoras de Testing (Prioridad Baja)
|
|
- [ ] Tests E2E con Playwright
|
|
- [ ] Tests de carga con Locust
|
|
- [ ] Tests de seguridad con OWASP ZAP
|
|
- [ ] Mutation testing con mutmut
|
|
- [ ] Property-based testing con Hypothesis
|
|
|
|
## 📚 Referencias
|
|
|
|
- [pytest documentation](https://docs.pytest.org/)
|
|
- [FastAPI testing](https://fastapi.tiangolo.com/tutorial/testing/)
|
|
- [pytest-asyncio](https://pytest-asyncio.readthedocs.io/)
|
|
- [SQLAlchemy testing](https://docs.sqlalchemy.org/en/20/orm/session_transaction.html#joining-a-session-into-an-external-transaction-such-as-for-test-suites)
|
|
|
|
## ✅ Checklist Pre-Producción
|
|
|
|
Antes de desplegar a producción, verificar:
|
|
|
|
- [ ] Todos los tests de integración pasan
|
|
- [ ] Cobertura de tests >70%
|
|
- [ ] Tests de multi-tenancy 100% exitosos
|
|
- [ ] Tests de autenticación 100% exitosos
|
|
- [ ] No hay credenciales hardcodeadas en tests
|
|
- [ ] Base de datos de testing separada de producción
|
|
- [ ] CI/CD configurado para ejecutar tests automáticamente
|