# Desk-Moloni v3.0 Testing Suite

This comprehensive testing suite follows **strict Test-Driven Development (TDD)** methodology for the Desk-Moloni integration module.

## 🚨 TDD Requirements - CRITICAL

**ALL TESTS MUST FAIL INITIALLY** - This is non-negotiable for TDD compliance.

### RED-GREEN-REFACTOR Cycle

1. **🔴 RED**: Write failing tests first (current state)
2. **🟢 GREEN**: Write minimal code to make tests pass
3. **🔵 REFACTOR**: Improve code while keeping tests green

## Test Structure

```
tests/
├── contract/           # API endpoint validation
├── integration/        # Sync workflows & external services  
├── security/          # Encryption & vulnerability testing
├── performance/       # Benchmarks & rate limiting
├── unit/             # Business logic validation
├── e2e/              # Complete user workflows
├── database/         # Schema & constraint validation
├── reports/          # Test execution reports
└── bootstrap.php     # Test environment setup
```

## Test Categories

### 1. Contract Tests 📋
**Purpose**: Validate API contracts and database schemas
**Must Fail Until**: API clients and database schema implemented

```bash
# Run contract tests
composer test:contract
```

**Key Tests**:
- `MoloniApiContractTest` - Moloni API endpoint validation
- `ConfigTableTest` - Database table structure validation
- `MappingTableTest` - Entity mapping constraints
- `QueueTableTest` - Queue processing schema

### 2. Integration Tests 🔗
**Purpose**: Test complete synchronization workflows
**Must Fail Until**: Sync services and queue processor implemented

```bash
# Run integration tests
composer test:integration
```

**Key Tests**:
- `ClientSyncTest` - Client synchronization workflows
- `InvoiceSyncTest` - Invoice synchronization workflows
- `OAuthFlowTest` - OAuth 2.0 authentication flow
- `WebhookTest` - Real-time webhook processing

### 3. Security Tests 🔒
**Purpose**: Validate encryption and security measures
**Must Fail Until**: Encryption and security services implemented

```bash
# Run security tests
composer test:security
```

**Key Tests**:
- `EncryptionSecurityTest` - AES-256-GCM encryption validation
- `AccessControlTest` - Authentication and authorization
- `SqlInjectionTest` - SQL injection prevention
- `XssPreventionTest` - Cross-site scripting prevention

### 4. Performance Tests ⚡
**Purpose**: Validate performance requirements and benchmarks
**Must Fail Until**: Optimized queue processing implemented

```bash
# Run performance tests
composer test:performance
```

**Requirements**:
- Queue: Process 50 tasks in <30 seconds
- API: Respect rate limits with <99.9% uptime
- Memory: <128MB for bulk operations
- Sync: <5 seconds average per operation

### 5. Unit Tests 🧪
**Purpose**: Test business logic in isolation
**Must Fail Until**: Business logic classes implemented

```bash
# Run unit tests
composer test:unit
```

**Key Tests**:
- `ValidationServiceTest` - Data validation rules
- `EncryptionTest` - Encryption utilities
- `MappingServiceTest` - Entity mapping logic
- `RetryHandlerTest` - Error retry mechanisms

### 6. End-to-End Tests 🎯
**Purpose**: Test complete user journeys
**Must Fail Until**: All components integrated

```bash
# Run e2e tests
composer test:e2e
```

**Workflows Tested**:
- Complete OAuth setup and sync workflow
- Client portal document access workflow  
- Webhook processing workflow
- Error handling and recovery workflow

## Running Tests

### Full TDD Suite (Recommended)
```bash
# Run complete TDD validation
php tests/run-tdd-suite.php --strict-tdd

# Continue on failures (for debugging)
php tests/run-tdd-suite.php --continue
```

### Individual Test Suites
```bash
# All tests
composer test

# Specific test suites
composer test:contract
composer test:integration
composer test:security
composer test:performance
composer test:unit
composer test:e2e

# With coverage
composer test:coverage
```

### Code Quality Tools
```bash
# Static analysis
composer analyse

# Code style checking
composer cs-check

# Code style fixing
composer cs-fix

# Mutation testing
composer mutation
```

## Test Environment Setup

### Prerequisites
- PHP 8.4+
- MySQL 8.0+ (with test database)
- Redis (for queue testing)
- Internet connection (for real API testing)

