All files / services/qualimetrie testAgent.ts

100% Statements 38/38
66.66% Branches 8/12
100% Functions 3/3
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 975x 5x 5x                                                         5x     3x   3x 3x       2x 2x   2x 2x 1x 1x             1x 1x 1x           1x   2x 2x       5x     1x     2x 2x 2x 1x 1x 1x   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x      
import { execSync } from 'child_process';
import fs from 'fs/promises';
import path from 'path';
import { Command } from 'commander';
 
export interface TestAgentOptions {}
 
export interface TestAgentResult {
  success: boolean;
  metrics?: {
    lines: number;
    functions: number;
    branches: number;
    statements: number;
  };
  summary?: {
    total: number;
    passed: number;
    failed: number;
    duration: string;
  };
  output?: string;
}
 
/**
 * Exécute les tests et collecte le rapport de couverture.
 */
 
/**
 * Exécute les tests Jest avec couverture (json-summary) et retourne les métriques globales.
 */
export async function testAgent(
  _opts?: TestAgentOptions,
): Promise<TestAgentResult> {
  try {
    // Run Jest to generate coverage summary and test results JSON
    const start = Date.now();
    execSync(
      'pnpm exec jest --coverage --coverageReporters=json-summary --json --outputFile=jest-results.json',
      { stdio: 'inherit' },
    );
    const durationMs = Date.now() - start;
    const duration = `${(durationMs / 1000).toFixed(2)}s`;
    // Read coverage-summary.json
    const summaryPath = path.resolve(process.cwd(), 'coverage', 'coverage-summary.json');
    const raw = await fs.readFile(summaryPath, 'utf8');
    const data = JSON.parse(raw).total;
    const metrics = {
      lines: data.lines.pct,
      functions: data.functions.pct,
      branches: data.branches.pct,
      statements: data.statements.pct,
    };
    // Read test summary
    const resultsRaw = await fs.readFile(path.resolve(process.cwd(), 'jest-results.json'), 'utf8');
    const results = JSON.parse(resultsRaw);
    const summary = {
      total: results.numTotalTests ?? 0,
      passed: results.numPassedTests ?? 0,
      failed: results.numFailedTests ?? 0,
      duration,
    };
    return { success: true, metrics, summary };
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : String(err);
    return { success: false, output: msg };
  }
}
 
export const cli = {
  command: 'qualimetrie:test',
  description: 'Exécute les tests et génère un rapport de couverture',
  builder: (cmd: Command) => cmd,
  handler: async (_opts: unknown) => {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const { testAgent: run } = require('./testAgent');
    const res = await run();
    if (!res.success || !res.metrics || !res.summary) {
      console.error(`❌ Erreur lors de l'exécution des tests ou de la collecte de couverture:`);
      console.error(res.output);
      process.exit(1);
    }
    const { metrics, summary } = res;
    // Génération du rapport Markdown
    console.log('Test Summary:');
    console.log(`- Total: ${summary.total}`);
    console.log(`- Passed: ${summary.passed}`);
    console.log(`- Failed: ${summary.failed}`);
    console.log(`- Duration: ${summary.duration}`);
    console.log('Coverage Summary:');
    console.log(`- Lines: **${metrics.lines}%**`);
    console.log(`- Functions: **${metrics.functions}%**`);
    console.log(`- Branches: **${metrics.branches}%**`);
    console.log(`- Statements: **${metrics.statements}%**`);
  },
};