-
Notifications
You must be signed in to change notification settings - Fork 8
/
testing.js
574 lines (491 loc) · 15.9 KB
/
testing.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
var assert = require('assert')
, path = require('path')
, fs = require('fs')
;
/* Runs an object of tests. Each property in the object should be a
* test. A test is just a method.
*
* Available configuration options:
*
* + parallel: boolean, for whether or not the tests should be run in parallel
* or serially. Obviously, parallel is faster, but it doesn't give
* as accurate error reporting
* + testName: string or array of strings, the name of a test to be ran
* + name: string, the name of the suite being ran
*
* Plus, there are options for the following events. These should be functions.
* See API.md for a description of these events.
*
* + onSuiteStart
* + onSuiteDone
* + onTestStart
* + onTestDone
* + onPrematureExit
*/
exports.runSuite = function(obj, options) {
// make sure options exists
options = options || {};
// keep track of internal state
var suite =
{ startTime: new Date()
, todo: exports.getTestsFromObject(obj, options.testName)
, queue: []
, errored: []
, results: []
}
if (suite.todo.length < 1) { return suiteFinished(); }
// TODO also pass the number of tests?
if (options.onSuiteStart) { options.onSuiteStart(options.name); }
process.on('uncaughtException', errorHandler);
process.on('exit', exitHandler);
// start the test chain
startNextTest();
/******** functions ********/
function startNextTest() {
var curTest = suite.todo.shift();
if (!curTest) {
return;
}
suite.queue.push(curTest);
curTest.startTime = new Date(); // for calculating how long it takes
curTest.func = Array.isArray(curTest.func) ? curTest.func : [curTest.func];
curTest.progress = 0;
curTest.numAssertions = 0; // assertions made
curTest.obj = // object that is passed to the tests
{ get uncaughtExceptionHandler() { return curTest.UEHandler; }
, set uncaughtExceptionHandler(h) {
if (options.parallel) {
throw new Error("Cannot set an 'uncaughtExceptionHandler' when running tests in parallel");
}
curTest.UEHandler = h;
}
, finish: function() { testProgressed(curTest); }
};
addAssertionFunctions(curTest);
if (options.onTestStart) {
// notify listeners
options.onTestStart(curTest.name);
}
try {
// actually run the test
// TODO pass finish function?
curTest.func[curTest.progress](curTest.obj);
}
catch(err) {
errorHandler(err, curTest);
}
// if we are supposed to run the tests in parallel, start the next test
if (options.parallel) {
process.nextTick(function() {
startNextTest();
});
}
}
function testProgressed(test, problem) {
if (!test.failure && problem) {
test.failure = problem;
}
if (test.errors) {
test.errors.forEach(function(e) {
e.candidates.splice(e.candidates.indexOf(test), 1);
});
delete test.errors;
}
test.progress++;
if (test.func.length == 1) {
testFinished(test);
}
else if (test.func.length == 3) {
if (test.progress == 1) {
if (test.failure) {
// if there was a failure skip the test function and just run teardown
test.progress++;
}
try {
test.func[test.progress](test.obj);
}
catch(err) {
errorHandler(err, test);
}
}
else if (test.progress == 2) {
try {
test.func[test.progress](test.obj);
}
catch(err) {
errorHandler(err, test);
}
}
else {
testFinished(test);
}
}
else {
console.log('Oops, tests need to be 3-tuples [setup, function teardown] or 1-tuples [function]');
}
}
function testFinished(test) {
// if they specified the number of assertions, make sure they match up
if (test.obj.numAssertions && test.obj.numAssertions != test.numAssertions) {
test.failure = new assert.AssertionError(
{ message: 'Wrong number of assertions: ' + test.numAssertions +
' != ' + test.obj.numAssertions
, actual: test.numAssertions
, expected: test.obj.numAssertions
});
}
// calculate the time it took
test.duration = test.duration || (new Date() - test.startTime);
// remove it from the list of tests that have been started
suite.queue.splice(suite.queue.indexOf(test), 1);
// clean up properties that are no longer needed
delete test.obj;
delete test.progress;
delete test.func;
delete test.startTime;
if (test.failure) { delete test.numAssertions; }
suite.results.push(test);
if (options.onTestDone) {
// notify listener
options.onTestDone(test);
}
process.nextTick(function() {
// if we have no more tests to start and none still running, we're done
if (suite.todo.length == 0 && suite.queue.length == 0) {
suiteFinished();
}
// check to see if we can isolate any errors
checkErrors();
startNextTest();
});
}
// listens for uncaught errors and keeps track of which tests they could be from
function errorHandler(err, test) {
// assertions throw an error, but we can't just catch those errors, because
// then the rest of the test will run. So, we don't catch it and it ends up
// here. When that happens just finish the test.
if (err instanceof assert.AssertionError && err.TEST) {
var t = err.TEST;
delete err.TEST;
return testProgressed(t, err);
}
// We want to allow tests to supply a function for handling uncaught errors,
// and since all uncaught errors come here, this is where we have to handle
// them.
// (you can only handle uncaught errors when not in parallel mode)
if (!options.parallel && suite.queue[0].UEHandler) {
// an error could possibly be thrown in the UncaughtExceptionHandler, in
// this case we do not want to call the handler again, so we move it
suite.queue[0].UEHandlerUsed = suite.queue[0].UEHandler;
delete suite.queue[0].UEHandler;
try {
// run the UncaughtExceptionHandler
suite.queue[0].UEHandlerUsed(err);
return;
}
catch(e) {
// we had an error, just run our error handler function on this error
// again. We don't have to worry about it triggering the uncaught
// exception handler again because we moved it just a second ago
return errorHandler(e, test);
}
}
if (test) {
// shortcut if we know the test that caused this error
return testProgressed(test, err);
}
var summary =
{ error: err
, candidates: suite.queue.slice()
, endTime: new Date()
};
summary.candidates.forEach(function(t) {
// add this error to the list of errors a test is a candidate for
if (t.errors) {
t.errors.push(summary);
}
else {
t.errors = [summary];
}
});
suite.errored.push(summary);
// check to see if we can isolate any errors
checkErrors();
}
function checkErrors() {
// any time a test finishes, we could learn more about errors that had
// multiple candidates, so loop through and see if anything has changed
for(var i = 0; i < suite.errored.length; i++) {
var err = suite.errored[i];
if (err.error.message == 'E teardown') {
testAsyncE = err;
}
// if there is only one candidate then we can finish that test
if (err.candidates.length == 1) {
suite.errored.splice(i,1);
i = -1;
var test = err.candidates[0];
test.duration = err.endTime - test.startTime;
delete err.endTime;
testProgressed(test, err.error);
}
}
// if the number of errors we've found equals the number of tests still
// running then we know that the errors must match up with the tests, so
// finish each of the tests.
if (suite.errored.length && suite.errored.length == suite.queue.length) {
var errs = suite.errored.map(function(d) { return d.error; });
suite.errored = [];
suite.queue.slice().forEach(function(t) {
testProgressed(t, errs);
});
}
}
function exitHandler() {
if (suite.queue.length > 0) {
if (options.onPrematureExit) {
options.onPrematureExit(suite.queue.map(function(t) { return t.name; }));
}
}
}
// clean up method which notifies all listeners of what happened
function suiteFinished() {
if (suite.finished) {
return;
}
suite.finished = true;
process.removeListener('uncaughtException', errorHandler);
process.removeListener('exit', exitHandler);
if (options.onSuiteDone) {
var result =
{ name: options.name
, duration: new Date() - suite.startTime
, tests: suite.results
, numFailures: 0
, numSuccesses: 0
};
suite.results.forEach(function(r) {
result[r.failure ? 'numFailures' : 'numSuccesses']++;
});
options.onSuiteDone(result);
}
}
}
/* runFiles runs an array, where each element in the array can be a file name or
* a directory name module.
*
* Available configuration options:
*
* + parallel: boolean, for whether or not the tests should be run in parallel
* or serially. Obviously, parallel is faster, but it doesn't give
* as accurate error reporting
* + testName: string or array of strings, the name(s) of a test to be ran
* + suiteName: string or array of strings, the name(s) of a suite to be ran
*
* Plus, there are options for the following events. These should be functions.
*
* + onStart
* + onDone
* + onSuiteStart
* + onSuiteDone
* + onTestStart
* + onTestDone
* + onPrematureExit
*/
exports.runFiles = function(list, options) {
// make sure options exist
options = options || {};
var suites
, startTime
, allResults = []
, index = 0
;
exports.expandFiles(list, options.suiteName, startSuites);
function startSuites(loaded) {
suites = loaded;
if (options.onStart) {
options.onStart(suites.length);
}
startTime = new Date();
runNextSuite();
}
function runNextSuite() {
var item = suites[index];
index++;
if (!item) {
if (options.onDone) {
options.onDone(allResults, new Date()-startTime);
}
return;
}
var name = item.name;
var suite = item.suite = require(item.path);
var itemOpts =
{ parallel: options.parallel
, testName: options.testName
, name: name
, onSuiteStart: options.onSuiteStart
, onSuiteDone: function(results) {
allResults.push(results);
if (options.onSuiteDone) {
options.onSuiteDone(results);
}
process.nextTick(function() {
runNextSuite();
});
}
, onTestStart: options.onTestStart
, onTestDone: options.onTestDone
, onPrematureExit: options.onPrematureExit
}
exports.runSuite(suite, itemOpts);
}
}
// expandFiles takes a file name, directory name or an array composed of any
// combination of either.
// It recursively searches through directories for test files.
// It gets an absolute path for each file (original file names might be relative)
// returns an array of file objects which look like:
// { name: 'the passed in path'
// , path: 'the absolute path to the file with the extension removed (for requiring)'
// , index: index in the array, later on this is useful for when passing around
// suites
// }
exports.expandFiles = function(list, suiteNames, cb) {
if (typeof cb === 'undefined') {
cb = suiteNames;
suiteNames = null;
}
if (!Array.isArray(list)) {
list = [list];
}
if (suiteNames && !Array.isArray(suiteNames)) {
suiteNames = [suiteNames];
}
if (suiteNames && suiteNames.length === 0) {
suiteNames = null;
}
list.sort();
var suites = []
, explicit = []
;
for(var i = 0; i < list.length; i++) {
explicit.push(list[i]);
}
processNextItem();
function foundSuite(suite) {
if (suites.some(function(el) { return el.path == suite.path })) {
// we've already added this file
return;
}
if (suiteNames && suiteNames.indexOf(suite.name) < 0) {
// this file doesn't match the specified suiteNames
return;
}
suite.index = suites.length;
suites.push(suite);
}
function processNextItem() {
if( list.length == 0 ) {
return cb(suites);
}
var item = list.shift();
// must be a filename
var file = item;
if (file.charAt(0) !== '/') {
file = path.join(process.cwd(),file);
}
fs.stat(file, function(err, stat) {
if (err) {
if (err.errno == 2) {
console.log('No such file or directory: '+file);
console.log('');
processNextItem();
return;
}
else {
throw err;
}
}
if (stat.isFile()) {
// if they explicitly requested this file make sure to grab it
// regardless of its name, otherwise when recursing into directories
// only grab files that start with "test-" and end with ".js"
if (explicit.indexOf(item) >= 0 || path.basename(file).match(/^test-.*\.js$/)) {
var p = path.join(path.dirname(file), path.basename(file, path.extname(file)));
foundSuite({name: item, path: p});
}
processNextItem();
}
else if (stat.isDirectory()) {
fs.readdir(file, function(err, files) {
if (err) {
throw err;
}
for(var i = 0; i < files.length; i++) {
// don't look at hidden files of directores
if (files[i].match(/^[^.]/)) {
list.push(path.join(item,files[i]));
}
}
processNextItem();
});
}
});
}
}
// store the assertion functions available to tests
var assertionFunctions = {};
// this allows people to add custom assertion functions.
//
// An assertion function needs to throw an error that is `instanceof
// assert.AssertionError` so it is possible to distinguish between runtime
// errors and failures. I recommend the `assert.fail` method.
exports.registerAssertion = function(name, func) {
assertionFunctions[name] = func;
}
// register the default functions
var assertionModuleAssertions = [ 'ok', 'equal', 'notEqual', 'deepEqual', 'notDeepEqual', 'strictEqual', 'notStrictEqual', 'throws', 'doesNotThrow', 'ifError'];
assertionModuleAssertions.forEach(function(funcName) {
exports.registerAssertion(funcName, assert[funcName]);
});
// used when tests are ran, adds the assertion functions to a test object, but
// binds them to that particular test so assertions are properly associated with
// the right test.
function addAssertionFunctions(test) {
for (var funcName in assertionFunctions) {
(function() {
var fn = funcName;
test.obj[fn] = function() {
try {
assertionFunctions[fn].apply(null, arguments);
test.numAssertions++;
}
catch(err) {
if (err instanceof assert.AssertionError) {
err.TEST = test;
}
throw err;
}
}
})();
};
}
// this is a recursive function because suites can hold sub suites
exports.getTestsFromObject = function(o, filter, namespace) {
var tests = [];
for(var key in o) {
var displayName = (namespace ? namespace+' \u2192 ' : '') + key;
if (typeof o[key] == 'function' || Array.isArray(o[key])) {
// if the testName option is set, then only add the test to the todo
// list if the name matches
if (!filter || filter.indexOf(key) >= 0) {
tests.push({name: displayName , func: o[key]});
}
}
else {
tests = tests.concat(exports.getTestsFromObject(o[key], filter, displayName));
}
}
return tests;
}