Skip to content

Update: add autofixing to test-case-property-ordering. (fixes #31) #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 31, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Name | ✔️ | 🛠 | Description
[prefer-placeholders](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/prefer-placeholders.md) | | | Disallows template literals as report messages
[report-message-format](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/report-message-format.md) | | | Enforces a consistent format for report messages
[require-meta-fixable](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/require-meta-fixable.md) | ✔️ | | Requires a `meta.fixable` property for fixable rules
[test-case-property-ordering](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/test-case-property-ordering.md) | | | Requires the properties of a test case to be placed in a consistent order.
[test-case-property-ordering](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/test-case-property-ordering.md) | | 🛠 | Requires the properties of a test case to be placed in a consistent order.
[test-case-shorthand-strings](https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/blob/master/docs/rules/test-case-shorthand-strings.md) | | 🛠 | Enforces consistent usage of shorthand strings for test cases with no options

## Supported Presets
Expand Down
2 changes: 2 additions & 0 deletions docs/rules/test-case-property-ordering.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# enforce ordering of keys in test cases (test-case-property-ordering)

(fixable) The `--fix` option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.

This rule enforces that the properties of RuleTester test cases are arranged in a consistent order.

## Rule Details
Expand Down
44 changes: 37 additions & 7 deletions lib/rules/test-case-property-ordering.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module.exports = {
category: 'Tests',
recommended: false,
},
fixable: null, // or "code" or "whitespace"
fixable: 'code',
schema: [{
type: 'array',
elements: { type: 'string' },
Expand All @@ -31,29 +31,59 @@ module.exports = {
// ----------------------------------------------------------------------
const message = 'The properties of a test case should be placed in a consistent order: [{{order}}].';
const order = context.options[0] || ['code', 'output', 'options', 'parserOptions', 'errors'];
const sourceCode = context.getSourceCode();

return {
Program (ast) {
utils.getTestInfo(context, ast).forEach(testRun => {
[testRun.valid, testRun.invalid].forEach(tests => {
(tests || []).forEach(test => {
const keys = (test.properties || []).map(utils.getKeyName);
const properties = test.properties || [];
const keyNames = properties.map(utils.getKeyName);

for (let i = 0, lastChecked; i < keys.length; i++) {
const current = order.indexOf(keys[i]);
for (let i = 0, lastChecked; i < keyNames.length; i++) {
const current = order.indexOf(keyNames[i]);

// current < lastChecked to catch unordered;
// and lastChecked === -1 to catch extra properties before.
if (current > -1 && (current < lastChecked || lastChecked === -1)) {
let orderMsg = order.filter(item => keys.indexOf(item) > -1);
let orderMsg = order.filter(item => keyNames.indexOf(item) > -1);
orderMsg = orderMsg.concat(
lastChecked === -1 ? keys.filter(item => order.indexOf(item) === -1) : []
lastChecked === -1 ? keyNames.filter(item => order.indexOf(item) === -1) : []
);

context.report({
node: test.properties[i],
node: properties[i],
message,
data: { order: orderMsg.join(', ') },
fix (fixer) {
const source = sourceCode.getText();
const last = properties[properties.length - 1];
// end loc to replace(including whitespaces).
const finalEnd = sourceCode.getTokenAfter(last, token => token.value === '}' && token.type === 'Punctuator').range[0];
// reorder the properties and put in result array.
const result = [];
for (let j = 0; j < keyNames.length; j++) {
const insertedIndex = orderMsg.indexOf(keyNames[j]);
const propertyCode = sourceCode.getText(properties[j]);
const propertyStart = properties[j].range[1];
const propertyEnd = j < properties.length - 1 ? properties[j + 1].range[0] : finalEnd;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these variable names are confusing because propertyStart and propertyEnd describe the boundaries of the whitespace after the property, not the property itself. Maybe whitespaceStart and whitespaceEnd would be better.

let trailing = source.slice(propertyStart, propertyEnd);

// for last property, should check & add trailling commas.
if (j === properties.length - 1 && sourceCode.getTokenAfter(last).value !== ',') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of having a special case for trailing commas, would it work to just set finalEnd to the trailing comma if it exists?

const finalEnd = sourceCode.getTokenAfter(last);

trailing = ', ' + trailing;
}
result[insertedIndex] = propertyCode + trailing;
}

const start = properties[0].range[0];

return fixer.replaceTextRange(
[start, finalEnd],
result.join('')
);
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to use the new feature in ESLint 4.1.0 where you can return an array of autofixes?

That way, this autofix would be very simple, because it wouldn't be necessary to deal with whitespace or trailing commas:

fix(fixer) {
  return orderMsg.map((key, index) => {
    const propertyToInsert = test.properties[keyNames.indexOf(key)];
    return fixer.replaceText(test.properties[index], sourceCode.getText(propertyToInsert));
  });
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome!!!

});
}
lastChecked = current;
Expand Down
99 changes: 48 additions & 51 deletions tests/lib/rules/test-case-property-ordering.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,35 +22,22 @@ ruleTester.run('test-case-property-ordering', rule, {
`
new RuleTester().run('foo', bar, {
valid: [
{
code: "foo",
output: "bar",
options: ["baz"],
},
{ code: "foo", output: "bar", options: ["baz"], },
]
});
`,
`
new RuleTester().run('foo', bar, {
valid: [
{
code: "foo",
output: "bar",
options: ["baz"],
env: { es6: true },
},
{ code: "foo",output: "bar",options: ["baz"],env: { es6: true }, },
]
});
`,
{
code: `
new RuleTester().run('foo', bar, {
valid: [
{
code: "foo",
options: ["baz"],
output: "bar",
},
{ code: "foo", options: ["baz"], output: "bar", },
]
});
`,
Expand All @@ -63,41 +50,48 @@ ruleTester.run('test-case-property-ordering', rule, {
code: `
new RuleTester().run('foo', bar, {
valid: [
{
code: "foo",
options: ["baz"],
output: "bar",
},
{ code: "foo", options: ["baz"], output: "bar", },
]
});
`,
output: `
new RuleTester().run('foo', bar, {
valid: [
{ code: "foo", output: "bar", options: ["baz"], },
]
});
`,
errors: [{ message: 'The properties of a test case should be placed in a consistent order: [code, output, options].' }],
},
{
code: `
new RuleTester().run('foo', bar, {
valid: [
{
env: { es6: true },
code: "foo",
output: "bar",
options: ["baz"],
},
]
});
new RuleTester().run('foo', bar, {
valid: [
{ env: { es6: true }, code: "foo", output: "bar", options: ["baz"], },
]
});
`,
output: `
new RuleTester().run('foo', bar, {
valid: [
{ code: "foo", output: "bar", options: ["baz"], env: { es6: true }, },
]
});
`,
errors: [{ message: 'The properties of a test case should be placed in a consistent order: [code, output, options, env].' }],
},
{
code: `
new RuleTester().run('foo', bar, {
valid: [
{
code: "foo",
env: { es6: true },
output: "bar",
options: ["baz"],
},
{ code: "foo", env: { es6: true }, output: "bar", options: ["baz"], },
]
});
`,
output: `
new RuleTester().run('foo', bar, {
valid: [
{ code: "foo", output: "bar", options: ["baz"], env: { es6: true }, },
]
});
`,
Expand All @@ -107,11 +101,14 @@ ruleTester.run('test-case-property-ordering', rule, {
code: `
new RuleTester().run('foo', bar, {
valid: [
{
code: "foo",
output: "bar",
options: ["baz"],
},
{ code: "foo", output: "bar", options: ["baz"], },
]
});
`,
output: `
new RuleTester().run('foo', bar, {
valid: [
{ code: "foo", options: ["baz"], output: "bar", },
]
});
`,
Expand All @@ -122,18 +119,18 @@ ruleTester.run('test-case-property-ordering', rule, {
code: `
new RuleTester().run('foo', bar, {
valid: [
{
options: ["baz"],
parserOptions: "",
code: "foo",
errors: ["foo"],
output: "",
},
{\ncode: "foo",\noutput: "",\nerrors: ["baz"],\nparserOptions: "",\n},
]
});
`,
output: `
new RuleTester().run('foo', bar, {
valid: [
{\ncode: "foo",\noutput: "",\nparserOptions: "",\nerrors: ["baz"],\n},
]
});
`,
options: [['code', 'errors', 'output']],
errors: [{ message: 'The properties of a test case should be placed in a consistent order: [code, errors, output, options, parserOptions].' }],
errors: [{ message: 'The properties of a test case should be placed in a consistent order: [code, output, parserOptions, errors].' }],
},
],
});