- 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.
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
- 🔴 RED: Write failing tests first (current state)
- 🟢 GREEN: Write minimal code to make tests pass
- 🔵 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 validationConfigTableTest- Database table structure validationMappingTableTest- Entity mapping constraintsQueueTableTest- 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 workflowsInvoiceSyncTest- Invoice synchronization workflowsOAuthFlowTest- OAuth 2.0 authentication flowWebhookTest- 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 validationAccessControlTest- Authentication and authorizationSqlInjectionTest- SQL injection preventionXssPreventionTest- 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 rulesEncryptionTest- Encryption utilitiesMappingServiceTest- Entity mapping logicRetryHandlerTest- 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
Full TDD Suite (Recommended)
# 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
- Database not initialized: Run migration script
- Redis not available: Start Redis service
- API credentials invalid: Check sandbox credentials
- 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
- Arrange-Act-Assert pattern
- One assertion per concept
- Descriptive test method names
- Test data isolation
- Mock external dependencies
TDD Guidelines
- Write tests first (always fail initially)
- Minimal implementation to pass
- Refactor with confidence
- Commit after each phase
- 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
- "Tests should fail in TDD": Perfect! This is expected
- Database connection errors: Check test database setup
- Redis connection errors: Verify Redis is running
- API timeout errors: Check internet connection
- Memory limit errors: Increase PHP memory limit
Getting Help
- Check test output for specific errors
- Review test documentation
- Verify environment setup
- 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:
- Tests actually test the functionality
- No accidental implementation exists
- TDD methodology is properly followed
Only proceed to implementation (GREEN phase) after all tests fail as expected.