/** * TEC Template Test Data Manager * * Comprehensive test data management for the TEC template test automation suite. * Handles setup, cleanup, and management of test data for all testing scenarios. * * Features: * - Test user management and authentication * - Sample event data generation * - Media asset management for testing * - Database state management * - Test environment setup and teardown * * @author Claude Code - Test Automation Specialist * @version 1.0.0 * @date August 12, 2025 */ const { chromium } = require('playwright'); const fs = require('fs'); const path = require('path'); // Test data configuration const TEST_DATA_CONFIG = { // Environment settings environment: { staging: 'https://upskill-staging.measurequick.com', production: 'https://upskillhvac.com' // Use with extreme caution }, // Test users testUsers: { trainer: { username: 'test_trainer', password: 'TestTrainer123!', email: 'test.trainer@hvactest.com', role: 'hvac_trainer' }, masterTrainer: { username: 'test_master', password: 'TestMaster123!', email: 'test.master@hvactest.com', role: 'hvac_master_trainer' }, fieldTestUser: { username: 'field_test_user', password: 'FieldTest123!', email: 'field.test@hvactest.com', role: 'hvac_trainer' } }, // Test data storage storage: { dataDir: 'test-data', backupDir: 'test-data/backups', mediaDir: 'test-data/media', outputDir: 'test-results' }, // Cleanup settings cleanup: { deleteTestEvents: true, preserveUserAccounts: true, cleanupMedia: false, maxTestEvents: 50 // Max test events to keep } }; // Sample test data sets const TEST_DATA_SETS = { // Basic event for simple testing basicEvent: { title: 'Basic HVAC Workshop - Test Event', content: 'Simple test event for basic functionality validation.', excerpt: 'Basic test event excerpt', startDate: '2025-09-30', endDate: '2025-09-30', startTime: '10:00', endTime: '15:00', cost: '150', categories: ['Training'], tags: ['basic', 'test', 'HVAC'] }, // Comprehensive event for full testing comprehensiveEvent: { title: 'Advanced HVAC Diagnostics & Performance Workshop - Comprehensive Test', content: `

Comprehensive HVAC Training Program

This comprehensive workshop covers all aspects of modern HVAC diagnostics and performance optimization.

Learning Objectives:

Workshop Modules:

  1. Refrigeration Cycle Analysis
  2. Electrical Diagnostics
  3. Airflow Measurement
  4. Energy Efficiency
  5. Smart Technology Integration

Prerequisites:

Basic HVAC knowledge required. Participants should bring laptops and basic tools.

Certification: Continuing education credits available upon completion.

