dd-trace 6.0.0-pre-0f36e48 → 6.0.0-pre-ca25754

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ci/init.js CHANGED
@@ -3,6 +3,7 @@ const tracer = require('../packages/dd-trace')
3
3
  const { isTrue } = require('../packages/dd-trace/src/util')
4
4
 
5
5
  const isJestWorker = !!process.env.JEST_WORKER_ID
6
+ const isCucumberWorker = !!process.env.CUCUMBER_WORKER_ID
6
7
 
7
8
  const options = {
8
9
  startupLogs: false,
@@ -37,6 +38,12 @@ if (isJestWorker) {
37
38
  }
38
39
  }
39
40
 
41
+ if (isCucumberWorker) {
42
+ options.experimental = {
43
+ exporter: 'cucumber_worker'
44
+ }
45
+ }
46
+
40
47
  if (shouldInit) {
41
48
  tracer.init(options)
42
49
  tracer.use('fs', false)
@@ -3,7 +3,8 @@ declare const exporters: {
3
3
  AGENT: 'agent',
4
4
  DATADOG: 'datadog',
5
5
  AGENT_PROXY: 'agent_proxy',
6
- JEST_WORKER: 'jest_worker'
6
+ JEST_WORKER: 'jest_worker',
7
+ CUCUMBER_WORKER: 'cucumber_worker'
7
8
  }
8
9
 
9
10
  export = exporters
package/ext/exporters.js CHANGED
@@ -4,5 +4,6 @@ module.exports = {
4
4
  AGENT: 'agent',
5
5
  DATADOG: 'datadog',
6
6
  AGENT_PROXY: 'agent_proxy',
7
- JEST_WORKER: 'jest_worker'
7
+ JEST_WORKER: 'jest_worker',
8
+ CUCUMBER_WORKER: 'cucumber_worker'
8
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dd-trace",
3
- "version": "6.0.0-pre-0f36e48",
3
+ "version": "6.0.0-pre-ca25754",
4
4
  "description": "Datadog APM tracing client for JavaScript",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
@@ -162,8 +162,11 @@ function getChannelSuffix (name) {
162
162
  'lambda',
163
163
  'redshift',
164
164
  's3',
165
+ 'sfn',
165
166
  'sns',
166
- 'sqs'
167
+ 'sqs',
168
+ 'states',
169
+ 'stepfunctions'
167
170
  ].includes(name)
168
171
  ? name
169
172
  : 'default'
@@ -22,6 +22,8 @@ const skippableSuitesCh = channel('ci:cucumber:test-suite:skippable')
22
22
  const sessionStartCh = channel('ci:cucumber:session:start')
23
23
  const sessionFinishCh = channel('ci:cucumber:session:finish')
24
24
 
25
+ const workerReportTraceCh = channel('ci:cucumber:worker-report:trace')
26
+
25
27
  const itrSkippedSuitesCh = channel('ci:cucumber:itr:skipped-suites')
26
28
 
27
29
  const {
@@ -29,7 +31,8 @@ const {
29
31
  resetCoverage,
30
32
  mergeCoverage,
31
33
  fromCoverageMapToCoverage,
32
- getTestSuitePath
34
+ getTestSuitePath,
35
+ CUCUMBER_WORKER_TRACE_PAYLOAD_CODE
33
36
  } = require('../../dd-trace/src/plugins/util/test')
34
37
 
35
38
  const isMarkedAsUnskippable = (pickle) => {
@@ -47,13 +50,19 @@ const numRetriesByPickleId = new Map()
47
50
 
48
51
  let pickleByFile = {}
49
52
  const pickleResultByFile = {}
53
+
54
+ const sessionAsyncResource = new AsyncResource('bound-anonymous-fn')
55
+
50
56
  let skippableSuites = []
51
57
  let itrCorrelationId = ''
52
58
  let isForcedToRun = false
53
59
  let isUnskippable = false
60
+ let isSuitesSkippingEnabled = false
54
61
  let isEarlyFlakeDetectionEnabled = false
55
62
  let earlyFlakeDetectionNumRetries = 0
56
63
  let knownTests = []
64
+ let skippedSuites = []
65
+ let isSuitesSkipped = false
57
66
 
58
67
  function getSuiteStatusFromTestStatuses (testStatuses) {
59
68
  if (testStatuses.some(status => status === 'fail')) {
@@ -106,6 +115,43 @@ function getTestStatusFromRetries (testStatuses) {
106
115
  return 'pass'
107
116
  }
108
117
 
118
+ function getChannelPromise (channelToPublishTo) {
119
+ return new Promise(resolve => {
120
+ sessionAsyncResource.runInAsyncScope(() => {
121
+ channelToPublishTo.publish({ onDone: resolve })
122
+ })
123
+ })
124
+ }
125
+
126
+ function getFilteredPickles (runtime, suitesToSkip) {
127
+ return runtime.pickleIds.reduce((acc, pickleId) => {
128
+ const test = runtime.eventDataCollector.getPickle(pickleId)
129
+ const testSuitePath = getTestSuitePath(test.uri, process.cwd())
130
+
131
+ const isUnskippable = isMarkedAsUnskippable(test)
132
+ const isSkipped = suitesToSkip.includes(testSuitePath)
133
+
134
+ if (isSkipped && !isUnskippable) {
135
+ acc.skippedSuites.add(testSuitePath)
136
+ } else {
137
+ acc.picklesToRun.push(pickleId)
138
+ }
139
+ return acc
140
+ }, { skippedSuites: new Set(), picklesToRun: [] })
141
+ }
142
+
143
+ function getPickleByFile (runtime) {
144
+ return runtime.pickleIds.reduce((acc, pickleId) => {
145
+ const test = runtime.eventDataCollector.getPickle(pickleId)
146
+ if (acc[test.uri]) {
147
+ acc[test.uri].push(test)
148
+ } else {
149
+ acc[test.uri] = [test]
150
+ }
151
+ return acc
152
+ }, {})
153
+ }
154
+
109
155
  function wrapRun (pl, isLatestVersion) {
110
156
  if (patched.has(pl)) return
111
157
 
@@ -125,7 +171,8 @@ function wrapRun (pl, isLatestVersion) {
125
171
  testStartCh.publish({
126
172
  testName: this.pickle.name,
127
173
  testFileAbsolutePath,
128
- testSourceLine
174
+ testSourceLine,
175
+ isParallel: !!process.env.CUCUMBER_WORKER_ID
129
176
  })
130
177
  try {
131
178
  const promise = run.apply(this, arguments)
@@ -193,12 +240,6 @@ function wrapRun (pl, isLatestVersion) {
193
240
  }
194
241
 
195
242
  function pickleHook (PickleRunner) {
196
- if (process.env.CUCUMBER_WORKER_ID) {
197
- // Parallel mode is not supported
198
- log.warn('Unable to initialize CI Visibility because Cucumber is running in parallel mode.')
199
- return PickleRunner
200
- }
201
-
202
243
  const pl = PickleRunner.default
203
244
 
204
245
  wrapRun(pl, false)
@@ -207,12 +248,6 @@ function pickleHook (PickleRunner) {
207
248
  }
208
249
 
209
250
  function testCaseHook (TestCaseRunner) {
210
- if (process.env.CUCUMBER_WORKER_ID) {
211
- // Parallel mode is not supported
212
- log.warn('Unable to initialize CI Visibility because Cucumber is running in parallel mode.')
213
- return TestCaseRunner
214
- }
215
-
216
251
  const pl = TestCaseRunner.default
217
252
 
218
253
  wrapRun(pl, true)
@@ -220,76 +255,21 @@ function testCaseHook (TestCaseRunner) {
220
255
  return TestCaseRunner
221
256
  }
222
257
 
223
- addHook({
224
- name: '@cucumber/cucumber',
225
- versions: ['7.0.0 - 7.2.1'],
226
- file: 'lib/runtime/pickle_runner.js'
227
- }, pickleHook)
228
-
229
- addHook({
230
- name: '@cucumber/cucumber',
231
- versions: ['>=7.3.0'],
232
- file: 'lib/runtime/test_case_runner.js'
233
- }, testCaseHook)
234
-
235
- function getFilteredPickles (runtime, suitesToSkip) {
236
- return runtime.pickleIds.reduce((acc, pickleId) => {
237
- const test = runtime.eventDataCollector.getPickle(pickleId)
238
- const testSuitePath = getTestSuitePath(test.uri, process.cwd())
239
-
240
- const isUnskippable = isMarkedAsUnskippable(test)
241
- const isSkipped = suitesToSkip.includes(testSuitePath)
242
-
243
- if (isSkipped && !isUnskippable) {
244
- acc.skippedSuites.add(testSuitePath)
245
- } else {
246
- acc.picklesToRun.push(pickleId)
247
- }
248
- return acc
249
- }, { skippedSuites: new Set(), picklesToRun: [] })
250
- }
251
-
252
- function getPickleByFile (runtime) {
253
- return runtime.pickleIds.reduce((acc, pickleId) => {
254
- const test = runtime.eventDataCollector.getPickle(pickleId)
255
- if (acc[test.uri]) {
256
- acc[test.uri].push(test)
257
- } else {
258
- acc[test.uri] = [test]
259
- }
260
- return acc
261
- }, {})
262
- }
263
-
264
- function getWrappedStart (start, frameworkVersion) {
258
+ function getWrappedStart (start, frameworkVersion, isParallel = false) {
265
259
  return async function () {
266
260
  if (!libraryConfigurationCh.hasSubscribers) {
267
261
  return start.apply(this, arguments)
268
262
  }
269
- const asyncResource = new AsyncResource('bound-anonymous-fn')
270
- let onDone
271
-
272
- const configPromise = new Promise(resolve => {
273
- onDone = resolve
274
- })
275
-
276
- asyncResource.runInAsyncScope(() => {
277
- libraryConfigurationCh.publish({ onDone })
278
- })
263
+ let errorSkippableRequest
279
264
 
280
- const configurationResponse = await configPromise
265
+ const configurationResponse = await getChannelPromise(libraryConfigurationCh)
281
266
 
282
267
  isEarlyFlakeDetectionEnabled = configurationResponse.libraryConfig?.isEarlyFlakeDetectionEnabled
283
268
  earlyFlakeDetectionNumRetries = configurationResponse.libraryConfig?.earlyFlakeDetectionNumRetries
269
+ isSuitesSkippingEnabled = configurationResponse.libraryConfig?.isSuitesSkippingEnabled
284
270
 
285
271
  if (isEarlyFlakeDetectionEnabled) {
286
- const knownTestsPromise = new Promise(resolve => {
287
- onDone = resolve
288
- })
289
- asyncResource.runInAsyncScope(() => {
290
- knownTestsCh.publish({ onDone })
291
- })
292
- const knownTestsResponse = await knownTestsPromise
272
+ const knownTestsResponse = await getChannelPromise(knownTestsCh)
293
273
  if (!knownTestsResponse.err) {
294
274
  knownTests = knownTestsResponse.knownTests
295
275
  } else {
@@ -297,35 +277,26 @@ function getWrappedStart (start, frameworkVersion) {
297
277
  }
298
278
  }
299
279
 
300
- const skippableSuitesPromise = new Promise(resolve => {
301
- onDone = resolve
302
- })
280
+ if (isSuitesSkippingEnabled) {
281
+ const skippableResponse = await getChannelPromise(skippableSuitesCh)
303
282
 
304
- asyncResource.runInAsyncScope(() => {
305
- skippableSuitesCh.publish({ onDone })
306
- })
283
+ errorSkippableRequest = skippableResponse.err
284
+ skippableSuites = skippableResponse.skippableSuites
307
285
 
308
- const skippableResponse = await skippableSuitesPromise
286
+ if (!errorSkippableRequest) {
287
+ const filteredPickles = getFilteredPickles(this, skippableSuites)
288
+ const { picklesToRun } = filteredPickles
289
+ isSuitesSkipped = picklesToRun.length !== this.pickleIds.length
309
290
 
310
- const err = skippableResponse.err
311
- skippableSuites = skippableResponse.skippableSuites
291
+ log.debug(
292
+ () => `${picklesToRun.length} out of ${this.pickleIds.length} suites are going to run.`
293
+ )
312
294
 
313
- let skippedSuites = []
314
- let isSuitesSkipped = false
295
+ this.pickleIds = picklesToRun
315
296
 
316
- if (!err) {
317
- const filteredPickles = getFilteredPickles(this, skippableSuites)
318
- const { picklesToRun } = filteredPickles
319
- isSuitesSkipped = picklesToRun.length !== this.pickleIds.length
320
-
321
- log.debug(
322
- () => `${picklesToRun.length} out of ${this.pickleIds.length} suites are going to run.`
323
- )
324
-
325
- this.pickleIds = picklesToRun
326
-
327
- skippedSuites = Array.from(filteredPickles.skippedSuites)
328
- itrCorrelationId = skippableResponse.itrCorrelationId
297
+ skippedSuites = Array.from(filteredPickles.skippedSuites)
298
+ itrCorrelationId = skippableResponse.itrCorrelationId
299
+ }
329
300
  }
330
301
 
331
302
  pickleByFile = getPickleByFile(this)
@@ -333,11 +304,11 @@ function getWrappedStart (start, frameworkVersion) {
333
304
  const processArgv = process.argv.slice(2).join(' ')
334
305
  const command = process.env.npm_lifecycle_script || `cucumber-js ${processArgv}`
335
306
 
336
- asyncResource.runInAsyncScope(() => {
307
+ sessionAsyncResource.runInAsyncScope(() => {
337
308
  sessionStartCh.publish({ command, frameworkVersion })
338
309
  })
339
310
 
340
- if (!err && skippedSuites.length) {
311
+ if (!errorSkippableRequest && skippedSuites.length) {
341
312
  itrSkippedSuitesCh.publish({ skippedSuites, frameworkVersion })
342
313
  }
343
314
 
@@ -355,7 +326,7 @@ function getWrappedStart (start, frameworkVersion) {
355
326
  global.__coverage__ = fromCoverageMapToCoverage(originalCoverageMap)
356
327
  }
357
328
 
358
- asyncResource.runInAsyncScope(() => {
329
+ sessionAsyncResource.runInAsyncScope(() => {
359
330
  sessionFinishCh.publish({
360
331
  status: success ? 'pass' : 'fail',
361
332
  isSuitesSkipped,
@@ -363,7 +334,8 @@ function getWrappedStart (start, frameworkVersion) {
363
334
  numSkippedSuites: skippedSuites.length,
364
335
  hasUnskippableSuites: isUnskippable,
365
336
  hasForcedToRunSuites: isForcedToRun,
366
- isEarlyFlakeDetectionEnabled
337
+ isEarlyFlakeDetectionEnabled,
338
+ isParallel
367
339
  })
368
340
  })
369
341
  return success
@@ -432,7 +404,8 @@ function getWrappedRunTest (runTestFunction) {
432
404
 
433
405
  testSuiteCodeCoverageCh.publish({
434
406
  coverageFiles,
435
- suiteFile: testFileAbsolutePath
407
+ suiteFile: testFileAbsolutePath,
408
+ testSuitePath
436
409
  })
437
410
  // We need to reset coverage to get a code coverage per suite
438
411
  // Before that, we preserve the original coverage
@@ -440,14 +413,97 @@ function getWrappedRunTest (runTestFunction) {
440
413
  resetCoverage(global.__coverage__)
441
414
  }
442
415
 
443
- testSuiteFinishCh.publish(testSuiteStatus)
416
+ testSuiteFinishCh.publish({ status: testSuiteStatus, testSuitePath })
444
417
  }
445
418
 
446
419
  return runTestCaseResult
447
420
  }
448
421
  }
449
422
 
450
- // From 7.3.0 onwards, runPickle becomes runTestCase
423
+ function getWrappedParseWorkerMessage (parseWorkerMessageFunction) {
424
+ return function (worker, message) {
425
+ // If the message is an array, it's a dd-trace message, so we need to stop cucumber processing,
426
+ // or cucumber will throw an error
427
+ // TODO: identify the message better
428
+ if (Array.isArray(message)) {
429
+ const [messageCode, payload] = message
430
+ if (messageCode === CUCUMBER_WORKER_TRACE_PAYLOAD_CODE) {
431
+ sessionAsyncResource.runInAsyncScope(() => {
432
+ workerReportTraceCh.publish(payload)
433
+ })
434
+ return
435
+ }
436
+ }
437
+
438
+ const { jsonEnvelope } = message
439
+ if (!jsonEnvelope) {
440
+ return parseWorkerMessageFunction.apply(this, arguments)
441
+ }
442
+ let parsed = jsonEnvelope
443
+
444
+ if (typeof parsed === 'string') {
445
+ try {
446
+ parsed = JSON.parse(jsonEnvelope)
447
+ } catch (e) {
448
+ // ignore errors and continue
449
+ return parseWorkerMessageFunction.apply(this, arguments)
450
+ }
451
+ }
452
+ if (parsed.testCaseStarted) {
453
+ const { pickleId } = this.eventDataCollector.testCaseMap[parsed.testCaseStarted.testCaseId]
454
+ const pickle = this.eventDataCollector.getPickle(pickleId)
455
+ const testFileAbsolutePath = pickle.uri
456
+ // First test in suite
457
+ if (!pickleResultByFile[testFileAbsolutePath]) {
458
+ pickleResultByFile[testFileAbsolutePath] = []
459
+ testSuiteStartCh.publish({
460
+ testSuitePath: getTestSuitePath(testFileAbsolutePath, process.cwd())
461
+ })
462
+ }
463
+ }
464
+
465
+ const parseWorkerResponse = parseWorkerMessageFunction.apply(this, arguments)
466
+
467
+ // after calling `parseWorkerMessageFunction`, the test status can already be read
468
+ if (parsed.testCaseFinished) {
469
+ const { pickle, worstTestStepResult } =
470
+ this.eventDataCollector.getTestCaseAttempt(parsed.testCaseFinished.testCaseStartedId)
471
+
472
+ const { status } = getStatusFromResultLatest(worstTestStepResult)
473
+
474
+ const testFileAbsolutePath = pickle.uri
475
+ const finished = pickleResultByFile[testFileAbsolutePath]
476
+ finished.push(status)
477
+
478
+ if (finished.length === pickleByFile[testFileAbsolutePath].length) {
479
+ testSuiteFinishCh.publish({
480
+ status: getSuiteStatusFromTestStatuses(finished),
481
+ testSuitePath: getTestSuitePath(testFileAbsolutePath, process.cwd())
482
+ })
483
+ }
484
+ }
485
+
486
+ return parseWorkerResponse
487
+ }
488
+ }
489
+
490
+ // Test start / finish for older versions. The only hook executed in workers when in parallel mode
491
+ addHook({
492
+ name: '@cucumber/cucumber',
493
+ versions: ['7.0.0 - 7.2.1'],
494
+ file: 'lib/runtime/pickle_runner.js'
495
+ }, pickleHook)
496
+
497
+ // Test start / finish for newer versions. The only hook executed in workers when in parallel mode
498
+ addHook({
499
+ name: '@cucumber/cucumber',
500
+ versions: ['>=7.3.0'],
501
+ file: 'lib/runtime/test_case_runner.js'
502
+ }, testCaseHook)
503
+
504
+ // From 7.3.0 onwards, runPickle becomes runTestCase. Not executed in parallel mode.
505
+ // `getWrappedStart` generates session start and finish events
506
+ // `getWrappedRunTest` generates suite start and finish events
451
507
  addHook({
452
508
  name: '@cucumber/cucumber',
453
509
  versions: ['>=7.3.0'],
@@ -459,6 +515,9 @@ addHook({
459
515
  return runtimePackage
460
516
  })
461
517
 
518
+ // Not executed in parallel mode.
519
+ // `getWrappedStart` generates session start and finish events
520
+ // `getWrappedRunTest` generates suite start and finish events
462
521
  addHook({
463
522
  name: '@cucumber/cucumber',
464
523
  versions: ['>=7.0.0 <7.3.0'],
@@ -469,3 +528,21 @@ addHook({
469
528
 
470
529
  return runtimePackage
471
530
  })
531
+
532
+ // Only executed in parallel mode.
533
+ // `getWrappedStart` generates session start and finish events
534
+ // `getWrappedGiveWork` generates suite start events and sets pickleResultByFile (used by suite finish events)
535
+ // `getWrappedParseWorkerMessage` generates suite finish events
536
+ addHook({
537
+ name: '@cucumber/cucumber',
538
+ versions: ['>=8.0.0'],
539
+ file: 'lib/runtime/parallel/coordinator.js'
540
+ }, (coordinatorPackage, frameworkVersion) => {
541
+ shimmer.wrap(coordinatorPackage.default.prototype, 'start', start => getWrappedStart(start, frameworkVersion, true))
542
+ shimmer.wrap(
543
+ coordinatorPackage.default.prototype,
544
+ 'parseWorkerMessage',
545
+ parseWorkerMessage => getWrappedParseWorkerMessage(parseWorkerMessage)
546
+ )
547
+ return coordinatorPackage
548
+ })
@@ -7,6 +7,9 @@ exports.kinesis = require('./kinesis')
7
7
  exports.lambda = require('./lambda')
8
8
  exports.redshift = require('./redshift')
9
9
  exports.s3 = require('./s3')
10
+ exports.sfn = require('./sfn')
10
11
  exports.sns = require('./sns')
11
12
  exports.sqs = require('./sqs')
13
+ exports.states = require('./states')
14
+ exports.stepfunctions = require('./stepfunctions')
12
15
  exports.default = require('./default')
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ const Stepfunctions = require('./stepfunctions')
3
+ class Sfn extends Stepfunctions {
4
+ static get id () { return 'sfn' }
5
+ }
6
+
7
+ module.exports = Sfn
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ const Stepfunctions = require('./stepfunctions')
3
+ class States extends Stepfunctions {
4
+ static get id () { return 'states' }
5
+ }
6
+
7
+ module.exports = States
@@ -0,0 +1,64 @@
1
+ 'use strict'
2
+ const log = require('../../../dd-trace/src/log')
3
+ const BaseAwsSdkPlugin = require('../base')
4
+
5
+ class Stepfunctions extends BaseAwsSdkPlugin {
6
+ static get id () { return 'stepfunctions' }
7
+
8
+ // This is the shape of StartExecutionInput, as defined in
9
+ // https://github.com/aws/aws-sdk-js/blob/master/apis/states-2016-11-23.normal.json
10
+ // "StartExecutionInput": {
11
+ // "type": "structure",
12
+ // "required": [
13
+ // "stateMachineArn"
14
+ // ],
15
+ // "members": {
16
+ // "stateMachineArn": {
17
+ // "shape": "Arn",
18
+ // },
19
+ // "name": {
20
+ // "shape": "Name",
21
+ // },
22
+ // "input": {
23
+ // "shape": "SensitiveData",
24
+ // },
25
+ // "traceHeader": {
26
+ // "shape": "TraceHeader",
27
+ // }
28
+ // }
29
+
30
+ generateTags (params, operation, response) {
31
+ if (!params) return {}
32
+ const tags = { 'resource.name': params.name ? `${operation} ${params.name}` : `${operation}` }
33
+ if (operation === 'startExecution' || operation === 'startSyncExecution') {
34
+ tags.statemachinearn = `${params.stateMachineArn}`
35
+ }
36
+ return tags
37
+ }
38
+
39
+ requestInject (span, request) {
40
+ const operation = request.operation
41
+ if (operation === 'startExecution' || operation === 'startSyncExecution') {
42
+ if (!request.params || !request.params.input) {
43
+ return
44
+ }
45
+
46
+ const input = request.params.input
47
+
48
+ try {
49
+ const inputObj = JSON.parse(input)
50
+ if (inputObj && typeof inputObj === 'object') {
51
+ // We've parsed the input JSON string
52
+ inputObj._datadog = {}
53
+ this.tracer.inject(span, 'text_map', inputObj._datadog)
54
+ const newInput = JSON.stringify(inputObj)
55
+ request.params.input = newInput
56
+ }
57
+ } catch (e) {
58
+ log.info('Unable to treat input as JSON')
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ module.exports = Stepfunctions
@@ -18,7 +18,14 @@ const {
18
18
  TEST_SOURCE_FILE,
19
19
  TEST_EARLY_FLAKE_ENABLED,
20
20
  TEST_IS_NEW,
21
- TEST_IS_RETRY
21
+ TEST_IS_RETRY,
22
+ TEST_SUITE_ID,
23
+ TEST_SESSION_ID,
24
+ TEST_COMMAND,
25
+ TEST_MODULE,
26
+ TEST_MODULE_ID,
27
+ TEST_SUITE,
28
+ CUCUMBER_IS_PARALLEL
22
29
  } = require('../../dd-trace/src/plugins/util/test')
23
30
  const { RESOURCE_NAME } = require('../../../ext/tags')
24
31
  const { COMPONENT, ERROR_MESSAGE } = require('../../dd-trace/src/constants')
@@ -32,6 +39,22 @@ const {
32
39
  TELEMETRY_ITR_UNSKIPPABLE,
33
40
  TELEMETRY_CODE_COVERAGE_NUM_FILES
34
41
  } = require('../../dd-trace/src/ci-visibility/telemetry')
42
+ const id = require('../../dd-trace/src/id')
43
+
44
+ const isCucumberWorker = !!process.env.CUCUMBER_WORKER_ID
45
+
46
+ function getTestSuiteTags (testSuiteSpan) {
47
+ const suiteTags = {
48
+ [TEST_SUITE_ID]: testSuiteSpan.context().toSpanId(),
49
+ [TEST_SESSION_ID]: testSuiteSpan.context().toTraceId(),
50
+ [TEST_COMMAND]: testSuiteSpan.context()._tags[TEST_COMMAND],
51
+ [TEST_MODULE]: 'cucumber'
52
+ }
53
+ if (testSuiteSpan.context()._parentId) {
54
+ suiteTags[TEST_MODULE_ID] = testSuiteSpan.context()._parentId.toString(10)
55
+ }
56
+ return suiteTags
57
+ }
35
58
 
36
59
  class CucumberPlugin extends CiPlugin {
37
60
  static get id () {
@@ -43,6 +66,8 @@ class CucumberPlugin extends CiPlugin {
43
66
 
44
67
  this.sourceRoot = process.cwd()
45
68
 
69
+ this.testSuiteSpanByPath = {}
70
+
46
71
  this.addSub('ci:cucumber:session:finish', ({
47
72
  status,
48
73
  isSuitesSkipped,
@@ -50,7 +75,8 @@ class CucumberPlugin extends CiPlugin {
50
75
  testCodeCoverageLinesTotal,
51
76
  hasUnskippableSuites,
52
77
  hasForcedToRunSuites,
53
- isEarlyFlakeDetectionEnabled
78
+ isEarlyFlakeDetectionEnabled,
79
+ isParallel
54
80
  }) => {
55
81
  const { isSuitesSkippingEnabled, isCodeCoverageEnabled } = this.libraryConfig || {}
56
82
  addIntelligentTestRunnerSpanTags(
@@ -70,6 +96,9 @@ class CucumberPlugin extends CiPlugin {
70
96
  if (isEarlyFlakeDetectionEnabled) {
71
97
  this.testSessionSpan.setTag(TEST_EARLY_FLAKE_ENABLED, 'true')
72
98
  }
99
+ if (isParallel) {
100
+ this.testSessionSpan.setTag(CUCUMBER_IS_PARALLEL, 'true')
101
+ }
73
102
 
74
103
  this.testSessionSpan.setTag(TEST_STATUS, status)
75
104
  this.testModuleSpan.setTag(TEST_STATUS, status)
@@ -101,7 +130,7 @@ class CucumberPlugin extends CiPlugin {
101
130
  if (itrCorrelationId) {
102
131
  testSuiteMetadata[ITR_CORRELATION_ID] = itrCorrelationId
103
132
  }
104
- this.testSuiteSpan = this.tracer.startSpan('cucumber.test_suite', {
133
+ const testSuiteSpan = this.tracer.startSpan('cucumber.test_suite', {
105
134
  childOf: this.testModuleSpan,
106
135
  tags: {
107
136
  [COMPONENT]: this.constructor.id,
@@ -109,25 +138,29 @@ class CucumberPlugin extends CiPlugin {
109
138
  ...testSuiteMetadata
110
139
  }
111
140
  })
141
+ this.testSuiteSpanByPath[testSuitePath] = testSuiteSpan
142
+
112
143
  this.telemetry.ciVisEvent(TELEMETRY_EVENT_CREATED, 'suite')
113
144
  if (this.libraryConfig?.isCodeCoverageEnabled) {
114
145
  this.telemetry.ciVisEvent(TELEMETRY_CODE_COVERAGE_STARTED, 'suite', { library: 'istanbul' })
115
146
  }
116
147
  })
117
148
 
118
- this.addSub('ci:cucumber:test-suite:finish', status => {
119
- this.testSuiteSpan.setTag(TEST_STATUS, status)
120
- this.testSuiteSpan.finish()
149
+ this.addSub('ci:cucumber:test-suite:finish', ({ status, testSuitePath }) => {
150
+ const testSuiteSpan = this.testSuiteSpanByPath[testSuitePath]
151
+ testSuiteSpan.setTag(TEST_STATUS, status)
152
+ testSuiteSpan.finish()
121
153
  this.telemetry.ciVisEvent(TELEMETRY_EVENT_FINISHED, 'suite')
122
154
  })
123
155
 
124
- this.addSub('ci:cucumber:test-suite:code-coverage', ({ coverageFiles, suiteFile }) => {
156
+ this.addSub('ci:cucumber:test-suite:code-coverage', ({ coverageFiles, suiteFile, testSuitePath }) => {
125
157
  if (!this.libraryConfig?.isCodeCoverageEnabled) {
126
158
  return
127
159
  }
128
160
  if (!coverageFiles.length) {
129
161
  this.telemetry.count(TELEMETRY_CODE_COVERAGE_EMPTY)
130
162
  }
163
+ const testSuiteSpan = this.testSuiteSpanByPath[testSuitePath]
131
164
 
132
165
  const relativeCoverageFiles = [...coverageFiles, suiteFile]
133
166
  .map(filename => getTestSuitePath(filename, this.repositoryRoot))
@@ -135,8 +168,8 @@ class CucumberPlugin extends CiPlugin {
135
168
  this.telemetry.distribution(TELEMETRY_CODE_COVERAGE_NUM_FILES, {}, relativeCoverageFiles.length)
136
169
 
137
170
  const formattedCoverage = {
138
- sessionId: this.testSuiteSpan.context()._traceId,
139
- suiteId: this.testSuiteSpan.context()._spanId,
171
+ sessionId: testSuiteSpan.context()._traceId,
172
+ suiteId: testSuiteSpan.context()._spanId,
140
173
  files: relativeCoverageFiles
141
174
  }
142
175
 
@@ -144,7 +177,7 @@ class CucumberPlugin extends CiPlugin {
144
177
  this.telemetry.ciVisEvent(TELEMETRY_CODE_COVERAGE_FINISHED, 'suite', { library: 'istanbul' })
145
178
  })
146
179
 
147
- this.addSub('ci:cucumber:test:start', ({ testName, testFileAbsolutePath, testSourceLine }) => {
180
+ this.addSub('ci:cucumber:test:start', ({ testName, testFileAbsolutePath, testSourceLine, isParallel }) => {
148
181
  const store = storage.getStore()
149
182
  const testSuite = getTestSuitePath(testFileAbsolutePath, this.sourceRoot)
150
183
  const testSourceFile = getTestSuitePath(testFileAbsolutePath, this.repositoryRoot)
@@ -153,6 +186,10 @@ class CucumberPlugin extends CiPlugin {
153
186
  [TEST_SOURCE_START]: testSourceLine,
154
187
  [TEST_SOURCE_FILE]: testSourceFile
155
188
  }
189
+ if (isParallel) {
190
+ extraTags[CUCUMBER_IS_PARALLEL] = 'true'
191
+ }
192
+
156
193
  const testSpan = this.startTestSpan(testName, testSuite, extraTags)
157
194
 
158
195
  this.enter(testSpan, store)
@@ -172,6 +209,36 @@ class CucumberPlugin extends CiPlugin {
172
209
  this.enter(span, store)
173
210
  })
174
211
 
212
+ this.addSub('ci:cucumber:worker-report:trace', (traces) => {
213
+ const formattedTraces = JSON.parse(traces).map(trace =>
214
+ trace.map(span => ({
215
+ ...span,
216
+ span_id: id(span.span_id),
217
+ trace_id: id(span.trace_id),
218
+ parent_id: id(span.parent_id)
219
+ }))
220
+ )
221
+
222
+ // We have to update the test session, test module and test suite ids
223
+ // before we export them in the main process
224
+ formattedTraces.forEach(trace => {
225
+ trace.forEach(span => {
226
+ if (span.name === 'cucumber.test') {
227
+ const testSuite = span.meta[TEST_SUITE]
228
+ const testSuiteSpan = this.testSuiteSpanByPath[testSuite]
229
+
230
+ const testSuiteTags = getTestSuiteTags(testSuiteSpan)
231
+ span.meta = {
232
+ ...span.meta,
233
+ ...testSuiteTags
234
+ }
235
+ }
236
+ })
237
+
238
+ this.tracer._exporter.export(trace)
239
+ })
240
+ })
241
+
175
242
  this.addSub('ci:cucumber:test:finish', ({ isStep, status, skipReason, errorMessage, isNew, isEfdRetry }) => {
176
243
  const span = storage.getStore().span
177
244
  const statusTag = isStep ? 'step.status' : TEST_STATUS
@@ -201,6 +268,10 @@ class CucumberPlugin extends CiPlugin {
201
268
  { hasCodeOwners: !!span.context()._tags[TEST_CODE_OWNERS] }
202
269
  )
203
270
  finishAllTraceSpans(span)
271
+ // If it's a worker, flushing is cheap, as it's just sending data to the main process
272
+ if (isCucumberWorker) {
273
+ this.tracer._exporter.flush()
274
+ }
204
275
  }
205
276
  })
206
277
 
@@ -213,10 +284,11 @@ class CucumberPlugin extends CiPlugin {
213
284
  }
214
285
 
215
286
  startTestSpan (testName, testSuite, extraTags) {
287
+ const testSuiteSpan = this.testSuiteSpanByPath[testSuite]
216
288
  return super.startTestSpan(
217
289
  testName,
218
290
  testSuite,
219
- this.testSuiteSpan,
291
+ testSuiteSpan,
220
292
  extraTags
221
293
  )
222
294
  }
@@ -0,0 +1,56 @@
1
+ 'use strict'
2
+
3
+ const Writer = require('./writer')
4
+ const {
5
+ JEST_WORKER_COVERAGE_PAYLOAD_CODE,
6
+ JEST_WORKER_TRACE_PAYLOAD_CODE,
7
+ CUCUMBER_WORKER_TRACE_PAYLOAD_CODE
8
+ } = require('../../../plugins/util/test')
9
+
10
+ function getInterprocessTraceCode () {
11
+ if (process.env.JEST_WORKER_ID) {
12
+ return JEST_WORKER_TRACE_PAYLOAD_CODE
13
+ }
14
+ if (process.env.CUCUMBER_WORKER_ID) {
15
+ return CUCUMBER_WORKER_TRACE_PAYLOAD_CODE
16
+ }
17
+ return null
18
+ }
19
+
20
+ // TODO: make it available with cucumber
21
+ function getInterprocessCoverageCode () {
22
+ if (process.env.JEST_WORKER_ID) {
23
+ return JEST_WORKER_COVERAGE_PAYLOAD_CODE
24
+ }
25
+ return null
26
+ }
27
+
28
+ /**
29
+ * Lightweight exporter whose writers only do simple JSON serialization
30
+ * of trace and coverage payloads, which they send to the test framework's main process.
31
+ * Currently used by Jest and Cucumber workers.
32
+ */
33
+ class TestWorkerCiVisibilityExporter {
34
+ constructor () {
35
+ const interprocessTraceCode = getInterprocessTraceCode()
36
+ const interprocessCoverageCode = getInterprocessCoverageCode()
37
+
38
+ this._writer = new Writer(interprocessTraceCode)
39
+ this._coverageWriter = new Writer(interprocessCoverageCode)
40
+ }
41
+
42
+ export (payload) {
43
+ this._writer.append(payload)
44
+ }
45
+
46
+ exportCoverage (formattedCoverage) {
47
+ this._coverageWriter.append(formattedCoverage)
48
+ }
49
+
50
+ flush () {
51
+ this._writer.flush()
52
+ this._coverageWriter.flush()
53
+ }
54
+ }
55
+
56
+ module.exports = TestWorkerCiVisibilityExporter
@@ -23,11 +23,18 @@ class Writer {
23
23
  }
24
24
 
25
25
  _sendPayload (data) {
26
+ // ## Jest
26
27
  // Only available when `child_process` is used for the jest worker.
27
28
  // eslint-disable-next-line
28
29
  // https://github.com/facebook/jest/blob/bb39cb2c617a3334bf18daeca66bd87b7ccab28b/packages/jest-worker/README.md#experimental-worker
29
30
  // If worker_threads is used, this will not work
30
31
  // TODO: make it compatible with worker_threads
32
+
33
+ // ## Cucumber
34
+ // This reports to the test's main process the same way test data is reported by Cucumber
35
+ // See cucumber code:
36
+ // eslint-disable-next-line
37
+ // https://github.com/cucumber/cucumber-js/blob/5ce371870b677fe3d1a14915dc535688946f734c/src/runtime/parallel/run_worker.ts#L13
31
38
  if (process.send) { // it only works if process.send is available
32
39
  process.send([this._interprocessCode, data])
33
40
  }
@@ -18,7 +18,8 @@ module.exports = name => {
18
18
  case exporters.AGENT_PROXY:
19
19
  return require('./ci-visibility/exporters/agent-proxy')
20
20
  case exporters.JEST_WORKER:
21
- return require('./ci-visibility/exporters/jest-worker')
21
+ case exporters.CUCUMBER_WORKER:
22
+ return require('./ci-visibility/exporters/test-worker')
22
23
  default:
23
24
  return inAWSLambda && !usingLambdaExtension ? require('./exporters/log') : require('./exporters/agent')
24
25
  }
@@ -61,6 +61,8 @@ const CI_APP_ORIGIN = 'ciapp-test'
61
61
  const JEST_TEST_RUNNER = 'test.jest.test_runner'
62
62
  const JEST_DISPLAY_NAME = 'test.jest.display_name'
63
63
 
64
+ const CUCUMBER_IS_PARALLEL = 'test.cucumber.is_parallel'
65
+
64
66
  const TEST_ITR_TESTS_SKIPPED = '_dd.ci.itr.tests_skipped'
65
67
  const TEST_ITR_SKIPPING_ENABLED = 'test.itr.tests_skipping.enabled'
66
68
  const TEST_ITR_SKIPPING_TYPE = 'test.itr.tests_skipping.type'
@@ -82,6 +84,9 @@ const TEST_BROWSER_VERSION = 'test.browser.version'
82
84
  const JEST_WORKER_TRACE_PAYLOAD_CODE = 60
83
85
  const JEST_WORKER_COVERAGE_PAYLOAD_CODE = 61
84
86
 
87
+ // cucumber worker variables
88
+ const CUCUMBER_WORKER_TRACE_PAYLOAD_CODE = 70
89
+
85
90
  // Early flake detection util strings
86
91
  const EFD_STRING = "Retried by Datadog's Early Flake Detection"
87
92
  const EFD_TEST_NAME_REGEX = new RegExp(EFD_STRING + ' \\(#\\d+\\): ', 'g')
@@ -92,6 +97,7 @@ module.exports = {
92
97
  TEST_FRAMEWORK_VERSION,
93
98
  JEST_TEST_RUNNER,
94
99
  JEST_DISPLAY_NAME,
100
+ CUCUMBER_IS_PARALLEL,
95
101
  TEST_TYPE,
96
102
  TEST_NAME,
97
103
  TEST_SUITE,
@@ -104,6 +110,7 @@ module.exports = {
104
110
  LIBRARY_VERSION,
105
111
  JEST_WORKER_TRACE_PAYLOAD_CODE,
106
112
  JEST_WORKER_COVERAGE_PAYLOAD_CODE,
113
+ CUCUMBER_WORKER_TRACE_PAYLOAD_CODE,
107
114
  TEST_SOURCE_START,
108
115
  TEST_SKIPPED_BY_ITR,
109
116
  TEST_CONFIGURATION_BROWSER_NAME,
@@ -1,33 +0,0 @@
1
- 'use strict'
2
-
3
- const Writer = require('./writer')
4
- const {
5
- JEST_WORKER_COVERAGE_PAYLOAD_CODE,
6
- JEST_WORKER_TRACE_PAYLOAD_CODE
7
- } = require('../../../plugins/util/test')
8
-
9
- /**
10
- * Lightweight exporter whose writers only do simple JSON serialization
11
- * of trace and coverage payloads, which they send to the jest main process.
12
- */
13
- class JestWorkerCiVisibilityExporter {
14
- constructor () {
15
- this._writer = new Writer(JEST_WORKER_TRACE_PAYLOAD_CODE)
16
- this._coverageWriter = new Writer(JEST_WORKER_COVERAGE_PAYLOAD_CODE)
17
- }
18
-
19
- export (payload) {
20
- this._writer.append(payload)
21
- }
22
-
23
- exportCoverage (formattedCoverage) {
24
- this._coverageWriter.append(formattedCoverage)
25
- }
26
-
27
- flush () {
28
- this._writer.flush()
29
- this._coverageWriter.flush()
30
- }
31
- }
32
-
33
- module.exports = JestWorkerCiVisibilityExporter