![]() Server : Apache/2 System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64 User : gositeme ( 1004) PHP Version : 8.2.29 Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname Directory : /home/gositeme/domains/lavocat.ca/public_html/scripts/ |
const WebSocket = require('ws');
const fetch = require('node-fetch');
// Test configuration
const BASE_URL = 'https://localhost:3443';
const WS_URL = 'wss://localhost:3443/_ws';
const TEST_CASE_ID = 'test-case-123';
const TEST_USER_ID = 'test-user-123';
// Test results tracking
let testResults = {
passed: 0,
failed: 0,
total: 0,
errors: []
};
// Utility functions
const log = (message, type = 'info') => {
const timestamp = new Date().toISOString();
const colors = {
info: '\x1b[36m', // Cyan
success: '\x1b[32m', // Green
error: '\x1b[31m', // Red
warning: '\x1b[33m', // Yellow
reset: '\x1b[0m' // Reset
};
console.log(`${colors[type]}[${timestamp}] ${message}${colors.reset}`);
};
const assert = (condition, message) => {
testResults.total++;
if (condition) {
testResults.passed++;
log(`✅ PASS: ${message}`, 'success');
} else {
testResults.failed++;
testResults.errors.push(message);
log(`❌ FAIL: ${message}`, 'error');
}
};
const testWebSocketConnection = () => {
return new Promise((resolve, reject) => {
log('🔌 Testing WebSocket connection...', 'info');
const ws = new WebSocket(WS_URL);
let connected = false;
let messageReceived = false;
const timeout = setTimeout(() => {
if (!connected) {
reject(new Error('WebSocket connection timeout'));
}
}, 5000);
ws.on('open', () => {
log('WebSocket connection opened', 'success');
connected = true;
clearTimeout(timeout);
// Send a test message
const testMessage = {
type: 'JOIN_CASE_CHAT',
data: { caseId: TEST_CASE_ID }
};
ws.send(JSON.stringify(testMessage));
});
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
log(`Received message: ${message.type}`, 'info');
messageReceived = true;
if (message.type === 'CASE_CHAT_JOINED') {
assert(message.data.caseId === TEST_CASE_ID, 'Case chat join confirmation');
ws.close();
resolve(true);
}
} catch (error) {
log(`Error parsing message: ${error.message}`, 'error');
}
});
ws.on('error', (error) => {
log(`WebSocket error: ${error.message}`, 'error');
clearTimeout(timeout);
reject(error);
});
ws.on('close', () => {
log('WebSocket connection closed', 'info');
});
});
};
const testCaseChatMessagesAPI = async () => {
log('📡 Testing Case Chat Messages API...', 'info');
try {
// Test the API endpoint
const response = await fetch(`${BASE_URL}/api/public/cases/${TEST_CASE_ID}/chat-messages`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
// Note: In a real test, you'd need proper authentication
}
});
assert(response.status === 401, 'API requires authentication');
log('API authentication check passed', 'success');
} catch (error) {
log(`API test error: ${error.message}`, 'error');
assert(false, 'API endpoint accessible');
}
};
const testDatabaseSchema = async () => {
log('🗄️ Testing database schema...', 'info');
try {
// Test if the CaseChatMessage table exists by checking the API
const response = await fetch(`${BASE_URL}/api/public/cases/${TEST_CASE_ID}/chat-messages?page=1&limit=10`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
// Should get 401 (unauthorized) but not 500 (server error)
assert(response.status === 401, 'Database schema accessible');
log('Database schema test passed', 'success');
} catch (error) {
log(`Database test error: ${error.message}`, 'error');
assert(false, 'Database schema working');
}
};
const testComponentImports = () => {
log('🧩 Testing component imports...', 'info');
try {
// Test if components can be imported
const LiveCaseChat = require('../src/components/LiveCaseChat.tsx');
assert(true, 'LiveCaseChat component importable');
const WebSocketContext = require('../src/context/EnhancedWebSocketContext.tsx');
assert(true, 'WebSocket context importable');
log('Component imports test passed', 'success');
} catch (error) {
log(`Component import error: ${error.message}`, 'error');
assert(false, 'Component imports working');
}
};
const testFileStructure = () => {
log('📁 Testing file structure...', 'info');
const fs = require('fs');
const path = require('path');
const requiredFiles = [
'src/components/LiveCaseChat.tsx',
'src/context/EnhancedWebSocketContext.tsx',
'src/pages/api/_ws.ts',
'src/pages/api/public/cases/[id]/chat-messages.ts',
'prisma/schema.prisma'
];
requiredFiles.forEach(file => {
const filePath = path.join(__dirname, '..', file);
const exists = fs.existsSync(filePath);
assert(exists, `File exists: ${file}`);
});
log('File structure test passed', 'success');
};
const testWebSocketMessageHandling = () => {
return new Promise((resolve, reject) => {
log('💬 Testing WebSocket message handling...', 'info');
const ws = new WebSocket(WS_URL);
let testCompleted = false;
const timeout = setTimeout(() => {
if (!testCompleted) {
ws.close();
reject(new Error('Message handling test timeout'));
}
}, 10000);
ws.on('open', () => {
// Test case chat message
const chatMessage = {
type: 'CASE_MESSAGE',
data: {
caseId: TEST_CASE_ID,
content: 'Test message from automated test',
senderId: TEST_USER_ID,
senderName: 'Test User',
senderRole: 'USER',
timestamp: Date.now(),
isPublic: true
}
};
ws.send(JSON.stringify(chatMessage));
// Test typing indicator
const typingMessage = {
type: 'CASE_TYPING',
data: {
caseId: TEST_CASE_ID,
userId: TEST_USER_ID,
userName: 'Test User',
isTyping: true,
timestamp: Date.now()
}
};
setTimeout(() => {
ws.send(JSON.stringify(typingMessage));
}, 1000);
});
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
log(`Received: ${message.type}`, 'info');
if (message.type === 'CASE_MESSAGE') {
assert(message.data.content === 'Test message from automated test', 'Message content preserved');
testCompleted = true;
clearTimeout(timeout);
ws.close();
resolve(true);
}
} catch (error) {
log(`Message parsing error: ${error.message}`, 'error');
}
});
ws.on('error', (error) => {
log(`WebSocket error: ${error.message}`, 'error');
clearTimeout(timeout);
reject(error);
});
});
};
const runAllTests = async () => {
log('🚀 Starting Live Chat System Tests...', 'info');
log('=' * 50, 'info');
try {
// Test 1: File structure
testFileStructure();
// Test 2: Component imports
testComponentImports();
// Test 3: Database schema
await testDatabaseSchema();
// Test 4: API endpoints
await testCaseChatMessagesAPI();
// Test 5: WebSocket connection
await testWebSocketConnection();
// Test 6: Message handling
await testWebSocketMessageHandling();
} catch (error) {
log(`Test execution error: ${error.message}`, 'error');
}
// Print results
log('=' * 50, 'info');
log(`📊 Test Results:`, 'info');
log(`✅ Passed: ${testResults.passed}`, 'success');
log(`❌ Failed: ${testResults.failed}`, 'error');
log(`📈 Total: ${testResults.total}`, 'info');
if (testResults.errors.length > 0) {
log('❌ Failed Tests:', 'error');
testResults.errors.forEach(error => {
log(` - ${error}`, 'error');
});
}
const successRate = ((testResults.passed / testResults.total) * 100).toFixed(1);
log(`🎯 Success Rate: ${successRate}%`, successRate >= 80 ? 'success' : 'warning');
if (testResults.failed === 0) {
log('🎉 All tests passed! Live chat system is ready!', 'success');
} else {
log('⚠️ Some tests failed. Please check the errors above.', 'warning');
}
};
// Run tests if this script is executed directly
if (require.main === module) {
runAllTests().catch(error => {
log(`Fatal error: ${error.message}`, 'error');
process.exit(1);
});
}
module.exports = {
runAllTests,
testResults
};