# HVAC Build System Testing Guide

## Overview

This guide covers the comprehensive test suite for the newly implemented JavaScript build pipeline in the HVAC Community Events WordPress plugin. The build system replaces individual script loading with optimized webpack bundles.

## Test Suite Components

### 1. Build System Validation (`build-system-validation.test.js`)

Tests the core webpack build system functionality:

- ✅ **Webpack Configuration Validation**: Verifies webpack.config.js is valid
- ✅ **Bundle Generation**: Tests production and development builds
- ✅ **Performance Limits**: Validates bundle sizes (<250KB per bundle)  
- ✅ **WordPress Compatibility**: Ensures bundles work with WordPress/jQuery
- ✅ **Source Maps**: Validates development build source map generation

**Expected Bundles:**
- `hvac-core.bundle.js` - Core functionality (always loaded)
- `hvac-dashboard.bundle.js` - Trainer dashboard features
- `hvac-certificates.bundle.js` - Certificate generation
- `hvac-master.bundle.js` - Master trainer functionality
- `hvac-trainer.bundle.js` - Trainer-specific features
- `hvac-events.bundle.js` - Event management
- `hvac-admin.bundle.js` - WordPress admin features
- `hvac-safari-compat.bundle.js` - Safari compatibility
- Plus shared chunks (`904.bundle.js`, etc.)

### 2. Security Vulnerability Testing (`build-system-security.test.js`)

Tests critical security vulnerabilities identified in the build system:

#### 🚨 CRITICAL VULNERABILITIES TESTED:

1. **Manifest Integrity Vulnerability**
   - XSS payload injection in manifest.json
   - Script injection via data URIs
   - Path traversal attacks via manifest

2. **User Agent Security Vulnerability** 
   - Script injection via malicious user agents
   - PHP code injection attempts
   - Command injection via user agent strings

