trading-platform/docs/97-adr/ADR-004-testing.md
rckrdmrd c1b5081208 feat(ml): Complete FASE 11 - BTCUSD update and comprehensive documentation alignment
ML Engine Updates:
- Updated BTCUSD with Polygon API data (2024-2025): 215,699 new records
- Re-trained all ML models: Attention (R²: 0.223), Base, Metamodel (87.3% confidence)
- Backtest results: +176.71R profit with aggressive_filter strategy

Documentation Consolidation:
- Created docs/99-analisis/_MAP.md index with 13 new analysis documents
- Consolidated inventories: removed duplicates from orchestration/inventarios/
- Updated ML_INVENTORY.yml with BTCUSD metrics and training results
- Added execution reports: FASE11-BTCUSD, correction issues, alignment validation

Architecture & Integration:
- Updated all module documentation with NEXUS v3.4 frontmatter
- Fixed _MAP.md indexes across all folders
- Updated orchestration plans and traces

Files: 229 changed, 5064 insertions(+), 1872 deletions(-)

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 09:31:29 -06:00

253 lines
6.4 KiB
Markdown

---
id: "ADR-004-testing"
title: "Estrategia de Testing"
type: "Documentation"
project: "trading-platform"
version: "1.0.0"
updated_date: "2026-01-04"
---
# ADR-003: Estrategia de Testing
**Estado:** Aceptado
**Fecha:** 2025-12-06
**Decisores:** Tech Lead, Arquitecto
**Relacionado:** ADR-001, ADR-002
---
## Contexto
Trading Platform maneja datos financieros críticos y predicciones de ML que afectan decisiones de inversión. Necesitamos:
1. **Confiabilidad**: Trading con dinero real requiere alta confianza en el código
2. **Regression Prevention**: Nuevas features no deben romper funcionalidades existentes
3. **Velocidad de Desarrollo**: Tests rápidos para no frenar el MVP (8 semanas)
4. **Coverage Meaningful**: No solo alcanzar %, sino testear lógica crítica
5. **Múltiples Tecnologías**: Frontend (React), Backend (Express), ML (Python)
El equipo tiene experiencia con Jest, Vitest y Pytest en proyectos previos.
---
## Decisión
### Testing Tools por Aplicación
| App | Framework | Justificación |
|-----|-----------|---------------|
| **Frontend** | **Vitest** + React Testing Library | Nativo para Vite, más rápido que Jest |
| **Backend** | **Jest** + Supertest | Estándar de Node.js, buena integración |
| **ML Engine** | **Pytest** + TestClient | Estándar Python, fixtures poderosos |
| **E2E** | **Playwright** | Cross-browser, auto-wait, debugging |
### Coverage Targets
```yaml
frontend:
statements: 70%
branches: 65%
functions: 70%
lines: 70%
backend:
statements: 80%
branches: 75%
functions: 80%
lines: 80%
ml-engine:
statements: 75%
branches: 70%
functions: 75%
lines: 75%
```
### Testing Pyramid
```
E2E (5%)
──────────────
Integration (25%)
─────────────────────
Unit Tests (70%)
──────────────────────────
```
### Estructura de Tests
```
apps/frontend/
src/
components/
Button/
Button.tsx
Button.test.tsx # Co-located unit tests
__tests__/
integration/ # Integration tests
auth-flow.test.tsx
apps/backend/
src/
routes/
auth.routes.ts
auth.routes.test.ts # Co-located tests
__tests__/
integration/
api.test.ts
apps/ml-engine/
tests/
unit/ # Unit tests
integration/ # Integration tests
conftest.py # Pytest fixtures
tests/e2e/ # E2E en root del monorepo
auth.spec.ts
trading.spec.ts
```
### Test Scripts
```json
{
"scripts": {
"test": "npm run test --workspaces",
"test:unit": "npm run test:unit --workspaces",
"test:integration": "npm run test:integration --workspaces",
"test:e2e": "playwright test",
"test:coverage": "npm run test:coverage --workspaces",
"test:watch": "npm run test:watch -w apps/frontend"
}
}
```
---
## Consecuencias
### Positivas
1. **Fast Feedback**: Vitest en frontend es ~10x más rápido que Jest
2. **Type Safety**: Tests en TypeScript previenen errores de tipos
3. **Confidence**: 80% coverage en backend protege lógica crítica
4. **Developer Experience**: Watch mode + HMR para tests instantáneos
5. **CI Pipeline**: Tests paralelos por workspace
6. **Debugging**: Playwright trace viewer para E2E failures
7. **Consistent Tools**: Misma API de assertions (expect) en todos los tests
### Negativas
1. **Múltiples Frameworks**: Equipo debe conocer Vitest, Jest y Pytest
2. **CI Time**: Tests completos pueden tardar 5-10 min
3. **Flaky E2E**: Playwright tests pueden fallar por timing issues
4. **Maintenance**: Tests también requieren refactoring
5. **Learning Curve**: React Testing Library requiere pensar en "user behavior"
### Riesgos y Mitigaciones
| Riesgo | Mitigación |
|--------|-----------|
| Tests lentos en CI | Paralelización + caching de dependencias |
| Flaky E2E tests | Retry logic (3 intentos) + auto-wait de Playwright |
| Low coverage | Pre-commit hook que bloquea < 70% |
| Mocks complejos | Usar MSW para mock de API requests |
---
## Alternativas Consideradas
### 1. Jest para Todo (Frontend + Backend)
- **Pros**: Una sola herramienta, configuración compartida
- **Contras**: Más lento en frontend, no nativo para Vite
- **Decisión**: Descartada - Vitest es superior para proyectos Vite
### 2. Cypress para E2E
- **Pros**: Developer-friendly, time-travel debugging
- **Contras**: Solo Chrome, más lento que Playwright
- **Decisión**: Descartada - Playwright es más rápido y multi-browser
### 3. Coverage al 100%
- **Pros**: Máxima confianza
- **Contras**: Tiempo de desarrollo excesivo, diminishing returns
- **Decisión**: Descartada - 70-80% es balance óptimo para MVP
### 4. Solo E2E Tests (Testing Trophy)
- **Pros**: Tests que cubren flujos reales
- **Contras**: Lentos, difíciles de debuggear, frágiles
- **Decisión**: Descartada - Necesitamos pirámide balanceada
### 5. TDD Estricto
- **Pros**: Diseño guiado por tests
- **Contras**: Ralentiza MVP, no todo el equipo tiene experiencia
- **Decisión**: Descartada - TDD opcional, no obligatorio
---
## Testing de Componentes Críticos
### Backend
```typescript
// ✅ MUST TEST
- Authentication & Authorization
- Payment processing (Stripe)
- ML predictions API
- Database transactions
- Rate limiting
// ⚠️ SHOULD TEST
- Validation middleware
- Error handlers
- Email/SMS services
// ❌ SKIP
- Trivial getters/setters
- Type definitions
```
### Frontend
```typescript
// ✅ MUST TEST
- Forms con validación
- Trading dashboard calculations
- Chart data transformations
- Authentication flows
// ⚠️ SHOULD TEST
- Hooks personalizados
- Zustand stores
- Utilities/helpers
// ❌ SKIP
- Componentes puramente visuales sin lógica
- Wrappers triviales
```
### ML Engine
```python
# ✅ MUST TEST
- Model predictions
- Feature engineering
- Data preprocessing
- Model loading/validation
# ⚠️ SHOULD TEST
- API endpoints
- Data validation
- Cache logic
# ❌ SKIP
- Configuración constants
- Type hints
```
---
## Referencias
- [Vitest Documentation](https://vitest.dev/)
- [React Testing Library](https://testing-library.com/react)
- [Playwright Best Practices](https://playwright.dev/docs/best-practices)
- [Pytest Documentation](https://docs.pytest.org/)
- [Testing Trophy by Kent C. Dodds](https://kentcdodds.com/blog/the-testing-trophy-and-testing-classifications)