browserstack-cypress-cli 1.23.1 → 1.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,699 @@
1
+ 'use strict';
2
+
3
+ const util = require('util');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { requireModule } = require('../helper/helper');
7
+ const Base = requireModule('mocha/lib/reporters/base.js'),
8
+ utils = requireModule('mocha/lib/utils.js');
9
+ const color = Base.color;
10
+ const Mocha = requireModule('mocha');
11
+ // const Runnable = requireModule('mocha/lib/runnable');
12
+ const Runnable = require('mocha/lib/runnable'); // need to handle as this isn't present in older mocha versions
13
+ const { v4: uuidv4 } = require('uuid');
14
+
15
+ const { IPC_EVENTS } = require('../helper/constants');
16
+ const { startIPCServer } = require('../plugin/ipcServer');
17
+
18
+ const HOOK_TYPES_MAP = {
19
+ "before all": "BEFORE_ALL",
20
+ "after all": "AFTER_ALL",
21
+ "before each": "BEFORE_EACH",
22
+ "after each": "AFTER_EACH",
23
+ }
24
+
25
+ const {
26
+ EVENT_RUN_END,
27
+ EVENT_TEST_BEGIN,
28
+ EVENT_TEST_END,
29
+ EVENT_TEST_PENDING,
30
+ EVENT_RUN_BEGIN,
31
+ EVENT_TEST_FAIL,
32
+ EVENT_TEST_PASS,
33
+ EVENT_SUITE_BEGIN,
34
+ EVENT_SUITE_END,
35
+ EVENT_HOOK_BEGIN,
36
+ EVENT_HOOK_END
37
+ } = Mocha.Runner.constants;
38
+
39
+ const {
40
+ STATE_PASSED,
41
+ STATE_PENDING,
42
+ STATE_FAILED,
43
+ } = Runnable.constants;
44
+
45
+ const {
46
+ uploadEventData,
47
+ failureData,
48
+ PathHelper,
49
+ getTestEnv,
50
+ getHookDetails,
51
+ getHooksForTest,
52
+ mapTestHooks,
53
+ debug,
54
+ isBrowserstackInfra,
55
+ requestQueueHandler,
56
+ getHookSkippedTests,
57
+ getOSDetailsFromSystem,
58
+ findGitConfig,
59
+ getFileSeparatorData,
60
+ setCrashReportingConfigFromReporter
61
+ } = require('../helper/helper');
62
+
63
+ const { consoleHolder } = require('../helper/constants');
64
+
65
+ // this reporter outputs test results, indenting two spaces per suite
66
+ class MyReporter {
67
+ constructor(runner, options) {
68
+ this.testObservability = true;
69
+ Base.call(this, runner, options);
70
+ this._testEnv = getTestEnv();
71
+ this._paths = new PathHelper({ cwd: process.cwd() }, this._testEnv.location_prefix);
72
+ this.currentTestSteps = [];
73
+ this.currentTestCucumberSteps = [];
74
+ this.beforeHooks = [];
75
+ this.platformDetailsMap = {};
76
+ this.runStatusMarkedHash = {};
77
+ this.haveSentBuildUpdate = false;
78
+ this.registerListeners();
79
+ setCrashReportingConfigFromReporter(null, process.env.OBS_CRASH_REPORTING_BS_CONFIG_PATH, process.env.OBS_CRASH_REPORTING_CYPRESS_CONFIG_PATH);
80
+
81
+ runner
82
+ .once(EVENT_RUN_BEGIN, async () => {
83
+ })
84
+
85
+ .on(EVENT_SUITE_BEGIN, (suite) => {
86
+ })
87
+
88
+ .on(EVENT_HOOK_BEGIN, async (hook) => {
89
+ if(this.testObservability == true) {
90
+ if(!hook.hookAnalyticsId) {
91
+ hook.hookAnalyticsId = uuidv4();
92
+ } else if(this.runStatusMarkedHash[hook.hookAnalyticsId]) {
93
+ delete this.runStatusMarkedHash[hook.hookAnalyticsId];
94
+ hook.hookAnalyticsId = uuidv4();
95
+ }
96
+ hook.hook_started_at = (new Date()).toISOString();
97
+ hook.started_at = (new Date()).toISOString();
98
+ this.current_hook = hook;
99
+ await this.sendTestRunEvent(hook,undefined,false,"HookRunStarted");
100
+ }
101
+ })
102
+
103
+ .on(EVENT_HOOK_END, async (hook) => {
104
+ if(this.testObservability == true) {
105
+ if(!this.runStatusMarkedHash[hook.hookAnalyticsId]) {
106
+ if(!hook.hookAnalyticsId) {
107
+ /* Hook objects don't maintain uuids in Cypress-Mocha */
108
+ hook.hookAnalyticsId = this.current_hook.hookAnalyticsId;
109
+ this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] = true;
110
+ } else {
111
+ this.runStatusMarkedHash[hook.hookAnalyticsId] = true;
112
+ }
113
+ await this.sendTestRunEvent(hook,undefined,false,"HookRunFinished");
114
+ }
115
+ }
116
+ })
117
+
118
+ .on(EVENT_SUITE_END, (suite) => {
119
+ })
120
+
121
+ .on(EVENT_TEST_PASS, async (test) => {
122
+ if(this.testObservability == true) {
123
+ if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
124
+ if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
125
+ await this.sendTestRunEvent(test);
126
+ }
127
+ }
128
+ })
129
+
130
+ .on(EVENT_TEST_FAIL, async (test, err) => {
131
+ if(this.testObservability == true) {
132
+ if((test.testAnalyticsId && !this.runStatusMarkedHash[test.testAnalyticsId]) || (test.hookAnalyticsId && !this.runStatusMarkedHash[test.hookAnalyticsId])) {
133
+ if(test.testAnalyticsId) {
134
+ this.runStatusMarkedHash[test.testAnalyticsId] = true;
135
+ await this.sendTestRunEvent(test,err);
136
+ } else if(test.hookAnalyticsId) {
137
+ this.runStatusMarkedHash[test.hookAnalyticsId] = true;
138
+ await this.sendTestRunEvent(test,err,false,"HookRunFinished");
139
+ }
140
+ }
141
+ }
142
+ })
143
+
144
+ .on(EVENT_TEST_PENDING, async (test) => {
145
+ if(this.testObservability == true) {
146
+ if(!test.testAnalyticsId) test.testAnalyticsId = uuidv4();
147
+ if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
148
+ this.runStatusMarkedHash[test.testAnalyticsId] = true;
149
+ await this.sendTestRunEvent(test,undefined,false,"TestRunSkipped");
150
+ }
151
+ }
152
+ })
153
+
154
+ .on(EVENT_TEST_BEGIN, async (test) => {
155
+ if(this.testObservability == true) {
156
+ await this.testStarted(test);
157
+ }
158
+ })
159
+
160
+ .on(EVENT_TEST_END, async (test) => {
161
+ if(this.testObservability == true) {
162
+ if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
163
+ if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
164
+ await this.sendTestRunEvent(test);
165
+ }
166
+ }
167
+ })
168
+
169
+ .once(EVENT_RUN_END, async () => {
170
+ try {
171
+ if(this.testObservability == true) {
172
+ const hookSkippedTests = getHookSkippedTests(this.runner.suite);
173
+ for(const test of hookSkippedTests) {
174
+ if(!test.testAnalyticsId) test.testAnalyticsId = uuidv4();
175
+ await this.sendTestRunEvent(test,undefined,false,"TestRunSkipped");
176
+ }
177
+ }
178
+ } catch(err) {
179
+ debug(`Exception in populating test data for hook skipped test with error : ${err}`, true, err);
180
+ }
181
+
182
+ await this.uploadTestSteps();
183
+ await requestQueueHandler.shutdown();
184
+ });
185
+ }
186
+
187
+ registerListeners() {
188
+ startIPCServer(
189
+ (server) => {
190
+ server.on(IPC_EVENTS.CONFIG, this.cypressConfigListener.bind(this));
191
+ server.on(IPC_EVENTS.LOG, this.cypressLogListener.bind(this));
192
+ server.on(IPC_EVENTS.SCREENSHOT, this.cypressScreenshotListener.bind(this));
193
+ server.on(IPC_EVENTS.COMMAND, this.cypressCommandListener.bind(this));
194
+ server.on(IPC_EVENTS.CUCUMBER, this.cypressCucumberStepListener.bind(this));
195
+ server.on(IPC_EVENTS.PLATFORM_DETAILS, this.cypressPlatformDetailsListener.bind(this));
196
+ },
197
+ (server) => {
198
+ server.off(IPC_EVENTS.CONFIG, '*');
199
+ server.off(IPC_EVENTS.LOG, '*');
200
+ server.off(IPC_EVENTS.SCREENSHOT, '*');
201
+ },
202
+ );
203
+ }
204
+
205
+ testStarted = async (test) => {
206
+ try {
207
+ const lastTest = this.current_test;
208
+ this.current_test = test;
209
+ test.retryOf = null;
210
+ test.testAnalyticsId = uuidv4();
211
+ test.started_at = (new Date()).toISOString();
212
+ test.test_started_at = test.started_at;
213
+ if(test._currentRetry > 0 && lastTest && lastTest.title == test.title) {
214
+ /* Sending async to current test start to avoid current test end call getting fired before its start call */
215
+ test.retryOf = lastTest.testAnalyticsId
216
+ await this.sendTestRunEvent(test, undefined, false, "TestRunStarted");
217
+ lastTest.state = STATE_FAILED;
218
+ await this.sendTestRunEvent(lastTest, undefined, true);
219
+ } else {
220
+ await this.sendTestRunEvent(test, undefined, false, "TestRunStarted");
221
+ }
222
+ this.lastTest = lastTest;
223
+ } catch(err) {
224
+ debug(`Exception in populating test data for test start with error : ${err}`, true, err);
225
+ }
226
+ }
227
+
228
+ uploadTestSteps = async (shouldClearCurrentSteps = true, cypressSteps = null) => {
229
+ const currentTestSteps = cypressSteps ? cypressSteps : JSON.parse(JSON.stringify(this.currentTestSteps));
230
+ /* TODO - Send as test logs */
231
+ const allStepsAsLogs = [];
232
+ currentTestSteps.forEach(step => {
233
+ const currentStepAsLog = {
234
+ test_run_uuid : step.test_run_uuid,
235
+ hook_run_uuid : step.hook_run_uuid,
236
+ timestamp: step.started_at,
237
+ duration: step.duration,
238
+ level: step.result,
239
+ message: step.text,
240
+ failure: step.failure,
241
+ failure_reason: step.failure_reason,
242
+ failure_type: step.failure_type,
243
+ kind: 'TEST_STEP',
244
+ http_response: {}
245
+ };
246
+ allStepsAsLogs.push(currentStepAsLog);
247
+ });
248
+ await uploadEventData({
249
+ event_type: 'LogCreated',
250
+ logs: allStepsAsLogs
251
+ });
252
+ if(shouldClearCurrentSteps) this.currentTestSteps = [];
253
+ }
254
+
255
+ sendTestRunEvent = async (test, err = undefined, customFinished=false, eventType = "TestRunFinished") => {
256
+ try {
257
+ if(test.body && test.body.match(/browserstack internal helper hook/)) return;
258
+ let failureArgs = [];
259
+ if(test.state === STATE_FAILED || eventType.match(/HookRun/)) {
260
+ if(test.err !== undefined) {
261
+ failureArgs = test.err.multiple ? [test.err.multiple, 'test'] : [test.err, 'err'];
262
+ } else if(err !== undefined) {
263
+ failureArgs = [err, 'err'];
264
+ } else {
265
+ failureArgs = [];
266
+ }
267
+ }
268
+
269
+ const failureReason = test.err !== undefined ? test.err.toString() : err !== undefined ? err.toString() : undefined;
270
+ if(eventType == 'TestRunFinished' && failureReason && this.currentTestCucumberSteps.length) {
271
+ this.currentTestCucumberSteps[this.currentTestCucumberSteps.length - 1] = {
272
+ ...this.currentTestCucumberSteps[this.currentTestCucumberSteps.length - 1],
273
+ result: 'failed'
274
+ }
275
+ }
276
+
277
+ let rootParentFile;
278
+ try {
279
+ rootParentFile = this.getRootParentFile(test)
280
+ } catch(e) {
281
+ rootParentFile = null;
282
+ }
283
+ let gitConfigPath = process.env.OBSERVABILITY_GIT_CONFIG_PATH ? process.env.OBSERVABILITY_GIT_CONFIG_PATH.toString() : (rootParentFile ? findGitConfig(rootParentFile) : null);
284
+ if(!isBrowserstackInfra()) gitConfigPath = process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL ? process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL.toString() : null;
285
+ const prefixedTestPath = rootParentFile ? this._paths.prefixTestPath(rootParentFile) : 'File path could not be found';
286
+
287
+ const { fileSeparator, fileSeparatorRegex } = getFileSeparatorData();
288
+
289
+ let testData = {
290
+ 'framework': 'Cypress',
291
+ 'uuid': (eventType.includes("Test") ? test.testAnalyticsId : test.hookAnalyticsId) || uuidv4(),
292
+ 'name': test.title,
293
+ 'body': {
294
+ 'lang': 'javascript',
295
+ 'code': test.body
296
+ },
297
+ 'scope': this.scope(test),
298
+ 'scopes': this.scopes(test),
299
+ 'identifier': test.fullTitle(),
300
+ 'file_name': prefixedTestPath.replaceAll("\\", "/"),
301
+ 'vc_filepath': !isBrowserstackInfra() ? ( gitConfigPath ? path.relative(gitConfigPath, rootParentFile) : null ) : ( gitConfigPath ? ((gitConfigPath == 'DEFAULT' ? '' : gitConfigPath) + fileSeparator + rootParentFile).replaceAll("\\", "/") : null ),
302
+ 'location': prefixedTestPath.replaceAll("\\", "/"),
303
+ 'result': eventType === "TestRunSkipped" ? 'skipped' : ( eventType === "TestRunStarted" ? 'pending' : this.analyticsResult(test, eventType, err) ),
304
+ 'failure_reason': failureReason,
305
+ 'duration_in_ms': test.duration || (eventType.match(/Finished/) || eventType.match(/Skipped/) ? Date.now() - (new Date(test.started_at)).getTime() : null),
306
+ 'started_at': ( ( (eventType.match(/TestRun/) ? test.test_started_at : test.hook_started_at) || test.started_at ) || (new Date()).toISOString() ),
307
+ 'finished_at': eventType.match(/Finished/) || eventType.match(/Skipped/) ? (new Date()).toISOString() : null,
308
+ 'failure': failureData(...failureArgs),
309
+ 'failure_type': !failureReason ? null : failureReason.match(/AssertionError/) ? 'AssertionError' : 'UnhandledError',
310
+ 'retry_of': test.retryOf,
311
+ 'meta': {
312
+ steps: JSON.parse(JSON.stringify(this.currentTestCucumberSteps))
313
+ }
314
+ };
315
+
316
+ this.currentTestCucumberSteps = [];
317
+
318
+ const { os, os_version } = await getOSDetailsFromSystem(process.env.observability_product);
319
+ if(process.env.observability_integration) {
320
+ testData = {...testData, integrations: {
321
+ [process.env.observability_integration || 'local_grid' ]: {
322
+ 'build_id': process.env.observability_build_id,
323
+ 'session_id': process.env.observability_automate_session_id + btoa(prefixedTestPath.replaceAll("\\", "/")),
324
+ 'capabilities': {},
325
+ 'product': process.env.observability_product,
326
+ 'platform': process.env.observability_os || os,
327
+ 'platform_version': process.env.observability_os_version || os_version,
328
+ 'browser': process.env.observability_browser,
329
+ 'browser_version': process.env.observability_browser_version
330
+ }
331
+ }};
332
+ } else if(this.platformDetailsMap[process.pid] && this.platformDetailsMap[process.pid][test.title]) {
333
+ const {browser, platform} = this.platformDetailsMap[process.pid][test.title];
334
+ testData = {...testData, integrations: {
335
+ 'local_grid': {
336
+ 'capabilities': {},
337
+ 'platform': os,
338
+ 'platform_version': os_version,
339
+ 'browser': browser.name,
340
+ 'browser_version': browser.majorVersion
341
+ }
342
+ }};
343
+ if(eventType === "TestRunFinished" || eventType === "TestRunSkipped") {
344
+ delete this.platformDetailsMap[process.pid][test.title];
345
+ }
346
+ }
347
+
348
+ if (eventType === "TestRunSkipped" && !testData['started_at']) {
349
+ testData['started_at'] = testData['finished_at'];
350
+ }
351
+
352
+ try {
353
+ if(eventType.match(/HookRun/)) {
354
+ [testData.hook_type, testData.name] = getHookDetails(test.fullTitle() || test.originalTitle || test.title);
355
+ if(eventType === "HookRunFinished") {
356
+ if(testData.result === 'pending') testData.result = 'passed';
357
+ if(testData.hook_type == 'before each' && testData.result === 'failed' && ( !this.runStatusMarkedHash[test.ctx.currentTest.testAnalyticsId] )) {
358
+ if(test.ctx.currentTest.testAnalyticsId) this.runStatusMarkedHash[test.ctx.currentTest.testAnalyticsId] = true;
359
+ test.ctx.currentTest.state = STATE_FAILED;
360
+ await this.sendTestRunEvent(test.ctx.currentTest,undefined,true);
361
+ }
362
+ }
363
+ if(testData.hook_type.includes('each')) {
364
+ testData['test_run_id'] = testData['test_run_id'] || test.testAnalyticsId;
365
+ } else if(testData.hook_type.includes('after')) {
366
+ testData['test_run_id'] = this.lastTest ? this.lastTest.testAnalyticsId : testData['test_run_id'];
367
+ }
368
+ } else if(eventType.match(/TestRun/)) {
369
+ mapTestHooks(test);
370
+ }
371
+ } catch(e) {
372
+ debug(`Exception in processing hook data for event ${eventType} with error : ${e}`, true, e);
373
+ }
374
+
375
+ const failure_data = testData['failure'][0];
376
+ if (failure_data) {
377
+ testData['failure_backtrace'] = failure_data['backtrace']
378
+ testData['failure_reason_expanded'] = failure_data['expanded']
379
+ }
380
+
381
+ if(["TestRunFinished","TestRunSkipped"].includes(eventType)) {
382
+ testData.hooks = getHooksForTest(test);
383
+ }
384
+
385
+ let uploadData = {
386
+ event_type: eventType === "TestRunSkipped" ? "TestRunFinished" : eventType,
387
+ }
388
+
389
+ if(eventType == "HookRunFinished") delete testData.started_at;
390
+
391
+ if(eventType.match(/HookRun/)) {
392
+ testData['hook_type'] = HOOK_TYPES_MAP[testData['hook_type']];
393
+ uploadData['hook_run'] = testData;
394
+ } else {
395
+ uploadData['test_run'] = testData;
396
+ }
397
+
398
+ if(eventType == 'HookRunFinished' && testData['hook_type'] == 'BEFORE_ALL') {
399
+ uploadData.cypressSteps = JSON.parse(JSON.stringify(this.currentTestSteps));
400
+ this.beforeHooks.push(uploadData);
401
+ this.currentTestSteps = [];
402
+ } else {
403
+ await uploadEventData(uploadData);
404
+
405
+ if(eventType.match(/Finished/)) {
406
+ await this.uploadTestSteps();
407
+ }
408
+
409
+ if(eventType.match(/TestRun/)) {
410
+ this.beforeHooks.forEach(async(hookUploadObj) => {
411
+ const currentTestSteps = hookUploadObj.cypressSteps;
412
+ delete hookUploadObj.cypressSteps;
413
+ hookUploadObj['hook_run']['test_run_id'] = test.testAnalyticsId;
414
+ await uploadEventData(hookUploadObj);
415
+ await this.uploadTestSteps(false, currentTestSteps);
416
+ });
417
+ this.beforeHooks = [];
418
+ }
419
+ }
420
+
421
+ if(!this.haveSentBuildUpdate && (process.env.observability_framework_version || this.currentCypressVersion)) {
422
+ this.shouldSendBuildUpdate = true;
423
+ const buildUpdateData = {
424
+ event_type: 'BuildUpdate',
425
+ 'misc': {
426
+ observability_version: {
427
+ frameworkName: "Cypress",
428
+ sdkVersion: process.env.OBSERVABILITY_LAUNCH_SDK_VERSION,
429
+ frameworkVersion: ( process.env.observability_framework_version || this.currentCypressVersion )
430
+ }
431
+ }
432
+ };
433
+ await uploadEventData(buildUpdateData);
434
+ }
435
+ } catch(error) {
436
+ debug(`Exception in populating test data for event ${eventType} with error : ${error}`, true, error);
437
+ }
438
+ }
439
+
440
+ appendTestItemLog = async (log) => {
441
+ try {
442
+ if(this.current_hook && ( this.current_hook.hookAnalyticsId && !this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] )) {
443
+ log.hook_run_uuid = this.current_hook.hookAnalyticsId;
444
+ }
445
+ if(!log.hook_run_uuid && this.current_test && ( this.current_test.testAnalyticsId && !this.runStatusMarkedHash[this.current_test.testAnalyticsId] )) log.test_run_uuid = this.current_test.testAnalyticsId;
446
+ if(log.hook_run_uuid || log.test_run_uuid) {
447
+ await uploadEventData({
448
+ event_type: 'LogCreated',
449
+ logs: [log]
450
+ });
451
+ }
452
+ } catch(error) {
453
+ debug(`Exception in uploading log data to Observability with error : ${error}`, true, error);
454
+ }
455
+ }
456
+
457
+ cypressConfigListener = async (config) => {
458
+ }
459
+
460
+ cypressCucumberStepListener = async ({log}) => {
461
+ if(log.name == 'step' && log.consoleProps && log.consoleProps.step && log.consoleProps.step.keyword) {
462
+ this.currentTestCucumberSteps = [
463
+ ...this.currentTestCucumberSteps,
464
+ {
465
+ id: log.chainerId,
466
+ keyword: log.consoleProps.step.keyword,
467
+ text: log.consoleProps.step.text,
468
+ started_at: new Date().toISOString(),
469
+ finished_at: new Date().toISOString(),
470
+ duration: 0,
471
+ result: 'passed'
472
+ }
473
+ ];
474
+ } else if(log.name == 'then' && log.type == 'child' && log.chainerId) {
475
+ this.currentTestCucumberSteps.forEach((gherkinStep, idx) => {
476
+ if(gherkinStep.id == log.chainerId) {
477
+ this.currentTestCucumberSteps[idx] = {
478
+ ...gherkinStep,
479
+ finished_at: new Date().toISOString(),
480
+ duration: Date.now() - (new Date(gherkinStep.started_at)).getTime(),
481
+ result: log.state,
482
+ failure: log.err?.stack || log.err?.message,
483
+ failure_reason: log.err?.stack || log.err?.message,
484
+ failure_type: log.err?.name || 'UnhandledError'
485
+ }
486
+ }
487
+ })
488
+ }
489
+ }
490
+
491
+ cypressLogListener = async ({level, message, file}) => {
492
+ this.appendTestItemLog({
493
+ timestamp: new Date().toISOString(),
494
+ level: level.toUpperCase(),
495
+ message,
496
+ kind: 'TEST_LOG',
497
+ http_response: {}
498
+ });
499
+ }
500
+
501
+ cypressScreenshotListener = async ({logMessage, screenshotInfo}) => {
502
+ if(screenshotInfo.path) {
503
+ const screenshotAsBase64 = fs.readFileSync(screenshotInfo.path, {encoding: 'base64'});
504
+ if(screenshotAsBase64) {
505
+ this.appendTestItemLog({
506
+ timestamp: screenshotInfo.takenAt || new Date().toISOString(),
507
+ message: screenshotAsBase64,
508
+ kind: 'TEST_SCREENSHOT'
509
+ });
510
+ }
511
+ }
512
+ }
513
+
514
+ cypressPlatformDetailsListener = async({testTitle, browser, platform, cypressVersion}) => {
515
+ if(!process.env.observability_integration) {
516
+ this.platformDetailsMap[process.pid] = this.platformDetailsMap[process.pid] || {};
517
+ if(testTitle) this.platformDetailsMap[process.pid][testTitle] = { browser, platform };
518
+ }
519
+ this.currentCypressVersion = cypressVersion;
520
+ }
521
+
522
+ getFormattedArgs = (args) => {
523
+ if(!args) return '';
524
+ let res = '';
525
+ args.forEach((val) => {
526
+ res = res + (res.length ? ', ' : '') + JSON.stringify(val);
527
+ });
528
+ return res;
529
+ }
530
+
531
+ cypressCommandListener = async ({type, command}) => {
532
+ if(!command || command?.attributes?.name == 'then') return;
533
+
534
+ if(type == 'COMMAND_RETRY') {
535
+ command.id = command._log.chainerId;
536
+ }
537
+
538
+ if(type == 'COMMAND_START') {
539
+ let isCommandPresent = null;
540
+ for(let idx=0; idx<this.currentTestSteps.length; idx++) {
541
+ if(this.currentTestSteps[idx].id == command.attributes.id) {
542
+ isCommandPresent = idx;
543
+ break;
544
+ }
545
+ }
546
+ /* COMMAND_END reported before COMMAND_START */
547
+ if(isCommandPresent) {
548
+ return;
549
+ }
550
+
551
+ const currentStepObj = {
552
+ id: command.attributes.id,
553
+ text: 'cy.' + command.attributes.name + '(' + this.getFormattedArgs(command.attributes.args) + ')',
554
+ started_at: new Date().toISOString(),
555
+ finished_at: null,
556
+ duration: null,
557
+ result: 'pending',
558
+ test_run_uuid: this.current_test?.testAnalyticsId && !this.runStatusMarkedHash[this.current_test.testAnalyticsId] ? this.current_test.testAnalyticsId : null,
559
+ hook_run_uuid : this.current_hook?.hookAnalyticsId && !this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] ? this.current_hook.hookAnalyticsId : null
560
+ };
561
+ if(currentStepObj.hook_run_uuid && currentStepObj.test_run_uuid) delete currentStepObj.test_run_uuid;
562
+ this.currentTestSteps = [
563
+ ...this.currentTestSteps,
564
+ currentStepObj
565
+ ];
566
+ } else if(type == 'COMMAND_END') {
567
+ let stepUpdated = false;
568
+ this.currentTestSteps.forEach((val, idx) => {
569
+ if(val.id == command.attributes.id) {
570
+ this.currentTestSteps[idx] = {
571
+ ...val,
572
+ finished_at: new Date().toISOString(),
573
+ duration: Date.now() - (new Date(val.started_at)).getTime(),
574
+ result: command.state
575
+ };
576
+ stepUpdated = true;
577
+ }
578
+ });
579
+
580
+ if(!stepUpdated) {
581
+ /* COMMAND_END reported before COMMAND_START */
582
+ const currentStepObj = {
583
+ id: command.attributes.id,
584
+ text: 'cy.' + command.attributes.name + '(' + this.getFormattedArgs(command.attributes.args) + ')',
585
+ started_at: new Date().toISOString(),
586
+ finished_at: new Date().toISOString(),
587
+ duration: 0,
588
+ result: command.state,
589
+ test_run_uuid: this.current_test?.testAnalyticsId && !this.runStatusMarkedHash[this.current_test.testAnalyticsId] ? this.current_test.testAnalyticsId : null,
590
+ hook_run_uuid : this.current_hook?.hookAnalyticsId && !this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] ? this.current_hook.hookAnalyticsId : null
591
+ };
592
+ if(currentStepObj.hook_run_uuid && currentStepObj.test_run_uuid) delete currentStepObj.test_run_uuid;
593
+ this.currentTestSteps = [
594
+ ...this.currentTestSteps,
595
+ currentStepObj
596
+ ];
597
+ }
598
+ } else if(type == 'COMMAND_RETRY') {
599
+ if(!command.id) return;
600
+
601
+ let isRetryStepFound = false;
602
+ /* Parse steps array in reverse and update the last step with common chainerId */
603
+ for(let idx=this.currentTestSteps.length-1; idx>=0; idx--) {
604
+ const val = this.currentTestSteps[idx];
605
+ if(val.id.includes(command.id)) {
606
+ this.currentTestSteps[idx] = {
607
+ ...val,
608
+ failure: command?.error?.message,
609
+ failure_reason: command?.error?.message,
610
+ failure_type: command?.error?.isDefaultAssertionErr ? 'AssertionError' : 'UnhandledError',
611
+ finished_at: new Date().toISOString(),
612
+ duration: Date.now() - (new Date(val.started_at)).getTime(),
613
+ result: command?.error?.message ? 'failed' : 'pending'
614
+ };
615
+ isRetryStepFound = true;
616
+ break;
617
+ }
618
+ }
619
+
620
+ /* As a backup, parse steps array in reverse and update the last step with pending status */
621
+ if(!isRetryStepFound) {
622
+ for(let idx=this.currentTestSteps.length-1; idx>=0; idx--) {
623
+ const val = this.currentTestSteps[idx];
624
+ if(val.state == 'pending') {
625
+ this.currentTestSteps[idx] = {
626
+ ...val,
627
+ failure: command?.error?.message,
628
+ failure_reason: command?.error?.message,
629
+ failure_type: command?.error?.isDefaultAssertionErr ? 'AssertionError' : 'UnhandledError',
630
+ finished_at: new Date().toISOString(),
631
+ duration: Date.now() - (new Date(val.started_at)).getTime(),
632
+ result: command?.error?.message ? 'failed' : 'pending'
633
+ };
634
+ isRetryStepFound = true;
635
+ break;
636
+ }
637
+ }
638
+ }
639
+ }
640
+ }
641
+
642
+ analyticsResult(test, eventType, err) {
643
+ if(eventType.match(/HookRun/)) {
644
+ if(test.isFailed() || test.err || err) {
645
+ return 'failed';
646
+ } else if(eventType == 'HookRunFinished') {
647
+ return 'passed';
648
+ } else {
649
+ return 'pending';
650
+ }
651
+ } else {
652
+ return {
653
+ [STATE_PASSED]: 'passed',
654
+ [STATE_PENDING]: 'pending',
655
+ [STATE_FAILED]: 'failed',
656
+ }[test.state]
657
+ }
658
+ }
659
+
660
+ scope(test) {
661
+ const titlePath = test.titlePath()
662
+ // titlePath returns an array of the scope + the test title.
663
+ // as the test title is the last array item, we just remove it
664
+ // and then join the rest of the array as a space separated string
665
+ return titlePath.slice(0, titlePath.length - 1).join(' ')
666
+ }
667
+
668
+ scopes(test) {
669
+ const titlePath = test.titlePath()
670
+ return titlePath.slice(0, titlePath.length - 1)
671
+ }
672
+
673
+ // Recursively find the root parent, and return the parents file
674
+ // This is required as test.file can be undefined in some tests on cypress
675
+ getRootParentFile(test) {
676
+ if (test.file) {
677
+ return test.file
678
+ }
679
+ if(test.ctx) {
680
+ const ctxRes = (test.ctx.currentTest ? this.getRootParentFile(test.ctx.currentTest) : null);
681
+ if(ctxRes) return ctxRes;
682
+ }
683
+ if (test.parent) {
684
+ const parentRes = this.getRootParentFile(test.parent) || (test.parent.ctx && test.parent.ctx.currentTest ? this.getRootParentFile(test.parent.ctx.currentTest) : null);
685
+ if(parentRes) return parentRes;
686
+
687
+ if(test.parent.suites && test.parent.suites.length > 0) {
688
+ test.parent.suites.forEach(suite => {
689
+ const suiteRes = suite.ctx ? this.getRootParentFile(suite.ctx) : null;
690
+ if(suiteRes) return suiteRes;
691
+ });
692
+ }
693
+ }
694
+
695
+ return null
696
+ }
697
+ }
698
+
699
+ module.exports = MyReporter;