forked from eslint-community/eslint-plugin-eslint-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
527 lines (485 loc) · 20.9 KB
/
utils.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
'use strict';
const { inspect } = require('util');
const lodash = require('lodash');
const espree = require('espree');
const eslintScope = require('eslint-scope');
const estraverse = require('estraverse');
const assert = require('chai').assert;
const utils = require('../../lib/utils');
describe('utils', () => {
describe('getRuleInfo', () => {
describe('the file does not have a valid rule', () => {
[
'',
'module.exports;',
'module.exports = foo;',
'module.boop = function() {};',
'exports = function() {};',
'module.exports = function* () {};',
'module.exports = async function () {};',
'module.exports = {};',
'module.exports = { meta: {} }',
'module.exports = { create: {} }',
'module.exports = { create: foo }',
'module.exports = { create: function* foo() {} }',
'module.exports = { create: async function foo() {} }',
].forEach(noRuleCase => {
it(`returns null for ${noRuleCase}`, () => {
const ast = espree.parse(noRuleCase, { ecmaVersion: 8, range: true });
assert.isNull(utils.getRuleInfo({ ast }), 'Expected no rule to be found');
});
});
});
describe('the file does not have a valid rule (ESM)', () => {
[
'',
'export const foo = { create() {} }',
'export default { foo: {} }',
'const foo = {}; export default foo',
].forEach(noRuleCase => {
it(`returns null for ${noRuleCase}`, () => {
const ast = espree.parse(noRuleCase, { ecmaVersion: 8, range: true, sourceType: 'module' });
assert.isNull(utils.getRuleInfo({ ast }), 'Expected no rule to be found');
});
});
});
describe('the file has a valid rule', () => {
const CASES = {
// CJS
'module.exports = { create: function foo() {} };': {
create: { type: 'FunctionExpression', id: { name: 'foo' } }, // (This property will actually contain the AST node.)
meta: null,
isNewStyle: true,
},
'module.exports = { create: () => { } };': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: true,
},
'module.exports = { create() {}, meta: { } };': {
create: { type: 'FunctionExpression' },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
'module.exports.create = function foo() {}; module.exports.meta = {}': {
create: { type: 'FunctionExpression', id: { name: 'foo' } },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
'exports.create = function foo() {}; exports.meta = {};': {
create: { type: 'FunctionExpression', id: { name: 'foo' } },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
'module.exports = { create: () => { } }; exports.create = function foo() {}; exports.meta = {};': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: true,
},
'exports.meta = {}; module.exports = { create: () => { } };': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: true,
},
'module.exports = { create: () => { } }; module.exports.meta = {};': {
create: { type: 'ArrowFunctionExpression' },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
'module.exports = { meta: {} }; module.exports.create = () => { };': {
create: { type: 'ArrowFunctionExpression' },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
'module.exports = { "meta": {} }; module.exports.create = () => { };': {
create: { type: 'ArrowFunctionExpression' },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
'module.exports = { create: () => { } }; exports.meta = {};': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: true,
},
'module.exports = function foo() {}': {
create: { type: 'FunctionExpression', id: { name: 'foo' } },
meta: null,
isNewStyle: false,
},
'module.exports = () => {}': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: false,
},
'exports.meta = {}; module.exports = () => {}': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: false,
},
'module.exports = () => {}; module.exports.meta = {};': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: false,
},
// ESM (object style)
'export default { create() {} }': {
create: { type: 'FunctionExpression' },
meta: null,
isNewStyle: true,
},
'export default { create() {}, meta: {} }': {
create: { type: 'FunctionExpression' },
meta: { type: 'ObjectExpression' },
isNewStyle: true,
},
// ESM (function style)
'export default function () {}': {
create: { type: 'FunctionDeclaration' },
meta: null,
isNewStyle: false,
},
'export default () => {}': {
create: { type: 'ArrowFunctionExpression' },
meta: null,
isNewStyle: false,
},
};
Object.keys(CASES).forEach(ruleSource => {
it(ruleSource, () => {
const ast = espree.parse(ruleSource, { ecmaVersion: 6, range: true, sourceType: ruleSource.startsWith('export default') ? 'module' : 'script' });
const ruleInfo = utils.getRuleInfo({ ast });
assert(
lodash.isMatch(ruleInfo, CASES[ruleSource]),
`Expected \n${inspect(ruleInfo)}\nto match\n${inspect(CASES[ruleSource])}`
);
});
});
for (const scopeOptions of [
{ ignoreEval: true, ecmaVersion: 6, sourceType: 'script', nodejsScope: true },
{ ignoreEval: true, ecmaVersion: 6, sourceType: 'script' },
{ ignoreEval: true, ecmaVersion: 6, sourceType: 'module' },
]) {
const ast = espree.parse(`
const create = () => {};
const meta = {};
module.exports = { create, meta };
`, { ecmaVersion: 6 });
const expected = {
create: { type: 'Identifier' },
meta: { type: 'Identifier' },
isNewStyle: true,
};
it(`ScopeOptions: ${JSON.stringify(scopeOptions)}`, () => {
const scopeManager = eslintScope.analyze(ast, scopeOptions);
const ruleInfo = utils.getRuleInfo({ ast, scopeManager });
assert(
lodash.isMatch(ruleInfo, expected),
`Expected \n${inspect(ruleInfo)}\nto match\n${inspect(expected)}`
);
});
}
});
});
describe('getContextIdentifiers', () => {
const CASES = {
'module.exports = context => { context; context; context; }' (ast) {
return [
ast.body[0].expression.right.body.body[0].expression,
ast.body[0].expression.right.body.body[1].expression,
ast.body[0].expression.right.body.body[2].expression,
];
},
'module.exports = { meta: {}, create(context, foo = context) {} }' (ast) {
return [ast.body[0].expression.right.properties[1].value.params[1].right];
},
'module.exports = { meta: {}, create(notContext) { notContext; notContext; notContext; } }' (ast) {
return [
ast.body[0].expression.right.properties[1].value.body.body[0].expression,
ast.body[0].expression.right.properties[1].value.body.body[1].expression,
ast.body[0].expression.right.properties[1].value.body.body[2].expression,
];
},
};
Object.keys(CASES).forEach(ruleSource => {
it(ruleSource, () => {
const ast = espree.parse(ruleSource, { ecmaVersion: 6, range: true });
const scope = eslintScope.analyze(ast, { ignoreEval: true, ecmaVersion: 6, sourceType: 'script', nodejsScope: true });
const identifiers = utils.getContextIdentifiers(scope, ast);
assert(identifiers instanceof Set, 'getContextIdentifiers should return a Set');
[...identifiers].forEach((identifier, index) => {
assert.strictEqual(identifier, CASES[ruleSource](ast)[index]);
});
});
});
});
describe('getKeyName', () => {
const CASES = {
'({ foo: 1 })': 'foo',
'({ "foo": 1 })': 'foo',
'({ ["foo"]: 1 })': 'foo',
'({ [`foo`]: 1 })': 'foo',
'({ foo() {} })': 'foo',
'({ "foo"() {} })': 'foo',
'({ ["foo"]() {} })': 'foo',
'({ [`foo`]() {} })': 'foo',
'({ 5: 1 })': '5',
'({ 0x123: 1 })': '291',
'({ [foo]: 1 })': null,
'({ [tag`foo`]: 1 })': null,
'({ ["foo" + "bar"]: 1 })': null,
};
Object.keys(CASES).forEach(objectSource => {
it(objectSource, () => {
const ast = espree.parse(objectSource, { ecmaVersion: 6, range: true });
assert.strictEqual(utils.getKeyName(ast.body[0].expression.properties[0]), CASES[objectSource]);
});
});
const CASES_ES9 = {
'({ ...foo })': null,
};
Object.keys(CASES_ES9).forEach(objectSource => {
it(objectSource, () => {
const ast = espree.parse(objectSource, { ecmaVersion: 9, range: true });
assert.strictEqual(utils.getKeyName(ast.body[0].expression.properties[0]), CASES_ES9[objectSource]);
});
});
});
describe('getTestInfo', () => {
describe('the file does not have valid tests', () => {
[
'',
'module.exports = context => context.report(foo);',
'new (require("eslint").NotRuleTester).run(foo, bar, { valid: [] })',
'new NotRuleTester().run(foo, bar, { valid: [] })',
'new RuleTester()',
'const foo = new RuleTester; bar.run(foo, bar, { valid: [] })',
'new RuleTester().run()',
'new RuleTester().run(foo)',
'new RuleTester().run(foo, bar)',
'new RuleTester().run(foo, bar, notAnObject)',
].forEach(noTestsCase => {
it(`returns no tests for ${noTestsCase}`, () => {
const ast = espree.parse(noTestsCase, { ecmaVersion: 8, range: true });
const scope = eslintScope.analyze(ast, { ignoreEval: true, ecmaVersion: 6, sourceType: 'script', nodejsScope: true });
assert.deepEqual(utils.getTestInfo(scope, ast), [], 'Expected no tests to be found');
});
});
});
describe('the file has valid tests', () => {
const CASES = {
'new RuleTester().run(bar, baz, { valid: [foo], invalid: [bar, baz] })': { valid: 1, invalid: 2 },
'var foo = new RuleTester(); foo.run(bar, baz, { valid: [foo], invalid: [bar] })': { valid: 1, invalid: 1 },
'var foo = new (require("eslint")).RuleTester; foo.run(bar, baz, { valid: [], invalid: [] })': { valid: 0, invalid: 0 },
'var foo = new bar.RuleTester; foo.run(bar, baz, { valid: [], invalid: [bar, baz] })': { valid: 0, invalid: 2 },
'var foo = new bar.RuleTester; foo.run(bar, baz, { valid: [,], invalid: [bar, , baz] })': { valid: 0, invalid: 2 },
};
Object.keys(CASES).forEach(testSource => {
it(testSource, () => {
const ast = espree.parse(testSource, { ecmaVersion: 6, range: true });
const scope = eslintScope.analyze(ast, { ignoreEval: true, ecmaVersion: 6, sourceType: 'script', nodejsScope: true });
const testInfo = utils.getTestInfo(scope, ast);
assert.strictEqual(testInfo.length, 1, 'Expected to find one test run');
assert.strictEqual(
testInfo[0].valid.length,
CASES[testSource].valid,
`Expected ${CASES[testSource].valid} valid cases but got ${testInfo[0].valid.length}`
);
assert.strictEqual(
testInfo[0].invalid.length,
CASES[testSource].invalid,
`Expected ${CASES[testSource].invalid} invalid cases but got ${testInfo[0].invalid.length}`
);
});
});
});
describe('the file has multiple test runs', () => {
const CASES = {
[`
new RuleTester().run(foo, bar, { valid: [foo], invalid: [] });
new RuleTester().run(foo, bar, { valid: [], invalid: [foo, bar] });
`]: [{ valid: 1, invalid: 0 }, { valid: 0, invalid: 2 }],
[`
var foo = new RuleTester;
var bar = new RuleTester;
foo.run(foo, bar, { valid: [foo, bar, baz], invalid: [foo] });
bar.run(foo, bar, { valid: [], invalid: [foo, bar] });
`]: [{ valid: 3, invalid: 1 }, { valid: 0, invalid: 2 }],
[`
var foo = new RuleTester, bar = new RuleTester;
foo.run(foo, bar, { valid: [foo, bar, baz], invalid: [foo] });
bar.run(foo, bar, { valid: [], invalid: [foo, bar] });
`]: [{ valid: 3, invalid: 1 }, { valid: 0, invalid: 2 }],
};
Object.keys(CASES).forEach(testSource => {
it(testSource, () => {
const ast = espree.parse(testSource, { ecmaVersion: 6, range: true });
const scope = eslintScope.analyze(ast, { ignoreEval: true, ecmaVersion: 6, sourceType: 'script', nodejsScope: true });
const testInfo = utils.getTestInfo(scope, ast);
assert.strictEqual(
testInfo.length,
CASES[testSource].length,
`Expected to find ${CASES[testSource].length} test runs but got ${testInfo.length}`
);
CASES[testSource].forEach((testRun, index) => {
assert.strictEqual(
testRun.valid,
testInfo[index].valid.length,
`On run ${index + 1}, expected ${testRun.valid} valid cases but got ${testInfo[index].valid.length}`
);
assert.strictEqual(
testRun.invalid,
testInfo[index].invalid.length,
`On run ${index + 1}, expected ${testRun.invalid} valid cases but got ${testInfo[index].invalid.length}`
);
});
});
});
});
});
describe('getReportInfo', () => {
const CASES = new Map([
[[], () => null],
[['foo', 'bar'], () => null],
[['foo', '"bar"', 'baz', 'qux', 'boop'], args => ({ node: args[0], message: args[1], data: args[2], fix: args[3] })],
[['foo', '`bar`', 'baz', 'qux', 'boop'], args => ({ node: args[0], message: args[1], data: args[2], fix: args[3] })],
[
['foo', '{ bar: 1 }', 'baz', 'qux', 'boop'],
args => ({ node: args[0], loc: args[1], message: args[2], data: args[3], fix: args[4] }),
],
[['foo', 'bar', 'baz'], () => null],
[
['{ node, message }'],
() => ({
node: { type: 'Identifier', name: 'node', start: 17, end: 21 },
message: { type: 'Identifier', name: 'message', start: 23, end: 30 },
}),
],
]);
for (const args of CASES.keys()) {
it(args.join(', '), () => {
const parsedArgs = espree.parse(
`context.report(${args.join(', ')})`,
{ ecmaVersion: 6, loc: false, range: false }
).body[0].expression.arguments;
const context = { getScope () {} }; // mock object
const reportInfo = utils.getReportInfo(parsedArgs, context);
assert.deepEqual(reportInfo, CASES.get(args)(parsedArgs));
});
}
});
describe('getSourceCodeIdentifiers', () => {
const CASES = {
'module.exports = context => { const sourceCode = context.getSourceCode(); sourceCode; foo; }': 2,
'module.exports = context => { const x = 1, sc = context.getSourceCode(); sc; sc; sc; sourceCode; }': 4,
'module.exports = context => { const sourceCode = context.getNotSourceCode(); }': 0,
};
Object.keys(CASES).forEach(testSource => {
it(testSource, () => {
const ast = espree.parse(testSource, { ecmaVersion: 6, range: true });
const scope = eslintScope.analyze(ast, { ignoreEval: true, ecmaVersion: 6, sourceType: 'script', nodejsScope: true });
estraverse.traverse(ast, {
enter (node, parent) {
node.parent = parent;
},
});
assert.strictEqual(utils.getSourceCodeIdentifiers(scope, ast).size, CASES[testSource]);
});
});
});
describe('collectReportViolationAndSuggestionData', () => {
const CASES = [
{
code: `
context.report({
node: {},
message: "message1",
messageId: "messageId1",
data: { foo: 'hello' },
fix(fixer) {},
suggest: [{
desc: "message2",
messageId: "messageId2",
data: { bar: 'world' },
fix(fixer) {},
}]
});
`,
shouldMatch: [
{
message: { type: 'Literal', value: 'message1' },
messageId: { type: 'Literal', value: 'messageId1' },
data: { type: 'ObjectExpression', properties: [{ key: { name: 'foo' } }] },
fix: { type: 'FunctionExpression' },
},
{
message: { type: 'Literal', value: 'message2' },
messageId: { type: 'Literal', value: 'messageId2' },
data: { type: 'ObjectExpression', properties: [{ key: { name: 'bar' } }] },
fix: { type: 'FunctionExpression' },
},
],
},
];
it('behaves correctly', () => {
for (const testCase of CASES) {
const ast = espree.parse(testCase.code, { ecmaVersion: 6, range: true });
const context = { getScope () {} }; // mock object
const reportNode = ast.body[0].expression;
const reportInfo = utils.getReportInfo(reportNode.arguments, context);
const data = utils.collectReportViolationAndSuggestionData(reportInfo);
assert(
lodash.isMatch(data, testCase.shouldMatch),
`Expected \n${inspect(data)}\nto match\n${inspect(testCase.shouldMatch)}`
);
}
});
});
describe('isAutoFixerFunction / isSuggestionFixerFunction', () => {
const CASES = {
// isAutoFixerFunction
'context.report({ fix(fixer) {} });' (ast) {
return { expected: true, node: ast.body[0].expression.arguments[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isAutoFixerFunction };
},
'context.notReport({ fix(fixer) {} });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isAutoFixerFunction };
},
'context.report({ notFix(fixer) {} });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isAutoFixerFunction };
},
'notContext.report({ notFix(fixer) {} });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value, context: undefined, fn: utils.isAutoFixerFunction };
},
// isSuggestionFixerFunction
'context.report({ suggest: [{ fix(fixer) {} }] });' (ast) {
return { expected: true, node: ast.body[0].expression.arguments[0].properties[0].value.elements[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isSuggestionFixerFunction };
},
'context.notReport({ suggest: [{ fix(fixer) {} }] });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value.elements[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isSuggestionFixerFunction };
},
'context.report({ notSuggest: [{ fix(fixer) {} }] });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value.elements[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isSuggestionFixerFunction };
},
'context.report({ suggest: [{ notFix(fixer) {} }] });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value.elements[0].properties[0].value, context: ast.body[0].expression.callee.object, fn: utils.isSuggestionFixerFunction };
},
'notContext.report({ suggest: [{ fix(fixer) {} }] });' (ast) {
return { expected: false, node: ast.body[0].expression.arguments[0].properties[0].value, context: undefined, fn: utils.isSuggestionFixerFunction };
},
};
Object.keys(CASES).forEach(ruleSource => {
it(ruleSource, () => {
const ast = espree.parse(ruleSource, { ecmaVersion: 6, range: true });
// Add parent to each node.
estraverse.traverse(ast, {
enter (node, parent) {
node.parent = parent;
},
});
const testCase = CASES[ruleSource](ast);
const contextIdentifiers = new Set([testCase.context]);
const result = testCase.fn(testCase.node, contextIdentifiers);
assert.strictEqual(result, testCase.expected);
});
});
});
});