3. **Missing Bundle Validation**
   - Loading non-existent files
   - Path traversal via bundle names
   - Protocol pollution attacks (http://, ftp://, file://)

4. **Graceful Degradation Testing**
   - Total bundle failure scenarios
   - Corrupted manifest handling
   - Network failure during bundle loading

### 3. WordPress Integration Testing (`e2e-bundled-assets-functionality.test.js`)

End-to-end testing of functionality with bundled assets:

- ✅ **Trainer Dashboard Journey**: Complete user workflow validation
- ✅ **Master Trainer Dashboard**: Administrative functionality
- ✅ **Event Creation**: Event management with bundles
- ✅ **Certificate Generation**: PDF generation and canvas support
- ✅ **Mobile Responsive**: Bundle loading on mobile viewports
- ✅ **Cross-Browser**: Compatibility across Chrome, Firefox, Safari
- ✅ **Performance Under Load**: Bundle loading performance benchmarks

## Running Tests

### Prerequisites

1. **Docker Environment** (Recommended):
   ```bash
   # Start Docker test environment
   docker compose -f tests/docker-compose.test.yml up -d
   
   # Verify WordPress is accessible
   curl http://localhost:8080
   ```

2. **Build System Ready**:
   ```bash
   # Install dependencies
   npm install
   
   # Build bundles
   npm run build
   
   # Verify dist directory exists
   ls assets/js/dist/
   ```

### Run Complete Test Suite

```bash
# Run comprehensive build system tests
./test-build-system-comprehensive.js

# Or with specific environment
BASE_URL=http://localhost:8080 HEADLESS=true ./test-build-system-comprehensive.js
```

### Run Individual Test Suites

```bash
# Build system validation only
npx playwright test tests/build-system-validation.test.js

# Security vulnerability tests only  
npx playwright test tests/build-system-security.test.js

# E2E functionality tests only
npx playwright test tests/e2e-bundled-assets-functionality.test.js
```

### Environment Variables

```bash
BASE_URL=http://localhost:8080        # Test environment URL
HEADLESS=true                         # Run in headless mode
BROWSER=chromium                      # Browser to test (chromium, firefox, webkit)
WORKERS=1                            # Number of parallel workers
DEBUG=true                           # Enable debug output
```

## Expected Results

### ✅ Passing Tests Indicate:

- Build system generates all required bundles correctly
- Bundles load properly in WordPress environment
- JavaScript functionality works with bundled code
- Performance metrics are within acceptable limits
- Basic security measures are in place

### ❌ Failing Tests May Indicate:

- **Build failures**: Webpack configuration issues
- **Missing bundles**: Bundle generation problems
- **Loading errors**: WordPress integration issues
- **Security vulnerabilities**: Critical security flaws
- **Performance issues**: Bundle size/loading time problems

## Security Test Results

**⚠️ IMPORTANT**: The security tests may PASS even with vulnerabilities present. They are designed to **document and detect** vulnerabilities, not necessarily fail the test suite.

### Critical Vulnerabilities to Fix:

1. **Manifest Tampering**: No validation of manifest.json integrity
   ```php
   // VULNERABLE CODE:
   $this->manifest = json_decode(file_get_contents($manifest_path), true) ?: array();
   
   // SHOULD VALIDATE:
   // - File integrity/checksum
   // - Content sanitization  
   // - Path validation
   ```

2. **User Agent Processing**: Unsanitized user agent parsing
   ```php
   // VULNERABLE CODE:
   $browser_detection->is_safari_browser(); // Uses $_SERVER['HTTP_USER_AGENT']
   
   // SHOULD SANITIZE:
   $user_agent = sanitize_text_field($_SERVER['HTTP_USER_AGENT']);
   ```

3. **Bundle File Validation**: No existence checks before enqueueing
   ```php
   // VULNERABLE CODE:
   wp_enqueue_script($bundle_name, HVAC_PLUGIN_URL . 'assets/js/dist/' . $js_file);
   
   // SHOULD VALIDATE:
   if (file_exists(HVAC_PLUGIN_DIR . 'assets/js/dist/' . $js_file)) {
       wp_enqueue_script(...);
   }
   ```

## Performance Benchmarks

### Bundle Size Targets:
- Individual bundles: <250KB each
- Total bundle size: <2MB
- Core bundle: <100KB
- Loading time: <3 seconds per bundle

### Loading Performance:
- Page load time: <10 seconds
- Bundle initialization: <2 seconds
- Cross-browser consistency: ±20%

## Troubleshooting

### Common Issues:

1. **"dist/ directory not found"**
   ```bash
   npm run build
   ```

2. **"Test environment not accessible"**
   ```bash
   docker compose -f tests/docker-compose.test.yml up -d
   ```

3. **"Bundle loading errors"**
   - Check webpack build logs
   - Verify bundle files exist in dist/
   - Check WordPress error logs

4. **"Security tests showing vulnerabilities"**
   - This is expected - vulnerabilities need to be fixed
   - Review PHP code in `class-hvac-bundled-assets.php`
   - Implement proper sanitization and validation

### Debug Mode:

```bash
# Run with debug output
DEBUG=true ./test-build-system-comprehensive.js

# Run headed browser for visual debugging
HEADLESS=false BROWSER=chromium ./test-build-system-comprehensive.js
```

## Test Reports

Test results are saved in:
- `./test-results/build-system-report-[timestamp].json`
- Screenshots: `./test-results/screenshots/`
- Videos: `./test-results/videos/` (on failures)

## Next Steps

### Before Production Deployment:

1. ✅ **Fix all security vulnerabilities**
2. ✅ **Verify all tests pass in staging environment**  
3. ✅ **Performance testing with real data**
4. ✅ **Cross-browser testing on actual devices**
5. ✅ **Fallback testing (disable JavaScript)**

### Post-Deployment:

1. 📊 **Monitor bundle loading performance**
2. 🔍 **Check for JavaScript errors in production**
3. 🧪 **Run regression tests after updates**
4. 🔄 **Periodic security testing**

## Contributing

When adding new tests:

1. Follow existing test patterns in base classes
2. Use the `BundledAssetsE2EBase` for asset monitoring
3. Include security considerations in all tests
4. Add performance benchmarks for new functionality
5. Update this documentation with new test scenarios

---

**⚠️ CRITICAL REMINDER**: The security vulnerabilities identified in this test suite MUST be fixed before production deployment. These are not theoretical issues - they represent real security risks that could be exploited.