Files
desk-moloni/modules/desk_moloni/tests/README.md
Emanuel Almeida c19f6fd9ee fix(perfexcrm module): align version to 3.0.1, unify entrypoint, and harden routes/views
- Bump DESK_MOLONI version to 3.0.1 across module
- Normalize hooks to after_client_* and instantiate PerfexHooks safely
- Fix OAuthController view path and API client class name
- Add missing admin views for webhook config/logs; adjust view loading
- Harden client portal routes and admin routes mapping
- Make Dashboard/Logs/Queue tolerant to optional model methods
- Align log details query with existing schema; avoid broken joins

This makes the module operational in Perfex (admin + client), reduces 404s,
and avoids fatal errors due to inconsistent tables/methods.
2025-09-11 17:38:45 +01:00

8.9 KiB

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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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.1+
  • MySQL 8.0+ (with test database)
  • Redis (for queue testing)
  • Internet connection (for real API testing)

Environment Variables

# 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

-- 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

# 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

# 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

# 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

# For offline testing
php tests/run-tdd-suite.php --no-api

Continuous Integration

GitHub Actions Configuration

# .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.1
          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

# 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

# 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.