ava 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,152 @@
1
+ 'use strict';
2
+ var path = require('path');
3
+ var chalk = require('chalk');
4
+ var figures = require('figures');
5
+ var convertSourceMap = require('convert-source-map');
6
+ var objectAssign = require('object-assign');
7
+ var semver = require('semver');
8
+ var colors = require('./colors');
9
+
10
+ function validate(conf) {
11
+ if (conf === undefined || conf === null) {
12
+ conf = 'default';
13
+ }
14
+
15
+ // check for valid babel config shortcuts (can be either "default" or "inherit")
16
+ var isValidShortcut = conf === 'default' || conf === 'inherit';
17
+
18
+ if (!conf || (typeof conf === 'string' && !isValidShortcut)) {
19
+ var message = colors.error(figures.cross);
20
+ message += ' Unexpected Babel configuration for AVA. ';
21
+ message += 'See ' + chalk.underline('https://github.com/avajs/ava#es2015-support') + ' for allowed values.';
22
+
23
+ throw new Error(message);
24
+ }
25
+
26
+ return conf;
27
+ }
28
+
29
+ function lazy(initFn) {
30
+ var initialized = false;
31
+ var value;
32
+
33
+ return function () {
34
+ if (!initialized) {
35
+ initialized = true;
36
+ value = initFn();
37
+ }
38
+
39
+ return value;
40
+ };
41
+ }
42
+
43
+ var defaultPresets = lazy(function () {
44
+ var esPreset = semver.satisfies(process.version, '>=4') ?
45
+ 'babel-preset-es2015-node4' :
46
+ 'babel-preset-es2015';
47
+
48
+ return [
49
+ require('babel-preset-stage-2'),
50
+ require(esPreset) // eslint-disable-line import/no-dynamic-require
51
+ ];
52
+ });
53
+
54
+ var rewritePlugin = lazy(function () {
55
+ var wrapListener = require('babel-plugin-detective/wrap-listener');
56
+
57
+ return wrapListener(rewriteBabelRuntimePaths, 'rewrite-runtime', {
58
+ generated: true,
59
+ require: true,
60
+ import: true
61
+ });
62
+ });
63
+
64
+ function rewriteBabelRuntimePaths(path) {
65
+ var isBabelPath = /^babel-runtime[\\/]?/.test(path.node.value);
66
+
67
+ if (path.isLiteral() && isBabelPath) {
68
+ path.node.value = require.resolve(path.node.value);
69
+ }
70
+ }
71
+
72
+ var espowerPlugin = lazy(function () {
73
+ var babel = require('babel-core');
74
+ var createEspowerPlugin = require('babel-plugin-espower/create');
75
+
76
+ // initialize power-assert
77
+ return createEspowerPlugin(babel, {
78
+ embedAst: true,
79
+ patterns: require('./enhance-assert').PATTERNS
80
+ });
81
+ });
82
+
83
+ var defaultPlugins = lazy(function () {
84
+ return [
85
+ require('babel-plugin-ava-throws-helper'),
86
+ rewritePlugin(),
87
+ require('babel-plugin-transform-runtime')
88
+ ];
89
+ });
90
+
91
+ function build(babelConfig, powerAssert, filePath, code) {
92
+ babelConfig = validate(babelConfig);
93
+
94
+ var options;
95
+
96
+ if (babelConfig === 'default') {
97
+ options = {
98
+ babelrc: false,
99
+ presets: defaultPresets()
100
+ };
101
+ } else if (babelConfig === 'inherit') {
102
+ options = {
103
+ babelrc: true
104
+ };
105
+ } else {
106
+ options = {
107
+ babelrc: false
108
+ };
109
+
110
+ objectAssign(options, babelConfig);
111
+ }
112
+
113
+ var sourceMap = getSourceMap(filePath, code);
114
+
115
+ objectAssign(options, {
116
+ inputSourceMap: sourceMap,
117
+ filename: filePath,
118
+ sourceMaps: true,
119
+ ast: false
120
+ });
121
+
122
+ options.plugins = (options.plugins || [])
123
+ .concat(powerAssert ? espowerPlugin() : [])
124
+ .concat(defaultPlugins());
125
+
126
+ return options;
127
+ }
128
+
129
+ function getSourceMap(filePath, code) {
130
+ var sourceMap = convertSourceMap.fromSource(code);
131
+
132
+ if (!sourceMap) {
133
+ var dirPath = path.dirname(filePath);
134
+
135
+ sourceMap = convertSourceMap.fromMapFileSource(code, dirPath);
136
+ }
137
+
138
+ if (sourceMap) {
139
+ sourceMap = sourceMap.toObject();
140
+ }
141
+
142
+ return sourceMap;
143
+ }
144
+
145
+ module.exports = {
146
+ validate: validate,
147
+ build: build,
148
+ pluginPackages: [
149
+ require.resolve('babel-core/package.json'),
150
+ require.resolve('babel-plugin-espower/package.json')
151
+ ]
152
+ };
@@ -2,6 +2,25 @@
2
2
  var StackUtils = require('stack-utils');