`, excerpt: 'Comprehensive HVAC diagnostics workshop covering advanced techniques, electrical troubleshooting, energy efficiency optimization, and smart technology integration.', startDate: '2025-10-15', endDate: '2025-10-16', startTime: '08:30', endTime: '17:30', cost: '599', categories: ['Advanced Training', 'Diagnostics', 'Certification'], tags: ['advanced', 'diagnostics', 'HVAC', 'certification', 'energy-efficiency', 'smart-technology'], venue: { name: 'HVAC Training Excellence Center', address: '2500 Technology Boulevard', city: 'Dallas', state: 'TX', zip: '75201', phone: '+1-214-555-0199', url: 'https://hvac-training-center.com' }, organizer: { name: 'Professional HVAC Training Solutions', email: 'training@hvac-pro-solutions.com', phone: '+1-214-555-0299', website: 'https://hvac-pro-solutions.com' } }, // Performance stress test event performanceStressEvent: { title: 'HVAC Performance Stress Test Event - Large Content and Complex Structure', content: this.generateLargeContent(), excerpt: 'Performance stress test event with large content size and complex structure for testing template performance under load.', startDate: '2025-11-01', endDate: '2025-11-03', startTime: '07:00', endTime: '18:00', cost: '1299', categories: ['Intensive Training', 'Performance Testing', 'Advanced Diagnostics', 'Certification'], tags: ['performance', 'stress-test', 'intensive', 'advanced', 'HVAC', 'diagnostics', 'certification', 'workshop', 'training', 'professional'] }, // Minimal event for compatibility testing minimalEvent: { title: 'Minimal Test Event', content: 'Minimal content for compatibility testing.', startDate: '2025-12-01', endDate: '2025-12-01', startTime: '14:00', endTime: '16:00' } }; /** * Test Data Manager Class */ class TestDataManager { constructor(environment = 'staging') { this.environment = environment; this.baseUrl = TEST_DATA_CONFIG.environment[environment]; this.createdEvents = []; this.uploadedMedia = []; this.testSessions = []; this.ensureDirectories(); } /** * Setup test environment */ async setupTestEnvironment() { console.log('πŸ› οΈ SETTING UP TEST ENVIRONMENT'); console.log('=============================='); console.log(`Environment: ${this.environment}`); console.log(`Base URL: ${this.baseUrl}`); console.log(''); try { // Verify test user access await this.verifyTestUsers(); // Prepare test media await this.prepareTestMedia(); // Clean up old test data await this.cleanupOldTestData(); // Create test data sets await this.createTestDataSets(); console.log('βœ… Test environment setup complete'); return true; } catch (error) { console.error('❌ Test environment setup failed:', error.message); throw error; } } /** * Verify test user access */ async verifyTestUsers() { console.log('πŸ‘€ Verifying test user access...'); const browser = await chromium.launch({ headless: true }); const context = await browser.newContext(); const page = await context.newPage(); try { for (const [userType, userConfig] of Object.entries(TEST_DATA_CONFIG.testUsers)) { try { // Navigate to login await page.goto(`${this.baseUrl}/training-login/`); await page.waitForLoadState('networkidle'); // Attempt login await page.fill('input[name="log"]', userConfig.username); await page.fill('input[name="pwd"]', userConfig.password); await page.click('input[type="submit"]'); await page.waitForLoadState('networkidle'); // Check for successful login const loginError = await page.locator('.login_error, .error').count(); if (loginError > 0) { throw new Error(`Login failed for ${userType}`); } // Verify dashboard access const dashboardUrl = userType === 'masterTrainer' ? '/master-trainer/master-dashboard/' : '/trainer/dashboard/'; await page.goto(`${this.baseUrl}${dashboardUrl}`); await page.waitForTimeout(2000); const dashboardTitle = await page.title(); if (!dashboardTitle.includes('Dashboard')) { throw new Error(`Dashboard not accessible for ${userType}`); } console.log(` βœ… ${userType}: Login successful, dashboard accessible`); } catch (error) { console.log(` ❌ ${userType}: ${error.message}`); throw new Error(`Test user verification failed for ${userType}: ${error.message}`); } } } finally { await browser.close(); } } /** * Prepare test media assets */ async prepareTestMedia() { console.log('πŸ–ΌοΈ Preparing test media assets...'); const mediaAssets = [ { name: 'test-hvac-workshop.jpg', type: 'image/jpeg', size: '1920x1080', description: 'HVAC workshop test image' }, { name: 'test-training-center.jpg', type: 'image/jpeg', size: '1200x800', description: 'Training center test image' }, { name: 'test-equipment.jpg', type: 'image/jpeg', size: '800x600', description: 'HVAC equipment test image' } ]; for (const asset of mediaAssets) { const assetPath = path.join(TEST_DATA_CONFIG.storage.mediaDir, asset.name); if (!fs.existsSync(assetPath)) { // Create a simple test image (placeholder) const svgContent = this.generateTestImage(asset.size, asset.description); fs.writeFileSync(assetPath.replace('.jpg', '.svg'), svgContent); console.log(` πŸ“ Created test asset: ${asset.name}`); } else { console.log(` βœ… Test asset exists: ${asset.name}`); } } } /** * Clean up old test data */ async cleanupOldTestData() { console.log('🧹 Cleaning up old test data...'); if (!TEST_DATA_CONFIG.cleanup.deleteTestEvents) { console.log(' ⚠️ Test event cleanup disabled in config'); return; } const browser = await chromium.launch({ headless: true }); const context = await browser.newContext(); const page = await context.newPage(); try { // Login as test user await this.loginAsTestUser(page, 'trainer'); // Navigate to events management await page.goto(`${this.baseUrl}/trainer/dashboard/`); await page.waitForTimeout(2000); // Look for test events to clean up // This would need to be implemented based on how events are managed console.log(' ℹ️ Test event cleanup - implementation needed based on event management UI'); } finally { await browser.close(); } } /** * Create test data sets */ async createTestDataSets() { console.log('πŸ“ Creating test data sets...'); // Save test data sets to files for reference const dataSetsFile = path.join(TEST_DATA_CONFIG.storage.dataDir, 'test-data-sets.json'); fs.writeFileSync(dataSetsFile, JSON.stringify(TEST_DATA_SETS, null, 2)); console.log(` πŸ’Ύ Test data sets saved to: ${dataSetsFile}`); // Create field mapping reference const fieldMappingFile = path.join(TEST_DATA_CONFIG.storage.dataDir, 'field-mapping.json'); const fieldMapping = this.generateFieldMapping(); fs.writeFileSync(fieldMappingFile, JSON.stringify(fieldMapping, null, 2)); console.log(` πŸ—ΊοΈ Field mapping saved to: ${fieldMappingFile}`); } /** * Get test data by type */ getTestData(dataType) { if (!TEST_DATA_SETS[dataType]) { throw new Error(`Test data type '${dataType}' not found`); } return JSON.parse(JSON.stringify(TEST_DATA_SETS[dataType])); // Deep clone } /** * Create random test event data */ generateRandomEventData() { const eventTypes = ['Workshop', 'Seminar', 'Training', 'Certification', 'Conference']; const topics = ['HVAC Diagnostics', 'Energy Efficiency', 'Smart Technology', 'Electrical Systems', 'Refrigeration']; const levels = ['Basic', 'Intermediate', 'Advanced', 'Expert']; const randomType = eventTypes[Math.floor(Math.random() * eventTypes.length)]; const randomTopic = topics[Math.floor(Math.random() * topics.length)]; const randomLevel = levels[Math.floor(Math.random() * levels.length)]; const randomId = Math.floor(Math.random() * 1000000); return { title: `${randomLevel} ${randomTopic} ${randomType} - Test ${randomId}`, content: `This is a randomly generated test event for ${randomTopic.toLowerCase()} training. Content ID: ${randomId}`, excerpt: `${randomLevel} ${randomTopic.toLowerCase()} ${randomType.toLowerCase()} for testing purposes.`, startDate: this.getRandomFutureDate(), endDate: this.getRandomFutureDate(1), startTime: this.getRandomTime(), endTime: this.getRandomTime(true), cost: Math.floor(Math.random() * 500 + 100).toString(), categories: [randomTopic], tags: ['test', randomLevel.toLowerCase(), randomTopic.toLowerCase().replace(' ', '-')] }; } /** * Login as test user */ async loginAsTestUser(page, userType = 'trainer') { const userConfig = TEST_DATA_CONFIG.testUsers[userType]; if (!userConfig) { throw new Error(`Test user type '${userType}' not found`); } await page.goto(`${this.baseUrl}/training-login/`); await page.waitForLoadState('networkidle'); await page.fill('input[name="log"]', userConfig.username); await page.fill('input[name="pwd"]', userConfig.password); await page.click('input[type="submit"]'); await page.waitForLoadState('networkidle'); // Verify login success const loginError = await page.locator('.login_error, .error').count(); if (loginError > 0) { throw new Error(`Login failed for test user: ${userType}`); } } /** * Cleanup test environment */ async cleanupTestEnvironment() { console.log('🧹 CLEANING UP TEST ENVIRONMENT'); console.log('==============================='); try { // Clean up created events if (TEST_DATA_CONFIG.cleanup.deleteTestEvents && this.createdEvents.length > 0) { await this.deleteCreatedEvents(); } // Clean up uploaded media if (TEST_DATA_CONFIG.cleanup.cleanupMedia && this.uploadedMedia.length > 0) { await this.deleteUploadedMedia(); } // Save session data for reference await this.saveSessionData(); console.log('βœ… Test environment cleanup complete'); } catch (error) { console.error('❌ Test environment cleanup failed:', error.message); } } /** * Generate test image SVG */ generateTestImage(size, description) { const [width, height] = size.split('x').map(Number); return ` TEST IMAGE ${description} ${size} `; } /** * Generate field mapping reference */ generateFieldMapping() { return { wordpress_core: { title: { selector: '#title, input[name="post_title"]', type: 'text' }, content: { selector: '#content, #tcepostcontent', type: 'tinymce' }, excerpt: { selector: '#hvac_post_excerpt', type: 'textarea' }, featured_image: { selector: '#hvac_featured_image_id', type: 'hidden' } }, taxonomies: { categories: { selector: 'input[name="tax_input[tribe_events_cat][]"]', type: 'checkbox' }, tags: { selector: '#hvac_tags_input', type: 'tags' } }, tec_core: { start_date: { selector: '#EventStartDate', type: 'date' }, end_date: { selector: '#EventEndDate', type: 'date' }, start_time: { selector: '#EventStartTime', type: 'time' }, end_time: { selector: '#EventEndTime', type: 'time' }, cost: { selector: '#EventCost', type: 'number' }, url: { selector: '#EventURL', type: 'url' } }, venue: { name: { selector: '#VenueVenue', type: 'text' }, address: { selector: '#VenueAddress', type: 'text' }, city: { selector: '#VenueCity', type: 'text' }, state: { selector: '#VenueStateProvince', type: 'text' }, zip: { selector: '#VenueZip', type: 'text' }, phone: { selector: '#VenuePhone', type: 'tel' }, url: { selector: '#VenueURL', type: 'url' } }, organizer: { name: { selector: '#OrganizerOrganizer', type: 'text' }, email: { selector: '#OrganizerEmail', type: 'email' }, phone: { selector: '#OrganizerPhone', type: 'tel' }, website: { selector: '#OrganizerWebsite', type: 'url' } } }; } /** * Generate large content for performance testing */ static generateLargeContent() { return `

