-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
api.js
309 lines (255 loc) · 7.66 KB
/
api.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
'use strict';
var EventEmitter = require('events').EventEmitter;
var path = require('path');
var util = require('util');
var fs = require('fs');
var flatten = require('arr-flatten');
var Promise = require('bluebird');
var figures = require('figures');
var globby = require('globby');
var chalk = require('chalk');
var objectAssign = require('object-assign');
var commonPathPrefix = require('common-path-prefix');
var resolveCwd = require('resolve-cwd');
var uniqueTempDir = require('unique-temp-dir');
var findCacheDir = require('find-cache-dir');
var slash = require('slash');
var AvaError = require('./lib/ava-error');
var fork = require('./lib/fork');
var formatter = require('./lib/enhance-assert').formatter();
var CachingPrecompiler = require('./lib/caching-precompiler');
function Api(options) {
if (!(this instanceof Api)) {
throw new TypeError('Class constructor Api cannot be invoked without \'new\'');
}
EventEmitter.call(this);
this.options = options || {};
this.options.require = (this.options.require || []).map(resolveCwd);
this.options.match = this.options.match || [];
this.excludePatterns = [
'!**/node_modules/**',
'!**/fixtures/**',
'!**/helpers/**'
];
Object.keys(Api.prototype).forEach(function (key) {
this[key] = this[key].bind(this);
}, this);
this._reset();
}
util.inherits(Api, EventEmitter);
module.exports = Api;
Api.prototype._reset = function () {
this.rejectionCount = 0;
this.exceptionCount = 0;
this.passCount = 0;
this.skipCount = 0;
this.todoCount = 0;
this.failCount = 0;
this.fileCount = 0;
this.testCount = 0;
this.hasExclusive = false;
this.errors = [];
this.stats = [];
this.tests = [];
this.base = '';
};
Api.prototype._runFile = function (file) {
var options = objectAssign({}, this.options, {
precompiled: this.precompiler.generateHashForFile(file)
});
return fork(file, options)
.on('teardown', this._handleTeardown)
.on('stats', this._handleStats)
.on('test', this._handleTest)
.on('unhandledRejections', this._handleRejections)
.on('uncaughtException', this._handleExceptions)
.on('stdout', this._handleOutput.bind(this, 'stdout'))
.on('stderr', this._handleOutput.bind(this, 'stderr'));
};
Api.prototype._handleOutput = function (channel, data) {
this.emit(channel, data);
};
Api.prototype._handleRejections = function (data) {
this.rejectionCount += data.rejections.length;
data.rejections.forEach(function (err) {
err.type = 'rejection';
err.file = data.file;
this.emit('error', err);
this.errors.push(err);
}, this);
};
Api.prototype._handleExceptions = function (data) {
this.exceptionCount++;
var err = data.exception;
err.type = 'exception';
err.file = data.file;
this.emit('error', err);
this.errors.push(err);
};
Api.prototype._handleTeardown = function (data) {
this.emit('dependencies', data.file, data.dependencies);
};
Api.prototype._handleStats = function (stats) {
if (this.hasExclusive && !stats.hasExclusive) {
return;
}
if (!this.hasExclusive && stats.hasExclusive) {
this.hasExclusive = true;
this.testCount = 0;
}
this.testCount += stats.testCount;
};
Api.prototype._handleTest = function (test) {
test.title = this._prefixTitle(test.file) + test.title;
if (test.error) {
if (test.error.powerAssertContext) {
var message = formatter(test.error.powerAssertContext);
if (test.error.originalMessage) {
message = test.error.originalMessage + ' ' + message;
}
test.error.message = message;
}
if (test.error.name !== 'AssertionError') {
test.error.message = 'failed with "' + test.error.message + '"';
}
this.errors.push(test);
}
this.emit('test', test);
};
Api.prototype._prefixTitle = function (file) {
if (this.fileCount === 1 && !this.options.explicitTitles) {
return '';
}
var separator = ' ' + chalk.gray.dim(figures.pointerSmall) + ' ';
var prefix = path.relative('.', file)
.replace(this.base, '')
.replace(/\.spec/, '')
.replace(/\.test/, '')
.replace(/test\-/g, '')
.replace(/\.js$/, '')
.split(path.sep)
.join(separator);
if (prefix.length > 0) {
prefix += separator;
}
return prefix;
};
Api.prototype.run = function (files) {
var self = this;
this._reset();
return handlePaths(files, this.excludePatterns)
.map(function (file) {
return path.resolve(file);
})
.then(function (files) {
if (files.length === 0) {
self._handleExceptions({
exception: new AvaError('Couldn\'t find any files to test'),
file: undefined
});
return [];
}
var cacheEnabled = self.options.cacheEnabled !== false;
var cacheDir = (cacheEnabled && findCacheDir({name: 'ava', files: files})) ||
uniqueTempDir();
self.options.cacheDir = cacheDir;
self.precompiler = new CachingPrecompiler(cacheDir, self.options.babelConfig);
self.fileCount = files.length;
self.base = path.relative('.', commonPathPrefix(files)) + path.sep;
var tests = files.map(self._runFile);
// receive test count from all files and then run the tests
var unreportedFiles = self.fileCount;
return new Promise(function (resolve) {
function run() {
if (self.options.match.length > 0 && !self.hasExclusive) {
self._handleExceptions({
exception: new AvaError('Couldn\'t find any matching tests'),
file: undefined
});
tests.forEach(function (test) {
// No tests will be run so tear down the child processes.
test.send('teardown');
});
resolve([]);
return;
}
self.emit('ready');
var method = self.options.serial ? 'mapSeries' : 'map';
var options = {
runOnlyExclusive: self.hasExclusive
};
resolve(Promise[method](files, function (file, index) {
return tests[index].run(options).catch(function (err) {
// The test failed catastrophically. Flag it up as an
// exception, then return an empty result. Other tests may
// continue to run.
self._handleExceptions({
exception: err,
file: file
});
return {
stats: {passCount: 0, skipCount: 0, todoCount: 0, failCount: 0},
tests: []
};
});
}));
}
tests.forEach(function (test) {
var tried = false;
function tryRun() {
if (!tried) {
unreportedFiles--;
if (unreportedFiles === 0) {
run();
}
}
}
test.on('stats', tryRun);
test.catch(tryRun);
});
});
})
.then(function (results) {
// assemble stats from all tests
self.stats = results.map(function (result) {
return result.stats;
});
self.tests = results.map(function (result) {
return result.tests;
});
self.tests = flatten(self.tests);
self.passCount = sum(self.stats, 'passCount');
self.skipCount = sum(self.stats, 'skipCount');
self.todoCount = sum(self.stats, 'todoCount');
self.failCount = sum(self.stats, 'failCount');
});
};
function handlePaths(files, excludePatterns) {
// convert pinkie-promise to Bluebird promise
files = Promise.resolve(globby(files.concat(excludePatterns)));
return files
.map(function (file) {
if (fs.statSync(file).isDirectory()) {
var pattern = path.join(file, '**', '*.js');
if (process.platform === 'win32') {
// Always use / in patterns, harmonizing matching across platforms.
pattern = slash(pattern);
}
return handlePaths([pattern], excludePatterns);
}
// globby returns slashes even on Windows. Normalize here so the file
// paths are consistently platform-accurate as tests are run.
return path.normalize(file);
})
.then(flatten)
.filter(function (file) {
return path.extname(file) === '.js' && path.basename(file)[0] !== '_';
});
}
function sum(arr, key) {
var result = 0;
arr.forEach(function (item) {
result += item[key];
});
return result;
}