/** * Global Test Setup for HVAC Testing Framework * * Runs once before all tests to: * - Initialize test environment * - Pre-generate authentication states * - Set up WordPress environment * - Verify system health * * @package HVAC_Community_Events * @version 2.0.0 * @created 2025-08-27 */ const { chromium } = require('playwright'); const ConfigManager = require('../core/ConfigManager'); const AuthManager = require('../core/AuthManager'); const WordPressUtils = require('../utils/WordPressUtils'); const fs = require('fs').promises; const path = require('path'); async function globalSetup(config) { console.log('\nšŸš€ HVAC Testing Framework - Global Setup'); console.log('='.repeat(50)); const startTime = Date.now(); const configManager = ConfigManager; const authManager = AuthManager; const wpUtils = new WordPressUtils(); try { // 1. Environment Validation console.log('\nšŸ“‹ 1. Validating Environment Configuration'); const environment = configManager.getEnvironment(); console.log(` Environment: ${environment}`); console.log(` Base URL: ${configManager.get('app.baseUrl')}`); // Validate configuration configManager.validate(); console.log(' āœ… Configuration valid'); // 2. WordPress Health Check console.log('\nšŸ„ 2. WordPress Health Check'); try { const health = await wpUtils.checkHealth(); console.log(' WordPress Version:', health.wpVersion); console.log(' HVAC Plugin Active:', health.pluginsActive ? 'āœ…' : 'āŒ'); console.log(' Database Connected:', health.databaseConnected ? 'āœ…' : 'āŒ'); if (!health.pluginsActive) { console.warn(' āš ļø HVAC plugin not active - some tests may fail'); } } catch (error) { console.warn(' āš ļø WordPress health check failed:', error.message); } // 3. Create Test Results Directories console.log('\nšŸ“ 3. Setting Up Test Directories'); const directories = [ configManager.get('media.screenshotDir'), configManager.get('media.videoDir'), configManager.get('reporting.outputDir'), './test-results/logs', './test-results/storage-states' ]; for (const dir of directories) { await fs.mkdir(dir, { recursive: true }); console.log(` āœ… Created: ${dir}`); } // 4. Pre-generate Authentication States console.log('\nšŸ” 4. Pre-generating Authentication States'); if (configManager.get('testData.seedData') && environment !== 'staging') { // Only pre-generate auth states in safe environments try { await authManager.preGenerateStorageStates(); console.log(' āœ… Authentication states generated'); } catch (error) { console.warn(' āš ļø Could not pre-generate auth states:', error.message); console.warn(' Tests will use fresh login instead'); } } else { console.log(' ā„¹ļø Skipping auth state generation (staging environment)'); } // 5. WordPress Environment Preparation console.log('\nāš™ļø 5. Preparing WordPress Environment'); if (environment === 'local' || environment === 'docker') { try { // Flush rewrite rules await wpUtils.flushRewriteRules(); console.log(' āœ… Rewrite rules flushed'); // Clear cache await wpUtils.clearCache(); console.log(' āœ… Cache cleared'); // Run cron await wpUtils.runCron(); console.log(' āœ… Cron executed'); } catch (error) { console.warn(' āš ļø WordPress preparation failed:', error.message); } } else { console.log(' ā„¹ļø Skipping WordPress modifications (staging environment)'); } // 6. Browser Verification console.log('\n🌐 6. Browser Environment Verification'); const browser = await chromium.launch({ headless: true, timeout: 10000 }); try { const context = await browser.newContext(); const page = await context.newPage(); // Test basic navigation await page.goto(configManager.get('app.baseUrl'), { timeout: 15000 }); const title = await page.title(); console.log(` āœ… Site accessible: ${title}`); await context.close(); } catch (error) { console.error(' āŒ Site not accessible:', error.message); throw new Error(`Cannot access test site: ${configManager.get('app.baseUrl')}`); } finally { await browser.close(); } // 7. Generate Setup Report console.log('\nšŸ“Š 7. Generating Setup Report'); const setupReport = { timestamp: new Date().toISOString(), environment, baseUrl: configManager.get('app.baseUrl'), configuration: configManager.getAll(), setupDuration: Date.now() - startTime, directories: directories, health: await wpUtils.checkHealth().catch(() => ({ error: 'Health check failed' })), authStatesGenerated: true // Will be updated based on actual generation }; const reportPath = path.resolve('./test-results/setup-report.json'); await fs.writeFile(reportPath, JSON.stringify(setupReport, null, 2)); console.log(` āœ… Setup report: ${reportPath}`); // 8. Final Summary const duration = ((Date.now() - startTime) / 1000).toFixed(2); console.log('\n' + '='.repeat(50)); console.log('āœ… Global Setup Complete'); console.log(`ā±ļø Duration: ${duration}s`); console.log(`šŸŒ Environment: ${environment}`); console.log(`šŸ”— Base URL: ${configManager.get('app.baseUrl')}`); console.log('='.repeat(50) + '\n'); return setupReport; } catch (error) { console.error('\nāŒ Global Setup Failed'); console.error('Error:', error.message); console.error('='.repeat(50) + '\n'); throw error; } } module.exports = globalSetup;