/
runner.js
1348 lines (1060 loc) · 34.1 KB
/
runner.js
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
/* eslint-disable prefer-rest-params */
/* globals Cypress */
const _ = require('lodash')
const moment = require('moment')
const Promise = require('bluebird')
const Pending = require('mocha/lib/pending')
const $Log = require('./log')
const $utils = require('./utils')
const $errUtils = require('./error_utils')
const $stackUtils = require('./stack_utils')
const mochaCtxKeysRe = /^(_runnable|test)$/
const betweenQuotesRe = /\"(.+?)\"/
const HOOKS = 'beforeAll beforeEach afterEach afterAll'.split(' ')
const TEST_BEFORE_RUN_EVENT = 'runner:test:before:run'
const TEST_AFTER_RUN_EVENT = 'runner:test:after:run'
const RUNNABLE_LOGS = 'routes agents commands hooks'.split(' ')
const RUNNABLE_PROPS = 'id order title root hookName hookId err state failedFromHookId body speed type duration wallClockStartedAt wallClockDuration timings file originalTitle invocationDetails'.split(' ')
const debug = require('debug')('cypress:driver:runner')
const fire = (event, runnable, Cypress) => {
debug('fire: %o', { event })
if (runnable._fired == null) {
runnable._fired = {}
}
runnable._fired[event] = true
// dont fire anything again if we are skipped
if (runnable._ALREADY_RAN) {
return
}
return Cypress.action(event, wrap(runnable), runnable)
}
const fired = (event, runnable) => {
return !!(runnable._fired && runnable._fired[event])
}
const testBeforeRunAsync = (test, Cypress) => {
return Promise.try(() => {
if (!fired('runner:test:before:run:async', test)) {
return fire('runner:test:before:run:async', test, Cypress)
}
})
}
const runnableAfterRunAsync = (runnable, Cypress) => {
runnable.clearTimeout()
return Promise.try(() => {
if (!fired('runner:runnable:after:run:async', runnable)) {
return fire('runner:runnable:after:run:async', runnable, Cypress)
}
})
}
const testAfterRun = (test, Cypress) => {
test.clearTimeout()
if (!fired(TEST_AFTER_RUN_EVENT, test)) {
setWallClockDuration(test)
fire(TEST_AFTER_RUN_EVENT, test, Cypress)
// perf loop only through
// a tests OWN properties and not
// inherited properties from its shared ctx
for (let key of Object.keys(test.ctx || {})) {
const value = test.ctx[key]
if (_.isObject(value) && !mochaCtxKeysRe.test(key)) {
// nuke any object properties that come from
// cy.as() aliases or anything set from 'this'
// so we aggressively perform GC and prevent obj
// ref's from building up
test.ctx[key] = undefined
}
}
// reset the fn to be empty function
// for GC to be aggressive and prevent
// closures from hold references
test.fn = () => {}
// prevent loop comprehension
return null
}
}
const setTestTimingsForHook = (test, hookName, obj) => {
if (test.timings == null) {
test.timings = {}
}
if (test.timings[hookName] == null) {
test.timings[hookName] = []
}
return test.timings[hookName].push(obj)
}
const setTestTimings = (test, name, obj) => {
if (test.timings == null) {
test.timings = {}
}
test.timings[name] = obj
}
const setWallClockDuration = (test) => {
return test.wallClockDuration = new Date() - test.wallClockStartedAt
}
// we need to optimize wrap by converting
// tests to an id-based object which prevents
// us from recursively iterating through every
// parent since we could just return the found test
const wrap = (runnable) => {
return $utils.reduceProps(runnable, RUNNABLE_PROPS)
}
const wrapAll = (runnable) => {
return _.extend(
{},
$utils.reduceProps(runnable, RUNNABLE_PROPS),
$utils.reduceProps(runnable, RUNNABLE_LOGS),
)
}
const condenseHooks = (runnable, getHookId) => {
const hooks = _.compact(_.concat(
runnable._beforeAll,
runnable._beforeEach,
runnable._afterAll,
runnable._afterEach,
))
return _.map(hooks, (hook) => {
if (!hook.hookId) {
hook.hookId = getHookId()
}
if (!hook.hookName) {
hook.hookName = getHookName(hook)
}
return wrap(hook)
})
}
const getHookName = (hook) => {
// find the name of the hook by parsing its
// title and pulling out whats between the quotes
const name = hook.title.match(betweenQuotesRe)
return name && name[1]
}
const forceGc = (obj) => {
// aggressively forces GC by purging
// references to ctx, and removes callback
// functions for closures
for (let key of Object.keys(obj.ctx || {})) {
obj.ctx[key] = undefined
}
if (obj.fn) {
obj.fn = () => {}
}
}
const eachHookInSuite = (suite, fn) => {
for (let type of HOOKS) {
for (let hook of suite[`_${type}`]) {
fn(hook)
}
}
// prevent loop comprehension
return null
}
// iterates over a suite's tests (including nested suites)
// and will return as soon as the callback is true
const findTestInSuite = (suite, fn = _.identity) => {
for (const test of suite.tests) {
if (fn(test)) {
return test
}
}
for (suite of suite.suites) {
const test = findTestInSuite(suite, fn)
if (test) {
return test
}
}
}
// same as findTestInSuite but iterates backwards
const findLastTestInSuite = (suite, fn = _.identity) => {
for (let i = suite.suites.length - 1; i >= 0; i--) {
const test = findLastTestInSuite(suite.suites[i], fn)
if (test) {
return test
}
}
for (let i = suite.tests.length - 1; i >= 0; i--) {
const test = suite.tests[i]
if (fn(test)) {
return test
}
}
}
const getAllSiblingTests = (suite, getTestById) => {
const tests = []
suite.eachTest((test) => {
// iterate through each of our suites tests.
// this will iterate through all nested tests
// as well. and then we add it only if its
// in our filtered tests array
if (getTestById(test.id)) {
return tests.push(test)
}
})
return tests
}
function getTestIndexFromId (id) {
return +id.slice(1)
}
const getTestFromHook = (hook) => {
// if theres already a currentTest use that
const test = hook.ctx.currentTest
if (test) {
return test
}
}
// we have to see if this is the last suite amongst
// its siblings. but first we have to filter out
// suites which dont have a filtered test in them
const isLastSuite = (suite, tests) => {
if (suite.root) {
return false
}
// grab all of the suites from our filtered tests
// including all of their ancestor suites!
const suites = _.reduce(tests, (memo, test) => {
let parent
while ((parent = test.parent)) {
memo.push(parent)
test = parent
}
return memo
}
, [])
// intersect them with our parent suites and see if the last one is us
return _
.chain(suites)
.uniq()
.intersection(suite.parent.suites)
.last()
.value() === suite
}
// we are the last test that will run in the suite
// if we're the last test in the tests array or
// if we failed from a hook and that hook was 'before'
// since then mocha skips the remaining tests in the suite
const lastTestThatWillRunInSuite = (test, tests) => {
return isLastTest(test, tests) || (test.failedFromHookId && (test.hookName === 'before all'))
}
const isLastTest = (test, tests) => {
return test === _.last(tests)
}
const isRootSuite = (suite) => {
return suite && suite.root
}
const overrideRunnerHook = (Cypress, _runner, getTestById, getTest, setTest, getTests) => {
// bail if our _runner doesnt have a hook.
// useful in tests
if (!_runner.hook) {
return
}
// monkey patch the hook event so we can wrap
// 'test:after:run' around all of
// the hooks surrounding a test runnable
const _runnerHook = _runner.hook
_runner.hook = function (name, fn) {
const allTests = getTests()
const changeFnToRunAfterHooks = () => {
const originalFn = fn
const test = getTest()
fn = function () {
setTest(null)
testAfterRun(test, Cypress)
// and now invoke next(err)
return originalFn.apply(window, arguments)
}
}
switch (name) {
case 'afterEach': {
const t = getTest()
// find all of the filtered _tests which share
// the same parent suite as our current _test
const tests = getAllSiblingTests(t.parent, getTestById)
// make sure this test isnt the last test overall but also
// isnt the last test in our filtered parent suite's tests array
if (this.suite.root && (t !== _.last(allTests)) && (t !== _.last(tests))) {
changeFnToRunAfterHooks()
}
break
}
case 'afterAll': {
// find all of the filtered allTests which share
// the same parent suite as our current _test
const t = getTest()
if (t) {
const siblings = getAllSiblingTests(t.parent, getTestById)
// 1. if we're the very last test in the entire allTests
// we wait until the root suite fires
// 2. else if we arent the last nested suite we fire if we're
// the last test that will run
if (
(isRootSuite(this.suite) && isLastTest(t, allTests)) ||
(!isLastSuite(this.suite, allTests) && lastTestThatWillRunInSuite(t, siblings))
) {
changeFnToRunAfterHooks()
}
}
break
}
default:
break
}
return _runnerHook.call(this, name, fn)
}
}
const getTestResults = (tests) => {
return _.map(tests, (test) => {
const obj = _.pick(test, 'id', 'duration', 'state')
obj.title = test.originalTitle
// TODO FIX THIS!
if (!obj.state) {
obj.state = 'skipped'
}
return obj
})
}
const hasOnly = (suite) => {
return (
suite._onlyTests.length ||
suite._onlySuites.length ||
_.some(suite.suites, hasOnly)
)
}
const normalizeAll = (suite, initialTests = {}, setTestsById, setTests, onRunnable, onLogsById, getTestId, getHookId) => {
let hasTests = false
// only loop until we find the first test
findTestInSuite(suite, (test) => {
return hasTests = true
})
// if we dont have any tests then bail
if (!hasTests) {
return
}
// we are doing a super perf loop here where
// we hand back a normalized object but also
// create optimized lookups for the tests without
// traversing through it multiple times
const tests = {}
const normalizedSuite = normalize(suite, tests, initialTests, onRunnable, onLogsById, getTestId, getHookId)
if (setTestsById) {
// use callback here to hand back
// the optimized tests
setTestsById(tests)
}
if (setTests) {
let i = 0
const testsArr = _.map(tests, (test) => {
test.order = i += 1
return test
})
// same pattern here
setTests(testsArr)
}
return normalizedSuite
}
const normalize = (runnable, tests, initialTests, onRunnable, onLogsById, getTestId, getHookId) => {
const normalizeRunnable = (runnable) => {
let i
runnable.id = getTestId()
// tests have a type of 'test' whereas suites do not have a type property
if (runnable.type == null) {
runnable.type = 'suite'
}
if (onRunnable) {
onRunnable(runnable)
}
// if we have a runnable in the initial state
// then merge in existing properties into the runnable
i = initialTests[runnable.id]
if (i) {
_.each(RUNNABLE_LOGS, (type) => {
return _.each(i[type], onLogsById)
})
_.extend(runnable, i)
}
// merge all hooks into single array
runnable.hooks = condenseHooks(runnable, getHookId)
// reduce this runnable down to its props
// and collections
return wrapAll(runnable)
}
const push = (test) => {
return tests[test.id] != null ? tests[test.id] : (tests[test.id] = test)
}
const normalizedRunnable = normalizeRunnable(runnable)
if ((runnable.type !== 'suite') || !hasOnly(runnable)) {
if (runnable.type === 'test') {
push(runnable)
}
// recursively iterate and normalize all other _runnables
_.each({ tests: runnable.tests, suites: runnable.suites }, (_runnables, type) => {
if (runnable[type]) {
return normalizedRunnable[type] = _.map(_runnables, (runnable) => {
return normalize(runnable, tests, initialTests, onRunnable, onLogsById, getTestId, getHookId)
})
}
})
return normalizedRunnable
}
// this follows how mocha filters onlys. its runner#filterOnly
// is pretty much the same minus the normalization part
const filterOnly = (normalizedSuite, suite) => {
if (suite._onlyTests.length) {
suite.tests = suite._onlyTests
normalizedSuite.tests = _.map(suite._onlyTests, (test) => {
const normalizedTest = normalizeRunnable(test, initialTests, onRunnable, onLogsById, getTestId, getHookId)
push(normalizedTest)
return normalizedTest
})
suite.suites = []
normalizedSuite.suites = []
} else {
suite.tests = []
normalizedSuite.tests = []
_.each(suite._onlySuites, (onlySuite) => {
const normalizedOnlySuite = normalizeRunnable(onlySuite, initialTests, onRunnable, onLogsById, getTestId, getHookId)
if (hasOnly(onlySuite)) {
return filterOnly(normalizedOnlySuite, onlySuite)
}
})
suite.suites = _.filter(suite.suites, (childSuite) => {
const normalizedChildSuite = normalizeRunnable(childSuite, initialTests, onRunnable, onLogsById, getTestId, getHookId)
return (suite._onlySuites.indexOf(childSuite) !== -1) || filterOnly(normalizedChildSuite, childSuite)
})
normalizedSuite.suites = _.map(suite.suites, (childSuite) => normalize(childSuite, tests, initialTests, onRunnable, onLogsById, getTestId, getHookId))
}
return suite.tests.length || suite.suites.length
}
filterOnly(normalizedRunnable, runnable)
return normalizedRunnable
}
const hookFailed = (hook, err, hookName, getTest, getTestFromHookOrFindTest) => {
// NOTE: sometimes mocha will fail a hook without having emitted on('hook')
// event, so this hook might not have currentTest set correctly
// in which case we need to lookup the test
const test = getTest() || getTestFromHookOrFindTest(hook)
test.err = err
test.state = 'failed'
test.duration = hook.duration // TODO: nope (?)
test.hookName = hookName // TODO: why are we doing this?
test.failedFromHookId = hook.hookId
if (hook.alreadyEmittedMocha) {
test.alreadyEmittedMocha = true
} else {
return Cypress.action('runner:test:end', wrap(test))
}
}
function getTestFromRunnable (runnable) {
switch (runnable.type) {
case 'hook':
return getTestFromHook(runnable)
case 'test':
return runnable
default: null
}
}
const _runnerListeners = (_runner, Cypress, _emissions, getTestById, getTest, setTest, getHookId, getTestFromHookOrFindTest) => {
_runner.on('start', () => {
return Cypress.action('runner:start', {
start: new Date(),
})
})
_runner.on('end', () => {
return Cypress.action('runner:end', {
end: new Date(),
})
})
_runner.on('suite', (suite) => {
if (_emissions.started[suite.id]) {
return
}
_emissions.started[suite.id] = true
return Cypress.action('runner:suite:start', wrap(suite))
})
_runner.on('suite end', (suite) => {
// cleanup our suite + its hooks
forceGc(suite)
eachHookInSuite(suite, forceGc)
if (_emissions.ended[suite.id]) {
return
}
_emissions.ended[suite.id] = true
return Cypress.action('runner:suite:end', wrap(suite))
})
_runner.on('hook', (hook) => {
// mocha incorrectly sets currentTest on before/after all's.
// if there is a nested suite with a before, then
// currentTest will refer to the previous test run
// and not our current
// https://github.com/cypress-io/cypress/issues/1987
if ((hook.hookName === 'before all' || hook.hookName === 'after all') && hook.ctx.currentTest) {
delete hook.ctx.currentTest
}
// set the hook's id from the test because
// hooks do not have their own id, their
// commands need to grouped with the test
// and we can only associate them by this id
const test = getTestFromHookOrFindTest(hook)
if (!test) {
// we couldn't find a test to run with this hook
// probably because the entire suite has already completed
// so return early and tell onRunnableRun to skip the test
return
}
hook.id = test.id
hook.ctx.currentTest = test
// make sure we set this test as the current now
// else its possible that our TEST_AFTER_RUN_EVENT
// will never fire if this failed in a before hook
setTest(test)
return Cypress.action('runner:hook:start', wrap(hook))
})
_runner.on('hook end', (hook) => {
return Cypress.action('runner:hook:end', wrap(hook))
})
_runner.on('test', (test) => {
setTest(test)
if (_emissions.started[test.id]) {
return
}
_emissions.started[test.id] = true
return Cypress.action('runner:test:start', wrap(test))
})
_runner.on('test end', (test) => {
if (_emissions.ended[test.id]) {
return
}
_emissions.ended[test.id] = true
return Cypress.action('runner:test:end', wrap(test))
})
_runner.on('pass', (test) => {
return Cypress.action('runner:pass', wrap(test))
})
// if a test is pending mocha will only
// emit the pending event instead of the test
// so we normalize the pending / test events
_runner.on('pending', function (test) {
// do nothing if our test is skipped
if (test._ALREADY_RAN) {
return
}
if (!fired(TEST_BEFORE_RUN_EVENT, test)) {
fire(TEST_BEFORE_RUN_EVENT, test, Cypress)
}
test.state = 'pending'
if (!test.alreadyEmittedMocha) {
// do not double emit this event
test.alreadyEmittedMocha = true
Cypress.action('runner:pending', wrap(test))
}
this.emit('test', test)
// if this is not the last test amongst its siblings
// then go ahead and fire its test:after:run event
// else this will not get called
const tests = getAllSiblingTests(test.parent, getTestById)
if (_.last(tests) !== test) {
return fire(TEST_AFTER_RUN_EVENT, test, Cypress)
}
})
return _runner.on('fail', (runnable, err) => {
let hookName
const isHook = runnable.type === 'hook'
err.stack = $stackUtils.normalizedStack(err)
if (isHook) {
const parentTitle = runnable.parent.title
hookName = getHookName(runnable)
// append a friendly message to the error indicating
// we're skipping the remaining tests in this suite
err = $errUtils.appendErrMsg(
err,
$errUtils.errByPath('uncaught.error_in_hook', {
parentTitle,
hookName,
}).message,
)
}
// always set runnable err so we can tap into
// taking a screenshot on error
runnable.err = $errUtils.wrapErr(err)
if (!runnable.alreadyEmittedMocha) {
// do not double emit this event
runnable.alreadyEmittedMocha = true
Cypress.action('runner:fail', wrap(runnable), runnable.err)
}
// if we've already fired the test after run event
// it means that this runnable likely failed due to
// a double done(err) callback, and we need to fire
// this again!
if (fired(TEST_AFTER_RUN_EVENT, runnable)) {
fire(TEST_AFTER_RUN_EVENT, runnable, Cypress)
}
if (isHook) {
// if a hook fails (such as a before) then the test will never
// get run and we'll need to make sure we set the test so that
// the TEST_AFTER_RUN_EVENT fires correctly
return hookFailed(runnable, runnable.err, hookName, getTest, getTestFromHookOrFindTest)
}
})
}
const create = (specWindow, mocha, Cypress, cy) => {
let _id = 0
let _hookId = 0
let _uncaughtFn = null
let _resumedAtTestIndex = null
const _runner = mocha.getRunner()
_runner.suite = mocha.getRootSuite()
function isNotAlreadyRunTest (test) {
return _resumedAtTestIndex == null || getTestIndexFromId(test.id) >= _resumedAtTestIndex
}
const getTestFromHookOrFindTest = (hook) => {
const test = getTestFromHook(hook)
if (test) {
return test
}
const suite = hook.parent
if (hook.hookName === 'after all') {
return findLastTestInSuite(suite, isNotAlreadyRunTest)
}
if (hook.hookName === 'before all') {
return findTestInSuite(suite, isNotAlreadyRunTest)
}
}
const onScriptError = (err) => {
// err will not be returned if cy can associate this
// uncaught exception to an existing runnable
if (!err) {
return true
}
const todoMsg = () => {
if (!Cypress.config('isTextTerminal')) {
return 'Check your console for the stack trace or click this message to see where it originated from.'
}
}
const appendMsg = _.chain([
'Cypress could not associate this error to any specific test.',
'We dynamically generated a new test to display this failure.',
todoMsg(),
])
.compact()
.join('\n\n')
.value()
err = $errUtils.appendErrMsg(err, appendMsg)
const throwErr = () => {
throw err
}
// we could not associate this error
// and shouldn't ever start our run
_uncaughtFn = throwErr
// return undefined so the browser does its default
// uncaught exception behavior (logging to console)
return undefined
}
specWindow.onerror = function () {
const err = cy.onSpecWindowUncaughtException.apply(cy, arguments)
return onScriptError(err)
}
// hold onto the _runnables for faster lookup later
let _test = null
let _tests = []
let _testsById = {}
const _testsQueue = []
const _testsQueueById = {}
const _runnables = []
const _logsById = {}
let _emissions = {
started: {},
ended: {},
}
let _startTime = null
// increment the id counter
const getTestId = () => {
return `r${_id += 1}`
}
const getHookId = () => {
return `h${_hookId += 1}`
}
const setTestsById = (tbid) => {
return _testsById = tbid
}
const setTests = (t) => {
return _tests = t
}
const getTests = () => {
return _tests
}
const onRunnable = (r) => {
return _runnables.push(r)
}
const onLogsById = (l) => {
return _logsById[l.id] = l
}
const getTest = () => {
return _test
}
const setTest = (t) => {
return _test = t
}
const getTestById = (id) => {
// perf short circuit
if (!id) {
return
}
return _testsById[id]
}
overrideRunnerHook(Cypress, _runner, getTestById, getTest, setTest, getTests)
return {
onScriptError,
normalizeAll (tests) {
// if we have an uncaught error then slice out
// all of the tests and suites and just generate
// a single test since we received an uncaught
// error prior to processing any of mocha's tests
// which could have occurred in a separate support file
if (_uncaughtFn) {
_runner.suite.suites = []
_runner.suite.tests = []
// create a runnable to associate for the failure
mocha.createRootTest('An uncaught error was detected outside of a test', _uncaughtFn)
}
return normalizeAll(
_runner.suite,
tests,
setTestsById,
setTests,
onRunnable,
onLogsById,
getTestId,
getHookId,
)
},
run (fn) {
if (_startTime == null) {
_startTime = moment().toJSON()
}
_runnerListeners(_runner, Cypress, _emissions, getTestById, getTest, setTest, getHookId, getTestFromHookOrFindTest)
return _runner.run((failures) => {
// if we happen to make it all the way through
// the run, then just set _runner.stopped to true here
_runner.stopped = true
// remove all the listeners
// so no more events fire
// since a test failure may 'leak' after a run completes
_runner.removeAllListeners()
// TODO this functions is not correctly
// synchronized with the 'end' event that
// we manage because of uncaught hook errors
if (fn) {
return fn(failures, getTestResults(_tests))
}
})
},
onRunnableRun (runnableRun, runnable, args) {
// extract out the next(fn) which mocha uses to
// move to the next runnable - this will be our async seam
const _next = args[0]
const test = getTest() || getTestFromRunnable(runnable)
// if there's no test, this is likely a rouge before/after hook
// that should not have run, so skip this runnable
if (!test) {
return _next()
}
// closure for calculating the actual
// runtime of a runnables fn exection duration
// and also the run of the runnable:after:run:async event
let lifecycleStart
let wallClockStartedAt = null
let wallClockEnd = null
let fnDurationStart = null
let fnDurationEnd = null
let afterFnDurationStart = null
let afterFnDurationEnd = null
// when this is a hook, capture the real start
// date so we can calculate our test's duration
// including all of its hooks
wallClockStartedAt = new Date()
if (!test.wallClockStartedAt) {
// if we don't have lifecycle timings yet
lifecycleStart = wallClockStartedAt
}
if (test.wallClockStartedAt == null) {
test.wallClockStartedAt = wallClockStartedAt
}
// if this isnt a hook, then the name is 'test'
const hookName = runnable.type === 'hook' ? getHookName(runnable) : 'test'
// set hook id to hook id or test id
const hookId = runnable.type === 'hook' ? runnable.hookId : runnable.id
// if we haven't yet fired this event for this test
// that means that we need to reset the previous state
// of cy - since we now have a new 'test' and all of the
// associated _runnables will share this state
if (!fired(TEST_BEFORE_RUN_EVENT, test)) {
fire(TEST_BEFORE_RUN_EVENT, test, Cypress)