ava 0.16.0 → 0.18.2

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.
package/lib/assert.js CHANGED
@@ -1,85 +1,88 @@
1
1
  'use strict';
2
- var util = require('util');
3
- var assert = require('core-assert');
4
- var deepEqual = require('not-so-shallow');
5
- var observableToPromise = require('observable-to-promise');
6
- var isObservable = require('is-observable');
7
- var isPromise = require('is-promise');
8
-
9
- var x = module.exports;
2
+ const assert = require('core-assert');
3
+ const deepEqual = require('lodash.isequal');
4
+ const observableToPromise = require('observable-to-promise');
5
+ const indentString = require('indent-string');
6
+ const isObservable = require('is-observable');
7
+ const isPromise = require('is-promise');
8
+ const jestSnapshot = require('jest-snapshot');
9
+ const snapshotState = require('./snapshot-state');
10
+
11
+ const x = module.exports;
12
+ const noop = () => {};
10
13
 
11
14
  Object.defineProperty(x, 'AssertionError', {value: assert.AssertionError});
12
15
 
13
- function noop() {}
14
-
15
16
  function create(val, expected, operator, msg, fn) {
16
17
  return {
17
18
  actual: val,
18
- expected: expected,
19
- message: msg,
20
- operator: operator,
19
+ expected,
20
+ message: msg || ' ',
21
+ operator,
21
22
  stackStartFunction: fn
22
23
  };
23
24
  }
24
25
 
25
26
  function test(ok, opts) {
26
27
  if (!ok) {
27
- throw new assert.AssertionError(opts);
28
+ const err = new assert.AssertionError(opts);
29
+ err.showOutput = ['fail', 'throws', 'notThrows'].indexOf(err.operator) === -1;
30
+ throw err;
28
31
  }
29
32
  }
30
33
 
