Skip to content

Commit

Permalink
tools: add assert-no-message-literals lint rule
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax committed Jul 28, 2017
1 parent 9623ce5 commit 2bdace7
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ rules:

# Custom rules in tools/eslint-rules
assert-throws-arguments: [error, { requireTwo: true }]
assert-no-message-literals: error
no-unescaped-regexp-dot: error

# Global scoped method and vars
Expand Down
72 changes: 72 additions & 0 deletions tools/eslint-rules/assert-no-message-literals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @fileoverview Check that calls to assert methods never have a simple
* string literal as the `message` argument.
* @author Anna Henningsen
*/
'use strict';

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

function checkThrowsArguments(context, node) {
if (node.callee.type === 'MemberExpression' &&
node.callee.object.name === 'assert') {
const args = node.arguments;
let messageArg = null;
switch (node.callee.property.name) {
case 'deepEqual':
case 'deepStrictEqual':
case 'equal':
case 'notDeepEqual':
case 'notDeepStrictEqual':
case 'notEqual':
case 'notStrictEqual':
case 'strictEqual':
if (args.length > 2)
messageArg = args[2];
break;
case 'ok':
if (args.length > 1)
messageArg = args[1];
break;
case 'doesNotThrow':
case 'throws':
if (args.length > 2) {
messageArg = args[2];
} else if (args.length > 1 && args[1].type === 'Literal' &&
!args[1].regex) {
messageArg = args[1];
}
break;
case 'ifError':
case 'fail':
return;
}

if (messageArg === null)
return;

if (messageArg.type === 'Literal') {
context.report({
message: 'Unexpected literal assertion message',
node: messageArg
});
}
}
}

module.exports = {
meta: {
schema: [
{
type: 'object',
}
]
},
create: function(context) {
return {
CallExpression: (node) => checkThrowsArguments(context, node)
};
}
};

0 comments on commit 2bdace7

Please sign in to comment.