-
Notifications
You must be signed in to change notification settings - Fork 406
Expand file tree
/
Copy pathcypress-reporting-instrumentation.spec.js
More file actions
2103 lines (1849 loc) · 83.9 KB
/
Copy pathcypress-reporting-instrumentation.spec.js
File metadata and controls
2103 lines (1849 loc) · 83.9 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 { exec, execFileSync, execSync } = require('node:child_process')
const { once } = require('node:events')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
const { format } = require('node:util')
const proxyquire = require('proxyquire').noPreserveCache()
const semver = require('semver')
const sinon = require('sinon')
const {
sandboxCwd,
useSandbox,
getCiVisAgentlessConfig,
getCiVisEvpProxyConfig,
assertObjectContains,
stopCiVisTestEnv,
warmCypressBinary,
} = require('../helpers')
const { FakeCiVisIntake } = require('../ci-visibility-intake')
const { startWebAppServer, stopWebAppServer } = require('../ci-visibility/web-app-server')
const {
TEST_STATUS,
TEST_COMMAND,
TEST_MODULE,
TEST_FRAMEWORK,
TEST_FRAMEWORK_VERSION,
TEST_TOOLCHAIN,
TEST_SOURCE_FILE,
TEST_SOURCE_START,
TEST_SESSION_NAME,
DD_TEST_IS_USER_PROVIDED_SERVICE,
DD_CI_LIBRARY_CONFIGURATION_ERROR_SETTINGS,
DD_CI_LIBRARY_CONFIGURATION_ERROR_SKIPPABLE_TESTS,
DD_CI_LIBRARY_CONFIGURATION_ERROR_KNOWN_TESTS,
DD_CI_LIBRARY_CONFIGURATION_ERROR_TEST_MANAGEMENT_TESTS,
} = require('../../packages/dd-trace/src/plugins/util/test')
const { DD_HOST_CPU_COUNT } = require('../../packages/dd-trace/src/plugins/util/env')
const { ERROR_MESSAGE } = require('../../packages/dd-trace/src/constants')
const { DD_MAJOR, NODE_MAJOR } = require('../../version')
const {
resolveOriginalSourceFile,
resolveSourceLineForTest,
} = require('../../packages/datadog-plugin-cypress/src/source-map-utils')
const { getCypressDependencies } = require('./dependencies')
const requestedVersion = process.env.CYPRESS_VERSION
const oldestVersion = DD_MAJOR >= 6 ? '12.0.0' : '6.7.0'
const version = requestedVersion === 'oldest' ? oldestVersion : requestedVersion
const CYPRESS_PRECOMPILED_SPEC_DIST_DIR = 'cypress/e2e/dist'
const over12It = (version === 'latest' || semver.gte(version, '12.0.0')) ? it : it.skip
const cypressVersionsSupportingNode18 = DD_MAJOR === 5
? ['10.2.0', '12.0.0', '14.5.4']
: ['12.0.0', '14.5.4']
function cleanupPrecompiledSourceLineDist (cwd) {
fs.rmSync(path.join(cwd, CYPRESS_PRECOMPILED_SPEC_DIST_DIR), { recursive: true, force: true })
}
function compilePrecompiledTypeScriptSpecs (cwd, env) {
try {
execSync('node_modules/.bin/tsc -p cypress/tsconfig.cypress.json', { cwd, env })
} catch {
// tsc emits files even on type errors (noEmitOnError: false), so this is expected
}
}
/**
* @param {string} cwd
* @returns {void}
*/
function configureCypressTypeScriptCompilation (cwd) {
// Cypress's webpack preprocessor resolves TypeScript config from the spec directory.
// Cypress sets inlineSourceMap itself, so setting sourceMap here breaks Cypress 12.
const tsconfig = {
compilerOptions: {
rootDir: '.',
target: 'ES2020',
module: 'commonjs',
skipLibCheck: true,
},
}
const typescriptVersion = require(path.join(cwd, 'node_modules/typescript/package.json')).version
if (semver.gte(typescriptVersion, '6.0.0')) {
tsconfig.compilerOptions.ignoreDeprecations = '6.0'
}
fs.writeFileSync(path.join(cwd, 'cypress/e2e/tsconfig.json'), JSON.stringify(tsconfig, null, 2))
}
/**
* @param {{ type: string, content: { meta: Record<string, string> } }[]} events
* @param {string} tag
* @returns {void}
*/
function assertRequestErrorTag (events, tag) {
const eventTypes = ['test_session_end', 'test_module_end', 'test_suite_end', 'test']
for (const eventType of eventTypes) {
const event = events.find(event => event.type === eventType)
assert.ok(event, `should have ${eventType} event`)
assert.strictEqual(event.content.meta[tag], 'true', `${eventType} should have ${tag} tag`)
}
}
function shouldTestsRun (type) {
if (DD_MAJOR === 5) {
if (NODE_MAJOR <= 16) {
return version === '6.7.0' && type === 'commonJS'
}
if (NODE_MAJOR > 16) {
// Cypress 15.0.0 has removed support for Node 18
if (NODE_MAJOR <= 18) {
return cypressVersionsSupportingNode18.includes(version)
}
return cypressVersionsSupportingNode18.includes(version) || version === 'latest'
}
}
if (DD_MAJOR >= 6) {
if (NODE_MAJOR <= 16) {
return false
}
if (NODE_MAJOR > 16) {
// Cypress 15.0.0 has removed support for Node 18
if (NODE_MAJOR <= 18) {
return cypressVersionsSupportingNode18.includes(version)
}
return cypressVersionsSupportingNode18.includes(version) || version === 'latest'
}
}
return false
}
const moduleTypes = [
{
type: 'commonJS',
testCommand: function commandWithSuffic (version) {
const commandSuffix = version === '6.7.0' ? '--config-file cypress-config.json --spec "cypress/e2e/*.cy.js"' : ''
return `./node_modules/.bin/cypress run ${commandSuffix}`
},
},
{
type: 'esm',
testCommand: 'node ./cypress-esm-config.mjs',
},
].filter(moduleType => !process.env.CYPRESS_MODULE_TYPE || process.env.CYPRESS_MODULE_TYPE === moduleType.type)
moduleTypes.forEach(({
type,
testCommand,
}) => {
if (typeof testCommand === 'function') {
testCommand = testCommand(version)
}
describe(`cypress@${version} ${type}`, function () {
if (!shouldTestsRun(type)) {
// eslint-disable-next-line no-console
console.log(`Skipping tests for cypress@${version} ${type} for dd-trace@${DD_MAJOR} node@${NODE_MAJOR}`)
return
}
this.timeout(80_000)
let cwd, receiver, childProcess, webAppBaseUrl, webAppServer
const sandboxDependencies = getCypressDependencies(version)
if (type === 'commonJS' && version === 'latest') {
// These dependencies are only needed by the component/Vite regression test below.
sandboxDependencies.push(
'@vitejs/plugin-react@4.3.4',
'react@18.3.1',
'react-dom@18.3.1',
'vite@6.1.0'
)
}
useSandbox(sandboxDependencies, true)
before(async function () {
this.timeout(180_000)
cwd = sandboxCwd()
await warmCypressBinary(cwd)
const webApp = await startWebAppServer()
webAppBaseUrl = webApp.baseUrl
webAppServer = webApp.server
})
beforeEach(async function () {
receiver = await new FakeCiVisIntake().start()
})
afterEach(async () => {
await stopCiVisTestEnv({ childProcess, receiver })
childProcess = undefined
})
after(async () => {
await stopWebAppServer(webAppServer)
})
// These tests require Cypress >=10 features (defineConfig, setupNodeEvents)
const over10It = (version !== '6.7.0') ? it : it.skip
const getCypressRunCommand = specToRun => version === '6.7.0'
? `./node_modules/.bin/cypress run --config-file cypress-config.json --spec "${specToRun}"`
: testCommand
// Regression guard: when OTEL_TRACES_EXPORTER=otlp is set in the
// environment (e.g. by an unrelated OpenTelemetry-instrumented shell),
// the tracer must still ship Test Optimization spans to
// /api/v2/citestcycle instead of silently replacing the Test
// Optimization exporter with OtlpHttpTraceExporter and dropping all
// test_session / test_module / test_suite / test spans.
over10It('keeps Test Optimization exporter when OTEL_TRACES_EXPORTER=otlp is set', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
childProcess = exec(
testCommand,
{
cwd,
env: {
...envVars,
// Simulates a user shell that already exports OTEL_* vars for
// a separate OTEL collector. The Test Optimization exporter
// must win inside isCiVisibility mode.
OTEL_TRACES_EXPORTER: 'otlp',
CYPRESS_BASE_URL: webAppBaseUrl,
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
// TODO: remove this once we have figured out flakiness
childProcess.stdout?.pipe(process.stdout)
childProcess.stderr?.pipe(process.stderr)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const sessionEvents = events.filter(event => event.type === 'test_session_end')
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(sessionEvents.length, 1, 'one test_session span must reach citestcycle')
const passedTest = testEvents.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 20000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
})
over10It('does not modify the user support file and cleans up the injected wrapper', async () => {
const supportFilePath = path.join(cwd, 'cypress/support/e2e.js')
const originalSupportContent = fs.readFileSync(supportFilePath, 'utf8')
const supportContentWithoutDdTrace = originalSupportContent
.split('\n')
.filter(line => !line.includes("require('dd-trace/ci/cypress/support')"))
.join('\n')
const getSupportWrappers = () => fs.readdirSync(path.dirname(supportFilePath))
.filter(filename => filename.startsWith('dd-cypress-support-'))
.sort()
fs.writeFileSync(supportFilePath, supportContentWithoutDdTrace)
const envVars = getCiVisAgentlessConfig(receiver.port)
const wrapperFilesBefore = getSupportWrappers()
try {
childProcess = exec(testCommand, {
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
})
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
const passedTest = events.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
},
{ hardTimeout: 60000 }
)
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
assert.strictEqual(fs.readFileSync(supportFilePath, 'utf8'), supportContentWithoutDdTrace)
assert.doesNotMatch(fs.readFileSync(supportFilePath, 'utf8'), /dd-trace\/ci\/cypress\/support/)
assert.deepStrictEqual(getSupportWrappers(), wrapperFilesBefore)
} finally {
fs.writeFileSync(supportFilePath, originalSupportContent)
}
})
over10It('retries when dd:beforeEach returns no result once', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
let testOutput = ''
childProcess = exec(testCommand, {
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
CYPRESS_DD_BEFORE_EACH_NO_RESULT_ONCE: '1',
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
})
childProcess.stdout?.on('data', (data) => { testOutput += data })
childProcess.stderr?.on('data', (data) => { testOutput += data })
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
const passedTest = events.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
},
{ hardTimeout: 60000 }
)
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
assert.match(testOutput, /\[datadog:test\] dd:beforeEach call 1/)
assert.match(testOutput, /\[datadog:test\] dd:beforeEach call 2/)
})
over10It('preserves config returned from setupNodeEvents', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
const returnConfigFile = type === 'esm'
? 'cypress-return-config.config.mjs'
: 'cypress-return-config.config.js'
childProcess = exec(
`./node_modules/.bin/cypress run --config-file ${returnConfigFile}`,
{
cwd,
env: envVars,
}
)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
const passedTest = events.find(event =>
event.content.resource ===
'cypress/e2e/returned-config.cy.js.returned config uses env from setupNodeEvents return value'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
})
over10It('custom after:spec and after:run handlers are chained with dd-trace instrumentation', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
let testOutput = ''
const customHooksConfigFile = type === 'esm'
? 'cypress-custom-after-hooks.config.mjs'
: 'cypress-custom-after-hooks.config.js'
childProcess = exec(
`./node_modules/.bin/cypress run --config-file ${customHooksConfigFile}`,
{
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
const passedTest = events.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
childProcess.stdout?.on('data', (d) => { testOutput += d })
childProcess.stderr?.on('data', (d) => { testOutput += d })
await Promise.all([
once(childProcess, 'exit'),
once(childProcess.stdout, 'end'),
once(childProcess.stderr, 'end'),
receiverPromise,
])
// Verify both dd-trace spans AND the custom handlers ran (including their async resolutions)
assert.match(testOutput, /\[custom:after:spec\]/)
assert.match(testOutput, /\[custom:after:spec:resolved\]/)
assert.match(testOutput, /\[custom:after:run\]/)
assert.match(testOutput, /\[custom:after:run:resolved\]/)
})
// Tests the old manual API: dd-trace/ci/cypress/after-run and after-spec
// used alongside the manual plugin, without NODE_OPTIONS auto-instrumentation.
over10It('works if after:run and after:spec are explicitly used with the manual plugin', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
childProcess = exec(
testCommand,
{
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
CYPRESS_ENABLE_AFTER_RUN_CUSTOM: '1',
CYPRESS_ENABLE_AFTER_SPEC_CUSTOM: '1',
CYPRESS_ENABLE_MANUAL_PLUGIN: '1',
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
// TODO: remove this once we have figured out flakiness
childProcess.stdout?.pipe(process.stdout)
childProcess.stderr?.pipe(process.stderr)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testSessionEvent = events.find(event => event.type === 'test_session_end')
assert.ok(testSessionEvent)
const testEvents = events.filter(event => event.type === 'test')
assert.ok(testEvents.length > 0, `Expected ${testEvents.length} > 0`)
}, { hardTimeout: 30000 })
await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
})
// Exercises the _isInit=true channel path: NODE_OPTIONS activates auto-instrumentation
// (wrapSetupNodeEvents), the manual plugin sets _isInit=true, and the channel subscriber
// chains the after:spec/after:run handlers intercepted by wrappedOn.
// Differs from the backwards-compat test (APM protocol, single pass) by validating
// the full citestcycle span hierarchy through the channel's _isInit=true branch.
over10It('correctly chains hooks when auto-instrumentation and manual plugin are both active', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
let testOutput = ''
const legacyConfigFile = type === 'esm'
? 'cypress-legacy-plugin.config.mjs'
: 'cypress-legacy-plugin.config.js'
childProcess = exec(
`./node_modules/.bin/cypress run --config-file ${legacyConfigFile}`,
{
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
CYPRESS_ENABLE_AFTER_SPEC_USER: '1',
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
childProcess.stdout?.on('data', (data) => { testOutput += data })
childProcess.stderr?.on('data', (data) => { testOutput += data })
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const sessionEvents = events.filter(event => event.type === 'test_session_end')
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(sessionEvents.length, 1, 'should have one test session')
assert.ok(testEvents.length >= 1, 'should have at least one test')
const passedTest = testEvents.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
once(childProcess.stdout, 'end'),
once(childProcess.stderr, 'end'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
assert.match(testOutput, /\[custom:after:spec:manual\]/)
})
over10It(
'uses one tracer when auto-instrumentation and the manual plugin are different package copies',
async () => {
const externalPackageDir = path.join(cwd, 'external-tracer', 'node_modules', 'dd-trace')
fs.rmSync(path.dirname(path.dirname(externalPackageDir)), { recursive: true, force: true })
fs.mkdirSync(path.dirname(externalPackageDir), { recursive: true })
fs.cpSync(path.join(cwd, 'node_modules', 'dd-trace'), externalPackageDir, { recursive: true })
const legacyConfigFile = type === 'esm'
? 'cypress-legacy-plugin.config.mjs'
: 'cypress-legacy-plugin.config.js'
const envVars = getCiVisAgentlessConfig(receiver.port)
let testOutput = ''
try {
childProcess = exec(
`./node_modules/.bin/cypress run --config-file ${legacyConfigFile}`,
{
cwd,
env: {
...envVars,
NODE_OPTIONS: `-r ${path.join(externalPackageDir, 'ci', 'init')}`,
CYPRESS_BASE_URL: webAppBaseUrl,
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
childProcess.stdout?.on('data', (data) => { testOutput += data })
childProcess.stderr?.on('data', (data) => { testOutput += data })
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
assert.strictEqual(events.filter(event => event.type === 'test_session_end').length, 1)
assert.strictEqual(events.filter(event => event.type === 'test_module_end').length, 1)
assert.strictEqual(events.filter(event => event.type === 'test_suite_end').length, 1)
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(testEvents.length, 1)
assertObjectContains(testEvents[0].content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, `cypress process should exit successfully\n${testOutput}`)
assert.doesNotMatch(testOutput, /Multiple attempts to register the following task/)
} finally {
fs.rmSync(path.dirname(path.dirname(externalPackageDir)), { recursive: true, force: true })
}
}
)
over10It('reports real test statuses when supportFile is false', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
const getSupportWrappers = () => fs.readdirSync(cwd)
.filter(filename => filename.startsWith('dd-cypress-support-'))
.sort()
const supportWrappersBefore = getSupportWrappers()
childProcess = exec(
'./node_modules/.bin/cypress run --config-file cypress-support-file-false.config.js',
{ cwd, env: envVars }
)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const testEvents = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
assert.strictEqual(testEvents.length, 2)
const statuses = Object.fromEntries(testEvents.map(event => [
event.content.resource,
event.content.meta[TEST_STATUS],
]))
assert.deepStrictEqual(statuses, {
'cypress/e2e/support-file-false.cy.js.support file false suite passes without a user support file':
'pass',
'cypress/e2e/support-file-false.cy.js.support file false suite skips without a user support file':
'skip',
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
assert.deepStrictEqual(getSupportWrappers(), supportWrappersBefore)
})
const readOnlyConfigIt = process.platform === 'win32' ? it.skip : over10It
readOnlyConfigIt('auto-instruments a plain-object config in a read-only directory', async () => {
const readOnlyConfigDir = path.join(cwd, 'read-only-config')
const configExtension = type === 'esm' ? '.mjs' : '.js'
const sourceConfig = path.join(cwd, `cypress-plain-object-auto.config${configExtension}`)
const readOnlyConfig = path.join(readOnlyConfigDir, `plain-object${configExtension}`)
fs.rmSync(readOnlyConfigDir, { recursive: true, force: true })
fs.mkdirSync(readOnlyConfigDir)
fs.copyFileSync(sourceConfig, readOnlyConfig)
fs.chmodSync(readOnlyConfigDir, 0o555)
const getConfigWrappers = () => fs.readdirSync(cwd)
.filter(filename => filename.startsWith('.dd-cypress-config-'))
.sort()
const configWrappersBefore = getConfigWrappers()
try {
const envVars = getCiVisAgentlessConfig(receiver.port)
childProcess = exec(
`./node_modules/.bin/cypress run --config-file ${readOnlyConfig}`,
{
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const testEvents = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
const passedTest = testEvents.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
assert.deepStrictEqual(getConfigWrappers(), configWrappersBefore)
} finally {
fs.chmodSync(readOnlyConfigDir, 0o755)
fs.rmSync(readOnlyConfigDir, { recursive: true, force: true })
}
})
const readOnlyTypeScriptConfigIt = process.platform !== 'win32' &&
type === 'commonJS' && version === '14.5.4' && NODE_MAJOR > 18
? it
: it.skip
readOnlyTypeScriptConfigIt(
'auto-instruments a TypeScript config when the writable fallback has a different module scope',
async () => {
const projectRoot = path.join(cwd, 'read-only-typescript-project')
const configDirectory = path.join(projectRoot, 'config')
const configFile = path.join(configDirectory, 'cypress.config.ts')
const specDirectory = path.join(projectRoot, 'cypress', 'e2e')
fs.rmSync(projectRoot, { recursive: true, force: true })
fs.mkdirSync(configDirectory, { recursive: true })
fs.mkdirSync(specDirectory, { recursive: true })
fs.writeFileSync(path.join(projectRoot, 'package.json'), '{ "type": "module" }')
fs.writeFileSync(path.join(configDirectory, 'package.json'), '{ "type": "commonjs" }')
fs.writeFileSync(configFile, [
'module.exports = {',
' e2e: { specPattern: "cypress/e2e/basic-pass.js", supportFile: false },',
' video: false,',
' screenshotOnRunFailure: false,',
'}',
'',
].join('\n'))
fs.copyFileSync(
path.join(cwd, 'cypress', 'e2e', 'basic-pass.js'),
path.join(specDirectory, 'basic-pass.js')
)
fs.chmodSync(configDirectory, 0o555)
const getGeneratedFiles = () => fs.readdirSync(projectRoot)
.filter(file => file.startsWith('.dd-cypress-config-') || file.startsWith('dd-cypress-support-'))
.sort()
const generatedFilesBefore = getGeneratedFiles()
let testOutput = ''
try {
childProcess = exec(
`./node_modules/.bin/cypress run --project ${projectRoot} --config-file ${configFile}`,
{
cwd,
env: {
...getCiVisAgentlessConfig(receiver.port),
CYPRESS_BASE_URL: webAppBaseUrl,
},
}
)
childProcess.stdout?.on('data', (data) => { testOutput += data })
childProcess.stderr?.on('data', (data) => { testOutput += data })
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const testEvents = payloads
.flatMap(({ payload }) => payload.events)
.filter(event => event.type === 'test')
const passedTest = testEvents.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, `cypress process should exit successfully\n${testOutput}`)
assert.deepStrictEqual(getGeneratedFiles(), generatedFilesBefore)
} finally {
fs.chmodSync(configDirectory, 0o755)
fs.rmSync(projectRoot, { recursive: true, force: true })
}
}
)
const componentIt = type === 'commonJS' && version === 'latest' ? it : it.skip
componentIt('auto-instruments component tests with the Vite dev server', async () => {
const envVars = getCiVisAgentlessConfig(receiver.port)
const supportDirectory = path.join(cwd, 'cypress', 'support')
const getSupportWrappers = () => fs.readdirSync(supportDirectory)
.filter(filename => filename.startsWith('dd-cypress-support-'))
.sort()
const supportWrappersBefore = getSupportWrappers()
childProcess = exec(
'./node_modules/.bin/cypress run --component --config-file cypress-component.config.js',
{ cwd, env: envVars }
)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(events.filter(event => event.type === 'test_session_end').length, 1)
assert.strictEqual(events.filter(event => event.type === 'test_module_end').length, 1)
assert.strictEqual(events.filter(event => event.type === 'test_suite_end').length, 1)
assert.strictEqual(testEvents.length, 1)
assertObjectContains(testEvents[0].content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
assert.deepStrictEqual(getSupportWrappers(), supportWrappersBefore)
})
// Exercises the manual plugin path without NODE_OPTIONS when users also register
// custom after:spec and after:run handlers. Without auto-instrumentation, there is
// no wrappedOn to intercept and chain handlers — the manual plugin's on() calls
// replace earlier registrations. This test verifies the system does not crash and
// spans are still correctly reported through the manual plugin's own hooks.
over10It('manual plugin with custom after hooks works without NODE_OPTIONS', async () => {
// Strip NODE_OPTIONS — the manual plugin initializes dd-trace itself.
const { NODE_OPTIONS, ...envVars } = getCiVisEvpProxyConfig(receiver.port)
const legacyConfigFile = type === 'esm'
? 'cypress-legacy-plugin.config.mjs'
: 'cypress-legacy-plugin.config.js'
childProcess = exec(
`./node_modules/.bin/cypress run --config-file ${legacyConfigFile}`,
{
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
CYPRESS_ENABLE_AFTER_RUN_CUSTOM: '1',
CYPRESS_ENABLE_AFTER_SPEC_CUSTOM: '1',
SPEC_PATTERN: 'cypress/e2e/basic-pass.js',
},
}
)
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const sessionEvents = events.filter(event => event.type === 'test_session_end')
const testEvents = events.filter(event => event.type === 'test')
assert.strictEqual(sessionEvents.length, 1, 'should have one test session')
assert.ok(testEvents.length >= 1, 'should have at least one test')
const passedTest = testEvents.find(event =>
event.content.resource === 'cypress/e2e/basic-pass.js.basic pass suite can pass'
)
assertObjectContains(passedTest?.content, {
meta: {
[TEST_STATUS]: 'pass',
[TEST_FRAMEWORK]: 'cypress',
},
})
}, { hardTimeout: 60000 })
const [[exitCode]] = await Promise.all([
once(childProcess, 'exit'),
receiverPromise,
])
assert.strictEqual(exitCode, 0, 'cypress process should exit successfully')
})
over12It('reports source file and line for pre-compiled typescript test files', async function () {
const envVars = getCiVisAgentlessConfig(receiver.port)
try {
cleanupPrecompiledSourceLineDist(cwd)
// Compile the TypeScript spec to JS + source map so the plugin can resolve
// the original TypeScript source file and line via the adjacent .js.map file.
compilePrecompiledTypeScriptSpecs(cwd, envVars)
const specToRun =
'cypress/e2e/dist/{spec-source-line,spec-source-line-fallback,spec-source-line-no-match}.cy.js'
childProcess = exec(testCommand, {
cwd,
env: {
...envVars,
CYPRESS_BASE_URL: webAppBaseUrl,
SPEC_PATTERN: specToRun,
},
})
const receiverPromise = receiver
.gatherPayloadsUntilChildExit(
childProcess,
({ url }) => url.endsWith('/api/v2/citestcycle'),
(payloads) => {
const events = payloads.flatMap(({ payload }) => payload.events)
const testEvents = events.filter(event => event.type === 'test')
const tsTestEvents = testEvents.filter(event =>
event.content.resource.includes('spec-source-line.cy.js.spec source line')
)
assert.strictEqual(tsTestEvents.length, 2, 'should have two typescript test events')
const itTestEvent = tsTestEvents.find(e => e.content.resource.includes('reports correct line number'))
const testTestEvent = tsTestEvents.find(
e => e.content.resource.includes('template interpolated string test name')
)
assert.ok(itTestEvent, 'it() test event should exist')
// 'it' is defined at line 11 in the TypeScript source file spec-source-line.cy.ts
assert.strictEqual(
itTestEvent.content.metrics[TEST_SOURCE_START],
11,
'should report the correct source line for it() test'
)
assert.match(
itTestEvent.content.meta[TEST_SOURCE_FILE],
/spec-source-line\.cy\.ts$/,
`TEST_SOURCE_FILE should point to TypeScript source, got: ${itTestEvent.content.meta[TEST_SOURCE_FILE]}`
)
// 'specify' with a template literal test name is defined at line 16.
// The plugin resolves the TS line by scanning the compiled JS for the template literal
// call (fuzzy-matching ${expr} placeholders) and mapping via the adjacent .js.map.
assert.ok(testTestEvent, 'specify() with template literal name should exist')
assert.strictEqual(
testTestEvent.content.metrics[TEST_SOURCE_START],
16,
'should report the correct source line for specify() with template literal name'
)
assert.match(
testTestEvent.content.meta[TEST_SOURCE_FILE],