forked from ChromeDevTools/devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmocha-resultsdb-reporter.ts
163 lines (143 loc) · 5.43 KB
/
mocha-resultsdb-reporter.ts
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as fs from 'fs';
import * as Mocha from 'mocha';
import * as path from 'path';
import * as ResultsDb from '../conductor/resultsdb.js';
import {
ScreenshotError,
} from '../conductor/screenshot-error.js';
const {
EVENT_TEST_FAIL,
EVENT_TEST_PASS,
EVENT_TEST_RETRY,
EVENT_TEST_PENDING,
} = Mocha.Runner.constants;
function sanitize(message: string): string {
return message.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll('\'', ''');
}
function getErrorMessage(error: Error|unknown): string {
if (error instanceof Error) {
if (error.cause) {
// TypeScript types error.cause as {}, which doesn't allow us to access
// properties on it or check for them. So we have to cast it to allow us
// to read the `message` property.
const cause = error.cause as {message?: string};
const causeMessage = cause.message || '';
return sanitize(`${error.message}\n${causeMessage}`);
}
return sanitize(error.stack ?? error.message);
}
return sanitize(`${error}`);
}
interface TestRetry {
currentRetry(): number;
}
interface HookWithParent {
parent: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any,
};
}
class ResultsDbReporter extends Mocha.reporters.Spec {
// The max length of the summary is 4000, but we need to leave some room for
// the rest of the HTML formatting (e.g. <pre> and </pre>).
static readonly SUMMARY_LENGTH_CUTOFF = 3985;
private suitePrefix?: string;
htmlResult: fs.WriteStream|undefined;
localResultsPath() {
return !ResultsDb.available() && this.suitePrefix ? path.join(__dirname, '..', this.suitePrefix, 'results.html') :
undefined;
}
constructor(runner: Mocha.Runner, options?: Mocha.MochaOptions) {
super(runner, options);
// `reportOptions` doesn't work with .mocharc.js (configurig via exports).
// BUT, every module.exports is forwarded onto the options object.
this.suitePrefix = (options as {suiteName: string} | undefined)?.suiteName;
const localResults = this.localResultsPath();
if (localResults) {
this.htmlResult = fs.createWriteStream(localResults, {});
}
runner.on(EVENT_TEST_PASS, this.onTestPass.bind(this));
runner.on(EVENT_TEST_FAIL, this.onTestFail.bind(this));
runner.on(EVENT_TEST_RETRY, this.onTestFail.bind(this));
runner.on(EVENT_TEST_PENDING, this.onTestSkip.bind(this));
}
private onTestPass(test: Mocha.Test) {
const testResult = this.buildDefaultTestResultFrom(test);
testResult.status = 'PASS';
testResult.expected = true;
ResultsDb.sendTestResult(testResult);
}
private onTestFail(test: Mocha.Test, error: Error|ScreenshotError|unknown) {
const testResult = this.buildDefaultTestResultFrom(test);
testResult.status = 'FAIL';
testResult.expected = false;
if (error instanceof ScreenshotError) {
[testResult.artifacts, testResult.summaryHtml] = error.toMiloArtifacts();
} else {
testResult.summaryHtml = `<pre>${getErrorMessage(error).slice(0, ResultsDbReporter.SUMMARY_LENGTH_CUTOFF)}</pre>`;
}
if (this.htmlResult) {
this.htmlResult.write(testResult.summaryHtml);
if (testResult.artifacts) {
for (const screenshot in testResult.artifacts) {
this.htmlResult.write(`<details><summary>${screenshot} screenshot:</summary><p><img src="${
testResult.artifacts[screenshot].filePath}"></img></p></details>`);
}
}
this.htmlResult.write('<hr>');
}
ResultsDb.sendTestResult(testResult);
}
private maybeHook(test: Mocha.Test): string|undefined {
if (!(test instanceof Mocha.Hook)) {
return undefined;
}
const hook = (test as unknown) as HookWithParent;
const suite = hook.parent;
const hookNames = ['afterAll', 'afterEach', 'beforeAll', 'beforeEach'];
return hookNames.find(hookName => suite[`_${hookName}`].includes(test) ? hookName : undefined);
}
private onTestSkip(test: Mocha.Test) {
const testResult = this.buildDefaultTestResultFrom(test);
testResult.status = 'SKIP';
testResult.expected = true;
ResultsDb.sendTestResult(testResult);
}
private buildDefaultTestResultFrom(test: Mocha.Test): ResultsDb.TestResult {
let testId = this.suitePrefix ? this.suitePrefix + '/' : '';
testId += test.titlePath().join('/'); // Chrome groups test by a path logic.
const testRetry = ((test as unknown) as TestRetry);
const result = {
testId: ResultsDb.sanitizedTestId(testId),
duration: `${test.duration || 0}ms`,
tags: [{key: 'run', value: String(testRetry.currentRetry() + 1)}],
testMetadata: {
name: test.title,
location: {
repo: ResultsDb.REPO,
fileName: ResultsDb.testLocation(test.file),
}
}
};
const hookName = this.maybeHook(test);
if (hookName) {
result.tags.push({key: 'hook', value: hookName});
}
return result;
}
override epilogue() {
super.epilogue();
const localResults = this.localResultsPath();
if (this.failures.length > 0 && localResults) {
console.error(`Results have been written to file://${localResults}`);
}
}
}
exports = module.exports = ResultsDbReporter;