diff --git a/lib/rule-tester/rule-tester.js b/lib/rule-tester/rule-tester.js index 8498b7c3c8e..2d820f5d859 100644 --- a/lib/rule-tester/rule-tester.js +++ b/lib/rule-tester/rule-tester.js @@ -55,6 +55,8 @@ const ajv = require("../shared/ajv")({ strictDefaults: true }); const espreePath = require.resolve("espree"); const parserSymbol = Symbol.for("eslint.RuleTester.parser"); +const { SourceCode } = require("../source-code"); + //------------------------------------------------------------------------------ // Typedefs //------------------------------------------------------------------------------ @@ -284,6 +286,17 @@ function wrapParser(parser) { }; } +/** + * Function to replace `SourceCode.prototype.getComments`. + * @returns {void} + * @throws {Error} Deprecation message. + */ +function getCommentsDeprecation() { + throw new Error( + "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead." + ); +} + //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ @@ -607,7 +620,16 @@ class RuleTester { validate(config, "rule-tester", id => (id === ruleName ? rule : null)); // Verify the code. - const messages = linter.verify(code, config, filename); + const { getComments } = SourceCode.prototype; + let messages; + + try { + SourceCode.prototype.getComments = getCommentsDeprecation; + messages = linter.verify(code, config, filename); + } finally { + SourceCode.prototype.getComments = getComments; + } + const fatalErrorMessage = messages.find(m => m.fatal); assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`); diff --git a/tests/lib/rule-tester/rule-tester.js b/tests/lib/rule-tester/rule-tester.js index 082d74c067d..43f078e90de 100644 --- a/tests/lib/rule-tester/rule-tester.js +++ b/tests/lib/rule-tester/rule-tester.js @@ -2480,4 +2480,37 @@ describe("RuleTester", () => { }); + describe("SourceCode#getComments()", () => { + const useGetCommentsRule = { + create: context => ({ + Program(node) { + const sourceCode = context.getSourceCode(); + + sourceCode.getComments(node); + } + }) + }; + + it("should throw if called from a valid test case", () => { + assert.throws(() => { + ruleTester.run("use-get-comments", useGetCommentsRule, { + valid: [""], + invalid: [] + }); + }, /`SourceCode#getComments\(\)` is deprecated/u); + }); + + it("should throw if called from an invalid test case", () => { + assert.throws(() => { + ruleTester.run("use-get-comments", useGetCommentsRule, { + valid: [], + invalid: [{ + code: "", + errors: [{}] + }] + }); + }, /`SourceCode#getComments\(\)` is deprecated/u); + }); + }); + });