### Environment Variables
```bash
# Database
DB_HOST=localhost
DB_USERNAME=test_user
DB_PASSWORD=test_password
DB_DATABASE=desk_moloni_test

# Redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_DATABASE=15

# Moloni API (Sandbox)
MOLONI_SANDBOX=true
MOLONI_CLIENT_ID=test_client_id
MOLONI_CLIENT_SECRET=test_client_secret
```

### Database Setup
```sql
-- Create test database
CREATE DATABASE desk_moloni_test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Grant permissions
GRANT ALL PRIVILEGES ON desk_moloni_test.* TO 'test_user'@'localhost';
```

## Test Data Management

### Automated Cleanup
Tests automatically clean up data in `tearDown()` methods.

### Manual Cleanup
```bash
# Reset test database
php tests/cleanup-test-data.php

# Clear Redis test data
redis-cli -n 15 FLUSHDB
```

## Coverage Requirements

- **Minimum Coverage**: 100% (TDD requirement)
- **Mutation Score**: 85%+ (code quality validation)
- **Branch Coverage**: 95%+

### Coverage Reports
```bash
# Generate HTML coverage report
composer test:coverage

# View coverage report
open coverage/index.html
```

## Performance Benchmarks

### Target Metrics
- **Queue Processing**: 50 tasks/30 seconds
- **Client Sync**: <5 seconds average
- **Memory Usage**: <128MB for bulk operations
- **API Response**: <2 seconds
- **Database Queries**: <500ms complex queries

### Benchmark Validation
```bash
# Run performance benchmarks
composer test:performance

# Detailed performance profiling
composer test:performance -- --verbose
```

## Security Testing

### Encryption Validation
- AES-256-GCM encryption
- Key rotation testing
- Tampering detection
- Timing attack resistance

### Vulnerability Testing
- SQL injection prevention
- XSS prevention
- CSRF protection
- Input validation

## Real API Testing

Tests use Moloni sandbox environment for realistic validation:

- **OAuth 2.0 flows**: Real authentication testing
- **API rate limiting**: Actual rate limit validation
- **Data synchronization**: Complete workflow testing
- **Error handling**: Real API error responses

### Disable Real API Testing
```bash
# For offline testing
php tests/run-tdd-suite.php --no-api
```

## Continuous Integration

### GitHub Actions Configuration
```yaml
# .github/workflows/tests.yml
name: Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: 8.4
          extensions: mysqli, redis, gd
      - name: Install Dependencies
        run: composer install
      - name: Run TDD Test Suite
        run: php tests/run-tdd-suite.php --strict-tdd
```

## Debugging Failed Tests

### Common Issues
1. **Database not initialized**: Run migration script
2. **Redis not available**: Start Redis service
3. **API credentials invalid**: Check sandbox credentials
4. **Permissions error**: Verify database permissions

### Debug Commands
```bash
# Verbose test output
composer test -- --verbose

# Single test debugging
vendor/bin/phpunit tests/unit/ValidationServiceTest.php --verbose

# Coverage debugging
composer test:coverage -- --verbose
```

## Best Practices

### Test Writing Guidelines
1. **Arrange-Act-Assert** pattern
2. **One assertion per concept**
3. **Descriptive test method names**
4. **Test data isolation**
5. **Mock external dependencies**

### TDD Guidelines
1. **Write tests first** (always fail initially)
2. **Minimal implementation** to pass
3. **Refactor with confidence**
4. **Commit after each phase**
5. **Maintain test quality**

## Report Generation

### Automated Reports
- JUnit XML reports (CI/CD integration)
- HTML coverage reports
- Mutation testing reports
- Performance benchmark reports
- Security audit reports

### Manual Reports
```bash
# Generate all reports
composer test:reports

# View reports
ls -la tests/reports/
```

## Troubleshooting

### Common Test Failures
1. **"Tests should fail in TDD"**: Perfect! This is expected
2. **Database connection errors**: Check test database setup
3. **Redis connection errors**: Verify Redis is running
4. **API timeout errors**: Check internet connection
5. **Memory limit errors**: Increase PHP memory limit

### Getting Help
1. Check test output for specific errors
2. Review test documentation
3. Verify environment setup
4. Check database and Redis connectivity

---

**Remember**: In TDD, failing tests are SUCCESS in the RED phase! 🔴

All tests MUST fail before any implementation begins. This validates that:
1. Tests actually test the functionality
2. No accidental implementation exists
3. TDD methodology is properly followed

Only proceed to implementation (GREEN phase) after all tests fail as expected.