-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathsuite.js
98 lines (86 loc) · 2 KB
/
suite.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
'use strict'
const async = require('async')
class Test {
constructor (name, cb) {
this.name = name
this.action = cb
this.timeout = 5000
}
run (cb) {
try {
this._run(cb)
} catch (e) {
cb(e)
}
}
_run (cb) {
if (!this.action) {
console.log(`${this.name} skipped`)
return cb()
}
if (!this.action.length) {
const result = this.action.call(this)
if (!(result || 0).then) {
return cb()
}
result
.then(() => cb())
.catch(err => cb(err || new Error('Unhandled promise rejection')))
} else {
this.action.call(this, cb)
}
}
}
class Suite {
constructor (name) {
console.log('')
this._queue = async.queue(this.run.bind(this), 1)
this._queue.drain = () => { }
}
run (test, cb) {
process.stdout.write(' ' + test.name + ' ')
if (!test.action) {
process.stdout.write('? - SKIPPED\n')
return cb()
}
const tid = setTimeout(() => {
const err = Error(`test: ${test.name} did not complete withint ${test.timeout}ms`)
console.log('\n' + err.stack)
process.exit(-1)
}, test.timeout)
test.run((err) => {
clearTimeout(tid)
if (err) {
process.stdout.write(`FAILED!\n\n${err.stack}\n`)
process.exit(-1)
} else {
process.stdout.write('✔\n')
cb()
}
})
}
test (name, cb) {
const test = new Test(name, cb)
this._queue.push(test)
}
/**
* Run an async test that can return a Promise. If the Promise resolves
* successfully then the test will pass. If the Promise rejects with an
* error then the test will be considered failed.
*/
testAsync (name, action) {
const test = new Test(name, cb => {
Promise.resolve()
.then(action)
.then(() => cb(null), cb)
})
this._queue.push(test)
}
}
process.on('unhandledRejection', (e) => {
setImmediate(() => {
console.error('Unhandled promise rejection')
throw e
})
})
module.exports = Suite