31
- x.pass = function (msg) {
34
+ x.pass = msg => {
32
35
  test(true, create(true, true, 'pass', msg, x.pass));
33
36
  };
34
37
 
35
- x.fail = function (msg) {
38
+ x.fail = msg => {
36
39
  msg = msg || 'Test failed via t.fail()';
37
40
  test(false, create(false, false, 'fail', msg, x.fail));
38
41
  };
39
42
 
40
- x.truthy = function (val, msg) {
43
+ x.truthy = (val, msg) => {
41
44
  test(val, create(val, true, '==', msg, x.truthy));
42
45
  };
43
46
 
44
- x.falsy = function (val, msg) {
47
+ x.falsy = (val, msg) => {
45
48
  test(!val, create(val, false, '==', msg, x.falsy));
46
49
  };
47
50
 
48
- x.true = function (val, msg) {
51
+ x.true = (val, msg) => {
49
52
  test(val === true, create(val, true, '===', msg, x.true));
50
53
  };
51
54
 
52
- x.false = function (val, msg) {
55
+ x.false = (val, msg) => {
53
56
  test(val === false, create(val, false, '===', msg, x.false));
54
57
  };
55
58
 
56
- x.is = function (val, expected, msg) {
59
+ x.is = (val, expected, msg) => {
57
60
  test(val === expected, create(val, expected, '===', msg, x.is));
58
61
  };
59
62
 
60
- x.not = function (val, expected, msg) {
63
+ x.not = (val, expected, msg) => {
61
64
  test(val !== expected, create(val, expected, '!==', msg, x.not));
62
65
  };
63
66
 
64
- x.deepEqual = function (val, expected, msg) {
67
+ x.deepEqual = (val, expected, msg) => {
65
68
  test(deepEqual(val, expected), create(val, expected, '===', msg, x.deepEqual));
66
69
  };
67
70
 
68
- x.notDeepEqual = function (val, expected, msg) {
71
+ x.notDeepEqual = (val, expected, msg) => {
69
72
  test(!deepEqual(val, expected), create(val, expected, '!==', msg, x.notDeepEqual));
70
73
  };
71
74
 
72
- x.throws = function (fn, err, msg) {
75
+ x.throws = (fn, err, msg) => {
73
76
  if (isObservable(fn)) {
74
77
  fn = observableToPromise(fn);
75
78
  }
76
79
 
77
80
  if (isPromise(fn)) {
78
81
  return fn
79
- .then(function () {
82
+ .then(() => {
80
83
  x.throws(noop, err, msg);
81
- }, function (fnErr) {
82
- return x.throws(function () {
84
+ }, fnErr => {
85
+ return x.throws(() => {
83
86
  throw fnErr;
84
87
  }, err, msg);
85
88
  });
@@ -91,15 +94,13 @@ x.throws = function (fn, err, msg) {
91
94
 
92
95
  try {
93
96
  if (typeof err === 'string') {
94
- var errMsg = err;
95
- err = function (err) {
96
- return err.message === errMsg;
97
- };
97
+ const errMsg = err;
98
+ err = err => err.message === errMsg;
98
99
  }
99
100
 
100
- var result;
101
+ let result;
101
102
 
102
- assert.throws(function () {
103
+ assert.throws(() => {
103
104
  try {
104
105
  fn();
105
106
  } catch (err) {
@@ -110,19 +111,19 @@ x.throws = function (fn, err, msg) {
110
111
 
111
112
  return result;
112
113
  } catch (err) {
113
- test(false, create(err.actual, err.expected, err.operator, err.message, x.throws));
114
+ test(false, create(err.actual, err.expected, 'throws', err.message, x.throws));
114
115
  }
115
116
  };
116
117
 
117
- x.notThrows = function (fn, msg) {
118
+ x.notThrows = (fn, msg) => {
118
119
  if (isObservable(fn)) {
119
120
  fn = observableToPromise(fn);
120
121
  }
121
122
 
122
123
  if (isPromise(fn)) {
123
124
  return fn
124
- .catch(function (err) {
125
- x.notThrows(function () {
125
+ .catch(err => {
126
+ x.notThrows(() => {
126
127
  throw err;
127
128
  }, msg);
128
129
  });
@@ -135,31 +136,64 @@ x.notThrows = function (fn, msg) {
135
136
  try {
136
137
  assert.doesNotThrow(fn, msg);
137
138
  } catch (err) {
138
- test(false, create(err.actual, err.expected, err.operator, err.message, x.notThrows));
139
+ test(false, create(err.actual, err.expected, 'notThrows', err.message, x.notThrows));
139
140
  }
140
141
  };
141
142
 
142
- x.regex = function (contents, regex, msg) {
143
+ x.regex = (contents, regex, msg) => {
143
144
  test(regex.test(contents), create(regex, contents, '===', msg, x.regex));
144
145
  };
145
146
 
146
- x.notRegex = function (contents, regex, msg) {
147
+ x.notRegex = (contents, regex, msg) => {
147
148
  test(!regex.test(contents), create(regex, contents, '!==', msg, x.notRegex));
148
149
  };
149
150
 
150
- x.ifError = x.error = function (err, msg) {
151
+ x.ifError = (err, msg) => {
151
152
  test(!err, create(err, 'Error', '!==', msg, x.ifError));
152
153
  };
153
154
 
154
- /*
155
- * deprecated APIs
156
- */
157
- x.doesNotThrow = util.deprecate(x.notThrows, getDeprecationNotice('doesNotThrow()', 'notThrows()'));
158
- x.ok = util.deprecate(x.truthy, getDeprecationNotice('ok()', 'truthy()'));
159
- x.notOk = util.deprecate(x.falsy, getDeprecationNotice('notOk()', 'falsy()'));
160
- x.same = util.deprecate(x.deepEqual, getDeprecationNotice('same()', 'deepEqual()'));
161
- x.notSame = util.deprecate(x.notDeepEqual, getDeprecationNotice('notSame()', 'notDeepEqual()'));
155
+ x._snapshot = function (tree, optionalMessage, match, snapshotStateGetter) {
156
+ // Set defaults - this allows tests to mock deps easily
157
+ const toMatchSnapshot = match || jestSnapshot.toMatchSnapshot;
158
+ const getState = snapshotStateGetter || snapshotState.get;
162
159
 
163
- function getDeprecationNotice(oldApi, newApi) {
164
- return 'DEPRECATION NOTICE: ' + oldApi + ' has been renamed to ' + newApi + ' and will eventually be removed. See https://github.com/avajs/ava-codemods to help upgrade your codebase automatically.';
165
- }
160
+ const state = getState();
161
+
162
+ const context = {
163
+ dontThrow() {},
164
+ currentTestName: this.title,
165
+ snapshotState: state
166
+ };
167
+
168
+ // Symbols can't be serialized and saved in a snapshot, that's why tree
169
+ // is saved in the `__ava_react_jsx` prop, so that JSX can be detected later
170
+ const serializedTree = tree.$$typeof === Symbol.for('react.test.json') ? {__ava_react_jsx: tree} : tree; // eslint-disable-line camelcase
171
+ const result = toMatchSnapshot.call(context, JSON.stringify(serializedTree));
172
+
173
+ let message = 'Please check your code or --update-snapshots';
174
+
175
+ if (optionalMessage) {
176
+ message += '\n\n' + indentString(optionalMessage, 2);
177
+ }
178
+
179
+ state.save();
180
+
181
+ let expected;
182
+
183
+ if (result.expected) {
184
+ // JSON in a snapshot is surrounded with `"`, because jest-snapshot
185
+ // serializes snapshot values too, so it ends up double JSON encoded
186
+ expected = JSON.parse(result.expected.slice(1).slice(0, -1));
187
+ // Define a `$$typeof` symbol, so that pretty-format detects it as React tree
188
+ if (expected.__ava_react_jsx) { // eslint-disable-line camelcase
189
+ expected = expected.__ava_react_jsx; // eslint-disable-line camelcase
190
+ Object.defineProperty(expected, '$$typeof', {value: Symbol.for('react.test.json')});
191
+ }
192
+ }
193
+
194
+ test(result.pass, create(tree, expected, 'snapshot', message, x.snapshot));
195
+ };
196
+
197
+ x.snapshot = function (tree, optionalMessage) {
198
+ x._snapshot.call(this, tree, optionalMessage);
199
+ };
package/lib/ava-error.js CHANGED
@@ -1,14 +1,10 @@
1
1
  'use strict';
2
2
 
3
- function AvaError(message) {
4
- if (!(this instanceof AvaError)) {
5
- throw new TypeError('Class constructor AvaError cannot be invoked without \'new\'');
3
+ class AvaError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'AvaError';
6
7
  }
7
-
8
- this.message = message;
9
- this.name = 'AvaError';
10
8
  }
11
9
 
12
- AvaError.prototype = Object.create(Error.prototype);
13
-
14
10
  module.exports = AvaError;
@@ -0,0 +1,282 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const Promise = require('bluebird');
5
+ const slash = require('slash');
6
+ const globby = require('globby');
7
+ const flatten = require('lodash.flatten');
8
+ const autoBind = require('auto-bind');
9
+ const defaultIgnore = require('ignore-by-default').directories();
10
+ const multimatch = require('multimatch');
11
+
12
+ function handlePaths(files, excludePatterns, globOptions) {
13
+ // Convert Promise to Bluebird
14
+ files = Promise.resolve(globby(files.concat(excludePatterns), globOptions));
15
+
16
+ const searchedParents = new Set();
17
+ const foundFiles = new Set();
18
+
19
+ function alreadySearchingParent(dir) {
20
+ if (searchedParents.has(dir)) {
21
+ return true;
22
+ }
23
+
24
+ const parentDir = path.dirname(dir);
25
+
26
+ if (parentDir === dir) {
27
+ // We have reached the root path
28
+ return false;
29
+ }
30
+
31
+ return alreadySearchingParent(parentDir);
32
+ }
33
+
34
+ return files
35
+ .map(file => {
36
+ file = path.resolve(globOptions.cwd, file);
37
+
38
+ if (fs.statSync(file).isDirectory()) {
39
+ if (alreadySearchingParent(file)) {
40
+ return null;
41
+ }
42
+
43
+ searchedParents.add(file);
44
+
45
+ let pattern = path.join(file, '**', '*.js');
46
+
47
+ if (process.platform === 'win32') {
48
+ // Always use `/` in patterns, harmonizing matching across platforms
49
+ pattern = slash(pattern);
50
+ }
51
+
52
+ return handlePaths([pattern], excludePatterns, globOptions);
53
+ }
54
+
55
+ // `globby` returns slashes even on Windows. Normalize here so the file
56
+ // paths are consistently platform-accurate as tests are run.
57
+ return path.normalize(file);
58
+ })
59
+ .then(flatten)
60
+ .filter(file => file && path.extname(file) === '.js')
61
+ .filter(file => {
62
+ if (path.basename(file)[0] === '_' && globOptions.includeUnderscoredFiles !== true) {
63
+ return false;
64
+ }
65
+
66
+ return true;
67
+ })
68
+ .map(file => path.resolve(file))
69
+ .filter(file => {
70
+ const alreadyFound = foundFiles.has(file);
71
+ foundFiles.add(file);
72
+ return !alreadyFound;
73
+ });
74
+ }
75
+
76
+ const defaultExcludePatterns = () => [
77
+ '!**/node_modules/**',
78
+ '!**/fixtures/**',
79
+ '!**/helpers/**'
80
+ ];
81
+
82
+ const defaultIncludePatterns = () => [
83
+ 'test.js',
84
+ 'test-*.js',
85
+ 'test',
86
+ '**/__tests__',
87
+ '**/*.test.js'
88
+ ];
89
+
90
+ const defaultHelperPatterns = () => [
91
+ '**/__tests__/helpers/**/*.js',
92
+ '**/__tests__/**/_*.js',
93
+ '**/test/helpers/**/*.js',
94
+ '**/test/**/_*.js'
95
+ ];
96
+
97
+ const getDefaultIgnorePatterns = () => defaultIgnore.map(dir => `${dir}/**/*`);
98
+
99
+ // Used on paths before they're passed to multimatch to harmonize matching
100
+ // across platforms
101
+ const matchable = process.platform === 'win32' ? slash : (path => path);
102
+
103
+ class AvaFiles {
104
+ constructor(options) {
105
+ options = options || {};
106
+
107
+ let files = (options.files || []).map(file => {
108
+ // `./` should be removed from the beginning of patterns because
109
+ // otherwise they won't match change events from Chokidar
110
+ if (file.slice(0, 2) === './') {
111
+ return file.slice(2);
112
+ }
113
+
114
+ return file;
115
+ });
116
+
117
+ if (files.length === 0) {
118
+ files = defaultIncludePatterns();
119
+ }
120
+
121
+ this.excludePatterns = defaultExcludePatterns();
122
+ this.files = files;
123
+ this.sources = options.sources || [];
124
+ this.cwd = options.cwd || process.cwd();
125
+
126
+ autoBind(this);
127
+ }
128
+ findTestFiles() {
129
+ return handlePaths(this.files, this.excludePatterns, {
130
+ cwd: this.cwd,
131
+ cache: Object.create(null),
132
+ statCache: Object.create(null),
133
+ realpathCache: Object.create(null),
134
+ symlinks: Object.create(null)
135
+ });
136
+ }
137
+ findTestHelpers() {
138
+ return handlePaths(defaultHelperPatterns(), ['!**/node_modules/**'], {
139
+ cwd: this.cwd,
140
+ includeUnderscoredFiles: true,
141
+ cache: Object.create(null),
142
+ statCache: Object.create(null),
143
+ realpathCache: Object.create(null),
144
+ symlinks: Object.create(null)
145
+ });
146
+ }
147
+ isSource(filePath) {
148
+ let mixedPatterns = [];
149
+ const defaultIgnorePatterns = getDefaultIgnorePatterns();
150
+ const overrideDefaultIgnorePatterns = [];
151
+
152
+ let hasPositivePattern = false;
153
+ this.sources.forEach(pattern => {
154
+ mixedPatterns.push(pattern);
155
+
156
+ // TODO: Why not just `pattern[0] !== '!'`?
157
+ if (!hasPositivePattern && pattern[0] !== '!') {
158
+ hasPositivePattern = true;
159
+ }
160
+
161
+ // Extract patterns that start with an ignored directory. These need to be
162
+ // rematched separately.
163
+ if (defaultIgnore.indexOf(pattern.split('/')[0]) >= 0) {
164
+ overrideDefaultIgnorePatterns.push(pattern);
165
+ }
166
+ });
167
+
168
+ // Same defaults as used for Chokidar
169
+ if (!hasPositivePattern) {
170
+ mixedPatterns = ['package.json', '**/*.js'].concat(mixedPatterns);
171
+ }
172
+
173
+ filePath = matchable(filePath);
174
+
175
+ // Ignore paths outside the current working directory.
176
+ // They can't be matched to a pattern.
177
+ if (/^\.\.\//.test(filePath)) {
178
+ return false;
179
+ }
180
+
181
+ const isSource = multimatch(filePath, mixedPatterns).length === 1;
182
+ if (!isSource) {
183
+ return false;
184
+ }
185
+
186
+ const isIgnored = multimatch(filePath, defaultIgnorePatterns).length === 1;
187
+ if (!isIgnored) {
188
+ return true;
189
+ }
190
+
191
+ const isErroneouslyIgnored = multimatch(filePath, overrideDefaultIgnorePatterns).length === 1;
192
+ if (isErroneouslyIgnored) {
193
+ return true;
194
+ }
195
+
196
+ return false;
197
+ }
198
+ isTest(filePath) {
199
+ const excludePatterns = this.excludePatterns;
200
+ const initialPatterns = this.files.concat(excludePatterns);
201
+
202
+ // Like in `api.js`, tests must be `.js` files and not start with `_`
203
+ if (path.extname(filePath) !== '.js' || path.basename(filePath)[0] === '_') {
204
+ return false;
205
+ }
206
+
207
+ // Check if the entire path matches a pattern
208
+ if (multimatch(matchable(filePath), initialPatterns).length === 1) {
209
+ return true;
210
+ }
211
+
212
+ // Check if the path contains any directory components
213
+ const dirname = path.dirname(filePath);
214
+ if (dirname === '.') {
215
+ return false;
216
+ }
217
+
218
+ // Compute all possible subpaths. Note that the dirname is assumed to be
219
+ // relative to the working directory, without a leading `./`.
220
+ const subpaths = dirname.split(/[\\/]/).reduce((subpaths, component) => {
221
+ const parent = subpaths[subpaths.length - 1];
222
+
223
+ if (parent) {
224
+ // Always use `/`` to makes multimatch consistent across platforms
225
+ subpaths.push(`${parent}/${component}`);
226
+ } else {
227
+ subpaths.push(component);
228
+ }
229
+
230
+ return subpaths;
231
+ }, []);
232
+
233
+ // Check if any of the possible subpaths match a pattern. If so, generate a
234
+ // new pattern with **/*.js.
235
+ const recursivePatterns = subpaths
236
+ .filter(subpath => multimatch(subpath, initialPatterns).length === 1)
237
+ // Always use `/` to makes multimatch consistent across platforms
238
+ .map(subpath => `${subpath}/**/*.js`);
239
+
240
+ // See if the entire path matches any of the subpaths patterns, taking the
241
+ // excludePatterns into account. This mimicks the behavior in api.js
242
+ return multimatch(matchable(filePath), recursivePatterns.concat(excludePatterns)).length === 1;
243
+ }
244
+ getChokidarPatterns() {
245
+ let paths = [];
246
+ let ignored = [];
247
+
248
+ this.sources.forEach(pattern => {
249
+ if (pattern[0] === '!') {
250
+ ignored.push(pattern.slice(1));
251
+ } else {
252
+ paths.push(pattern);
253
+ }
254
+ });
255
+
256
+ // Allow source patterns to override the default ignore patterns. Chokidar
257
+ // ignores paths that match the list of ignored patterns. It uses anymatch
258
+ // under the hood, which supports negation patterns. For any source pattern
259
+ // that starts with an ignored directory, ensure the corresponding negation
260
+ // pattern is added to the ignored paths.
261
+ const overrideDefaultIgnorePatterns = paths
262
+ .filter(pattern => defaultIgnore.indexOf(pattern.split('/')[0]) >= 0)
263
+ .map(pattern => `!${pattern}`);
264
+
265
+ ignored = getDefaultIgnorePatterns().concat(ignored, overrideDefaultIgnorePatterns);
266
+
267
+ if (paths.length === 0) {
268
+ paths = ['package.json', '**/*.js'];
269
+ }
270
+
271
+ paths = paths.concat(this.files);
272
+
273
+ return {
274
+ paths,
275
+ ignored
276
+ };
277
+ }
278
+ }
279
+
280
+ module.exports = AvaFiles;
281
+ module.exports.defaultIncludePatterns = defaultIncludePatterns;
282
+ module.exports.defaultExcludePatterns = defaultExcludePatterns;