Spaces:
Running
Running
File size: 14,386 Bytes
0d110c2 759768a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
/**
* GreenPlus by GXS Comprehensive Test Suite
* Automated testing for all environmental analysis tools
*/
import { analyzeAudioForSpecies } from './audioAnalysis';
import { analyzeWaterImage, waterQualityAnalyzer } from './imageAnalysis';
import { waterQualityDB } from './waterQualityDatabase';
import { biodiversityDB } from './biodiversityDatabase';
import { systemHealthChecker } from './systemHealth';
import { accuracyValidator } from './accuracyValidator';
export class EcoSpireTestSuite {
constructor() {
this.testResults = {
passed: 0,
failed: 0,
warnings: 0,
tests: []
};
}
/**
* Run all tests
*/
async runAllTests() {
console.log('π§ͺ Starting GreenPlus by GXS Test Suite...');
this.testResults = {
passed: 0,
failed: 0,
warnings: 0,
tests: []
};
// Core functionality tests
await this.testSystemHealth();
await this.testDatabases();
await this.testAudioAnalysis();
await this.testWaterQualityAnalysis();
await this.testAccuracyValidation();
// Integration tests
await this.testDataPersistence();
await this.testErrorHandling();
await this.testPerformance();
// Generate report
const report = this.generateTestReport();
console.log('π Test Results:', report);
return report;
}
/**
* Test system health monitoring
*/
async testSystemHealth() {
const testName = 'System Health Check';
try {
console.log('π Testing system health...');
const healthStatus = await systemHealthChecker.performHealthCheck();
this.assert(healthStatus.overall !== 'unknown', 'Health check completed');
this.assert(Object.keys(healthStatus.components).length > 0, 'Components checked');
this.assert(healthStatus.lastCheck !== null, 'Timestamp recorded');
if (healthStatus.overall === 'error') {
this.addWarning(testName, 'System health shows errors: ' + healthStatus.errors.join(', '));
}
this.addTest(testName, 'passed', 'System health monitoring working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test database functionality
*/
async testDatabases() {
await this.testWaterQualityDB();
await this.testBiodiversityDB();
}
async testWaterQualityDB() {
const testName = 'Water Quality Database';
try {
console.log('π§ Testing water quality database...');
// Test initialization
await waterQualityDB.init();
this.assert(waterQualityDB.db !== null, 'Database initialized');
// Test data operations
const testData = {
id: 'test_' + Date.now(),
waterSource: 'Test Water',
results: { ph: 7.0, chlorine: 1.0 },
overallQuality: 'Good',
safetyLevel: 'Safe',
confidence: 95
};
await waterQualityDB.saveWaterTest(testData);
const retrieved = await waterQualityDB.getAllWaterTests(1);
this.assert(retrieved.length > 0, 'Data saved and retrieved');
this.assert(retrieved[0].id === testData.id, 'Data integrity maintained');
this.addTest(testName, 'passed', 'Database operations working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
async testBiodiversityDB() {
const testName = 'Biodiversity Database';
try {
console.log('π¦ Testing biodiversity database...');
await biodiversityDB.init();
this.assert(biodiversityDB.db !== null, 'Database initialized');
const testData = {
id: 'test_bio_' + Date.now(),
habitat: 'Test Habitat',
detectedSpecies: [{ name: 'Test Bird', confidence: 85 }],
biodiversityMetrics: { speciesRichness: 1, ecosystemHealth: 'Good' }
};
await biodiversityDB.saveRecording(testData);
const retrieved = await biodiversityDB.getAllRecordings(1);
this.assert(retrieved.length > 0, 'Recording saved and retrieved');
this.addTest(testName, 'passed', 'Database operations working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test audio analysis functionality
*/
async testAudioAnalysis() {
const testName = 'Audio Analysis';
try {
console.log('π΅ Testing audio analysis...');
// Test with mock data (since we can't generate real audio in tests)
const mockAudioBlob = new Blob(['mock audio data'], { type: 'audio/wav' });
const result = await analyzeAudioForSpecies(mockAudioBlob, 'North America', 'Urban Park');
this.assert(result !== null, 'Analysis completed');
this.assert(result.detectedSpecies !== undefined, 'Species detection attempted');
this.assert(result.biodiversityMetrics !== undefined, 'Biodiversity metrics calculated');
this.assert(result.confidence !== undefined, 'Confidence score provided');
this.assert(result.recommendations !== undefined, 'Recommendations generated');
// Test accuracy validation
const validation = await accuracyValidator.validateBiodiversityAccuracy(result);
this.assert(validation.accuracy !== undefined, 'Accuracy validation working');
this.addTest(testName, 'passed', 'Audio analysis pipeline working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test water quality analysis
*/
async testWaterQualityAnalysis() {
const testName = 'Water Quality Analysis';
try {
console.log('π§ Testing water quality analysis...');
// Create a mock image (canvas-based)
const canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 300;
const ctx = canvas.getContext('2d');
// Draw a simple test pattern
ctx.fillStyle = '#ff0000';
ctx.fillRect(0, 0, 100, 100);
ctx.fillStyle = '#00ff00';
ctx.fillRect(100, 0, 100, 100);
ctx.fillStyle = '#0000ff';
ctx.fillRect(200, 0, 100, 100);
const mockImageData = canvas.toDataURL('image/png');
const result = await analyzeWaterImage(mockImageData, 'Tap Water');
this.assert(result !== null, 'Analysis completed');
this.assert(result.ph !== undefined, 'pH analysis performed');
this.assert(result.chlorine !== undefined, 'Chlorine analysis performed');
this.assert(result.confidence !== undefined, 'Confidence score provided');
// Test quality assessment
const assessment = waterQualityAnalyzer.assessWaterQuality(result);
this.assert(assessment.quality !== undefined, 'Quality assessment performed');
this.assert(assessment.safety !== undefined, 'Safety assessment performed');
this.addTest(testName, 'passed', 'Water quality analysis working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test accuracy validation system
*/
async testAccuracyValidation() {
const testName = 'Accuracy Validation';
try {
console.log('π― Testing accuracy validation...');
// Test water quality validation
const mockWaterResult = {
ph: 7.0,
chlorine: 1.5,
nitrates: 5,
hardness: 120,
alkalinity: 100,
bacteria: 0,
confidence: 90
};
const waterValidation = await accuracyValidator.validateWaterQualityAccuracy(mockWaterResult);
this.assert(waterValidation.accuracy !== undefined, 'Water quality validation working');
// Test biodiversity validation
const mockBioResult = {
detectedSpecies: [
{ name: 'Test Bird', confidence: 85, scientificName: 'Testus birdus', habitat: 'Test' }
],
biodiversityMetrics: { speciesRichness: 1, ecosystemHealth: 'Good' }
};
const bioValidation = await accuracyValidator.validateBiodiversityAccuracy(mockBioResult);
this.assert(bioValidation.accuracy !== undefined, 'Biodiversity validation working');
// Test overall validation
const overallValidation = await accuracyValidator.validateOverallAccuracy();
this.assert(overallValidation.overallAccuracy !== undefined, 'Overall validation working');
this.addTest(testName, 'passed', 'Accuracy validation system working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test data persistence
*/
async testDataPersistence() {
const testName = 'Data Persistence';
try {
console.log('πΎ Testing data persistence...');
// Test localStorage
const testKey = 'ecospire_test_' + Date.now();
const testValue = { test: 'data', timestamp: Date.now() };
localStorage.setItem(testKey, JSON.stringify(testValue));
const retrieved = JSON.parse(localStorage.getItem(testKey));
this.assert(retrieved.test === testValue.test, 'localStorage working');
localStorage.removeItem(testKey);
// Test IndexedDB (basic check)
this.assert('indexedDB' in window, 'IndexedDB available');
this.addTest(testName, 'passed', 'Data persistence working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test error handling
*/
async testErrorHandling() {
const testName = 'Error Handling';
try {
console.log('β οΈ Testing error handling...');
// Test invalid audio data
try {
await analyzeAudioForSpecies(null, 'North America', 'Urban Park');
this.addWarning(testName, 'Audio analysis should reject null input');
} catch (error) {
this.assert(error.message.includes('No audio data'), 'Audio error handling working');
}
// Test invalid image data
try {
await analyzeWaterImage(null, 'Tap Water');
this.addWarning(testName, 'Image analysis should reject null input');
} catch (error) {
this.assert(error.message.includes('No image source'), 'Image error handling working');
}
this.addTest(testName, 'passed', 'Error handling working');
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Test performance
*/
async testPerformance() {
const testName = 'Performance';
try {
console.log('β‘ Testing performance...');
const startTime = performance.now();
// Run a quick analysis
const mockAudioBlob = new Blob(['mock'], { type: 'audio/wav' });
await analyzeAudioForSpecies(mockAudioBlob, 'North America', 'Urban Park');
const endTime = performance.now();
const duration = endTime - startTime;
this.assert(duration < 10000, 'Analysis completes within 10 seconds'); // Generous limit
if (duration > 5000) {
this.addWarning(testName, `Analysis took ${duration.toFixed(0)}ms (>5s)`);
}
this.addTest(testName, 'passed', `Performance acceptable (${duration.toFixed(0)}ms)`);
} catch (error) {
this.addTest(testName, 'failed', error.message);
}
}
/**
* Helper methods
*/
assert(condition, message) {
if (!condition) {
throw new Error(`Assertion failed: ${message}`);
}
}
addTest(name, status, message) {
this.testResults.tests.push({ name, status, message, timestamp: new Date().toISOString() });
if (status === 'passed') this.testResults.passed++;
else if (status === 'failed') this.testResults.failed++;
}
addWarning(testName, message) {
this.testResults.warnings++;
console.warn(`β οΈ ${testName}: ${message}`);
}
generateTestReport() {
const total = this.testResults.passed + this.testResults.failed;
const successRate = total > 0 ? (this.testResults.passed / total * 100).toFixed(1) : 0;
return {
summary: {
total: total,
passed: this.testResults.passed,
failed: this.testResults.failed,
warnings: this.testResults.warnings,
successRate: `${successRate}%`
},
details: this.testResults.tests,
timestamp: new Date().toISOString(),
systemReady: this.testResults.failed === 0 && this.testResults.warnings < 3
};
}
/**
* Run quick health check
*/
async quickHealthCheck() {
console.log('π₯ Running quick health check...');
const checks = {
browserAPIs: this.checkBrowserAPIs(),
localStorage: this.checkLocalStorage(),
databases: await this.checkDatabases(),
utilities: await this.checkUtilities()
};
const passedChecks = Object.values(checks).filter(Boolean).length;
const totalChecks = Object.keys(checks).length;
return {
status: passedChecks === totalChecks ? 'healthy' : 'warning',
score: Math.round((passedChecks / totalChecks) * 100),
checks: checks,
message: `${passedChecks}/${totalChecks} health checks passed`
};
}
checkBrowserAPIs() {
return !!(window.AudioContext || window.webkitAudioContext) &&
!!navigator.mediaDevices &&
!!window.indexedDB &&
!!window.localStorage;
}
checkLocalStorage() {
try {
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
return true;
} catch (e) {
return false;
}
}
async checkDatabases() {
try {
await waterQualityDB.init();
await biodiversityDB.init();
return true;
} catch (e) {
return false;
}
}
async checkUtilities() {
try {
return typeof analyzeAudioForSpecies === 'function' &&
typeof analyzeWaterImage === 'function' &&
typeof systemHealthChecker === 'object';
} catch (e) {
return false;
}
}
}
// Create singleton instance
export const testSuite = new EcoSpireTestSuite();
// Auto-run quick health check in development
if (process.env.NODE_ENV === 'development') {
testSuite.quickHealthCheck().then(result => {
console.log('π₯ Quick Health Check:', result.status, `(${result.score}%)`);
});
}
export default testSuite; |