-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
runner.ts
1826 lines (1416 loc) · 50.6 KB
/
runner.ts
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 */
import _ from 'lodash'
import dayjs from 'dayjs'
import Promise from 'bluebird'
import { LogUtils } from './log'
import $utils from './utils'
import $errUtils from './error_utils'
import $stackUtils from './stack_utils'
import { getResolvedTestConfigOverride } from '../cy/testConfigOverrides'
import debugFn from 'debug'
import type { Emissions } from '@packages/types'
const mochaCtxKeysRe = /^(_runnable|test)$/
const betweenQuotesRe = /\"(.+?)\"/
const HOOKS = ['beforeAll', 'beforeEach', 'afterEach', 'afterAll'] as const
const TEST_BEFORE_RUN_ASYNC_EVENT = 'runner:test:before:run:async'
// event fired before hooks and test execution
const TEST_BEFORE_RUN_EVENT = 'runner:test:before:run'
const TEST_AFTER_RUN_EVENT = 'runner:test:after:run'
const TEST_AFTER_RUN_ASYNC_EVENT = 'runner:runnable:after:run:async'
const RUNNABLE_LOGS = ['routes', 'agents', 'commands', 'hooks'] as const
const RUNNABLE_PROPS = [
'_testConfig', 'id', 'order', 'title', '_titlePath', 'root', 'hookName', 'hookId', 'err', 'state', 'failedFromHookId', 'body', 'speed', 'type', 'duration', 'wallClockStartedAt', 'wallClockDuration', 'timings', 'file', 'originalTitle', 'invocationDetails', 'final', 'currentRetry', 'retries', '_slow',
] as const
const debug = debugFn('cypress:driver:runner')
const debugErrors = debugFn('cypress:driver:errors')
const RUNNER_EVENTS = [
TEST_BEFORE_RUN_ASYNC_EVENT,
TEST_BEFORE_RUN_EVENT,
TEST_AFTER_RUN_EVENT,
TEST_AFTER_RUN_ASYNC_EVENT,
] as const
export type HandlerType = 'error' | 'unhandledrejection'
const duration = (before: Date, after: Date) => {
return Number(before) - Number(after)
}
const fire = (event: typeof RUNNER_EVENTS[number], runnable, Cypress) => {
debug('fire: %o', { event })
if (runnable._fired == null) {
runnable._fired = {}
}
runnable._fired[event] = true
// don't fire anything again if we are skipped
if (runnable._ALREADY_RAN) {
return
}
return Cypress.action(event, wrap(runnable), runnable)
}
const fired = (event: typeof RUNNER_EVENTS[number], runnable) => {
return !!(runnable._fired && runnable._fired[event])
}
const testBeforeRunAsync = (test, Cypress) => {
return Promise.try(() => {
if (!fired(TEST_BEFORE_RUN_ASYNC_EVENT, test)) {
return fire(TEST_BEFORE_RUN_ASYNC_EVENT, test, Cypress)
}
})
}
const runnableAfterRunAsync = (runnable, Cypress) => {
runnable.clearTimeout()
return Promise.try(() => {
// NOTE: other events we do not fire more than once, but this needed to change for test-retries
return fire(TEST_AFTER_RUN_ASYNC_EVENT, runnable, Cypress)
})
}
const testAfterRun = (test, Cypress) => {
test.clearTimeout()
if (!fired(TEST_AFTER_RUN_EVENT, test)) {
setWallClockDuration(test)
try {
fire(TEST_AFTER_RUN_EVENT, test, Cypress)
} catch (e) {
// if the test:after:run listener throws it's likely spec code
// Since the test status has already been emitted this can't affect the test status.
// Let's just log the error to console
// TODO: revisit when we handle uncaught exceptions/rejections between tests
// eslint-disable-next-line no-console
console.error(e)
}
// 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
}
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 = duration(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): Record<string, any> | null => {
return $utils.reduceProps(runnable, RUNNABLE_PROPS)
}
// Reduce runnable down to its props and collections.
// Sent to the Reporter to populate command log
// and send to the Dashboard when in record mode.
const wrapAll = (runnable): Record<string, any> => {
return _.extend(
{},
$utils.reduceProps(runnable, RUNNABLE_PROPS),
$utils.reduceProps(runnable, RUNNABLE_LOGS),
)
}
const condenseHooks = (runnable, getHookId) => {
runnable._condensedHooks = true
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: any = _.identity) => {
for (const test of suite.tests) {
if (fn(test)) {
return test
}
}
for (const childSuite of suite.suites) {
const test = findTestInSuite(childSuite, fn)
if (test) {
return test
}
}
}
const findSuiteInSuite = (suite, fn: any = _.identity) => {
if (fn(suite)) {
return suite
}
for (const childSuite of suite.suites) {
const foundSuite = findSuiteInSuite(childSuite, fn)
if (foundSuite) {
return foundSuite
}
}
}
const suiteHasTest = (suite, testId) => {
return findTestInSuite(suite, (test) => test.id === testId)
}
const suiteHasSuite = (suite, suiteId) => {
return findSuiteInSuite(suite, (s) => s.id === suiteId)
}
// same as findTestInSuite but iterates backwards
const findLastTestInSuite = (suite, fn: any = _.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: any[] = []
suite.eachTest((testRunnable) => {
// 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
const test = getTestById(testRunnable.id)
if (test) {
return tests.push(test)
}
return
})
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<any, any[]>(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.id === _.get(_.last(tests), 'id')
}
const isRootSuite = (suite) => {
return suite && suite.root
}
const overrideRunnerHook = (Cypress, _runner, getTestById, getTest, setTest, getTests) => {
// bail if our _runner doesn't 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 = $utils.monkeypatchBefore(_runner.hook, function (name, fn) {
if (name !== 'afterAll' && name !== 'afterEach') {
return
}
const test = getTest()
const allTests = getTests()
let shouldFireTestAfterRun = () => false
switch (name) {
case 'afterEach':
shouldFireTestAfterRun = () => {
// find all of the grep'd tests which share
// the same parent suite as our current test
const tests = getAllSiblingTests(test.parent, getTestById)
if (this.suite.root) {
_runner._shouldBufferSuiteEnd = true
// make sure this test isnt the last test overall but also
// isnt the last test in our filtered parent suite's tests array
if (test.final === false || (test !== _.last(allTests)) && (test !== _.last(tests))) {
return true
}
}
return false
}
break
case 'afterAll':
shouldFireTestAfterRun = () => {
// find all of the filtered allTests which share
// the same parent suite as our current _test
// const t = getTest()
if (test) {
const siblings = getAllSiblingTests(test.parent, getTestById)
const testIsActuallyInSuite = suiteHasTest(this.suite, test.id)
// we ensure the test actually belongs to this suite.
// the test may not belong to the suite when a suite is skipped
// due to already being run on top navigation
// https://github.com/cypress-io/cypress/issues/9026
if (!testIsActuallyInSuite) {
return false
}
// 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(test, allTests)) ||
(!isLastSuite(this.suite, allTests) && lastTestThatWillRunInSuite(test, siblings))
) {
return true
}
}
return false
}
break
default:
break
}
const newArgs = [name, $utils.monkeypatchBefore(fn,
function () {
if (!shouldFireTestAfterRun()) return
setTest(null)
if (test.final !== false) {
test.final = true
if (test.state === 'passed') {
Cypress.action('runner:pass', wrap(test))
}
Cypress.action('runner:test:end', wrap(test))
_runner._shouldBufferSuiteEnd = false
_runner._onTestAfterRun.map((fn) => {
return fn()
})
_runner._onTestAfterRun = []
}
testAfterRun(test, Cypress)
})]
return newArgs
})
}
const getTestResults = (tests) => {
return _.map(tests, (test) => {
const obj: Record<string, any> = _.pick(test, 'title', 'id', 'duration', 'state')
// 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, getRunnableId, getHookId, getOnlyTestId, getOnlySuiteId, createEmptyOnlyTest) => {
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
// unless we're using studio to add to the root suite
if (!hasTests && getOnlySuiteId() !== 'r1') {
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: Record<string, any> = {}
const normalizedSuite = normalize(suite, tests, initialTests, getRunnableId, getHookId, getOnlyTestId, getOnlySuiteId, createEmptyOnlyTest)
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)
}
// generate the diff of the config after spec has been executed
// e.g. config changes via Cypress.config('...')
normalizedSuite.runtimeConfig = {}
_.map(Cypress.config(), (v, key) => {
if (_.isEqual(v, Cypress.originalConfig[key])) {
return null
}
normalizedSuite.runtimeConfig[key] = v
return
})
return normalizedSuite
}
const normalize = (runnable, tests, initialTests, getRunnableId, getHookId, getOnlyTestId, getOnlySuiteId, createEmptyOnlyTest) => {
const normalizeRunnable = (runnable) => {
if (!runnable.id) {
runnable.id = getRunnableId()
}
// tests have a type of 'test' whereas suites do not have a type property
if (runnable.type == null) {
runnable.type = 'suite'
}
// if we have a runnable in the initial state
// then merge in existing properties into the runnable
const i = initialTests[runnable.id]
let prevAttempts
if (i) {
prevAttempts = []
if (i.prevAttempts) {
prevAttempts = _.map(i.prevAttempts, wrapAll)
}
_.extend(runnable, i)
}
// merge all hooks into single array
runnable.hooks = condenseHooks(runnable, getHookId)
const wrappedRunnable = wrapAll(runnable)
if (runnable.type === 'test') {
const cfg = getResolvedTestConfigOverride(runnable)
if (_.size(cfg)) {
runnable._testConfig = cfg
wrappedRunnable._testConfig = cfg
}
wrappedRunnable._titlePath = runnable.titlePath()
}
if (prevAttempts) {
wrappedRunnable.prevAttempts = prevAttempts
}
return wrappedRunnable
}
const push = (test) => {
return tests[test.id] != null ? tests[test.id] : (tests[test.id] = test)
}
const onlyIdMode = () => {
return !!getOnlyTestId() || !!getOnlySuiteId()
}
const suiteHasOnlyId = (suite) => {
return suiteHasTest(suite, getOnlyTestId()) || suiteHasSuite(suite, getOnlySuiteId())
}
const normalizedRunnable = normalizeRunnable(runnable)
if (getOnlySuiteId() && runnable.id === getOnlySuiteId()) {
createEmptyOnlyTest(runnable)
}
if ((runnable.type !== 'suite') || !hasOnly(runnable)) {
if (runnable.type === 'test' && (!getOnlyTestId() || runnable.id === getOnlyTestId())) {
push(runnable)
}
const runnableTests = runnable.tests
const runnableSuites = runnable.suites
if (onlyIdMode()) {
runnable.tests = []
runnable._onlyTests = []
runnable.suites = []
runnable._onlySuites = []
runnable._afterAll = []
runnable._afterEach = []
}
// recursively iterate and normalize all other _runnables
_.each({ tests: runnableTests, suites: runnableSuites }, (_runnables, type) => {
if (runnable[type]) {
return normalizedRunnable[type] = _.compact(_.map(_runnables, (childRunnable) => {
const normalizedChild = normalize(childRunnable, tests, initialTests, getRunnableId, getHookId, getOnlyTestId, getOnlySuiteId, createEmptyOnlyTest)
if (type === 'tests' && onlyIdMode()) {
if (normalizedChild.id === getOnlyTestId()) {
runnable.tests = [childRunnable]
runnable._onlyTests = [childRunnable]
return normalizedChild
}
return null
}
if (type === 'suites' && onlyIdMode()) {
if (suiteHasOnlyId(childRunnable)) {
runnable.suites = [childRunnable]
runnable._onlySuites = [childRunnable]
return normalizedChild
}
return null
}
return normalizedChild
}))
}
return null
})
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) {
const suiteOnlyTests = suite._onlyTests
if (getOnlyTestId()) {
suite.tests = []
suite._onlyTests = []
suite._afterAll = []
suite._afterEach = []
} else {
suite.tests = suite._onlyTests
}
normalizedSuite.tests = _.compact(_.map(suiteOnlyTests, (test) => {
const normalizedTest = normalizeRunnable(test)
if (getOnlyTestId()) {
if (normalizedTest.id === getOnlyTestId()) {
suite.tests = [test]
suite._onlyTests = [test]
push(test)
return normalizedTest
}
return null
}
push(test)
return normalizedTest
}))
suite.suites = []
normalizedSuite.suites = []
} else {
suite.tests = []
normalizedSuite.tests = []
_.each(suite._onlySuites, (onlySuite) => {
const normalizedOnlySuite = normalizeRunnable(onlySuite)
if (hasOnly(onlySuite)) {
filterOnly(normalizedOnlySuite, onlySuite)
}
})
const suiteSuites = suite.suites
suite.suites = []
normalizedSuite.suites = _.compact(_.map(suiteSuites, (childSuite) => {
const normalizedChildSuite = normalize(childSuite, tests, initialTests, getRunnableId, getHookId, getOnlyTestId, getOnlySuiteId, createEmptyOnlyTest)
if ((suite._onlySuites.indexOf(childSuite) !== -1) || filterOnly(normalizedChildSuite, childSuite)) {
if (onlyIdMode()) {
if (suiteHasOnlyId(childSuite)) {
suite.suites.push(childSuite)
return normalizedChildSuite
}
return null
}
suite.suites.push(childSuite)
return normalizedChildSuite
}
return null
}))
}
return suite.tests.length || suite.suites.length
}
filterOnly(normalizedRunnable, runnable)
return normalizedRunnable
}
const hookFailed = (hook, err, 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)
setHookFailureProps(test, hook, err)
if (hook.alreadyEmittedMocha) {
test.alreadyEmittedMocha = true
} else {
return Cypress.action('runner:test:end', wrap(test))
}
}
const setHookFailureProps = (test, hook, err) => {
err = $errUtils.wrapErr(err)
const hookName = getHookName(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
}
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, 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._shouldBufferSuiteEnd = false
_runner._onTestAfterRun = []
_runner.on('suite end', (suite) => {
const handleSuiteEnd = () => {
// cleanup our suite + its hooks
forceGc(suite)
eachHookInSuite(suite, forceGc)
if (_emissions.ended[suite.id]) {
return
}
_emissions.ended[suite.id] = true
Cypress.action('runner:suite:end', wrap(suite))
}
if (_runner._shouldBufferSuiteEnd) {
_runner._onTestAfterRun = _runner._onTestAfterRun.concat([handleSuiteEnd])
return
}
return handleSuiteEnd()
})
_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
}
let test = getTest()
if (test && test.state !== 'pending') {
// if the current test isn't within the hook's suite
// then don't run the hook https://github.com/cypress-io/cypress/issues/17705
if (!suiteHasTest(hook.parent, test.id)) {
return
}
} else {
// https://github.com/cypress-io/cypress/issues/9162
// In https://github.com/cypress-io/cypress/issues/8113, getTest() call was removed to handle skip() properly.
// But it caused tests to hang when there's a failure in before().
// That's why getTest() is revived and checks if the state is 'pending'.
// 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
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
// NOTE: we wait to send 'test end' until after hooks run
// return Cypress.action('runner:test:end', wrap(test))
})
// Ignore the 'pass' event since we emit our own
// _runner.on('pass', (test) => {
// return Cypress.action('runner:pass', wrap(test))
// })
/**
* Mocha retry event is only fired in Mocha version 6+
* https://github.com/mochajs/mocha/commit/2a76dd7589e4a1ed14dd2a33ab89f182e4c4a050
*/
_runner.on('retry', (test, err) => {
test.err = $errUtils.wrapErr(err)
Cypress.action('runner:retry', wrap(test), test.err)
})
// 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) {
test.final = true
return fire(TEST_AFTER_RUN_EVENT, test, Cypress)
}
})
_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)
const test = getTest() || getTestFromHookOrFindTest(runnable)
const unsupportedPlugin = $errUtils.getUnsupportedPlugin(runnable)
// append a friendly message to the error indicating
// we're skipping the remaining tests in this suite
const errMessage = $errUtils.errByPath('uncaught.error_in_hook', {
parentTitle,
hookName,
retries: test._retries,
unsupportedPlugin,
errMessage: err.message,
}).message
if (unsupportedPlugin) {
err = $errUtils.modifyErrMsg(err, errMessage, () => errMessage)
} else {
err = $errUtils.appendErrMsg(err, errMessage)
}