Comprehensive HVAC Performance and Diagnostics Training Program

Executive Summary

This intensive training program is designed to provide HVAC professionals with comprehensive knowledge and practical skills in advanced diagnostics, performance optimization, and cutting-edge technology integration. The curriculum covers everything from fundamental principles to advanced troubleshooting techniques.

Program Overview

Our comprehensive HVAC training program spans multiple days and covers an extensive range of topics essential for modern HVAC professionals. Participants will gain hands-on experience with the latest diagnostic equipment, learn advanced troubleshooting methodologies, and understand the integration of smart technology in HVAC systems.

Day 1: Fundamentals and Diagnostics

Morning Session (8:30 AM - 12:00 PM)

Afternoon Session (1:00 PM - 5:30 PM)

Day 2: Electrical Systems and Troubleshooting

Morning Session (8:30 AM - 12:00 PM)

Afternoon Session (1:00 PM - 5:30 PM)

Day 3: Performance Optimization and Smart Technology

Morning Session (8:30 AM - 12:00 PM)

Afternoon Session (1:00 PM - 5:30 PM)

Learning Objectives

Upon completion of this comprehensive training program, participants will be able to:

  1. Perform Advanced Diagnostics: Utilize sophisticated diagnostic equipment to identify and resolve complex HVAC system issues efficiently and accurately.
  2. Analyze Electrical Systems: Diagnose and repair electrical components, including motors, capacitors, relays, and advanced control systems.
  3. Optimize System Performance: Implement energy efficiency measures and performance optimization strategies to maximize system effectiveness.
  4. Integrate Smart Technology: Install, configure, and maintain smart HVAC components and IoT devices for enhanced system control and monitoring.
  5. Conduct Energy Assessments: Perform comprehensive energy audits and recommend improvements for residential and commercial HVAC systems.
  6. Interpret Complex Data: Analyze system performance data, identify trends, and make informed recommendations for system improvements.
  7. Implement Preventive Maintenance: Develop and execute comprehensive maintenance programs to ensure optimal system performance and longevity.
  8. Communicate Effectively: Present findings and recommendations to customers in a clear, professional manner that builds trust and confidence.

