-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathindex.js
More file actions
901 lines (803 loc) · 34.6 KB
/
index.js
File metadata and controls
901 lines (803 loc) · 34.6 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
'use strict';
const util = require('util');
const fs = require('fs');
const path = require('path');
const { requireModule } = require('../helper/helper');
const Base = requireModule('mocha/lib/reporters/base.js'),
utils = requireModule('mocha/lib/utils.js');
const color = Base.color;
const Mocha = requireModule('mocha');
// const Runnable = requireModule('mocha/lib/runnable');
const Runnable = require('mocha/lib/runnable'); // need to handle as this isn't present in older mocha versions
const { v4: uuidv4 } = require('uuid');
const http = require('http');
const { IPC_EVENTS, TEST_REPORTING_ANALYTICS } = require('../helper/constants');
const { startIPCServer } = require('../plugin/ipcServer');
const HOOK_TYPES_MAP = {
"before all": "BEFORE_ALL",
"after all": "AFTER_ALL",
"before each": "BEFORE_EACH",
"after each": "AFTER_EACH",
}
const {
EVENT_RUN_END,
EVENT_TEST_BEGIN,
EVENT_TEST_END,
EVENT_TEST_PENDING,
EVENT_RUN_BEGIN,
EVENT_TEST_FAIL,
EVENT_TEST_PASS,
EVENT_SUITE_BEGIN,
EVENT_SUITE_END,
EVENT_HOOK_BEGIN,
EVENT_HOOK_END
} = Mocha.Runner.constants;
const {
STATE_PASSED,
STATE_PENDING,
STATE_FAILED,
} = Runnable.constants;
const {
uploadEventData,
failureData,
PathHelper,
getTestEnv,
getHookDetails,
getHooksForTest,
mapTestHooks,
debug,
isBrowserstackInfra,
getHookSkippedTests,
getOSDetailsFromSystem,
findGitConfig,
getFileSeparatorData,
setCrashReportingConfigFromReporter,
debugOnConsole
} = require('../helper/helper');
const { consoleHolder } = require('../helper/constants');
const { shouldProcessEventForTesthub } = require('../../testhub/utils');
// this reporter outputs test results, indenting two spaces per suite
class MyReporter {
constructor(runner, options) {
this.testObservability = true;
Base.call(this, runner, options);
this._testEnv = getTestEnv();
this._paths = new PathHelper({ cwd: process.cwd() }, this._testEnv.location_prefix);
this.currentTestSteps = [];
this.httpServer = null;
this.currentTestCucumberSteps = [];
this.hooksStarted = {};
this.beforeHooks = [];
this.testIdMap = {};
this.internalIdMap = {};
this.platformDetailsMap = {};
this.runStatusMarkedHash = {};
this.haveSentBuildUpdate = false;
this.startHttpServer();
this.registerListeners();
setCrashReportingConfigFromReporter(null, process.env.OBS_CRASH_REPORTING_BS_CONFIG_PATH, process.env.OBS_CRASH_REPORTING_CYPRESS_CONFIG_PATH);
runner
.once(EVENT_RUN_BEGIN, async () => {
})
.on(EVENT_SUITE_BEGIN, (suite) => {
})
.on(EVENT_HOOK_BEGIN, async (hook) => {
if (this.isInternalHook(hook)) return;
debugOnConsole(`[MOCHA EVENT] EVENT_HOOK_BEGIN`);
if(shouldProcessEventForTesthub()) {
if(!hook.hookAnalyticsId) {
hook.hookAnalyticsId = uuidv4();
} else if(this.runStatusMarkedHash[hook.hookAnalyticsId]) {
delete this.runStatusMarkedHash[hook.hookAnalyticsId];
hook.hookAnalyticsId = uuidv4();
}
if (hook.id) this.internalIdMap[hook.id] = hook.hookAnalyticsId;
debugOnConsole(`[MOCHA EVENT] EVENT_HOOK_BEGIN for uuid: ${hook.hookAnalyticsId}`);
hook.hook_started_at = (new Date()).toISOString();
hook.started_at = (new Date()).toISOString();
this.current_hook = hook;
await this.sendTestRunEvent(hook,undefined,false,"HookRunStarted");
}
})
.on(EVENT_HOOK_END, async (hook) => {
if (this.isInternalHook(hook)) return;
debugOnConsole(`[MOCHA EVENT] EVENT_HOOK_END`);
if(shouldProcessEventForTesthub()) {
if(!this.runStatusMarkedHash[hook.hookAnalyticsId]) {
if(!hook.hookAnalyticsId) {
/* Hook objects don't maintain uuids in Cypress-Mocha */
hook.hookAnalyticsId = this.current_hook.hookAnalyticsId;
this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] = true;
} else {
this.runStatusMarkedHash[hook.hookAnalyticsId] = true;
}
// Remove hooks added at hook start
delete this.hooksStarted[hook.hookAnalyticsId];
debugOnConsole(`[MOCHA EVENT] EVENT_HOOK_END for uuid: ${hook.hookAnalyticsId}`);
await this.sendTestRunEvent(hook,undefined,false,"HookRunFinished");
}
}
})
.on(EVENT_SUITE_END, (suite) => {
if (suite.root) {
debugOnConsole(`[MOCHA EVENT] EVENT_SUITE_END for root suite`);
this.internalIdMap = {};
}
})
.on(EVENT_TEST_PASS, async (test) => {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PASS`);
if(shouldProcessEventForTesthub()) {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PASS for uuid: ${test.testAnalyticsId}`);
if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
await this.sendTestRunEvent(test);
}
}
})
.on(EVENT_TEST_FAIL, async (test, err) => {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_FAIL`);
if(shouldProcessEventForTesthub()) {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_FAIL for uuid: ${test.testAnalyticsId}`);
if((test.testAnalyticsId && !this.runStatusMarkedHash[test.testAnalyticsId]) || (test.hookAnalyticsId && !this.runStatusMarkedHash[test.hookAnalyticsId])) {
if(test.testAnalyticsId) {
this.runStatusMarkedHash[test.testAnalyticsId] = true;
await this.sendTestRunEvent(test,err);
} else if(test.hookAnalyticsId) {
this.runStatusMarkedHash[test.hookAnalyticsId] = true;
await this.sendTestRunEvent(test,err,false,"HookRunFinished");
}
}
}
})
.on(EVENT_TEST_PENDING, async (test) => {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PENDING`);
if(shouldProcessEventForTesthub()) {
if(!test.testAnalyticsId) test.testAnalyticsId = uuidv4();
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PENDING for uuid: ${test.testAnalyticsId}`);
if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
this.runStatusMarkedHash[test.testAnalyticsId] = true;
await this.sendTestRunEvent(test,undefined,false,"TestRunSkipped");
}
}
})
.on(EVENT_TEST_BEGIN, async (test) => {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_BEGIN for uuid: ${test.testAnalyticsId}`);
if (this.runStatusMarkedHash[test.testAnalyticsId]) return;
if(shouldProcessEventForTesthub()) {
await this.testStarted(test);
}
})
.on(EVENT_TEST_END, async (test) => {
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_BEGIN for uuid: ${test.testAnalyticsId}`);
if (this.runStatusMarkedHash[test.testAnalyticsId]) return;
if(shouldProcessEventForTesthub()) {
if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
await this.sendTestRunEvent(test);
}
}
})
.once(EVENT_RUN_END, async () => {
try {
debugOnConsole(`[MOCHA EVENT] EVENT_RUN_END`);
if(shouldProcessEventForTesthub()) {
const hookSkippedTests = getHookSkippedTests(this.runner.suite);
for(const test of hookSkippedTests) {
if(!test.testAnalyticsId) test.testAnalyticsId = uuidv4();
debugOnConsole(`[MOCHA EVENT] EVENT_RUN_END TestRunSkipped for uuid: ${test.testAnalyticsId}`);
await this.sendTestRunEvent(test,undefined,false,"TestRunSkipped");
}
}
} catch(err) {
debug(`Exception in populating test data for hook skipped test with error : ${err}`, true, err);
}
await this.uploadTestSteps();
});
}
isInternalHook(hook) {
if (!hook || !hook.body) return false;
const body = hook.body.toString();
// Keep your existing check for BrowserStack internal helpers
if (body.includes('/* browserstack internal helper hook */')) {
return true;
}
// Filter duplicate hooks caused by @badeball
const isBadeballInternal =
body.includes('beforeEachHandler.call(this, context)') ||
body.includes('afterEachHandler.call(this, context)') ||
body.includes('beforeHandler.call(this, context)') ||
body.includes('afterHandler.call(this, context)');
if (isBadeballInternal) {
return true;
}
return false;
}
async startHttpServer() {
if(this.httpServer !== null) return;
try {
const httpModule = http;
this.httpServer = httpModule.createServer(async(req, res) => {
try {
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
const query = parsedUrl.searchParams;
if (pathname === '/test-uuid' && req.method === 'GET') {
const testIdentifier = query.get('testIdentifier');
if (!testIdentifier) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'testIdentifier parameter is required',
testRunUuid: null
}));
return;
}
const testRunUuid = this.getTestId(testIdentifier);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ testRunUuid: testRunUuid }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
} catch (error) {
debugOnConsole(`Exception in handling HTTP request : ${error}`);
debug(`Exception in handling HTTP request : ${error}`, true, error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ testRunUuid: null }));
}
});
const port = process.env.REPORTER_API_PORT_NO;
this.httpServer.on('error', (error) => {
if (error.code === 'EADDRINUSE') {
debugOnConsole(`Port ${port} is already in use. HTTP server could not start.`);
debug(`Port ${port} is already in use. HTTP server could not start.`, true, error);
} else {
debugOnConsole(`Exception in starting reporter server : ${error}`);
debug(`Exception in starting reporter server : ${error}`, true, error);
}
});
this.httpServer.listen(port, '127.0.0.1', async () => {
console.log(`Reporter HTTP server listening on port ${port}`);
});
} catch (error) {
debugOnConsole(`Exception in starting reporter server : ${error}`);
debug(`Exception in starting reporter server : ${error}`, true, error);
}
}
registerListeners() {
startIPCServer(
(server) => {
server.on(IPC_EVENTS.CONFIG, this.cypressConfigListener.bind(this));
server.on(IPC_EVENTS.LOG, this.cypressLogListener.bind(this));
server.on(IPC_EVENTS.SCREENSHOT, this.cypressScreenshotListener.bind(this));
server.on(IPC_EVENTS.COMMAND, this.cypressCommandListener.bind(this));
server.on(IPC_EVENTS.CUCUMBER, this.cypressCucumberStepListener.bind(this));
server.on(IPC_EVENTS.PLATFORM_DETAILS, this.cypressPlatformDetailsListener.bind(this));
},
(server) => {
server.off(IPC_EVENTS.CONFIG, '*');
server.off(IPC_EVENTS.LOG, '*');
server.off(IPC_EVENTS.SCREENSHOT, '*');
},
);
}
testStarted = async (test) => {
try {
const lastTest = this.current_test;
this.current_test = test;
test.retryOf = null;
test.testAnalyticsId = uuidv4();
if (test.id) this.internalIdMap[test.id] = test.testAnalyticsId;
debugOnConsole(`[MOCHA EVENT] EVENT_TEST_BEGIN for uuid: ${test.testAnalyticsId}`);
test.started_at = (new Date()).toISOString();
test.test_started_at = test.started_at;
if(test._currentRetry > 0 && lastTest && lastTest.title == test.title) {
/* Sending async to current test start to avoid current test end call getting fired before its start call */
test.retryOf = lastTest.testAnalyticsId
await this.sendTestRunEvent(test, undefined, false, "TestRunStarted");
lastTest.state = STATE_FAILED;
await this.sendTestRunEvent(lastTest, undefined, true);
} else {
await this.sendTestRunEvent(test, undefined, false, "TestRunStarted");
}
this.lastTest = lastTest;
} catch(err) {
debug(`Exception in populating test data for test start with error : ${err}`, true, err);
}
}
uploadTestSteps = async (shouldClearCurrentSteps = true, cypressSteps = null) => {
const currentTestSteps = cypressSteps ? cypressSteps : JSON.parse(JSON.stringify(this.currentTestSteps));
if(shouldClearCurrentSteps && !cypressSteps) {
this.currentTestSteps = [];
}
if (!currentTestSteps || currentTestSteps.length === 0) {
return;
}
/* TODO - Send as test logs */
const allStepsAsLogs = [];
currentTestSteps.forEach(step => {
const currentStepAsLog = {
test_run_uuid : step.test_run_uuid,
hook_run_uuid : step.hook_run_uuid,
timestamp: step.started_at,
duration: step.duration,
level: step.result,
message: step.text,
failure: step.failure,
failure_reason: step.failure_reason,
failure_type: step.failure_type,
kind: 'TEST_STEP',
http_response: {}
};
allStepsAsLogs.push(currentStepAsLog);
});
await uploadEventData({
event_type: 'LogCreated',
logs: allStepsAsLogs
});
}
sendTestRunEvent = async (test, err = undefined, customFinished=false, eventType = "TestRunFinished") => {
try {
if(test.body && test.body.match(/browserstack internal helper hook/)) return;
let failureArgs = [];
if(test.state === STATE_FAILED || eventType.match(/HookRun/)) {
if(test.err !== undefined) {
failureArgs = test.err.multiple ? [test.err.multiple, 'test'] : [test.err, 'err'];
} else if(err !== undefined) {
failureArgs = [err, 'err'];
} else {
failureArgs = [];
}
}
const failureReason = test.err !== undefined ? test.err.toString() : err !== undefined ? err.toString() : undefined;
if(eventType == 'TestRunFinished' && failureReason && this.currentTestCucumberSteps.length) {
this.currentTestCucumberSteps[this.currentTestCucumberSteps.length - 1] = {
...this.currentTestCucumberSteps[this.currentTestCucumberSteps.length - 1],
result: 'failed'
}
}
let rootParentFile;
try {
rootParentFile = this.getRootParentFile(test)
} catch(e) {
rootParentFile = null;
}
let gitConfigPath = process.env.OBSERVABILITY_GIT_CONFIG_PATH ? process.env.OBSERVABILITY_GIT_CONFIG_PATH.toString() : (rootParentFile ? findGitConfig(rootParentFile) : null);
if(!isBrowserstackInfra()) gitConfigPath = process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL ? process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL.toString() : null;
const prefixedTestPath = rootParentFile ? this._paths.prefixTestPath(rootParentFile) : 'File path could not be found';
const fileSeparator = getFileSeparatorData();
let testData = {
'framework': 'Cypress',
'uuid': (eventType.includes("Test") ? test.testAnalyticsId : test.hookAnalyticsId) || uuidv4(),
'name': test.title,
'body': {
'lang': 'javascript',
'code': test.body
},
'scope': this.scope(test),
'scopes': this.scopes(test),
'identifier': test.fullTitle(),
'file_name': prefixedTestPath.replaceAll("\\", "/"),
'vc_filepath': !isBrowserstackInfra() ? ( gitConfigPath ? path.relative(gitConfigPath, rootParentFile) : null ) : ( gitConfigPath ? ((gitConfigPath == 'DEFAULT' ? '' : gitConfigPath) + fileSeparator + rootParentFile).replaceAll("\\", "/") : null ),
'location': prefixedTestPath.replaceAll("\\", "/"),
'result': eventType === "TestRunSkipped" ? 'skipped' : ( eventType === "TestRunStarted" ? 'pending' : this.analyticsResult(test, eventType, err) ),
'failure_reason': failureReason,
'duration_in_ms': test.duration || (eventType.match(/Finished/) || eventType.match(/Skipped/) ? Date.now() - (new Date(test.started_at)).getTime() : null),
'started_at': ( ( (eventType.match(/TestRun/) ? test.test_started_at : test.hook_started_at) || test.started_at ) || (new Date()).toISOString() ),
'finished_at': eventType.match(/Finished/) || eventType.match(/Skipped/) ? (new Date()).toISOString() : null,
'failure': failureData(...failureArgs),
'failure_type': !failureReason ? null : failureReason.match(/AssertionError/) ? 'AssertionError' : 'UnhandledError',
'retry_of': test.retryOf,
'meta': {
steps: []
}
};
debugOnConsole(`${eventType} for uuid: ${testData.uuid}`);
this.mapTestId(testData, eventType);
if(eventType.match(/TestRunFinished/) || eventType.match(/TestRunSkipped/)) {
testData['meta'].steps = JSON.parse(JSON.stringify(this.currentTestCucumberSteps));
this.currentTestCucumberSteps = [];
}
const { os, os_version } = await getOSDetailsFromSystem(process.env.observability_product);
if(process.env.observability_integration) {
testData = {...testData, integrations: {
[process.env.observability_integration || 'local_grid' ]: {
'build_id': process.env.observability_build_id,
'session_id': process.env.observability_automate_session_id + btoa(prefixedTestPath.replaceAll("\\", "/")),
'capabilities': {},
'product': process.env.observability_product,
'platform': process.env.observability_os || os,
'platform_version': process.env.observability_os_version || os_version,
'browser': process.env.observability_browser,
'browser_version': process.env.observability_browser_version
}
}};
} else if(this.platformDetailsMap[process.pid] && this.platformDetailsMap[process.pid][test.title]) {
const {browser, platform} = this.platformDetailsMap[process.pid][test.title];
testData = {...testData, integrations: {
'local_grid': {
'capabilities': {},
'platform': os,
'platform_version': os_version,
'browser': browser.name,
'browser_version': browser.majorVersion
}
}};
if(eventType === "TestRunFinished" || eventType === "TestRunSkipped") {
delete this.platformDetailsMap[process.pid][test.title];
}
}
if (eventType === "TestRunSkipped" && !testData['started_at']) {
testData['started_at'] = testData['finished_at'];
}
try {
if(eventType.match(/HookRun/)) {
[testData.hook_type, testData.name] = getHookDetails(test.fullTitle() || test.originalTitle || test.title);
if(eventType === "HookRunFinished") {
if(testData.result === 'pending') testData.result = 'passed';
if(testData.hook_type == 'before each' && testData.result === 'failed' && ( !this.runStatusMarkedHash[test.ctx.currentTest.testAnalyticsId] )) {
if(test.ctx.currentTest.testAnalyticsId) this.runStatusMarkedHash[test.ctx.currentTest.testAnalyticsId] = true;
test.ctx.currentTest.state = STATE_FAILED;
await this.sendTestRunEvent(test.ctx.currentTest,undefined,true);
}
}
if(testData.hook_type.includes('each')) {
testData['test_run_id'] = testData['test_run_id'] || test.testAnalyticsId;
} else if(testData.hook_type.includes('after')) {
testData['test_run_id'] = this.lastTest ? this.lastTest.testAnalyticsId : testData['test_run_id'];
}
} else if(eventType.match(/TestRun/)) {
mapTestHooks(test);
}
} catch(e) {
debugOnConsole(`Exception in processing hook data for event ${eventType} with error : ${e}`);
debug(`Exception in processing hook data for event ${eventType} with error : ${e}`, true, e);
}
const failure_data = testData['failure'][0];
if (failure_data) {
testData['failure_backtrace'] = failure_data['backtrace']
testData['failure_reason_expanded'] = failure_data['expanded']
}
if(["TestRunFinished","TestRunSkipped"].includes(eventType)) {
testData.hooks = getHooksForTest(test);
}
let uploadData = {
event_type: eventType === "TestRunSkipped" ? "TestRunFinished" : eventType,
}
if(eventType == "HookRunFinished") delete testData.started_at;
if(eventType.match(/HookRun/)) {
testData['hook_type'] = HOOK_TYPES_MAP[testData['hook_type']];
uploadData['hook_run'] = testData;
} else {
uploadData['test_run'] = testData;
}
if(eventType == 'HookRunFinished' && testData['hook_type'] == 'BEFORE_ALL') {
uploadData.cypressSteps = JSON.parse(JSON.stringify(this.currentTestSteps));
this.beforeHooks.push(uploadData);
this.currentTestSteps = [];
} else {
await uploadEventData(uploadData);
if(eventType.match(/Finished/)) {
await this.uploadTestSteps();
}
if(eventType.match(/TestRun/)) {
this.beforeHooks.forEach(async(hookUploadObj) => {
const currentTestSteps = hookUploadObj.cypressSteps;
delete hookUploadObj.cypressSteps;
hookUploadObj['hook_run']['test_run_id'] = test.testAnalyticsId;
await uploadEventData(hookUploadObj);
await this.uploadTestSteps(false, currentTestSteps);
});
this.beforeHooks = [];
}
}
if(!this.haveSentBuildUpdate && (process.env.observability_framework_version || this.currentCypressVersion)) {
this.shouldSendBuildUpdate = true;
const buildUpdateData = {
event_type: 'BuildUpdate',
'misc': {
observability_version: {
frameworkName: "Cypress",
sdkVersion: process.env.OBSERVABILITY_LAUNCH_SDK_VERSION,
frameworkVersion: ( process.env.observability_framework_version || this.currentCypressVersion )
}
}
};
await uploadEventData(buildUpdateData);
}
// Add started hooks to the hash
if(eventType === 'HookRunStarted' && ['BEFORE_EACH', 'AFTER_EACH', 'BEFORE_ALL'].includes(testData['hook_type'])) {
this.hooksStarted[testData.uuid] = uploadData;
}
// Send pending hook finsihed events for hook starts
if (eventType === 'TestRunFinished' || eventType === 'TestRunSkipped') {
Object.values(this.hooksStarted).forEach(async hookData => {
hookData['event_type'] = 'HookRunFinished';
hookData['hook_run'] = {
...hookData['hook_run'],
result: uploadData['test_run'].result,
failure: uploadData['test_run'].failure,
failure_type: uploadData['test_run'].failure_type,
failure_reason: uploadData['test_run'].failure_reason,
failure_reason_expanded: uploadData['test_run'].failure_reason_expanded,
failure_backtrace: uploadData['test_run'].failure_backtrace
}
if (hookData['hook_run']['hook_type'] === 'BEFORE_ALL') {
hookData['hook_run'].finished_at = uploadData['test_run'].finished_at;
hookData['hook_run'].duration_in_ms = new Date(hookData['hook_run'].finished_at).getTime() - new Date(hookData['hook_run'].started_at).getTime();
} else {
hookData['hook_run'].finished_at = hookData['hook_run'].started_at;
hookData['hook_run'].duration_in_ms = 0;
}
await uploadEventData(hookData);
})
this.hooksStarted = {};
}
} catch(error) {
debugOnConsole(`Exception in populating test data for event ${eventType} with error : ${error}`);
debug(`Exception in populating test data for event ${eventType} with error : ${error}`, true, error);
}
}
mapTestId = (testData, eventType) => {
if (!eventType.match(/TestRun/)) {return}
this.testIdMap[testData.name] = testData.uuid;
}
getTestId = (testIdentifier) => {
return this.testIdMap[testIdentifier] || null;
}
appendTestItemLog = async (log) => {
try {
if(this.current_hook && ( this.current_hook.hookAnalyticsId && !this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] )) {
log.hook_run_uuid = this.current_hook.hookAnalyticsId;
}
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;
if(log.hook_run_uuid || log.test_run_uuid) {
await uploadEventData({
event_type: 'LogCreated',
logs: [log]
});
}
} catch(error) {
debug(`Exception in uploading log data to ${TEST_REPORTING_ANALYTICS} with error : ${error}`, true, error);
}
}
cypressConfigListener = async (config) => {
}
cypressCucumberStepListener = async ({log, started_at, finished_at}) => {
if(log.name == 'step' && log.consoleProps && log.consoleProps.step && log.consoleProps.step.keyword) {
this.currentTestCucumberSteps = [
...this.currentTestCucumberSteps,
{
id: log.chainerId,
keyword: log.consoleProps.step.keyword,
text: log.consoleProps.step.text,
started_at: started_at || new Date().toISOString(),
finished_at: finished_at || new Date().toISOString(),
duration: 0,
result: 'passed'
}
];
} else if(log.name == 'then' && log.type == 'child' && log.chainerId) {
this.currentTestCucumberSteps.forEach((gherkinStep, idx) => {
if(gherkinStep.id == log.chainerId) {
this.currentTestCucumberSteps[idx] = {
...gherkinStep,
finished_at: finished_at || new Date().toISOString(),
duration: (finished_at ? new Date(finished_at).getTime() : Date.now()) - (new Date(gherkinStep.started_at)).getTime(),
result: log.state,
failure: log.err?.stack || log.err?.message,
failure_reason: log.err?.stack || log.err?.message,
failure_type: log.err?.name || 'UnhandledError'
}
}
})
}
}
cypressLogListener = async ({timestamp, level, message}) => {
this.appendTestItemLog({
timestamp: timestamp || new Date().toISOString(),
level: level.toUpperCase(),
message,
kind: 'TEST_LOG',
http_response: {}
});
}
cypressScreenshotListener = async ({logMessage, screenshotInfo}) => {
if(screenshotInfo.path) {
const screenshotAsBase64 = fs.readFileSync(screenshotInfo.path, {encoding: 'base64'});
if(screenshotAsBase64) {
this.appendTestItemLog({
timestamp: screenshotInfo.takenAt || new Date().toISOString(),
message: screenshotAsBase64,
kind: 'TEST_SCREENSHOT'
});
}
}
}
cypressPlatformDetailsListener = async({testTitle, browser, platform, cypressVersion}) => {
if(!process.env.observability_integration) {
this.platformDetailsMap[process.pid] = this.platformDetailsMap[process.pid] || {};
if(testTitle) this.platformDetailsMap[process.pid][testTitle] = { browser, platform };
}
this.currentCypressVersion = cypressVersion;
}
getFormattedArgs = (args) => {
if(!args) return '';
let res = '';
args.forEach((val) => {
res = res + (res.length ? ', ' : '') + JSON.stringify(val);
});
return res;
}
cypressCommandListener = async ({type, command}) => {
if(!command || command?.attributes?.name == 'then') return;
if(type == 'COMMAND_RETRY') {
command.id = command._log.chainerId;
}
if(type == 'COMMAND_START') {
let isCommandPresent = null;
for(let idx=0; idx<this.currentTestSteps.length; idx++) {
if(this.currentTestSteps[idx].id == command.attributes.id) {
isCommandPresent = idx;
break;
}
}
/* COMMAND_END reported before COMMAND_START */
if(isCommandPresent) {
return;
}
const cypressTestId = command.testId || command.attributes?.testId;
const cypressHookId = command.hookId || command.attributes?.hookId;
const currentStepObj = {
id: command.attributes.id,
text: 'cy.' + command.attributes.name + '(' + this.getFormattedArgs(command.attributes.args) + ')',
started_at: command.started_at || new Date().toISOString(),
finished_at: null,
duration: null,
result: 'pending',
test_run_uuid: command.location === 'test'
? (this.internalIdMap[cypressTestId] || this.current_test?.testAnalyticsId) : null,
hook_run_uuid : command.location === 'hook'
? (this.internalIdMap[cypressHookId] || this.current_hook?.hookAnalyticsId) : null
};
if(currentStepObj.hook_run_uuid && currentStepObj.test_run_uuid) delete currentStepObj.test_run_uuid;
this.currentTestSteps = [
...this.currentTestSteps,
currentStepObj
];
} else if(type == 'COMMAND_END') {
let stepUpdated = false;
this.currentTestSteps.forEach((val, idx) => {
if(val.id == command.attributes.id) {
this.currentTestSteps[idx] = {
...val,
finished_at: command.finished_at || new Date().toISOString(),
duration: (command.finished_at ? new Date(command.finished_at).getTime() : Date.now()) - (new Date(val.started_at)).getTime(),
result: command.state
};
stepUpdated = true;
}
});
if(!stepUpdated) {
/* COMMAND_END reported before COMMAND_START */
const cypressTestId = command.testId || command.attributes?.testId;
const cypressHookId = command.hookId || command.attributes?.hookId;
const currentStepObj = {
id: command.attributes.id,
text: 'cy.' + command.attributes.name + '(' + this.getFormattedArgs(command.attributes.args) + ')',
started_at: new Date().toISOString(),
finished_at: new Date().toISOString(),
duration: 0,
result: command.state,
test_run_uuid: command.location === 'test'
? (this.internalIdMap[cypressTestId] || this.current_test?.testAnalyticsId) : null,
hook_run_uuid : command.location === 'hook'
? (this.internalIdMap[cypressHookId] || this.current_hook?.hookAnalyticsId) : null
};
if(currentStepObj.hook_run_uuid && currentStepObj.test_run_uuid) delete currentStepObj.test_run_uuid;
this.currentTestSteps = [
...this.currentTestSteps,
currentStepObj
];
}
} else if(type == 'COMMAND_RETRY') {
if(!command.id) return;
let isRetryStepFound = false;
/* Parse steps array in reverse and update the last step with common chainerId */
for(let idx=this.currentTestSteps.length-1; idx>=0; idx--) {
const val = this.currentTestSteps[idx];
if(val.id.includes(command.id)) {
this.currentTestSteps[idx] = {
...val,
failure: command?.error?.message,
failure_reason: command?.error?.message,
failure_type: command?.error?.isDefaultAssertionErr ? 'AssertionError' : 'UnhandledError',
finished_at: new Date().toISOString(),
duration: Date.now() - (new Date(val.started_at)).getTime(),
result: command?.error?.message ? 'failed' : 'pending'
};
isRetryStepFound = true;
break;
}
}
/* As a backup, parse steps array in reverse and update the last step with pending status */
if(!isRetryStepFound) {
for(let idx=this.currentTestSteps.length-1; idx>=0; idx--) {
const val = this.currentTestSteps[idx];
if(val.state == 'pending') {
this.currentTestSteps[idx] = {
...val,
failure: command?.error?.message,
failure_reason: command?.error?.message,
failure_type: command?.error?.isDefaultAssertionErr ? 'AssertionError' : 'UnhandledError',
finished_at: new Date().toISOString(),
duration: Date.now() - (new Date(val.started_at)).getTime(),
result: command?.error?.message ? 'failed' : 'pending'
};
isRetryStepFound = true;
break;
}
}
}
}
}
analyticsResult(test, eventType, err) {
if(eventType.match(/HookRun/)) {
if(test.isFailed() || test.err || err) {
return 'failed';
} else if(eventType == 'HookRunFinished') {
return 'passed';
} else {
return 'pending';
}
} else {
return {
[STATE_PASSED]: 'passed',
[STATE_PENDING]: 'pending',
[STATE_FAILED]: 'failed',
}[test.state]
}
}
scope(test) {
const titlePath = test.titlePath()
// titlePath returns an array of the scope + the test title.
// as the test title is the last array item, we just remove it
// and then join the rest of the array as a space separated string
return titlePath.slice(0, titlePath.length - 1).join(' ')
}
scopes(test) {
const titlePath = test.titlePath()
return titlePath.slice(0, titlePath.length - 1)
}
// Recursively find the root parent, and return the parents file
// This is required as test.file can be undefined in some tests on cypress
getRootParentFile(test) {
if (test.file) {
return test.file
}
if(test.ctx) {
const ctxRes = (test.ctx.currentTest ? this.getRootParentFile(test.ctx.currentTest) : null);
if(ctxRes) return ctxRes;
}
if (test.parent) {
const parentRes = this.getRootParentFile(test.parent) || (test.parent.ctx && test.parent.ctx.currentTest ? this.getRootParentFile(test.parent.ctx.currentTest) : null);
if(parentRes) return parentRes;
if(test.parent.suites && test.parent.suites.length > 0) {
test.parent.suites.forEach(suite => {
const suiteRes = suite.ctx ? this.getRootParentFile(suite.ctx) : null;
if(suiteRes) return suiteRes;
});
}
}
return null
}
}
module.exports = MyReporter;