3
3
  var debug = require('debug')('ava');
4
4
 
5
+ //-----------
6
+ // embedded `clean-stack` module (because it requires Node.js 4)
7
+ var extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/;
8
+ var pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/babel-polyfill\/.*)?\w+)\.js:\d+:\d+)|native)/;
9
+
10
+ var cleanStack = function (stack) {
11
+ return stack.replace(/\\/g, '/').split('\n').filter(function (x) {
12
+ var pathMatches = x.match(extractPathRegex);
13
+ if (pathMatches === null || !pathMatches[1]) {
14
+ return true;
15
+ }
16
+
17
+ return !pathRegex.test(pathMatches[1]);
18
+ }).filter(function (x) {
19
+ return x.trim() !== '';
20
+ }).join('\n');
21
+ };
22
+ //-----------
23
+
5
24
  function indent(str) {
6
25
  return ' ' + str;
7
26
  }
@@ -25,6 +44,10 @@ module.exports = function (stack) {
25
44
  return '';
26
45
  }
27
46
 
47
+ // workaround for https://github.com/tapjs/stack-utils/issues/14
48
+ // TODO: fix it in `stack-utils`
49
+ stack = cleanStack(stack);
50
+
28
51
  var title = stack.split('\n')[0];
29
52
  var lines = stackUtils
30
53
  .clean(stack)
@@ -3,24 +3,25 @@ var path = require('path');
3
3
  var fs = require('fs');
4
4
  var convertSourceMap = require('convert-source-map');
5
5
  var cachingTransform = require('caching-transform');
6
- var objectAssign = require('object-assign');
6
+ var packageHash = require('package-hash');
7
7
  var stripBom = require('strip-bom');
8
+ var autoBind = require('auto-bind');
8
9
  var md5Hex = require('md5-hex');
9
- var packageHash = require('package-hash');
10
- var enhanceAssert = require('./enhance-assert');
10
+ var babelConfigHelper = require('./babel-config');
11
11
 
