no-useless-run-test.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @fileoverview Reject run_test() definitions where they aren't necessary.
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. */
  8. "use strict";
  9. module.exports = {
  10. meta: {
  11. docs: {
  12. url:
  13. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/no-useless-run-test.html",
  14. },
  15. fixable: "code",
  16. type: "suggestion",
  17. },
  18. create(context) {
  19. return {
  20. "Program > FunctionDeclaration": function(node) {
  21. if (
  22. node.id.name === "run_test" &&
  23. node.body.type === "BlockStatement" &&
  24. node.body.body.length === 1 &&
  25. node.body.body[0].type === "ExpressionStatement" &&
  26. node.body.body[0].expression.type === "CallExpression" &&
  27. node.body.body[0].expression.callee.name === "run_next_test"
  28. ) {
  29. context.report({
  30. node,
  31. fix: fixer => {
  32. let sourceCode = context.getSourceCode();
  33. let startNode;
  34. if (sourceCode.getCommentsBefore) {
  35. // ESLint 4 has getCommentsBefore.
  36. startNode = sourceCode.getCommentsBefore(node);
  37. } else if (node && node.body && node.leadingComments) {
  38. // This is for ESLint 3.
  39. startNode = node.leadingComments;
  40. }
  41. // If we have comments, we want the start node to be the comments,
  42. // rather than the token before the comments, so that we don't
  43. // remove the comments - for run_test, these are likely to be useful
  44. // information about the test.
  45. if (startNode?.length) {
  46. startNode = startNode[startNode.length - 1];
  47. } else {
  48. startNode = sourceCode.getTokenBefore(node);
  49. }
  50. return fixer.removeRange([
  51. // If there's no startNode, we fall back to zero, i.e. start of
  52. // file.
  53. startNode ? startNode.range[1] + 1 : 0,
  54. // We know the function is a block and it'll end with }. Normally
  55. // there's a new line after that, so just advance past it. This
  56. // may be slightly not dodgy in some cases, but covers the existing
  57. // cases.
  58. node.range[1] + 1,
  59. ]);
  60. },
  61. message:
  62. "Useless run_test function - only contains run_next_test; whole function can be removed",
  63. });
  64. }
  65. },
  66. };
  67. },
  68. };