#!/usr/bin/env node /** * INJECTION AUTOMATIQUE DE L'AUTO-REPORTER DANS TOUS LES TESTS * Modifie automatiquement tous les fichiers .test.js pour inclure l'AutoReporter */ import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const projectRoot = path.join(__dirname, '..'); function findTestFiles(dir) { const testFiles = []; function scanDir(currentDir) { const items = fs.readdirSync(currentDir); for (const item of items) { const fullPath = path.join(currentDir, item); const stat = fs.statSync(fullPath); if (stat.isDirectory()) { scanDir(fullPath); } else if (item.endsWith('.test.js')) { testFiles.push(fullPath); } } } scanDir(dir); return testFiles; } // Code à injecter const AUTOREPORTER_IMPORT = `import { AutoReporter } from './reporters/AutoReporter.js';`; const AUTOREPORTER_RELATIVE_IMPORT = `import { AutoReporter } from '../reporters/AutoReporter.js';`; const AUTOREPORTER_INIT = `const autoReporter = new AutoReporter();`; function getRelativeImportPath(filePath) { const testDir = path.dirname(filePath); const reportersPath = path.join(projectRoot, 'tests', 'reporters', 'AutoReporter.js'); // Calculer le chemin relatif depuis le fichier de test vers AutoReporter const relativePath = path.relative(testDir, reportersPath); // Normaliser pour utiliser des slashes (même sur Windows) const normalizedPath = relativePath.replace(/\\/g, '/'); // Si le fichier est dans le répertoire tests/, utiliser ./ if (normalizedPath.startsWith('../')) { return normalizedPath; } else { return './' + normalizedPath; } } async function injectAutoReporterIntoFile(filePath) { try { const content = fs.readFileSync(filePath, 'utf8'); // Vérifier si AutoReporter est déjà importé if (content.includes('AutoReporter')) { console.log(`⏭️ SKIP: ${filePath} (AutoReporter déjà présent)`); return false; } // Calculer l'import relatif correct const relativeImportPath = getRelativeImportPath(filePath); const autoReporterImport = `import { AutoReporter } from '${relativeImportPath}';`; const lines = content.split('\n'); let modifiedLines = [...lines]; let hasImports = false; let importInsertIndex = 0; let initInsertIndex = 0; // Trouver où insérer l'import for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (line.startsWith('import ')) { hasImports = true; importInsertIndex = i + 1; } else if (hasImports && !line.startsWith('import ') && line !== '') { break; } } // Si pas d'imports, insérer au début if (!hasImports) { importInsertIndex = 0; } // Trouver où insérer l'initialisation (après les imports et avant le premier test) for (let i = importInsertIndex; i < lines.length; i++) { const line = lines[i].trim(); if (line.startsWith('test(') || line.startsWith('describe(')) { initInsertIndex = i; break; } } // Insérer l'import modifiedLines.splice(importInsertIndex, 0, autoReporterImport); // Insérer l'initialisation (avec décalage car on a ajouté une ligne) const actualInitIndex = initInsertIndex + 1; modifiedLines.splice(actualInitIndex, 0, '', '// Auto-Reporter Configuration', AUTOREPORTER_INIT, ''); const newContent = modifiedLines.join('\n'); // Écrire le fichier modifié fs.writeFileSync(filePath, newContent, 'utf8'); console.log(`✅ MODIFIÉ: ${filePath}`); return true; } catch (error) { console.error(`❌ ERREUR: ${filePath} - ${error.message}`); return false; } } async function main() { console.log('🔧 === INJECTION AUTO-REPORTER DANS TOUS LES TESTS ==='); let modifiedFiles = 0; let totalFiles = 0; try { const testsDir = path.join(projectRoot, 'tests'); const files = findTestFiles(testsDir); console.log(`\n📋 Trouvé ${files.length} fichiers de test`); for (const file of files) { // Skip certains fichiers spéciaux const fileName = path.basename(file); if (fileName.includes('AutoReporter') || fileName.includes('commonjs-bridge')) { console.log(`⏭️ SKIP: ${file} (fichier système)`); continue; } totalFiles++; const wasModified = await injectAutoReporterIntoFile(file); if (wasModified) { modifiedFiles++; } } } catch (error) { console.error(`❌ Erreur lors de la recherche des fichiers:`, error.message); } console.log(`\n📊 === RÉSUMÉ ===`); console.log(`📁 Fichiers traités: ${totalFiles}`); console.log(`✅ Fichiers modifiés: ${modifiedFiles}`); console.log(`⏭️ Fichiers déjà configurés: ${totalFiles - modifiedFiles}`); if (modifiedFiles > 0) { console.log('\n🎉 AutoReporter injecté avec succès dans tous les tests !'); console.log('💡 Vous pouvez maintenant lancer: npm run test:all-with-reporter'); } } main().catch(console.error);