12
- function CachingPrecompiler(cacheDirPath, babelConfig) {
12
+ function CachingPrecompiler(options) {
13
13
  if (!(this instanceof CachingPrecompiler)) {
14
14
  throw new TypeError('Class constructor CachingPrecompiler cannot be invoked without \'new\'');
15
15
  }
16
16
 
17
- this.babelConfig = babelConfig || 'default';
18
- this.cacheDirPath = cacheDirPath;
19
- this.fileHashes = {};
17
+ autoBind(this);
20
18
 
21
- Object.keys(CachingPrecompiler.prototype).forEach(function (name) {
22
- this[name] = this[name].bind(this);
23
- }, this);
19
+ options = options || {};
20
+
21
+ this.babelConfig = babelConfigHelper.validate(options.babel);
22
+ this.cacheDirPath = options.path;
23
+ this.powerAssert = Boolean(options.powerAssert);
24
+ this.fileHashes = {};
24
25
 
25
26
  this.transform = this._createTransform();
26
27
  }
@@ -38,52 +39,24 @@ CachingPrecompiler.prototype.precompileFile = function (filePath) {
38
39
  };
39
40
 
40
41
  // conditionally called by caching-transform when precompiling is required
41
- CachingPrecompiler.prototype._factory = function () {
42
- this._init();
43
-
44
- return this._transform;
45
- };
46
-
47
42
  CachingPrecompiler.prototype._init = function () {
48
43
  this.babel = require('babel-core');
49
44
 
50
- this.defaultPresets = [
51
- require('babel-preset-stage-2'),
52
- require('babel-preset-es2015')
53
- ];
54
-
55
- var transformRuntime = require('babel-plugin-transform-runtime');
56
- var throwsHelper = require('babel-plugin-ava-throws-helper');
57
- var rewriteBabelPaths = this._createRewritePlugin();
58
- var powerAssert = this._createEspowerPlugin();
59
-
60
- this.defaultPlugins = [
61
- powerAssert,
62
- throwsHelper,
63
- rewriteBabelPaths,
64
- transformRuntime
65
- ];
45
+ return this._transform;
66
46
  };
67
47
 
68
48
  CachingPrecompiler.prototype._transform = function (code, filePath, hash) {
69
49
  code = code.toString();
70
50
 
71
- var options = this._buildOptions(filePath, code);
51
+ var options = babelConfigHelper.build(this.babelConfig, this.powerAssert, filePath, code);
72
52
  var result = this.babel.transform(code, options);
73
53
 
74
54
  // save source map
75
55
  var mapPath = path.join(this.cacheDirPath, hash + '.js.map');
76
56
  fs.writeFileSync(mapPath, JSON.stringify(result.map));
77
57
 
78
- // When loading the test file, test workers intercept the require call and
79
- // load the cached code instead. Libraries like nyc may also be intercepting
80
- // require calls, however they won't know that different code was loaded.
81
- // They may then attempt to resolve a source map from the original file
82
- // location.
83
- //
84
- // Add a source map file comment to the cached code. The file path is
85
- // relative from the directory of the original file to where the source map
86
- // is cached. This will allow the source map to be resolved.
58
+ // append source map comment to transformed code
59
+ // so that other libraries (like nyc) can find the source map
87
60
  var dirPath = path.dirname(filePath);
88
61
  var relativeMapPath = path.relative(dirPath, mapPath);
89
62
  var comment = convertSourceMap.generateMapFileComment(relativeMapPath);
@@ -91,83 +64,19 @@ CachingPrecompiler.prototype._transform = function (code, filePath, hash) {
91
64
  return result.code + '\n' + comment;
92
65
  };
93
66
 
94
- CachingPrecompiler.prototype._buildOptions = function (filePath, code) {
95
- var options = {babelrc: false};
96
-
97
- if (this.babelConfig === 'default') {
98
- objectAssign(options, {presets: this.defaultPresets});
99
- } else if (this.babelConfig === 'inherit') {
100
- objectAssign(options, {babelrc: true});
101
- } else {
102
- objectAssign(options, this.babelConfig);
103
- }
104
-
105
- var sourceMap = this._getSourceMap(filePath, code);
106
-
107
- objectAssign(options, {
108
- inputSourceMap: sourceMap,
109
- filename: filePath,
110
- sourceMaps: true,
111
- ast: false
112
- });
113
-
114
- options.plugins = (options.plugins || []).concat(this.defaultPlugins);
115
-
116
- return options;
117
- };
118
-
119
- CachingPrecompiler.prototype._getSourceMap = function (filePath, code) {
120
- var sourceMap = convertSourceMap.fromSource(code);
121
-
122
- if (!sourceMap) {
123
- var dirPath = path.dirname(filePath);
124
-
125
- sourceMap = convertSourceMap.fromMapFileSource(code, dirPath);
126
- }
127
-
128
- if (sourceMap) {
129
- sourceMap = sourceMap.toObject();
130
- }
131
-
132
- return sourceMap;
133
- };
134
-
135
- CachingPrecompiler.prototype._createRewritePlugin = function () {
136
- var wrapListener = require('babel-plugin-detective/wrap-listener');
137
-
138
- return wrapListener(this._rewriteBabelRuntimePaths, 'rewrite-runtime', {
139
- generated: true,
140
- require: true,
141
- import: true
142
- });
143
- };
144
-
145
- CachingPrecompiler.prototype._rewriteBabelRuntimePaths = function (path) {
146
- var isBabelPath = /^babel-runtime[\\\/]?/.test(path.node.value);
147
-
148
- if (path.isLiteral() && isBabelPath) {
149
- path.node.value = require.resolve(path.node.value);
150
- }
151
- };
152
-
153
- CachingPrecompiler.prototype._createEspowerPlugin = function () {
154
- var createEspowerPlugin = require('babel-plugin-espower/create');
67
+ CachingPrecompiler.prototype._createTransform = function () {
68
+ var pluginPackages = babelConfigHelper.pluginPackages;
69
+ var avaPackage = require.resolve('../package.json');
70
+ var packages = [avaPackage].concat(pluginPackages);
155
71
 
156
- // initialize power-assert
157
- return createEspowerPlugin(this.babel, {
158
- patterns: enhanceAssert.PATTERNS
159
- });
160
- };
72
+ var majorNodeVersion = process.version.split('.')[0];
73
+ var babelConfig = JSON.stringify(this.babelConfig);
74
+ var packageSalt = babelConfig + majorNodeVersion;
161
75
 
162
- CachingPrecompiler.prototype._createTransform = function () {
163
- var salt = packageHash.sync([
164
- require.resolve('../package.json'),
165
- require.resolve('babel-core/package.json'),
166
- require.resolve('babel-plugin-espower/package.json')
167
- ], JSON.stringify(this.babelConfig));
76
+ var salt = packageHash.sync(packages, packageSalt);
168
77
 
169
78
  return cachingTransform({
170
- factory: this._factory,
79
+ factory: this._init,
171
80
  cacheDir: this.cacheDirPath,
172
81
  hash: this._generateHash,
173
82
  salt: salt,
package/lib/cli.js ADDED
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+ var path = require('path');
3
+ var updateNotifier = require('update-notifier');
4
+ var figures = require('figures');
5
+ var arrify = require('arrify');
6
+ var meow = require('meow');
7
+ var Promise = require('bluebird');
8
+ var pkgConf = require('pkg-conf');
9
+ var isCi = require('is-ci');
10
+ var hasFlag = require('has-flag');
11
+ var Api = require('../api');
12
+ var colors = require('./colors');
13
+ var verboseReporter = require('./reporters/verbose');
14
+ var miniReporter = require('./reporters/mini');
15
+ var tapReporter = require('./reporters/tap');
16
+ var Logger = require('./logger');
17
+ var Watcher = require('./watcher');
18
+ var babelConfig = require('./babel-config');
19
+
20
+ // Bluebird specific
21
+ Promise.longStackTraces();
22
+
23
+ exports.run = function () {
24
+ var conf = pkgConf.sync('ava');
25
+
26
+ var filepath = pkgConf.filepath(conf);
27
+ var pkgDir = filepath === null ? process.cwd() : path.dirname(filepath);
28
+
29
+ var cli = meow([
30
+ 'Usage',
31
+ ' ava [<file|directory|glob> ...]',
32
+ '',
33
+ 'Options',
34
+ ' --init Add AVA to your project',
35
+ ' --fail-fast Stop after first test failure',
36
+ ' --serial, -s Run tests serially',
37
+ ' --tap, -t Generate TAP output',
38
+ ' --verbose, -v Enable verbose output',
39
+ ' --no-cache Disable the transpiler cache',
40
+ ' --no-power-assert Disable Power Assert',
41
+ ' --match, -m Only run tests with matching title (Can be repeated)',
42
+ ' --watch, -w Re-run tests when tests and source files change',
43
+ ' --source, -S Pattern to match source files so tests can be re-run (Can be repeated)',
44
+ ' --timeout, -T Set global timeout',
45
+ ' --concurrency, -c Maximum number of test files running at the same time (EXPERIMENTAL)',
46
+ '',
47
+ 'Examples',
48
+ ' ava',
49
+ ' ava test.js test2.js',
50
+ ' ava test-*.js',
51
+ ' ava test',
52
+ ' ava --init',
53
+ ' ava --init foo.js',
54
+ '',
55
+ 'Default patterns when no arguments:',
56
+ 'test.js test-*.js test/**/*.js **/__tests__/**/*.js **/*.test.js'
57
+ ], {
58
+ string: [
59
+ '_',
60
+ 'timeout',
61
+ 'source',
62
+ 'match',
63
+ 'concurrency'
64
+ ],
65
+ boolean: [
66
+ 'fail-fast',
67
+ 'verbose',
68
+ 'serial',
69
+ 'tap',
70
+ 'watch'
71
+ ],
72
+ default: conf,
73
+ alias: {
74
+ t: 'tap',
75
+ v: 'verbose',
76
+ s: 'serial',
77
+ m: 'match',
78
+ w: 'watch',
79
+ S: 'source',
80
+ T: 'timeout',
81
+ c: 'concurrency'
82
+ }
83
+ });
84
+
85
+ updateNotifier({pkg: cli.pkg}).notify();
86
+
87
+ if (cli.flags.init) {
88
+ require('ava-init')();
89
+ return;
90
+ }
91
+
92
+ if (
93
+ ((hasFlag('--watch') || hasFlag('-w')) && (hasFlag('--tap') || hasFlag('-t'))) ||
94
+ (conf.watch && conf.tap)
95
+ ) {
96
+ throw new Error(colors.error(figures.cross) + ' The TAP reporter is not available when using watch mode.');
97
+ }
98
+
99
+ if (hasFlag('--require') || hasFlag('-r')) {
100
+ throw new Error(colors.error(figures.cross) + ' The --require and -r flags are deprecated. Requirements should be configured in package.json - see documentation.');
101
+ }
102
+
103
+ var api = new Api({
104
+ failFast: cli.flags.failFast,
105
+ serial: cli.flags.serial,
106
+ require: arrify(conf.require),
107
+ cacheEnabled: cli.flags.cache !== false,
108
+ powerAssert: cli.flags.powerAssert !== false,
109
+ explicitTitles: cli.flags.watch,
110
+ match: arrify(cli.flags.match),
111
+ babelConfig: babelConfig.validate(conf.babel),
112
+ resolveTestsFrom: cli.input.length === 0 ? pkgDir : process.cwd(),
113
+ pkgDir: pkgDir,
114
+ timeout: cli.flags.timeout,
115
+ concurrency: cli.flags.concurrency ? parseInt(cli.flags.concurrency, 10) : 0
116
+ });
117
+
118
+ var reporter;
119
+
120
+ if (cli.flags.tap && !cli.flags.watch) {
121
+ reporter = tapReporter();
122
+ } else if (cli.flags.verbose || isCi) {
123
+ reporter = verboseReporter();
124
+ } else {
125
+ reporter = miniReporter({watching: cli.flags.watch});
126
+ }
127
+
128
+ reporter.api = api;
129
+ var logger = new Logger(reporter);
130
+
131
+ logger.start();
132
+
133
+ api.on('test-run', function (runStatus) {
134
+ reporter.api = runStatus;
135
+ runStatus.on('test', logger.test);
136
+ runStatus.on('error', logger.unhandledError);
137
+
138
+ runStatus.on('stdout', logger.stdout);
139
+ runStatus.on('stderr', logger.stderr);
140
+ });
141
+
142
+ var files = cli.input.length ? cli.input : arrify(conf.files);
143
+
144
+ if (cli.flags.watch) {
145
+ try {
146
+ var watcher = new Watcher(logger, api, files, arrify(cli.flags.source));
147
+ watcher.observeStdin(process.stdin);
148
+ } catch (err) {
149
+ if (err.name === 'AvaError') {
150
+ // An AvaError may be thrown if chokidar is not installed. Log it nicely.
151
+ console.error(' ' + colors.error(figures.cross) + ' ' + err.message);
152
+ logger.exit(1);
153
+ } else {
154
+ // Rethrow so it becomes an uncaught exception.
155
+ throw err;
156
+ }
157
+ }
158
+ } else {
159
+ api.run(files)
160
+ .then(function (runStatus) {
161
+ logger.finish(runStatus);
162
+ logger.exit(runStatus.failCount > 0 || runStatus.rejectionCount > 0 || runStatus.exceptionCount > 0 ? 1 : 0);
163
+ })
164
+ .catch(function (err) {
165
+ // Don't swallow exceptions. Note that any expected error should already
166
+ // have been logged.
167
+ setImmediate(function () {
168
+ throw err;
169
+ });
170
+ });
171
+ }
172
+ };
package/lib/colors.js CHANGED
@@ -2,10 +2,12 @@
2
2
  var chalk = require('chalk');
3
3
 
4
4
  module.exports = {
5
+ title: chalk.white,
5
6
  error: chalk.red,
6
7
  skip: chalk.yellow,
7
8
  todo: chalk.blue,
8
9
  pass: chalk.green,
9
10
  duration: chalk.gray.dim,
11
+ errorStack: chalk.gray,
10
12
  stack: chalk.red
11
13
  };
package/lib/concurrent.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
  var Promise = require('bluebird');
3
3
  var isPromise = require('is-promise');
4
+ var autoBind = require('auto-bind');
4
5
  var AvaError = require('./ava-error');
5
6
 
6
7
  function noop() {}
@@ -22,9 +23,7 @@ function Concurrent(tests, bail) {
22
23
  this.tests = tests;
23
24
  this.bail = bail || false;
24
25
 
25
- Object.keys(Concurrent.prototype).forEach(function (key) {
26
- this[key] = this[key].bind(this);
27
- }, this);
26
+ autoBind(this);
28
27
  }
29
28
 
30
29
  Concurrent.prototype.run = function () {
@@ -13,6 +13,7 @@ module.exports.PATTERNS = [
13
13
  't.deepEqual(value, expected, [message])',
14
14
  't.notDeepEqual(value, expected, [message])',
15
15
  't.regex(contents, regex, [message])',
16
+ 't.notRegex(contents, regex, [message])',
16
17
  // deprecated apis
17
18
  't.ok(value, [message])',
18
19
  't.notOk(value, [message])',
@@ -30,6 +31,7 @@ module.exports.NON_ENHANCED_PATTERNS = [
30
31
 
31
32
  function enhanceAssert(opts) {
32
33
  var empower = require('empower-core');
34
+
33
35
  var enhanced = empower(
34
36
  opts.assert,
35
37
  {
@@ -46,14 +48,21 @@ function enhanceAssert(opts) {
46
48
  }
47
49
 
48
50
  function formatter() {
49
- var powerAssertFormatter = require('power-assert-formatter');
50
- var powerAssertRenderers = require('power-assert-renderers');
51
+ var createFormatter = require('power-assert-context-formatter');
52
+ var SuccinctRenderer = require('power-assert-renderer-succinct');
53
+ var AssertionRenderer = require('power-assert-renderer-assertion');
51
54
 
52
- return powerAssertFormatter({
53
- maxDepth: 3,
55
+ return createFormatter({
54
56
  renderers: [
55
- powerAssertRenderers.AssertionRenderer,
56
- powerAssertRenderers.SuccinctRenderer
57
+ {
58
+ ctor: AssertionRenderer
59
+ },
60
+ {
61
+ ctor: SuccinctRenderer,
62
+ options: {
63
+ maxDepth: 3
64
+ }
65
+ }
57
66
  ]
58
67
  });
59
68
  }