Files
SteelBase/public/js/tests/test-persistencia.js

310 lines
12 KiB
JavaScript

/**
* Script de Teste para Sistema de Persistência
* Testa as funcionalidades do AdminConfigManager e BackupManager
*/
class PersistenceTest {
constructor() {
this.tests = [];
this.results = [];
}
/**
* Executa todos os testes de persistência
*/
async runAllTests() {
console.log('🧪 Iniciando testes de persistência...');
// Aguardar carregamento dos módulos
await this.waitForModules();
// Executar testes
await this.testConfigPersistence();
await this.testBackupSystem();
await this.testThemePersistence();
await this.testResetFunctionality();
// Mostrar resultados
this.showResults();
console.log('✅ Testes de persistência concluídos!');
}
/**
* Aguarda os módulos necessários estarem carregados
*/
async waitForModules() {
console.log('⏳ Aguardando módulos...');
let attempts = 0;
const maxAttempts = 50; // 5 segundos
while (attempts < maxAttempts) {
// Verificar instâncias globais inicializadas pelos módulos
if (window.adminConfigManager && window.backupManager && window.toastManager) {
console.log('✅ Módulos (instâncias) carregados');
return;
}
// Como fallback, se as classes existirem mas instâncias ainda não, tentar inicializar
if (!window.adminConfigManager && typeof AdminConfigManager !== 'undefined') {
try { window.adminConfigManager = new AdminConfigManager(); } catch(e) {}
}
if (!window.backupManager && typeof BackupManager !== 'undefined') {
try { window.backupManager = new BackupManager(); } catch(e) {}
}
if (!window.toastManager && typeof ToastManager !== 'undefined') {
try { window.toastManager = new ToastManager(); } catch(e) {}
}
await new Promise(resolve => setTimeout(resolve, 100));
attempts++;
}
throw new Error('❌ Módulos não carregados após 5 segundos');
}
/**
* Testa persistência de configurações
*/
async testConfigPersistence() {
console.log('📝 Testando persistência de configurações...');
try {
// Criar instância do config manager
const configManager = new AdminConfigManager();
// Testar configuração inicial
const initialConfig = configManager.getConfig();
this.addResult('Config inicial', !!initialConfig, 'Configuração inicial carregada');
// Testar salvamento de configuração
configManager.updateConfig('app.name', 'Aço Calc Pro - Teste');
configManager.updateConfig('app.version', '2.0.0');
configManager.updateConfig('theme.name', 'light');
// Recarregar e verificar se persistiu
const configManager2 = new AdminConfigManager();
const config2 = configManager2.getConfig();
this.addResult('Salvamento app.name', config2.app.name === 'Aço Calc Pro - Teste', 'Nome da aplicação persistido');
this.addResult('Salvamento app.version', config2.app.version === '2.0.0', 'Versão persistida');
this.addResult('Salvamento theme.name', config2.theme.name === 'light', 'Tema persistido');
console.log('✅ Testes de persistência de configurações concluídos');
} catch (error) {
this.addResult('Config Persistence', false, `Erro: ${error.message}`);
console.error('❌ Erro nos testes de configuração:', error);
}
}
/**
* Testa sistema de backup
*/
async testBackupSystem() {
console.log('💾 Testando sistema de backup...');
try {
const backupManager = new BackupManager();
// Testar criação de backup
const backup = await backupManager.createBackup();
this.addResult('Criação backup', !!backup.id, 'Backup criado com ID');
// Testar listagem de backups
const backups = backupManager.getBackups();
this.addResult('Listagem backups', backups.length > 0, `${backups.length} backup(s) encontrado(s)`);
// Testar recuperação de backup específico (via lista)
const specificBackup = backups.find(b => b.timestamp === backup.timestamp);
this.addResult('Recuperação backup', !!specificBackup, 'Backup recuperado por timestamp');
// Testar remoção de backup (usar timestamp)
backupManager.removeBackup(backup.timestamp);
const backupsAfterRemove = backupManager.getBackups();
this.addResult('Remoção backup', backupsAfterRemove.length === backups.length - 1, 'Backup removido com sucesso');
console.log('✅ Testes de backup concluídos');
} catch (error) {
this.addResult('Backup System', false, `Erro: ${error.message}`);
console.error('❌ Erro nos testes de backup:', error);
}
}
/**
* Testa persistência de tema
*/
async testThemePersistence() {
console.log('🎨 Testando persistência de tema...');
try {
const configManager = new AdminConfigManager();
// Testar diferentes temas
const themes = ['dark', 'light', 'auto'];
for (const theme of themes) {
configManager.updateConfig('theme.name', theme);
// Recarregar e verificar
const configManager2 = new AdminConfigManager();
const config2 = configManager2.getConfig();
this.addResult(`Tema ${theme}`, config2.theme.name === theme, `Tema ${theme} persistido`);
}
console.log('✅ Testes de tema concluídos');
} catch (error) {
this.addResult('Theme Persistence', false, `Erro: ${error.message}`);
console.error('❌ Erro nos testes de tema:', error);
}
}
/**
* Testa funcionalidade de reset
*/
async testResetFunctionality() {
console.log('🔄 Testando funcionalidade de reset...');
try {
const configManager = new AdminConfigManager();
// Modificar configurações
configManager.updateConfig('app.name', 'Nome Modificado');
configManager.updateConfig('app.version', '9.9.9');
// Resetar
configManager.resetConfig();
// Verificar se voltou ao padrão
const config = configManager.getConfig();
// Estrutura padrão usa chaves top-level: appName e version
const isDefaultName = config.appName === 'AÇO CALC PRO';
const isDefaultVersion = config.version === '1.0.0';
this.addResult('Reset app.name', isDefaultName, 'Nome resetado para padrão');
this.addResult('Reset app.version', isDefaultVersion, 'Versão resetada para padrão');
console.log('✅ Testes de reset concluídos');
} catch (error) {
this.addResult('Reset Functionality', false, `Erro: ${error.message}`);
console.error('❌ Erro nos testes de reset:', error);
}
}
/**
* Adiciona resultado de teste
*/
addResult(testName, success, message) {
this.results.push({
name: testName,
success: success,
message: message,
timestamp: new Date().toISOString()
});
const status = success ? '✅' : '❌';
console.log(`${status} ${testName}: ${message}`);
}
/**
* Mostra resultados dos testes
*/
showResults() {
const totalTests = this.results.length;
const passedTests = this.results.filter(r => r.success).length;
const failedTests = totalTests - passedTests;
console.log('\n📊 RESUMO DOS TESTES:');
console.log(`Total de testes: ${totalTests}`);
console.log(`✅ Passou: ${passedTests}`);
console.log(`❌ Falhou: ${failedTests}`);
console.log(`Taxa de sucesso: ${((passedTests / totalTests) * 100).toFixed(1)}%`);
// Mostrar falhas em detalhes
if (failedTests > 0) {
console.log('\n📋 FALHAS DETALHADAS:');
this.results.filter(r => !r.success).forEach(result => {
console.log(`${result.name}: ${result.message}`);
});
}
// Testar se o ToastManager está disponível para mostrar resultado
if (window.toastManager) {
const successRate = (passedTests / totalTests) * 100;
if (successRate === 100) {
window.toastManager.success(`🧪 Todos os testes de persistência passaram! (${passedTests}/${totalTests})`);
} else if (successRate >= 80) {
window.toastManager.warning(`🧪 ${passedTests}/${totalTests} testes passaram (${successRate.toFixed(1)}%)`);
} else {
window.toastManager.error(`🧪 Apenas ${passedTests}/${totalTests} testes passaram (${successRate.toFixed(1)}%)`);
}
}
}
}
// Função para testar persistência após reload
function testarPersistenciaAposReload() {
console.log('🔄 Testando persistência após reload da página...');
// Salvar configuração de teste
if (window.adminConfigManager) {
window.adminConfigManager.updateConfig('app.name', 'Aço Calc Pro - Teste Reload');
window.adminConfigManager.updateConfig('theme.name', 'light');
console.log('✅ Configurações de teste salvas');
console.log('🔄 Recarregando página em 2 segundos...');
setTimeout(() => {
location.reload();
}, 2000);
} else {
// Verificar se as configurações persistiram após reload
if (window.adminConfigManager) {
const config = window.adminConfigManager.getConfig();
if (config.app.name === 'Aço Calc Pro - Teste Reload') {
console.log('✅ Persistência após reload: SUCESSO!');
if (window.toastManager) {
window.toastManager.success('✅ Configurações persistiram após reload!');
}
} else {
console.log('❌ Persistência após reload: FALHA');
if (window.toastManager) {
window.toastManager.error('❌ Configurações não persistiram após reload');
}
}
}
}
}
// Auto-executar testes quando os módulos estiverem prontos
if (typeof window !== 'undefined') {
window.addEventListener('load', async () => {
console.log('🧪 Sistema de testes de persistência carregado');
// Aguardar um pouco para garantir que tudo está carregado
setTimeout(async () => {
try {
const tester = new PersistenceTest();
await tester.runAllTests();
} catch (error) {
console.error('❌ Erro ao executar testes:', error);
}
}, 1000);
});
}
// Disponibilizar funções globalmente para testes manuais
window.testarPersistencia = () => {
const tester = new PersistenceTest();
tester.runAllTests();
};
window.testarPersistenciaAposReload = testarPersistenciaAposReload;
console.log('🧪 Sistema de testes de persistência inicializado');