1 | const Mocha = require('mocha')
|
2 | const log = require('debug')('rocha')
|
3 |
|
4 | const e2e = require('debug')('rocha:e2e')
|
5 | const la = require('lazy-ass')
|
6 | const is = require('check-more-types')
|
7 | const chalk = require('chalk')
|
8 |
|
9 | const order = require('./src/order-of-tests')
|
10 | const cache = require('./src/order-cache')
|
11 | la(is.object(cache), 'missing test order object')
|
12 |
|
13 | function rocha (options) {
|
14 | options = options || {}
|
15 |
|
16 | const mocha = options.mocha || new Mocha()
|
17 |
|
18 | log('starting rocha with options')
|
19 | log(JSON.stringify(options, null, 2))
|
20 |
|
21 | var specFilenames = options.spec
|
22 | if (!specFilenames) {
|
23 | console.error('Missing spec file pattern')
|
24 | process.exit(-1)
|
25 | }
|
26 |
|
27 | if (typeof specFilenames === 'string') {
|
28 | specFilenames = [specFilenames]
|
29 | }
|
30 |
|
31 | specFilenames.forEach(mocha.addFile.bind(mocha))
|
32 |
|
33 | mocha.suite.beforeAll(function () {
|
34 | const cachedOrder = cache.load()
|
35 | if (cachedOrder) {
|
36 | log('reordering specs like last time')
|
37 | order.set(mocha.suite, cachedOrder)
|
38 | } else {
|
39 | const randomOrder = order.shuffle(mocha.suite)
|
40 | const names = order.collect(randomOrder)
|
41 | e2e('shuffled names:')
|
42 | e2e('%j', names)
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | const testNames = order.collect(mocha.suite)
|
49 | cache.save(testNames)
|
50 | })
|
51 |
|
52 | mocha.run(function (failures) {
|
53 | process.on('exit', function () {
|
54 | if (failures === 0) {
|
55 | cache.clear()
|
56 | } else {
|
57 | const filename = cache.filename()
|
58 | la(is.unemptyString(filename), 'missing save filename')
|
59 | console.error('Failed tests order saved in', chalk.yellow(filename))
|
60 | console.error('If you run Rocha again, the same failed test order will be used')
|
61 | }
|
62 | process.exit(failures)
|
63 | })
|
64 | })
|
65 | }
|
66 |
|
67 | module.exports = rocha
|