Skip to content
Permalink
Browse files
Breaking: disallow SourceCode#getComments() in RuleTester (refs #14744)…
… (#14769)

* Breaking: disallow SourceCode#getComments() in RuleTester (refs #14744)

* Update lib/rule-tester/rule-tester.js

Co-authored-by: Nicholas C. Zakas <nicholas@nczconsulting.com>

Co-authored-by: Nicholas C. Zakas <nicholas@nczconsulting.com>
  • Loading branch information
mdjermanovic and nzakas committed Aug 5, 2021
1 parent 1d2213d commit 86d31a4951e3a39e359e284f5fe336ac477369fe
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
@@ -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}`);
@@ -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);
});
});

});

0 comments on commit 86d31a4

Please sign in to comment.