api-stats-logger
Version:
SDK completo de logging e monitoramento de APIs com auto-instrumentação, dashboard em tempo real e CLI para configuração automática
224 lines (182 loc) • 6.33 kB
JavaScript
/**
* Teste automatizado do fluxo da CLI
* Verifica se todas as funções críticas estão funcionando
*/
const ApiStatsCLI = require('./cli.js');
class CLITester {
constructor() {
this.tests = [];
this.results = [];
}
addTest(name, testFunction) {
this.tests.push({ name, testFunction });
}
async runTests() {
console.log('🧪 Iniciando testes do fluxo da CLI...\n');
for (const test of this.tests) {
try {
console.log(`▶️ Executando: ${test.name}`);
await test.testFunction();
this.results.push({ name: test.name, status: 'PASSOU', error: null });
console.log(`✅ PASSOU: ${test.name}\n`);
} catch (error) {
this.results.push({ name: test.name, status: 'FALHOU', error: error.message });
console.log(`❌ FALHOU: ${test.name} - ${error.message}\n`);
}
}
this.printSummary();
}
printSummary() {
console.log('📊 Resumo dos Testes:\n');
let passed = 0;
let failed = 0;
for (const result of this.results) {
const icon = result.status === 'PASSOU' ? '✅' : '❌';
console.log(`${icon} ${result.name}`);
if (result.error) {
console.log(` └── ${result.error}`);
}
if (result.status === 'PASSOU') passed++;
else failed++;
}
console.log(`\n📈 Total: ${this.results.length} testes`);
console.log(`✅ Passaram: ${passed}`);
console.log(`❌ Falharam: ${failed}`);
if (failed === 0) {
console.log('\n🎉 Todos os testes passaram!');
} else {
console.log('\n⚠️ Alguns testes falharam. Verifique os logs acima.');
process.exit(1);
}
}
}
// Testes específicos
const tester = new CLITester();
// Teste 1: Instanciação da CLI
tester.addTest('Instanciação da CLI', async () => {
const cli = new ApiStatsCLI();
if (!cli.baseUrl) throw new Error('baseUrl não configurado');
if (!cli.rl) throw new Error('readline não inicializado');
});
// Teste 2: Detecção de Framework
tester.addTest('Detecção de Framework', async () => {
const cli = new ApiStatsCLI();
const framework = cli.detectFramework();
// Deve retornar null ou um framework válido
if (framework && !['express', 'nestjs', 'fastify', 'koa'].includes(framework)) {
throw new Error(`Framework inválido detectado: ${framework}`);
}
});
// Teste 3: Validação de API Key (formato)
tester.addTest('Validação de formato de API Key', async () => {
const cli = new ApiStatsCLI();
// Teste com key válida da configuração
const fs = require('fs');
const path = require('path');
try {
const envContent = fs.readFileSync(path.join(__dirname, '.env.api-stats'), 'utf8');
const apiKeyMatch = envContent.match(/API_STATS_API_KEY=(.+)/);
if (apiKeyMatch && apiKeyMatch[1]) {
const apiKey = apiKeyMatch[1].trim();
if (apiKey.length < 32) {
throw new Error('API key muito curta');
}
}
} catch (error) {
// Se não conseguir ler .env, não é um erro crítico
console.log(' ⚠️ Não foi possível verificar API key do .env (normal se não configurado)');
}
});
// Teste 4: Configuração de Storage de Auth
tester.addTest('Storage de Autenticação', async () => {
const cli = new ApiStatsCLI();
// Testar armazenamento e recuperação
const testToken = 'test-token-123';
const testDeviceId = 'test-device-456';
cli.storeAuthData(testToken, testDeviceId);
const storedData = cli.getStoredAuthData();
if (!storedData || storedData.token !== testToken || storedData.deviceId !== testDeviceId) {
throw new Error('Falha ao armazenar/recuperar dados de autenticação');
}
// Limpar dados de teste
cli.clearStoredAuthData();
const clearedData = cli.getStoredAuthData();
if (clearedData && clearedData.token) {
throw new Error('Falha ao limpar dados de autenticação');
}
});
// Teste 5: Métodos de Question (sem input real)
tester.addTest('Métodos de Input', async () => {
const cli = new ApiStatsCLI();
// Verificar se métodos existem e são funções
if (typeof cli.question !== 'function') {
throw new Error('Método question não é uma função');
}
if (typeof cli.questionBoolean !== 'function') {
throw new Error('Método questionBoolean não é uma função');
}
if (typeof cli.cleanup !== 'function') {
throw new Error('Método cleanup não é uma função');
}
});
// Teste 6: Geração de Exemplos
tester.addTest('Geração de Exemplos de Framework', async () => {
const cli = new ApiStatsCLI();
const testConfig = {
service: 'test-service',
environment: 'test',
framework: 'express',
captureBody: true,
captureHeaders: true,
apiKey: 'test-key'
};
const examples = [
cli.getExpressExample(testConfig),
cli.getNestJSExample(testConfig),
cli.getFastifyExample(testConfig),
cli.getKoaExample(testConfig),
cli.getGenericExample(testConfig)
];
for (let i = 0; i < examples.length; i++) {
if (!examples[i] || examples[i].length < 100) {
throw new Error(`Exemplo ${i} muito curto ou vazio`);
}
}
});
// Teste 7: Cleanup de Recursos
tester.addTest('Cleanup de Recursos', async () => {
const cli = new ApiStatsCLI();
// Testar cleanup sem erros
await cli.cleanup();
// Verificar se readline foi limpo
if (cli.rl !== null) {
throw new Error('Readline não foi limpo corretamente');
}
});
// Teste 8: Configuração de URLs
tester.addTest('Configuração de URLs', async () => {
const cli = new ApiStatsCLI();
// Verificar se baseUrl está configurado corretamente
if (!cli.baseUrl.startsWith('http')) {
throw new Error('baseUrl não é uma URL válida');
}
// Verificar se é a URL da SquareCloud por padrão
if (!cli.baseUrl.includes('apistats.squareweb.app')) {
console.log(' ⚠️ baseUrl não é da SquareCloud (pode ser configuração local)');
}
});
// Executar todos os testes
async function main() {
try {
await tester.runTests();
} catch (error) {
console.error('❌ Erro fatal nos testes:', error.message);
process.exit(1);
}
}
// Executar se chamado diretamente
if (require.main === module) {
main();
}
module.exports = CLITester;