-
Notifications
You must be signed in to change notification settings - Fork 1
/
ntt.js
118 lines (106 loc) · 2.47 KB
/
ntt.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
// Node Tiny Tests module. https://github.com/hit9/ntt
// MIT. Copyright (c) Chao Wang <hit9@icloud.com>
//
// ntt('unit', function(test) {
// test('case1', function(done) {
// done();
// });
// test('case2', function(done) {
// setTimeout(function() {
// done();
// }, 1000)
// });
// });
var domain = require('domain');
var util = require('util');
// exports
module.exports = function(name, fn) {
units.push([name, fn]);
units.next();
};
var config = exports.confg = {
style: true, // if output with style
bail: false, // bail on first failure
};
// internals
var fails = 0;
var tests = [];
var units = [];
var log = console.log;
function styled(s, name) {
if (config.style) {
var code = util.inspect.colors[name][0];
return util.format('\033[%dm%s\033[0m', code, s);
}
return s;
}
function execute(name, fn, cb) {
var d = domain.create();
d.on('error', function(e) {
// on fail
var msg;
if (e.stack) {
msg = e.stack.trim()
.split(/\n/)
.map(function(s) {
return s.trim();
}).join('\n ');
} else {
msg = e.toString();
}
// logging
var flag = styled('-', 'red');
var nam_ = styled(name, 'red');
var msg_ = styled(msg, 'grey');
log(' %s %s \n %s', flag, nam_, msg_);
fails ++;
tests.pending = false;
tests.next();
});
d.run(function() {
return fn(cb);
});
}
tests.pending = false;
tests.next = function() {
if (!tests.pending) {
var test = tests.shift();
if (!test) {
units.pending = false;
units.next();
return;
}
if (config.bail && fails > 0)
return;
var start = new Date();
tests.pending = true;
execute(test[0], test[1], function() {
// on pass
// logging
var flag = styled('+', 'green');
var nam_ = styled(test[0], 'green');
var span = styled((new Date() - start).toFixed(2) + 'ms',
'grey');
log(' %s %s %s', flag, nam_, span);
// roll next
tests.pending = false;
tests.next();
});
}
};
units.pending = false;
units.next = function() {
if (!units.pending) {
var unit = units.shift();
if (!unit) {
log(styled('=> %d fails', fails? 'red' : 'green'), fails);
process.exit(fails);
}
log('# %s', styled(unit[0], 'bold'));
units.pending = true;
unit[1](function(name, fn) {
tests.push([name, fn]);
process.nextTick(tests.next);
});
}
};