test: full test suite (Vitest + pgTAP + Playwright) + TDD plan restructure

Add a 4-layer test stack covering RLS, triggers, and UI flows for Fases 0–2a,
then restructure every plan file so future fases start with tests and end with
a verification gate.

Test suite
- packages/test-utils: Vitest integration tests signing HS256 JWTs via jose so
  each test acts as a specific seed user (createClientAs + createAdminClient)
- supabase/tests: pgTAP for accept_invitation(), item_frequency trigger, and
  promote-on-admin-leave; each file self-installs pgtap extension
- apps/web/tests: Playwright E2E with live Keycloak login per test (storageState
  caching doesn't rehydrate Supabase's session state reliably)
- just test-all chains the three suites; test-db forwards POSTGRES_PASSWORD
  as PGPASSWORD with ON_ERROR_STOP=1 so failures abort the chain

Supabase auth gotcha
- PostgREST queries inside onAuthStateChange deadlock on GoTrue's navigator.locks
  auth lock (getAccessToken → getSession → initializePromise waits on the same
  lock that's held during event dispatch). Fix is two defenses: a pass-through
  lock in $lib/supabase, and a setTimeout(0) defer in root +layout.svelte to
  push loadUserCollectives out of the callback's microtask chain. Either alone
  is insufficient; both together unblock the Playwright suite.

Env key rotation
- apps/web/.env.development had a stale demo anon key signed with a different
  secret than root .env; Vite inlined that into the browser bundle so Kong (which
  uses the root .env value) rejected every request with 401. Aligned the two
  files and added a memory entry to flag this for the next rotation.

Plan restructure (TDD)
- Every fase now opens with X.0 Tests primero and closes with X.Z Verificación
  final. Completed fases (0, 1, 2a) show the pattern retroactively with the
  tests that currently cover them; pending fases (2b, 3, 4) list the tests to
  write before implementation.

Docs
- CLAUDE.md status line reports 54 + 12 + 15 = 81 green tests, adds gotchas
  #11 (auth-lock deadlock) and #12 (no storageState caching)
- README.md adds a TDD methodology section and the test-all command
- .gitignore excludes Playwright's generated reports and auth state

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-13 01:40:16 +02:00
parent 3af1276c15
commit f396897cb5
39 changed files with 2889 additions and 97 deletions

View File

@@ -5,16 +5,40 @@
---
## Estado actual
| Fase | Estado |
|------|--------|
| Fase 0 — Infraestructura | ✅ Completa |
| Fase 1 — Auth y Colectivo | ✅ Completa |
| Fase 2a — Lista de Compra CRUD | ✅ Completa |
| Suite de tests (integración + pgTAP + E2E) | ✅ Completa — 81 tests verdes (54 Vitest + 12 pgTAP + 15 Playwright), lanzables con `just test-all` |
| Fase 2b — Realtime y Modo Compra | ⏳ Pendiente |
| Fase 3 — Tareas y Notas | ⏳ Pendiente |
| Fase 4 — Búsqueda y Pulido | ⏳ Pendiente |
---
## Metodología por fase (TDD)
Desde la Fase 1 en adelante, cada fase está estructurada así:
1. **`X.0 Tests primero`** — se escriben los tests (Vitest + pgTAP + Playwright) que definen el éxito de la fase, **antes** de cualquier implementación.
2. **`X.1 … X.N`** — implementación en el orden que mejor sirva a los tests.
3. **`X.Z Verificación final`** — `just test-all` debe devolver 0 failures. Sólo entonces la fase se considera cerrada.
Las fases ya cerradas (0, 1, 2a) reflejan este patrón retroactivamente: la sección `X.0` enumera los tests que hoy cubren la fase, y `X.Z` confirma que `just test-all` pasa.
## Índice de Fases
| Fase | Archivo | Duración estimada |
|------|---------|-------------------|
| Fase 0 | [fase-0-infraestructura.md](fase-0-infraestructura.md) | 12 semanas |
| Fase 1 | [fase-1-auth-colectivo.md](fase-1-auth-colectivo.md) | 23 semanas |
| Fase 2a | [fase-2a-lista-compra-crud.md](fase-2a-lista-compra-crud.md) | 2 semanas |
| Fase 2b | [fase-2b-realtime-modo-compra.md](fase-2b-realtime-modo-compra.md) | 23 semanas |
| Fase 3 | [fase-3-tareas-notas.md](fase-3-tareas-notas.md) | 12 semanas |
| Fase 4 | [fase-4-busqueda-pulido.md](fase-4-busqueda-pulido.md) | 1 semana |
| Fase 0 | [fase-0-infraestructura.md](plan/fase-0-infraestructura.md) | 12 semanas |
| Fase 1 | [fase-1-auth-colectivo.md](plan/fase-1-auth-colectivo.md) | 23 semanas |
| Fase 2a | [fase-2a-lista-compra-crud.md](plan/fase-2a-lista-compra-crud.md) | 2 semanas |
| Fase 2b | [fase-2b-realtime-modo-compra.md](plan/fase-2b-realtime-modo-compra.md) | 23 semanas |
| Fase 3 | [fase-3-tareas-notas.md](plan/fase-3-tareas-notas.md) | 12 semanas |
| Fase 4 | [fase-4-busqueda-pulido.md](plan/fase-4-busqueda-pulido.md) | 1 semana |
**Total estimado: 913 semanas**
@@ -54,20 +78,31 @@ colectivo/
│ │ │ └── components/ # componentes UI reutilizables
│ │ ├── routes/ # rutas SvelteKit
│ │ └── service-worker.ts # SW personalizado (Workbox)
│ ├── tests/
│ │ ├── fixtures/
│ │ │ ├── users.ts # constantes de usuarios semilla
│ │ │ └── global-setup.ts # login por usuario vía Keycloak, cachea storageState
│ │ └── e2e/ # tests Playwright (A, C, D series)
│ ├── static/
│ │ ├── manifest.webmanifest
│ │ └── icons/ # iconos PWA (512, 192, 180...)
│ └── vite.config.ts
├── packages/
── types/ # tipos TypeScript compartidos
── types/ # tipos TypeScript compartidos
│ │ └── src/
│ │ ├── database.ts # tipos generados desde schema Supabase
│ │ └── domain.ts # tipos de dominio (Colectivo, Item, etc.)
│ └── test-utils/ # infraestructura de tests de integración
│ └── src/
│ ├── database.ts # tipos generados desde schema Supabase
── domain.ts # tipos de dominio (Colectivo, Item, etc.)
│ ├── seed-constants.ts # UUIDs fijos de usuarios y colectivo de prueba
── supabase-clients.ts # createClientAs(userId) + createAdminClient()
│ └── db-helpers.ts # sql() vía pg.Pool (bypassa RLS para setup/teardown)
├── supabase/
│ ├── migrations/ # migraciones SQL versionadas
│ ├── seed.sql # datos de prueba para dev
│ ├── tests/ # tests pgTAP (SQL puro, sin mocking)
│ ├── functions/ # Edge Functions (invitaciones, etc.)
│ └── config.toml # configuración Supabase CLI + OIDC Keycloak
@@ -122,6 +157,11 @@ just backup keycloak # backup manual inmediato de keycloak
just restore supabase <file> # restaura un dump concreto en supabase
just restore keycloak <file> # restaura un dump concreto en keycloak
just logs # docker compose logs -f (prod)
just test-all # ejecuta todas las suites (pgTAP + Vitest + Playwright); requiere just dev activo
just test-integration # Vitest: tests de integración RLS (requiere just dev activo)
just test-db # pgTAP: tests SQL directamente contra la BD dev
just test-e2e # Playwright: tests E2E en modo headless (requiere just dev activo)
just test-e2e-headed # Playwright: tests E2E con navegador visible (debugging)
```
---