|
| 1 | +import { writeFile } from 'node:fs/promises'; |
| 2 | +import { relative } from 'pathe'; |
| 3 | +import stripAnsi from 'strip-ansi'; |
| 4 | +import type { |
| 5 | + Duration, |
| 6 | + GetSourcemap, |
| 7 | + Reporter, |
| 8 | + TestFileResult, |
| 9 | + TestResult, |
| 10 | +} from '../types'; |
| 11 | +import { getTaskNameWithPrefix } from '../utils'; |
| 12 | +import { formatStack, parseErrorStacktrace } from '../utils/error'; |
| 13 | + |
| 14 | +interface JUnitTestCase { |
| 15 | + name: string; |
| 16 | + classname: string; |
| 17 | + time: number; |
| 18 | + status: string; |
| 19 | + errors?: { |
| 20 | + message: string; |
| 21 | + type: string; |
| 22 | + details?: string; |
| 23 | + }[]; |
| 24 | +} |
| 25 | + |
| 26 | +interface JUnitTestSuite { |
| 27 | + name: string; |
| 28 | + tests: number; |
| 29 | + failures: number; |
| 30 | + errors: number; |
| 31 | + skipped: number; |
| 32 | + time: number; |
| 33 | + timestamp: string; |
| 34 | + testcases: JUnitTestCase[]; |
| 35 | +} |
| 36 | + |
| 37 | +interface JUnitReport { |
| 38 | + testsuites: { |
| 39 | + name: string; |
| 40 | + tests: number; |
| 41 | + failures: number; |
| 42 | + errors: number; |
| 43 | + skipped: number; |
| 44 | + time: number; |
| 45 | + timestamp: string; |
| 46 | + testsuite: JUnitTestSuite[]; |
| 47 | + }; |
| 48 | +} |
| 49 | + |
| 50 | +export class JUnitReporter implements Reporter { |
| 51 | + private rootPath: string; |
| 52 | + private outputPath?: string; |
| 53 | + |
| 54 | + constructor({ |
| 55 | + rootPath, |
| 56 | + options: { outputPath } = {}, |
| 57 | + }: { |
| 58 | + rootPath: string; |
| 59 | + options?: { outputPath?: string }; |
| 60 | + }) { |
| 61 | + this.rootPath = rootPath; |
| 62 | + this.outputPath = outputPath; |
| 63 | + } |
| 64 | + |
| 65 | + private sanitizeXml(text: string): string { |
| 66 | + let result = ''; |
| 67 | + |
| 68 | + // XML 1.0 valid chars: \x09 | \x0A | \x0D | [\x20-\uD7FF] | [\uE000-\uFFFD] | [\u{10000}-\u{10FFFF}] |
| 69 | + // Iterate code points to keep valid ones and drop invalid (e.g., 0x1B, other control chars) |
| 70 | + for (const ch of stripAnsi(text)) { |
| 71 | + const cp = ch.codePointAt(0)!; |
| 72 | + const valid = |
| 73 | + cp === 0x09 || |
| 74 | + cp === 0x0a || |
| 75 | + cp === 0x0d || |
| 76 | + (cp >= 0x20 && cp <= 0xd7ff) || |
| 77 | + (cp >= 0xe000 && cp <= 0xfffd) || |
| 78 | + (cp >= 0x10000 && cp <= 0x10ffff); |
| 79 | + if (valid) { |
| 80 | + result += ch; |
| 81 | + } |
| 82 | + } |
| 83 | + return result; |
| 84 | + } |
| 85 | + |
| 86 | + private escapeXml(text: string): string { |
| 87 | + const sanitized = this.sanitizeXml(text); |
| 88 | + return sanitized |
| 89 | + .replace(/&/g, '&') |
| 90 | + .replace(/</g, '<') |
| 91 | + .replace(/>/g, '>') |
| 92 | + .replace(/"/g, '"') |
| 93 | + .replace(/'/g, '''); |
| 94 | + } |
| 95 | + |
| 96 | + private async createJUnitTestCase( |
| 97 | + test: TestResult, |
| 98 | + getSourcemap: GetSourcemap, |
| 99 | + ): Promise<JUnitTestCase> { |
| 100 | + const testCase: JUnitTestCase = { |
| 101 | + name: getTaskNameWithPrefix(test), |
| 102 | + classname: relative(this.rootPath, test.testPath), |
| 103 | + time: (test.duration || 0) / 1000, // Convert to seconds |
| 104 | + status: test.status, |
| 105 | + }; |
| 106 | + |
| 107 | + if (test.errors && test.errors.length > 0) { |
| 108 | + testCase.errors = await Promise.all( |
| 109 | + test.errors.map(async (error) => { |
| 110 | + let details = `${error.message}${error.diff ? `\n${error.diff}` : ''}`; |
| 111 | + const stackFrames = error.stack |
| 112 | + ? await parseErrorStacktrace({ |
| 113 | + stack: error.stack, |
| 114 | + fullStack: error.fullStack, |
| 115 | + getSourcemap, |
| 116 | + }) |
| 117 | + : []; |
| 118 | + |
| 119 | + if (stackFrames[0]) { |
| 120 | + details += `\n${formatStack(stackFrames[0], this.rootPath)}`; |
| 121 | + } |
| 122 | + |
| 123 | + return { |
| 124 | + message: this.escapeXml(error.message), |
| 125 | + type: error.name || 'Error', |
| 126 | + details: this.escapeXml(details), |
| 127 | + }; |
| 128 | + }), |
| 129 | + ); |
| 130 | + } |
| 131 | + |
| 132 | + return testCase; |
| 133 | + } |
| 134 | + |
| 135 | + private async createJUnitTestSuite( |
| 136 | + fileResult: TestFileResult, |
| 137 | + getSourcemap: GetSourcemap, |
| 138 | + ): Promise<JUnitTestSuite> { |
| 139 | + const testCases = await Promise.all( |
| 140 | + fileResult.results.map(async (test) => |
| 141 | + this.createJUnitTestCase(test, getSourcemap), |
| 142 | + ), |
| 143 | + ); |
| 144 | + |
| 145 | + const failures = testCases.filter((test) => test.status === 'fail').length; |
| 146 | + const errors = 0; // No separate error tracking; set to 0 for clarity |
| 147 | + const skipped = testCases.filter( |
| 148 | + (test) => test.status === 'skip' || test.status === 'todo', |
| 149 | + ).length; |
| 150 | + const totalTime = testCases.reduce((sum, test) => sum + test.time, 0); |
| 151 | + |
| 152 | + return { |
| 153 | + name: relative(this.rootPath, fileResult.testPath), |
| 154 | + tests: testCases.length, |
| 155 | + failures, |
| 156 | + errors, |
| 157 | + skipped, |
| 158 | + time: totalTime, |
| 159 | + timestamp: new Date().toISOString(), |
| 160 | + testcases: testCases, |
| 161 | + }; |
| 162 | + } |
| 163 | + |
| 164 | + private generateJUnitXml(report: JUnitReport): string { |
| 165 | + const xmlDeclaration = '<?xml version="1.0" encoding="UTF-8"?>'; |
| 166 | + |
| 167 | + const testsuitesXml = ` |
| 168 | +<testsuites name="${this.escapeXml(report.testsuites.name)}" tests="${report.testsuites.tests}" failures="${report.testsuites.failures}" errors="${report.testsuites.errors}" skipped="${report.testsuites.skipped}" time="${report.testsuites.time}" timestamp="${this.escapeXml(report.testsuites.timestamp)}">`; |
| 169 | + |
| 170 | + const testsuiteXmls = report.testsuites.testsuite |
| 171 | + .map((suite) => { |
| 172 | + const testsuiteStart = ` |
| 173 | + <testsuite name="${this.escapeXml(suite.name)}" tests="${suite.tests}" failures="${suite.failures}" errors="${suite.errors}" skipped="${suite.skipped}" time="${suite.time}" timestamp="${this.escapeXml(suite.timestamp)}">`; |
| 174 | + |
| 175 | + const testcaseXmls = suite.testcases |
| 176 | + .map((testcase) => { |
| 177 | + let testcaseXml = ` |
| 178 | + <testcase name="${this.escapeXml(testcase.name)}" classname="${this.escapeXml(testcase.classname)}" time="${testcase.time}">`; |
| 179 | + |
| 180 | + if (testcase.status === 'skip' || testcase.status === 'todo') { |
| 181 | + testcaseXml += ` |
| 182 | + <skipped/>`; |
| 183 | + } else if (testcase.status === 'fail' && testcase.errors) { |
| 184 | + testcase.errors.forEach((error) => { |
| 185 | + testcaseXml += ` |
| 186 | + <failure message="${error.message}" type="${error.type}">${error.details || ''}</failure>`; |
| 187 | + }); |
| 188 | + } |
| 189 | + |
| 190 | + testcaseXml += ` |
| 191 | + </testcase>`; |
| 192 | + return testcaseXml; |
| 193 | + }) |
| 194 | + .join(''); |
| 195 | + |
| 196 | + const testsuiteEnd = ` |
| 197 | + </testsuite>`; |
| 198 | + |
| 199 | + return testsuiteStart + testcaseXmls + testsuiteEnd; |
| 200 | + }) |
| 201 | + .join(''); |
| 202 | + |
| 203 | + const testsuitesEnd = ` |
| 204 | +</testsuites>`; |
| 205 | + |
| 206 | + return xmlDeclaration + testsuitesXml + testsuiteXmls + testsuitesEnd; |
| 207 | + } |
| 208 | + |
| 209 | + async onTestRunEnd({ |
| 210 | + results, |
| 211 | + testResults, |
| 212 | + duration, |
| 213 | + getSourcemap, |
| 214 | + }: { |
| 215 | + getSourcemap: GetSourcemap; |
| 216 | + results: TestFileResult[]; |
| 217 | + testResults: TestResult[]; |
| 218 | + duration: Duration; |
| 219 | + }): Promise<void> { |
| 220 | + const testSuites = await Promise.all( |
| 221 | + results.map(async (fileResult) => |
| 222 | + this.createJUnitTestSuite(fileResult, getSourcemap), |
| 223 | + ), |
| 224 | + ); |
| 225 | + |
| 226 | + const totalTests = testResults.length; |
| 227 | + const totalFailures = testResults.filter( |
| 228 | + (test) => test.status === 'fail', |
| 229 | + ).length; |
| 230 | + const totalErrors = 0; // This framework does not distinguish between failures and errors, so errors are always reported as zero. |
| 231 | + const totalSkipped = testResults.filter( |
| 232 | + (test) => test.status === 'skip' || test.status === 'todo', |
| 233 | + ).length; |
| 234 | + const totalTime = duration.testTime / 1000; // Convert to seconds |
| 235 | + |
| 236 | + const report: JUnitReport = { |
| 237 | + testsuites: { |
| 238 | + name: 'rstest tests', |
| 239 | + tests: totalTests, |
| 240 | + failures: totalFailures, |
| 241 | + errors: totalErrors, |
| 242 | + skipped: totalSkipped, |
| 243 | + time: totalTime, |
| 244 | + timestamp: new Date().toISOString(), |
| 245 | + testsuite: testSuites, |
| 246 | + }, |
| 247 | + }; |
| 248 | + |
| 249 | + const xmlContent = this.generateJUnitXml(report); |
| 250 | + |
| 251 | + if (this.outputPath) { |
| 252 | + try { |
| 253 | + await writeFile(this.outputPath, xmlContent, 'utf-8'); |
| 254 | + console.log(`JUnit XML report written to: ${this.outputPath}`); |
| 255 | + } catch (error) { |
| 256 | + console.error( |
| 257 | + `Failed to write JUnit XML report to ${this.outputPath}:`, |
| 258 | + error, |
| 259 | + ); |
| 260 | + // Fallback to console output |
| 261 | + console.log('JUnit XML Report:'); |
| 262 | + console.log(xmlContent); |
| 263 | + } |
| 264 | + } else { |
| 265 | + // Output to console by default |
| 266 | + console.log(xmlContent); |
| 267 | + } |
| 268 | + } |
| 269 | +} |
0 commit comments