-
-
Notifications
You must be signed in to change notification settings - Fork 160
/
SerenityReporterForPlaywrightTest.ts
316 lines (257 loc) · 10.2 KB
/
SerenityReporterForPlaywrightTest.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import type { FullConfig } from '@playwright/test';
import type { Reporter, Suite, TestCase, TestError, TestResult } from '@playwright/test/reporter';
import type {
ClassDescription,
Serenity,
StageCrewMember,
StageCrewMemberBuilder,
Timestamp
} from '@serenity-js/core';
import {
LogicError,
serenity as reporterSerenityInstance
} from '@serenity-js/core';
import type { OutputStream } from '@serenity-js/core/lib/adapter';
import type {
DomainEvent} from '@serenity-js/core/lib/events';
import * as events from '@serenity-js/core/lib/events';
import {
InteractionFinished,
RetryableSceneDetected,
SceneFinished,
SceneStarts,
SceneTagged,
TestRunFinished,
TestRunFinishes,
TestRunnerDetected,
TestRunStarts
} from '@serenity-js/core/lib/events';
import { FileSystemLocation, Path } from '@serenity-js/core/lib/io';
import type {
CorrelationId,
Outcome} from '@serenity-js/core/lib/model';
import {
ArbitraryTag,
Category,
ExecutionFailedWithAssertionError,
ExecutionFailedWithError,
ExecutionIgnored,
ExecutionRetriedTag,
ExecutionSkipped,
ExecutionSuccessful,
FeatureTag,
Name,
ScenarioDetails,
} from '@serenity-js/core/lib/model';
import { SERENITY_JS_DOMAIN_EVENTS_ATTACHMENT_CONTENT_TYPE } from './PlaywrightAttachments';
/**
* Configuration object accepted by `@serenity-js/playwright-test` reporter.
*
* See {@apilink SerenityOptions} for usage examples.
*/
export interface SerenityReporterForPlaywrightTestConfig {
/**
* A list of {@apilink StageCrewMemberBuilder|StageCrewMemberBuilders} or {@apilink StageCrewMember|StageCrewMembers}
* to be instantiated in Playwright Test reporter process and notified of {@apilink DomainEvent|DomainEvents} that occur during the scenario execution.
* Note that the `crew` can also be configured using {@apilink ClassDescription|ClassDescriptions}.
*
* #### Learn more
* - {@apilink SerenityOptions}
* - {@apilink SerenityConfig.crew}
*/
crew?: Array<StageCrewMember | StageCrewMemberBuilder | ClassDescription>;
/**
* An output stream to be injected into {@apilink StageCrewMemberBuilder|StageCrewMemberBuilders}
*
* Defaults to [`process.stdout`](https://nodejs.org/api/process.html#process_process_stdout).
*
* #### Learn more
* - {@apilink SerenityConfig.outputStream}
*/
outputStream?: OutputStream;
}
/**
* Serenity/JS reporter that receives notifications from Playwright Test and emits them as
* Serenity/JS {@apilink DomainEvent|domain events} which can be used by
* Serenity/JS {@apilink StageCrewMember|stage crew members}.
*/
export class SerenityReporterForPlaywrightTest implements Reporter {
private errorParser = new PlaywrightErrorParser();
private sceneIds: Map<string, CorrelationId> = new Map();
/**
* @param config
* @param serenity
* Instance of {@apilink Serenity}, specific to the Node process running this Serenity reporter.
* Note that Playwright runs test workers and reporters in separate processes.
*/
constructor(
config: SerenityReporterForPlaywrightTestConfig,
private readonly serenity: Serenity = reporterSerenityInstance,
) {
this.serenity.configure(config);
}
onBegin(config: FullConfig, suite: Suite): void {
this.serenity.announce(new TestRunStarts(this.now()));
}
onTestBegin(test: TestCase): void {
const currentSceneId = this.serenity.assignNewSceneId();
this.sceneIds.set(test.id, currentSceneId);
const scenario = this.scenarioDetailsFrom(test);
this.emit(
new SceneStarts(currentSceneId, scenario, this.serenity.currentTime()),
new SceneTagged(currentSceneId, new FeatureTag(scenario.category.value), this.serenity.currentTime()),
new TestRunnerDetected(currentSceneId, new Name('Playwright'), this.serenity.currentTime()),
);
}
// TODO might be nice to support that by emitting TestStepStarted / Finished
// onStepBegin(test: TestCase, _result: TestResult, step: TestStep): void {
// // console.log('>> onStepBegin');
// }
// onStepEnd(test: TestCase, _result: TestResult, step: TestStep): void {
// // console.log('>> onStepEnd');
// }
onTestEnd(test: TestCase, result: TestResult): void {
this.announceRetryIfNeeded(test, result);
const currentSceneId = this.sceneIds.get(test.id);
let worstInteractionOutcome: Outcome = new ExecutionSuccessful();
for (const attachment of result.attachments) {
if (! (attachment.contentType === SERENITY_JS_DOMAIN_EVENTS_ATTACHMENT_CONTENT_TYPE && attachment.body)) {
continue;
}
const messages = JSON.parse(attachment.body.toString());
for (const message of messages) {
if (message.value.sceneId === 'unknown') {
message.value.sceneId = currentSceneId.value;
}
const event = events[message.type].fromJSON(message.value);
this.serenity.announce(event);
if (event instanceof InteractionFinished && event.outcome.isWorseThan(worstInteractionOutcome)) {
worstInteractionOutcome = event.outcome;
}
}
}
const scenarioOutcome = this.outcomeFrom(test, result);
this.serenity.announce(
new SceneFinished(
currentSceneId,
this.scenarioDetailsFrom(test),
this.determineScenarioOutcome(worstInteractionOutcome, scenarioOutcome),
this.now(),
)
);
}
private determineScenarioOutcome(worstInteractionOutcome: Outcome, scenarioOutcome: Outcome): Outcome {
if (worstInteractionOutcome instanceof ExecutionFailedWithAssertionError) {
return worstInteractionOutcome;
}
return worstInteractionOutcome.isWorseThan(scenarioOutcome)
? worstInteractionOutcome
: scenarioOutcome;
}
private outcomeFrom(test: TestCase, result: TestResult): Outcome {
const outcome = test.outcome();
if (outcome === 'skipped') {
return new ExecutionSkipped();
}
if (outcome === 'unexpected' && result.status === 'passed') {
return new ExecutionFailedWithError(new LogicError(`Scenario expected to fail, but ${ result.status }`));
}
if (['failed', 'interrupted', 'timedOut'].includes(result.status)) {
if (test.retries > result.retry) {
return new ExecutionIgnored(this.errorParser.errorFrom(result.error));
}
return new ExecutionFailedWithError(this.errorParser.errorFrom(result.error));
}
return new ExecutionSuccessful();
}
private scenarioDetailsFrom(test: TestCase) {
const [ root_, browserName_, fileName, describeOrItBlockTitle, ...nestedTitles] = test.titlePath();
const path = new Path(test.location.file);
const scenarioName = nestedTitles.join(' ').trim();
const featureName = scenarioName
? describeOrItBlockTitle
: fileName;
return new ScenarioDetails(
new Name(scenarioName || describeOrItBlockTitle),
new Category(featureName),
new FileSystemLocation(
path,
test.location.line,
test.location.column,
),
);
}
async onEnd(): Promise<void> {
this.serenity.announce(new TestRunFinishes(this.serenity.currentTime()));
try {
await this.serenity.waitForNextCue();
this.serenity.announce(new TestRunFinished(new ExecutionSuccessful(), this.serenity.currentTime()));
}
catch (error) {
this.serenity.announce(new TestRunFinished(new ExecutionFailedWithError(error), this.serenity.currentTime()));
throw error;
}
}
// TODO emit a text artifact with stdout?
// reporter.onStdErr(chunk, test, result)
// reporter.onStdOut(chunk, test, result)
private emit(...events: DomainEvent[]): void {
events.forEach(event => {
this.serenity.announce(event)
});
}
private announceRetryIfNeeded(test: TestCase, result: TestResult): void {
if (test.retries === 0) {
return;
}
const currentSceneId = this.sceneIds.get(test.id);
this.emit(
new RetryableSceneDetected(
currentSceneId,
this.now(),
),
new SceneTagged(
currentSceneId,
new ArbitraryTag('retried'), // todo: replace with a dedicated tag
this.now(),
),
);
if (result.retry > 0) {
this.emit(
new SceneTagged(
currentSceneId,
new ExecutionRetriedTag(result.retry),
this.serenity.currentTime(),
),
);
}
}
private now(): Timestamp {
return this.serenity.currentTime();
}
printsToStdio(): boolean {
return true;
}
}
class PlaywrightErrorParser {
private static ascii = new RegExp(
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))', // eslint-disable-line no-control-regex
'g',
);
public errorFrom(testError: TestError): Error {
const message = testError.message && PlaywrightErrorParser.stripAsciiFrom(testError.message);
let stack = testError.stack && PlaywrightErrorParser.stripAsciiFrom(testError.stack);
// TODO: Do I need to process it?
// const value = testError.value;
const prologue = `Error: ${message}`;
if (stack && message && stack.startsWith(prologue)) {
stack = stack.slice(prologue.length);
}
const error = new Error(message);
error.stack = stack;
return error;
}
private static stripAsciiFrom(text: string): string {
return text.replace(this.ascii, '');
}
}