-
Notifications
You must be signed in to change notification settings - Fork 39
/
LogCollectExtendedControl.js
396 lines (354 loc) · 13 KB
/
LogCollectExtendedControl.js
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
const CONSTANTS = require('../constants');
const LogCollectBaseControl = require('./LogCollectBaseControl');
/**
* Collects and dispatches all logs from all tests and hooks.
*/
module.exports = class LogCollectExtendedControl extends LogCollectBaseControl {
constructor(collectorState, config) {
super();
this.config = config;
this.collectorState = collectorState;
this.registerCypressBeforeMochaHooksSealEvent();
}
register() {
this.collectorState.setStrict(true);
this.registerState();
this.registerBeforeAllHooks();
this.registerAfterAllHooks();
this.registerTests();
this.registerLogToFiles();
}
sendLogsToPrinter(logStackIndex, mochaRunnable, options = {}) {
if (!mochaRunnable.parent.invocationDetails && !mochaRunnable.invocationDetails) {
return;
}
let testState = options.state || mochaRunnable.state;
let testTitle = options.title || mochaRunnable.title;
let testLevel = 0;
let spec = this.getSpecFilePath(mochaRunnable);
let wait = typeof options.wait === 'number' ? options.wait : 6;
{
let parent = mochaRunnable.parent;
while (parent && parent.title) {
testTitle = `${parent.title} -> ${testTitle}`
parent = parent.parent;
++testLevel;
}
}
const prepareLogs = () => {
return this.prepareLogs(logStackIndex, {mochaRunnable, testState, testTitle, testLevel});
};
if (options.noQueue) {
this.debounceNextMochaSuite(Promise.resolve()
// Need to wait for command log update debounce.
.then(() => new Promise(resolve => setTimeout(resolve, wait)))
.then(() => {
Cypress.backend('task', {
task: CONSTANTS.TASK_NAME,
arg: {
spec: spec,
test: testTitle,
messages: prepareLogs(),
state: testState,
level: testLevel,
consoleTitle: options.consoleTitle,
isHook: options.isHook,
continuous: false,
}
})
// For some reason cypress throws empty error although the task indeed works.
.catch((error) => {/* noop */})
}).catch(console.error)
);
} else {
// Need to wait for command log update debounce.
cy.wait(wait, {log: false})
.then(() => {
cy.task(
CONSTANTS.TASK_NAME,
{
spec: spec,
test: testTitle,
messages: prepareLogs(),
state: testState,
level: testLevel,
consoleTitle: options.consoleTitle,
isHook: options.isHook,
continuous: false,
},
{log: false}
);
});
}
}
registerState() {
const self = this;
Cypress.on('log:changed', (options) => {
if (options.state === 'failed') {
this.collectorState.updateLogStatusForChainId(options.id);
}
});
Cypress.mocha.getRunner().on('test', (test) => {
this.collectorState.startTest(test);
});
Cypress.mocha.getRunner().on('suite', () => {
this.collectorState.startSuite();
});
Cypress.mocha.getRunner().on('suite end', () => {
this.collectorState.endSuite();
});
// Keeps track of before and after all hook indexes.
Cypress.mocha.getRunner().on('hook', function (hook) {
if (!hook._ctr_hook && !hook.fn._ctr_hook) {
// After each hooks get merged with the test.
if (hook.hookName !== "after each") {
self.collectorState.addNewLogStack();
}
// Before each hooks also get merged with the test.
if (hook.hookName === "before each") {
self.collectorState.markCurrentStackFromBeforeEach();
}
if (hook.hookName === "before all") {
self.collectorState.incrementBeforeHookIndex();
} else if (hook.hookName === "after all") {
self.collectorState.incrementAfterHookIndex();
}
}
});
}
registerBeforeAllHooks() {
const self = this;
// Logs commands from before all hook if the hook passed.
Cypress.mocha.getRunner().on('hook end', function (hook) {
if (hook.hookName === "before all" && self.collectorState.hasLogsCurrentStack() && !hook._ctr_hook) {
self.debugLog('extended: sending logs of passed after all hook');
self.sendLogsToPrinter(
self.collectorState.getCurrentLogStackIndex(),
this.currentRunnable,
{
state: 'passed',
isHook: true,
title: self.collectorState.getBeforeHookTestTile(),
consoleTitle: self.collectorState.getBeforeHookTestTile(),
}
);
}
});
// Logs commands from before all hooks that failed.
Cypress.on('before:mocha:hooks:seal', function () {
self.prependBeforeAllHookInAllSuites(this.mocha.getRootSuite().suites, function ctrAfterAllPerSuite() {
if (
this.test.parent === this.currentTest.parent // Since we have after all in each suite we need this for nested suites case.
&& this.currentTest.failedFromHookId // This is how we know a hook failed the suite.
&& self.collectorState.hasLogsCurrentStack()
) {
self.debugLog('extended: sending logs of failed before all hook');
self.sendLogsToPrinter(
self.collectorState.getCurrentLogStackIndex(),
this.currentTest,
{
state: 'failed',
title: self.collectorState.getBeforeHookTestTile(),
isHook: true
}
);
}
});
});
}
registerAfterAllHooks() {
const self = this;
// Logs commands from after all hooks that passed.
Cypress.mocha.getRunner().on('hook end', function (hook) {
if (hook.hookName === "after all" && self.collectorState.hasLogsCurrentStack() && !hook._ctr_hook) {
self.debugLog('extended: sending logs of passed after all hook');
self.sendLogsToPrinter(
self.collectorState.getCurrentLogStackIndex(),
hook,
{
state: 'passed',
title: self.collectorState.getAfterHookTestTile(),
consoleTitle: self.collectorState.getAfterHookTestTile(),
isHook: true,
noQueue: true,
}
);
}
});
// Logs after all hook commands when a command fails in the hook.
Cypress.prependListener('fail', function (error) {
const currentRunnable = this.mocha.getRunner().currentRunnable;
if (currentRunnable.hookName === 'after all' && self.collectorState.hasLogsCurrentStack()) {
// We only have the full list of commands when the suite ends.
this.mocha.getRunner().prependOnceListener('suite end', () => {
self.debugLog('extended: sending logs of failed after all hook');
self.sendLogsToPrinter(
self.collectorState.getCurrentLogStackIndex(),
currentRunnable,
{
state: 'failed',
title: self.collectorState.getAfterHookTestTile(),
isHook: true,
noQueue: true,
wait: 5, // Need to wait so that cypress log updates happen.
}
);
});
// Have to wait for debounce on log updates to have correct state information.
// Done state is used as callback and awaited in Cypress.fail.
Cypress.state('done', async (error) => {
await new Promise(resolve => setTimeout(resolve, 6));
throw error;
});
}
Cypress.state('error', error);
throw error;
});
}
registerTests() {
const self = this;
const sendLogsToPrinterForATest = (test) => {
// We take over logging the passing test titles since we need to control when it gets printed so
// that our logs come after it is printed.
if (test.state === 'passed') {
this.printPassingMochaTestTitle(test);
this.preventNextMochaPassEmit();
}
this.sendLogsToPrinter(this.collectorState.getCurrentLogStackIndex(), test, {noQueue: true});
};
const testHasAfterEachHooks = (test) => {
do {
if (test.parent._afterEach.length > 0) {
return true;
}
test = test.parent;
} while(test.parent);
return false;
};
const isLastAfterEachHookForTest = (test, hook) => {
let suite = test.parent;
do {
if (suite._afterEach.length === 0) {
suite = suite.parent;
} else {
return suite._afterEach.indexOf(hook) === suite._afterEach.length - 1;
}
} while (suite);
return false;
};
// Logs commands form each separate test when after each hooks are present.
Cypress.mocha.getRunner().on('hook end', function (hook) {
if (hook.hookName === 'after each') {
if (isLastAfterEachHookForTest(self.collectorState.getCurrentTest(), hook)) {
self.debugLog('extended: sending logs for ended test, just after the last after each hook: ' + self.collectorState.getCurrentTest().title);
sendLogsToPrinterForATest(self.collectorState.getCurrentTest());
}
}
});
// Logs commands form each separate test when there is no after each hook.
Cypress.mocha.getRunner().on('test end', function (test) {
if (!testHasAfterEachHooks(test)) {
self.debugLog('extended: sending logs for ended test, that has not after each hooks: ' + self.collectorState.getCurrentTest().title);
sendLogsToPrinterForATest(self.collectorState.getCurrentTest());
}
});
// Logs commands if test was manually skipped.
Cypress.mocha.getRunner().on('pending', function (test) {
if (self.collectorState.getCurrentTest() === test) {
// In case of fully skipped tests we might not yet have a log stack.
if (self.collectorState.hasLogsCurrentStack()) {
self.debugLog('extended: sending logs for skipped test: ' + test.title);
sendLogsToPrinterForATest(test);
}
}
});
}
registerLogToFiles() {
after(function () {
cy.wait(6, {log: false});
cy.task(CONSTANTS.TASK_NAME_OUTPUT, null, {log: false});
});
}
debounceNextMochaSuite(promise) {
const runner = Cypress.mocha.getRunner();
// Hack to make mocha wait for our logs to be written to console before
// going to the next suite. This is because 'fail' and 'suite begin' both
// fire synchronously and thus we wouldn't get a window to display the
// logs between the failed hook title and next suite title.
const originalRunSuite = runner.runSuite;
runner.runSuite = function (...args) {
promise
.catch(() => {/* noop */})
// We need to wait here as for some reason the next suite title will be displayed to soon.
.then(() => new Promise(resolve => setTimeout(resolve, 6)))
.then(() => {
originalRunSuite.apply(runner, args);
runner.runSuite = originalRunSuite;
});
}
}
registerCypressBeforeMochaHooksSealEvent() {
// Hack to have dynamic after hook per suite.
// The onSpecReady in cypress is called before the hooks are 'condensed', or so
// to say sealed and thus in this phase we can register dynamically hooks.
const oldOnSpecReady = Cypress.onSpecReady;
Cypress.onSpecReady = function () {
Cypress.emit('before:mocha:hooks:seal');
oldOnSpecReady(...arguments);
};
}
prependBeforeAllHookInAllSuites(rootSuites, hookCallback) {
const recursiveSuites = (suites) => {
if (suites) {
suites.forEach((suite) => {
if (suite.isPending()) {
return
}
suite.afterAll(hookCallback);
// Make sure our hook is first so that other after all hook logs come after
// the failed before all hooks logs.
const hook = suite._afterAll.pop();
suite._afterAll.unshift(hook);
// Don't count this in the hook index and logs.
hook._ctr_hook = true;
recursiveSuites(suite.suites);
});
}
};
recursiveSuites(rootSuites);
}
printPassingMochaTestTitle(test) {
if (Cypress.config('isTextTerminal')) {
Cypress.emit('mocha', 'pass', {
"id": test.id,
"order": test.order,
"title": test.title,
"state": "passed",
"type": "test",
"duration": test.duration,
"wallClockStartedAt": test.wallClockStartedAt,
"timings": test.timings,
"file": null,
"invocationDetails": test.invocationDetails,
"final": true,
"currentRetry": test.currentRetry(),
"retries": test.retries(),
})
}
}
preventNextMochaPassEmit() {
const oldAction = Cypress.action;
Cypress.action = function (actionName, ...args) {
if (actionName === 'runner:pass') {
Cypress.action = oldAction;
return;
}
return oldAction.call(Cypress, actionName, ...args);
};
}
debugLog(message) {
if (this.config.debug) {
console.log(CONSTANTS.DEBUG_LOG_PREFIX + message);
}
}
};