Prerequisites and Requirements

Educational Background

Participants should have a solid foundation in HVAC principles and at least 2 years of hands-on experience in the field. Basic understanding of electrical circuits and mechanical systems is essential.

Required Equipment

Each participant should bring the following equipment:

Safety Requirements

All participants must adhere to strict safety protocols throughout the training. Personal protective equipment is mandatory during hands-on sessions.

Certification and Continuing Education

Upon successful completion of the program, participants will receive:

Instructor Information

This program is led by industry-recognized experts with decades of combined experience in HVAC design, installation, and service. Our instructors hold multiple industry certifications and stay current with the latest technology and best practices.

Registration and Logistics

Training Facility

The training takes place at our state-of-the-art facility equipped with the latest HVAC equipment and diagnostic tools. The facility features comfortable classroom spaces, hands-on training labs, and all necessary safety equipment.

Meals and Refreshments

Continental breakfast, lunch, and afternoon refreshments are provided each day. Special dietary requirements can be accommodated with advance notice.

Parking and Transportation

Free parking is available on-site. The facility is easily accessible by public transportation, and detailed directions will be provided upon registration.

Follow-up and Support

Our commitment to your success doesn't end when the training concludes. We provide ongoing support through:

Note: This comprehensive content is designed to test template performance with large, complex HTML content including multiple headings, lists, and formatted text sections.

