template-saas/orchestration/_archive/planes/PLAN-SPRINT-1-TESTS.md
Adrian Flores Cortes 1c847fbe04
Some checks are pending
CI / Backend CI (push) Waiting to run
CI / Frontend CI (push) Waiting to run
CI / Security Scan (push) Waiting to run
CI / CI Summary (push) Blocked by required conditions
[ESTANDAR-ORCHESTRATION] refactor: Consolidate to standard structure
- Rename _archivo to _archive (standard convention)
- Move analisis/, planes/ to _archive/
- Archive extra root files
- Update _MAP.md with standardized structure

Standard: SIMCO-ESTANDAR-ORCHESTRATION v1.0.0
Level: PROVIDER (L1A)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 14:38:23 -06:00

374 lines
11 KiB
Markdown

# PLAN SPRINT 1 - Test Coverage
**Proyecto:** template-saas
**Sprint:** 1
**Objetivo:** Subir cobertura de tests de 62.56% a 80%
**Fecha Inicio:** 2026-01-10
**SP Total:** 8
---
## RESUMEN EJECUTIVO
### Estado Actual
- **Cobertura actual:** 62.56%
- **Tests actuales:** 387 tests en 24 suites
- **Objetivo:** 80% cobertura
### Gap a Cerrar
- **Delta requerido:** +17.44% de cobertura
- **Tests estimados adicionales:** ~80-100 tests nuevos
---
## TAREAS DEL SPRINT
### TST-001: Tests Auth Module Adicionales
**Agente:** Backend-Agent
**SP:** 2
**Dependencia:** Ninguna
**Paralelo con:** TST-002
#### Archivos a Leer
```yaml
archivos:
- apps/backend/src/modules/auth/services/auth.service.ts
- apps/backend/src/modules/auth/services/token.service.ts
- apps/backend/src/modules/auth/services/oauth.service.ts
- apps/backend/src/modules/auth/__tests__/auth.service.spec.ts
```
#### Entregables
```yaml
entregables:
- apps/backend/src/modules/auth/__tests__/token.service.spec.ts
- apps/backend/src/modules/auth/__tests__/oauth.service.spec.ts
- apps/backend/src/modules/auth/__tests__/mfa.service.spec.ts
```
#### Casos de Test a Implementar
**token.service.spec.ts:**
- [ ] generateAccessToken - genera token valido
- [ ] generateAccessToken - incluye tenant_id en claims
- [ ] generateRefreshToken - genera token de refresh
- [ ] validateToken - valida token correcto
- [ ] validateToken - rechaza token expirado
- [ ] validateToken - rechaza token malformado
- [ ] revokeToken - revoca token existente
- [ ] revokeAllUserTokens - revoca todos los tokens de usuario
**oauth.service.spec.ts:**
- [ ] getOAuthUrl - genera URL para Google
- [ ] getOAuthUrl - genera URL para GitHub
- [ ] getOAuthUrl - genera URL para Microsoft
- [ ] handleCallback - procesa callback exitoso
- [ ] handleCallback - maneja error de proveedor
- [ ] linkAccount - vincula cuenta OAuth a usuario existente
- [ ] unlinkAccount - desvincula cuenta OAuth
**mfa.service.spec.ts:**
- [ ] generateSecret - genera secreto TOTP
- [ ] verifyCode - valida codigo correcto
- [ ] verifyCode - rechaza codigo incorrecto
- [ ] enableMfa - activa MFA para usuario
- [ ] disableMfa - desactiva MFA
- [ ] generateBackupCodes - genera codigos de respaldo
#### Criterios de Aceptacion
- [ ] Todos los tests pasan
- [ ] Cobertura del modulo auth >= 85%
- [ ] No hay tests flaky
- [ ] Mocks correctamente implementados
---
### TST-002: Tests Billing Edge Cases
**Agente:** Backend-Agent
**SP:** 2
**Dependencia:** Ninguna
**Paralelo con:** TST-001
#### Archivos a Leer
```yaml
archivos:
- apps/backend/src/modules/billing/services/billing.service.ts
- apps/backend/src/modules/billing/services/subscription.service.ts
- apps/backend/src/modules/billing/services/stripe.service.ts
- apps/backend/src/modules/billing/__tests__/
```
#### Entregables
```yaml
entregables:
- apps/backend/src/modules/billing/__tests__/subscription.service.spec.ts (ampliar)
- apps/backend/src/modules/billing/__tests__/stripe-webhooks.spec.ts
- apps/backend/src/modules/billing/__tests__/invoice.service.spec.ts
```
#### Casos de Test a Implementar
**subscription.service.spec.ts (adicionales):**
- [ ] createSubscription - con periodo trial
- [ ] createSubscription - sin metodo de pago (trial only)
- [ ] upgradeSubscription - prorratea correctamente
- [ ] downgradeSubscription - aplica al siguiente ciclo
- [ ] cancelSubscription - cancela inmediatamente
- [ ] cancelSubscription - cancela al fin de periodo
- [ ] reactivateSubscription - reactiva suscripcion cancelada
- [ ] handlePaymentFailure - suspende tras N intentos
**stripe-webhooks.spec.ts:**
- [ ] handleWebhook - valida firma correcta
- [ ] handleWebhook - rechaza firma invalida
- [ ] customer.subscription.updated - actualiza BD
- [ ] customer.subscription.deleted - marca cancelado
- [ ] invoice.paid - registra pago
- [ ] invoice.payment_failed - notifica admin
- [ ] checkout.session.completed - activa tenant
**invoice.service.spec.ts:**
- [ ] generateInvoice - crea invoice con items
- [ ] markAsPaid - actualiza estado
- [ ] sendInvoiceEmail - envia por email
- [ ] getInvoicePdf - genera PDF
#### Criterios de Aceptacion
- [ ] Todos los tests pasan
- [ ] Cobertura del modulo billing >= 85%
- [ ] Webhooks testeados con payloads reales
- [ ] Edge cases de suscripcion cubiertos
---
### TST-003: Tests Notifications Queue
**Agente:** Backend-Agent
**SP:** 2
**Dependencia:** Ninguna
**Paralelo con:** TST-004
#### Archivos a Leer
```yaml
archivos:
- apps/backend/src/modules/notifications/services/notification-queue.service.ts
- apps/backend/src/modules/notifications/services/push-notification.service.ts
- apps/backend/src/modules/notifications/gateways/notifications.gateway.ts
- apps/backend/src/modules/notifications/__tests__/
```
#### Entregables
```yaml
entregables:
- apps/backend/src/modules/notifications/__tests__/notification-queue.service.spec.ts
- apps/backend/src/modules/notifications/__tests__/notifications.gateway.spec.ts
- apps/backend/src/modules/notifications/__tests__/push-notification.service.spec.ts (ampliar)
```
#### Casos de Test a Implementar
**notification-queue.service.spec.ts:**
- [ ] enqueue - agrega a la cola correctamente
- [ ] enqueue - respeta prioridades
- [ ] process - procesa item de cola
- [ ] process - reintenta en fallo
- [ ] process - marca como fallido tras max retries
- [ ] getQueueStats - retorna estadisticas
- [ ] clearOldItems - limpia items procesados
**notifications.gateway.spec.ts:**
- [ ] handleConnection - registra cliente
- [ ] handleDisconnect - remueve cliente
- [ ] sendToUser - envia a usuario especifico
- [ ] sendToTenant - broadcast a tenant
- [ ] sendToRoom - envia a room especifica
- [ ] handleAcknowledgement - marca como leida
**push-notification.service.spec.ts (adicionales):**
- [ ] sendPush - envia a dispositivo valido
- [ ] sendPush - maneja dispositivo invalido
- [ ] sendBulk - envia a multiples dispositivos
- [ ] registerDevice - registra nuevo dispositivo
- [ ] unregisterDevice - remueve dispositivo
#### Criterios de Aceptacion
- [ ] Todos los tests pasan
- [ ] Cola BullMQ mockeada correctamente
- [ ] WebSocket gateway testeado
- [ ] Push notifications con VAPID testeadas
---
### TST-004: Tests Storage Upload/Download
**Agente:** Backend-Agent
**SP:** 2
**Dependencia:** Ninguna
**Paralelo con:** TST-003
#### Archivos a Leer
```yaml
archivos:
- apps/backend/src/modules/storage/services/storage.service.ts
- apps/backend/src/modules/storage/services/s3.service.ts
- apps/backend/src/modules/storage/__tests__/
```
#### Entregables
```yaml
entregables:
- apps/backend/src/modules/storage/__tests__/storage.service.spec.ts (ampliar)
- apps/backend/src/modules/storage/__tests__/s3.service.spec.ts
- apps/backend/src/modules/storage/__tests__/storage.controller.spec.ts
```
#### Casos de Test a Implementar
**storage.service.spec.ts (adicionales):**
- [ ] uploadFile - sube archivo correctamente
- [ ] uploadFile - valida tipo de archivo
- [ ] uploadFile - valida tamano maximo
- [ ] uploadFile - respeta cuota de tenant
- [ ] downloadFile - descarga archivo existente
- [ ] downloadFile - error si no existe
- [ ] deleteFile - elimina archivo
- [ ] deleteFile - actualiza cuota usada
- [ ] getSignedUrl - genera URL firmada
- [ ] getSignedUrl - expira correctamente
**s3.service.spec.ts:**
- [ ] putObject - sube a S3
- [ ] getObject - descarga de S3
- [ ] deleteObject - elimina de S3
- [ ] getPresignedUrl - genera URL para upload
- [ ] getPresignedDownloadUrl - genera URL para download
- [ ] copyObject - copia entre buckets
- [ ] listObjects - lista objetos con prefijo
**storage.controller.spec.ts:**
- [ ] POST /upload - inicia upload
- [ ] POST /complete - completa upload multipart
- [ ] GET /:id - descarga archivo
- [ ] DELETE /:id - elimina archivo
- [ ] GET /usage - retorna uso de cuota
#### Criterios de Aceptacion
- [ ] Todos los tests pasan
- [ ] S3 mockeado con aws-sdk-mock
- [ ] Validaciones de archivo testeadas
- [ ] Cuotas de storage validadas
---
## EJECUCION DEL SPRINT
### Orden de Ejecucion
```
Dia 1-2:
├── TST-001 (Backend-Agent #1) ──► Paralelo
└── TST-002 (Backend-Agent #2) ──► Paralelo
Dia 3-4:
├── TST-003 (Backend-Agent #1) ──► Paralelo
└── TST-004 (Backend-Agent #2) ──► Paralelo
Dia 5:
└── Validacion y merge (QA-Agent)
```
### Comandos de Validacion
```bash
# Ejecutar todos los tests
cd apps/backend && npm run test
# Coverage report
cd apps/backend && npm run test:cov
# Tests especificos por modulo
cd apps/backend && npm run test -- --testPathPattern=auth
cd apps/backend && npm run test -- --testPathPattern=billing
cd apps/backend && npm run test -- --testPathPattern=notifications
cd apps/backend && npm run test -- --testPathPattern=storage
```
### Metricas de Exito
| Metrica | Antes | Objetivo |
|---------|-------|----------|
| Total tests | 387 | ~470 |
| Test suites | 24 | ~30 |
| Coverage | 62.56% | 80% |
| Auth coverage | ~70% | 85% |
| Billing coverage | ~65% | 85% |
| Notifications coverage | ~60% | 85% |
| Storage coverage | ~55% | 85% |
---
## ACTUALIZACIONES POST-SPRINT
### Inventarios a Actualizar
- [ ] `orchestration/inventarios/BACKEND_INVENTORY.yml` - tests count
- [ ] `orchestration/PROJECT-STATUS.md` - coverage metrics
- [ ] `orchestration/PROXIMA-ACCION.md` - siguiente sprint
### Documentacion a Actualizar
- [ ] `README.md` - badge de coverage
- [ ] `docs/02-devops/TESTING-GUIDE.md` - nuevos patrones
---
## REFERENCIAS
- `orchestration/analisis/ANALISIS-MAESTRO-TEMPLATE-SAAS.md`
- `apps/backend/jest.config.js`
- `apps/backend/package.json` (scripts de test)
---
**Creado:** 2026-01-10
**Sprint:** 1 de 5
**Estado:** COMPLETADO
---
## REPORTE DE EJECUCION
**Fecha Finalizacion:** 2026-01-10
### Resultados
| Metrica | Objetivo | Resultado |
|---------|----------|-----------|
| Cobertura Total | 80% | 76.37% |
| Tests Nuevos | ~80 | +323 |
| Tests Totales | ~470 | 710 |
| Test Suites | ~30 | 31 |
### Cobertura por Modulo (Sprint 1)
| Modulo | Objetivo | Resultado |
|--------|----------|-----------|
| auth.service.ts | 85% | 100% |
| billing.service.ts | 85% | 100% |
| stripe.service.ts | 85% | 97.02% |
| notification-queue.service.ts | 85% | 98.52% |
| storage.service.ts | 85% | 95.9% |
| s3.provider.ts | 85% | 100% |
### Observaciones
1. **Meta casi alcanzada:** Cobertura de 76.37% vs objetivo de 80% (gap: 3.63%)
2. **Servicios principales cubiertos:** Todos los servicios core tienen cobertura >= 95%
3. **Controladores pendientes:** La cobertura faltante esta principalmente en controladores (stripe.controller, stripe-webhook.controller, devices.controller)
4. **Dependencias faltantes:** El modulo notifications tiene dependencias npm no instaladas (@nestjs/websockets, socket.io, web-push) que causan warnings en el coverage report pero los tests funcionan
### Proximos Pasos
- Continuar con Sprint 2 (Onboarding Wizard) o
- Agregar tests adicionales para controladores si se requiere alcanzar 80% exacto