-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathcypress-plugin.js
More file actions
2040 lines (1860 loc) · 72.6 KB
/
Copy pathcypress-plugin.js
File metadata and controls
2040 lines (1860 loc) · 72.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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
// Capture real timers at module load, before any test can install fake timers.
const { performance } = require('perf_hooks')
const { basename } = require('node:path')
const dateNow = Date.now
const { createCoverageMap } = require('../../../vendor/dist/istanbul-lib-coverage')
const satisfies = require('../../../vendor/dist/semifies')
const { RUM_TEST_EXECUTION_ID_COOKIE_NAME } = require('../../dd-trace/src/ci-visibility/rum')
const {
EMPTY_EFD_RETRY_POLICY,
getEfdRetryCountForDuration,
hasEfdRetries,
shouldSkipEfdRetry,
} = require('../../dd-trace/src/ci-visibility/efd-retry-policy')
const {
TEST_STATUS,
setRumTestTags,
TEST_CODE_OWNERS,
getTestEnvironmentMetadata,
getTestLevelsMetadataTags,
CI_APP_ORIGIN,
getTestParentSpan,
getCodeOwnersFileEntries,
getCodeOwnersForFilename,
getTestCommonTags,
getTestSessionCommonTags,
getTestModuleCommonTags,
getTestSuiteCommonTags,
TEST_SUITE_ID,
TEST_MODULE_ID,
TEST_SESSION_ID,
TEST_COMMAND,
TEST_LEVELS_METADATA,
TEST_MODULE,
TEST_SOURCE_START,
finishAllTraceSpans,
getCoveredFilesFromCoverage,
getExecutableFilesFromCoverage,
getRelativeCoverageFiles,
getTestCoverageLinesPercentage,
applySkippedCoverageToCoverage,
mergeCoverage,
getTestSuitePath,
addIntelligentTestRunnerSpanTags,
TEST_SKIPPED_BY_ITR,
TEST_ITR_UNSKIPPABLE,
TEST_ITR_FORCED_RUN,
TEST_ITR_SKIPPING_ENABLED,
ITR_CORRELATION_ID,
TEST_SOURCE_FILE,
TEST_IS_NEW,
TEST_IS_RETRY,
TEST_EARLY_FLAKE_ENABLED,
TEST_EARLY_FLAKE_ABORT_REASON,
getTestSessionName,
TEST_SESSION_NAME,
TEST_RETRY_REASON,
DD_TEST_IS_USER_PROVIDED_SERVICE,
TEST_MANAGEMENT_IS_QUARANTINED,
TEST_MANAGEMENT_ENABLED,
TEST_MANAGEMENT_IS_DISABLED,
TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX,
TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED,
TEST_HAS_FAILED_ALL_RETRIES,
getLibraryCapabilitiesTags,
TEST_RETRY_REASON_TYPES,
getPullRequestDiff,
getModifiedFilesFromDiff,
getSessionRequestErrorTags,
DD_CI_LIBRARY_CONFIGURATION_ERROR_SETTINGS,
DD_CI_LIBRARY_CONFIGURATION_ERROR_KNOWN_TESTS,
DD_CI_LIBRARY_CONFIGURATION_ERROR_SKIPPABLE_TESTS,
DD_CI_LIBRARY_CONFIGURATION_ERROR_TEST_MANAGEMENT_TESTS,
getSessionItrSkippingEnabledTags,
TEST_IS_MODIFIED,
TEST_HAS_DYNAMIC_NAME,
getIsFaultyEarlyFlakeDetection,
DYNAMIC_NAME_RE,
isMarkedAsUnskippable,
recordAttemptToFixExecution,
recordTestManagementExecution,
logAttemptToFixTestExecution,
logTestOptimizationSummary,
getPullRequestBaseBranch,
TEST_FINAL_STATUS,
getTestOptimizationRequestResults,
} = require('../../dd-trace/src/plugins/util/test')
const { ORIGIN_KEY, COMPONENT } = require('../../dd-trace/src/constants')
const { RESOURCE_NAME } = require('../../../ext/tags')
const getConfig = require('../../dd-trace/src/config')
const {
SCREENSHOT_UPLOAD_RESULT_ERROR,
SCREENSHOT_UPLOAD_RESULT_UPLOADED,
getScreenshotCapturedAtMs,
getScreenshotUploadResult,
setScreenshotUploadTags,
} = require('../../dd-trace/src/ci-visibility/test-screenshot')
const { appClosing: appClosingTelemetry } = require('../../dd-trace/src/telemetry')
const log = require('../../dd-trace/src/log')
const {
TELEMETRY_EVENT_CREATED,
TELEMETRY_EVENT_FINISHED,
TELEMETRY_ITR_FORCED_TO_RUN,
TELEMETRY_CODE_COVERAGE_EMPTY,
TELEMETRY_ITR_UNSKIPPABLE,
TELEMETRY_CODE_COVERAGE_NUM_FILES,
incrementCountMetric,
distributionMetric,
TELEMETRY_ITR_SKIPPED,
TELEMETRY_TEST_SESSION,
} = require('../../dd-trace/src/ci-visibility/telemetry')
const {
GIT_REPOSITORY_URL,
GIT_COMMIT_SHA,
GIT_BRANCH,
CI_PROVIDER_NAME,
CI_WORKSPACE_PATH,
GIT_COMMIT_MESSAGE,
GIT_TAG,
GIT_PULL_REQUEST_BASE_BRANCH_SHA,
GIT_COMMIT_HEAD_SHA,
GIT_PULL_REQUEST_BASE_BRANCH,
GIT_COMMIT_HEAD_MESSAGE,
} = require('../../dd-trace/src/plugins/util/tags')
const {
OS_VERSION,
OS_PLATFORM,
OS_ARCHITECTURE,
RUNTIME_NAME,
RUNTIME_VERSION,
} = require('../../dd-trace/src/plugins/util/env')
const { DD_MAJOR } = require('../../../version')
const {
resolveOriginalSourceFile,
resolveSourceLineForTest,
shouldTrustInvocationDetailsLine,
} = require('./source-map-utils')
const TEST_FRAMEWORK_NAME = 'cypress'
let hasWarnedDeprecatedCypressVersion = false
const CYPRESS_STATUS_TO_TEST_STATUS = {
passed: 'pass',
failed: 'fail',
pending: 'skip',
skipped: 'skip',
}
const SCREENSHOT_ATTEMPT_RE = /\(attempt \d+\)/
function getScreenshotFilePath (screenshot) {
return typeof screenshot === 'string' ? screenshot : screenshot?.path
}
function isFailureScreenshotByMetadata (screenshot, screenshotFilePath) {
if (screenshot !== null && typeof screenshot === 'object' && screenshot.testFailure !== undefined) {
return screenshot.testFailure === true
}
return screenshotFilePath.includes('(failed)')
}
function isFailureScreenshotForUpload (screenshot) {
const screenshotFilePath = getScreenshotFilePath(screenshot)
if (!screenshotFilePath) {
return false
}
if (screenshot !== null && typeof screenshot === 'object') {
// after:screenshot details omit testFailure for manual cy.screenshot() captures, so this
// path cannot safely fall back to the '(failed)' filename marker.
return screenshot.testFailure === true
}
return screenshotFilePath.includes('(failed)')
}
function isFailureScreenshot (screenshot) {
const screenshotFilePath = getScreenshotFilePath(screenshot)
// Require an explicit failure signal: prefer the `testFailure` metadata, and fall back to the
// '(failed)' filename marker only when the RunResult omits `testFailure`. This keeps manual
// cy.screenshot() captures out of the failure-screenshot upload (privacy).
return !!screenshotFilePath && isFailureScreenshotByMetadata(screenshot, screenshotFilePath)
}
function getAttemptScreenshots (cypressTest, attemptIndex) {
if (!Array.isArray(cypressTest.attempts)) {
return []
}
const attempt = cypressTest.attempts[attemptIndex]
if (!Array.isArray(attempt?.screenshots)) {
return []
}
return attempt.screenshots.filter(isFailureScreenshot)
}
function isScreenshotForTestAttempt (screenshot, titleParts, attemptIndex) {
const screenshotFilePath = getScreenshotFilePath(screenshot)
if (!screenshotFilePath || !isFailureScreenshot(screenshot)) {
return false
}
for (const titlePart of titleParts) {
if (!screenshotFilePath.includes(titlePart)) {
return false
}
}
if (attemptIndex === 0) {
return !SCREENSHOT_ATTEMPT_RE.test(screenshotFilePath)
}
return screenshotFilePath.includes(`(attempt ${attemptIndex + 1})`)
}
function getTestScreenshots (cypressTest, attemptIndex, specScreenshots) {
const attemptScreenshots = getAttemptScreenshots(cypressTest, attemptIndex)
if (attemptScreenshots.length > 0) {
return attemptScreenshots
}
if (!Array.isArray(specScreenshots)) {
return []
}
const titleParts = Array.isArray(cypressTest.title) ? cypressTest.title : []
return specScreenshots.filter(screenshot => isScreenshotForTestAttempt(screenshot, titleParts, attemptIndex))
}
function getSessionStatus (summary) {
if (summary.totalFailed !== undefined && summary.totalFailed > 0) {
return 'fail'
}
if (summary.totalSkipped !== undefined && summary.totalSkipped === summary.totalTests) {
return 'skip'
}
return 'pass'
}
function getCypressVersion (details) {
if (details?.cypressVersion) {
return details.cypressVersion
}
if (details?.config?.version) {
return details.config.version
}
return ''
}
function warnDeprecatedCypressVersion (version) {
if (DD_MAJOR >= 6 || hasWarnedDeprecatedCypressVersion || !version || !satisfies(version, '<12.0.0')) {
return
}
hasWarnedDeprecatedCypressVersion = true
// console.warn does not seem to work reliably in Cypress, so use console.log instead.
// eslint-disable-next-line no-console
console.log(
'WARNING: dd-trace support for Cypress<12.0.0 is deprecated' +
' and will not be supported in dd-trace v6. Please upgrade Cypress to >=12.0.0.'
)
}
function getRootDir (details) {
if (details?.config) {
return details.config.projectRoot || details.config.repoRoot || process.cwd()
}
return process.cwd()
}
function getCypressCommand (details) {
if (!details) {
return TEST_FRAMEWORK_NAME
}
return `${TEST_FRAMEWORK_NAME} ${details.specPattern || ''}`
}
function getIsTestIsolationEnabled (cypressConfig) {
if (!cypressConfig) {
// If we can't read testIsolation config parameter, we default to allowing retries
return true
}
return cypressConfig.testIsolation === undefined ? true : cypressConfig.testIsolation
}
function getLibraryConfiguration (tracer, testConfiguration) {
return new Promise(resolve => {
if (!tracer._tracer._exporter?.getLibraryConfiguration) {
return resolve({ err: new Error('Test Optimization was not initialized correctly') })
}
tracer._tracer._exporter.getLibraryConfiguration(testConfiguration, (err, libraryConfig) => {
resolve({ err, libraryConfig })
})
})
}
function getSkippableTests (tracer, testConfiguration) {
return new Promise(resolve => {
if (!tracer._tracer._exporter?.getSkippableSuites) {
return resolve({ err: new Error('Test Optimization was not initialized correctly') })
}
tracer._tracer._exporter.getSkippableSuites(
testConfiguration,
(err, skippableTests, correlationId, skippableTestsCoverage) => {
resolve({
err,
skippableTests,
correlationId,
skippableTestsCoverage,
})
}
)
})
}
function getKnownTests (tracer, testConfiguration) {
return new Promise(resolve => {
if (!tracer._tracer._exporter?.getKnownTests) {
return resolve({ err: new Error('Test Optimization was not initialized correctly') })
}
tracer._tracer._exporter.getKnownTests(testConfiguration, (err, knownTests) => {
resolve({
err,
knownTests,
})
})
})
}
function getTestManagementTests (tracer, testConfiguration) {
return new Promise(resolve => {
if (!tracer._tracer._exporter?.getTestManagementTests) {
return resolve({ err: new Error('Test Optimization was not initialized correctly') })
}
tracer._tracer._exporter.getTestManagementTests(testConfiguration, (err, testManagementTests) => {
resolve({
err,
testManagementTests,
})
})
})
}
function getModifiedFiles (testEnvironmentMetadata) {
const {
[GIT_PULL_REQUEST_BASE_BRANCH]: pullRequestBaseBranch,
[GIT_PULL_REQUEST_BASE_BRANCH_SHA]: pullRequestBaseBranchSha,
[GIT_COMMIT_HEAD_SHA]: commitHeadSha,
} = testEnvironmentMetadata
const baseBranchSha = pullRequestBaseBranchSha || getPullRequestBaseBranch(pullRequestBaseBranch)
if (baseBranchSha) {
const diff = getPullRequestDiff(baseBranchSha, commitHeadSha)
const modifiedFiles = getModifiedFilesFromDiff(diff)
if (modifiedFiles) {
return modifiedFiles
}
}
throw new Error('Modified tests could not be retrieved')
}
function getSuiteStatus (suiteStats) {
if (!suiteStats) {
return 'skip'
}
if (suiteStats.failures !== undefined && suiteStats.failures > 0) {
return 'fail'
}
if (suiteStats.tests !== undefined &&
(suiteStats.tests === suiteStats.pending || suiteStats.tests === suiteStats.skipped)) {
return 'skip'
}
return 'pass'
}
function getMatchingCypressTest (cypressTests, testName, attemptIndex, testStatus, preferIndexedMatch = false) {
let matchingTestByIndex
let matchingTestByStatus
let matchingTestIndex = 0
for (const cypressTest of cypressTests) {
if (cypressTest.title.join(' ') !== testName) {
continue
}
if (matchingTestIndex === attemptIndex) {
matchingTestByIndex = cypressTest
}
matchingTestIndex++
if (!matchingTestByStatus && CYPRESS_STATUS_TO_TEST_STATUS[cypressTest.state] === testStatus) {
matchingTestByStatus = cypressTest
}
}
return preferIndexedMatch
? matchingTestByIndex || matchingTestByStatus
: matchingTestByStatus || matchingTestByIndex
}
function isCypressHookFailure (cypressTest) {
return CYPRESS_STATUS_TO_TEST_STATUS[cypressTest.state] === 'fail' &&
/\bhook\b/.test(String(cypressTest.displayError || ''))
}
const FINAL_STATUS_RETRY_KIND = {
none: 'none',
atr: 'atr',
efd: 'efd',
atf: 'atf',
}
function getFinalStatusRetryKind ({ finishedTest, finishedTestAttempts, flakyTestRetriesCount }) {
// Infer retry kind from the executions we actually saw so ATR enabled with
// a retry count of 0 is still treated as a single final execution.
if (finishedTest.isAttemptToFix) {
return FINAL_STATUS_RETRY_KIND.atf
}
if (finishedTestAttempts.some(testAttempt => testAttempt.isEfdRetry)) {
return FINAL_STATUS_RETRY_KIND.efd
}
if (finishedTestAttempts.length > 1 && flakyTestRetriesCount > 0) {
return FINAL_STATUS_RETRY_KIND.atr
}
return FINAL_STATUS_RETRY_KIND.none
}
function getFinalStatus ({
status,
retryKind,
hasFailedAllRetries,
hasPassedAllAtfRetries,
isQuarantined,
isDisabled,
}) {
// If the test is quarantined or disabled, its final status is skip unless attempt-to-fix takes precedence.
if (status === 'skip' || (retryKind !== FINAL_STATUS_RETRY_KIND.atf && (isQuarantined || isDisabled))) {
return 'skip'
}
switch (retryKind) {
case FINAL_STATUS_RETRY_KIND.atr:
case FINAL_STATUS_RETRY_KIND.efd:
// These modes report the aggregate result across attempts.
return hasFailedAllRetries ? 'fail' : 'pass'
case FINAL_STATUS_RETRY_KIND.atf:
// Attempt-to-fix only passes if every execution passed.
return hasPassedAllAtfRetries ? 'pass' : 'fail'
default:
return status
}
}
class CypressPlugin {
_isInit = false
testEnvironmentMetadata = getTestEnvironmentMetadata(TEST_FRAMEWORK_NAME)
finishedTestsByFile = {}
testStatuses = {}
hasLibraryConfiguration = false
isItrEnabled = false
isTestsSkipped = false
isSuitesSkippingEnabled = false
isCodeCoverageEnabled = false
isCoverageReportUploadEnabled = false
isFlakyTestRetriesEnabled = false
flakyTestRetriesCount = 0
isEarlyFlakeDetectionEnabled = false
isEarlyFlakeDetectionFaulty = false
isKnownTestsEnabled = false
earlyFlakeDetectionRetryPolicy = EMPTY_EFD_RETRY_POLICY
efdRetryCountByTest = {}
efdSlowAbortedTests = {}
earlyFlakeDetectionFaultyThreshold = 0
testsToSkip = []
skippedTests = []
skippedTestIds = new Set()
skippableTestsCoverage
testSessionCoverageMap = createCoverageMap()
hasForcedToRunSuites = false
hasUnskippableSuites = false
unskippableSuites = []
knownTests = []
isTestManagementTestsEnabled = false
testManagementAttemptToFixRetries = 0
isImpactedTestsEnabled = false
modifiedFiles = []
newTestsWithDynamicNames = new Set()
attemptToFixExecutions = new Map()
loggedAttemptToFixTests = new Set()
uploadedScreenshotPaths = new Set()
screenshotUploadPromisesByTraceId = new Map()
screenshotUploadAbortControllers = new Set()
afterScreenshotHandler = undefined
lastFinishedTest = null
pendingScreenshotUploads = []
constructor () {
const {
[GIT_REPOSITORY_URL]: repositoryUrl,
[GIT_COMMIT_SHA]: sha,
[OS_VERSION]: osVersion,
[OS_PLATFORM]: osPlatform,
[OS_ARCHITECTURE]: osArchitecture,
[RUNTIME_NAME]: runtimeName,
[RUNTIME_VERSION]: runtimeVersion,
[GIT_BRANCH]: branch,
[CI_PROVIDER_NAME]: ciProviderName,
[CI_WORKSPACE_PATH]: repositoryRoot,
[GIT_COMMIT_MESSAGE]: commitMessage,
[GIT_TAG]: tag,
[GIT_PULL_REQUEST_BASE_BRANCH_SHA]: pullRequestBaseSha,
[GIT_COMMIT_HEAD_SHA]: commitHeadSha,
[GIT_COMMIT_HEAD_MESSAGE]: commitHeadMessage,
} = this.testEnvironmentMetadata
this.repositoryRoot = repositoryRoot || process.cwd()
this.ciProviderName = ciProviderName
this.codeOwnersEntries = getCodeOwnersFileEntries(repositoryRoot)
this.testConfiguration = {
repositoryUrl,
sha,
osVersion,
osPlatform,
osArchitecture,
runtimeName,
runtimeVersion,
branch,
testLevel: 'test',
commitMessage,
tag,
pullRequestBaseSha,
commitHeadSha,
commitHeadMessage,
}
}
/**
* Resets state that is scoped to a single Cypress run so the singleton plugin
* can be reused safely across multiple programmatic cypress.run() calls.
*
* @returns {void}
*/
resetRunState () {
this._isInit = false
this.finishedTestsByFile = {}
this.testStatuses = {}
this.hasLibraryConfiguration = false
this.isItrEnabled = false
this.isTestsSkipped = false
this.isSuitesSkippingEnabled = false
this.isCodeCoverageEnabled = false
this.isCoverageReportUploadEnabled = false
this.isFlakyTestRetriesEnabled = false
this.flakyTestRetriesCount = 0
this.isEarlyFlakeDetectionEnabled = false
this.isEarlyFlakeDetectionFaulty = false
this.isKnownTestsEnabled = false
this.earlyFlakeDetectionRetryPolicy = EMPTY_EFD_RETRY_POLICY
this.efdRetryCountByTest = {}
this.efdSlowAbortedTests = {}
this.earlyFlakeDetectionFaultyThreshold = 0
this.testsToSkip = []
this.skippedTests = []
this.skippedTestIds = new Set()
this.skippableTestsCoverage = undefined
this.testSessionCoverageMap = createCoverageMap()
this.hasForcedToRunSuites = false
this.hasUnskippableSuites = false
this.unskippableSuites = []
this.knownTests = []
this.knownTestsByTestSuite = undefined
this.isTestManagementTestsEnabled = false
this.testManagementAttemptToFixRetries = 0
this.testManagementTests = undefined
this.isImpactedTestsEnabled = false
this.modifiedFiles = []
this.attemptToFixExecutions = new Map()
this.loggedAttemptToFixTests = new Set()
this.uploadedScreenshotPaths = new Set()
this.screenshotUploadPromisesByTraceId = new Map()
this.screenshotUploadAbortControllers = new Set()
this.lastFinishedTest = null
this.pendingScreenshotUploads = []
this.activeTestSpan = null
this.testSuiteSpan = null
this.finishedTestSuiteSpans = []
this.testModuleSpan = null
this.testSessionSpan = null
this.command = undefined
this.frameworkVersion = undefined
this.rootDir = undefined
this.itrCorrelationId = undefined
this.isTestIsolationEnabled = undefined
this.rumFlushWaitMillis = undefined
this._pendingRequestErrorTags = []
this.libraryConfigurationPromise = undefined
this._timeOrigin = 0
this._perfOrigin = 0
}
/**
* Returns a stable after:screenshot handler so auto-instrumentation can recognize
* the handler registered by the manual plugin and avoid treating it as a user hook.
*
* @returns {Function} Datadog after:screenshot handler
*/
getAfterScreenshotHandler () {
if (!this.afterScreenshotHandler) {
this.afterScreenshotHandler = this.afterScreenshot.bind(this)
}
return this.afterScreenshotHandler
}
/**
* Tracks a screenshot upload by its owning test trace id so the test event can be tagged
* before the span is finished.
*
* @param {string} traceId - Test trace id used for the upload
* @param {Promise<string|undefined>} uploadPromise - Promise resolving to the upload outcome
* @returns {void}
*/
addScreenshotUploadPromise (traceId, uploadPromise) {
const uploadPromises = this.screenshotUploadPromisesByTraceId.get(traceId)
if (uploadPromises) {
uploadPromises.push(uploadPromise)
} else {
this.screenshotUploadPromisesByTraceId.set(traceId, [uploadPromise])
}
}
/**
* Returns the aggregate upload outcome for all screenshots associated with a test trace id.
*
* @param {string} traceId - Test trace id used for the upload
* @returns {Promise<string|undefined>|undefined} Promise resolving to the aggregate upload outcome
*/
getScreenshotUploadResultPromise (traceId) {
const uploadPromises = this.screenshotUploadPromisesByTraceId.get(traceId)
if (!uploadPromises?.length) {
return
}
return Promise.all(uploadPromises).then(getScreenshotUploadResult)
}
/**
* Cancels screenshot work that must not outlive an errored after:spec finalization boundary.
*
* @param {Error} error - Error that triggered finalization
* @returns {void}
*/
abortPendingScreenshotUploads (error) {
for (const controller of this.screenshotUploadAbortControllers) controller.abort(error)
this.screenshotUploadAbortControllers.clear()
this.screenshotUploadPromisesByTraceId.clear()
this.pendingScreenshotUploads = []
}
/**
* Returns the current time in the same coordinate system used by span
* start/finish. Captured at session span creation so it shares the same
* epoch as the trace without reaching into span internals.
*
* @returns {number}
*/
_now () {
return this._timeOrigin + performance.now() - this._perfOrigin
}
/**
* Returns the directory used to normalize coverage file names.
*
* @returns {string}
*/
getCoverageRootDir () {
return this.repositoryRoot || this.rootDir || process.cwd()
}
/**
* Returns whether skipped test coverage should be backfilled into the session coverage map.
*
* @returns {boolean}
*/
shouldBackfillSkippedCoverage () {
return this.isItrEnabled &&
this.isCoverageReportUploadEnabled &&
this.isTestsSkipped &&
this.skippableTestsCoverage !== undefined
}
/**
* Adds a test's Istanbul coverage to the aggregated session coverage map.
*
* @param {object} coverage
* @returns {void}
*/
addTestSessionCoverage (coverage) {
mergeCoverage(coverage, this.testSessionCoverageMap)
}
/**
* Applies backend skipped-test coverage to the aggregated session coverage map.
*
* @returns {boolean}
*/
applySkippedCoverageToTestSessionCoverage () {
if (!this.shouldBackfillSkippedCoverage()) {
return false
}
return applySkippedCoverageToCoverage(
this.testSessionCoverageMap,
this.skippableTestsCoverage,
this.getCoverageRootDir()
)
}
/**
* Calculates the total session code coverage percentage when product rules allow reporting it.
*
* @param {boolean} hasBackfilledCoverage
* @returns {number | undefined}
*/
getTestCodeCoverageLinesTotal (hasBackfilledCoverage) {
if (!this.testSessionCoverageMap.files().length || (this.isTestsSkipped && !hasBackfilledCoverage)) {
return
}
return getTestCoverageLinesPercentage(this.testSessionCoverageMap, undefined, this.getCoverageRootDir())
}
/**
* Returns repository-relative executable-line coverage files for the test session.
*
* @returns {Array<{ filename: string, bitmap: Buffer }>}
*/
getTestSessionCoverageFiles () {
return getRelativeCoverageFiles(
getExecutableFilesFromCoverage(this.testSessionCoverageMap),
this.getCoverageRootDir()
)
}
/**
* Uploads executable-line coverage for the test session when backend configuration enables it.
*
* @returns {void}
*/
reportTestSessionCoverage () {
const exporter = this.tracer._tracer._exporter
if (
!this.testSessionSpan ||
!this.isCoverageReportUploadEnabled ||
!exporter?.exportCoverage
) {
return
}
const files = this.getTestSessionCoverageFiles()
if (!files.length) {
return
}
exporter.exportCoverage({
sessionId: this.testSessionSpan.context()._traceId,
files,
})
}
/**
* Warns when screenshot upload is enabled but Cypress cannot produce or send the screenshots.
*
* @param {object} cypressConfig - Cypress resolved config
* @param {object} tracer - dd-trace proxy tracer
* @param {object} testOptimizationConfig - Test Optimization config
* @returns {void}
*/
warnIfMisconfiguredTestFailureScreenshots (cypressConfig, tracer, testOptimizationConfig) {
if (!testOptimizationConfig.DD_TEST_FAILURE_SCREENSHOTS_ENABLED) {
return
}
if (cypressConfig.screenshotOnRunFailure === false) {
log.warn(
'%s %s',
'DD_TEST_FAILURE_SCREENSHOTS_ENABLED is true, but Cypress screenshotOnRunFailure is false.',
'Datadog cannot upload failure screenshots unless Cypress is configured to capture them.'
)
return
}
if (!tracer?._tracer?._exporter?.canUploadTestScreenshots?.()) {
log.warn(
'%s %s',
'DD_TEST_FAILURE_SCREENSHOTS_ENABLED is true, but Cypress failure screenshot upload is only supported',
'in agentless mode.'
)
}
}
// Init function returns a promise that resolves with the Cypress configuration
// Depending on the received configuration, the Cypress configuration can be modified:
// for example, to enable retries for failed tests.
init (tracer, cypressConfig) {
if (this.cypressConfig === cypressConfig && this.hasOriginalCypressRetries) {
cypressConfig.retries = this.originalCypressRetries !== null &&
typeof this.originalCypressRetries === 'object'
? { ...this.originalCypressRetries }
: this.originalCypressRetries
} else {
this.originalCypressRetries = cypressConfig.retries !== null && typeof cypressConfig.retries === 'object'
? { ...cypressConfig.retries }
: cypressConfig.retries
this.hasOriginalCypressRetries = true
}
this.resetRunState()
this._isInit = true
this.tracer = tracer
this.cypressConfig = cypressConfig
warnDeprecatedCypressVersion(cypressConfig.version)
this.isTestIsolationEnabled = getIsTestIsolationEnabled(cypressConfig)
const testOptimizationConfig = getConfig().testOptimization
this.rumFlushWaitMillis = testOptimizationConfig.DD_CIVISIBILITY_RUM_FLUSH_WAIT_MILLIS
this.warnIfMisconfiguredTestFailureScreenshots(cypressConfig, tracer, testOptimizationConfig)
if (!this.isTestIsolationEnabled) {
log.warn('Test isolation is disabled, retries will not be enabled')
}
// we have to do it here because the tracer is not initialized in the constructor
this.testEnvironmentMetadata[DD_TEST_IS_USER_PROVIDED_SERVICE] =
tracer._tracer._config.isServiceUserProvided ? 'true' : 'false'
this._pendingRequestErrorTags = []
this.libraryConfigurationPromise = getLibraryConfiguration(this.tracer, this.testConfiguration)
.then((libraryConfigurationResponse) => {
if (libraryConfigurationResponse.err) {
log.error('Cypress plugin library config response error', libraryConfigurationResponse.err)
this._pendingRequestErrorTags.push({
tag: DD_CI_LIBRARY_CONFIGURATION_ERROR_SETTINGS,
value: 'true',
})
} else {
this.hasLibraryConfiguration = true
const {
libraryConfig: {
isItrEnabled,
isSuitesSkippingEnabled,
isCodeCoverageEnabled,
isCoverageReportUploadEnabled,
isEarlyFlakeDetectionEnabled,
earlyFlakeDetectionRetryPolicy,
earlyFlakeDetectionFaultyThreshold,
isFlakyTestRetriesEnabled,
flakyTestRetriesCount,
isKnownTestsEnabled,
isTestManagementEnabled,
testManagementAttemptToFixRetries,
isImpactedTestsEnabled,
},
} = libraryConfigurationResponse
this.isItrEnabled = isItrEnabled
this.isSuitesSkippingEnabled = isSuitesSkippingEnabled
this.isCodeCoverageEnabled = isCodeCoverageEnabled
this.isCoverageReportUploadEnabled = isCoverageReportUploadEnabled
this.isEarlyFlakeDetectionEnabled = isEarlyFlakeDetectionEnabled
this.earlyFlakeDetectionRetryPolicy = earlyFlakeDetectionRetryPolicy ?? EMPTY_EFD_RETRY_POLICY
this.earlyFlakeDetectionFaultyThreshold = earlyFlakeDetectionFaultyThreshold
this.isKnownTestsEnabled = isKnownTestsEnabled
if (isFlakyTestRetriesEnabled && this.isTestIsolationEnabled) {
this.isFlakyTestRetriesEnabled = true
this.flakyTestRetriesCount = flakyTestRetriesCount ?? 0
if (typeof this.cypressConfig.retries === 'number') {
this.cypressConfig.retries = {
openMode: this.cypressConfig.retries,
runMode: this.cypressConfig.retries,
}
}
this.cypressConfig.retries.runMode = this.flakyTestRetriesCount
} else {
this.flakyTestRetriesCount = 0
}
this.isTestManagementTestsEnabled = isTestManagementEnabled
this.testManagementAttemptToFixRetries = testManagementAttemptToFixRetries
this.isImpactedTestsEnabled = isImpactedTestsEnabled
}
return this.cypressConfig
})
return this.libraryConfigurationPromise
}
getIsTestModified (testSuiteAbsolutePath) {
const relativeTestSuitePath = getTestSuitePath(testSuiteAbsolutePath, this.repositoryRoot)
if (!this.modifiedFiles) {
return false
}
const lines = this.modifiedFiles[relativeTestSuitePath]
if (!lines) {
return false
}
return lines.length > 0
}
getTestSuiteProperties (testSuite) {
return this.testManagementTests?.cypress?.suites?.[testSuite]?.tests || {}
}
getTestProperties (testSuite, testName) {
const { attempt_to_fix: isAttemptToFix, disabled: isDisabled, quarantined: isQuarantined } =
this.getTestSuiteProperties(testSuite)?.[testName]?.properties || {}
return { isAttemptToFix, isDisabled, isQuarantined }
}
/**
* Stores the selected EFD retry count for a test after its first execution duration is known.
*
* @param {string} testSuite
* @param {string} testName
* @param {number | undefined} duration
* @returns {number}
*/
setEfdRetryCountForTest (testSuite, testName, duration) {
if (!this.efdRetryCountByTest[testSuite]) {
this.efdRetryCountByTest[testSuite] = {}
}
const retryCount = getEfdRetryCountForDuration(duration ?? 0, this.earlyFlakeDetectionRetryPolicy)
this.efdRetryCountByTest[testSuite][testName] = retryCount
if (retryCount === 0) {
if (!this.efdSlowAbortedTests[testSuite]) {
this.efdSlowAbortedTests[testSuite] = {}
}
this.efdSlowAbortedTests[testSuite][testName] = true
}
return retryCount
}
/**
* Returns whether an EFD retry clone is beyond the selected retry count and should be discarded.
*
* @param {string} testSuite
* @param {string} testName
* @param {number} efdRetryIndex
* @returns {boolean}
*/
shouldSkipEfdRetry (testSuite, testName, efdRetryIndex) {
const testSuiteRetries = this.efdRetryCountByTest[testSuite]
return shouldSkipEfdRetry(efdRetryIndex, testSuiteRetries?.[testName])
}
getTestSuiteSpan ({ testSuite, testSuiteAbsolutePath }) {
const testSuiteSpanMetadata = {
...getTestSuiteCommonTags(this.command, this.frameworkVersion, testSuite, TEST_FRAMEWORK_NAME),
...this.getSessionRequestErrorTags(),
...this.getSessionItrSkippingEnabledTags(),
}
this.ciVisEvent(TELEMETRY_EVENT_CREATED, 'suite')
if (testSuiteAbsolutePath) {
const resolvedSuiteAbsolutePath = resolveOriginalSourceFile(testSuiteAbsolutePath) || testSuiteAbsolutePath
const testSourceFile = getTestSuitePath(resolvedSuiteAbsolutePath, this.repositoryRoot)
testSuiteSpanMetadata[TEST_SOURCE_FILE] = testSourceFile
testSuiteSpanMetadata[TEST_SOURCE_START] = 1
const codeOwners = this.getTestCodeOwners({ testSuite, testSourceFile })
if (codeOwners) {
testSuiteSpanMetadata[TEST_CODE_OWNERS] = codeOwners
}
}
return this.tracer.startSpan(`${TEST_FRAMEWORK_NAME}.test_suite`, {
childOf: this.testModuleSpan,
tags: {
[COMPONENT]: TEST_FRAMEWORK_NAME,
...this.testEnvironmentMetadata,
...testSuiteSpanMetadata,
},
integrationName: TEST_FRAMEWORK_NAME,
})
}
getTestSpan ({ testName, testSuite, isUnskippable, isForcedToRun, testSourceFile, isDisabled, isQuarantined }) {
const testSuiteTags = {
[TEST_MODULE]: TEST_FRAMEWORK_NAME,
}
if (this.testSuiteSpan) {
testSuiteTags[TEST_SUITE_ID] = this.testSuiteSpan.context().toSpanId()
}
if (this.testSessionSpan && this.testModuleSpan) {
testSuiteTags[TEST_SESSION_ID] = this.testSessionSpan.context().toTraceId()
testSuiteTags[TEST_MODULE_ID] = this.testModuleSpan.context().toSpanId()
Object.assign(testSuiteTags, this.getSessionRequestErrorTags())
// If testSuiteSpan couldn't be created, we'll use the testModuleSpan as the parent
if (!this.testSuiteSpan) {
testSuiteTags[TEST_SUITE_ID] = this.testModuleSpan.context().toSpanId()