-
Notifications
You must be signed in to change notification settings - Fork 385
Expand file tree
/
Copy pathcypress-plugin.js
More file actions
1100 lines (997 loc) · 38.5 KB
/
cypress-plugin.js
File metadata and controls
1100 lines (997 loc) · 38.5 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'
const {
TEST_STATUS,
TEST_IS_RUM_ACTIVE,
TEST_CODE_OWNERS,
getTestEnvironmentMetadata,
CI_APP_ORIGIN,
getTestParentSpan,
getCodeOwnersFileEntries,
getCodeOwnersForFilename,
getTestCommonTags,
getTestSessionCommonTags,
getTestModuleCommonTags,
getTestSuiteCommonTags,
TEST_SUITE_ID,
TEST_MODULE_ID,
TEST_SESSION_ID,
TEST_COMMAND,
TEST_MODULE,
TEST_SOURCE_START,
finishAllTraceSpans,
getCoveredFilenamesFromCoverage,
getTestSuitePath,
addIntelligentTestRunnerSpanTags,
TEST_SKIPPED_BY_ITR,
TEST_ITR_UNSKIPPABLE,
TEST_ITR_FORCED_RUN,
ITR_CORRELATION_ID,
TEST_SOURCE_FILE,
TEST_IS_NEW,
TEST_IS_RETRY,
TEST_EARLY_FLAKE_ENABLED,
getTestSessionName,
TEST_SESSION_NAME,
TEST_LEVEL_EVENT_TYPES,
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,
TEST_IS_MODIFIED,
TEST_HAS_DYNAMIC_NAME,
DYNAMIC_NAME_RE,
logDynamicNamesWarning,
getPullRequestBaseBranch,
} = require('../../dd-trace/src/plugins/util/test')
const { isMarkedAsUnskippable } = require('../../datadog-plugin-jest/src/util')
const { ORIGIN_KEY, COMPONENT } = require('../../dd-trace/src/constants')
const { getValueFromEnvSources } = require('../../dd-trace/src/config/helper')
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 {
resolveOriginalSourcePosition,
resolveSourceLineForTest,
shouldTrustInvocationDetailsLine,
} = require('./source-map-utils')
const TEST_FRAMEWORK_NAME = 'cypress'
const CYPRESS_STATUS_TO_TEST_STATUS = {
passed: 'pass',
failed: 'fail',
pending: 'skip',
skipped: 'skip',
}
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 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) => {
resolve({
err,
skippableTests,
correlationId,
})
})
})
}
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'
}
class CypressPlugin {
_isInit = false
testEnvironmentMetadata = getTestEnvironmentMetadata(TEST_FRAMEWORK_NAME)
finishedTestsByFile = {}
testStatuses = {}
isTestsSkipped = false
isSuitesSkippingEnabled = false
isCodeCoverageEnabled = false
isFlakyTestRetriesEnabled = false
flakyTestRetriesCount = 0
isEarlyFlakeDetectionEnabled = false
isKnownTestsEnabled = false
earlyFlakeDetectionNumRetries = 0
testsToSkip = []
skippedTests = []
hasForcedToRunSuites = false
hasUnskippableSuites = false
unskippableSuites = []
knownTests = []
isTestManagementTestsEnabled = false
testManagementAttemptToFixRetries = 0
isImpactedTestsEnabled = false
modifiedFiles = []
newTestsWithDynamicNames = new Set()
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,
}
}
// 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) {
this._isInit = true
this.tracer = tracer
this.cypressConfig = cypressConfig
this.isTestIsolationEnabled = getIsTestIsolationEnabled(cypressConfig)
const envFlushWait = Number(getValueFromEnvSources('DD_CIVISIBILITY_RUM_FLUSH_WAIT_MILLIS'))
this.rumFlushWaitMillis = Number.isFinite(envFlushWait) ? envFlushWait : undefined
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,
value: 'true',
})
} else {
const {
libraryConfig: {
isSuitesSkippingEnabled,
isCodeCoverageEnabled,
isEarlyFlakeDetectionEnabled,
earlyFlakeDetectionNumRetries,
isFlakyTestRetriesEnabled,
flakyTestRetriesCount,
isKnownTestsEnabled,
isTestManagementEnabled,
testManagementAttemptToFixRetries,
isImpactedTestsEnabled,
},
} = libraryConfigurationResponse
this.isSuitesSkippingEnabled = isSuitesSkippingEnabled
this.isCodeCoverageEnabled = isCodeCoverageEnabled
this.isEarlyFlakeDetectionEnabled = isEarlyFlakeDetectionEnabled
this.earlyFlakeDetectionNumRetries = earlyFlakeDetectionNumRetries
this.isKnownTestsEnabled = isKnownTestsEnabled
if (isFlakyTestRetriesEnabled && this.isTestIsolationEnabled) {
this.isFlakyTestRetriesEnabled = true
this.flakyTestRetriesCount = flakyTestRetriesCount ?? 0
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 }
}
getTestSuiteSpan ({ testSuite, testSuiteAbsolutePath }) {
const testSuiteSpanMetadata =
getTestSuiteCommonTags(this.command, this.frameworkVersion, testSuite, TEST_FRAMEWORK_NAME)
this.ciVisEvent(TELEMETRY_EVENT_CREATED, 'suite')
if (testSuiteAbsolutePath) {
const resolvedSuitePosition = resolveOriginalSourcePosition(testSuiteAbsolutePath, 1)
const resolvedSuiteAbsolutePath = resolvedSuitePosition ? resolvedSuitePosition.sourceFile : 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_COMMAND]: this.command,
[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()
}
}
const childOf = getTestParentSpan(this.tracer)
const {
resource,
...testSpanMetadata
} = getTestCommonTags(testName, testSuite, this.cypressConfig.version, TEST_FRAMEWORK_NAME)
if (testSourceFile) {
testSpanMetadata[TEST_SOURCE_FILE] = testSourceFile
}
const codeOwners = this.getTestCodeOwners({ testSuite, testSourceFile })
if (codeOwners) {
testSpanMetadata[TEST_CODE_OWNERS] = codeOwners
}
if (isUnskippable) {
this.hasUnskippableSuites = true
incrementCountMetric(TELEMETRY_ITR_UNSKIPPABLE, { testLevel: 'suite' })
testSpanMetadata[TEST_ITR_UNSKIPPABLE] = 'true'
}
if (isForcedToRun) {
this.hasForcedToRunSuites = true
incrementCountMetric(TELEMETRY_ITR_FORCED_TO_RUN, { testLevel: 'suite' })
testSpanMetadata[TEST_ITR_FORCED_RUN] = 'true'
}
if (isDisabled) {
testSpanMetadata[TEST_MANAGEMENT_IS_DISABLED] = 'true'
}
if (isQuarantined) {
testSpanMetadata[TEST_MANAGEMENT_IS_QUARANTINED] = 'true'
}
this.ciVisEvent(TELEMETRY_EVENT_CREATED, 'test', { hasCodeOwners: !!codeOwners })
return this.tracer.startSpan(`${TEST_FRAMEWORK_NAME}.test`, {
childOf,
tags: {
[COMPONENT]: TEST_FRAMEWORK_NAME,
[ORIGIN_KEY]: CI_APP_ORIGIN,
...testSpanMetadata,
...this.testEnvironmentMetadata,
...testSuiteTags,
},
integrationName: TEST_FRAMEWORK_NAME,
})
}
/**
* Returns request error tags from the test session span for propagation to test spans.
* @returns {Record<string, string>}
*/
getSessionRequestErrorTags () {
return getSessionRequestErrorTags(this.testSessionSpan)
}
ciVisEvent (name, testLevel, tags = {}) {
incrementCountMetric(name, {
testLevel,
testFramework: 'cypress',
isUnsupportedCIProvider: !this.ciProviderName,
...tags,
})
}
async beforeRun (details) {
// We need to make sure that the plugin is initialized before running the tests
// This is for the case where the user has not returned the promise from the init function
await this.libraryConfigurationPromise
this.command = getCypressCommand(details)
this.frameworkVersion = getCypressVersion(details)
this.rootDir = getRootDir(details)
if (this.isKnownTestsEnabled) {
const knownTestsResponse = await getKnownTests(
this.tracer,
this.testConfiguration
)
if (knownTestsResponse.err) {
log.error('Cypress known tests response error', knownTestsResponse.err)
this.isEarlyFlakeDetectionEnabled = false
this.isKnownTestsEnabled = false
} else {
if (knownTestsResponse.knownTests[TEST_FRAMEWORK_NAME]) {
this.knownTestsByTestSuite = knownTestsResponse.knownTests[TEST_FRAMEWORK_NAME]
} else {
this.isEarlyFlakeDetectionEnabled = false
this.isKnownTestsEnabled = false
}
}
}
if (this.isSuitesSkippingEnabled) {
const skippableTestsResponse = await getSkippableTests(
this.tracer,
this.testConfiguration
)
if (skippableTestsResponse.err) {
log.error('Cypress skippable tests response error', skippableTestsResponse.err)
} else {
const { skippableTests, correlationId } = skippableTestsResponse
this.testsToSkip = skippableTests || []
this.itrCorrelationId = correlationId
incrementCountMetric(TELEMETRY_ITR_SKIPPED, { testLevel: 'test' }, this.testsToSkip.length)
}
}
if (this.isTestManagementTestsEnabled) {
const testManagementTestsResponse = await getTestManagementTests(
this.tracer,
this.testConfiguration
)
if (testManagementTestsResponse.err) {
log.error('Cypress test management tests response error', testManagementTestsResponse.err)
this.isTestManagementTestsEnabled = false
} else {
this.testManagementTests = testManagementTestsResponse.testManagementTests
}
}
if (this.isImpactedTestsEnabled) {
try {
this.modifiedFiles = getModifiedFiles(this.testEnvironmentMetadata)
} catch (error) {
log.error(error)
this.isImpactedTestsEnabled = false
}
}
// `details.specs` are test files
if (details.specs) {
for (const { absolute, relative } of details.specs) {
const isUnskippableSuite = isMarkedAsUnskippable({ path: absolute })
if (isUnskippableSuite) {
this.unskippableSuites.push(relative)
}
}
}
const childOf = getTestParentSpan(this.tracer)
const testSessionSpanMetadata =
getTestSessionCommonTags(this.command, this.frameworkVersion, TEST_FRAMEWORK_NAME)
const testModuleSpanMetadata =
getTestModuleCommonTags(this.command, this.frameworkVersion, TEST_FRAMEWORK_NAME)
if (this.isEarlyFlakeDetectionEnabled) {
testSessionSpanMetadata[TEST_EARLY_FLAKE_ENABLED] = 'true'
}
const trimmedCommand = DD_MAJOR < 6 ? this.command : 'cypress run'
const testSessionName = getTestSessionName(
this.tracer._tracer._config,
trimmedCommand,
this.testEnvironmentMetadata
)
if (this.tracer._tracer._exporter?.addMetadataTags) {
const metadataTags = {}
for (const testLevel of TEST_LEVEL_EVENT_TYPES) {
metadataTags[testLevel] = {
[TEST_SESSION_NAME]: testSessionName,
}
}
const libraryCapabilitiesTags = getLibraryCapabilitiesTags(this.constructor.id, this.frameworkVersion)
metadataTags.test = {
...metadataTags.test,
...libraryCapabilitiesTags,
}
this.tracer._tracer._exporter.addMetadataTags(metadataTags)
}
this.testSessionSpan = this.tracer.startSpan(`${TEST_FRAMEWORK_NAME}.test_session`, {
childOf,
tags: {
[COMPONENT]: TEST_FRAMEWORK_NAME,
...this.testEnvironmentMetadata,
...testSessionSpanMetadata,
},
integrationName: TEST_FRAMEWORK_NAME,
})
for (const { tag, value } of this._pendingRequestErrorTags) {
this.testSessionSpan.setTag(tag, value)
}
this._pendingRequestErrorTags = []
this.ciVisEvent(TELEMETRY_EVENT_CREATED, 'session')
const sessionRequestErrorTags = getSessionRequestErrorTags(this.testSessionSpan)
this.testModuleSpan = this.tracer.startSpan(`${TEST_FRAMEWORK_NAME}.test_module`, {
childOf: this.testSessionSpan,
tags: {
[COMPONENT]: TEST_FRAMEWORK_NAME,
...this.testEnvironmentMetadata,
...testModuleSpanMetadata,
...sessionRequestErrorTags,
},
integrationName: TEST_FRAMEWORK_NAME,
})
this.ciVisEvent(TELEMETRY_EVENT_CREATED, 'module')
return details
}
afterRun (suiteStats) {
if (!this._isInit) {
log.warn('Attemping to call afterRun without initializating the plugin first')
return
}
if (this.testSessionSpan && this.testModuleSpan) {
const testStatus = getSessionStatus(suiteStats)
this.testModuleSpan.setTag(TEST_STATUS, testStatus)
this.testSessionSpan.setTag(TEST_STATUS, testStatus)
addIntelligentTestRunnerSpanTags(
this.testSessionSpan,
this.testModuleSpan,
{
isSuitesSkipped: this.isTestsSkipped,
isSuitesSkippingEnabled: this.isSuitesSkippingEnabled,
isCodeCoverageEnabled: this.isCodeCoverageEnabled,
skippingType: 'test',
skippingCount: this.skippedTests.length,
hasForcedToRunSuites: this.hasForcedToRunSuites,
hasUnskippableSuites: this.hasUnskippableSuites,
}
)
if (this.isTestManagementTestsEnabled) {
this.testSessionSpan.setTag(TEST_MANAGEMENT_ENABLED, 'true')
}
logDynamicNamesWarning(this.newTestsWithDynamicNames)
this.testModuleSpan.finish()
this.ciVisEvent(TELEMETRY_EVENT_FINISHED, 'module')
this.testSessionSpan.finish()
this.ciVisEvent(TELEMETRY_EVENT_FINISHED, 'session')
incrementCountMetric(TELEMETRY_TEST_SESSION, {
provider: this.ciProviderName,
autoInjected: !!getValueFromEnvSources('DD_CIVISIBILITY_AUTO_INSTRUMENTATION_PROVIDER'),
})
finishAllTraceSpans(this.testSessionSpan)
}
return new Promise(resolve => {
const exporter = this.tracer._tracer._exporter
if (!exporter) {
return resolve(null)
}
if (exporter.flush) {
exporter.flush(() => {
appClosingTelemetry()
resolve(null)
})
} else if (exporter._writer) {
exporter._writer.flush(() => {
appClosingTelemetry()
resolve(null)
})
}
})
}
afterSpec (spec, results) {
const { tests, stats } = results || {}
const cypressTests = tests || []
const finishedTests = this.finishedTestsByFile[spec.relative] || []
if (!this.testSuiteSpan) {
// dd:testSuiteStart hasn't been triggered for whatever reason
// We will create the test suite span on the spot if that's the case
log.warn('There was an error creating the test suite event.')
this.testSuiteSpan = this.getTestSuiteSpan({
testSuite: spec.relative,
testSuiteAbsolutePath: spec.absolute,
})
}
// Get tests that didn't go through `dd:afterEach`
// and create a skipped test span for each of them
for (const { title } of cypressTests) {
const cypressTestName = title.join(' ')
const isTestFinished = finishedTests.find(({ testName }) => cypressTestName === testName)
if (isTestFinished) {
continue
}
const isSkippedByItr = this.testsToSkip.find(test =>
cypressTestName === test.name && spec.relative === test.suite
)
const testSourceFile = spec.absolute && this.repositoryRoot
? getTestSuitePath(spec.absolute, this.repositoryRoot)
: spec.relative
const skippedTestSpan = this.getTestSpan({ testName: cypressTestName, testSuite: spec.relative, testSourceFile })
skippedTestSpan.setTag(TEST_STATUS, 'skip')
if (isSkippedByItr) {
skippedTestSpan.setTag(TEST_SKIPPED_BY_ITR, 'true')
}
if (this.itrCorrelationId) {
skippedTestSpan.setTag(ITR_CORRELATION_ID, this.itrCorrelationId)
}
const { isDisabled, isQuarantined } = this.getTestProperties(spec.relative, cypressTestName)
if (isDisabled) {
skippedTestSpan.setTag(TEST_MANAGEMENT_IS_DISABLED, 'true')
} else if (isQuarantined) {
skippedTestSpan.setTag(TEST_MANAGEMENT_IS_QUARANTINED, 'true')
}
skippedTestSpan.finish()
}
// Make sure that reported test statuses are the same as Cypress reports.
// This is not always the case, such as when an `after` hook fails:
// Cypress will report the last run test as failed, but we don't know that yet at `dd:afterEach`
let latestError
const finishedTestsByTestName = finishedTests.reduce((acc, finishedTest) => {
if (!acc[finishedTest.testName]) {
acc[finishedTest.testName] = []
}
acc[finishedTest.testName].push(finishedTest)
return acc
}, {})
for (const [testName, finishedTestAttempts] of Object.entries(finishedTestsByTestName)) {
for (const [attemptIndex, finishedTest] of finishedTestAttempts.entries()) {
// TODO: there could be multiple if there have been retries!
// potentially we need to match the test status!
const cypressTest = cypressTests.find(test => test.title.join(' ') === testName)
if (!cypressTest) {
continue
}
// finishedTests can include multiple tests with the same name if they have been retried
// by early flake detection. Cypress is unaware of this so .attempts does not necessarily have
// the same length as `finishedTestAttempts`
let cypressTestStatus = CYPRESS_STATUS_TO_TEST_STATUS[cypressTest.state]
if (cypressTest.attempts && cypressTest.attempts[attemptIndex]) {
cypressTestStatus = CYPRESS_STATUS_TO_TEST_STATUS[cypressTest.attempts[attemptIndex].state]
const isAtrRetry = attemptIndex > 0 &&
this.isFlakyTestRetriesEnabled &&
!finishedTest.isAttemptToFix &&
!finishedTest.isEfdRetry
if (attemptIndex > 0) {
finishedTest.testSpan.setTag(TEST_IS_RETRY, 'true')
if (finishedTest.isEfdRetry) {
finishedTest.testSpan.setTag(TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd)
} else if (isAtrRetry) {
finishedTest.testSpan.setTag(TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.atr)
} else {
finishedTest.testSpan.setTag(TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.ext)
}
}
}
if (cypressTest.displayError) {
latestError = new Error(cypressTest.displayError)
}
// Update test status - but NOT for quarantined tests where we intentionally
// report 'fail' to Datadog even though Cypress sees it as 'pass'
const isQuarantinedTest = finishedTest.testSpan?.context()?._tags?.[TEST_MANAGEMENT_IS_QUARANTINED] === 'true'
if (cypressTestStatus !== finishedTest.testStatus && !isQuarantinedTest) {
finishedTest.testSpan.setTag(TEST_STATUS, cypressTestStatus)
finishedTest.testSpan.setTag('error', latestError)
}
if (this.itrCorrelationId) {
finishedTest.testSpan.setTag(ITR_CORRELATION_ID, this.itrCorrelationId)
}
const resolvedSpecPosition = spec.absolute ? resolveOriginalSourcePosition(spec.absolute, 1) : null
const resolvedSpecAbsolutePath = resolvedSpecPosition ? resolvedSpecPosition.sourceFile : spec.absolute
const testSourceFile = resolvedSpecAbsolutePath && this.repositoryRoot
? getTestSuitePath(resolvedSpecAbsolutePath, this.repositoryRoot)
: spec.relative
if (testSourceFile) {
finishedTest.testSpan.setTag(TEST_SOURCE_FILE, testSourceFile)
}
const codeOwners = this.getTestCodeOwners({ testSuite: spec.relative, testSourceFile })
if (codeOwners) {
finishedTest.testSpan.setTag(TEST_CODE_OWNERS, codeOwners)
}
finishedTest.testSpan.finish(finishedTest.finishTime)
}
}
if (this.testSuiteSpan) {
const status = getSuiteStatus(stats)
this.testSuiteSpan.setTag(TEST_STATUS, status)
if (latestError) {
this.testSuiteSpan.setTag('error', latestError)
}
this.testSuiteSpan.finish()
this.testSuiteSpan = null
this.ciVisEvent(TELEMETRY_EVENT_FINISHED, 'suite')
}
}
getTasks () {
return {
'dd:testSuiteStart': ({ testSuite, testSuiteAbsolutePath }) => {
const suitePayload = {
isEarlyFlakeDetectionEnabled: this.isEarlyFlakeDetectionEnabled,
knownTestsForSuite: this.knownTestsByTestSuite?.[testSuite] || [],
earlyFlakeDetectionNumRetries: this.earlyFlakeDetectionNumRetries,
isKnownTestsEnabled: this.isKnownTestsEnabled,
isTestManagementEnabled: this.isTestManagementTestsEnabled,
testManagementAttemptToFixRetries: this.testManagementAttemptToFixRetries,
testManagementTests: this.getTestSuiteProperties(testSuite),
isImpactedTestsEnabled: this.isImpactedTestsEnabled,
isModifiedTest: this.getIsTestModified(testSuiteAbsolutePath),
repositoryRoot: this.repositoryRoot,
isTestIsolationEnabled: this.isTestIsolationEnabled,
rumFlushWaitMillis: this.rumFlushWaitMillis,
}
if (this.testSuiteSpan) {
return suitePayload
}
this.testSuiteSpan = this.getTestSuiteSpan({ testSuite, testSuiteAbsolutePath })
return suitePayload
},
'dd:beforeEach': (test) => {
const { testName, testSuite } = test
const shouldSkip = this.testsToSkip.some(test => {
return testName === test.name && testSuite === test.suite
})
const isUnskippable = this.unskippableSuites.includes(testSuite)
const isForcedToRun = shouldSkip && isUnskippable
const { isAttemptToFix, isDisabled, isQuarantined } = this.getTestProperties(testSuite, testName)
// skip test
if (shouldSkip && !isUnskippable) {
this.skippedTests.push(test)
this.isTestsSkipped = true
return { shouldSkip: true }
}
// For disabled tests (not attemptToFix), skip them
if (!isAttemptToFix && isDisabled) {
return { shouldSkip: true }
}
// Quarantined tests (not attemptToFix) run normally but their failures are caught
// by Cypress.on('fail') in support.js and suppressed, so Cypress sees them as passed
if (!this.activeTestSpan) {
this.activeTestSpan = this.getTestSpan({
testName,
testSuite,
isUnskippable,
isForcedToRun,
isDisabled,
isQuarantined,
})
}
return this.activeTestSpan ? { traceId: this.activeTestSpan.context().toTraceId() } : {}
},
'dd:afterEach': ({ test, coverage }) => {
if (!this.activeTestSpan) {
log.warn('There is no active test span in dd:afterEach handler')
return null
}
const {
state,
error,
isRUMActive,
testSourceLine,
testSourceStack,
testSuite,
testSuiteAbsolutePath,
testName,
testItTitle,
isNew,
isEfdRetry,
isAttemptToFix,
isModified,
isQuarantined: isQuarantinedFromSupport,
} = test
if (coverage && this.isCodeCoverageEnabled && this.tracer._tracer._exporter?.exportCoverage) {
const coverageFiles = getCoveredFilenamesFromCoverage(coverage)
const relativeCoverageFiles = [...coverageFiles, testSuiteAbsolutePath].map(
file => getTestSuitePath(file, this.repositoryRoot || this.rootDir)
)
if (!relativeCoverageFiles.length) {
incrementCountMetric(TELEMETRY_CODE_COVERAGE_EMPTY)
}
distributionMetric(TELEMETRY_CODE_COVERAGE_NUM_FILES, {}, relativeCoverageFiles.length)
const { _traceId, _spanId } = this.testSuiteSpan.context()
const formattedCoverage = {
sessionId: _traceId,
suiteId: _spanId,
testId: this.activeTestSpan.context()._spanId,
files: relativeCoverageFiles,
}
this.tracer._tracer._exporter.exportCoverage(formattedCoverage)
}
const testStatus = CYPRESS_STATUS_TO_TEST_STATUS[state]
this.activeTestSpan.setTag(TEST_STATUS, testStatus)
// Save the test status to know if it has passed all retries
if (this.testStatuses[testName]) {
this.testStatuses[testName].push(testStatus)
} else {
this.testStatuses[testName] = [testStatus]
}
const testStatuses = this.testStatuses[testName]
if (error) {
this.activeTestSpan.setTag('error', error)
}
if (isRUMActive) {
this.activeTestSpan.setTag(TEST_IS_RUM_ACTIVE, 'true')
}
// Source-line resolution strategy:
// 1. If plain JS and no source map, trust invocationDetails.line directly.
// 2. Otherwise, try invocationDetails.stack line mapped through source map.
// 3. If that fails, scan generated file for it/test/specify declaration by test name.
// 4. If declaration found:
// - .ts file: use declaration line directly.
// - .js file: map declaration line through source map.
// 5. If all fail, keep original invocationDetails.line.
if (testSourceLine) {
let resolvedLine = testSourceLine
if (testSuiteAbsolutePath && testItTitle) {
// Use invocationDetails directly only for plain JS specs without source maps.
// Otherwise, resolve from the test declaration in the spec and map via source map.
const shouldTrustInvocationDetails = shouldTrustInvocationDetailsLine(testSuiteAbsolutePath, testSourceLine)
if (!shouldTrustInvocationDetails) {
resolvedLine = resolveSourceLineForTest(
testSuiteAbsolutePath,
testItTitle,
testSourceStack
) ?? testSourceLine
}
}
this.activeTestSpan.setTag(TEST_SOURCE_START, resolvedLine)
}
if (isNew) {
this.activeTestSpan.setTag(TEST_IS_NEW, 'true')
if (isEfdRetry) {
this.activeTestSpan.setTag(TEST_IS_RETRY, 'true')
this.activeTestSpan.setTag(TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd)
}
if (DYNAMIC_NAME_RE.test(testName)) {
this.activeTestSpan.setTag(TEST_HAS_DYNAMIC_NAME, 'true')