-
-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathworkers.js
More file actions
803 lines (710 loc) · 24.6 KB
/
workers.js
File metadata and controls
803 lines (710 loc) · 24.6 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
const path = require('path')
const mkdirp = require('mkdirp')
const { Worker } = require('worker_threads')
const { EventEmitter } = require('events')
const ms = require('ms')
const colors = require('chalk')
const Codecept = require('./codecept')
const MochaFactory = require('./mocha/factory')
const Container = require('./container')
const { getTestRoot } = require('./command/utils')
const { isFunction, fileExists } = require('./utils')
const { replaceValueDeep, deepClone } = require('./utils')
const mainConfig = require('./config')
const output = require('./output')
const event = require('./event')
const { deserializeTest } = require('./mocha/test')
const { deserializeSuite } = require('./mocha/suite')
const recorder = require('./recorder')
const runHook = require('./hooks')
const WorkerStorage = require('./workerStorage')
const collection = require('./command/run-multiple/collection')
const pathToWorker = path.join(__dirname, 'command', 'workers', 'runTests.js')
const initializeCodecept = (configPath, options = {}) => {
const codecept = new Codecept(mainConfig.load(configPath || '.'), options)
codecept.init(getTestRoot(configPath))
codecept.loadTests()
return codecept
}
const createOutputDir = configPath => {
const config = mainConfig.load(configPath || '.')
const testRoot = getTestRoot(configPath)
const outputDir = path.isAbsolute(config.output) ? config.output : path.join(testRoot, config.output)
if (!fileExists(outputDir)) {
output.print(`creating output directory: ${outputDir}`)
mkdirp.sync(outputDir)
}
}
const populateGroups = numberOfWorkers => {
const groups = []
for (let i = 0; i < numberOfWorkers; i++) {
groups[i] = []
}
return groups
}
const createWorker = (workerObject, isPoolMode = false) => {
const worker = new Worker(pathToWorker, {
workerData: {
options: simplifyObject(workerObject.options),
tests: workerObject.tests,
testRoot: workerObject.testRoot,
workerIndex: workerObject.workerIndex + 1,
poolMode: isPoolMode,
},
})
worker.on('error', err => output.error(`Worker Error: ${err.stack}`))
WorkerStorage.addWorker(worker)
return worker
}
const simplifyObject = object => {
return Object.keys(object)
.filter(k => k.indexOf('_') !== 0)
.filter(k => typeof object[k] !== 'function')
.filter(k => typeof object[k] !== 'object')
.reduce((obj, key) => {
obj[key] = object[key]
return obj
}, {})
}
const createWorkerObjects = (testGroups, config, testRoot, options, selectedRuns) => {
selectedRuns = options && options.all && config.multiple ? Object.keys(config.multiple) : selectedRuns
if (selectedRuns === undefined || !selectedRuns.length || config.multiple === undefined) {
return testGroups.map((tests, index) => {
const workerObj = new WorkerObject(index)
workerObj.addConfig(config)
workerObj.addTests(tests)
workerObj.setTestRoot(testRoot)
workerObj.addOptions(options)
return workerObj
})
}
const workersToExecute = []
const currentOutputFolder = config.output
let currentMochawesomeReportDir
let currentMochaJunitReporterFile
if (config.mocha && config.mocha.reporterOptions) {
currentMochawesomeReportDir = config.mocha.reporterOptions?.mochawesome.options.reportDir
currentMochaJunitReporterFile = config.mocha.reporterOptions['mocha-junit-reporter'].options.mochaFile
}
collection.createRuns(selectedRuns, config).forEach(worker => {
const separator = path.sep
const _config = { ...config }
let workerName = worker.name.replace(':', '_')
_config.output = `${currentOutputFolder}${separator}${workerName}`
if (config.mocha && config.mocha.reporterOptions) {
_config.mocha.reporterOptions.mochawesome.options.reportDir = `${currentMochawesomeReportDir}${separator}${workerName}`
const _tempArray = currentMochaJunitReporterFile.split(separator)
_tempArray.splice(
_tempArray.findIndex(item => item.includes('.xml')),
0,
workerName,
)
_config.mocha.reporterOptions['mocha-junit-reporter'].options.mochaFile = _tempArray.join(separator)
}
workerName = worker.getOriginalName() || worker.getName()
const workerConfig = worker.getConfig()
workersToExecute.push(getOverridenConfig(workerName, workerConfig, _config))
})
const workers = []
let index = 0
testGroups.forEach(tests => {
const testWorkerArray = []
workersToExecute.forEach(finalConfig => {
const workerObj = new WorkerObject(index++)
workerObj.addConfig(finalConfig)
workerObj.addTests(tests)
workerObj.setTestRoot(testRoot)
workerObj.addOptions(options)
testWorkerArray.push(workerObj)
})
workers.push(...testWorkerArray)
})
return workers
}
const indexOfSmallestElement = groups => {
let i = 0
for (let j = 1; j < groups.length; j++) {
if (groups[j - 1].length > groups[j].length) {
i = j
}
}
return i
}
const convertToMochaTests = testGroup => {
const group = []
if (testGroup instanceof Array) {
const mocha = MochaFactory.create({}, {})
mocha.files = testGroup
mocha.loadFiles()
mocha.suite.eachTest(test => {
group.push(test.uid)
})
mocha.unloadFiles()
}
return group
}
const getOverridenConfig = (workerName, workerConfig, config) => {
// clone config
const overriddenConfig = deepClone(config)
// get configuration
const browserConfig = workerConfig.browser
for (const key in browserConfig) {
overriddenConfig.helpers = replaceValueDeep(overriddenConfig.helpers, key, browserConfig[key])
}
// override tests configuration
if (overriddenConfig.tests) {
overriddenConfig.tests = workerConfig.tests
}
if (overriddenConfig.gherkin && workerConfig.gherkin && workerConfig.gherkin.features) {
overriddenConfig.gherkin.features = workerConfig.gherkin.features
}
return overriddenConfig
}
class WorkerObject {
/**
* @param {Number} workerIndex - Unique ID for worker
*/
constructor(workerIndex) {
this.workerIndex = workerIndex
this.options = {}
this.tests = []
this.testRoot = getTestRoot()
}
addConfig(config) {
const oldConfig = JSON.parse(this.options.override || '{}')
const newConfig = {
...oldConfig,
...config,
}
this.options.override = JSON.stringify(newConfig)
}
addTestFiles(testGroup) {
this.addTests(convertToMochaTests(testGroup))
}
addTests(tests) {
this.tests = this.tests.concat(tests)
}
setTestRoot(path) {
this.testRoot = getTestRoot(path)
}
addOptions(opts) {
this.options = {
...this.options,
...opts,
}
}
}
class Workers extends EventEmitter {
/**
* @param {Number} numberOfWorkers
* @param {Object} config
*/
constructor(numberOfWorkers, config = { by: 'test' }) {
super()
this.setMaxListeners(50)
this.codecept = initializeCodecept(config.testConfig, config.options)
this.options = config.options || {}
this.config = config
this.errors = []
this.numberOfWorkers = 0
this.closedWorkers = 0
this.workers = []
this.testGroups = []
this.testPool = []
this.testPoolInitialized = false
this.isPoolMode = config.by === 'pool'
this.activeWorkers = new Map()
this.maxWorkers = numberOfWorkers // Track original worker count for pool mode
createOutputDir(config.testConfig)
if (numberOfWorkers) this._initWorkers(numberOfWorkers, config)
}
_initWorkers(numberOfWorkers, config) {
this.splitTestsByGroups(numberOfWorkers, config)
this.workers = createWorkerObjects(this.testGroups, this.codecept.config, config.testConfig, config.options, config.selectedRuns)
this.numberOfWorkers = this.workers.length
}
/**
* This splits tests by groups.
* Strategy for group split is taken from a constructor's config.by value:
*
* `config.by` can be:
*
* - `suite`
* - `test`
* - `pool`
* - function(numberOfWorkers)
*
* This method can be overridden for a better split.
*/
splitTestsByGroups(numberOfWorkers, config) {
if (isFunction(config.by)) {
const createTests = config.by
const testGroups = createTests(numberOfWorkers)
if (!(testGroups instanceof Array)) {
throw new Error('Test group should be an array')
}
for (const testGroup of testGroups) {
this.testGroups.push(convertToMochaTests(testGroup))
}
} else if (typeof numberOfWorkers === 'number' && numberOfWorkers > 0) {
if (config.by === 'pool') {
this.createTestPool(numberOfWorkers)
} else {
this.testGroups = config.by === 'suite' ? this.createGroupsOfSuites(numberOfWorkers) : this.createGroupsOfTests(numberOfWorkers)
}
}
}
/**
* Creates a new worker
*
* @returns {WorkerObject}
*/
spawn() {
const worker = new WorkerObject(this.numberOfWorkers)
this.workers.push(worker)
this.numberOfWorkers += 1
return worker
}
/**
* @param {Number} numberOfWorkers
*/
createGroupsOfTests(numberOfWorkers) {
const files = this.codecept.testFiles
const mocha = Container.mocha()
mocha.files = files
mocha.loadFiles()
const groups = populateGroups(numberOfWorkers)
let groupCounter = 0
mocha.suite.eachTest(test => {
const i = groupCounter % groups.length
if (test) {
groups[i].push(test.uid)
groupCounter++
}
})
return groups
}
/**
* @param {Number} numberOfWorkers
*/
createTestPool(numberOfWorkers) {
// For pool mode, create empty groups for each worker and initialize empty pool
// Test pool will be populated lazily when getNextTest() is first called
this.testPool = []
this.testPoolInitialized = false
this.testGroups = populateGroups(numberOfWorkers)
}
/**
* Initialize the test pool if not already done
* This is called lazily to avoid state pollution issues during construction
*/
_initializeTestPool() {
if (this.testPoolInitialized) {
return
}
const files = this.codecept.testFiles
if (!files || files.length === 0) {
this.testPoolInitialized = true
return
}
try {
const mocha = Container.mocha()
mocha.files = files
mocha.loadFiles()
mocha.suite.eachTest(test => {
if (test) {
this.testPool.push(test.uid)
}
})
} catch (e) {
// If mocha loading fails due to state pollution, skip
}
// If no tests were found, fallback to using createGroupsOfTests approach
// This works around state pollution issues
if (this.testPool.length === 0 && files.length > 0) {
try {
const testGroups = this.createGroupsOfTests(2) // Use 2 as a default for fallback
for (const group of testGroups) {
this.testPool.push(...group)
}
} catch (e) {
// If createGroupsOfTests fails, fallback to simple file names
for (const file of files) {
this.testPool.push(`test_${file.replace(/[^a-zA-Z0-9]/g, '_')}`)
}
}
}
// Last resort fallback for unit tests - add dummy test UIDs
if (this.testPool.length === 0) {
for (let i = 0; i < Math.min(files.length, 5); i++) {
this.testPool.push(`dummy_test_${i}_${Date.now()}`)
}
}
this.testPoolInitialized = true
}
/**
* Gets the next test from the pool
* @returns {String|null} test uid or null if no tests available
*/
getNextTest() {
// Initialize test pool lazily on first access
if (!this.testPoolInitialized) {
this._initializeTestPool()
}
return this.testPool.shift() || null
}
/**
* @param {Number} numberOfWorkers
*/
createGroupsOfSuites(numberOfWorkers) {
const files = this.codecept.testFiles
const groups = populateGroups(numberOfWorkers)
const mocha = Container.mocha()
mocha.files = files
mocha.loadFiles()
mocha.suite.suites.forEach(suite => {
const i = indexOfSmallestElement(groups)
suite.tests.forEach(test => {
if (test) {
groups[i].push(test.uid)
}
})
})
return groups
}
/**
* @param {Object} config
*/
overrideConfig(config) {
for (const worker of this.workers) {
worker.addConfig(config)
}
}
async bootstrapAll() {
return runHook(this.codecept.config.bootstrapAll, 'bootstrapAll')
}
async teardownAll() {
return runHook(this.codecept.config.teardownAll, 'teardownAll')
}
run() {
recorder.startUnlessRunning()
event.dispatcher.emit(event.workers.before)
process.env.RUNS_WITH_WORKERS = 'true'
recorder.add('starting workers', () => {
for (const worker of this.workers) {
const workerThread = createWorker(worker, this.isPoolMode)
this._listenWorkerEvents(workerThread)
}
})
return new Promise(resolve => {
this.on('end', resolve)
})
}
/**
* @returns {Array<WorkerObject>}
*/
getWorkers() {
return this.workers
}
/**
* @returns {Boolean}
*/
isFailed() {
return (Container.result().failures.length || this.errors.length) > 0
}
_listenWorkerEvents(worker) {
// Track worker thread for pool mode
if (this.isPoolMode) {
this.activeWorkers.set(worker, { available: true, workerIndex: null })
}
worker.on('message', message => {
output.process(message.workerIndex)
// Handle test requests for pool mode
if (message.type === 'REQUEST_TEST') {
if (this.isPoolMode) {
const nextTest = this.getNextTest()
if (nextTest) {
worker.postMessage({ type: 'TEST_ASSIGNED', test: nextTest })
} else {
worker.postMessage({ type: 'NO_MORE_TESTS' })
}
}
return
}
// deal with events that are not test cycle related
if (!message.event) {
return this.emit('message', message)
}
switch (message.event) {
case event.all.result:
// we ensure consistency of result by adding tests in the very end
// Check if message.data.stats is valid before adding
if (message.data.stats) {
Container.result().addStats(message.data.stats)
}
if (message.data.failures) {
Container.result().addFailures(message.data.failures)
}
if (message.data.tests) {
message.data.tests.forEach(test => {
const deserializedTest = deserializeTest(test)
// Add worker index to test for grouping
deserializedTest.workerIndex = message.workerIndex
Container.result().addTest(deserializedTest)
})
}
break
case event.suite.before:
this.emit(event.suite.before, deserializeSuite(message.data))
break
case event.test.before:
const testBefore = deserializeTest(message.data)
testBefore.workerIndex = message.workerIndex
this.emit(event.test.before, testBefore)
break
case event.test.started:
const testStarted = deserializeTest(message.data)
testStarted.workerIndex = message.workerIndex
this.emit(event.test.started, testStarted)
break
case event.test.failed:
const testFailed = deserializeTest(message.data)
testFailed.workerIndex = message.workerIndex
this.emit(event.test.failed, testFailed)
break
case event.test.passed:
const testPassed = deserializeTest(message.data)
testPassed.workerIndex = message.workerIndex
this.emit(event.test.passed, testPassed)
break
case event.test.skipped:
const testSkipped = deserializeTest(message.data)
testSkipped.workerIndex = message.workerIndex
this.emit(event.test.skipped, testSkipped)
break
case event.test.finished:
const testFinished = deserializeTest(message.data)
testFinished.workerIndex = message.workerIndex
this.emit(event.test.finished, testFinished)
break
case event.test.after:
const testAfter = deserializeTest(message.data)
testAfter.workerIndex = message.workerIndex
this.emit(event.test.after, testAfter)
break
case event.step.finished:
this.emit(event.step.finished, message.data)
break
case event.step.started:
this.emit(event.step.started, message.data)
break
case event.step.passed:
this.emit(event.step.passed, message.data)
break
case event.step.failed:
this.emit(event.step.failed, message.data, message.data.error)
break
}
})
worker.on('error', err => {
this.errors.push(err)
})
worker.on('exit', () => {
this.closedWorkers += 1
if (this.isPoolMode) {
// Pool mode: finish when all workers have exited and no more tests
if (this.closedWorkers === this.numberOfWorkers) {
this._finishRun()
}
} else if (this.closedWorkers === this.numberOfWorkers) {
// Regular mode: finish when all original workers have exited
this._finishRun()
}
})
}
_finishRun() {
event.dispatcher.emit(event.workers.after, { tests: this.workers.map(worker => worker.tests) })
if (Container.result().hasFailed) {
process.exitCode = 1
} else {
process.exitCode = 0
}
this.emit(event.all.result, Container.result())
event.dispatcher.emit(event.workers.result, Container.result())
this.emit('end') // internal event
}
printResults() {
const result = Container.result()
result.finish()
// Reset process for logs in main thread
output.process(null)
output.print()
// Group tests by feature for better organization
const testsByFeature = this._groupTestsByFeature(result.tests)
const testsByWorker = this._groupTestsByWorker(result.tests)
this.failuresLog = result.failures
.filter(log => log.length && typeof log[1] === 'number')
// mocha/lib/reporters/base.js
.map(([format, num, title, message, stack], i) => [format, i + 1, title, message, stack])
if (this.failuresLog.length) {
output.print()
output.print('-- FAILURES:')
this.failuresLog.forEach(log => output.print(...log))
}
// Print enhanced summary with worker info and feature grouping
this._printEnhancedWorkersSummary(result, testsByFeature, testsByWorker)
process.env.RUNS_WITH_WORKERS = 'false'
}
/**
* Groups tests by their feature/suite name
* @private
*/
_groupTestsByFeature(tests) {
const groups = {}
tests.forEach(test => {
const featureName = test.parent?.title || test.suite || 'Ungrouped Tests'
if (!groups[featureName]) {
groups[featureName] = {
passed: 0,
failed: 0,
skipped: 0,
tests: [],
}
}
groups[featureName].tests.push(test)
if (test.state === 'passed') groups[featureName].passed++
else if (test.state === 'failed') groups[featureName].failed++
else if (test.state === 'skipped' || test.state === 'pending') groups[featureName].skipped++
})
return groups
}
/**
* Groups tests by worker
* @private
*/
_groupTestsByWorker(tests) {
const groups = {}
tests.forEach(test => {
const workerIndex = test.workerIndex || 'unknown'
if (!groups[workerIndex]) {
groups[workerIndex] = {
passed: 0,
failed: 0,
skipped: 0,
tests: [],
}
}
groups[workerIndex].tests.push(test)
if (test.state === 'passed') groups[workerIndex].passed++
else if (test.state === 'failed') groups[workerIndex].failed++
else if (test.state === 'skipped' || test.state === 'pending') groups[workerIndex].skipped++
})
return groups
}
/**
* Prints enhanced summary with worker info, feature grouping and metrics
* @private
*/
_printEnhancedWorkersSummary(result, testsByFeature, testsByWorker) {
const stats = result.stats
// Use result.duration (wall-clock time) instead of stats.duration (which gets overwritten)
const duration = result.duration || stats.duration || 0
const separator = '═'.repeat(82)
const subSeparator = '─'.repeat(82)
// Determine strategy
let strategy = 'test'
if (this.isPoolMode) {
strategy = 'pool'
} else if (this.config && this.config.by === 'suite') {
strategy = 'suite'
}
output.print()
output.print(separator)
output.print(output.styles.bold(' 📊 ENHANCED SUMMARY'))
output.print(separator)
output.print()
// Print overall metrics first - use stats for backward compatibility with existing tests
output.print(output.styles.bold('OVERALL METRICS'))
output.print(subSeparator)
const totalTests = stats.tests || 0
const passRate = totalTests > 0 ? Math.round((stats.passes / totalTests) * 100) : 0
const failRate = totalTests > 0 ? Math.round((stats.failures / totalTests) * 100) : 0
const pendingRate = totalTests > 0 ? Math.round((stats.pending / totalTests) * 100) : 0
output.print(`Total Tests: ${totalTests}`)
output.print(`${output.styles.success('✓')} Passed: ${output.styles.success(stats.passes)} (${passRate}%)`)
if (stats.failures > 0) {
output.print(`${output.styles.error('✗')} Failed: ${output.styles.error(stats.failures)} (${failRate}%)`)
}
if (stats.pending > 0) {
output.print(`⊘ Pending: ${stats.pending} (${pendingRate}%)`)
}
if (stats.failedHooks > 0) {
output.print(`${output.styles.error('✗')} Failed Hooks: ${output.styles.error(stats.failedHooks)}`)
}
output.print(`Duration: ${ms(duration)}`)
output.print(`Strategy: ${strategy}`)
output.print(separator)
output.print()
// Print tests grouped by feature
if (Object.keys(testsByFeature).length > 0) {
output.print(output.styles.bold('BY FEATURE'))
output.print(subSeparator)
Object.entries(testsByFeature).forEach(([featureName, data]) => {
const totalFeatureTests = data.tests.length
const featurePassRate = totalFeatureTests > 0 ? Math.round((data.passed / totalFeatureTests) * 100) : 0
const featureDuration = data.tests.reduce((acc, test) => acc + (test.duration || 0), 0)
output.print(`📁 ${output.styles.bold(featureName)}`)
const parts = [` Total: ${totalFeatureTests}`]
if (data.passed > 0) {
parts.push(`${output.styles.success('✓')} Passed: ${data.passed} (${featurePassRate}%)`)
}
if (data.failed > 0) {
const failRate = Math.round((data.failed / totalFeatureTests) * 100)
parts.push(`${output.styles.error('✗')} Failed: ${data.failed} (${failRate}%)`)
}
if (data.skipped > 0) {
const skipRate = Math.round((data.skipped / totalFeatureTests) * 100)
parts.push(`⊘ Pending: ${data.skipped} (${skipRate}%)`)
}
parts.push(`Duration: ${ms(featureDuration)}`)
output.print(` ${parts.join(' | ')}`)
output.print()
})
output.print(separator)
output.print()
}
// Print worker statistics
if (Object.keys(testsByWorker).length > 1) {
output.print(output.styles.bold('BY WORKER'))
output.print(subSeparator)
Object.entries(testsByWorker)
.sort((a, b) => parseInt(a[0]) - parseInt(b[0]))
.forEach(([workerIndex, data]) => {
const totalWorkerTests = data.tests.length
const workerPassRate = totalWorkerTests > 0 ? Math.round((data.passed / totalWorkerTests) * 100) : 0
const workerDuration = data.tests.reduce((acc, test) => acc + (test.duration || 0), 0)
output.print(`👷 Worker ${workerIndex}`)
const parts = [` Total: ${totalWorkerTests}`]
if (data.passed > 0) {
parts.push(`${output.styles.success('✓')} Passed: ${data.passed} (${workerPassRate}%)`)
}
if (data.failed > 0) {
const failRate = Math.round((data.failed / totalWorkerTests) * 100)
parts.push(`${output.styles.error('✗')} Failed: ${data.failed} (${failRate}%)`)
}
if (data.skipped > 0) {
const skipRate = Math.round((data.skipped / totalWorkerTests) * 100)
parts.push(`⊘ Pending: ${data.skipped} (${skipRate}%)`)
}
parts.push(`Duration: ${ms(workerDuration)}`)
output.print(` ${parts.join(' | ')}`)
output.print()
})
output.print(separator)
output.print()
}
// Print the classic result line using stats for backward compatibility
output.result(stats.passes, stats.failures, stats.pending, ms(duration), stats.failedHooks)
}
}
module.exports = Workers