-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathvitest.spec.js
More file actions
2702 lines (2337 loc) · 108 KB
/
vitest.spec.js
File metadata and controls
2702 lines (2337 loc) · 108 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 assert = require('node:assert/strict')
const { once } = require('node:events')
const { exec, execSync } = require('child_process')
const path = require('path')
const fs = require('fs')
const { assertObjectContains } = require('../helpers')
const {
sandboxCwd,
useSandbox,
getCiVisAgentlessConfig,
getCiVisEvpProxyConfig,
} = require('../helpers')
const { FakeCiVisIntake } = require('../ci-visibility-intake')
const {
TEST_STATUS,
TEST_TYPE,
TEST_IS_RETRY,
TEST_CODE_OWNERS,
TEST_CODE_COVERAGE_LINES_PCT,
TEST_SESSION_NAME,
TEST_COMMAND,
TEST_LEVEL_EVENT_TYPES,
TEST_SOURCE_FILE,
TEST_SOURCE_START,
TEST_IS_NEW,
TEST_NAME,
TEST_EARLY_FLAKE_ENABLED,
TEST_EARLY_FLAKE_ABORT_REASON,
TEST_SUITE,
DI_ERROR_DEBUG_INFO_CAPTURED,
DI_DEBUG_ERROR_PREFIX,
DI_DEBUG_ERROR_FILE_SUFFIX,
DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX,
DI_DEBUG_ERROR_LINE_SUFFIX,
TEST_RETRY_REASON,
DD_TEST_IS_USER_PROVIDED_SERVICE,
TEST_MANAGEMENT_ENABLED,
TEST_MANAGEMENT_IS_QUARANTINED,
TEST_MANAGEMENT_IS_DISABLED,
TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX,
TEST_HAS_FAILED_ALL_RETRIES,
TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED,
DD_CAPABILITIES_TEST_IMPACT_ANALYSIS,
DD_CAPABILITIES_EARLY_FLAKE_DETECTION,
DD_CAPABILITIES_AUTO_TEST_RETRIES,
DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE,
DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE,
DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX,
DD_CAPABILITIES_FAILED_TEST_REPLAY,
TEST_RETRY_REASON_TYPES,
TEST_HAS_DYNAMIC_NAME,
TEST_IS_MODIFIED,
DD_CAPABILITIES_IMPACTED_TESTS,
VITEST_POOL,
TEST_IS_TEST_FRAMEWORK_WORKER,
GIT_COMMIT_SHA,
GIT_REPOSITORY_URL,
DD_CI_LIBRARY_CONFIGURATION_ERROR,
} = require('../../packages/dd-trace/src/plugins/util/test')
const { DD_HOST_CPU_COUNT } = require('../../packages/dd-trace/src/plugins/util/env')
const { TELEMETRY_COVERAGE_UPLOAD } = require('../../packages/dd-trace/src/ci-visibility/telemetry')
const { NODE_MAJOR } = require('../../version')
const NUM_RETRIES_EFD = 3
// vitest@4.x requires Node.js >= 20
const versions = NODE_MAJOR <= 18 ? ['1.6.0', '3'] : ['1.6.0', 'latest']
const linePctMatchRegex = /Lines\s+:\s+([\d.]+)%/
versions.forEach((version) => {
describe(`vitest@${version}`, () => {
let cwd, receiver, childProcess, testOutput
useSandbox([
`vitest@${version}`,
`@vitest/coverage-istanbul@${version}`,
`@vitest/coverage-v8@${version}`,
'tinypool',
], true)
before(function () {
cwd = sandboxCwd()
})
beforeEach(async function () {
receiver = await new FakeCiVisIntake().start()
})
afterEach(async () => {
testOutput = ''
childProcess.kill()
await receiver.stop()
})
const poolConfig = ['forks', 'threads']
poolConfig.forEach((poolConfig) => {
it(`can run and report tests with pool=${poolConfig}`, async () => {
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init', // ESM requires more flags
DD_TEST_SESSION_NAME: 'my-test-session',
POOL_CONFIG: poolConfig,
DD_SERVICE: undefined,
},
}
)
await Promise.all([
once(childProcess, 'exit'),
receiver.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata)
metadataDicts.forEach(metadata => {
for (const testLevel of TEST_LEVEL_EVENT_TYPES) {
assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session')
}
})
const events = payloads.flatMap(({ payload }) => payload.events)
const testSessionEvent = events.find(event => event.type === 'test_session_end')
if (poolConfig === 'threads') {
assert.strictEqual(testSessionEvent.content.meta[VITEST_POOL], 'worker_threads')
} else {
assert.strictEqual(testSessionEvent.content.meta[VITEST_POOL], 'child_process')
}
const testModuleEvent = events.find(event => event.type === 'test_module_end')
const testSuiteEvents = events.filter(event => event.type === 'test_suite_end')
const testEvents = events.filter(event => event.type === 'test')
assert.ok(testSessionEvent.content.resource.includes('test_session.vitest run'))
assert.strictEqual(testSessionEvent.content.meta[TEST_STATUS], 'fail')
assert.ok(testModuleEvent.content.resource.includes('test_module.vitest run'))
assert.strictEqual(testModuleEvent.content.meta[TEST_STATUS], 'fail')
assert.strictEqual(testSessionEvent.content.meta[TEST_TYPE], 'test')
assert.strictEqual(testModuleEvent.content.meta[TEST_TYPE], 'test')
const passedSuite = testSuiteEvents.find(
suite =>
suite.content.resource === 'test_suite.ci-visibility/vitest-tests/test-visibility-passed-suite.mjs'
)
assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass')
const failedSuite = testSuiteEvents.find(
suite =>
suite.content.resource === 'test_suite.ci-visibility/vitest-tests/test-visibility-failed-suite.mjs'
)
assert.strictEqual(failedSuite.content.meta[TEST_STATUS], 'fail')
const failedSuiteHooks = testSuiteEvents.find(
suite =>
suite.content.resource === 'test_suite.ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs'
)
assert.strictEqual(failedSuiteHooks.content.meta[TEST_STATUS], 'fail')
assert.deepStrictEqual(testEvents.map(test => test.content.resource).sort(),
[
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report failed test',
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report more',
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report more',
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report passed test',
'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' +
'.test-visibility-failed-suite-first-describe can report failed test',
'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' +
'.test-visibility-failed-suite-first-describe can report more',
'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' +
'.test-visibility-failed-suite-second-describe can report more',
'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' +
'.test-visibility-failed-suite-second-describe can report passed test',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.context can report more',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.context can report passed test',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.no suite',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can programmatic skip',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can report more',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can report passed test',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can skip',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can todo',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.programmatic skip no suite',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.skip no suite',
]
)
const failedTests = testEvents.filter(test => test.content.meta[TEST_STATUS] === 'fail')
assertObjectContains(
failedTests.map(test => test.content.resource).sort(),
[
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report failed test',
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report more',
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report more',
'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report passed test',
'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' +
'.test-visibility-failed-suite-first-describe can report failed test',
]
)
const skippedTests = testEvents.filter(test => test.content.meta[TEST_STATUS] === 'skip')
assertObjectContains(
skippedTests.map(test => test.content.resource),
[
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can skip',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can todo',
'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can programmatic skip',
]
)
testEvents.forEach(test => {
// `threads` config will report directly. TODO: update this once we're testing vitest@>=4
if (poolConfig === 'forks') {
assert.strictEqual(test.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true')
}
assert.strictEqual(test.content.meta[TEST_COMMAND], 'vitest run')
assert.ok(test.content.metrics[DD_HOST_CPU_COUNT])
assert.strictEqual(test.content.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false')
})
testSuiteEvents.forEach(testSuite => {
// `threads` config will report directly. TODO: update this once we're testing vitest@>=4
if (poolConfig === 'forks') {
assert.strictEqual(testSuite.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true')
}
assert.strictEqual(testSuite.content.meta[TEST_COMMAND], 'vitest run')
assert.strictEqual(
testSuite.content.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/vitest-tests/test-visibility'),
true
)
assert.strictEqual(testSuite.content.metrics[TEST_SOURCE_START], 1)
assert.ok(testSuite.content.metrics[DD_HOST_CPU_COUNT])
})
}),
])
})
})
it('propagates test span context to HTTP requests and hooks during test execution', async () => {
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', (payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const tests = events.filter(event => event.type === 'test').map(event => event.content)
const spans = events.filter(event => event.type === 'span').map(event => event.content)
// --- Test function: HTTP request + custom tag ---
const httpTestSpan = tests.find(
test => test.meta[TEST_NAME] === 'vitest-test-integration-http can do integration http'
)
assert.ok(httpTestSpan, 'should have http test span')
assert.strictEqual(httpTestSpan.meta[TEST_STATUS], 'pass')
assert.strictEqual(httpTestSpan.meta['test.custom_tag'], 'custom_value',
'custom tag set via active span should be present')
const testHttpSpans = spans.filter(span =>
span.name === 'http.request' &&
span.trace_id.toString() === httpTestSpan.trace_id.toString()
)
assert.ok(testHttpSpans.length > 0, 'should have http span with matching trace_id')
const testHttpSpan = testHttpSpans.find(span =>
span.parent_id.toString() === httpTestSpan.span_id.toString()
)
assert.ok(testHttpSpan, 'HTTP span from test fn should be child of test span')
assert.match(testHttpSpan.meta['http.url'], /\/info/)
// --- beforeEach + afterEach hooks: HTTP requests ---
const hookTestSpan = tests.find(
test => test.meta[TEST_NAME] === 'vitest-test-hook-http hook http is linked to test span'
)
assert.ok(hookTestSpan, 'should have hook test span')
assert.strictEqual(hookTestSpan.meta[TEST_STATUS], 'pass')
const hookHttpSpans = spans.filter(span =>
span.name === 'http.request' &&
span.trace_id.toString() === hookTestSpan.trace_id.toString() &&
span.parent_id.toString() === hookTestSpan.span_id.toString()
)
assert.strictEqual(hookHttpSpans.length, 2,
'should have 2 http spans from hooks (beforeEach + afterEach) as children of test span')
const cleanupHookTestName =
'vitest-test-before-each-cleanup-http beforeEach cleanup http is linked to test span'
const cleanupHookTestSpan = tests.find(test => test.meta[TEST_NAME] === cleanupHookTestName)
assert.ok(cleanupHookTestSpan, 'should have beforeEach cleanup hook test span')
assert.strictEqual(cleanupHookTestSpan.meta[TEST_STATUS], 'pass')
const cleanupHookHttpSpans = spans.filter(span =>
span.name === 'http.request' &&
span.trace_id.toString() === cleanupHookTestSpan.trace_id.toString() &&
span.parent_id.toString() === cleanupHookTestSpan.span_id.toString()
)
assert.strictEqual(cleanupHookHttpSpans.length, 2,
'should have 2 http spans from beforeEach and its returned cleanup as children of test span')
}, 25000)
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
TEST_DIR: 'ci-visibility/vitest-tests/http-integration*',
DD_SERVICE: undefined,
},
}
)
await Promise.all([
once(childProcess, 'exit'),
eventsPromise,
])
})
context('error tags', () => {
it('tags session and children with _dd.ci.library_configuration_error when settings fails', async () => {
receiver.setSettingsResponseCode(404)
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', (payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testSession = events.find(event => event.type === 'test_session_end').content
assert.strictEqual(testSession.meta[DD_CI_LIBRARY_CONFIGURATION_ERROR], 'true')
const testEvent = events.find(event => event.type === 'test')
assert.ok(testEvent, 'should have test event')
assert.strictEqual(testEvent.content.meta[DD_CI_LIBRARY_CONFIGURATION_ERROR], 'true')
})
childProcess = exec('./node_modules/.bin/vitest run', {
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
},
})
await Promise.all([eventsPromise, once(childProcess, 'exit')])
})
})
it('sends telemetry with test_session metric when telemetry is enabled', async () => {
const telemetryPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/apmtelemetry'), (payloads) => {
const telemetryMetrics = payloads.flatMap(({ payload }) => payload.payload.series)
const testSessionMetric = telemetryMetrics.find(
({ metric }) => metric === 'test_session'
)
assert.ok(testSessionMetric, 'test_session telemetry metric should be sent')
})
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisEvpProxyConfig(receiver.port),
DD_TRACE_AGENT_PORT: String(receiver.port),
DD_INSTRUMENTATION_TELEMETRY_ENABLED: 'true',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init', // ESM requires more flags
TEST_DIR: 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs',
},
}
)
await Promise.all([
once(childProcess, 'exit'),
telemetryPromise,
])
})
context('flaky test retries', () => {
it('can retry flaky tests', (done) => {
receiver.setSettings({
itr_enabled: false,
code_coverage: false,
tests_skipping: false,
flaky_test_retries_enabled: true,
early_flake_detection: {
enabled: false,
},
})
receiver.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(testEvents.length, 11)
assertObjectContains(testEvents.map(test => test.content.resource), [
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
// passes at the third retry
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
// never passes
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
// passes on the first try
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary',
])
const eventuallyPassingTest = testEvents.filter(
test => test.content.resource ===
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass'
)
assert.strictEqual(eventuallyPassingTest.length, 4)
assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 3)
assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 1)
assert.strictEqual(
eventuallyPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length,
3
)
assert.strictEqual(eventuallyPassingTest.filter(test =>
test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr
).length, 3)
const neverPassingTest = testEvents.filter(
test => test.content.resource ===
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass'
)
assert.strictEqual(neverPassingTest.length, 6)
assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 6)
assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 0)
assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, 5)
assert.strictEqual(neverPassingTest.filter(test =>
test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr
).length, 5)
}).then(() => done()).catch(done)
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/flaky-test-retries*',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init', // ESM requires more flags
},
}
)
})
it('is disabled if DD_CIVISIBILITY_FLAKY_RETRY_ENABLED is false', (done) => {
receiver.setSettings({
itr_enabled: false,
code_coverage: false,
tests_skipping: false,
flaky_test_retries_enabled: true,
early_flake_detection: {
enabled: false,
},
})
receiver.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(testEvents.length, 3)
assertObjectContains(testEvents.map(test => test.content.resource), [
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary',
])
assert.strictEqual(testEvents.filter(
test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr
).length, 0)
}).then(() => done()).catch(done)
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/flaky-test-retries*',
DD_CIVISIBILITY_FLAKY_RETRY_ENABLED: 'false',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init', // ESM requires more flags
},
}
)
})
it('retries DD_CIVISIBILITY_FLAKY_RETRY_COUNT times', (done) => {
receiver.setSettings({
itr_enabled: false,
code_coverage: false,
tests_skipping: false,
flaky_test_retries_enabled: true,
early_flake_detection: {
enabled: false,
},
})
receiver.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(testEvents.length, 5)
assertObjectContains(testEvents.map(test => test.content.resource), [
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass',
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary',
])
assert.strictEqual(testEvents.filter(
test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr
).length, 2)
}).then(() => done()).catch(done)
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/flaky-test-retries*',
DD_CIVISIBILITY_FLAKY_RETRY_COUNT: '1',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init', // ESM requires more flags
},
}
)
})
it('sets TEST_HAS_FAILED_ALL_RETRIES when all ATR attempts fail', async () => {
receiver.setSettings({
itr_enabled: false,
code_coverage: false,
tests_skipping: false,
flaky_test_retries_enabled: true,
flaky_test_retries_count: 2,
early_flake_detection: {
enabled: false,
},
})
const eventsPromise = receiver.gatherPayloadsMaxTimeout(
({ url }) => url === '/api/v2/citestcycle',
payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const tests = events.filter(event => event.type === 'test').map(event => event.content)
const neverPassingTest = tests.filter(
test => test.resource ===
'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass'
)
assert.strictEqual(neverPassingTest.length, 3, '1 initial + 2 ATR retries')
neverPassingTest.forEach(t => assert.strictEqual(t.meta[TEST_STATUS], 'fail'))
const lastAttempt = neverPassingTest[neverPassingTest.length - 1]
assert.strictEqual(lastAttempt.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true')
for (let i = 0; i < neverPassingTest.length - 1; i++) {
assert.ok(!(TEST_HAS_FAILED_ALL_RETRIES in neverPassingTest[i].meta))
}
}
)
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/flaky-test-retries*',
DD_CIVISIBILITY_FLAKY_RETRY_COUNT: '2',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
},
}
)
await Promise.all([once(childProcess, 'exit'), eventsPromise])
})
})
it('correctly calculates test code owners when working directory is not repository root', (done) => {
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const test = events.find(event => event.type === 'test').content
const testSuite = events.find(event => event.type === 'test_suite_end').content
assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js']))
assert.strictEqual(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js']))
}, 25000)
childProcess = exec(
'../../node_modules/.bin/vitest run',
{
cwd: `${cwd}/ci-visibility/subproject`,
env: {
...getCiVisAgentlessConfig(receiver.port),
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
TEST_DIR: './vitest-test.mjs',
},
}
)
childProcess.on('exit', () => {
eventsPromise.then(() => {
done()
}).catch(done)
})
})
// total code coverage only works for >=2.0.0
// v4 dropped support for Node 18. Every test but this once passes, so we'll leave them
// for now. The breaking change is in https://github.com/vitest-dev/vitest/commit/9a0bf2254
// shipped in https://github.com/vitest-dev/vitest/releases/tag/v4.0.0-beta.12
if (version === 'latest' && NODE_MAJOR >= 20) {
const coverageProviders = ['v8', 'istanbul']
coverageProviders.forEach((coverageProvider) => {
it(`reports code coverage for ${coverageProvider} provider`, async () => {
let codeCoverageExtracted
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testSession = events.find(event => event.type === 'test_session_end').content
codeCoverageExtracted = testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]
})
childProcess = exec(
'./node_modules/.bin/vitest run --coverage',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
COVERAGE_PROVIDER: coverageProvider,
TEST_DIR: 'ci-visibility/vitest-tests/coverage-test.mjs',
},
}
)
childProcess.stdout?.on('data', (chunk) => {
testOutput += chunk.toString()
})
childProcess.stderr?.on('data', (chunk) => {
testOutput += chunk.toString()
})
await Promise.all([
once(childProcess, 'exit'),
eventsPromise,
])
const linePctMatch = testOutput.match(linePctMatchRegex)
const linesPctFromNyc = Number(linePctMatch[1])
assert.strictEqual(
linesPctFromNyc,
codeCoverageExtracted,
'coverage reported by vitest does not match extracted coverage'
)
})
})
it('reports zero code coverage for instanbul provider', async () => {
let codeCoverageExtracted
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testSession = events.find(event => event.type === 'test_session_end').content
codeCoverageExtracted = testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]
})
childProcess = exec(
'./node_modules/.bin/vitest run --coverage',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
COVERAGE_PROVIDER: 'istanbul',
TEST_DIR: 'ci-visibility/vitest-tests/coverage-test-zero.mjs',
},
}
)
childProcess.stdout?.on('data', (chunk) => {
testOutput += chunk.toString()
})
childProcess.stderr?.on('data', (chunk) => {
testOutput += chunk.toString()
})
await Promise.all([
once(childProcess, 'exit'),
eventsPromise,
])
const linePctMatch = testOutput.match(linePctMatchRegex)
const linesPctFromNyc = Number(linePctMatch[1])
assert.strictEqual(
linesPctFromNyc,
codeCoverageExtracted,
'coverage reported by vitest does not match extracted coverage'
)
assert.strictEqual(
linesPctFromNyc,
0,
'zero coverage should be reported'
)
})
}
context('early flake detection', () => {
it('retries new tests', (done) => {
receiver.setSettings({
early_flake_detection: {
enabled: true,
slow_test_retries: {
'5s': NUM_RETRIES_EFD,
},
},
known_tests_enabled: true,
})
receiver.setKnownTests({
vitest: {
'ci-visibility/vitest-tests/early-flake-detection.mjs': [
// 'early flake detection can retry tests that eventually pass', // will be considered new
// 'early flake detection can retry tests that always pass', // will be considered new
// 'early flake detection can retry tests that eventually fail', // will be considered new
// 'early flake detection does not retry if the test is skipped', // skipped so not retried
'early flake detection does not retry if it is not new',
],
},
})
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const tests = events.filter(event => event.type === 'test').map(test => test.content)
assert.strictEqual(tests.length, 14)
assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that always pass',
'early flake detection can retry tests that always pass',
'early flake detection can retry tests that always pass',
'early flake detection can retry tests that eventually fail',
'early flake detection can retry tests that eventually fail',
'early flake detection can retry tests that eventually fail',
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that always pass',
'early flake detection does not retry if it is not new',
'early flake detection does not retry if the test is skipped',
'early flake detection can retry tests that eventually fail',
])
const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true')
// 4 executions of the 3 new tests + 1 new skipped test (not retried)
assert.strictEqual(newTests.length, 13)
const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true')
assert.strictEqual(retriedTests.length, 9) // 3 retries of the 3 new tests
retriedTests.forEach(test => {
assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd)
})
// exit code should be 0 and test session should be reported as passed,
// even though there are some failing executions
const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail')
assert.strictEqual(failedTests.length, 3)
const testSessionEvent = events.find(event => event.type === 'test_session_end').content
assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'pass')
assert.strictEqual(testSessionEvent.meta[TEST_EARLY_FLAKE_ENABLED], 'true')
})
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/early-flake-detection*',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
SHOULD_ADD_EVENTUALLY_FAIL: '1',
},
}
)
childProcess.on('exit', (exitCode) => {
eventsPromise.then(() => {
assert.strictEqual(exitCode, 0)
done()
}).catch(done)
})
})
it('fails if all the attempts fail', (done) => {
receiver.setSettings({
early_flake_detection: {
enabled: true,
slow_test_retries: {
'5s': NUM_RETRIES_EFD,
},
},
known_tests_enabled: true,
})
receiver.setKnownTests({
vitest: {
'ci-visibility/vitest-tests/early-flake-detection.mjs': [
// 'early flake detection can retry tests that eventually pass', // will be considered new
// 'early flake detection can retry tests that always pass', // will be considered new
// 'early flake detection does not retry if the test is skipped', // skipped so not retried
'early flake detection does not retry if it is not new',
],
},
})
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const tests = events.filter(event => event.type === 'test').map(test => test.content)
assert.strictEqual(tests.length, 10)
assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that always pass',
'early flake detection can retry tests that always pass',
'early flake detection can retry tests that always pass',
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that always pass',
'early flake detection does not retry if it is not new',
'early flake detection does not retry if the test is skipped',
])
const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true')
// 4 executions of the 2 new tests + 1 new skipped test (not retried)
assert.strictEqual(newTests.length, 9)
const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true')
assert.strictEqual(retriedTests.length, 6) // 3 retries of the 2 new tests
// the multiple attempts did not result in a single pass,
// so the test session should be reported as failed
const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail')
assert.strictEqual(failedTests.length, 6)
const testSessionEvent = events.find(event => event.type === 'test_session_end').content
assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail')
assert.strictEqual(testSessionEvent.meta[TEST_EARLY_FLAKE_ENABLED], 'true')
// Check that TEST_HAS_FAILED_ALL_RETRIES is set for tests that fail all EFD attempts
const alwaysFailTests = tests.filter(test =>
test.meta[TEST_NAME] === 'early flake detection can retry tests that always pass'
)
assert.strictEqual(alwaysFailTests.length, 4) // 1 initial + 3 retries
// The last execution should have TEST_HAS_FAILED_ALL_RETRIES set
const testsWithFlag = alwaysFailTests.filter(test =>
test.meta[TEST_HAS_FAILED_ALL_RETRIES] === 'true'
)
assert.strictEqual(
testsWithFlag.length,
1,
'Exactly one test should have TEST_HAS_FAILED_ALL_RETRIES set'
)
// It should be the last one
const lastAttempt = alwaysFailTests[alwaysFailTests.length - 1]
assert.strictEqual(
lastAttempt.meta[TEST_HAS_FAILED_ALL_RETRIES],
'true',
'Last attempt should have the flag'
)
})
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/early-flake-detection*',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
ALWAYS_FAIL: 'true',
},
}
)
childProcess.on('exit', (exitCode) => {
eventsPromise.then(() => {
assert.strictEqual(exitCode, 1)
done()
}).catch(done)
})
})
it('bails out of EFD if the percentage of new tests is too high', (done) => {
receiver.setSettings({
early_flake_detection: {
enabled: true,
slow_test_retries: {
'5s': NUM_RETRIES_EFD,
},
faulty_session_threshold: 0,
},
known_tests_enabled: true,
})
receiver.setKnownTests({
vitest: {},
}) // tests from ci-visibility/vitest-tests/early-flake-detection.mjs will be new
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testSession = events.find(event => event.type === 'test_session_end').content
assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty')
const tests = events.filter(event => event.type === 'test').map(event => event.content)
assert.strictEqual(tests.length, 4)
const newTests = tests.filter(
test => test.meta[TEST_IS_NEW] === 'true'
)
// no new tests
assert.strictEqual(newTests.length, 0)
})
childProcess = exec(
'./node_modules/.bin/vitest run',
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
TEST_DIR: 'ci-visibility/vitest-tests/early-flake-detection*',
NODE_OPTIONS: '--import dd-trace/register.js -r dd-trace/ci/init',
},
}
)
childProcess.on('exit', (exitCode) => {
eventsPromise.then(() => {
assert.strictEqual(exitCode, 1)
done()
}).catch(done)
})
})
it('is disabled if DD_CIVISIBILITY_EARLY_FLAKE_DETECTION_ENABLED is false', (done) => {
receiver.setSettings({
early_flake_detection: {
enabled: true,
slow_test_retries: {
'5s': NUM_RETRIES_EFD,
},
},
known_tests_enabled: true,
})
receiver.setKnownTests({
vitest: {
'ci-visibility/vitest-tests/early-flake-detection.mjs': [
// 'early flake detection can retry tests that eventually pass', // will be considered new
// 'early flake detection can retry tests that always pass', // will be considered new
// 'early flake detection does not retry if the test is skipped', // will be considered new
'early flake detection does not retry if it is not new',
],
},
})
const eventsPromise = receiver
.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => {
const events = payloads.flatMap(({ payload }) => payload.events)
const tests = events.filter(event => event.type === 'test').map(test => test.content)
assert.strictEqual(tests.length, 4)
assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [
'early flake detection can retry tests that eventually pass',
'early flake detection can retry tests that always pass',
'early flake detection does not retry if it is not new',