@typespec/compiler
Version:
TypeSpec Compiler Preview
59 lines • 2.72 kB
JavaScript
import { ok, strictEqual } from "assert";
import { applyCodeFix as applyCodeFixReal } from "../core/code-fixes.js";
import { createDiagnosticCollector } from "../core/diagnostics.js";
import { createLinterRuleContext } from "../core/linter.js";
import { navigateProgram } from "../core/semantic-walker.js";
import { expectDiagnosticEmpty, expectDiagnostics } from "./expect.js";
import { resolveVirtualPath, trimBlankLines } from "./test-utils.js";
export function createLinterRuleTester(runner, ruleDef, libraryName) {
return {
expect,
};
function expect(code) {
return {
toBeValid,
toEmitDiagnostics,
applyCodeFix,
};
async function toBeValid() {
const diagnostics = await diagnose(code);
expectDiagnosticEmpty(diagnostics);
}
async function toEmitDiagnostics(match) {
const diagnostics = await diagnose(code);
expectDiagnostics(diagnostics, match);
}
function applyCodeFix(fixId) {
return { toEqual };
async function toEqual(expectedCode) {
const diagnostics = await diagnose(code);
const codefix = diagnostics[0].codefixes?.find((x) => x.id === fixId);
ok(codefix, `Codefix with id "${fixId}" not found.`);
let content;
const host = {
...runner.program.host,
writeFile: (name, newContent) => {
content = newContent;
return Promise.resolve();
},
};
await applyCodeFixReal(host, codefix);
ok(content, "No content was written to the host.");
const offset = runner.fs.get(resolveVirtualPath("./main.tsp"))?.indexOf(code);
strictEqual(trimBlankLines(content.slice(offset)), trimBlankLines(expectedCode));
}
}
}
async function diagnose(code) {
await runner.diagnose(code, { parseOptions: { comments: true } });
const diagnostics = createDiagnosticCollector();
const rule = { ...ruleDef, id: `${libraryName}/${ruleDef.name}` };
const context = createLinterRuleContext(runner.program, rule, diagnostics);
const listener = ruleDef.create(context);
navigateProgram(runner.program, listener);
// No diagnostics should have been reported to the program. If it happened the rule is calling reportDiagnostic directly and should NOT be doing that.
expectDiagnosticEmpty(runner.program.diagnostics);
return diagnostics.diagnostics;
}
}
//# sourceMappingURL=rule-tester.js.map