diff --git a/scripts/checks/run.mts b/scripts/checks/run.mts index e40dcebdc6a..fdef63a22c1 100644 --- a/scripts/checks/run.mts +++ b/scripts/checks/run.mts @@ -98,6 +98,11 @@ export const CHECKS: readonly CheckCommand[] = [ command: TSX, args: ["scripts/checks/no-unit-blocks-in-live-e2e.mts"], }, + { + name: "test-registration-boundary", + command: TSX, + args: ["scripts/checks/test-registration-boundary.mts"], + }, ]; type RunChecksOptions = { diff --git a/scripts/checks/test-registration-boundary.mts b/scripts/checks/test-registration-boundary.mts new file mode 100644 index 00000000000..3b4aeb0f039 --- /dev/null +++ b/scripts/checks/test-registration-boundary.mts @@ -0,0 +1,345 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import ts from "typescript"; + +export type TestRegistrationViolation = { + readonly file: string; + readonly line: number; + readonly column: number; + readonly call: string; +}; + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const DEFAULT_SCAN_ROOTS = Object.freeze([ + "bin", + "nemoclaw/src", + "scripts", + "src", + "test", + "tools", +]); +const SOURCE_FILE_PATTERN = /\.(?:[cm]?[jt]sx?)$/; +const TEST_FILE_PATTERN = /\.(?:test|spec)\.(?:[cm]?[jt]sx?)$/; +const SUITE_FILE_PATTERN = /-suite\.(?:[cm]?[jt]sx?)$/; +const SOURCE_EXTENSIONS = Object.freeze([ + ".ts", + ".tsx", + ".mts", + ".cts", + ".js", + ".jsx", + ".mjs", + ".cjs", +]); +const SKIP_DIRS = new Set([".git", ".venv", "coverage", "dist", "node_modules"]); +const REGISTRATION_NAMES = new Set(["describe", "it", "suite", "test"]); +const REGISTRATION_MODIFIERS = new Set([ + "concurrent", + "each", + "fails", + "for", + "only", + "runIf", + "scoped", + "sequential", + "skip", + "skipIf", + "todo", +]); + +type CallChain = { + readonly rootName: string; + readonly rootNode: ts.Identifier; + readonly members: readonly string[]; +}; + +type VitestBindings = { + readonly registrations: ReadonlyMap; + readonly namespaces: ReadonlySet; +}; + +function scriptKindFor(filePath: string): ts.ScriptKind { + if (/\.tsx$/i.test(filePath)) return ts.ScriptKind.TSX; + if (/\.jsx$/i.test(filePath)) return ts.ScriptKind.JSX; + if (/\.[cm]?js$/i.test(filePath)) return ts.ScriptKind.JS; + return ts.ScriptKind.TS; +} + +function bindSourceFile(file: string, source: string): { + readonly checker: ts.TypeChecker; + readonly sourceFile: ts.SourceFile; +} { + const fileName = path.resolve(file); + const sourceFile = ts.createSourceFile( + fileName, + source, + ts.ScriptTarget.Latest, + true, + scriptKindFor(fileName), + ); + const host: ts.CompilerHost = { + fileExists: (candidate) => path.resolve(candidate) === fileName, + getCanonicalFileName: (candidate) => candidate, + getCurrentDirectory: () => path.dirname(fileName), + getDefaultLibFileName: () => "lib.d.ts", + getNewLine: () => "\n", + getSourceFile: (candidate) => (path.resolve(candidate) === fileName ? sourceFile : undefined), + readFile: (candidate) => (path.resolve(candidate) === fileName ? source : undefined), + useCaseSensitiveFileNames: () => true, + writeFile: () => undefined, + }; + const program = ts.createProgram( + [fileName], + { allowJs: true, noLib: true, noResolve: true, target: ts.ScriptTarget.Latest }, + host, + ); + return { checker: program.getTypeChecker(), sourceFile }; +} + +function collectVitestBindings( + sourceFile: ts.SourceFile, + checker: ts.TypeChecker, +): VitestBindings { + const registrations = new Map(); + const namespaces = new Set(); + + for (const statement of sourceFile.statements) { + if ( + !ts.isImportDeclaration(statement) || + !ts.isStringLiteral(statement.moduleSpecifier) || + statement.moduleSpecifier.text !== "vitest" + ) { + continue; + } + const importClause = statement.importClause; + if (importClause === undefined || importClause.isTypeOnly) continue; + + const bindings = importClause.namedBindings; + if (bindings === undefined) continue; + if (ts.isNamespaceImport(bindings)) { + const symbol = checker.getSymbolAtLocation(bindings.name); + if (symbol !== undefined) namespaces.add(symbol); + continue; + } + for (const element of bindings.elements) { + if (element.isTypeOnly) continue; + const importedName = element.propertyName?.text ?? element.name.text; + if (REGISTRATION_NAMES.has(importedName)) { + const symbol = checker.getSymbolAtLocation(element.name); + if (symbol !== undefined) registrations.set(symbol, importedName); + } + } + } + + return { registrations, namespaces }; +} + +function callChain(expression: ts.Expression): CallChain | null { + if (ts.isIdentifier(expression)) { + return { rootName: expression.text, rootNode: expression, members: [] }; + } + if (ts.isPropertyAccessExpression(expression)) { + const inner = callChain(expression.expression); + if (inner === null) return null; + return { ...inner, members: [...inner.members, expression.name.text] }; + } + if (ts.isTaggedTemplateExpression(expression)) return callChain(expression.tag); + if (ts.isCallExpression(expression)) return callChain(expression.expression); + return null; +} + +function registrationCall( + chain: CallChain, + bindings: VitestBindings, + checker: ts.TypeChecker, +): string | null { + const symbol = checker.getSymbolAtLocation(chain.rootNode); + if (symbol === undefined) return null; + const imported = bindings.registrations.get(symbol); + const name = imported ?? (bindings.namespaces.has(symbol) ? chain.members[0] : undefined); + const modifiers = imported === undefined ? chain.members.slice(1) : chain.members; + if (name === undefined || !REGISTRATION_NAMES.has(name)) return null; + if (!modifiers.every((modifier) => REGISTRATION_MODIFIERS.has(modifier))) return null; + return [chain.rootName, ...chain.members].join("."); +} + +export function scanTestRegistrations( + file: string, + source: string, +): readonly TestRegistrationViolation[] { + if (!source.includes("vitest")) return []; + const { checker, sourceFile } = bindSourceFile(file, source); + const bindings = collectVitestBindings(sourceFile, checker); + if (bindings.registrations.size === 0 && bindings.namespaces.size === 0) return []; + + const violations: TestRegistrationViolation[] = []; + const reported = new Set(); + + function visit(node: ts.Node): void { + if (ts.isCallExpression(node)) { + const chain = callChain(node.expression); + const call = chain === null ? null : registrationCall(chain, bindings, checker); + if (chain !== null && call !== null) { + const start = chain.rootNode.getStart(sourceFile); + if (!reported.has(start)) { + reported.add(start); + const location = sourceFile.getLineAndCharacterOfPosition(start); + violations.push({ + file, + line: location.line + 1, + column: location.character + 1, + call, + }); + } + } + } + ts.forEachChild(node, visit); + } + + visit(sourceFile); + return violations; +} + +export function isScannedModule(file: string, suiteImportedByTest = false): boolean { + const name = path.basename(file); + return ( + SOURCE_FILE_PATTERN.test(name) && + !TEST_FILE_PATTERN.test(name) && + (!SUITE_FILE_PATTERN.test(name) || !suiteImportedByTest) + ); +} + +function isSkipped(absolutePath: string): boolean { + const segments = path.relative(REPO_ROOT, absolutePath).split(path.sep); + return segments.some((segment) => SKIP_DIRS.has(segment)); +} + +function* walkSourceModules(directory: string): Generator { + if (!existsSync(directory) || isSkipped(directory)) return; + + for (const entry of readdirSync(directory, { withFileTypes: true })) { + if (entry.isSymbolicLink()) continue; + const absolutePath = path.join(directory, entry.name); + if (isSkipped(absolutePath)) continue; + if (entry.isDirectory()) { + yield* walkSourceModules(absolutePath); + } else if (entry.isFile() && SOURCE_FILE_PATTERN.test(entry.name)) { + yield absolutePath; + } + } +} + +function staticModuleSpecifiers(sourceFile: ts.SourceFile): readonly string[] { + const specifiers: string[] = []; + for (const statement of sourceFile.statements) { + if ( + (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && + statement.moduleSpecifier !== undefined && + ts.isStringLiteral(statement.moduleSpecifier) + ) { + specifiers.push(statement.moduleSpecifier.text); + } + } + return specifiers; +} + +function resolveRelativeModule( + importer: string, + specifier: string, + modules: ReadonlySet, +): string | null { + if (!specifier.startsWith(".")) return null; + const base = path.resolve(path.dirname(importer), specifier); + const extension = path.extname(base); + const stem = SOURCE_EXTENSIONS.includes(extension) ? base.slice(0, -extension.length) : base; + const candidates = new Set([base, ...SOURCE_EXTENSIONS.map((suffix) => `${stem}${suffix}`)]); + for (const candidate of candidates) { + if (modules.has(candidate)) return candidate; + } + return null; +} + +function importedSuiteModules(modules: ReadonlySet): ReadonlySet { + const importedSuites = new Set(); + for (const importer of modules) { + if (!TEST_FILE_PATTERN.test(path.basename(importer))) continue; + const source = readFileSync(importer, "utf8"); + const sourceFile = ts.createSourceFile( + importer, + source, + ts.ScriptTarget.Latest, + true, + scriptKindFor(importer), + ); + for (const specifier of staticModuleSpecifiers(sourceFile)) { + const resolved = resolveRelativeModule(importer, specifier, modules); + if (resolved !== null && SUITE_FILE_PATTERN.test(path.basename(resolved))) { + importedSuites.add(resolved); + } + } + } + return importedSuites; +} + +export function findTestRegistrationViolations( + roots: readonly string[] = DEFAULT_SCAN_ROOTS, +): readonly TestRegistrationViolation[] { + const violations: TestRegistrationViolation[] = []; + const modules = new Set(); + for (const root of roots) { + const absoluteRoot = path.resolve(REPO_ROOT, root); + for (const absolutePath of walkSourceModules(absoluteRoot)) modules.add(absolutePath); + } + const importedSuites = importedSuiteModules(modules); + for (const absolutePath of modules) { + if (!isScannedModule(absolutePath, importedSuites.has(absolutePath))) continue; + const file = path.relative(REPO_ROOT, absolutePath).split(path.sep).join("/"); + violations.push(...scanTestRegistrations(file, readFileSync(absolutePath, "utf8"))); + } + return violations; +} + +export function formatViolations(violations: readonly TestRegistrationViolation[]): string { + const lines = [ + "Test registration boundary check failed.", + "", + "These modules register Vitest tests, but Vitest does not collect them as test", + "files. Their cases run only when a collected test file imports the module, and", + "not at all when nothing imports it. Either way the cases stay outside the", + "vitest-project-overlap, test file size budget, and test-title-style checks.", + "", + "Fix: move each registration into a collected test file — root test/**/*.test.ts,", + "a co-located src/**/*.test.ts, or test/e2e/support/**. Rename the module to", + "*-suite.ts only when a collected test file imports it to register shared tests.", + "", + ]; + for (const violation of violations) { + lines.push(`- ${violation.file}:${violation.line}:${violation.column} ${violation.call}(...)`); + } + return lines.join("\n"); +} + +function main(): void { + const violations = findTestRegistrationViolations(); + if (violations.length === 0) { + console.log("Test registration boundary check passed."); + return; + } + + console.error(formatViolations(violations)); + console.error(`Found ${violations.length} test registration violation(s).`); + process.exitCode = 1; +} + +const invokedPath = process.argv[1]; +if ( + invokedPath !== undefined && + import.meta.url === pathToFileURL(path.resolve(invokedPath)).href +) { + main(); +} diff --git a/test/checks-runner.test.ts b/test/checks-runner.test.ts index d727788d9ad..66718c3950f 100644 --- a/test/checks-runner.test.ts +++ b/test/checks-runner.test.ts @@ -25,6 +25,14 @@ describe("checks runner", () => { }); }); + it("registers the test registration boundary check", () => { + expect(CHECKS).toContainEqual({ + name: "test-registration-boundary", + command: process.platform === "win32" ? "tsx.cmd" : "tsx", + args: ["scripts/checks/test-registration-boundary.mts"], + }); + }); + it("runs Windows command shims through cmd.exe", () => { expect( buildCheckSpawnInvocation(sampleCheck, "win32", { diff --git a/test/test-registration-boundary.test.ts b/test/test-registration-boundary.test.ts new file mode 100644 index 00000000000..ced2e3fd689 --- /dev/null +++ b/test/test-registration-boundary.test.ts @@ -0,0 +1,278 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + findTestRegistrationViolations, + formatViolations, + isScannedModule, + scanTestRegistrations, +} from "../scripts/checks/test-registration-boundary.mts"; + +function scan(source: string, file = "test/helpers/example-helper.ts") { + return scanTestRegistrations(file, source); +} + +describe("test registration boundary scanner", () => { + it("flags a helper module that registers a suite", () => { + const violations = scan( + [ + 'import { describe, expect, it } from "vitest";', + "", + "export function registerExampleTests() {", + ' describe("example", () => {', + ' it("holds", () => expect(1).toBe(1));', + " });", + "}", + ].join("\n"), + ); + + expect(violations).toEqual([ + { file: "test/helpers/example-helper.ts", line: 4, column: 3, call: "describe" }, + { file: "test/helpers/example-helper.ts", line: 5, column: 5, call: "it" }, + ]); + }); + + it("flags the describe, it, suite, and test registrations", () => { + const violations = scan( + [ + 'import { describe, it, suite, test } from "vitest";', + "", + 'describe("a", () => {});', + 'it("b", () => {});', + 'suite("c", () => {});', + 'test("d", () => {});', + ].join("\n"), + ); + + expect(violations.map(({ call }) => call)).toEqual(["describe", "it", "suite", "test"]); + }); + + it("flags modifier chains on a registration binding", () => { + const violations = scan( + [ + 'import { describe, it, test } from "vitest";', + "", + 'describe.each([1, 2])("each %i", () => {});', + 'it.only("only", () => {});', + 'it.skip("skip", () => {});', + 'test.skipIf(false)("skipIf", () => {});', + 'test.runIf(true)("runIf", () => {});', + 'describe.concurrent("concurrent", () => {});', + ].join("\n"), + ); + + expect(violations.map(({ call }) => call)).toEqual([ + "describe.each", + "it.only", + "it.skip", + "test.skipIf", + "test.runIf", + "describe.concurrent", + ]); + }); + + it("reports a chained registration once at the root binding", () => { + const violations = scan( + ['import { it } from "vitest";', "", 'it.skipIf(false)("chained", () => {});'].join("\n"), + ); + + expect(violations).toEqual([ + { file: "test/helpers/example-helper.ts", line: 3, column: 1, call: "it.skipIf" }, + ]); + }); + + it("resolves a renamed registration import", () => { + const violations = scan( + [ + 'import { describe as group, it as scenario } from "vitest";', + "", + 'group("renamed", () => {', + ' scenario("case", () => {});', + "});", + ].join("\n"), + ); + + expect(violations.map(({ call }) => call)).toEqual(["group", "scenario"]); + }); + + it("resolves registrations reached through a namespace import", () => { + const violations = scan( + [ + 'import * as vitest from "vitest";', + "", + 'vitest.describe.only("namespaced", () => {});', + ].join("\n"), + ); + + expect(violations.map(({ call }) => call)).toEqual(["vitest.describe.only"]); + }); + + it("flags tagged-template registrations through direct, renamed, and namespace imports", () => { + const violations = scan( + [ + 'import { describe, test as scenario } from "vitest";', + 'import * as vitest from "vitest";', + "", + 'describe.each`value | expected\n${1} | ${1}`("direct", () => {});', + 'scenario.each`value\n${2}`("renamed", () => {});', + 'vitest.suite.each`value\n${3}`("namespaced", () => {});', + ].join("\n"), + ); + + expect(violations.map(({ call }) => call)).toEqual([ + "describe.each", + "scenario.each", + "vitest.suite.each", + ]); + }); + + it("does not flag fixture extension", () => { + const violations = scan( + [ + 'import { test as base, describe, expect } from "vitest";', + "", + "export const test = base.extend({", + " resource: async ({}, use) => {", + " await use({});", + " },", + "});", + "", + "export { describe, expect };", + ].join("\n"), + ); + + expect(violations).toEqual([]); + }); + + it("does not flag registration names inside comments and strings", () => { + const violations = scan( + [ + 'import { describe } from "vitest";', + "", + '// describe("commented", () => {});', + '/* it("blocked", () => {}); */', + "export const label = 'test(\"quoted\", () => {})';", + ].join("\n"), + ); + + expect(violations).toEqual([]); + }); + + it("does not flag a locally declared registration name", () => { + const violations = scan( + [ + 'import { expect } from "vitest";', + "", + "function it(title: string, body: () => void) {", + " return { title, body };", + "}", + "", + 'export const recorded = it("local", () => expect(true).toBe(true));', + ].join("\n"), + ); + + expect(violations).toEqual([]); + }); + + it("resolves a nested registration parameter instead of the imported binding", () => { + const violations = scan( + [ + 'import { it } from "vitest";', + "", + 'it("imported", () => {});', + "function invoke(it: (title: string, body: () => void) => unknown) {", + ' it("local", () => {});', + "}", + ].join("\n"), + ); + + expect(violations).toEqual([ + { file: "test/helpers/example-helper.ts", line: 3, column: 1, call: "it" }, + ]); + }); + + it("does not flag a type-only Vitest import", () => { + const violations = scan( + [ + 'import type { TestContext } from "vitest";', + "", + "export function describe(context: TestContext) {", + " return context;", + "}", + "", + "export const described = describe({} as TestContext);", + ].join("\n"), + ); + + expect(violations).toEqual([]); + }); +}); + +describe("test registration boundary module selection", () => { + it("selects modules that Vitest does not collect as test files", () => { + expect(isScannedModule("test/helpers/example-helper.ts")).toBe(true); + expect(isScannedModule("src/lib/example.mts")).toBe(true); + expect(isScannedModule("bin/example.js")).toBe(true); + }); + + it("does not select test or spec files", () => { + expect(isScannedModule("src/lib/example.test.ts")).toBe(false); + expect(isScannedModule("test/example.spec.js")).toBe(false); + }); + + it("selects an orphan suite module but exempts one imported by a test", () => { + expect(isScannedModule("test/orphan-suite.ts")).toBe(true); + expect(isScannedModule("test/local-credential-helper-suite.ts", true)).toBe(false); + expect(isScannedModule("test/openclaw-integrity-pin-suite.ts", true)).toBe(false); + }); + + it("does not select files that are not JavaScript or TypeScript", () => { + expect(isScannedModule("docs/example.mdx")).toBe(false); + expect(isScannedModule("scripts/example.sh")).toBe(false); + }); +}); + +describe("test registration boundary diagnostics", () => { + it("names the file, position, and remediation for each violation", () => { + const report = formatViolations([ + { file: "test/helpers/example-helper.ts", line: 4, column: 3, call: "describe" }, + ]); + + expect(report).toContain("test/helpers/example-helper.ts:4:3 describe(...)"); + expect(report).toContain("*.test.ts"); + expect(report).toContain("*-suite.ts"); + }); +}); + +describe("test registration boundary repository state", () => { + it("exempts an imported suite module and reports an orphan suite module", () => { + const root = mkdtempSync(path.join(os.tmpdir(), "nemoclaw-test-registration-boundary-")); + try { + writeFileSync(path.join(root, "collected.test.ts"), 'import "./imported-suite";\n'); + writeFileSync( + path.join(root, "imported-suite.ts"), + 'import { it } from "vitest";\nit("imported", () => {});\n', + ); + writeFileSync( + path.join(root, "orphan-suite.ts"), + 'import { it } from "vitest";\nit("orphan", () => {});\n', + ); + + const violations = findTestRegistrationViolations([root]); + + expect(violations).toHaveLength(1); + expect(path.basename(violations[0]?.file ?? "")).toBe("orphan-suite.ts"); + } finally { + rmSync(root, { force: true, recursive: true }); + } + }); + + it("reports no test registration outside test and suite files", () => { + expect(findTestRegistrationViolations()).toEqual([]); + }); +});