|
| 1 | +/*! |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +import * as fs from 'fs' |
| 7 | +import * as path from 'path' |
| 8 | +import * as xml2js from 'xml2js' |
| 9 | + |
| 10 | +/** |
| 11 | + * Merge all of the packages/ test reports into a single directory |
| 12 | + */ |
| 13 | +async function mergeReports() { |
| 14 | + console.log('Merging test reports') |
| 15 | + |
| 16 | + const packagesDir = `${__dirname}/../packages` |
| 17 | + |
| 18 | + // Get all packages/* directories |
| 19 | + const packageDirs = fs.readdirSync(packagesDir).map((dir) => path.join(packagesDir, dir)) |
| 20 | + |
| 21 | + // Find report.xml files in .test-reports subdirectories |
| 22 | + const testReports = packageDirs |
| 23 | + .map((dir) => `${dir}/.test-reports/report.xml`) |
| 24 | + .filter((file) => fs.existsSync(file)) |
| 25 | + |
| 26 | + const mergedReport = { |
| 27 | + testsuites: { |
| 28 | + testsuite: [], |
| 29 | + }, |
| 30 | + } |
| 31 | + |
| 32 | + // Collect all test reports into a single merged test report object |
| 33 | + for (const file of testReports) { |
| 34 | + const content = fs.readFileSync(file) |
| 35 | + const result: { testsuites: { testsuite: [] } } = await xml2js.parseStringPromise(content) |
| 36 | + if (result.testsuites && result.testsuites.testsuite) { |
| 37 | + mergedReport.testsuites.testsuite.push(...result.testsuites.testsuite) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + const builder = new xml2js.Builder() |
| 42 | + const xml = builder.buildObject(mergedReport) |
| 43 | + |
| 44 | + /** |
| 45 | + * Create the new test reports directory and write the test report |
| 46 | + */ |
| 47 | + const reportsDir = path.join(__dirname, '..', '.test-reports') |
| 48 | + |
| 49 | + // Create reports directory if it doesn't exist |
| 50 | + if (!fs.existsSync(reportsDir)) { |
| 51 | + fs.mkdirSync(reportsDir, { recursive: true }) |
| 52 | + } |
| 53 | + |
| 54 | + fs.writeFileSync(`${reportsDir}/report.xml`, xml) |
| 55 | + |
| 56 | + const exitCodeArg = process.argv[2] |
| 57 | + if (exitCodeArg) { |
| 58 | + /** |
| 59 | + * Retrieves the exit code from the previous test run execution. |
| 60 | + * |
| 61 | + * This allows us to: |
| 62 | + * 1. Merge and upload test reports regardless of the test execution status |
| 63 | + * 2. Preserve the original test run exit code |
| 64 | + * 3. Report the test status back to CI |
| 65 | + */ |
| 66 | + const exitCode = parseInt(exitCodeArg || '0', 10) |
| 67 | + process.exit(exitCode) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +mergeReports() |
0 commit comments