-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathcucumber.js
More file actions
1781 lines (1543 loc) · 61 KB
/
Copy pathcucumber.js
File metadata and controls
1781 lines (1543 loc) · 61 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 { performance } = require('node:perf_hooks')
const { createCoverageMap } = require('../../../vendor/dist/istanbul-lib-coverage')
const shimmer = require('../../datadog-shimmer')
const log = require('../../dd-trace/src/log')
const { getEnvironmentVariable } = require('../../dd-trace/src/config/helper')
const { getSegment } = require('../../dd-trace/src/util')
const {
EMPTY_EFD_RETRY_POLICY,
getEfdRetryCountForDuration,
hasEfdRetries,
} = require('../../dd-trace/src/ci-visibility/efd-retry-policy')
const {
getCoveredFilesFromCoverage,
getExecutableFilesFromCoverage,
resetCoverage,
mergeCoverage,
fromCoverageMapToCoverage,
getTestSuitePath,
getRelativeCoverageFiles,
CUCUMBER_WORKER_TRACE_PAYLOAD_CODE,
CUCUMBER_WORKER_TELEMETRY_PAYLOAD_CODE,
getIsFaultyEarlyFlakeDetection,
applySkippedCoverageToCoverage,
getTestCoverageLinesPercentage,
recordTestManagementExecution,
recordAttemptToFixExecution,
collectTestOptimizationSummariesFromTraces,
logAttemptToFixTestExecution,
logTestOptimizationSummary,
TEST_IMPACT_ANALYSIS_ALL_TESTS_SKIPPED_MESSAGE,
getTestOptimizationRequestResults,
} = require('../../dd-trace/src/plugins/util/test')
const { writeCoverageBackfillToCache } = require('../../dd-trace/src/ci-visibility/test-optimization-cache')
const satisfies = require('../../../vendor/dist/semifies')
const { getChannelPromise } = require('./helpers/channel')
const { addHook, channel } = require('./helpers/instrument')
const cucumberWorkerThreadsPatchModule = require.resolve('./cucumber-worker-threads')
const testStartCh = channel('ci:cucumber:test:start')
const testRetryCh = channel('ci:cucumber:test:retry')
const testFinishCh = channel('ci:cucumber:test:finish') // used for test steps too
const testFnCh = channel('ci:cucumber:test:fn')
const testStepStartCh = channel('ci:cucumber:test-step:start')
const errorCh = channel('ci:cucumber:error')
const testSuiteStartCh = channel('ci:cucumber:test-suite:start')
const testSuiteFinishCh = channel('ci:cucumber:test-suite:finish')
const testSuiteCodeCoverageCh = channel('ci:cucumber:test-suite:code-coverage')
const libraryConfigurationCh = channel('ci:cucumber:library-configuration')
const knownTestsCh = channel('ci:cucumber:known-tests')
const skippableSuitesCh = channel('ci:cucumber:test-suite:skippable')
const sessionStartCh = channel('ci:cucumber:session:start')
const sessionFinishCh = channel('ci:cucumber:session:finish')
const testManagementTestsCh = channel('ci:cucumber:test-management-tests')
const modifiedFilesCh = channel('ci:cucumber:modified-files')
const isModifiedCh = channel('ci:cucumber:is-modified-test')
const workerReportTraceCh = channel('ci:cucumber:worker-report:trace')
const workerReportTelemetryCh = channel('ci:cucumber:worker-report:telemetry')
const itrSkippedSuitesCh = channel('ci:cucumber:itr:skipped-suites')
const getCodeCoverageCh = channel('ci:nyc:get-coverage')
const DD_EFD_RETRY_COUNT_MESSAGE = '_ddEfdRetryCount'
const CUCUMBER_RETRY_NAME_SUFFIX = / ?\(attempt \d+(?:, retried)?\) ?$/
/**
* Removes Cucumber's generated retry suffix without changing literal scenario names.
*
* @param {string} testName
* @param {boolean} isRetry
* @returns {string}
*/
function getCucumberTestName (testName, isRetry) {
return isRetry ? testName.replace(CUCUMBER_RETRY_NAME_SUFFIX, '') : testName
}
const isMarkedAsUnskippable = (pickle) => {
return pickle.tags.some(tag => tag.name === '@datadog:unskippable')
}
// We'll preserve the original coverage here
const originalCoverageMap = createCoverageMap()
// TODO: remove in a later major version
const patched = new WeakSet()
const patchedCucumberWorkers = new WeakSet()
const lastStatusByPickleId = new Map()
/** For ATR: statuses keyed by stable scenario id (uri:name) so retries accumulate correctly */
const atrStatusesByScenarioKey = new Map()
const numRetriesByPickleId = new Map()
const efdRetryCountByPickleId = new Map()
const efdSlowAbortedPickleIds = new Set()
const finishedParallelSuites = new Set()
const numAttemptToCtx = new Map()
const newTestsByTestFullname = new Map()
const attemptToFixTestsByTestFullname = new Map()
const modifiedTestsByPickleId = new Map()
const runnerToRetryState = new WeakMap()
// Pickle IDs for tests that are genuinely new (not in known tests list).
const newTestPickleIds = new Set()
const attemptToFixExecutions = new Map()
const loggedAttemptToFixTests = new Set()
let eventDataCollector = null
let pickleByFile = {}
const pickleResultByFile = {}
let skippableSuites = []
let skippableSuitesCoverage
let skippedSuitesCoverage = {}
let itrCorrelationId = ''
let isForcedToRun = false
let isUnskippable = false
let isItrEnabled = false
let isSuitesSkippingEnabled = false
let isCoverageReportUploadEnabled = false
let isEarlyFlakeDetectionEnabled = false
let earlyFlakeDetectionRetryPolicy = EMPTY_EFD_RETRY_POLICY
let earlyFlakeDetectionFaultyThreshold = 0
let isEarlyFlakeDetectionFaulty = false
let isFlakyTestRetriesEnabled = false
let isKnownTestsEnabled = false
let isTestManagementTestsEnabled = false
let isImpactedTestsEnabled = false
let testManagementAttemptToFixRetries = 0
let testManagementTests = {}
let modifiedFiles = {}
let numTestRetries = 0
let knownTests = {}
let skippedSuites = []
let isSuitesSkipped = false
let areAllSuitesSkipped = false
let repositoryRoot
/**
* @returns {boolean}
*/
function shouldRunEarlyFlakeDetection () {
return isEarlyFlakeDetectionEnabled && hasEfdRetries(earlyFlakeDetectionRetryPolicy)
}
function isValidKnownTests (receivedKnownTests) {
return !!receivedKnownTests.cucumber
}
function isTiaCoverageBackfillEnabled () {
return isItrEnabled && isCoverageReportUploadEnabled
}
function getCoverageRootDir () {
return repositoryRoot || process.cwd()
}
function shouldReportCodeCoverageLinesPct (hasBackfilledCoverage) {
return !isSuitesSkipped || hasBackfilledCoverage
}
function getSkippedSuitesCoverageForRun () {
return isSuitesSkipped && isTiaCoverageBackfillEnabled() && skippableSuitesCoverage !== undefined
? skippableSuitesCoverage
: {}
}
function applySkippedCoverageToCucumberCoverageMap () {
if (!isTiaCoverageBackfillEnabled()) return false
return applySkippedCoverageToCoverage(originalCoverageMap, skippedSuitesCoverage, getCoverageRootDir())
}
function getCucumberTestSessionCoverageFiles () {
return getRelativeCoverageFiles(getExecutableFilesFromCoverage(originalCoverageMap), getCoverageRootDir())
}
function resetSuiteSkippingRunState () {
skippableSuites = []
skippableSuitesCoverage = undefined
skippedSuitesCoverage = {}
skippedSuites = []
isSuitesSkipped = false
areAllSuitesSkipped = false
repositoryRoot = undefined
writeCoverageBackfillToCache({})
}
function getSuiteStatusFromTestStatuses (testStatuses) {
if (testStatuses.includes('fail')) {
return 'fail'
}
if (testStatuses.every(status => status === 'skip')) {
return 'skip'
}
return 'pass'
}
function publishWorkerEfdRetryCount (pickle, retryCount) {
const message = {
[DD_EFD_RETRY_COUNT_MESSAGE]: {
pickleId: pickle.id,
retryCount,
testFileAbsolutePath: pickle.uri,
testName: pickle.name,
},
}
if (typeof process.send === 'function') {
try {
process.send(message)
} catch {
// ignore IPC errors
}
return
}
try {
const { isMainThread, parentPort } = require('node:worker_threads')
if (isMainThread || !parentPort) return
parentPort.postMessage(message)
} catch {
// ignore IPC errors
}
}
function configureParallelWorkerWorldParameters (options) {
options.worldParameters ??= {}
if (isKnownTestsEnabled && isValidKnownTests(knownTests)) {
options.worldParameters._ddIsKnownTestsEnabled = true
options.worldParameters._ddIsEarlyFlakeDetectionEnabled = isEarlyFlakeDetectionEnabled
options.worldParameters._ddKnownTests = knownTests
options.worldParameters._ddEarlyFlakeDetectionRetryPolicy = earlyFlakeDetectionRetryPolicy
} else {
isEarlyFlakeDetectionEnabled = false
isKnownTestsEnabled = false
options.worldParameters._ddIsEarlyFlakeDetectionEnabled = false
options.worldParameters._ddIsKnownTestsEnabled = false
options.worldParameters._ddEarlyFlakeDetectionRetryPolicy = EMPTY_EFD_RETRY_POLICY
}
if (isImpactedTestsEnabled) {
options.worldParameters._ddImpactedTestsEnabled = isImpactedTestsEnabled
options.worldParameters._ddModifiedFiles = modifiedFiles
}
options.worldParameters._ddIsFlakyTestRetriesEnabled = isFlakyTestRetriesEnabled
options.worldParameters._ddNumTestRetries = numTestRetries
if (isTestManagementTestsEnabled) {
options.worldParameters._ddIsTestManagementTestsEnabled = true
options.worldParameters._ddTestManagementTests = testManagementTests
options.worldParameters._ddTestManagementAttemptToFixRetries = testManagementAttemptToFixRetries
}
}
function readParallelWorkerWorldParameters (options) {
const worldParameters = options?.worldParameters
if (!worldParameters) return
isKnownTestsEnabled = !!worldParameters._ddIsKnownTestsEnabled
if (isKnownTestsEnabled) {
knownTests = worldParameters._ddKnownTests
// if for whatever reason the worker does not receive valid known tests, we disable EFD and known tests
if (!isValidKnownTests(knownTests)) {
isKnownTestsEnabled = false
knownTests = {}
}
}
isEarlyFlakeDetectionEnabled = !!worldParameters._ddIsEarlyFlakeDetectionEnabled
earlyFlakeDetectionRetryPolicy = isEarlyFlakeDetectionEnabled
? worldParameters._ddEarlyFlakeDetectionRetryPolicy ?? EMPTY_EFD_RETRY_POLICY
: EMPTY_EFD_RETRY_POLICY
isImpactedTestsEnabled = !!worldParameters._ddImpactedTestsEnabled
if (isImpactedTestsEnabled) {
modifiedFiles = worldParameters._ddModifiedFiles
}
isFlakyTestRetriesEnabled = !!worldParameters._ddIsFlakyTestRetriesEnabled
numTestRetries = worldParameters._ddNumTestRetries ?? 0
isTestManagementTestsEnabled = !!worldParameters._ddIsTestManagementTestsEnabled
if (isTestManagementTestsEnabled) {
testManagementTests = worldParameters._ddTestManagementTests
testManagementAttemptToFixRetries = worldParameters._ddTestManagementAttemptToFixRetries
}
}
function handleDdWorkerMessage (message) {
if (Array.isArray(message)) {
const [messageCode, payload] = message
if (messageCode === CUCUMBER_WORKER_TRACE_PAYLOAD_CODE) {
collectTestOptimizationSummariesFromTraces(payload, { attemptToFixExecutions })
workerReportTraceCh.publish(payload)
return true
}
if (messageCode === CUCUMBER_WORKER_TELEMETRY_PAYLOAD_CODE) {
workerReportTelemetryCh.publish(payload)
return true
}
}
if (message?.[DD_EFD_RETRY_COUNT_MESSAGE]) {
handleEfdRetryCountMessage(message[DD_EFD_RETRY_COUNT_MESSAGE])
return true
}
return false
}
function onCucumberWorkerThreadMessage (message) {
if (!testSuiteFinishCh.hasSubscribers) return
handleDdWorkerMessage(message)
}
function registerWorkerThreadMessageHandlers (workers) {
if (!workers) return
for (const worker of workers) {
worker.workerThread.on('message', onCucumberWorkerThreadMessage)
}
}
function registerWorkerThreadPatchModule (supportCodeLibrary) {
const requireModules = supportCodeLibrary?.originalCoordinates?.requireModules
if (!Array.isArray(requireModules) || requireModules.includes(cucumberWorkerThreadsPatchModule)) return
requireModules.unshift(cucumberWorkerThreadsPatchModule)
}
function getRunningAssembledTestCase (adapter, worker) {
const command = adapter.running?.get(worker)
return command?.assembledTestCase
}
function maybeStartParallelSuite (pickle) {
if (!pickle) return
const testFileAbsolutePath = pickle.uri
if (pickleResultByFile[testFileAbsolutePath]) return
pickleResultByFile[testFileAbsolutePath] = []
testSuiteStartCh.publish({
testFileAbsolutePath,
})
}
function handleParallelTestCaseFinished (pickle, worstTestStepResult, usesNumericStatus = false) {
const { status } = usesNumericStatus
? getStatusFromResult(worstTestStepResult)
: getStatusFromResultLatest(worstTestStepResult)
let isNew = false
if (isKnownTestsEnabled) {
isNew = isNewTest(pickle.uri, pickle.name)
}
const testFileAbsolutePath = pickle.uri
const finished = (pickleResultByFile[testFileAbsolutePath] ||= [])
if (shouldRunEarlyFlakeDetection() && isNew) {
const testFullname = `${pickle.uri}:${pickle.name}`
let testStatuses = newTestsByTestFullname.get(testFullname)
if (testStatuses) {
testStatuses.push(status)
} else {
testStatuses = [status]
newTestsByTestFullname.set(testFullname, testStatuses)
}
let efdRetryCount = efdRetryCountByPickleId.get(pickle.id)
if (efdRetryCount === undefined) {
efdRetryCount = status === 'skip'
? 0
: earlyFlakeDetectionRetryPolicy.schedulingRetryCount
efdRetryCountByPickleId.set(pickle.id, efdRetryCount)
if (efdRetryCount === 0 && status !== 'skip') {
efdSlowAbortedPickleIds.add(pickle.id)
}
}
maybeRecordFinalParallelEfdStatus({ pickleId: pickle.id, testFileAbsolutePath, testFullname })
} else if (
isTestManagementTestsEnabled &&
getTestProperties(getTestSuitePath(testFileAbsolutePath, process.cwd()), pickle.name).attemptToFix
) {
const testFullname = `${pickle.uri}:${pickle.name}`
let testStatuses = attemptToFixTestsByTestFullname.get(testFullname)
if (testStatuses) {
testStatuses.push(status)
} else {
testStatuses = [status]
attemptToFixTestsByTestFullname.set(testFullname, testStatuses)
}
if (status === 'skip' || testStatuses.length === testManagementAttemptToFixRetries + 1) {
finished.push(getTestStatusFromAttemptToFixExecutions(testStatuses))
attemptToFixTestsByTestFullname.delete(testFullname)
}
} else {
// TODO: can we get error message?
finished.push(status)
}
finishParallelSuiteIfDone(testFileAbsolutePath)
}
function getWrappedHandleWorkerThreadEvent (handleEventFromWorker) {
return function (worker, event) {
if (!testSuiteFinishCh.hasSubscribers) {
return handleEventFromWorker.apply(this, arguments)
}
if (handleDdWorkerMessage(event)) return
const envelope = event?.type === 'ENVELOPE' && event.envelope
if (!envelope) {
return handleEventFromWorker.apply(this, arguments)
}
const assembledTestCase = getRunningAssembledTestCase(this, worker)
if (envelope.testCaseStarted) {
maybeStartParallelSuite(assembledTestCase?.pickle)
}
const result = handleEventFromWorker.apply(this, arguments)
if (envelope.testCaseFinished && assembledTestCase?.pickle && eventDataCollector) {
const worstTestStepResult =
eventDataCollector.getTestCaseAttempt(envelope.testCaseFinished.testCaseStartedId).worstTestStepResult
handleParallelTestCaseFinished(assembledTestCase.pickle, worstTestStepResult)
}
return result
}
}
function getWrappedWorkerThreadsSetup (setup) {
return async function () {
if (testSuiteFinishCh.hasSubscribers) {
configureParallelWorkerWorldParameters(this.options)
registerWorkerThreadPatchModule(this.supportCodeLibrary)
}
const result = await setup.apply(this, arguments)
if (testSuiteFinishCh.hasSubscribers) {
registerWorkerThreadMessageHandlers(this.workers)
}
return result
}
}
function getWrappedWorkerThreadsTeardown (teardown) {
return function () {
if (testSuiteFinishCh.hasSubscribers && this.workers) {
for (const worker of this.workers) {
worker.workerThread.removeListener('message', onCucumberWorkerThreadMessage)
}
}
return teardown.apply(this, arguments)
}
}
function finishParallelSuiteIfDone (testFileAbsolutePath) {
const finished = pickleResultByFile[testFileAbsolutePath]
const expectedPickles = pickleByFile[testFileAbsolutePath]
if (!finished || !expectedPickles || finished.length !== expectedPickles.length) return
if (finishedParallelSuites.has(testFileAbsolutePath)) return
finishedParallelSuites.add(testFileAbsolutePath)
testSuiteFinishCh.publish({
status: getSuiteStatusFromTestStatuses(finished),
testSuitePath: getTestSuitePath(testFileAbsolutePath, process.cwd()),
})
}
function maybeRecordFinalParallelEfdStatus ({ pickleId, testFileAbsolutePath, testFullname }) {
const efdRetryCount = efdRetryCountByPickleId.get(pickleId)
const testStatuses = newTestsByTestFullname.get(testFullname)
const finished = pickleResultByFile[testFileAbsolutePath]
if (efdRetryCount === undefined || !testStatuses || !finished) return
if (testStatuses.length !== efdRetryCount + 1) return
finished.push(getTestStatusFromRetries(testStatuses))
newTestsByTestFullname.delete(testFullname)
finishParallelSuiteIfDone(testFileAbsolutePath)
}
function handleEfdRetryCountMessage (message) {
const { pickleId, retryCount, testFileAbsolutePath, testName } = message
if (!pickleId || typeof retryCount !== 'number' || !testFileAbsolutePath || !testName) return
efdRetryCountByPickleId.set(pickleId, retryCount)
maybeRecordFinalParallelEfdStatus({
pickleId,
testFileAbsolutePath,
testFullname: `${testFileAbsolutePath}:${testName}`,
})
}
function getStatusFromResult (result) {
if (result.status === 1) {
return { status: 'pass' }
}
if (result.status === 2) {
return { status: 'skip' }
}
if (result.status === 4) {
return { status: 'skip', skipReason: 'not implemented' }
}
return { status: 'fail', errorMessage: result.message }
}
function getStatusFromResultLatest (result) {
if (result.status === 'PASSED') {
return { status: 'pass' }
}
if (result.status === 'SKIPPED' || result.status === 'PENDING') {
return { status: 'skip' }
}
if (result.status === 'UNDEFINED') {
return { status: 'skip', skipReason: 'not implemented' }
}
return { status: 'fail', errorMessage: result.message }
}
function isNewTest (testSuite, testName) {
if (!isValidKnownTests(knownTests)) {
return false
}
const testsForSuite = knownTests.cucumber[testSuite] || []
return !testsForSuite.includes(testName)
}
function getTestProperties (testSuite, testName) {
const { attempt_to_fix: attemptToFix, disabled, quarantined } =
testManagementTests?.cucumber?.suites?.[testSuite]?.tests?.[testName]?.properties || {}
return { attemptToFix, disabled, quarantined }
}
function getTestStatusFromRetries (testStatuses) {
if (testStatuses.every(status => status === 'fail')) {
return 'fail'
}
if (testStatuses.includes('pass')) {
return 'pass'
}
return 'pass'
}
function getTestStatusFromAttemptToFixExecutions (testStatuses) {
if (testStatuses.every(status => status === 'pass')) {
return 'pass'
}
if (testStatuses.every(status => status === 'skip')) {
return 'skip'
}
return 'fail'
}
function getErrorFromCucumberResult (cucumberResult) {
if (!cucumberResult.message) {
return
}
const error = new Error(getSegment(cucumberResult.message, '\n', 0))
if (cucumberResult.exception) {
error.type = cucumberResult.exception.type
}
error.stack = cucumberResult.message
return error
}
function getShouldBeSkippedSuite (pickle, suitesToSkip) {
const testSuitePath = getTestSuitePath(pickle.uri, process.cwd())
const isUnskippable = isMarkedAsUnskippable(pickle)
const isSkipped = suitesToSkip.includes(testSuitePath)
return [isSkipped && !isUnskippable, testSuitePath]
}
// From cucumber@>=11
function getFilteredPicklesNew (coordinator, suitesToSkip) {
return coordinator.sourcedPickles.reduce((acc, sourcedPickle) => {
const { pickle } = sourcedPickle
const [shouldBeSkipped, testSuitePath] = getShouldBeSkippedSuite(pickle, suitesToSkip)
if (shouldBeSkipped) {
acc.skippedSuites.add(testSuitePath)
} else {
acc.picklesToRun.push(sourcedPickle)
}
return acc
}, { skippedSuites: new Set(), picklesToRun: [] })
}
function getFilteredPickles (runtime, suitesToSkip) {
return runtime.pickleIds.reduce((acc, pickleId) => {
const pickle = runtime.eventDataCollector.getPickle(pickleId)
const [shouldBeSkipped, testSuitePath] = getShouldBeSkippedSuite(pickle, suitesToSkip)
if (shouldBeSkipped) {
acc.skippedSuites.add(testSuitePath)
} else {
acc.picklesToRun.push(pickleId)
}
return acc
}, { skippedSuites: new Set(), picklesToRun: [] })
}
// From cucumber@>=11
function getPickleByFileNew (coordinator) {
return coordinator.sourcedPickles.reduce((acc, { pickle }) => {
if (acc[pickle.uri]) {
acc[pickle.uri].push(pickle)
} else {
acc[pickle.uri] = [pickle]
}
return acc
}, {})
}
function getPickleByFile (runtimeOrCoodinator) {
return runtimeOrCoodinator.pickleIds.reduce((acc, pickleId) => {
const test = runtimeOrCoodinator.eventDataCollector.getPickle(pickleId)
if (acc[test.uri]) {
acc[test.uri].push(test)
} else {
acc[test.uri] = [test]
}
return acc
}, {})
}
function getFinalStatus ({
status,
hasFailedAllRetries,
isLastAtrRetry,
isLastEfdRetry,
isLastAttemptToFix,
hasPassedAllRetries,
isQuarantined,
isDisabled,
}) {
// Note that intermediate executions DO NOT report a final status tag
// If the test is quarantined or disabled, its final status is skip unless attempt-to-fix takes precedence.
if (status === 'skip' || (!isLastAttemptToFix && (isQuarantined || isDisabled))) {
return 'skip'
}
// When no retry feature is active, every execution is final
if (!isLastAtrRetry && !isLastEfdRetry && !isLastAttemptToFix) {
return status
}
// ATR and EFD: pass unless every attempt failed
if (isLastAtrRetry || isLastEfdRetry) {
return hasFailedAllRetries ? 'fail' : 'pass'
}
// Branch for ATF (We need to check hasPassedAllRetries)
if (isLastAttemptToFix) {
return hasPassedAllRetries ? 'pass' : 'fail'
}
}
async function handleRetriedAttempt (runner, state) {
const { promises } = state
if (promises.hitBreakpointPromise) {
await promises.hitBreakpointPromise
}
const setProbePromise = publishRetriedAttempt(runner, state)
if (setProbePromise) {
await setProbePromise
promises.setProbePromise = undefined
}
startRetriedAttempt(state)
}
function handleRetriedAttemptFromEnvelope (runner, state) {
publishRetriedAttempt(runner, state)
startRetriedAttempt(state)
}
function publishRetriedAttempt (runner, state) {
const { promises } = state
let error
try {
const cucumberResult = runner.getWorstStepResult()
error = getErrorFromCucumberResult(cucumberResult)
} catch {
// ignore error
}
const currentAttempt = state.numAttempt
const nextAttempt = currentAttempt + 1
const failedAttemptCtx = numAttemptToCtx.get(currentAttempt)
const isFirstAttempt = currentAttempt === 0
const isAtrRetry = !isFirstAttempt && isFlakyTestRetriesEnabled
// ATR: record this attempt as failed so when run().finally runs (after retry) we have all statuses
if (isFlakyTestRetriesEnabled) {
const nameForKey = getCucumberTestName(runner.pickle.name, currentAttempt > 0)
const atrKey = `${runner.pickle.uri}:${nameForKey}`
if (atrStatusesByScenarioKey.has(atrKey)) {
atrStatusesByScenarioKey.get(atrKey).push('fail')
} else {
atrStatusesByScenarioKey.set(atrKey, ['fail'])
}
}
// the current span will be finished and a new one will be created
testRetryCh.publish({
isFirstAttempt,
error,
isAtrRetry,
promises,
canWaitForDi: state.testStartPayload.canWaitForDi,
...failedAttemptCtx.currentStore,
})
state.numAttempt = nextAttempt
return promises.setProbePromise
}
function startRetriedAttempt (state) {
const { promises, testStartPayload } = state
const newCtx = { ...testStartPayload, promises }
numAttemptToCtx.set(state.numAttempt, newCtx)
testStartCh.runStores(newCtx, () => {})
}
function wrapRun (pl, isLatestVersion, version) {
if (patched.has(pl)) return
patched.add(pl)
const canAwaitRetries = typeof pl.prototype.runAttempt === 'function'
if (canAwaitRetries) {
shimmer.wrap(pl.prototype, 'runAttempt', runAttempt => async function (...args) {
const willBeRetried = await runAttempt.apply(this, args)
const state = runnerToRetryState.get(this)
if (willBeRetried && state) {
await handleRetriedAttempt(this, state)
}
return willBeRetried
})
}
shimmer.wrap(pl.prototype, 'run', run => function (...args) {
if (!testFinishCh.hasSubscribers) {
return run.apply(this, args)
}
const testFileAbsolutePath = this.pickle.uri
const testSuitePath = getTestSuitePath(testFileAbsolutePath, process.cwd())
const testSourceLine = this.gherkinDocument?.feature?.location?.line
const testStartPayload = {
testName: this.pickle.name,
testFileAbsolutePath,
testSourceLine,
isParallel: !!getEnvironmentVariable('CUCUMBER_WORKER_ID'),
// Older Cucumber runners do not expose an awaited retry boundary. Failed Test Replay
// intentionally skips DI setup there instead of bringing back the synchronous wait.
canWaitForDi: canAwaitRetries,
}
const ctx = testStartPayload
const promises = {}
const state = { numAttempt: 0, promises, testStartPayload }
numAttemptToCtx.set(state.numAttempt, ctx)
runnerToRetryState.set(this, state)
if (isTestManagementTestsEnabled && getTestProperties(testSuitePath, this.pickle.name).attemptToFix) {
logAttemptToFixTestExecution(testSuitePath, this.pickle.name, loggedAttemptToFixTests)
}
testStartCh.runStores(ctx, () => {})
try {
const onEnvelope = (testCase) => {
if (canAwaitRetries) return
// Only supported from >=8.0.0
if (testCase?.testCaseFinished) {
const { testCaseFinished: { willBeRetried } } = testCase
if (willBeRetried) { // test case failed and will be retried
handleRetriedAttemptFromEnvelope(this, state)
}
}
}
if (!canAwaitRetries) {
this.eventBroadcaster.on('envelope', onEnvelope)
}
let promise
const executionStart = performance.now()
testFnCh.runStores(ctx, () => {
promise = run.apply(this, args)
})
const finalize = async () => {
if (!canAwaitRetries) {
this.eventBroadcaster.removeListener('envelope', onEnvelope)
}
runnerToRetryState.delete(this)
const result = this.getWorstStepResult()
const { status, skipReason } = isLatestVersion
? getStatusFromResultLatest(result)
: getStatusFromResult(result)
const testName = getCucumberTestName(this.pickle.name, state.numAttempt > 0)
if (lastStatusByPickleId.has(this.pickle.id)) {
lastStatusByPickleId.get(this.pickle.id).push(status)
} else {
lastStatusByPickleId.set(this.pickle.id, [status])
}
let isNew = false
let isEfdRetry = false
let isAttemptToFix = false
let isAttemptToFixRetry = false
let hasFailedAllRetries = false
let hasPassedAllRetries = false
let hasFailedAttemptToFix = false
let isDisabled = false
let isQuarantined = false
let isModified = false
if (isTestManagementTestsEnabled) {
const testSuitePath = getTestSuitePath(testFileAbsolutePath, process.cwd())
const testProperties = getTestProperties(testSuitePath, testName)
const numRetries = numRetriesByPickleId.get(this.pickle.id)
isAttemptToFix = testProperties.attemptToFix
isAttemptToFixRetry = isAttemptToFix && numRetries > 0
isDisabled = testProperties.disabled
isQuarantined = testProperties.quarantined
if (isAttemptToFixRetry) {
const statuses = lastStatusByPickleId.get(this.pickle.id)
if (statuses.length === testManagementAttemptToFixRetries + 1) {
const { pass, fail } = statuses.reduce((acc, status) => {
acc[status]++
return acc
}, { pass: 0, fail: 0 })
hasFailedAllRetries = fail === testManagementAttemptToFixRetries + 1
hasPassedAllRetries = pass === testManagementAttemptToFixRetries + 1
hasFailedAttemptToFix = fail > 0
}
}
}
const numRetries = numRetriesByPickleId.get(this.pickle.id)
if (isImpactedTestsEnabled) {
isModified = modifiedTestsByPickleId.get(this.pickle.id)
}
if (isKnownTestsEnabled && status !== 'skip') {
isNew = newTestPickleIds.has(this.pickle.id)
}
if (isNew || isModified) {
isEfdRetry = numRetries > 0
}
if (
shouldRunEarlyFlakeDetection() &&
status !== 'skip' &&
(isNew || isModified) &&
!isEfdRetry &&
!efdRetryCountByPickleId.has(this.pickle.id)
) {
const retryCount = getEfdRetryCountForDuration(
performance.now() - executionStart,
earlyFlakeDetectionRetryPolicy
)
efdRetryCountByPickleId.set(this.pickle.id, retryCount)
if (retryCount === 0) {
efdSlowAbortedPickleIds.add(this.pickle.id)
}
}
const efdRetryCount = efdRetryCountByPickleId.get(this.pickle.id) ??
earlyFlakeDetectionRetryPolicy.schedulingRetryCount
// Check if all EFD retries failed
if (isEfdRetry && (isNew || isModified)) {
const statuses = lastStatusByPickleId.get(this.pickle.id)
if (statuses.length === efdRetryCount + 1) {
const { fail } = statuses.reduce((acc, status) => {
acc[status]++
return acc
}, { pass: 0, fail: 0 })
if (fail === efdRetryCount + 1) {
hasFailedAllRetries = true
}
}
}
// ATR: accumulate statuses by stable scenario key (uri:name) so retries are grouped.
// Cucumber appends " (attempt N)" or " (attempt N, retried)" to the scenario name; normalize for keying.
if (isFlakyTestRetriesEnabled && !isAttemptToFix && !isEfdRetry && numTestRetries > 0) {
const atrKey = `${this.pickle.uri}:${testName}`
if (atrStatusesByScenarioKey.has(atrKey)) {
atrStatusesByScenarioKey.get(atrKey).push(status)
} else {
atrStatusesByScenarioKey.set(atrKey, [status])
}
const atrStatuses = atrStatusesByScenarioKey.get(atrKey)
const pickleStatuses = lastStatusByPickleId.get(this.pickle.id)
const statusesToCheck = atrStatuses?.length >= (numTestRetries + 1) ? atrStatuses : pickleStatuses
if (statusesToCheck && statusesToCheck.length === numTestRetries + 1 &&
statusesToCheck.every(s => s === 'fail')) {
hasFailedAllRetries = true
}
}
const attemptCtx = numAttemptToCtx.get(state.numAttempt)
const error = getErrorFromCucumberResult(result)
if (!testStartPayload.isParallel) {
recordTestManagementExecution({
testSuite: testSuitePath,
testName,
status,
isAttemptToFix,
isDisabled,
isQuarantined,
})
}
if (isAttemptToFix) {
recordAttemptToFixExecution(attemptToFixExecutions, {
testSuite: testSuitePath,
testName,
status,
isDisabled,
isQuarantined,
})
}
if (promises.hitBreakpointPromise) {
await promises.hitBreakpointPromise
}
// Notice that ATR is handled using cucumber native retries features.
// Therefore, if we reach this point, we are certain that it's the last ATR execution
const isLastAtrRetry = isFlakyTestRetriesEnabled && !isAttemptToFix && !isEfdRetry && numTestRetries > 0
const statuses = lastStatusByPickleId.get(this.pickle.id)
const isLastEfdRetry = isEfdRetry && statuses?.length === efdRetryCount + 1
const isLastAttemptToFixRetry = isAttemptToFix && statuses?.length === testManagementAttemptToFixRetries + 1
// Intermediate (non-last EFD or ATF retries) executions do not report a final status
const isIntermediateExecution = (isEfdRetry && !isLastEfdRetry) || (isAttemptToFix && !isLastAttemptToFixRetry)
const finalStatus = isIntermediateExecution
? undefined
: getFinalStatus({
status,
hasFailedAllRetries,
isLastAtrRetry,
isLastEfdRetry,
isLastAttemptToFix: isLastAttemptToFixRetry,
hasPassedAllRetries,
isQuarantined,
isDisabled,
})
testFinishCh.publish({
status,
skipReason,
error,
isNew,
isEfdRetry,
isFlakyRetry: state.numAttempt > 0 && isFlakyTestRetriesEnabled,
isExternalRetry: state.numAttempt > 0 && !isFlakyTestRetriesEnabled,
isAttemptToFix,
isAttemptToFixRetry,
hasFailedAllRetries,
hasPassedAllRetries,
hasFailedAttemptToFix,
isDisabled,
isQuarantined,
isModified,
earlyFlakeAbortReason: efdSlowAbortedPickleIds.has(this.pickle.id) ? 'slow' : undefined,