`; } /** * Get random future date */ getRandomFutureDate(daysOffset = 0) { const today = new Date(); const futureDate = new Date(today); futureDate.setDate(today.getDate() + Math.floor(Math.random() * 90) + 30 + daysOffset); // 30-120 days in future return futureDate.toISOString().split('T')[0]; } /** * Get random time */ getRandomTime(isEndTime = false) { const startHour = isEndTime ? 14 : 8; // End times start from 2 PM, start times from 8 AM const endHour = isEndTime ? 20 : 13; // End times until 8 PM, start times until 1 PM const hour = Math.floor(Math.random() * (endHour - startHour)) + startHour; const minute = Math.random() < 0.5 ? '00' : '30'; return `${hour.toString().padStart(2, '0')}:${minute}`; } /** * Ensure required directories exist */ ensureDirectories() { Object.values(TEST_DATA_CONFIG.storage).forEach(dir => { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } }); } /** * Save session data */ async saveSessionData() { const sessionData = { timestamp: new Date().toISOString(), environment: this.environment, createdEvents: this.createdEvents, uploadedMedia: this.uploadedMedia, testSessions: this.testSessions }; const sessionFile = path.join(TEST_DATA_CONFIG.storage.dataDir, 'last-session.json'); fs.writeFileSync(sessionFile, JSON.stringify(sessionData, null, 2)); } /** * Delete created events (placeholder) */ async deleteCreatedEvents() { console.log(` πŸ—‘οΈ Cleaning up ${this.createdEvents.length} created events...`); // Implementation would depend on WordPress/TEC API or admin interface console.log(' ℹ️ Event deletion - implementation needed based on WordPress admin interface'); } /** * Delete uploaded media (placeholder) */ async deleteUploadedMedia() { console.log(` πŸ—‘οΈ Cleaning up ${this.uploadedMedia.length} uploaded media files...`); // Implementation would depend on WordPress media library API console.log(' ℹ️ Media cleanup - implementation needed based on WordPress media library'); } } /** * Run test data setup */ async function setupTestData(environment = 'staging') { const dataManager = new TestDataManager(environment); try { await dataManager.setupTestEnvironment(); console.log('\nβœ… Test data setup completed successfully'); return dataManager; } catch (error) { console.error('\n❌ Test data setup failed:', error.message); throw error; } } /** * Run test data cleanup */ async function cleanupTestData(dataManager) { try { await dataManager.cleanupTestEnvironment(); console.log('\nβœ… Test data cleanup completed successfully'); } catch (error) { console.error('\n❌ Test data cleanup failed:', error.message); } } // Export for module usage module.exports = { TestDataManager, setupTestData, cleanupTestData, TEST_DATA_CONFIG, TEST_DATA_SETS }; // Run if called directly if (require.main === module) { const command = process.argv[2]; const environment = process.argv[3] || 'staging'; if (command === 'setup') { setupTestData(environment); } else if (command === 'cleanup') { const dataManager = new TestDataManager(environment); cleanupTestData(dataManager); } else { console.log('Usage: node test-data-manager.js [setup|cleanup] [staging|production]'); } }