From 1d4339d455ea7c5c392814c59cf0acba5dbc6626 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 13:10:44 +0900 Subject: [PATCH 01/14] fix(test-inventory): mark only calls into functions that can receive a test context as opaque Since the contextual gate was inverted, any helper that hands its parameter on (check(x) { expect(x).toBe(2) }) was opaque_call when called with a call result, an imported value or a let variable, for Vitest and Jest too. A call is now opaque only when the function can really receive a context (it is passed by name to the runner, or reached from one with a test's context) and is also reached with something else, or uses its context in ways not followed: handing it to a call other than a tracked local function, storing it, arguments, a rest parameter. A let never assigned again is traced like a const. helper(assert) and helper(new AssertionError()) are no_assertion again. A callback passed by name whose context escapes the same way (test('x', viaMethod), stored, arguments, a rest parameter) is analysed as the test body and now inconclusive (opaque_call) instead of no_assertion, matching (t) => viaMethod(t). --- packages/test-inventory/src/index.ts | 135 +++++++++++++++- .../test/context-precision.test.ts | 153 ++++++++++++++++++ 2 files changed, 282 insertions(+), 6 deletions(-) create mode 100644 packages/test-inventory/test/context-precision.test.ts diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index dafc578c..bc2eebea 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -8503,6 +8503,10 @@ function readTest( // A callback passed some other way (an imported function, a call's result) cannot be read: the test is not // judged empty for it. const unreadCallbackArgument = testFn === undefined && opaqueCallback(info.callback); + // A function passed by name that uses its context in ways not followed (`runner.run(t)`, `{ t }`, `arguments`, + // a rest parameter): what it asserts through the context is unknown, as when a test hands it its context. + const escapedContext = + testFn !== undefined && contextCallback === testFn && contextEscapes(testFn, checker); const nodes = body ? descendants(body) : []; const contextParameter = testFn?.parameters[0] && ts.isIdentifier(testFn.parameters[0].name) @@ -8629,6 +8633,7 @@ function readTest( !unreadCallback && !analysis?.helperAsserts && !analysis?.assertionsUnknown && + !escapedContext && !callsHelperWithAssertion(body, source) ) suspicions.push('no_assertion'); @@ -8637,7 +8642,7 @@ function readTest( // Code that runs when the file loads (outside any function), its own or that of the local modules it imports, // runs before every test in it. const loading = fileLoadReach(source, ctx); - const opaque = analysis?.opaque === true || loading.opaque || unreadCallback; + const opaque = analysis?.opaque === true || loading.opaque || unreadCallback || escapedContext; const unresolved = unresolvedImports.size > 0 || loading.unresolved; // An unresolved import, a child process or a dynamic import may well reach project code: absence is not proven. @@ -10742,16 +10747,132 @@ let contextCallback: ts.Node | undefined; * may come from a test with a real context, where the function's assertions are not counted. Decided from the file's * structure alone, never from which test is being read, so it does not depend on the order tests are analysed in. */ +/** Whether a variable is never assigned after its declaration (`x = …`, `x += …`, `x++`, a destructuring target). */ +function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeChecker): boolean { + const symbol = checker.getSymbolAtLocation(declaration.name); + const assigned = (node: ts.Identifier): boolean => { + let target: ts.Node = node; + + while ( + ts.isParenthesizedExpression(target.parent) || + ts.isShorthandPropertyAssignment(target.parent) || + ts.isPropertyAssignment(target.parent) || + ts.isArrayLiteralExpression(target.parent) || + ts.isObjectLiteralExpression(target.parent) + ) + target = target.parent; + const parent = target.parent; + + return ( + (ts.isBinaryExpression(parent) && + parent.left === target && + parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && + parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment) || + ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && + (parent.operator === ts.SyntaxKind.PlusPlusToken || + parent.operator === ts.SyntaxKind.MinusMinusToken)) || + ts.isForInStatement(parent) || + ts.isForOfStatement(parent) + ); + }; + + return ( + symbol !== undefined && + descendants(declaration.getSourceFile()).every( + (node) => + !ts.isIdentifier(node) || + node === declaration.name || + checker.getSymbolAtLocation(node) !== symbol || + !assigned(node), + ) + ); +} + +/** + * Whether a function uses its context parameter in a way no context is traced through: a rest parameter or a rest + * element, `arguments`, a computed member read, or the parameter (or a destructured member of it) handed to anything + * but a local function's first argument, stored, returned, spread or assigned. Member reads (`t.assert.equal`), uses + * that read nothing (`primitiveUse`) and forwarding to a local function (followed by `contextReach`) are followed. + */ +function contextEscapes(fn: ts.SignatureDeclaration, checker: ts.TypeChecker): boolean { + const parameter = fn.parameters[0]; + const body = (fn as ts.FunctionLikeDeclaration).body; + + if (readsArguments(fn)) return true; + + if (!parameter || !body) return false; + + if (parameter.dotDotDotToken) return true; + const names: ts.Identifier[] = []; + const collect = (name: ts.BindingName): boolean => { + if (ts.isIdentifier(name)) { + names.push(name); + + return true; + } + + return name.elements.every( + (element) => ts.isOmittedExpression(element) || (!element.dotDotDotToken && collect(element.name)), + ); + }; + + if (!collect(parameter.name)) return true; + const symbols = new Set(names.map((name) => checker.getSymbolAtLocation(name))); + const reach = contextReach(fn.getSourceFile(), checker); + + return descendants(body).some((node) => { + if (!ts.isIdentifier(node)) return false; + + if (ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node) + return symbols.has(checker.getShorthandAssignmentValueSymbol(node.parent)); + + if (!symbols.has(checker.getSymbolAtLocation(node))) return false; + const parent = node.parent; + + if (ts.isPropertyAccessExpression(parent) && parent.expression === node) return false; + + // A member destructured from the context, called (`({ expect }) => expect(x)`). + if (ts.isCallExpression(parent) && parent.expression === node) return false; + + if (primitiveUse(node)) return false; + + // `helper(t)`: followed when the helper is a local function `contextReach` tracks. + if (ts.isCallExpression(parent) && parent.arguments[0] === node) { + const callee = skipParens(parent.expression); + const declaration = ts.isIdentifier(callee) + ? checker.getSymbolAtLocation(callee)?.valueDeclaration + : undefined; + const target = + declaration && ts.isFunctionDeclaration(declaration) + ? declaration + : declaration && ts.isVariableDeclaration(declaration) && declaration.initializer + ? skipParens(declaration.initializer) + : undefined; + + return !(target && (reach.real.has(target) || reach.fake.has(target) || reach.unknown.has(target))); + } + + return true; + }); +} + function handsContextToMixedCallback(node: Invocation, body: ts.Node, checker: ts.TypeChecker): boolean { const fn = body.parent; if (!ts.isCallExpression(node) || !fn || !isFunctionLike(fn)) return false; const reach = contextReach(fn.getSourceFile(), checker); - if (!reach.contextual.has(fn)) return false; + // Only a function that can really receive a context (one passed by name to the runner, or reached from one with a + // test's context): an ordinary helper (`check(x) { expect(x).toBe(2) }`) is judged as any other call. + if (!reach.contextual.has(fn) || !reach.real.has(fn)) return false; - // A function reading `arguments` uses what it is handed in ways no context is traced through. - if (!reach.unknown.has(fn) && !(reach.real.has(fn) && reach.fake.has(fn)) && !readsArguments(fn)) + // Reached also with something else, or using its context in ways no context is traced through (handing it to a + // call, storing it, `arguments`, a rest parameter). + if ( + !reach.unknown.has(fn) && + !reach.fake.has(fn) && + !contextEscapes(fn as ts.SignatureDeclaration, checker) + ) return false; // Opaque unless what the call hands it is plainly not a context (a literal, an object written there). @@ -10779,12 +10900,14 @@ function traceArgument( if (declaration && ts.isParameter(declaration)) return declaration; + // A `const`, or a `let` or `var` never assigned again (`let context = t`), stands for its initializer. if ( declaration && ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) && - (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0 && - declaration.initializer + declaration.initializer && + ((ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0 || + neverReassigned(declaration, checker)) ) return traceArgument(declaration.initializer, checker, depth + 1); diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts new file mode 100644 index 00000000..241ef2c8 --- /dev/null +++ b/packages/test-inventory/test/context-precision.test.ts @@ -0,0 +1,153 @@ +import { VeritasConfig } from '@under18dev/veritas-core'; +import { jestTestRunner as jest } from '@under18dev/veritas-test-runner-jest'; +import { nodeTestRunner as node } from '@under18dev/veritas-test-runner-node'; +import { vitestTestRunner as vitest } from '@under18dev/veritas-test-runner-vitest'; +import { describe, expect, it } from 'vitest'; +import { inventoryTests } from '../src/index.js'; +import { tempProject } from './helpers.js'; + +const SERVICE = `export const svc = { price: (n: number) => n + 1 };\nexport const value = (n: number) => n + 1;\nexport const two = 2;\n`; + +const inventory = (root: string, recognition: Parameters[0]['recognition']) => + inventoryTests({ + recognition, + root, + config: VeritasConfig.parse({ analysis: { testInclude: ['test/*.test.ts'] } }), + }); + +function byName(tests: ReturnType['tests'], name: string) { + const test = tests.find((candidate) => candidate.name === name); + + if (!test) throw new Error(`missing test: ${name}`); + + return test; +} + +describe('test contexts and ordinary helpers', () => { + const helperCases = (header: string, assertion: string) => ` + ${header} + import { svc, two } from '../src/svc'; + function check(x: number) { ${assertion} } + test('call result', () => { check(svc.price(1)); }); + test('imported value', () => { check(two); }); + test('let variable', () => { + let n = svc.price(1); + n += 0; + check(n); + }); + `; + + for (const [runner, recognition, header, assertion] of [ + ['Vitest', vitest.recognition, "import { expect, test } from 'vitest';", 'expect(x).toBe(2);'], + ['Jest', jest.recognition, '', 'expect(x).toBe(2);'], + [ + 'node:test', + node.recognition, + "import { test } from 'node:test';\nimport assert from 'node:assert/strict';", + 'assert.equal(x, 2);', + ], + ] as const) + it(`judges an ordinary assertion helper as before, never opaque (${runner})`, () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/helper.test.ts': helperCases(header, assertion), + }); + const { tests } = inventory(root, recognition); + + for (const name of ['call result', 'imported value', 'let variable']) { + expect(byName(tests, name).suspicions, `${runner} ${name}`).not.toContain('opaque_call'); + expect(byName(tests, name).suspicions, `${runner} ${name}`).not.toContain('no_assertion'); + } + }); + + it('judges a helper handed node:assert or an error, not a context, as asserting nothing', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/n28a.test.ts': ` + import { test } from 'node:test'; + import assert, { AssertionError } from 'node:assert'; + import { value } from '../src/svc'; + function helper(a) { a.equal(value(1), 2); } + test('handed assert', () => { helper(assert); }); + test('handed an error', () => { helper(new AssertionError({ message: 'x' })); }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['handed assert', 'handed an error']) { + expect(byName(tests, name).suspicions, name).toContain('no_assertion'); + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + } + }); + + it('keeps a test that hands its context to a helper using it in ways not followed inconclusive', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/c1.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + const runner = { run(t) { t.assert.equal(value(1), 2); } }; + function destr({ assert }) { assert.equal(value(1), 2); } + function viaMethod(t) { runner.run(t); } + function stored(t) { const s = { t }; s.t.assert.equal(value(1), 2); } + function args0() { arguments[0].assert.equal(value(1), 2); } + function rest(...all) { all[0].assert.equal(value(1), 2); } + test('destr caller', (t) => destr(t)); + test('viaMethod caller', (t) => viaMethod(t)); + test('stored caller', (t) => stored(t)); + test('args0 caller', (t) => args0(t)); + test('rest caller', (t) => rest(t)); + test('destr by reference', destr); + test('viaMethod by reference', viaMethod); + test('stored by reference', stored); + test('args0 by reference', args0); + test('rest by reference', rest); + `, + }); + const { tests } = inventory(root, node.recognition); + + // The destructured member is read as the context's: the assertion counts. + expect(byName(tests, 'destr by reference').assertionCount).toBe(1); + + for (const name of ['destr caller', 'destr by reference']) { + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + expect( + byName(tests, name).targetCalls.some((call) => call.asserted), + name, + ).toBe(true); + } + + for (const name of [ + 'viaMethod caller', + 'stored caller', + 'args0 caller', + 'rest caller', + 'viaMethod by reference', + 'stored by reference', + 'args0 by reference', + 'rest by reference', + ]) { + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + expect(byName(tests, name).suspicions, name).toContain('opaque_call'); + } + }); + + it("keeps Vitest's destructured expect working in a callback passed by name", () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/ctx.test.ts': ` + import { test } from 'vitest'; + import { value } from '../src/svc'; + function check({ expect }) { expect(value(1)).toBe(2); } + test('by reference', check); + test('inline', ({ expect }) => { expect(value(1)).toBe(2); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + for (const name of ['by reference', 'inline']) { + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + } + }); +}); From cf20517d91d5990e922c0d2fb693bf5e18bfb245 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 13:10:45 +0900 Subject: [PATCH 02/14] docs: describe when a test handing its context on is inconclusive --- docs/concepts/support-matrix.md | 2 +- docs/ja/concepts/support-matrix.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/concepts/support-matrix.md b/docs/concepts/support-matrix.md index aa0adb84..5914b0d6 100644 --- a/docs/concepts/support-matrix.md +++ b/docs/concepts/support-matrix.md @@ -66,7 +66,7 @@ The Node.js test runner is built into Node.js, so `init` never chooses it just f With Jest, what `jest.mock` does depends on how the tests run. Babel and ts-jest compile them to CommonJS and hoist `jest.mock` above the imports, so it replaces the module and Veritas records a mock. In native ES modules (`"type": "module"` with no Babel config, no compiling transformer, and a Jest config whose `transform` is absent or empty and that has no `preset`; when in doubt, Veritas keeps counting `jest.mock` as a mock) the static imports are bound before `jest.mock` runs and the tests reach the real code, so Veritas does not count it as a mock of them; `jest.unstable_mockModule` followed by a dynamic `import()` is the ESM way, and what such an import loads is reported as unknown. -With the Node.js test runner, Veritas reads `test`/`it` and `describe`/`suite` from `node:test` (named, aliased, or the default import `import test from 'node:test'`, also through its members such as `test.describe` and `test.it`), `.skip`/`.todo`/`.only` and the same as an options object (`{ skip: true }`, `{ skip: 'reason' }`, `{ todo: 'later' }`, `{ only: true }`), the hooks `before`/`after`/`beforeEach`/`afterEach`, and the `mock` API (`mock.fn`, `mock.method`, `mock.getter`/`mock.setter`, `mock.module`). Every value export of `node:assert`, `node:assert/strict` and `assert` counts as an assertion (`assert(x)`, `assert.equal`, named imports such as `strictEqual`, `assert.strict.*`, `require`); a call counts only when its name resolves to that import, so a local function of the same name does not. So does `t.assert.*` on the test context and on the contexts of its subtests. CommonJS test files that bind them with a top-level `const { test } = require('node:test')` or `const assert = require('node:assert')` are read the same way, including modifiers read on a required member (`require('node:test')['describe']['skip']`, `test['skip'](...)`), and `node:assert` required inside a test; `require` counts only when the file does not declare its own. CommonJS has no default export, so `require('node:test').default` and `const { default: test } = require('node:test')` register nothing, while `import { default as test } from 'node:test'` does. Subtests (`t.test`) are analysed as part of the test that registers them, not listed on their own. With any runner, a test file matching `analysis.testInclude` from which no test registration can be read (its tests are registered by code static analysis does not follow) is named in the messages of the `map` stage, which is then `partial`, so the run cannot report `pass`. A file is left out only when it is shown to register nothing: every statement of it and of each local module it loads is known to run no code when it loads, and no module it imports registers tests. Known to run none are imports and exports of modules that pass the package rule, declarations of functions, types, interfaces, const or literal enums and classes without decorators, static blocks or static initialisers that run code, variables and `export default` of inert values (literals, templates without substitutions, functions, object and array literals of such values without spread, local names), CommonJS exports of inert values, a few inert builtins (`Symbol()`, `Object.freeze()`, path and URL helpers) and the runner's hooks and mock configuration (`beforeAll`, `vi.mock`, `jest.setTimeout`). Anything else counts: other calls, `new`, `await`, loops, spread, assignments, member reads that may run a getter, decorators. A package loaded for its side effects (`import 'pkg'`), re-exported whole (`export * from 'pkg'`) or imported dynamically always counts, and in a file of the runner's own pattern (`*.test.*`, `*.spec.*`) so does a package imported by name anywhere in its local imports; in a helper matched only by a directory glob, a package imported by name and used only inside functions does not. This has a known limitation with the Node.js test runner: `node --test` runs every file under a `test` directory as a test file, but a file matched only by such a directory glob (`**/test/**`) still uses the looser rule, so a file there that only binds a package import is not named, even if that package registers tests when it is imported. A local module that does not resolve counts too. A file that the rest of static analysis already finds open (code at load time it cannot read, or code it does not follow, such as a dynamic import of a computed name or a computed member of the runner; re-exports of the runner's API, local JSON loaded by `require` or `import()`, CommonJS exports of inert values and, in a helper matched only by a directory glob, a top-level `require` of a package used only inside functions are not such code) is never left out, whatever this rule says. So a barrel such as `export { test } from 'node:test'` or a helper that only defines functions is not named, while one that runs `const app = createApp()` when it loads is. When the code it runs calls into a package (`import { suite } from 'some-lib'; suite()`), possibly in a local module it loads, the message names the package and that module. A file that uses another runner's API (`bun:test`, `Deno.test`) is named with that reason. The message names the first 10 files and counts the rest. +With the Node.js test runner, Veritas reads `test`/`it` and `describe`/`suite` from `node:test` (named, aliased, or the default import `import test from 'node:test'`, also through its members such as `test.describe` and `test.it`), `.skip`/`.todo`/`.only` and the same as an options object (`{ skip: true }`, `{ skip: 'reason' }`, `{ todo: 'later' }`, `{ only: true }`), the hooks `before`/`after`/`beforeEach`/`afterEach`, and the `mock` API (`mock.fn`, `mock.method`, `mock.getter`/`mock.setter`, `mock.module`). Every value export of `node:assert`, `node:assert/strict` and `assert` counts as an assertion (`assert(x)`, `assert.equal`, named imports such as `strictEqual`, `assert.strict.*`, `require`); a call counts only when its name resolves to that import, so a local function of the same name does not. So does `t.assert.*` on the test context and on the contexts of its subtests. Members destructured from the context (`({ assert, mock }) => …`) are read the same way. When a test hands its context to a function that uses it in ways the analysis does not follow (passes it to another call, stores it, reads `arguments` or a rest parameter), including a function passed by name as the test itself, or to one that is also called with something else, the test is inconclusive (`opaque_call`) rather than judged to assert nothing. An ordinary helper that never receives a context (`function check(x) { expect(x).toBe(2) }`) is judged as any other call. CommonJS test files that bind them with a top-level `const { test } = require('node:test')` or `const assert = require('node:assert')` are read the same way, including modifiers read on a required member (`require('node:test')['describe']['skip']`, `test['skip'](...)`), and `node:assert` required inside a test; `require` counts only when the file does not declare its own. CommonJS has no default export, so `require('node:test').default` and `const { default: test } = require('node:test')` register nothing, while `import { default as test } from 'node:test'` does. Subtests (`t.test`) are analysed as part of the test that registers them, not listed on their own. With any runner, a test file matching `analysis.testInclude` from which no test registration can be read (its tests are registered by code static analysis does not follow) is named in the messages of the `map` stage, which is then `partial`, so the run cannot report `pass`. A file is left out only when it is shown to register nothing: every statement of it and of each local module it loads is known to run no code when it loads, and no module it imports registers tests. Known to run none are imports and exports of modules that pass the package rule, declarations of functions, types, interfaces, const or literal enums and classes without decorators, static blocks or static initialisers that run code, variables and `export default` of inert values (literals, templates without substitutions, functions, object and array literals of such values without spread, local names), CommonJS exports of inert values, a few inert builtins (`Symbol()`, `Object.freeze()`, path and URL helpers) and the runner's hooks and mock configuration (`beforeAll`, `vi.mock`, `jest.setTimeout`). Anything else counts: other calls, `new`, `await`, loops, spread, assignments, member reads that may run a getter, decorators. A package loaded for its side effects (`import 'pkg'`), re-exported whole (`export * from 'pkg'`) or imported dynamically always counts, and in a file of the runner's own pattern (`*.test.*`, `*.spec.*`) so does a package imported by name anywhere in its local imports; in a helper matched only by a directory glob, a package imported by name and used only inside functions does not. This has a known limitation with the Node.js test runner: `node --test` runs every file under a `test` directory as a test file, but a file matched only by such a directory glob (`**/test/**`) still uses the looser rule, so a file there that only binds a package import is not named, even if that package registers tests when it is imported. A local module that does not resolve counts too. A file that the rest of static analysis already finds open (code at load time it cannot read, or code it does not follow, such as a dynamic import of a computed name or a computed member of the runner; re-exports of the runner's API, local JSON loaded by `require` or `import()`, CommonJS exports of inert values and, in a helper matched only by a directory glob, a top-level `require` of a package used only inside functions are not such code) is never left out, whatever this rule says. So a barrel such as `export { test } from 'node:test'` or a helper that only defines functions is not named, while one that runs `const app = createApp()` when it loads is. When the code it runs calls into a package (`import { suite } from 'some-lib'; suite()`), possibly in a local module it loads, the message names the package and that module. A file that uses another runner's API (`bun:test`, `Deno.test`) is named with that reason. The message names the first 10 files and counts the rest. When Veritas runs these tests, it runs `node --test` from the project root with Node's default file patterns, not the project's test script, so extra flags such as `--import tsx` or custom globs in that script are not applied. The bundled reporter writes its JSON report inside `.veritas/improve/`. Tests are keyed `:: test > subtest>`, and skipped and todo tests count as skipped. TypeScript tests run through Node's type stripping, so they must use erasable syntax and import `.ts` file names. diff --git a/docs/ja/concepts/support-matrix.md b/docs/ja/concepts/support-matrix.md index 33d2bb35..921a3689 100644 --- a/docs/ja/concepts/support-matrix.md +++ b/docs/ja/concepts/support-matrix.md @@ -66,7 +66,7 @@ Node.js のテストランナーは Node.js に組み込まれているので、 Jest では、`jest.mock` の効果がテストの実行方法で変わります。Babel や ts-jest はテストを CommonJS にコンパイルし、`jest.mock` を import より前に移すので、モジュールが置き換わり、Veritas はモックとして記録します。ネイティブ ESM(`"type": "module"` で、Babel の設定もコンパイルする transformer もなく、Jest の設定の `transform` がないか空で `preset` もない。判断できないときは `jest.mock` をモックとして数え続けます)では、`jest.mock` が実行される前に静的な import が結び付けられ、テストは本物のコードを実行するので、Veritas はそれらのモックとして数えません。ESM でのモックは `jest.unstable_mockModule` と動的な `import()` の組み合わせで、そうした import が読み込むものは不明として報告します。 -Node.js のテストランナーでは、`node:test` の `test`/`it` と `describe`/`suite`(名前付き、別名、既定の import `import test from 'node:test'` のいずれも。`test.describe` や `test.it` のようにそのメンバーを通しても読みます)、`.skip`/`.todo`/`.only` と、同じ指定をオプションのオブジェクトで書いたもの(`{ skip: true }`、`{ skip: 'reason' }`、`{ todo: 'later' }`、`{ only: true }`)、フックの `before`/`after`/`beforeEach`/`afterEach`、`mock` の API(`mock.fn`、`mock.method`、`mock.getter`/`mock.setter`、`mock.module`)を読みます。`node:assert`、`node:assert/strict`、`assert` が export する値はすべて assertion として数え(`assert(x)`、`assert.equal`、`strictEqual` などの名前付き import、`assert.strict.*`、`require`)。数えるのは、呼び出した名前がその import に解決されるときだけで、同じ名前のローカルの関数は数えません。テストのコンテキストとそのサブテストのコンテキストの `t.assert.*` も同じです。トップレベルの `const { test } = require('node:test')` や `const assert = require('node:assert')` で束縛する CommonJS のテストファイルも、同じように読みます。require したメンバーに続けた修飾子(`require('node:test')['describe']['skip']`、`test['skip'](...)`)や、テストの中で require した `node:assert` も読みます。`require` は、ファイルが同じ名前を自分で宣言していないときだけ数えます。CommonJS には既定の export がないので、`require('node:test').default` や `const { default: test } = require('node:test')` はテストを登録しませんが、`import { default as test } from 'node:test'` は登録します。サブテスト(`t.test`)は、それを登録したテストの一部として解析し、単独では一覧に載せません。どのランナーでも、`analysis.testInclude` に当てはまるのにテストの登録を1つも読めなかったテストファイル(静的解析で追えないコードがテストを登録している場合など)は、`map` ステージのメッセージに名前が出ます。このとき `map` ステージは `partial` になり、実行結果が `pass` になることはありません。名前を出さないのは、テストを登録しないことを示せたファイルだけです。つまり、そのファイルと読み込むローカルのモジュールのすべての文が、読み込まれる間にコードを実行しないとわかっていて、テストを登録するモジュールを import していないファイルです。コードを実行しないとみなすのは、パッケージの規則を満たすモジュールの import と export、関数・型・interface・const か値がリテラルの enum・デコレーターや static ブロックやコードを実行する static 初期化子のない class の宣言、無害な値(リテラル、置換のないテンプレート、関数、spread のないそうした値のオブジェクトと配列、ローカルの名前)で初期化する変数と `export default`、無害な値の CommonJS の export、少数の無害な組み込み(`Symbol()`、`Object.freeze()`、パスと URL のヘルパー)、ランナーのフックとモックの設定(`beforeAll`、`vi.mock`、`jest.setTimeout`)だけです。それ以外の呼び出し、`new`、`await`、ループ、spread、代入、getter を実行しうるメンバーの読み取り、デコレーターはコードの実行とみなします。副作用のためのパッケージの読み込み(`import 'pkg'`)、パッケージ全体の re-export(`export * from 'pkg'`)、パッケージの動的 import は常に数えます。ランナー自身のパターン(`*.test.*`、`*.spec.*`)に当てはまるファイルでは、ローカルの import のどこかで名前付きでパッケージを import することも数えます。ディレクトリの glob だけで当てはまるヘルパーでは、名前付きで import して関数の中でだけ使うパッケージは数えません。これには Node.js のテストランナーで既知の制限があります。`node --test` は `test` ディレクトリの下のファイルをすべてテストファイルとして実行しますが、そうしたディレクトリの glob(`**/test/**`)だけで当てはまるファイルにはゆるいほうの規則を使います。そのため、そこにあってパッケージの import を束縛するだけのファイルは、そのパッケージが import されたときにテストを登録するものであっても、名前が出ません。解決できないローカルのモジュールも数えます。また、静的解析のほかの部分がすでに開いているとみなしたファイル(読み込み時に読めないコードがある、または計算された名前の動的 import やランナーの計算されたメンバーのように追えないコードに届く。ランナーの API の re-export、`require` や `import()` で読み込むローカルの JSON、無害な値の CommonJS の export、ディレクトリの glob だけで当てはまるヘルパーでトップレベルに `require` して関数の中でだけ使うパッケージは、これに当たりません)は、この規則にかかわらず必ず名前が出ます。そのため、`export { test } from 'node:test'` のような barrel や、関数を定義するだけのヘルパーは名前が出ませんが、読み込まれるときに `const app = createApp()` を実行するヘルパーは名前が出ます。実行するコードがパッケージを呼び出しているとき(`import { suite } from 'some-lib'; suite()`。読み込むローカルのモジュールの中の場合も含みます)は、メッセージにそのパッケージとモジュールが出ます。ほかのランナーの API(`bun:test`、`Deno.test`)を使うファイルは、その理由とともに名前が出ます。メッセージに名前が出るのは最初の 10 個までで、残りは数だけを示します。 +Node.js のテストランナーでは、`node:test` の `test`/`it` と `describe`/`suite`(名前付き、別名、既定の import `import test from 'node:test'` のいずれも。`test.describe` や `test.it` のようにそのメンバーを通しても読みます)、`.skip`/`.todo`/`.only` と、同じ指定をオプションのオブジェクトで書いたもの(`{ skip: true }`、`{ skip: 'reason' }`、`{ todo: 'later' }`、`{ only: true }`)、フックの `before`/`after`/`beforeEach`/`afterEach`、`mock` の API(`mock.fn`、`mock.method`、`mock.getter`/`mock.setter`、`mock.module`)を読みます。`node:assert`、`node:assert/strict`、`assert` が export する値はすべて assertion として数え(`assert(x)`、`assert.equal`、`strictEqual` などの名前付き import、`assert.strict.*`、`require`)。数えるのは、呼び出した名前がその import に解決されるときだけで、同じ名前のローカルの関数は数えません。テストのコンテキストとそのサブテストのコンテキストの `t.assert.*` も同じです。コンテキストから分割代入したメンバー(`({ assert, mock }) => …`)も同じように読みます。テストが、解析で追えない使い方(別の呼び出しに渡す、格納する、`arguments` や rest 引数で読む)をする関数にコンテキストを渡すとき(テストとして名前で渡した関数そのものも含みます)や、ほかの値でも呼ばれる関数に渡すときは、assertion がないとは判定せず、判断できない(`opaque_call`)とします。コンテキストを受け取ることのない普通のヘルパー(`function check(x) { expect(x).toBe(2) }`)は、ほかの呼び出しと同じように判定します。トップレベルの `const { test } = require('node:test')` や `const assert = require('node:assert')` で束縛する CommonJS のテストファイルも、同じように読みます。require したメンバーに続けた修飾子(`require('node:test')['describe']['skip']`、`test['skip'](...)`)や、テストの中で require した `node:assert` も読みます。`require` は、ファイルが同じ名前を自分で宣言していないときだけ数えます。CommonJS には既定の export がないので、`require('node:test').default` や `const { default: test } = require('node:test')` はテストを登録しませんが、`import { default as test } from 'node:test'` は登録します。サブテスト(`t.test`)は、それを登録したテストの一部として解析し、単独では一覧に載せません。どのランナーでも、`analysis.testInclude` に当てはまるのにテストの登録を1つも読めなかったテストファイル(静的解析で追えないコードがテストを登録している場合など)は、`map` ステージのメッセージに名前が出ます。このとき `map` ステージは `partial` になり、実行結果が `pass` になることはありません。名前を出さないのは、テストを登録しないことを示せたファイルだけです。つまり、そのファイルと読み込むローカルのモジュールのすべての文が、読み込まれる間にコードを実行しないとわかっていて、テストを登録するモジュールを import していないファイルです。コードを実行しないとみなすのは、パッケージの規則を満たすモジュールの import と export、関数・型・interface・const か値がリテラルの enum・デコレーターや static ブロックやコードを実行する static 初期化子のない class の宣言、無害な値(リテラル、置換のないテンプレート、関数、spread のないそうした値のオブジェクトと配列、ローカルの名前)で初期化する変数と `export default`、無害な値の CommonJS の export、少数の無害な組み込み(`Symbol()`、`Object.freeze()`、パスと URL のヘルパー)、ランナーのフックとモックの設定(`beforeAll`、`vi.mock`、`jest.setTimeout`)だけです。それ以外の呼び出し、`new`、`await`、ループ、spread、代入、getter を実行しうるメンバーの読み取り、デコレーターはコードの実行とみなします。副作用のためのパッケージの読み込み(`import 'pkg'`)、パッケージ全体の re-export(`export * from 'pkg'`)、パッケージの動的 import は常に数えます。ランナー自身のパターン(`*.test.*`、`*.spec.*`)に当てはまるファイルでは、ローカルの import のどこかで名前付きでパッケージを import することも数えます。ディレクトリの glob だけで当てはまるヘルパーでは、名前付きで import して関数の中でだけ使うパッケージは数えません。これには Node.js のテストランナーで既知の制限があります。`node --test` は `test` ディレクトリの下のファイルをすべてテストファイルとして実行しますが、そうしたディレクトリの glob(`**/test/**`)だけで当てはまるファイルにはゆるいほうの規則を使います。そのため、そこにあってパッケージの import を束縛するだけのファイルは、そのパッケージが import されたときにテストを登録するものであっても、名前が出ません。解決できないローカルのモジュールも数えます。また、静的解析のほかの部分がすでに開いているとみなしたファイル(読み込み時に読めないコードがある、または計算された名前の動的 import やランナーの計算されたメンバーのように追えないコードに届く。ランナーの API の re-export、`require` や `import()` で読み込むローカルの JSON、無害な値の CommonJS の export、ディレクトリの glob だけで当てはまるヘルパーでトップレベルに `require` して関数の中でだけ使うパッケージは、これに当たりません)は、この規則にかかわらず必ず名前が出ます。そのため、`export { test } from 'node:test'` のような barrel や、関数を定義するだけのヘルパーは名前が出ませんが、読み込まれるときに `const app = createApp()` を実行するヘルパーは名前が出ます。実行するコードがパッケージを呼び出しているとき(`import { suite } from 'some-lib'; suite()`。読み込むローカルのモジュールの中の場合も含みます)は、メッセージにそのパッケージとモジュールが出ます。ほかのランナーの API(`bun:test`、`Deno.test`)を使うファイルは、その理由とともに名前が出ます。メッセージに名前が出るのは最初の 10 個までで、残りは数だけを示します。 Veritas がこれらのテストを実行するときは、プロジェクトのルートで Node.js の既定のファイルパターンを使って `node --test` を実行します。プロジェクトの test スクリプトは実行しないので、そこに書いた `--import tsx` などのフラグや独自の glob は適用されません。同梱のレポーターは JSON のレポートを `.veritas/improve/` の中に書きます。テストのキーは `:: test > subtest>` で、skip と todo のテストはスキップとして数えます。TypeScript のテストは Node.js の型の除去(type stripping)で実行するので、消去できる構文だけを使い、`.ts` のファイル名で import する必要があります。 From 403fcea111605ca2571e8fad4c2a69073a6c4991 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 13:41:35 +0900 Subject: [PATCH 03/14] fix(test-inventory): follow contexts through mutable aliases and table rows, and leave hidden context uses and side effects inconclusive - An untraced value derived from a test's context (let c; c = t; check(c), check(t.x), check(wrap(t))) seeds a new unknownContext set; a contextual function in it is opaque_call for the calls that may hand it a context, while ordinary values (svc.price(1), an import, a let never touching a context) still seed nothing. - neverReassigned recognises every write form: shorthand and nested destructuring assignments (resolved with getShorthandAssignmentValueSymbol), array destructuring, defaults in patterns, compound assignments, ++/--, for...of and for...in heads; a name in a literal whose role cannot be told counts as written. - The callback of a table-driven registration (test.each, it.each, describe.each, Vitest's test.for) takes a row first: it is not a context callback, and with test.for the second parameter is checked as the context. - A test whose own context goes where it is not followed (a later argument, Reflect.apply, fn.call(t), stored in an array or object) and that asserts nothing of its own is opaque_call instead of no_assertion. - A helper handed a project object that it calls through its parameter (checkObj(svc) with o.price(1)) is opaque_call when its own analysis resolves no project call, instead of target_not_called. - An assertion on a variable written by a closure handed to a project call, in the test or anywhere in the file (compose([tuple(mw)])(ctx), app.on(() => { aborted = true })), makes the test opaque_call instead of disconnected. --- packages/test-inventory/src/index.ts | 499 ++++++++++++++++-- .../test/context-precision.test.ts | 206 ++++++++ 2 files changed, 656 insertions(+), 49 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index bc2eebea..ecc3bff3 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -3669,6 +3669,10 @@ function callInfo(node: Invocation, ctx: Ctx): CallInfo { // counted where it is followed from, so whether this call asserts is unknown, never "no assertion". if (handsContextToMixedCallback(node, helper, ctx.checker)) info = { ...info, opaque: true, assertionsUnknown: true }; + // `checkObj(svc)` with the helper calling `o.price(1)`: calls of project code made through its parameter, which + // the helper's own analysis cannot resolve. What they reach is unknown, not absent. + else if (info.targets.length === 0 && projectValueCalledThroughParameter(node, helper, ctx)) + info = { ...info, opaque: true }; // What a local component renders is what it returns: calls whose result does not reach that are not shown. if (mount) @@ -8505,8 +8509,17 @@ function readTest( const unreadCallbackArgument = testFn === undefined && opaqueCallback(info.callback); // A function passed by name that uses its context in ways not followed (`runner.run(t)`, `{ t }`, `arguments`, // a rest parameter): what it asserts through the context is unknown, as when a test hands it its context. + // The same for the test's own callback, inline or passed by name, whose context goes where it is not followed + // (`second(1, t)`, `fn.call(t)`, `Reflect.apply(fn, null, [t])`, `[t]`). A table-driven test's callback takes a row + // first; with Vitest's `test.for` the context comes second. + const factory = registrationFactory(registrationCall); + const contextIndex = info.modifiers.includes('each') + ? factory !== undefined && propertyChain(factory).includes('for') + ? 1 + : undefined + : 0; const escapedContext = - testFn !== undefined && contextCallback === testFn && contextEscapes(testFn, checker); + testFn !== undefined && contextIndex !== undefined && contextEscapes(testFn, checker, contextIndex); const nodes = body ? descendants(body) : []; const contextParameter = testFn?.parameters[0] && ts.isIdentifier(testFn.parameters[0].name) @@ -8626,6 +8639,20 @@ function readTest( ); const nondeterminism = [...new Set(nodes.flatMap((node) => nondeterminismFor(node, fakeTimers)))]; const suspicions: TestCaseType['suspicions'] = []; + // Where the context went may hold assertions: inconclusive, unless the test asserts on its own anyway. + const contextHidesAssertions = escapedContext && assertions.length === 0 && !analysis?.helperAsserts; + // An assertion on what a closure handed to project code writes (`compose([mw])(ctx)` with `mw` setting `called`): + // the project call may well decide it, though the link is not shown. Inconclusive, never disconnected. + const sideEffectLink = + body !== undefined && + !targetCalls.some((call) => call.asserted) && + assertionReadsProjectSideEffect( + assertions, + (analysis?.calls ?? []).map((entry) => entry.node), + body, + checker, + (call) => resolveProjectCall(call, checker, ctx.projectSet, root) !== undefined, + ); if ( assertions.length === 0 && @@ -8633,7 +8660,7 @@ function readTest( !unreadCallback && !analysis?.helperAsserts && !analysis?.assertionsUnknown && - !escapedContext && + !contextHidesAssertions && !callsHelperWithAssertion(body, source) ) suspicions.push('no_assertion'); @@ -8642,7 +8669,8 @@ function readTest( // Code that runs when the file loads (outside any function), its own or that of the local modules it imports, // runs before every test in it. const loading = fileLoadReach(source, ctx); - const opaque = analysis?.opaque === true || loading.opaque || unreadCallback || escapedContext; + const opaque = + analysis?.opaque === true || loading.opaque || unreadCallback || contextHidesAssertions || sideEffectLink; const unresolved = unresolvedImports.size > 0 || loading.unresolved; // An unresolved import, a child process or a dynamic import may well reach project code: absence is not proven. @@ -10742,49 +10770,90 @@ function isContextParameter( let contextCallback: ts.Node | undefined; /** - * Whether a call may hand a test context first to a local function whose first parameter receives a context on some - * paths and something else on others (in both sets of `contextReach`): its first argument is a parameter, so the call - * may come from a test with a real context, where the function's assertions are not counted. Decided from the file's - * structure alone, never from which test is being read, so it does not depend on the order tests are analysed in. + * Whether a variable is never written after its declaration. Every write form counts: `x = …` and compound + * assignments, `x++` and `x--`, a target of a destructuring assignment at any depth (`[x] = …`, `({ x } = …)`, + * `({ a: x } = …)`, `({ a: [x] } = …)`, with or without defaults), and `for (x of …)` / `for (x in …)`. A name in an + * object or array literal whose role cannot be told is taken as written. */ -/** Whether a variable is never assigned after its declaration (`x = …`, `x += …`, `x++`, a destructuring target). */ function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeChecker): boolean { const symbol = checker.getSymbolAtLocation(declaration.name); + /** Whether a literal (or a name in one) is the target of a destructuring assignment or a `for…in/of` head. */ + const writtenPattern = (node: ts.Node): boolean => { + let target: ts.Node = node; + + for (;;) { + const parent: ts.Node = target.parent; + + if ( + ts.isParenthesizedExpression(parent) || + ts.isArrayLiteralExpression(parent) || + ts.isObjectLiteralExpression(parent) || + ts.isSpreadElement(parent) || + ts.isSpreadAssignment(parent) || + (ts.isShorthandPropertyAssignment(parent) && parent.name === target) || + (ts.isPropertyAssignment(parent) && parent.initializer === target) || + // A default in a pattern (`[x = 1] = …`): `x` is the target. + (ts.isBinaryExpression(parent) && + parent.left === target && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && + (ts.isArrayLiteralExpression(parent.parent) || + ts.isPropertyAssignment(parent.parent) || + ts.isSpreadElement(parent.parent))) + ) { + target = parent; + continue; + } + + if (target === node) return false; + + return ( + (ts.isBinaryExpression(parent) && + parent.left === target && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) || + ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === target) || + // Inside a literal whose use is not one of the above: cannot be told, so taken as written. + !(ts.isCallExpression(parent) || ts.isVariableDeclaration(parent) || ts.isReturnStatement(parent)) + ); + } + }; const assigned = (node: ts.Identifier): boolean => { let target: ts.Node = node; - while ( - ts.isParenthesizedExpression(target.parent) || - ts.isShorthandPropertyAssignment(target.parent) || - ts.isPropertyAssignment(target.parent) || - ts.isArrayLiteralExpression(target.parent) || - ts.isObjectLiteralExpression(target.parent) - ) - target = target.parent; + while (ts.isParenthesizedExpression(target.parent)) target = target.parent; const parent = target.parent; - return ( - (ts.isBinaryExpression(parent) && - parent.left === target && - parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && - parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment) || - ((ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && - (parent.operator === ts.SyntaxKind.PlusPlusToken || - parent.operator === ts.SyntaxKind.MinusMinusToken)) || - ts.isForInStatement(parent) || - ts.isForOfStatement(parent) - ); + if ( + ts.isBinaryExpression(parent) && + parent.left === target && + parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && + parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment + ) + return true; + + if ( + (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) && + (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken) + ) + return true; + + if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === target) + return true; + + return writtenPattern(node); }; return ( symbol !== undefined && - descendants(declaration.getSourceFile()).every( - (node) => - !ts.isIdentifier(node) || - node === declaration.name || - checker.getSymbolAtLocation(node) !== symbol || - !assigned(node), - ) + descendants(declaration.getSourceFile()).every((node) => { + if (!ts.isIdentifier(node) || node === declaration.name) return true; + // The name of a shorthand property stands for the variable (`({ x } = …)`, `{ x }`). + const resolved = + ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node + ? checker.getShorthandAssignmentValueSymbol(node.parent) + : checker.getSymbolAtLocation(node); + + return resolved !== symbol || !assigned(node); + }) ); } @@ -10794,15 +10863,16 @@ function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeCh * but a local function's first argument, stored, returned, spread or assigned. Member reads (`t.assert.equal`), uses * that read nothing (`primitiveUse`) and forwarding to a local function (followed by `contextReach`) are followed. */ -function contextEscapes(fn: ts.SignatureDeclaration, checker: ts.TypeChecker): boolean { - const parameter = fn.parameters[0]; +function contextEscapes(fn: ts.SignatureDeclaration, checker: ts.TypeChecker, index = 0): boolean { + const parameter = fn.parameters[index]; const body = (fn as ts.FunctionLikeDeclaration).body; if (readsArguments(fn)) return true; - if (!parameter || !body) return false; + // A rest parameter at or before it takes the context with whatever else is handed. + if (fn.parameters.slice(0, index + 1).some((each) => each.dotDotDotToken)) return true; - if (parameter.dotDotDotToken) return true; + if (!parameter || !body) return false; const names: ts.Identifier[] = []; const collect = (name: ts.BindingName): boolean => { if (ts.isIdentifier(name)) { @@ -10856,27 +10926,300 @@ function contextEscapes(fn: ts.SignatureDeclaration, checker: ts.TypeChecker): b }); } +/** + * Whether an assertion reads a variable that a closure handed to project code writes: the closure (or a local + * function, constant or array/object holding it, up to two names away) appears in the arguments of a project call + * of the test, and assigns the variable, updates it (`n++`), writes a member of it (`state.called = true`) or calls a + * method of it (`calls.push(x)`). The project call may run the closure (`compose([mw])(ctx)`), which links the + * assertion to it in a way not shown. + */ +function assertionReadsProjectSideEffect( + assertions: readonly ts.CallExpression[], + projectCalls: readonly Invocation[], + body: ts.Node, + checker: ts.TypeChecker, + isProjectCall: (call: ts.CallExpression) => boolean, +): boolean { + if (assertions.length === 0) return false; + const read = new Set(); + + for (const assertion of assertions) + for (const value of comparedValues(assertion)) + for (const node of [value, ...descendants(value)]) + if (ts.isIdentifier(node)) { + const symbol = checker.getSymbolAtLocation(node); + + if (symbol) read.add(symbol); + } + + if (read.size === 0) return false; + const calls = new Set(projectCalls); + /** + * Whether a node is inside what a project call is handed: a call of the test, or one anywhere in the file + * (`app.get('/stream', (c) => streamSSE(c, …))` in a `describe`, `stream.onAbort(() => …)`). + */ + const insideHanded = (node: ts.Node): boolean => { + for ( + let current: ts.Node = node; + current.parent && !ts.isSourceFile(current.parent); + current = current.parent + ) { + const parent = current.parent; + + if ( + ts.isCallExpression(parent) && + parent.arguments.includes(current as ts.Expression) && + (calls.has(parent) || isProjectCall(parent)) + ) + return true; + } + + return false; + }; + const source = body.getSourceFile(); + const nameOf = (fn: ts.Node): ts.Identifier | undefined => + ts.isFunctionDeclaration(fn) && fn.name + ? fn.name + : ts.isVariableDeclaration(fn.parent) && ts.isIdentifier(fn.parent.name) + ? fn.parent.name + : undefined; + /** Whether a name is used in what project calls are handed, directly or through a constant that holds it. */ + const handedByName = (name: ts.Identifier, depth: number): boolean => { + const symbol = checker.getSymbolAtLocation(name); + + if (!symbol) return false; + + for (const node of descendants(source)) { + if (!ts.isIdentifier(node) || node === name || checker.getSymbolAtLocation(node) !== symbol) continue; + + if (insideHanded(node)) return true; + + // `const middleware = [first, second]`, `const app = { onAbort: handler }`. + if (depth < 2) + for ( + let current: ts.Node = node.parent; + current && !ts.isSourceFile(current); + current = current.parent + ) + if (ts.isVariableDeclaration(current)) { + if (ts.isIdentifier(current.name) && handedByName(current.name, depth + 1)) return true; + break; + } + } + + return false; + }; + /** The variable a node writes: an assignment's or update's target, a member written, or a method called on it. */ + const written = (node: ts.Node): ts.Identifier | undefined => { + let target: ts.Expression | undefined; + + if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && + node.operatorToken.kind <= ts.SyntaxKind.LastAssignment + ) + target = node.left; + else if ( + (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) && + (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) + ) + target = node.operand; + else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(skipParens(node.expression))) + target = (skipParens(node.expression) as ts.PropertyAccessExpression).expression; + + return target === undefined ? undefined : rootIdentifierNode(skipParens(target)); + }; + + for (const node of descendants(source)) { + const target = written(node); + const symbol = target && checker.getSymbolAtLocation(target); + + if (!symbol || !read.has(symbol)) continue; + + for (let current: ts.Node = node.parent; current && !ts.isSourceFile(current); current = current.parent) { + if (!isFunctionLike(current)) continue; + + // Written by the test itself, not by a closure it hands on. + if (current === body.parent) break; + + if (insideHanded(current)) return true; + const name = nameOf(current); + + if (name && handedByName(name, 0)) return true; + } + } + + return false; +} + +/** + * Whether a call hands a local helper a project value (an import of project code, or an instance of a project class + * made there) as an argument whose parameter the helper calls or calls a method of (`function checkObj(o) { + * o.price(1) }` called as `checkObj(svc)`): those calls run project code the helper's analysis does not resolve. + */ +function projectValueCalledThroughParameter(node: Invocation, body: ts.Node, ctx: Ctx): boolean { + const fn = body.parent; + + if (!ts.isCallExpression(node) || !fn || !isFunctionLike(fn)) return false; + const { checker } = ctx; + const fromProject = (declaration: ts.Declaration) => + ctx.projectSet.has(path.resolve(declaration.getSourceFile().fileName)); + const projectValue = (argument: ts.Expression): boolean => { + const value = skipValueWrappers(argument); + const name = ts.isNewExpression(value) ? skipParens(value.expression) : value; + + if (!ts.isIdentifier(name)) return false; + let symbol = checker.getSymbolAtLocation(name); + + try { + if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol); + } catch { + return false; + } + + return (symbol?.declarations ?? []).some(fromProject); + }; + + return node.arguments.some((argument, index) => { + const parameter = fn.parameters[index]; + + if (!parameter || !ts.isIdentifier(parameter.name) || !projectValue(argument)) return false; + const symbol = checker.getSymbolAtLocation(parameter.name); + + return descendants(body).some( + (child) => + ts.isCallExpression(child) && + rootIdentifierNode(skipParens(child.expression)) !== undefined && + checker.getSymbolAtLocation(rootIdentifierNode(skipParens(child.expression)) as ts.Identifier) === + symbol, + ); + }); +} + +/** + * Whether a call may hand a test context to a local function that can receive one and also receives something else, + * or uses it in ways not followed (see `contextReach`, `contextEscapes`): its first argument is not plainly a value, + * so the call may come from a test with a real context, where the function's assertions are not counted. Decided + * from the file's structure alone, never from which test is being read, so it does not depend on the order tests are + * analysed in. + */ function handsContextToMixedCallback(node: Invocation, body: ts.Node, checker: ts.TypeChecker): boolean { const fn = body.parent; if (!ts.isCallExpression(node) || !fn || !isFunctionLike(fn)) return false; const reach = contextReach(fn.getSourceFile(), checker); - // Only a function that can really receive a context (one passed by name to the runner, or reached from one with a - // test's context): an ordinary helper (`check(x) { expect(x).toBe(2) }`) is judged as any other call. - if (!reach.contextual.has(fn) || !reach.real.has(fn)) return false; + // Only a function that can really receive a context: one passed by name to the runner, reached from one with a + // test's context, or handed a value derived from a context that is not traced (`let c; c = t; check(c)`). An + // ordinary helper (`check(x) { expect(x).toBe(2) }`) is judged as any other call. + if (!reach.contextual.has(fn) || !(reach.real.has(fn) || reach.unknownContext.has(fn))) return false; - // Reached also with something else, or using its context in ways no context is traced through (handing it to a - // call, storing it, `arguments`, a rest parameter). + // Reached also with something else or with an untraced context, or using its context in ways no context is traced + // through (handing it to a call, storing it, `arguments`, a rest parameter). if ( !reach.unknown.has(fn) && !reach.fake.has(fn) && + !reach.unknownContext.has(fn) && !contextEscapes(fn as ts.SignatureDeclaration, checker) ) return false; - // Opaque unless what the call hands it is plainly not a context (a literal, an object written there). - return traceArgument(node.arguments[0], checker) !== 'value'; + // Opaque only when what the call hands it may be a context: a parameter, or an untraced value derived from one + // (`let c; c = t`). A literal, an object written there or an ordinary value (`svc.price(1)`) is not. + const traced = traceArgument(node.arguments[0], checker); + + if (traced === 'value') return false; + + if (traced !== 'unknown') return true; + + return derivedParameters(node.arguments[0] as ts.Expression, checker).some((parameter) => { + const owner = parameter.parent; + + return ( + isFunctionLike(owner) && + owner.parameters[0] === parameter && + (reach.real.has(owner) || reach.unknownContext.has(owner) || isContextParameter(parameter, checker, 0)) + ); + }); +} + +const assignedValuesCache = new WeakMap>(); + +/** + * What each variable of a file is assigned anywhere (`x = …`, `x += …`, and the whole value of a destructuring + * assignment it is a target of), for following an untraced value back to the parameters it may come from. + */ +function assignedValuesOf(source: ts.SourceFile, checker: ts.TypeChecker): Map { + const cached = assignedValuesCache.get(source); + + if (cached) return cached; + const values = new Map(); + const add = (symbol: ts.Symbol | undefined, value: ts.Expression) => { + if (symbol) values.set(symbol, [...(values.get(symbol) ?? []), value]); + }; + + for (const node of descendants(source)) { + if ( + !ts.isBinaryExpression(node) || + node.operatorToken.kind < ts.SyntaxKind.FirstAssignment || + node.operatorToken.kind > ts.SyntaxKind.LastAssignment + ) + continue; + const target = skipParens(node.left); + + if (ts.isIdentifier(target)) add(checker.getSymbolAtLocation(target), node.right); + else if (ts.isObjectLiteralExpression(target) || ts.isArrayLiteralExpression(target)) + for (const item of descendants(target)) + add( + ts.isShorthandPropertyAssignment(item) + ? checker.getShorthandAssignmentValueSymbol(item) + : ts.isIdentifier(item) + ? checker.getSymbolAtLocation(item) + : undefined, + node.right, + ); + } + assignedValuesCache.set(source, values); + + return values; +} + +/** + * The parameters an expression may derive from, through the variables it reads, their initializers and everything + * they are assigned anywhere in the file (cycles end). + */ +function derivedParameters( + expression: ts.Node, + checker: ts.TypeChecker, + seen = new Set(), +): ts.ParameterDeclaration[] { + const found: ts.ParameterDeclaration[] = []; + const assigned = assignedValuesOf(expression.getSourceFile(), checker); + + for (const node of [expression, ...descendants(expression)]) { + const symbol = + node.parent && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node + ? checker.getShorthandAssignmentValueSymbol(node.parent) + : ts.isIdentifier(node) + ? checker.getSymbolAtLocation(node) + : undefined; + + if (!symbol || seen.has(symbol)) continue; + seen.add(symbol); + const declaration = symbol.valueDeclaration; + + if (declaration && ts.isParameter(declaration)) found.push(declaration); + let holder: ts.Node | undefined = declaration; + + while (holder && ts.isBindingElement(holder)) holder = holder.parent.parent; + + if (holder && ts.isVariableDeclaration(holder) && holder.initializer) + found.push(...derivedParameters(holder.initializer, checker, seen)); + + for (const value of assigned.get(symbol) ?? []) found.push(...derivedParameters(value, checker, seen)); + } + + return found; } /** @@ -11044,6 +11387,12 @@ interface ContextReach { fake: Set; /** Local functions whose first parameter can receive a value not traced (a `let`, a member, a call's result). */ unknown: Set; + /** + * Of those, the functions whose untraced value may be a real context: it is derived from the context parameter of a + * test or hook callback (`let c; c = t; check(c)`, `check(t.x)`, `check(wrap(t))`), or from the first parameter of a + * function that can receive one. + */ + unknownContext: Set; /** * Local functions that use their first parameter as a context may be used: they read a member of it * (`t.assert.equal`, `t.mock.fn`, `t.test`), or hand it to one that does. Only for these does what they receive @@ -11069,7 +11418,13 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe if (cached && cached.runner === runner) return cached.reach; if (computingReach.has(source)) - return { real: new Set(), fake: new Set(), unknown: new Set(), contextual: new Set() }; + return { + real: new Set(), + fake: new Set(), + unknown: new Set(), + unknownContext: new Set(), + contextual: new Set(), + }; computingReach.add(source); try { @@ -11094,8 +11449,23 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe const real = new Set(callbacks); const fake = new Set(); const unknown = new Set(); + const unknownContext = new Set(); /** `from` hands its first parameter to `to`. */ const forwards: [ts.Node, ts.Node][] = []; + /** `from` hands `to` an untraced value derived from its first parameter (`wrap(t) { check(t.x) }`). */ + const derivedForwards: [ts.Node, ts.Node][] = []; + const derivedFrom = (expression: ts.Node) => derivedParameters(expression, checker); + /** Whether a parameter is the context of an inline test, hook or subtest callback (not one passed by name). */ + const inlineContext = (parameter: ts.ParameterDeclaration): boolean => { + const owner = parameter.parent; + + return ( + isFunction(owner) && + owner.parameters[0] === parameter && + !named.has(owner) && + isContextParameter(parameter, checker, 0) + ); + }; /** Where a value handed first to a function comes from: a local function's first parameter, a real context, or neither. */ const origin = ( argument: ts.Expression | undefined, @@ -11159,8 +11529,23 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe if (from === 'real') real.add(fn); else if (from === 'fake') fake.add(fn); - else if (from === 'unknown') unknown.add(fn); - else forwards.push([from, fn]); + else if (from === 'unknown') { + unknown.add(fn); + + // Untraced, but derived from a context (`let c; c = t; check(c)`): it may be a real one. An ordinary value + // (`check(svc.price(1))`, an import, a `let` that never touches a context) is not. + for (const parameter of derivedFrom(parent.arguments[0] ?? parent)) { + const owner = parameter.parent; + + if (inlineContext(parameter)) unknownContext.add(fn); + else if ( + isFunctionLike(owner) && + owner.parameters[0] === parameter && + (named.has(owner) || callbacks.has(owner)) + ) + derivedForwards.push([owner, fn]); + } + } else forwards.push([from, fn]); } else if ( ts.isCallExpression(parent) && parent.arguments.some((argument) => skipParens(argument) === node) @@ -11195,7 +11580,19 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe unknown.add(to); changed = true; } + + if (unknownContext.has(from) && !unknownContext.has(to)) { + unknownContext.add(to); + changed = true; + } } + + // An untraced value derived from the first parameter of a function that can receive a context may be one. + for (const [from, to] of derivedForwards) + if ((real.has(from) || unknownContext.has(from)) && !unknownContext.has(to)) { + unknownContext.add(to); + changed = true; + } } // Functions reading a member of their first parameter, and those handing it to one (a fixpoint the other way). const contextual = new Set(); @@ -11212,7 +11609,7 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe changed = true; } } - const reach = { real, fake, unknown, contextual }; + const reach = { real, fake, unknown, unknownContext, contextual }; contextReachCache.set(source, { runner, reach }); return reach; @@ -11236,6 +11633,10 @@ function referencedCallbacks(source: ts.SourceFile, checker: ts.TypeChecker): Se for (const node of descendants(source)) { if (!ts.isCallExpression(node)) continue; const registration = testRegistration(node) ?? describeRegistration(node); + + // A table-driven registration (`test.each(rows)`, `describe.each(rows)`, Vitest's `test.for(rows)`) hands its + // callback a row first, not a context. + if (registration?.modifiers.includes('each')) continue; const callback = registration ? registration.callback : runner.hooks.has(runnerExport(skipParens(node.expression))?.name ?? '') diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index 241ef2c8..b0d36d4c 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -150,4 +150,210 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); } }); + + it('leaves a context handed through a variable assigned later inconclusive', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/mutable.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function check(t) { t.assert.equal(value(1), 2); } + test('assigned later', (t) => { + let context; + context = t; + check(context); + }); + test('let never touching a context', () => { + let n = value(1); + n += 0; + check(n); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + expect(byName(tests, 'assigned later').suspicions).not.toContain('no_assertion'); + expect(byName(tests, 'assigned later').suspicions).toContain('opaque_call'); + // An ordinary value: judged as before, not opaque. + expect(byName(tests, 'let never touching a context').suspicions).not.toContain('opaque_call'); + }); + + it('takes every write form for a reassignment, never tracing a variable written through a pattern', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/writes.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function check(t) { t.assert.equal(value(1), 2); } + const fake = { assert: { equal() {} } }; + test('by reference', check); + test('shorthand destructuring', (t) => { + let context = t; + ({ context } = { context: fake }); + check(context); + }); + test('array destructuring', (t) => { + let context = t; + [context] = [fake]; + check(context); + }); + test('nested destructuring', (t) => { + let context = t; + ({ a: [context] } = { a: [fake] }); + check(context); + }); + test('for of', (t) => { + let context = t; + for (context of [fake]) void 0; + check(context); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['shorthand destructuring', 'array destructuring', 'nested destructuring', 'for of']) { + // Never credited as the real context's assertion: inconclusive at most. + expect( + byName(tests, name).targetCalls.some((call) => call.asserted), + name, + ).toBe(false); + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + } + }); + + it('reads the first parameter of a table-driven callback as a row, not a context', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/rows.test.ts': ` + import { describe, expect, test } from 'vitest'; + import { value } from '../src/svc'; + function checkRow(n: number) { expect(value(n)).toBe(2); } + function checkFor([n]: [number], { expect: check }) { check(value(n)).toBe(2); } + function suiteRows(n: number) { test('inside', () => expect(value(n)).toBe(2)); } + test.each([[1]])('each %s', checkRow); + test.for([[1]])('for %s', checkFor); + describe.each([[1]])('suite %s', suiteRows); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + for (const name of ['each %s', 'for %s', 'inside']) + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + }); + + it('takes a test whose own context goes where it is not followed for inconclusive', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/escapes.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function second(n, t) { t.assert.equal(value(n), 2); } + function first(t) { t.assert.equal(value(1), 2); } + test('later argument', (t) => { second(1, t); }); + test('Reflect.apply', (t) => { Reflect.apply(first, null, [t]); }); + test('call with this', (t) => { first.call(t, t); }); + test('stored in an array', (t) => { const box = [t]; box[0].assert.equal(value(1), 2); }); + test('stored in an object', (t) => { const box = { t }; box.t.assert.equal(value(1), 2); }); + test('own assertion', (t) => { second(1, t); t.assert.equal(value(1), 2); }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of [ + 'later argument', + 'Reflect.apply', + 'call with this', + 'stored in an array', + 'stored in an object', + ]) { + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + expect(byName(tests, name).suspicions, name).toContain('opaque_call'); + } + // It asserts on its own: nothing hidden to leave inconclusive. + expect(byName(tests, 'own assertion').suspicions).not.toContain('opaque_call'); + }); + + for (const [runner, recognition, header, assertion] of [ + ['Vitest', vitest.recognition, "import { expect, test } from 'vitest';", 'expect(o.price(1)).toBe(2);'], + ['Jest', jest.recognition, '', 'expect(o.price(1)).toBe(2);'], + [ + 'node:test', + node.recognition, + "import { test } from 'node:test';\nimport assert from 'node:assert/strict';", + 'assert.equal(o.price(1), 2);', + ], + ] as const) + it(`never takes a project object called through a helper parameter for no project call (${runner})`, () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/obj.test.ts': ` + ${header} + import { svc } from '../src/svc'; + function checkObj(o) { ${assertion} } + test('through a parameter', () => { checkObj(svc); }); + `, + }); + const { tests } = inventory(root, recognition); + const test = byName(tests, 'through a parameter'); + + expect(test.suspicions, runner).not.toContain('target_not_called'); + expect(test.suspicions, runner).toContain('opaque_call'); + }); + + it('links an assertion to a project call that runs the closure writing what it reads', () => { + const root = tempProject({ + 'src/compose.ts': ` + export const compose = (middleware: [(c: object, next: () => void) => void][]) => (c: object) => { + for (const [run] of middleware) run(c, () => {}); + return c; + }; + export class App { + handlers: (() => void)[] = []; + on(handler: () => void) { this.handlers.push(handler); } + } + `, + 'test/compose.test.ts': ` + import { describe, expect, it } from 'vitest'; + import { App, compose } from '../src/compose'; + const tuple = (fn: (c: object, next: () => void) => void): [typeof fn] => [fn]; + describe('Compose', () => { + it('should compose w/ other compositions', () => { + const called: number[] = []; + compose([tuple((_c, next) => { called.push(1); next(); })])({}); + expect(called).toEqual([1]); + }); + it('written by the test itself', () => { + let called = false; + compose([])({}); + called = true; + expect(called).toBe(true); + }); + }); + describe('stream', () => { + const app = new App(); + let aborted = false; + app.on(() => { aborted = true; }); + const request = async () => { await Promise.resolve(); }; + it('Should call onAbort', async () => { + await request(); + expect(aborted).toBe(true); + }); + }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + for (const name of ['should compose w/ other compositions', 'Should call onAbort']) { + const test = byName(tests, name); + + // Linked, or inconclusive: never disconnected from the project call that runs the closure. + expect(test.suspicions, name).not.toContain('target_not_called'); + expect( + test.suspicions.includes('opaque_call') || test.targetCalls.some((call) => call.asserted), + name, + ).toBe(true); + } + expect(byName(tests, 'Should call onAbort').suspicions).toContain('opaque_call'); + expect(byName(tests, 'written by the test itself').suspicions).not.toContain('opaque_call'); + }); }); From 3cc493e0e02a02af1ccada5a2ce7faa2b96a12df Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 13:43:04 +0900 Subject: [PATCH 04/14] docs: describe tests left inconclusive by closures and project objects handed on --- docs/concepts/support-matrix.md | 2 +- docs/ja/concepts/support-matrix.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/concepts/support-matrix.md b/docs/concepts/support-matrix.md index 5914b0d6..571c3e9e 100644 --- a/docs/concepts/support-matrix.md +++ b/docs/concepts/support-matrix.md @@ -66,7 +66,7 @@ The Node.js test runner is built into Node.js, so `init` never chooses it just f With Jest, what `jest.mock` does depends on how the tests run. Babel and ts-jest compile them to CommonJS and hoist `jest.mock` above the imports, so it replaces the module and Veritas records a mock. In native ES modules (`"type": "module"` with no Babel config, no compiling transformer, and a Jest config whose `transform` is absent or empty and that has no `preset`; when in doubt, Veritas keeps counting `jest.mock` as a mock) the static imports are bound before `jest.mock` runs and the tests reach the real code, so Veritas does not count it as a mock of them; `jest.unstable_mockModule` followed by a dynamic `import()` is the ESM way, and what such an import loads is reported as unknown. -With the Node.js test runner, Veritas reads `test`/`it` and `describe`/`suite` from `node:test` (named, aliased, or the default import `import test from 'node:test'`, also through its members such as `test.describe` and `test.it`), `.skip`/`.todo`/`.only` and the same as an options object (`{ skip: true }`, `{ skip: 'reason' }`, `{ todo: 'later' }`, `{ only: true }`), the hooks `before`/`after`/`beforeEach`/`afterEach`, and the `mock` API (`mock.fn`, `mock.method`, `mock.getter`/`mock.setter`, `mock.module`). Every value export of `node:assert`, `node:assert/strict` and `assert` counts as an assertion (`assert(x)`, `assert.equal`, named imports such as `strictEqual`, `assert.strict.*`, `require`); a call counts only when its name resolves to that import, so a local function of the same name does not. So does `t.assert.*` on the test context and on the contexts of its subtests. Members destructured from the context (`({ assert, mock }) => …`) are read the same way. When a test hands its context to a function that uses it in ways the analysis does not follow (passes it to another call, stores it, reads `arguments` or a rest parameter), including a function passed by name as the test itself, or to one that is also called with something else, the test is inconclusive (`opaque_call`) rather than judged to assert nothing. An ordinary helper that never receives a context (`function check(x) { expect(x).toBe(2) }`) is judged as any other call. CommonJS test files that bind them with a top-level `const { test } = require('node:test')` or `const assert = require('node:assert')` are read the same way, including modifiers read on a required member (`require('node:test')['describe']['skip']`, `test['skip'](...)`), and `node:assert` required inside a test; `require` counts only when the file does not declare its own. CommonJS has no default export, so `require('node:test').default` and `const { default: test } = require('node:test')` register nothing, while `import { default as test } from 'node:test'` does. Subtests (`t.test`) are analysed as part of the test that registers them, not listed on their own. With any runner, a test file matching `analysis.testInclude` from which no test registration can be read (its tests are registered by code static analysis does not follow) is named in the messages of the `map` stage, which is then `partial`, so the run cannot report `pass`. A file is left out only when it is shown to register nothing: every statement of it and of each local module it loads is known to run no code when it loads, and no module it imports registers tests. Known to run none are imports and exports of modules that pass the package rule, declarations of functions, types, interfaces, const or literal enums and classes without decorators, static blocks or static initialisers that run code, variables and `export default` of inert values (literals, templates without substitutions, functions, object and array literals of such values without spread, local names), CommonJS exports of inert values, a few inert builtins (`Symbol()`, `Object.freeze()`, path and URL helpers) and the runner's hooks and mock configuration (`beforeAll`, `vi.mock`, `jest.setTimeout`). Anything else counts: other calls, `new`, `await`, loops, spread, assignments, member reads that may run a getter, decorators. A package loaded for its side effects (`import 'pkg'`), re-exported whole (`export * from 'pkg'`) or imported dynamically always counts, and in a file of the runner's own pattern (`*.test.*`, `*.spec.*`) so does a package imported by name anywhere in its local imports; in a helper matched only by a directory glob, a package imported by name and used only inside functions does not. This has a known limitation with the Node.js test runner: `node --test` runs every file under a `test` directory as a test file, but a file matched only by such a directory glob (`**/test/**`) still uses the looser rule, so a file there that only binds a package import is not named, even if that package registers tests when it is imported. A local module that does not resolve counts too. A file that the rest of static analysis already finds open (code at load time it cannot read, or code it does not follow, such as a dynamic import of a computed name or a computed member of the runner; re-exports of the runner's API, local JSON loaded by `require` or `import()`, CommonJS exports of inert values and, in a helper matched only by a directory glob, a top-level `require` of a package used only inside functions are not such code) is never left out, whatever this rule says. So a barrel such as `export { test } from 'node:test'` or a helper that only defines functions is not named, while one that runs `const app = createApp()` when it loads is. When the code it runs calls into a package (`import { suite } from 'some-lib'; suite()`), possibly in a local module it loads, the message names the package and that module. A file that uses another runner's API (`bun:test`, `Deno.test`) is named with that reason. The message names the first 10 files and counts the rest. +With the Node.js test runner, Veritas reads `test`/`it` and `describe`/`suite` from `node:test` (named, aliased, or the default import `import test from 'node:test'`, also through its members such as `test.describe` and `test.it`), `.skip`/`.todo`/`.only` and the same as an options object (`{ skip: true }`, `{ skip: 'reason' }`, `{ todo: 'later' }`, `{ only: true }`), the hooks `before`/`after`/`beforeEach`/`afterEach`, and the `mock` API (`mock.fn`, `mock.method`, `mock.getter`/`mock.setter`, `mock.module`). Every value export of `node:assert`, `node:assert/strict` and `assert` counts as an assertion (`assert(x)`, `assert.equal`, named imports such as `strictEqual`, `assert.strict.*`, `require`); a call counts only when its name resolves to that import, so a local function of the same name does not. So does `t.assert.*` on the test context and on the contexts of its subtests. Members destructured from the context (`({ assert, mock }) => …`) are read the same way. When a test hands its context to a function that uses it in ways the analysis does not follow (passes it to another call, stores it, reads `arguments` or a rest parameter), including a function passed by name as the test itself, or to one that is also called with something else, the test is inconclusive (`opaque_call`) rather than judged to assert nothing. An ordinary helper that never receives a context (`function check(x) { expect(x).toBe(2) }`) is judged as any other call. With any runner, a test is also inconclusive when it asserts on a variable written by a closure it hands to project code (`compose([middleware])(ctx)` with the middleware setting `called`, or a handler registered on a project object in a `describe`), or when it hands a project object to a local helper that calls it through its parameter; the link to the project call is possible but not shown. CommonJS test files that bind them with a top-level `const { test } = require('node:test')` or `const assert = require('node:assert')` are read the same way, including modifiers read on a required member (`require('node:test')['describe']['skip']`, `test['skip'](...)`), and `node:assert` required inside a test; `require` counts only when the file does not declare its own. CommonJS has no default export, so `require('node:test').default` and `const { default: test } = require('node:test')` register nothing, while `import { default as test } from 'node:test'` does. Subtests (`t.test`) are analysed as part of the test that registers them, not listed on their own. With any runner, a test file matching `analysis.testInclude` from which no test registration can be read (its tests are registered by code static analysis does not follow) is named in the messages of the `map` stage, which is then `partial`, so the run cannot report `pass`. A file is left out only when it is shown to register nothing: every statement of it and of each local module it loads is known to run no code when it loads, and no module it imports registers tests. Known to run none are imports and exports of modules that pass the package rule, declarations of functions, types, interfaces, const or literal enums and classes without decorators, static blocks or static initialisers that run code, variables and `export default` of inert values (literals, templates without substitutions, functions, object and array literals of such values without spread, local names), CommonJS exports of inert values, a few inert builtins (`Symbol()`, `Object.freeze()`, path and URL helpers) and the runner's hooks and mock configuration (`beforeAll`, `vi.mock`, `jest.setTimeout`). Anything else counts: other calls, `new`, `await`, loops, spread, assignments, member reads that may run a getter, decorators. A package loaded for its side effects (`import 'pkg'`), re-exported whole (`export * from 'pkg'`) or imported dynamically always counts, and in a file of the runner's own pattern (`*.test.*`, `*.spec.*`) so does a package imported by name anywhere in its local imports; in a helper matched only by a directory glob, a package imported by name and used only inside functions does not. This has a known limitation with the Node.js test runner: `node --test` runs every file under a `test` directory as a test file, but a file matched only by such a directory glob (`**/test/**`) still uses the looser rule, so a file there that only binds a package import is not named, even if that package registers tests when it is imported. A local module that does not resolve counts too. A file that the rest of static analysis already finds open (code at load time it cannot read, or code it does not follow, such as a dynamic import of a computed name or a computed member of the runner; re-exports of the runner's API, local JSON loaded by `require` or `import()`, CommonJS exports of inert values and, in a helper matched only by a directory glob, a top-level `require` of a package used only inside functions are not such code) is never left out, whatever this rule says. So a barrel such as `export { test } from 'node:test'` or a helper that only defines functions is not named, while one that runs `const app = createApp()` when it loads is. When the code it runs calls into a package (`import { suite } from 'some-lib'; suite()`), possibly in a local module it loads, the message names the package and that module. A file that uses another runner's API (`bun:test`, `Deno.test`) is named with that reason. The message names the first 10 files and counts the rest. When Veritas runs these tests, it runs `node --test` from the project root with Node's default file patterns, not the project's test script, so extra flags such as `--import tsx` or custom globs in that script are not applied. The bundled reporter writes its JSON report inside `.veritas/improve/`. Tests are keyed `:: test > subtest>`, and skipped and todo tests count as skipped. TypeScript tests run through Node's type stripping, so they must use erasable syntax and import `.ts` file names. diff --git a/docs/ja/concepts/support-matrix.md b/docs/ja/concepts/support-matrix.md index 921a3689..4768b4d0 100644 --- a/docs/ja/concepts/support-matrix.md +++ b/docs/ja/concepts/support-matrix.md @@ -66,7 +66,7 @@ Node.js のテストランナーは Node.js に組み込まれているので、 Jest では、`jest.mock` の効果がテストの実行方法で変わります。Babel や ts-jest はテストを CommonJS にコンパイルし、`jest.mock` を import より前に移すので、モジュールが置き換わり、Veritas はモックとして記録します。ネイティブ ESM(`"type": "module"` で、Babel の設定もコンパイルする transformer もなく、Jest の設定の `transform` がないか空で `preset` もない。判断できないときは `jest.mock` をモックとして数え続けます)では、`jest.mock` が実行される前に静的な import が結び付けられ、テストは本物のコードを実行するので、Veritas はそれらのモックとして数えません。ESM でのモックは `jest.unstable_mockModule` と動的な `import()` の組み合わせで、そうした import が読み込むものは不明として報告します。 -Node.js のテストランナーでは、`node:test` の `test`/`it` と `describe`/`suite`(名前付き、別名、既定の import `import test from 'node:test'` のいずれも。`test.describe` や `test.it` のようにそのメンバーを通しても読みます)、`.skip`/`.todo`/`.only` と、同じ指定をオプションのオブジェクトで書いたもの(`{ skip: true }`、`{ skip: 'reason' }`、`{ todo: 'later' }`、`{ only: true }`)、フックの `before`/`after`/`beforeEach`/`afterEach`、`mock` の API(`mock.fn`、`mock.method`、`mock.getter`/`mock.setter`、`mock.module`)を読みます。`node:assert`、`node:assert/strict`、`assert` が export する値はすべて assertion として数え(`assert(x)`、`assert.equal`、`strictEqual` などの名前付き import、`assert.strict.*`、`require`)。数えるのは、呼び出した名前がその import に解決されるときだけで、同じ名前のローカルの関数は数えません。テストのコンテキストとそのサブテストのコンテキストの `t.assert.*` も同じです。コンテキストから分割代入したメンバー(`({ assert, mock }) => …`)も同じように読みます。テストが、解析で追えない使い方(別の呼び出しに渡す、格納する、`arguments` や rest 引数で読む)をする関数にコンテキストを渡すとき(テストとして名前で渡した関数そのものも含みます)や、ほかの値でも呼ばれる関数に渡すときは、assertion がないとは判定せず、判断できない(`opaque_call`)とします。コンテキストを受け取ることのない普通のヘルパー(`function check(x) { expect(x).toBe(2) }`)は、ほかの呼び出しと同じように判定します。トップレベルの `const { test } = require('node:test')` や `const assert = require('node:assert')` で束縛する CommonJS のテストファイルも、同じように読みます。require したメンバーに続けた修飾子(`require('node:test')['describe']['skip']`、`test['skip'](...)`)や、テストの中で require した `node:assert` も読みます。`require` は、ファイルが同じ名前を自分で宣言していないときだけ数えます。CommonJS には既定の export がないので、`require('node:test').default` や `const { default: test } = require('node:test')` はテストを登録しませんが、`import { default as test } from 'node:test'` は登録します。サブテスト(`t.test`)は、それを登録したテストの一部として解析し、単独では一覧に載せません。どのランナーでも、`analysis.testInclude` に当てはまるのにテストの登録を1つも読めなかったテストファイル(静的解析で追えないコードがテストを登録している場合など)は、`map` ステージのメッセージに名前が出ます。このとき `map` ステージは `partial` になり、実行結果が `pass` になることはありません。名前を出さないのは、テストを登録しないことを示せたファイルだけです。つまり、そのファイルと読み込むローカルのモジュールのすべての文が、読み込まれる間にコードを実行しないとわかっていて、テストを登録するモジュールを import していないファイルです。コードを実行しないとみなすのは、パッケージの規則を満たすモジュールの import と export、関数・型・interface・const か値がリテラルの enum・デコレーターや static ブロックやコードを実行する static 初期化子のない class の宣言、無害な値(リテラル、置換のないテンプレート、関数、spread のないそうした値のオブジェクトと配列、ローカルの名前)で初期化する変数と `export default`、無害な値の CommonJS の export、少数の無害な組み込み(`Symbol()`、`Object.freeze()`、パスと URL のヘルパー)、ランナーのフックとモックの設定(`beforeAll`、`vi.mock`、`jest.setTimeout`)だけです。それ以外の呼び出し、`new`、`await`、ループ、spread、代入、getter を実行しうるメンバーの読み取り、デコレーターはコードの実行とみなします。副作用のためのパッケージの読み込み(`import 'pkg'`)、パッケージ全体の re-export(`export * from 'pkg'`)、パッケージの動的 import は常に数えます。ランナー自身のパターン(`*.test.*`、`*.spec.*`)に当てはまるファイルでは、ローカルの import のどこかで名前付きでパッケージを import することも数えます。ディレクトリの glob だけで当てはまるヘルパーでは、名前付きで import して関数の中でだけ使うパッケージは数えません。これには Node.js のテストランナーで既知の制限があります。`node --test` は `test` ディレクトリの下のファイルをすべてテストファイルとして実行しますが、そうしたディレクトリの glob(`**/test/**`)だけで当てはまるファイルにはゆるいほうの規則を使います。そのため、そこにあってパッケージの import を束縛するだけのファイルは、そのパッケージが import されたときにテストを登録するものであっても、名前が出ません。解決できないローカルのモジュールも数えます。また、静的解析のほかの部分がすでに開いているとみなしたファイル(読み込み時に読めないコードがある、または計算された名前の動的 import やランナーの計算されたメンバーのように追えないコードに届く。ランナーの API の re-export、`require` や `import()` で読み込むローカルの JSON、無害な値の CommonJS の export、ディレクトリの glob だけで当てはまるヘルパーでトップレベルに `require` して関数の中でだけ使うパッケージは、これに当たりません)は、この規則にかかわらず必ず名前が出ます。そのため、`export { test } from 'node:test'` のような barrel や、関数を定義するだけのヘルパーは名前が出ませんが、読み込まれるときに `const app = createApp()` を実行するヘルパーは名前が出ます。実行するコードがパッケージを呼び出しているとき(`import { suite } from 'some-lib'; suite()`。読み込むローカルのモジュールの中の場合も含みます)は、メッセージにそのパッケージとモジュールが出ます。ほかのランナーの API(`bun:test`、`Deno.test`)を使うファイルは、その理由とともに名前が出ます。メッセージに名前が出るのは最初の 10 個までで、残りは数だけを示します。 +Node.js のテストランナーでは、`node:test` の `test`/`it` と `describe`/`suite`(名前付き、別名、既定の import `import test from 'node:test'` のいずれも。`test.describe` や `test.it` のようにそのメンバーを通しても読みます)、`.skip`/`.todo`/`.only` と、同じ指定をオプションのオブジェクトで書いたもの(`{ skip: true }`、`{ skip: 'reason' }`、`{ todo: 'later' }`、`{ only: true }`)、フックの `before`/`after`/`beforeEach`/`afterEach`、`mock` の API(`mock.fn`、`mock.method`、`mock.getter`/`mock.setter`、`mock.module`)を読みます。`node:assert`、`node:assert/strict`、`assert` が export する値はすべて assertion として数え(`assert(x)`、`assert.equal`、`strictEqual` などの名前付き import、`assert.strict.*`、`require`)。数えるのは、呼び出した名前がその import に解決されるときだけで、同じ名前のローカルの関数は数えません。テストのコンテキストとそのサブテストのコンテキストの `t.assert.*` も同じです。コンテキストから分割代入したメンバー(`({ assert, mock }) => …`)も同じように読みます。テストが、解析で追えない使い方(別の呼び出しに渡す、格納する、`arguments` や rest 引数で読む)をする関数にコンテキストを渡すとき(テストとして名前で渡した関数そのものも含みます)や、ほかの値でも呼ばれる関数に渡すときは、assertion がないとは判定せず、判断できない(`opaque_call`)とします。コンテキストを受け取ることのない普通のヘルパー(`function check(x) { expect(x).toBe(2) }`)は、ほかの呼び出しと同じように判定します。また、どのランナーでも、プロジェクトのコードに渡したクロージャーが書き換える変数を assertion で確かめるテスト(`called` を設定するミドルウェアを渡す `compose([middleware])(ctx)` や、`describe` の中でプロジェクトのオブジェクトに登録したハンドラー)と、プロジェクトのオブジェクトをローカルのヘルパーに渡し、ヘルパーが引数を通してそれを呼ぶテストも、判断できない扱いにします。プロジェクトの呼び出しとのつながりはありうるものの、示せていないためです。トップレベルの `const { test } = require('node:test')` や `const assert = require('node:assert')` で束縛する CommonJS のテストファイルも、同じように読みます。require したメンバーに続けた修飾子(`require('node:test')['describe']['skip']`、`test['skip'](...)`)や、テストの中で require した `node:assert` も読みます。`require` は、ファイルが同じ名前を自分で宣言していないときだけ数えます。CommonJS には既定の export がないので、`require('node:test').default` や `const { default: test } = require('node:test')` はテストを登録しませんが、`import { default as test } from 'node:test'` は登録します。サブテスト(`t.test`)は、それを登録したテストの一部として解析し、単独では一覧に載せません。どのランナーでも、`analysis.testInclude` に当てはまるのにテストの登録を1つも読めなかったテストファイル(静的解析で追えないコードがテストを登録している場合など)は、`map` ステージのメッセージに名前が出ます。このとき `map` ステージは `partial` になり、実行結果が `pass` になることはありません。名前を出さないのは、テストを登録しないことを示せたファイルだけです。つまり、そのファイルと読み込むローカルのモジュールのすべての文が、読み込まれる間にコードを実行しないとわかっていて、テストを登録するモジュールを import していないファイルです。コードを実行しないとみなすのは、パッケージの規則を満たすモジュールの import と export、関数・型・interface・const か値がリテラルの enum・デコレーターや static ブロックやコードを実行する static 初期化子のない class の宣言、無害な値(リテラル、置換のないテンプレート、関数、spread のないそうした値のオブジェクトと配列、ローカルの名前)で初期化する変数と `export default`、無害な値の CommonJS の export、少数の無害な組み込み(`Symbol()`、`Object.freeze()`、パスと URL のヘルパー)、ランナーのフックとモックの設定(`beforeAll`、`vi.mock`、`jest.setTimeout`)だけです。それ以外の呼び出し、`new`、`await`、ループ、spread、代入、getter を実行しうるメンバーの読み取り、デコレーターはコードの実行とみなします。副作用のためのパッケージの読み込み(`import 'pkg'`)、パッケージ全体の re-export(`export * from 'pkg'`)、パッケージの動的 import は常に数えます。ランナー自身のパターン(`*.test.*`、`*.spec.*`)に当てはまるファイルでは、ローカルの import のどこかで名前付きでパッケージを import することも数えます。ディレクトリの glob だけで当てはまるヘルパーでは、名前付きで import して関数の中でだけ使うパッケージは数えません。これには Node.js のテストランナーで既知の制限があります。`node --test` は `test` ディレクトリの下のファイルをすべてテストファイルとして実行しますが、そうしたディレクトリの glob(`**/test/**`)だけで当てはまるファイルにはゆるいほうの規則を使います。そのため、そこにあってパッケージの import を束縛するだけのファイルは、そのパッケージが import されたときにテストを登録するものであっても、名前が出ません。解決できないローカルのモジュールも数えます。また、静的解析のほかの部分がすでに開いているとみなしたファイル(読み込み時に読めないコードがある、または計算された名前の動的 import やランナーの計算されたメンバーのように追えないコードに届く。ランナーの API の re-export、`require` や `import()` で読み込むローカルの JSON、無害な値の CommonJS の export、ディレクトリの glob だけで当てはまるヘルパーでトップレベルに `require` して関数の中でだけ使うパッケージは、これに当たりません)は、この規則にかかわらず必ず名前が出ます。そのため、`export { test } from 'node:test'` のような barrel や、関数を定義するだけのヘルパーは名前が出ませんが、読み込まれるときに `const app = createApp()` を実行するヘルパーは名前が出ます。実行するコードがパッケージを呼び出しているとき(`import { suite } from 'some-lib'; suite()`。読み込むローカルのモジュールの中の場合も含みます)は、メッセージにそのパッケージとモジュールが出ます。ほかのランナーの API(`bun:test`、`Deno.test`)を使うファイルは、その理由とともに名前が出ます。メッセージに名前が出るのは最初の 10 個までで、残りは数だけを示します。 Veritas がこれらのテストを実行するときは、プロジェクトのルートで Node.js の既定のファイルパターンを使って `node --test` を実行します。プロジェクトの test スクリプトは実行しないので、そこに書いた `--import tsx` などのフラグや独自の glob は適用されません。同梱のレポーターは JSON のレポートを `.veritas/improve/` の中に書きます。テストのキーは `:: test > subtest>` で、skip と todo のテストはスキップとして数えます。TypeScript のテストは Node.js の型の除去(type stripping)で実行するので、消去できる構文だけを使い、`.ts` のファイル名で import する必要があります。 From 3109145e1837cc5026e89bfa08f66d859bccbf7f Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 14:06:52 +0900 Subject: [PATCH 05/14] fix(test-inventory): add a context safety net and read test contexts only where runners hand them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TestRunnerRecognition gains testContext, set for node:test and Vitest. Context tracking (contextReach, context parameters, escape checks) applies only to runners that hand one, so Jest's done is never read as a context. - Safety net: when a test's context, a member destructured from it, or a const alias or cast of them is used in any way but a direct member call the inventory reads (t.assert.equal(…), t.mock.fn(), t.test(…), ctx.expect(…)) or a member read where it reads nothing, the test can no longer be no_assertion or tautological_assertion. It is opaque_call unless one of its project calls is asserted. This holds whatever reach propagation knows. - The context's position follows the registration: the second parameter with Vitest's test.for, none with each, for inline callbacks, callbacks passed by name and the seeding of reach. ctx.expect(…) and an expect destructured under another name count as assertions. - A member destructured from a parameter derives from that parameter (({ assert }) => check(assert)). - Every write check sees through parentheses, as, satisfies, non-null and type assertions ((context as any) = fake). - The side-effect scan counts only writers that can run for the analysed test: its own body, hooks of its enclosing suites, module or suite level; not other tests' callbacks or other suites' hooks. --- packages/core/src/test-runner.ts | 6 + packages/test-inventory/src/index.ts | 300 +++++++++++++++--- .../test/context-precision.test.ts | 163 ++++++++++ packages/test-runners/node/src/index.ts | 2 + packages/test-runners/vitest/src/index.ts | 2 + 5 files changed, 428 insertions(+), 45 deletions(-) diff --git a/packages/core/src/test-runner.ts b/packages/core/src/test-runner.ts index 4e01afcf..67f9910e 100644 --- a/packages/core/src/test-runner.ts +++ b/packages/core/src/test-runner.ts @@ -157,6 +157,12 @@ export interface TestRunnerRecognition { * `test(namedFn)`, `test({ skip: true }, function x() {})`); otherwise only a title written first counts. */ readonly functionTitles?: boolean; + /** + * The runner hands a test, hook or suite callback a context as its first parameter (the second for a table + * registration run with `for`, Vitest's `test.for`): Node's `t`, Vitest's `ctx`. Without it the first parameter is + * something else (Jest's `done`), never read as a context. + */ + readonly testContext?: boolean; /** * An option of `testOptions` is set by any value but `false` and `undefined` (Node: `{ skip: '' }`, `{ skip: 0 }` * and `{ skip: null }` skip); without it a value sets the option when it is truthy, as in Vitest. diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index ecc3bff3..c001fdde 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -104,6 +104,8 @@ interface RunnerApi { chainedModifiersWin: boolean; /** A registration without a title takes its function's name (Node). */ functionTitles: boolean; + /** The runner hands its callbacks a test context (see `TestRunnerRecognition.testContext`). */ + testContext: boolean; /** An option is set by any value but `false` and `undefined` (Node). */ optionsSetUnlessFalse: boolean; /** The export a default import of the runner's module stands for (`import test from 'node:test'`), if any. */ @@ -144,6 +146,7 @@ function runnerApi(recognition: TestRunnerRecognition): RunnerApi { testOptions: recognition.testOptions === true, chainedModifiersWin: recognition.chainedModifiersWin === true, functionTitles: recognition.functionTitles === true, + testContext: recognition.testContext === true, optionsSetUnlessFalse: recognition.optionsSetUnlessFalse === true, defaultExport: recognition.defaultExport, beforeEach: new Set(hooks.beforeEach), @@ -8507,23 +8510,21 @@ function readTest( // A callback passed some other way (an imported function, a call's result) cannot be read: the test is not // judged empty for it. const unreadCallbackArgument = testFn === undefined && opaqueCallback(info.callback); - // A function passed by name that uses its context in ways not followed (`runner.run(t)`, `{ t }`, `arguments`, - // a rest parameter): what it asserts through the context is unknown, as when a test hands it its context. - // The same for the test's own callback, inline or passed by name, whose context goes where it is not followed - // (`second(1, t)`, `fn.call(t)`, `Reflect.apply(fn, null, [t])`, `[t]`). A table-driven test's callback takes a row - // first; with Vitest's `test.for` the context comes second. - const factory = registrationFactory(registrationCall); - const contextIndex = info.modifiers.includes('each') - ? factory !== undefined && propertyChain(factory).includes('for') - ? 1 - : undefined - : 0; + // The test's context, for a runner that hands one (Node's `t`, Vitest's `ctx`; not Jest's `done`), at the position + // its callback takes it: a table row comes first with `each`, before the context with Vitest's `test.for`. + const contextIndex = runner.testContext ? registrationContextIndex(registrationCall) : undefined; + const contextNode = contextIndex !== undefined ? testFn?.parameters[contextIndex] : undefined; + // Safety net: the context (or a member destructured from it, an alias, a cast) used in any way but a direct member + // call the inventory reads (`t.assert.equal(…)`, `t.mock.fn()`, `t.test(…)`, `ctx.expect(…)`) may hold assertions + // the inventory does not see, whatever is known of where it goes. const escapedContext = - testFn !== undefined && contextIndex !== undefined && contextEscapes(testFn, checker, contextIndex); + testFn !== undefined && + contextIndex !== undefined && + (contextNode !== undefined ? contextUseUnfollowed(testFn, contextNode, checker) : readsArguments(testFn)); const nodes = body ? descendants(body) : []; const contextParameter = - testFn?.parameters[0] && ts.isIdentifier(testFn.parameters[0].name) - ? checker.getSymbolAtLocation(testFn.parameters[0].name) + contextNode && ts.isIdentifier(contextNode.name) + ? checker.getSymbolAtLocation(contextNode.name) : undefined; const contextParameters = contextParameter ? subtestContexts(contextParameter, nodes, checker) @@ -8639,8 +8640,8 @@ function readTest( ); const nondeterminism = [...new Set(nodes.flatMap((node) => nondeterminismFor(node, fakeTimers)))]; const suspicions: TestCaseType['suspicions'] = []; - // Where the context went may hold assertions: inconclusive, unless the test asserts on its own anyway. - const contextHidesAssertions = escapedContext && assertions.length === 0 && !analysis?.helperAsserts; + // Assertions through the context may be unseen: inconclusive, unless the test is linked to project code anyway. + const contextHidesAssertions = escapedContext && !targetCalls.some((call) => call.asserted); // An assertion on what a closure handed to project code writes (`compose([mw])(ctx)` with `mw` setting `called`): // the project call may well decide it, though the link is not shown. Inconclusive, never disconnected. const sideEffectLink = @@ -8660,12 +8661,12 @@ function readTest( !unreadCallback && !analysis?.helperAsserts && !analysis?.assertionsUnknown && - !contextHidesAssertions && + !escapedContext && !callsHelperWithAssertion(body, source) ) suspicions.push('no_assertion'); - if (tautological && !unreadCallback) suspicions.push('tautological_assertion'); + if (tautological && !unreadCallback && !escapedContext) suspicions.push('tautological_assertion'); // Code that runs when the file loads (outside any function), its own or that of the local modules it imports, // runs before every test in it. const loading = fileLoadReach(source, ctx); @@ -10730,17 +10731,22 @@ function isContextParameter( ): boolean { const fn = declaration.parent; - if (!isFunctionLike(fn) || fn.parameters[0] !== declaration) return false; + // Only for a runner that hands one (not Jest, whose first argument is `done`), at the position the callback takes + // it: a table row comes first with `each`, before the context with `for`. + if (!runner.testContext || !isFunctionLike(fn)) return false; + const index = contextIndexOf(fn, checker); + + if (index === undefined || fn.parameters[index] !== declaration) return false; // A function passed by name as a test, suite or hook callback (`test('x', check)`), read as that callback: its first // parameter is the context the runner hands it. - if (contextCallback === fn && referencedCallbacks(fn.getSourceFile(), checker).has(fn)) return true; + if (contextCallback === fn) return true; // A local function followed from its calls: a context only when every path to it hands it one (see `contextReach`); // one also reached with a plain object (`check({ assert: { equal() {} } })`) is not, and the calls that may hand it a // real context are opaque instead (`handsContextToMixedCallback`). const reach = contextReach(fn.getSourceFile(), checker); - if (reach.real.has(fn) || reach.fake.has(fn) || reach.unknown.has(fn)) + if (index === 0 && (reach.real.has(fn) || reach.fake.has(fn) || reach.unknown.has(fn))) return reach.real.has(fn) && !reach.fake.has(fn) && !reach.unknown.has(fn); if (!isFunction(fn)) return false; @@ -10785,7 +10791,7 @@ function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeCh const parent: ts.Node = target.parent; if ( - ts.isParenthesizedExpression(parent) || + valueWrapper(parent) || ts.isArrayLiteralExpression(parent) || ts.isObjectLiteralExpression(parent) || ts.isSpreadElement(parent) || @@ -10819,7 +10825,7 @@ function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeCh const assigned = (node: ts.Identifier): boolean => { let target: ts.Node = node; - while (ts.isParenthesizedExpression(target.parent)) target = target.parent; + while (valueWrapper(target.parent)) target = target.parent; const parent = target.parent; if ( @@ -10857,6 +10863,111 @@ function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeCh ); } +/** + * Whether a test's callback uses its context in any way but a direct member call the inventory reads: the context + * parameter, the members destructured from it, and every `const` alias of them (also through a cast or a + * destructuring) may only be the root of a member chain that is called (`t.assert.equal(…)`, `t.mock.fn()`, + * `t.test(…)`, `ctx.expect(…)`), be called themselves (`({ expect }) => expect(x)`), or have a member read where it + * reads nothing (`t.name` in a template). Anything else (handed to a call, stored, returned, spread, assigned, a rest + * element, `arguments`) may lead to assertions the inventory does not see. + */ +function contextUseUnfollowed( + fn: ts.SignatureDeclaration, + parameter: ts.ParameterDeclaration, + checker: ts.TypeChecker, +): boolean { + const body = (fn as ts.FunctionLikeDeclaration).body; + + if (!body) return false; + + if (readsArguments(fn) || parameter.dotDotDotToken) return true; + const symbols = new Set(); + const declarations = new Set(); + const bind = (name: ts.BindingName): boolean => { + if (ts.isIdentifier(name)) { + const symbol = checker.getSymbolAtLocation(name); + + if (symbol) symbols.add(symbol); + declarations.add(name); + + return true; + } + + return name.elements.every( + (element) => + ts.isOmittedExpression(element) || + (!element.dotDotDotToken && + (!element.propertyName || + !ts.isComputedPropertyName(element.propertyName) || + ts.isStringLiteralLike(skipParens(element.propertyName.expression))) && + bind(element.name)), + ); + }; + + if (!bind(parameter.name)) return true; + const nodes = [body, ...descendants(body)]; + const resolve = (node: ts.Identifier) => + ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node + ? checker.getShorthandAssignmentValueSymbol(node.parent) + : checker.getSymbolAtLocation(node); + + // `const c = t`, `const c = t as Ctx`, `const { assert } = t`: aliases, followed in turn. + for (let added = true; added; ) { + added = false; + + for (const node of nodes) + if ( + ts.isVariableDeclaration(node) && + node.initializer && + !declarations.has(node.name) && + (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0 + ) { + const value = skipValueWrappers(node.initializer); + const symbol = ts.isIdentifier(value) ? checker.getSymbolAtLocation(value) : undefined; + + if (symbol && symbols.has(symbol)) { + if (!bind(node.name)) return true; + added = true; + } + } + } + + return nodes.some((node) => { + if (!ts.isIdentifier(node) || declarations.has(node)) return false; + const symbol = resolve(node); + + if (!symbol || !symbols.has(symbol)) return false; + + if (ts.isShorthandPropertyAssignment(node.parent)) return true; + let use: ts.Node = node; + + while (valueWrapper(use.parent)) use = use.parent; + + // The initializer of an alias, followed above. + if ( + ts.isVariableDeclaration(use.parent) && + use.parent.initializer === use && + declarations.has(use.parent.name) + ) + return false; + + if ( + ts.isVariableDeclaration(use.parent) && + use.parent.initializer === use && + ts.isObjectBindingPattern(use.parent.name) + ) + return false; + let chain: ts.Node = use; + + while (ts.isPropertyAccessExpression(chain.parent) && chain.parent.expression === chain) + chain = chain.parent; + + if (ts.isCallExpression(chain.parent) && chain.parent.expression === chain) return false; + + return !(chain !== use && primitiveUse(chain)); + }); +} + /** * Whether a function uses its context parameter in a way no context is traced through: a rest parameter or a rest * element, `arguments`, a computed member read, or the parameter (or a destructured member of it) handed to anything @@ -11027,14 +11138,51 @@ function assertionReadsProjectSideEffect( else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(skipParens(node.expression))) target = (skipParens(node.expression) as ts.PropertyAccessExpression).expression; - return target === undefined ? undefined : rootIdentifierNode(skipParens(target)); + if (target === undefined) return undefined; + let root = skipValueWrappers(target); + + // `(state as Ctx).called = true`: through casts at any step of the member chain. + while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root)) + root = skipValueWrappers(root.expression); + + return ts.isIdentifier(root) ? root : undefined; + }; + + /** + * Whether code at a node can run for the analysed test: not inside another test's callback, nor inside a hook of a + * suite that does not enclose the test; in the test itself, its suites' hooks, or at module or suite level. + */ + const runsForTest = (node: ts.Node): boolean => { + for (let current: ts.Node = node.parent; current && !ts.isSourceFile(current); current = current.parent) { + if (current === body.parent) return true; + + if (!isFunction(current) || !ts.isCallExpression(current.parent)) continue; + const call = current.parent; + + if (testRegistration(call) !== undefined) return false; + + if (runner.hooks.has(runnerExport(skipParens(call.expression))?.name ?? '')) { + let suite: ts.Node | undefined = call.parent; + + while ( + suite && + !ts.isSourceFile(suite) && + !(isFunction(suite) && ts.isCallExpression(suite.parent) && describeRegistration(suite.parent)) + ) + suite = suite.parent; + + return suite === undefined || ts.isSourceFile(suite) || contains(suite, body); + } + } + + return true; }; for (const node of descendants(source)) { const target = written(node); const symbol = target && checker.getSymbolAtLocation(target); - if (!symbol || !read.has(symbol)) continue; + if (!symbol || !read.has(symbol) || !runsForTest(node)) continue; for (let current: ts.Node = node.parent; current && !ts.isSourceFile(current); current = current.parent) { if (!isFunctionLike(current)) continue; @@ -11165,7 +11313,7 @@ function assignedValuesOf(source: ts.SourceFile, checker: ts.TypeChecker): Map ts.SyntaxKind.LastAssignment ) continue; - const target = skipParens(node.left); + const target = skipValueWrappers(node.left); if (ts.isIdentifier(target)) add(checker.getSymbolAtLocation(target), node.right); else if (ts.isObjectLiteralExpression(target) || ts.isArrayLiteralExpression(target)) @@ -11213,6 +11361,9 @@ function derivedParameters( while (holder && ts.isBindingElement(holder)) holder = holder.parent.parent; + // A member destructured from a parameter (`({ assert }) => check(assert)`) derives from that parameter. + if (holder && holder !== declaration && ts.isParameter(holder)) found.push(holder); + if (holder && ts.isVariableDeclaration(holder) && holder.initializer) found.push(...derivedParameters(holder.initializer, checker, seen)); @@ -11417,6 +11568,16 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe if (cached && cached.runner === runner) return cached.reach; + // A runner that hands its callbacks no context (Jest's `done`) has none to follow. + if (!runner.testContext) + return { + real: new Set(), + fake: new Set(), + unknown: new Set(), + unknownContext: new Set(), + contextual: new Set(), + }; + if (computingReach.has(source)) return { real: new Set(), @@ -11459,12 +11620,7 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe const inlineContext = (parameter: ts.ParameterDeclaration): boolean => { const owner = parameter.parent; - return ( - isFunction(owner) && - owner.parameters[0] === parameter && - !named.has(owner) && - isContextParameter(parameter, checker, 0) - ); + return isFunction(owner) && !named.has(owner) && isContextParameter(parameter, checker, 0); }; /** Where a value handed first to a function comes from: a local function's first parameter, a real context, or neither. */ const origin = ( @@ -11478,9 +11634,14 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe if (traced === 'unknown' || depth > 20) return 'unknown'; const owner = traced.parent; + if (!isFunctionLike(owner)) return 'unknown'; + + // The context of an inline registration callback, at the position it takes it (`(row, ctx) => …` with `test.for`). + if (isFunction(owner) && !named.has(owner) && isContextParameter(traced, checker, 0)) return 'real'; + // A parameter other than a function's first, or of a function static analysis does not follow (a `forEach` - // callback's row): not known. - if (!isFunctionLike(owner) || owner.parameters[0] !== traced) return 'unknown'; + // callback's row, a table row): not known. + if (owner.parameters[0] !== traced) return 'unknown'; if (callbacks.has(owner) || named.has(owner)) return owner; @@ -11490,14 +11651,6 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe if (!ts.isCallExpression(call) || !call.arguments.includes(owner)) return 'unknown'; const callee = skipParens(call.expression); - // A registration of the runner first: `nt.test(…)` with `nt` its namespace or default import registers a test. - if ( - testRegistration(call) !== undefined || - describeRegistration(call) !== undefined || - runner.hooks.has(runnerExport(callee)?.name ?? '') - ) - return 'real'; - // `t.test('child', (child) => …)` on a context: the child's context comes from wherever `t` does. if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'test') { const receiver = traceArgument(callee.expression, checker); @@ -11618,6 +11771,52 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe } } +/** + * The position of the context among the parameters of a registration's callback: the first, the second for a table + * run with `for` (Vitest's `test.for(rows)(name, (row, ctx) => …)`), or none for one run with `each`, whose callback + * takes a row's values. + */ +function registrationContextIndex(call: ts.CallExpression): number | undefined { + const registration = testRegistration(call) ?? describeRegistration(call); + + if (!registration?.modifiers.includes('each')) return 0; + const factory = registrationFactory(call); + + return factory !== undefined && propertyChain(factory).includes('for') ? 1 : undefined; +} + +const callbackIndexCache = new WeakMap< + ts.SourceFile, + { runner: RunnerApi; indexes: Map } +>(); + +/** + * Where a function takes the test context: for one a registration takes as its callback, inline or by name, the + * position `registrationContextIndex` gives; for any other function its first parameter. + */ +function contextIndexOf(fn: ts.Node, checker: ts.TypeChecker): number | undefined { + const source = fn.getSourceFile(); + let cached = callbackIndexCache.get(source); + + if (!cached || cached.runner !== runner) { + const indexes = new Map(); + + for (const node of descendants(source)) { + if (!ts.isCallExpression(node)) continue; + const registration = testRegistration(node) ?? describeRegistration(node); + + if (!registration?.callback) continue; + const callback = testFunction(registration.callback, checker); + + if (callback) indexes.set(callback, registrationContextIndex(node)); + } + cached = { runner, indexes }; + callbackIndexCache.set(source, cached); + } + + return cached.indexes.has(fn) ? cached.indexes.get(fn) : 0; +} + const referencedCallbackCache = new WeakMap }>(); /** @@ -13235,7 +13434,11 @@ function isContextAssertion( return symbol !== undefined && parameters.has(symbol); }; - if (ts.isIdentifier(holder)) return CONTEXT_ASSERTIONS.has(callee.name.text) && isContext(holder); + // `t.is(…)`, and Vitest's `ctx.expect(…)` (the runner's `expect` read from the context). + if (ts.isIdentifier(holder)) + return ( + (CONTEXT_ASSERTIONS.has(callee.name.text) || runner.expect.has(callee.name.text)) && isContext(holder) + ); // `t.assert.equal(...)`, `t.assert.called(fn)` and members not known yet; never `t.assert.bind`. return ( @@ -13415,9 +13618,16 @@ function isTypeLevelAssertion(node: ts.CallExpression): boolean { /** `expect(...)`, and the test runner's type-level checks (`expectTypeOf(...)`, `assertType(...)`). */ function isExpectCall(node: ts.CallExpression): boolean { - const root = rootIdentifier(node.expression); + const root = rootIdentifierNode(node.expression); + + if (root === undefined) return false; + + if (runner.expect.has(root.text) || runner.typeLevel.has(root.text)) return true; + + // `expect` destructured from the test context under another name (`(row, { expect: check }) => check(x)`). + const destructured = runnerChecker ? contextMemberPath(root, runnerChecker) : undefined; - return root !== undefined && (runner.expect.has(root) || runner.typeLevel.has(root)); + return destructured?.length === 1 && runner.expect.has(destructured[0] as string); } /** diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index b0d36d4c..d912355c 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -356,4 +356,167 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, 'Should call onAbort').suspicions).toContain('opaque_call'); expect(byName(tests, 'written by the test itself').suspicions).not.toContain('opaque_call'); }); + + it('never judges a test whose context goes where it is not followed as asserting nothing (safety net)', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/net.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + test('handed to an unknown function', (t) => { (globalThis as any).run(t); }); + test('destructured and handed on', ({ assert }) => { (globalThis as any).run(assert); }); + test('aliased and returned', (t) => { const c = t as unknown; return c; }); + test('cast and stored', (t) => { const box = { c: t as unknown }; void box; }); + test('spread', (t) => { const copy = { ...t }; void copy; }); + test('tautological with an escaping context', (t) => { + (globalThis as any).run(t); + t.assert.equal(1, 1); + }); + test('direct member calls only', (t) => { t.diagnostic(String(value(1))); t.assert.equal(value(1), 2); }); + test('reads a member in a template', (t) => { void \`\${t.name}\`; }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of [ + 'handed to an unknown function', + 'destructured and handed on', + 'aliased and returned', + 'cast and stored', + 'spread', + 'tautological with an escaping context', + ]) { + const test = byName(tests, name); + + expect(test.suspicions, name).not.toContain('no_assertion'); + expect(test.suspicions, name).not.toContain('tautological_assertion'); + expect(test.suspicions, name).toContain('opaque_call'); + } + expect(byName(tests, 'direct member calls only').suspicions).not.toContain('opaque_call'); + // Nothing escapes and nothing asserts: judged as before. + expect(byName(tests, 'reads a member in a template').suspicions).toContain('no_assertion'); + }); + + it("never reads Jest's done as a context", () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/done.test.ts': ` + import { value } from '../src/svc'; + function finish(done: () => void) { done(); } + test('hands done on', (done) => { value(1); finish(done); }); + test('by reference', finish); + `, + }); + const { tests } = inventory(root, jest.recognition); + + for (const name of ['hands done on', 'by reference']) { + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + expect(byName(tests, name).suspicions, name).toContain('no_assertion'); + } + }); + + it('follows a destructured member of the context handed to a helper', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/member.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function check(assert) { assert.equal(value(1), 2); } + test('destructured member', ({ assert }) => { check(assert); }); + `, + }); + const { tests } = inventory(root, node.recognition); + + expect(byName(tests, 'destructured member').suspicions).not.toContain('no_assertion'); + expect(byName(tests, 'destructured member').suspicions).toContain('opaque_call'); + }); + + it("reads Vitest's test.for context at its position: ctx.expect, a renamed expect and a named helper", () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/for.test.ts': ` + import { test } from 'vitest'; + import { value } from '../src/svc'; + function check(ctx) { ctx.expect(value(1)).toBe(2); } + function forHelper([n]: [number], ctx) { ctx.expect(value(n)).toBe(2); } + test.for([[1]])('ctx.expect %s', ([n], ctx) => { ctx.expect(value(n)).toBe(2); }); + test.for([[1]])('renamed %s', ([n], { expect: e }) => { e(value(n)).toBe(2); }); + test.for([[1]])('named %s', forHelper); + test.for([[1]])('handed on %s', ([n], ctx) => { void n; check(ctx); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + for (const name of ['ctx.expect %s', 'renamed %s', 'named %s']) { + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + expect( + byName(tests, name).targetCalls.some((call) => call.asserted), + name, + ).toBe(true); + } + expect(byName(tests, 'handed on %s').suspicions).not.toContain('no_assertion'); + }); + + it('counts only side-effect writers that can run for the test', () => { + const root = tempProject({ + 'src/app.ts': ` + export class App { + handlers: (() => void)[] = []; + on(handler: () => void) { this.handlers.push(handler); } + } + `, + 'test/scope.test.ts': ` + import { beforeEach, describe, expect, it } from 'vitest'; + import { App } from '../src/app'; + let flag = false; + describe('other suite', () => { + beforeEach(() => { new App().on(() => { flag = true; }); }); + it('writes in its own hook', () => { expect(flag).toBe(true); }); + }); + describe('suite', () => { + it('another test writes', () => { new App().on(() => { flag = true; }); }); + it.skip('a skipped test writes', () => { new App().on(() => { flag = true; }); }); + it('only reads', () => { expect(flag).toBe(true); }); + }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + // Its own suite's hook writes: linked, inconclusive. + expect(byName(tests, 'writes in its own hook').suspicions).toContain('opaque_call'); + // Only other tests and another suite's hook write: not linked. + expect(byName(tests, 'only reads').suspicions).not.toContain('opaque_call'); + }); + + it('takes a write through a cast for a reassignment', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/cast.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function check(t) { t.assert.equal(value(1), 2); } + const fake = { assert: { equal() {} } }; + test('by reference', check); + test('cast write', (t) => { + let context = t; + (context as any) = fake; + check(context); + }); + test('non-null write', (t) => { + let context: typeof t | undefined = t; + context! = fake as never; + check(context); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['cast write', 'non-null write']) { + expect( + byName(tests, name).targetCalls.some((call) => call.asserted), + name, + ).toBe(false); + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + } + }); }); diff --git a/packages/test-runners/node/src/index.ts b/packages/test-runners/node/src/index.ts index d622f112..7a0a1548 100644 --- a/packages/test-runners/node/src/index.ts +++ b/packages/test-runners/node/src/index.ts @@ -57,6 +57,8 @@ export const nodeTestRunner: TestRunnerProvider = { chainedModifiersWin: true, // `test(function addsOne() {})` is titled `addsOne`. functionTitles: true, + // `test(name, (t) => …)`: the test context. + testContext: true, // Node checks `skip !== undefined && skip !== false`: an empty reason, 0 or null still skips. optionsSetUnlessFalse: true, hooks: { diff --git a/packages/test-runners/vitest/src/index.ts b/packages/test-runners/vitest/src/index.ts index b79fb318..cb5cafb1 100644 --- a/packages/test-runners/vitest/src/index.ts +++ b/packages/test-runners/vitest/src/index.ts @@ -46,6 +46,8 @@ export const vitestTestRunner: TestRunnerProvider = { registrationFactories: ['each', 'for', 'skipIf', 'runIf'], tableFactories: ['each', 'for'], testOptions: true, + // `test(name, (ctx) => …)`, `test.for(rows)(name, (row, ctx) => …)`: the test context. + testContext: true, hooks: { beforeEach: ['beforeEach'], beforeAll: ['beforeAll'], From 3da0ee3af5c3f52454fb081e8b667fdbde79dbad Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 14:07:28 +0900 Subject: [PATCH 06/14] docs: describe the context safety net and Jest's done --- docs/concepts/support-matrix.md | 2 +- docs/ja/concepts/support-matrix.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/concepts/support-matrix.md b/docs/concepts/support-matrix.md index 571c3e9e..f027c582 100644 --- a/docs/concepts/support-matrix.md +++ b/docs/concepts/support-matrix.md @@ -66,7 +66,7 @@ The Node.js test runner is built into Node.js, so `init` never chooses it just f With Jest, what `jest.mock` does depends on how the tests run. Babel and ts-jest compile them to CommonJS and hoist `jest.mock` above the imports, so it replaces the module and Veritas records a mock. In native ES modules (`"type": "module"` with no Babel config, no compiling transformer, and a Jest config whose `transform` is absent or empty and that has no `preset`; when in doubt, Veritas keeps counting `jest.mock` as a mock) the static imports are bound before `jest.mock` runs and the tests reach the real code, so Veritas does not count it as a mock of them; `jest.unstable_mockModule` followed by a dynamic `import()` is the ESM way, and what such an import loads is reported as unknown. -With the Node.js test runner, Veritas reads `test`/`it` and `describe`/`suite` from `node:test` (named, aliased, or the default import `import test from 'node:test'`, also through its members such as `test.describe` and `test.it`), `.skip`/`.todo`/`.only` and the same as an options object (`{ skip: true }`, `{ skip: 'reason' }`, `{ todo: 'later' }`, `{ only: true }`), the hooks `before`/`after`/`beforeEach`/`afterEach`, and the `mock` API (`mock.fn`, `mock.method`, `mock.getter`/`mock.setter`, `mock.module`). Every value export of `node:assert`, `node:assert/strict` and `assert` counts as an assertion (`assert(x)`, `assert.equal`, named imports such as `strictEqual`, `assert.strict.*`, `require`); a call counts only when its name resolves to that import, so a local function of the same name does not. So does `t.assert.*` on the test context and on the contexts of its subtests. Members destructured from the context (`({ assert, mock }) => …`) are read the same way. When a test hands its context to a function that uses it in ways the analysis does not follow (passes it to another call, stores it, reads `arguments` or a rest parameter), including a function passed by name as the test itself, or to one that is also called with something else, the test is inconclusive (`opaque_call`) rather than judged to assert nothing. An ordinary helper that never receives a context (`function check(x) { expect(x).toBe(2) }`) is judged as any other call. With any runner, a test is also inconclusive when it asserts on a variable written by a closure it hands to project code (`compose([middleware])(ctx)` with the middleware setting `called`, or a handler registered on a project object in a `describe`), or when it hands a project object to a local helper that calls it through its parameter; the link to the project call is possible but not shown. CommonJS test files that bind them with a top-level `const { test } = require('node:test')` or `const assert = require('node:assert')` are read the same way, including modifiers read on a required member (`require('node:test')['describe']['skip']`, `test['skip'](...)`), and `node:assert` required inside a test; `require` counts only when the file does not declare its own. CommonJS has no default export, so `require('node:test').default` and `const { default: test } = require('node:test')` register nothing, while `import { default as test } from 'node:test'` does. Subtests (`t.test`) are analysed as part of the test that registers them, not listed on their own. With any runner, a test file matching `analysis.testInclude` from which no test registration can be read (its tests are registered by code static analysis does not follow) is named in the messages of the `map` stage, which is then `partial`, so the run cannot report `pass`. A file is left out only when it is shown to register nothing: every statement of it and of each local module it loads is known to run no code when it loads, and no module it imports registers tests. Known to run none are imports and exports of modules that pass the package rule, declarations of functions, types, interfaces, const or literal enums and classes without decorators, static blocks or static initialisers that run code, variables and `export default` of inert values (literals, templates without substitutions, functions, object and array literals of such values without spread, local names), CommonJS exports of inert values, a few inert builtins (`Symbol()`, `Object.freeze()`, path and URL helpers) and the runner's hooks and mock configuration (`beforeAll`, `vi.mock`, `jest.setTimeout`). Anything else counts: other calls, `new`, `await`, loops, spread, assignments, member reads that may run a getter, decorators. A package loaded for its side effects (`import 'pkg'`), re-exported whole (`export * from 'pkg'`) or imported dynamically always counts, and in a file of the runner's own pattern (`*.test.*`, `*.spec.*`) so does a package imported by name anywhere in its local imports; in a helper matched only by a directory glob, a package imported by name and used only inside functions does not. This has a known limitation with the Node.js test runner: `node --test` runs every file under a `test` directory as a test file, but a file matched only by such a directory glob (`**/test/**`) still uses the looser rule, so a file there that only binds a package import is not named, even if that package registers tests when it is imported. A local module that does not resolve counts too. A file that the rest of static analysis already finds open (code at load time it cannot read, or code it does not follow, such as a dynamic import of a computed name or a computed member of the runner; re-exports of the runner's API, local JSON loaded by `require` or `import()`, CommonJS exports of inert values and, in a helper matched only by a directory glob, a top-level `require` of a package used only inside functions are not such code) is never left out, whatever this rule says. So a barrel such as `export { test } from 'node:test'` or a helper that only defines functions is not named, while one that runs `const app = createApp()` when it loads is. When the code it runs calls into a package (`import { suite } from 'some-lib'; suite()`), possibly in a local module it loads, the message names the package and that module. A file that uses another runner's API (`bun:test`, `Deno.test`) is named with that reason. The message names the first 10 files and counts the rest. +With the Node.js test runner, Veritas reads `test`/`it` and `describe`/`suite` from `node:test` (named, aliased, or the default import `import test from 'node:test'`, also through its members such as `test.describe` and `test.it`), `.skip`/`.todo`/`.only` and the same as an options object (`{ skip: true }`, `{ skip: 'reason' }`, `{ todo: 'later' }`, `{ only: true }`), the hooks `before`/`after`/`beforeEach`/`afterEach`, and the `mock` API (`mock.fn`, `mock.method`, `mock.getter`/`mock.setter`, `mock.module`). Every value export of `node:assert`, `node:assert/strict` and `assert` counts as an assertion (`assert(x)`, `assert.equal`, named imports such as `strictEqual`, `assert.strict.*`, `require`); a call counts only when its name resolves to that import, so a local function of the same name does not. So does `t.assert.*` on the test context and on the contexts of its subtests. Members destructured from the context (`({ assert, mock }) => …`) are read the same way. When a test hands its context to a function that uses it in ways the analysis does not follow (passes it to another call, stores it, reads `arguments` or a rest parameter), including a function passed by name as the test itself, or to one that is also called with something else, the test is inconclusive (`opaque_call`) rather than judged to assert nothing. With node:test and Vitest, whose callbacks receive a test context (the second parameter with Vitest's `test.for`), any use of the context, a member destructured from it or an alias of them other than a direct member call such as `t.assert.equal(…)` or `ctx.expect(…)` keeps the test from being judged to assert nothing or to assert only constants. Jest's `done` is not a context. An ordinary helper that never receives a context (`function check(x) { expect(x).toBe(2) }`) is judged as any other call. With any runner, a test is also inconclusive when it asserts on a variable written by a closure it hands to project code (`compose([middleware])(ctx)` with the middleware setting `called`, or a handler registered on a project object in a `describe`), or when it hands a project object to a local helper that calls it through its parameter; the link to the project call is possible but not shown. CommonJS test files that bind them with a top-level `const { test } = require('node:test')` or `const assert = require('node:assert')` are read the same way, including modifiers read on a required member (`require('node:test')['describe']['skip']`, `test['skip'](...)`), and `node:assert` required inside a test; `require` counts only when the file does not declare its own. CommonJS has no default export, so `require('node:test').default` and `const { default: test } = require('node:test')` register nothing, while `import { default as test } from 'node:test'` does. Subtests (`t.test`) are analysed as part of the test that registers them, not listed on their own. With any runner, a test file matching `analysis.testInclude` from which no test registration can be read (its tests are registered by code static analysis does not follow) is named in the messages of the `map` stage, which is then `partial`, so the run cannot report `pass`. A file is left out only when it is shown to register nothing: every statement of it and of each local module it loads is known to run no code when it loads, and no module it imports registers tests. Known to run none are imports and exports of modules that pass the package rule, declarations of functions, types, interfaces, const or literal enums and classes without decorators, static blocks or static initialisers that run code, variables and `export default` of inert values (literals, templates without substitutions, functions, object and array literals of such values without spread, local names), CommonJS exports of inert values, a few inert builtins (`Symbol()`, `Object.freeze()`, path and URL helpers) and the runner's hooks and mock configuration (`beforeAll`, `vi.mock`, `jest.setTimeout`). Anything else counts: other calls, `new`, `await`, loops, spread, assignments, member reads that may run a getter, decorators. A package loaded for its side effects (`import 'pkg'`), re-exported whole (`export * from 'pkg'`) or imported dynamically always counts, and in a file of the runner's own pattern (`*.test.*`, `*.spec.*`) so does a package imported by name anywhere in its local imports; in a helper matched only by a directory glob, a package imported by name and used only inside functions does not. This has a known limitation with the Node.js test runner: `node --test` runs every file under a `test` directory as a test file, but a file matched only by such a directory glob (`**/test/**`) still uses the looser rule, so a file there that only binds a package import is not named, even if that package registers tests when it is imported. A local module that does not resolve counts too. A file that the rest of static analysis already finds open (code at load time it cannot read, or code it does not follow, such as a dynamic import of a computed name or a computed member of the runner; re-exports of the runner's API, local JSON loaded by `require` or `import()`, CommonJS exports of inert values and, in a helper matched only by a directory glob, a top-level `require` of a package used only inside functions are not such code) is never left out, whatever this rule says. So a barrel such as `export { test } from 'node:test'` or a helper that only defines functions is not named, while one that runs `const app = createApp()` when it loads is. When the code it runs calls into a package (`import { suite } from 'some-lib'; suite()`), possibly in a local module it loads, the message names the package and that module. A file that uses another runner's API (`bun:test`, `Deno.test`) is named with that reason. The message names the first 10 files and counts the rest. When Veritas runs these tests, it runs `node --test` from the project root with Node's default file patterns, not the project's test script, so extra flags such as `--import tsx` or custom globs in that script are not applied. The bundled reporter writes its JSON report inside `.veritas/improve/`. Tests are keyed `:: test > subtest>`, and skipped and todo tests count as skipped. TypeScript tests run through Node's type stripping, so they must use erasable syntax and import `.ts` file names. diff --git a/docs/ja/concepts/support-matrix.md b/docs/ja/concepts/support-matrix.md index 4768b4d0..2b66dfa6 100644 --- a/docs/ja/concepts/support-matrix.md +++ b/docs/ja/concepts/support-matrix.md @@ -66,7 +66,7 @@ Node.js のテストランナーは Node.js に組み込まれているので、 Jest では、`jest.mock` の効果がテストの実行方法で変わります。Babel や ts-jest はテストを CommonJS にコンパイルし、`jest.mock` を import より前に移すので、モジュールが置き換わり、Veritas はモックとして記録します。ネイティブ ESM(`"type": "module"` で、Babel の設定もコンパイルする transformer もなく、Jest の設定の `transform` がないか空で `preset` もない。判断できないときは `jest.mock` をモックとして数え続けます)では、`jest.mock` が実行される前に静的な import が結び付けられ、テストは本物のコードを実行するので、Veritas はそれらのモックとして数えません。ESM でのモックは `jest.unstable_mockModule` と動的な `import()` の組み合わせで、そうした import が読み込むものは不明として報告します。 -Node.js のテストランナーでは、`node:test` の `test`/`it` と `describe`/`suite`(名前付き、別名、既定の import `import test from 'node:test'` のいずれも。`test.describe` や `test.it` のようにそのメンバーを通しても読みます)、`.skip`/`.todo`/`.only` と、同じ指定をオプションのオブジェクトで書いたもの(`{ skip: true }`、`{ skip: 'reason' }`、`{ todo: 'later' }`、`{ only: true }`)、フックの `before`/`after`/`beforeEach`/`afterEach`、`mock` の API(`mock.fn`、`mock.method`、`mock.getter`/`mock.setter`、`mock.module`)を読みます。`node:assert`、`node:assert/strict`、`assert` が export する値はすべて assertion として数え(`assert(x)`、`assert.equal`、`strictEqual` などの名前付き import、`assert.strict.*`、`require`)。数えるのは、呼び出した名前がその import に解決されるときだけで、同じ名前のローカルの関数は数えません。テストのコンテキストとそのサブテストのコンテキストの `t.assert.*` も同じです。コンテキストから分割代入したメンバー(`({ assert, mock }) => …`)も同じように読みます。テストが、解析で追えない使い方(別の呼び出しに渡す、格納する、`arguments` や rest 引数で読む)をする関数にコンテキストを渡すとき(テストとして名前で渡した関数そのものも含みます)や、ほかの値でも呼ばれる関数に渡すときは、assertion がないとは判定せず、判断できない(`opaque_call`)とします。コンテキストを受け取ることのない普通のヘルパー(`function check(x) { expect(x).toBe(2) }`)は、ほかの呼び出しと同じように判定します。また、どのランナーでも、プロジェクトのコードに渡したクロージャーが書き換える変数を assertion で確かめるテスト(`called` を設定するミドルウェアを渡す `compose([middleware])(ctx)` や、`describe` の中でプロジェクトのオブジェクトに登録したハンドラー)と、プロジェクトのオブジェクトをローカルのヘルパーに渡し、ヘルパーが引数を通してそれを呼ぶテストも、判断できない扱いにします。プロジェクトの呼び出しとのつながりはありうるものの、示せていないためです。トップレベルの `const { test } = require('node:test')` や `const assert = require('node:assert')` で束縛する CommonJS のテストファイルも、同じように読みます。require したメンバーに続けた修飾子(`require('node:test')['describe']['skip']`、`test['skip'](...)`)や、テストの中で require した `node:assert` も読みます。`require` は、ファイルが同じ名前を自分で宣言していないときだけ数えます。CommonJS には既定の export がないので、`require('node:test').default` や `const { default: test } = require('node:test')` はテストを登録しませんが、`import { default as test } from 'node:test'` は登録します。サブテスト(`t.test`)は、それを登録したテストの一部として解析し、単独では一覧に載せません。どのランナーでも、`analysis.testInclude` に当てはまるのにテストの登録を1つも読めなかったテストファイル(静的解析で追えないコードがテストを登録している場合など)は、`map` ステージのメッセージに名前が出ます。このとき `map` ステージは `partial` になり、実行結果が `pass` になることはありません。名前を出さないのは、テストを登録しないことを示せたファイルだけです。つまり、そのファイルと読み込むローカルのモジュールのすべての文が、読み込まれる間にコードを実行しないとわかっていて、テストを登録するモジュールを import していないファイルです。コードを実行しないとみなすのは、パッケージの規則を満たすモジュールの import と export、関数・型・interface・const か値がリテラルの enum・デコレーターや static ブロックやコードを実行する static 初期化子のない class の宣言、無害な値(リテラル、置換のないテンプレート、関数、spread のないそうした値のオブジェクトと配列、ローカルの名前)で初期化する変数と `export default`、無害な値の CommonJS の export、少数の無害な組み込み(`Symbol()`、`Object.freeze()`、パスと URL のヘルパー)、ランナーのフックとモックの設定(`beforeAll`、`vi.mock`、`jest.setTimeout`)だけです。それ以外の呼び出し、`new`、`await`、ループ、spread、代入、getter を実行しうるメンバーの読み取り、デコレーターはコードの実行とみなします。副作用のためのパッケージの読み込み(`import 'pkg'`)、パッケージ全体の re-export(`export * from 'pkg'`)、パッケージの動的 import は常に数えます。ランナー自身のパターン(`*.test.*`、`*.spec.*`)に当てはまるファイルでは、ローカルの import のどこかで名前付きでパッケージを import することも数えます。ディレクトリの glob だけで当てはまるヘルパーでは、名前付きで import して関数の中でだけ使うパッケージは数えません。これには Node.js のテストランナーで既知の制限があります。`node --test` は `test` ディレクトリの下のファイルをすべてテストファイルとして実行しますが、そうしたディレクトリの glob(`**/test/**`)だけで当てはまるファイルにはゆるいほうの規則を使います。そのため、そこにあってパッケージの import を束縛するだけのファイルは、そのパッケージが import されたときにテストを登録するものであっても、名前が出ません。解決できないローカルのモジュールも数えます。また、静的解析のほかの部分がすでに開いているとみなしたファイル(読み込み時に読めないコードがある、または計算された名前の動的 import やランナーの計算されたメンバーのように追えないコードに届く。ランナーの API の re-export、`require` や `import()` で読み込むローカルの JSON、無害な値の CommonJS の export、ディレクトリの glob だけで当てはまるヘルパーでトップレベルに `require` して関数の中でだけ使うパッケージは、これに当たりません)は、この規則にかかわらず必ず名前が出ます。そのため、`export { test } from 'node:test'` のような barrel や、関数を定義するだけのヘルパーは名前が出ませんが、読み込まれるときに `const app = createApp()` を実行するヘルパーは名前が出ます。実行するコードがパッケージを呼び出しているとき(`import { suite } from 'some-lib'; suite()`。読み込むローカルのモジュールの中の場合も含みます)は、メッセージにそのパッケージとモジュールが出ます。ほかのランナーの API(`bun:test`、`Deno.test`)を使うファイルは、その理由とともに名前が出ます。メッセージに名前が出るのは最初の 10 個までで、残りは数だけを示します。 +Node.js のテストランナーでは、`node:test` の `test`/`it` と `describe`/`suite`(名前付き、別名、既定の import `import test from 'node:test'` のいずれも。`test.describe` や `test.it` のようにそのメンバーを通しても読みます)、`.skip`/`.todo`/`.only` と、同じ指定をオプションのオブジェクトで書いたもの(`{ skip: true }`、`{ skip: 'reason' }`、`{ todo: 'later' }`、`{ only: true }`)、フックの `before`/`after`/`beforeEach`/`afterEach`、`mock` の API(`mock.fn`、`mock.method`、`mock.getter`/`mock.setter`、`mock.module`)を読みます。`node:assert`、`node:assert/strict`、`assert` が export する値はすべて assertion として数え(`assert(x)`、`assert.equal`、`strictEqual` などの名前付き import、`assert.strict.*`、`require`)。数えるのは、呼び出した名前がその import に解決されるときだけで、同じ名前のローカルの関数は数えません。テストのコンテキストとそのサブテストのコンテキストの `t.assert.*` も同じです。コンテキストから分割代入したメンバー(`({ assert, mock }) => …`)も同じように読みます。テストが、解析で追えない使い方(別の呼び出しに渡す、格納する、`arguments` や rest 引数で読む)をする関数にコンテキストを渡すとき(テストとして名前で渡した関数そのものも含みます)や、ほかの値でも呼ばれる関数に渡すときは、assertion がないとは判定せず、判断できない(`opaque_call`)とします。テストのコンテキストを受け取る node:test と Vitest(Vitest の `test.for` では第 2 引数)では、コンテキストやそこから分割代入したメンバー、それらの別名を、`t.assert.equal(…)` や `ctx.expect(…)` のような直接のメンバー呼び出し以外の形で使うテストは、assertion がない、または定数だけを確かめているとは判定しません。Jest の `done` はコンテキストとして扱いません。コンテキストを受け取ることのない普通のヘルパー(`function check(x) { expect(x).toBe(2) }`)は、ほかの呼び出しと同じように判定します。また、どのランナーでも、プロジェクトのコードに渡したクロージャーが書き換える変数を assertion で確かめるテスト(`called` を設定するミドルウェアを渡す `compose([middleware])(ctx)` や、`describe` の中でプロジェクトのオブジェクトに登録したハンドラー)と、プロジェクトのオブジェクトをローカルのヘルパーに渡し、ヘルパーが引数を通してそれを呼ぶテストも、判断できない扱いにします。プロジェクトの呼び出しとのつながりはありうるものの、示せていないためです。トップレベルの `const { test } = require('node:test')` や `const assert = require('node:assert')` で束縛する CommonJS のテストファイルも、同じように読みます。require したメンバーに続けた修飾子(`require('node:test')['describe']['skip']`、`test['skip'](...)`)や、テストの中で require した `node:assert` も読みます。`require` は、ファイルが同じ名前を自分で宣言していないときだけ数えます。CommonJS には既定の export がないので、`require('node:test').default` や `const { default: test } = require('node:test')` はテストを登録しませんが、`import { default as test } from 'node:test'` は登録します。サブテスト(`t.test`)は、それを登録したテストの一部として解析し、単独では一覧に載せません。どのランナーでも、`analysis.testInclude` に当てはまるのにテストの登録を1つも読めなかったテストファイル(静的解析で追えないコードがテストを登録している場合など)は、`map` ステージのメッセージに名前が出ます。このとき `map` ステージは `partial` になり、実行結果が `pass` になることはありません。名前を出さないのは、テストを登録しないことを示せたファイルだけです。つまり、そのファイルと読み込むローカルのモジュールのすべての文が、読み込まれる間にコードを実行しないとわかっていて、テストを登録するモジュールを import していないファイルです。コードを実行しないとみなすのは、パッケージの規則を満たすモジュールの import と export、関数・型・interface・const か値がリテラルの enum・デコレーターや static ブロックやコードを実行する static 初期化子のない class の宣言、無害な値(リテラル、置換のないテンプレート、関数、spread のないそうした値のオブジェクトと配列、ローカルの名前)で初期化する変数と `export default`、無害な値の CommonJS の export、少数の無害な組み込み(`Symbol()`、`Object.freeze()`、パスと URL のヘルパー)、ランナーのフックとモックの設定(`beforeAll`、`vi.mock`、`jest.setTimeout`)だけです。それ以外の呼び出し、`new`、`await`、ループ、spread、代入、getter を実行しうるメンバーの読み取り、デコレーターはコードの実行とみなします。副作用のためのパッケージの読み込み(`import 'pkg'`)、パッケージ全体の re-export(`export * from 'pkg'`)、パッケージの動的 import は常に数えます。ランナー自身のパターン(`*.test.*`、`*.spec.*`)に当てはまるファイルでは、ローカルの import のどこかで名前付きでパッケージを import することも数えます。ディレクトリの glob だけで当てはまるヘルパーでは、名前付きで import して関数の中でだけ使うパッケージは数えません。これには Node.js のテストランナーで既知の制限があります。`node --test` は `test` ディレクトリの下のファイルをすべてテストファイルとして実行しますが、そうしたディレクトリの glob(`**/test/**`)だけで当てはまるファイルにはゆるいほうの規則を使います。そのため、そこにあってパッケージの import を束縛するだけのファイルは、そのパッケージが import されたときにテストを登録するものであっても、名前が出ません。解決できないローカルのモジュールも数えます。また、静的解析のほかの部分がすでに開いているとみなしたファイル(読み込み時に読めないコードがある、または計算された名前の動的 import やランナーの計算されたメンバーのように追えないコードに届く。ランナーの API の re-export、`require` や `import()` で読み込むローカルの JSON、無害な値の CommonJS の export、ディレクトリの glob だけで当てはまるヘルパーでトップレベルに `require` して関数の中でだけ使うパッケージは、これに当たりません)は、この規則にかかわらず必ず名前が出ます。そのため、`export { test } from 'node:test'` のような barrel や、関数を定義するだけのヘルパーは名前が出ませんが、読み込まれるときに `const app = createApp()` を実行するヘルパーは名前が出ます。実行するコードがパッケージを呼び出しているとき(`import { suite } from 'some-lib'; suite()`。読み込むローカルのモジュールの中の場合も含みます)は、メッセージにそのパッケージとモジュールが出ます。ほかのランナーの API(`bun:test`、`Deno.test`)を使うファイルは、その理由とともに名前が出ます。メッセージに名前が出るのは最初の 10 個までで、残りは数だけを示します。 Veritas がこれらのテストを実行するときは、プロジェクトのルートで Node.js の既定のファイルパターンを使って `node --test` を実行します。プロジェクトの test スクリプトは実行しないので、そこに書いた `--import tsx` などのフラグや独自の glob は適用されません。同梱のレポーターは JSON のレポートを `.veritas/improve/` の中に書きます。テストのキーは `:: test > subtest>` で、skip と todo のテストはスキップとして数えます。TypeScript のテストは Node.js の型の除去(type stripping)で実行するので、消去できる構文だけを使い、`.ts` のファイル名で import する必要があります。 From d34d42f210d592e73320e9f37ba278e97682396d Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 14:27:30 +0900 Subject: [PATCH 07/14] fix(test-inventory): end the context alias fixpoint and cap every fixpoint and worklist The alias loop of the context safety net never ended for const { assert } = t or const { expect } = ctx in a test body: it re-added the destructuring pattern on every round, hanging the inventory. Each declaration is now taken once, and the loop ends when no new alias is found. A member destructured with a const in the body ({ assert } = t, nested { assert: { equal } } = t) is read as the context's member. Every fixpoint and worklist added for context reach and unread test files (context aliases, contextReach and its contextual sets, the local-module walks for loadsCode and packageCall) also stops at an iteration limit. Past it, its result is read as unknown: context escapes, every function may receive an untraced context, the module may run code. A debug log event (inventory-iteration-cap) records it. setInventoryIterationLimit sets the limit for tests. --- packages/test-inventory/src/index.ts | 128 +++++++++++++++--- .../test/context-precision.test.ts | 75 +++++++++- 2 files changed, 180 insertions(+), 23 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index c001fdde..5c384b7e 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -2,6 +2,7 @@ import { readdirSync, readFileSync } from 'node:fs'; import { builtinModules } from 'node:module'; import path from 'node:path'; import { + logEvent, type MockCallRole, resolveInsideRoot, sha256, @@ -190,6 +191,33 @@ let runner: RunnerApi = runnerApi({ * The id of the test registered in `file` under `suitePath` and `name`. Registrations that share all three (the same * literal title twice, two ``s, two anonymous callbacks) are told apart by `disambiguateTestIds`. */ +/** At most this many rounds for each fixpoint or worklist of the inventory; past it, what it decides is unknown. */ +let iterationLimit = 10_000; + +/** + * Set the iteration limit of the inventory's fixpoints and worklists (for tests of the fail-safe path); returns a + * function that restores the previous limit. + */ +export function setInventoryIterationLimit(limit: number): () => void { + const previous = iterationLimit; + iterationLimit = limit; + + return () => { + iterationLimit = previous; + }; +} + +/** Record that a fixpoint or worklist stopped at the iteration limit; its result is then read as unknown. */ +function iterationCapHit(where: string): void { + logEvent( + 'debug', + `test inventory: ${where} stopped after ${iterationLimit} iterations; its result is read as unknown`, + { + event: 'inventory-iteration-cap', + }, + ); +} + export function testId(file: string, suitePath: string[], name: string): string { return stableId('T', { file: file.split('\\').join('/'), suitePath, name }); } @@ -1060,7 +1088,14 @@ function loadsCode(source: ts.SourceFile): boolean { const seen = new Set([source]); const queue = [source]; - for (let current = queue.shift(); current; current = queue.shift()) { + // Each module is queued once (`seen`); the cap guards the walk all the same, and stopping there may run code. + for (let current = queue.shift(), rounds = 0; current; current = queue.shift(), rounds++) { + if (rounds > iterationLimit) { + iterationCapHit('the walk of local modules for code they run'); + + return true; + } + if (moduleRunsCode(current, strict)) return true; for (const specifier of localSpecifiers(current)) { @@ -1155,7 +1190,12 @@ function reachedPackageCall( const seen = new Set([source]); const queue = [source]; - for (let current = queue.shift(); current; current = queue.shift()) { + for (let current = queue.shift(), rounds = 0; current; current = queue.shift(), rounds++) { + if (rounds > iterationLimit) { + iterationCapHit('the walk of local modules for package calls'); + + return { unresolved: true }; + } const own = packageCall(current).packageCall; if (own !== undefined) @@ -10703,7 +10743,11 @@ function isTestContext(identifier: ts.Identifier, checker: ts.TypeChecker, depth * `t.assert`, `({ assert: { equal } }) => …` binds `equal` to `t.assert.equal`), outermost first; undefined for a * name not destructured from a context parameter (a rest element, a computed key, any other pattern). */ -function contextMemberPath(identifier: ts.Identifier, checker: ts.TypeChecker): string[] | undefined { +function contextMemberPath( + identifier: ts.Identifier, + checker: ts.TypeChecker, + depth = 0, +): string[] | undefined { const declaration = checker.getSymbolAtLocation(identifier)?.valueDeclaration; if (!declaration || !ts.isBindingElement(declaration)) return undefined; @@ -10720,7 +10764,26 @@ function contextMemberPath(identifier: ts.Identifier, checker: ts.TypeChecker): node = node.parent.parent; } - return ts.isParameter(node) && isContextParameter(node, checker, 0) ? path : undefined; + if (ts.isParameter(node)) return isContextParameter(node, checker, 0) ? path : undefined; + + // `const { assert } = t` in the body: destructured from the context, or from a member already destructured from it. + if ( + ts.isVariableDeclaration(node) && + node.initializer && + (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0 && + depth < 20 + ) { + const value = skipValueWrappers(node.initializer); + + if (!ts.isIdentifier(value)) return undefined; + + if (isTestContext(value, checker)) return path; + const prefix = contextMemberPath(value, checker, depth + 1); + + return prefix ? [...prefix, ...path] : undefined; + } + + return undefined; } /** Whether a function's parameter is the context its runner hands it (see `isTestContext`), under any name or pattern. */ @@ -10912,20 +10975,30 @@ function contextUseUnfollowed( : checker.getSymbolAtLocation(node); // `const c = t`, `const c = t as Ctx`, `const { assert } = t`: aliases, followed in turn. - for (let added = true; added; ) { + // Each declaration is taken once (a destructuring pattern too), so the loop ends when no new alias is found. + const aliases = new Set(); + + for (let added = true, rounds = 0; added; rounds++) { + if (rounds > iterationLimit) { + iterationCapHit('context aliases'); + + return true; + } added = false; for (const node of nodes) if ( ts.isVariableDeclaration(node) && node.initializer && - !declarations.has(node.name) && + !aliases.has(node) && (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0 ) { const value = skipValueWrappers(node.initializer); const symbol = ts.isIdentifier(value) ? checker.getSymbolAtLocation(value) : undefined; if (symbol && symbols.has(symbol)) { + aliases.add(node); + if (!bind(node.name)) return true; added = true; } @@ -10943,20 +11016,8 @@ function contextUseUnfollowed( while (valueWrapper(use.parent)) use = use.parent; - // The initializer of an alias, followed above. - if ( - ts.isVariableDeclaration(use.parent) && - use.parent.initializer === use && - declarations.has(use.parent.name) - ) - return false; - - if ( - ts.isVariableDeclaration(use.parent) && - use.parent.initializer === use && - ts.isObjectBindingPattern(use.parent.name) - ) - return false; + // The initializer of an alias, followed above (a `const`, also destructuring it); any other declaration is not. + if (aliases.has(use.parent)) return false; let chain: ts.Node = use; while (ts.isPropertyAccessExpression(chain.parent) && chain.parent.expression === chain) @@ -11715,7 +11776,14 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe } else fake.add(fn); } - for (let changed = true; changed; ) { + // Each round adds to a set or ends: the sets only grow, so the loop ends; the cap guards it all the same. + let capped = false; + + for (let changed = true, rounds = 0; changed; rounds++) { + if (rounds > iterationLimit) { + capped = true; + break; + } changed = false; for (const [from, to] of forwards) { @@ -11753,7 +11821,11 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe for (const fn of new Set([...named, ...callbacks])) if (!unrelatedFirstParameter(fn as ts.SignatureDeclaration, checker)) contextual.add(fn); - for (let changed = true; changed; ) { + for (let changed = true, rounds = 0; changed; rounds++) { + if (rounds > iterationLimit) { + capped = true; + break; + } changed = false; for (const [from, to] of forwards) @@ -11762,6 +11834,18 @@ function contextReach(source: ts.SourceFile, checker: ts.TypeChecker): ContextRe changed = true; } } + + // Stopped at the cap: nothing is known of any function, so every one may receive an untraced context and none is + // read as a context. + if (capped) { + iterationCapHit('context reach'); + + for (const fn of new Set([...named, ...callbacks])) { + unknown.add(fn); + unknownContext.add(fn); + contextual.add(fn); + } + } const reach = { real, fake, unknown, unknownContext, contextual }; contextReachCache.set(source, { runner, reach }); diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index d912355c..bbac8ea7 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -3,7 +3,7 @@ import { jestTestRunner as jest } from '@under18dev/veritas-test-runner-jest'; import { nodeTestRunner as node } from '@under18dev/veritas-test-runner-node'; import { vitestTestRunner as vitest } from '@under18dev/veritas-test-runner-vitest'; import { describe, expect, it } from 'vitest'; -import { inventoryTests } from '../src/index.js'; +import { inventoryTests, setInventoryIterationLimit } from '../src/index.js'; import { tempProject } from './helpers.js'; const SERVICE = `export const svc = { price: (n: number) => n + 1 };\nexport const value = (n: number) => n + 1;\nexport const two = 2;\n`; @@ -519,4 +519,77 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); } }); + + it('reads a context destructured with a const in the test body, and ends', { timeout: 20_000 }, () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/node.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + test('const assert', (t) => { + const { assert } = t; + assert.equal(value(1), 2); + }); + test('nested', (t) => { + const { assert: { equal } } = t; + equal(value(1), 2); + }); + test('destructured then handed on', (t) => { + const { assert } = t; + (globalThis as any).run(assert); + }); + `, + 'test/vitest.test.ts': ` + import { test } from 'vitest'; + import { value } from '../src/svc'; + test('const expect', (ctx) => { + const { expect } = ctx; + expect(value(1)).toBe(2); + }); + `, + }); + const nodeTests = inventory(root, node.recognition).tests; + const vitestTests = inventory(root, vitest.recognition).tests; + + for (const name of ['const assert', 'nested']) { + expect(byName(nodeTests, name).suspicions, name).not.toContain('opaque_call'); + expect(byName(nodeTests, name).suspicions, name).not.toContain('no_assertion'); + } + expect(byName(nodeTests, 'destructured then handed on').suspicions).toContain('opaque_call'); + expect(byName(vitestTests, 'const expect').suspicions).not.toContain('opaque_call'); + expect(byName(vitestTests, 'const expect').suspicions).not.toContain('no_assertion'); + }); + + it('reads what a fixpoint stopped at its cap decides as unknown, never hanging', { + timeout: 20_000, + }, () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/cap.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + test('const assert', (t) => { + const { assert } = t; + value(1); + assert.equal(1, 1); + }); + `, + }); + // Read in full: the alias is followed, and the assertion compares constants. + expect(byName(inventory(root, node.recognition).tests, 'const assert').suspicions).toContain( + 'tautological_assertion', + ); + const restore = setInventoryIterationLimit(0); + + try { + const test = byName(inventory(root, node.recognition).tests, 'const assert'); + + // Stopped at the cap: what the context leads to is unknown, never judged tautological or empty. + expect(test.suspicions).toContain('opaque_call'); + expect(test.suspicions).not.toContain('tautological_assertion'); + expect(test.suspicions).not.toContain('no_assertion'); + } finally { + restore(); + } + }); }); From a0dcbf688aaa1f5ace54d5ccd0b82e3c34ae4d9b Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 14:45:29 +0900 Subject: [PATCH 08/14] fix(test-inventory): leave subtests known not to run out of the context and side-effect scans The safety net and the side-effect writer scan looked inside subtests that are skipped or todo (t.test(name, { skip: true }, fn), t.test.todo), so a test whose only escape was in such a subtest was opaque_call instead of no_assertion. Those bodies are now left out, as analyzeTest already leaves them out of assertions; subtests whose options cannot be read still count. --- packages/test-inventory/src/index.ts | 17 ++++++++--- .../test/context-precision.test.ts | 30 +++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index 5c384b7e..b10a91c2 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -7693,9 +7693,11 @@ function functionName(value: ts.Expression): string | undefined { function skippedSubtestBodies( body: ts.Node, checker: ts.TypeChecker, -): { skipped: ts.Node[]; unread: boolean } { - if (!runner.testOptions) return { skipped: [], unread: false }; +): { skipped: ts.Node[]; unread: boolean; definite: ts.Node[] } { + if (!runner.testOptions) return { skipped: [], unread: false, definite: [] }; const skipped: ts.Node[] = []; + // Those known not to run (skipped or todo), not those whose options cannot be read. + const definite: ts.Node[] = []; let unread = false; for (const node of descendants(body)) { @@ -7721,9 +7723,10 @@ function skippedSubtestBodies( skipped.push(skipParens(fn)); if (state === 'unknown') unread = true; + else definite.push(skipParens(fn)); } - return { skipped, unread }; + return { skipped, unread, definite }; } /** @@ -10968,7 +10971,9 @@ function contextUseUnfollowed( }; if (!bind(parameter.name)) return true; - const nodes = [body, ...descendants(body)]; + // Not what subtests known not to run hold (`t.test(name, { skip: true }, fn)`); those whose options cannot be read count. + const notRun = skippedSubtestBodies(body, checker).definite; + const nodes = [body, ...descendants(body)].filter((node) => !notRun.some((fn) => contains(fn, node))); const resolve = (node: ts.Identifier) => ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) @@ -11213,7 +11218,11 @@ function assertionReadsProjectSideEffect( * Whether code at a node can run for the analysed test: not inside another test's callback, nor inside a hook of a * suite that does not enclose the test; in the test itself, its suites' hooks, or at module or suite level. */ + // Subtests of the test known not to run (`t.test(name, { skip: true }, fn)`) write nothing for it. + const notRun = skippedSubtestBodies(body, checker).definite; const runsForTest = (node: ts.Node): boolean => { + if (notRun.some((fn) => contains(fn, node))) return false; + for (let current: ts.Node = node.parent; current && !ts.isSourceFile(current); current = current.parent) { if (current === body.parent) return true; diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index bbac8ea7..2ef1f8b8 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -592,4 +592,34 @@ describe('test contexts and ordinary helpers', () => { restore(); } }); + + it('leaves out subtests known not to run, and keeps those whose options cannot be read', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/sub.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + const options = (globalThis as any).options; + test('skipped subtest', (t) => { + value(1); + t.test('child', { skip: true }, () => (globalThis as any).sink(t)); + }); + test('todo subtest', (t) => { + value(1); + t.test.todo('child', () => (globalThis as any).sink(t)); + }); + test('options not read', (t) => { + value(1); + t.test('child', options, () => (globalThis as any).sink(t)); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['skipped subtest', 'todo subtest']) { + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + expect(byName(tests, name).suspicions, name).toContain('no_assertion'); + } + expect(byName(tests, 'options not read').suspicions).not.toContain('no_assertion'); + }); }); From 1bf26fe69873448a7c533f1364b0521a661bd6c6 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 15:01:29 +0900 Subject: [PATCH 09/14] fix(test-inventory): scan todo subtests for execution, apply the safety net to subtest contexts, and pass the iteration limit per call - Node runs todo subtests: their bodies are scanned again for side-effect writers and context escapes, and their calls are recorded as run, while their assertions still gate nothing. Only skipped subtests are left out. - Each running subtest's own context counts for the safety net: an escape in a subtest body (Reflect.apply(check, null, [s])) keeps the test that owns the evidence from no_assertion. - The safety net treats a context reached through more aliases than assertion counting follows (ALIAS_DEPTH) as unfollowed. - The iteration limit is an inventoryTests option (iterationLimit) set for the duration of one call, instead of a mutable global exported from the package. --- packages/test-inventory/src/index.ts | 136 ++++++++++++++---- .../test/context-precision.test.ts | 126 ++++++++++++++-- 2 files changed, 217 insertions(+), 45 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index b10a91c2..d1d7858b 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -191,21 +191,15 @@ let runner: RunnerApi = runnerApi({ * The id of the test registered in `file` under `suitePath` and `name`. Registrations that share all three (the same * literal title twice, two ``s, two anonymous callbacks) are told apart by `disambiguateTestIds`. */ -/** At most this many rounds for each fixpoint or worklist of the inventory; past it, what it decides is unknown. */ -let iterationLimit = 10_000; - +/** How many `const` aliases of a test context (`const c = t; const d = c`) assertion counting follows. */ +const ALIAS_DEPTH = 20; +/** Rounds a fixpoint or worklist of the inventory runs by default; past them, what it decides is unknown. */ +const DEFAULT_ITERATION_LIMIT = 10_000; /** - * Set the iteration limit of the inventory's fixpoints and worklists (for tests of the fail-safe path); returns a - * function that restores the previous limit. + * At most this many rounds for each fixpoint or worklist of the inventory; past it, what it decides is unknown. Set + * for the duration of one `inventoryTests` call from its `iterationLimit` option (calls are synchronous). */ -export function setInventoryIterationLimit(limit: number): () => void { - const previous = iterationLimit; - iterationLimit = limit; - - return () => { - iterationLimit = previous; - }; -} +let iterationLimit = DEFAULT_ITERATION_LIMIT; /** Record that a fixpoint or worklist stopped at the iteration limit; its result is then read as unknown. */ function iterationCapHit(where: string): void { @@ -1278,16 +1272,24 @@ export function inventoryTests(options: { config: VeritasConfig; recognition: TestRunnerRecognition; files?: string[]; + /** + * Rounds each fixpoint or worklist of the analysis may run (default 10,000); past them, what it decides is read as + * unknown (fail-safe), never looped on. + */ + iterationLimit?: number; }): TestInventory { const previous = runner; const previousChecker = runnerChecker; + const previousLimit = iterationLimit; runner = runnerApi(options.recognition); + iterationLimit = options.iterationLimit ?? DEFAULT_ITERATION_LIMIT; try { return inventory(options); } finally { runner = previous; runnerChecker = previousChecker; + iterationLimit = previousLimit; } } @@ -1975,9 +1977,11 @@ function analyzeBody( // Subtests that are skipped or todo (`t.test('x', { skip: true }, fn)`) never run: nothing in them counts. const subtests = skippedSubtestBodies(body, checker); const notRun = (node: ts.Node) => subtests.skipped.some((fn) => contains(fn, node)); + // A todo subtest runs (Node reports it `# TODO`): its calls run, though its assertions gate nothing. + const todo = (node: ts.Node) => subtests.todo.some((fn) => contains(fn, node)); for (const node of descendants(body)) { - if (notRun(node)) continue; + if (notRun(node) && !todo(node)) continue; if (ts.isTryStatement(node) && node.catchClause?.variableDeclaration) bind( @@ -2082,7 +2086,11 @@ function analyzeBody( if (specifier !== undefined) unresolvedImports.add(specifier); } - if (ts.isCallExpression(node) && (isExpectCall(node) || isAssertCall(node) || contextAssertion(node))) + if ( + !todo(node) && + ts.isCallExpression(node) && + (isExpectCall(node) || isAssertCall(node) || contextAssertion(node)) + ) assertions.push(node); } // What a helper returns may come from enclosing variables, e.g. `const of = (n) => candidates.filter(...)`. @@ -7693,10 +7701,12 @@ function functionName(value: ts.Expression): string | undefined { function skippedSubtestBodies( body: ts.Node, checker: ts.TypeChecker, -): { skipped: ts.Node[]; unread: boolean; definite: ts.Node[] } { - if (!runner.testOptions) return { skipped: [], unread: false, definite: [] }; +): { skipped: ts.Node[]; unread: boolean; definite: ts.Node[]; todo: ts.Node[] } { + if (!runner.testOptions) return { skipped: [], unread: false, definite: [], todo: [] }; + // Those that run though they gate nothing: todo, and not skipped. + const todo: ts.Node[] = []; const skipped: ts.Node[] = []; - // Those known not to run (skipped or todo), not those whose options cannot be read. + // Those known not to run: skipped, not todo (which runs) nor those whose options cannot be read. const definite: ts.Node[] = []; let unread = false; @@ -7723,10 +7733,57 @@ function skippedSubtestBodies( skipped.push(skipParens(fn)); if (state === 'unknown') unread = true; - else definite.push(skipParens(fn)); + + // A todo subtest still runs (Node reports it `# TODO`), its side effects included: only a skipped one does not. + const skip = chained + ? outer.name.text === 'skip' + ? 'skipped' + : 'runs' + : subtestState(node, checker, ['skip']); + + if (skip === 'skipped') definite.push(skipParens(fn)); + else if (skip === 'runs' && state === 'skipped') todo.push(skipParens(fn)); } - return { skipped, unread, definite }; + return { skipped, unread, definite, todo }; +} + +/** + * The inline callbacks of the subtests a test body registers through a context (`t.test('x', (s) => …)`, nested + * ones too) that may run: all but those known to be skipped (a todo runs, and options that cannot be read may let it). + */ +function runningSubtestCallbacks( + body: ts.Node | undefined, + checker: ts.TypeChecker, +): (ts.ArrowFunction | ts.FunctionExpression)[] { + if (body === undefined) return []; + const notRun = skippedSubtestBodies(body, checker).definite; + const callbacks: (ts.ArrowFunction | ts.FunctionExpression)[] = []; + + for (const node of descendants(body)) { + if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) continue; + const outer = node.expression; + const callee = + (outer.name.text === 'skip' || outer.name.text === 'todo') && + ts.isPropertyAccessExpression(outer.expression) + ? outer.expression + : outer; + + if ( + !ts.isPropertyAccessExpression(callee) || + callee.name.text !== 'test' || + !ts.isIdentifier(callee.expression) || + !isTestContext(callee.expression, checker) + ) + continue; + const fn = node.arguments.findLast((argument) => isFunction(skipParens(argument))); + const callback = fn && skipParens(fn); + + if (callback && isFunction(callback) && !notRun.some((skipped) => contains(skipped, callback))) + callbacks.push(callback); + } + + return callbacks; } /** @@ -7734,7 +7791,11 @@ function skippedSubtestBodies( * to anything but `false` or `undefined`, also through a constant holding the object literal (`const o = { skip: * true }`); unknown when an option or the options object cannot be read. */ -function subtestState(call: ts.CallExpression, checker: ts.TypeChecker): 'runs' | 'skipped' | 'unknown' { +function subtestState( + call: ts.CallExpression, + checker: ts.TypeChecker, + options: readonly string[] = ['skip', 'todo'], +): 'runs' | 'skipped' | 'unknown' { const resolve = (expression: ts.Expression): ts.Expression => { let value = skipParens(expression); @@ -7781,7 +7842,7 @@ function subtestState(call: ts.CallExpression, checker: ts.TypeChecker): 'runs' continue; } - if (name !== 'skip' && name !== 'todo') continue; + if (!options.includes(name)) continue; const option = skipParens(property.initializer); if ( @@ -8563,7 +8624,15 @@ function readTest( const escapedContext = testFn !== undefined && contextIndex !== undefined && - (contextNode !== undefined ? contextUseUnfollowed(testFn, contextNode, checker) : readsArguments(testFn)); + ((contextNode !== undefined + ? contextUseUnfollowed(testFn, contextNode, checker) + : readsArguments(testFn)) || + // The subtests it runs are part of it: each one's own context counts too (`t.test('x', (s) => fn.call(s))`). + runningSubtestCallbacks(body, checker).some((callback) => + callback.parameters[0] !== undefined + ? contextUseUnfollowed(callback, callback.parameters[0], checker) + : readsArguments(callback), + )); const nodes = body ? descendants(body) : []; const contextParameter = contextNode && ts.isIdentifier(contextNode.name) @@ -10721,7 +10790,7 @@ function importsRunnerModule( function isTestContext(identifier: ts.Identifier, checker: ts.TypeChecker, depth = 0): boolean { const declaration = checker.getSymbolAtLocation(identifier)?.valueDeclaration; - if (depth > 20) return false; + if (depth > ALIAS_DEPTH) return false; // `const context = t`: an alias of a context is one. if ( @@ -10774,7 +10843,7 @@ function contextMemberPath( ts.isVariableDeclaration(node) && node.initializer && (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0 && - depth < 20 + depth < ALIAS_DEPTH ) { const value = skipValueWrappers(node.initializer); @@ -10948,12 +11017,17 @@ function contextUseUnfollowed( if (readsArguments(fn) || parameter.dotDotDotToken) return true; const symbols = new Set(); + // How many aliases away from the parameter each name is: counting assertions follows no more than `ALIAS_DEPTH`. + const depths = new Map(); const declarations = new Set(); - const bind = (name: ts.BindingName): boolean => { + const bind = (name: ts.BindingName, depth: number): boolean => { if (ts.isIdentifier(name)) { const symbol = checker.getSymbolAtLocation(name); - if (symbol) symbols.add(symbol); + if (symbol) { + symbols.add(symbol); + depths.set(symbol, depth); + } declarations.add(name); return true; @@ -10966,11 +11040,11 @@ function contextUseUnfollowed( (!element.propertyName || !ts.isComputedPropertyName(element.propertyName) || ts.isStringLiteralLike(skipParens(element.propertyName.expression))) && - bind(element.name)), + bind(element.name, depth)), ); }; - if (!bind(parameter.name)) return true; + if (!bind(parameter.name, 0)) return true; // Not what subtests known not to run hold (`t.test(name, { skip: true }, fn)`); those whose options cannot be read count. const notRun = skippedSubtestBodies(body, checker).definite; const nodes = [body, ...descendants(body)].filter((node) => !notRun.some((fn) => contains(fn, node))); @@ -11003,8 +11077,10 @@ function contextUseUnfollowed( if (symbol && symbols.has(symbol)) { aliases.add(node); + const depth = (depths.get(symbol) ?? 0) + 1; - if (!bind(node.name)) return true; + // Past the depth assertion counting follows, a use through it would not be credited: unfollowed. + if (depth >= ALIAS_DEPTH || !bind(node.name, depth)) return true; added = true; } } diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index 2ef1f8b8..ed306b21 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -3,7 +3,7 @@ import { jestTestRunner as jest } from '@under18dev/veritas-test-runner-jest'; import { nodeTestRunner as node } from '@under18dev/veritas-test-runner-node'; import { vitestTestRunner as vitest } from '@under18dev/veritas-test-runner-vitest'; import { describe, expect, it } from 'vitest'; -import { inventoryTests, setInventoryIterationLimit } from '../src/index.js'; +import { inventoryTests } from '../src/index.js'; import { tempProject } from './helpers.js'; const SERVICE = `export const svc = { price: (n: number) => n + 1 };\nexport const value = (n: number) => n + 1;\nexport const two = 2;\n`; @@ -579,21 +579,25 @@ describe('test contexts and ordinary helpers', () => { expect(byName(inventory(root, node.recognition).tests, 'const assert').suspicions).toContain( 'tautological_assertion', ); - const restore = setInventoryIterationLimit(0); - - try { - const test = byName(inventory(root, node.recognition).tests, 'const assert'); + const capped = inventoryTests({ + recognition: node.recognition, + root, + config: VeritasConfig.parse({ analysis: { testInclude: ['test/*.test.ts'] } }), + iterationLimit: 0, + }); + const test = byName(capped.tests, 'const assert'); - // Stopped at the cap: what the context leads to is unknown, never judged tautological or empty. - expect(test.suspicions).toContain('opaque_call'); - expect(test.suspicions).not.toContain('tautological_assertion'); - expect(test.suspicions).not.toContain('no_assertion'); - } finally { - restore(); - } + // Stopped at the cap: what the context leads to is unknown, never judged tautological or empty. + expect(test.suspicions).toContain('opaque_call'); + expect(test.suspicions).not.toContain('tautological_assertion'); + expect(test.suspicions).not.toContain('no_assertion'); + // The limit holds for that call only. + expect(byName(inventory(root, node.recognition).tests, 'const assert').suspicions).toContain( + 'tautological_assertion', + ); }); - it('leaves out subtests known not to run, and keeps those whose options cannot be read', () => { + it('leaves out skipped subtests, and scans todo ones and those whose options cannot be read', () => { const root = tempProject({ 'src/svc.ts': SERVICE, 'test/sub.test.ts': ` @@ -604,6 +608,10 @@ describe('test contexts and ordinary helpers', () => { value(1); t.test('child', { skip: true }, () => (globalThis as any).sink(t)); }); + test('chained skip', (t) => { + value(1); + t.test.skip('child', () => (globalThis as any).sink(t)); + }); test('todo subtest', (t) => { value(1); t.test.todo('child', () => (globalThis as any).sink(t)); @@ -616,10 +624,98 @@ describe('test contexts and ordinary helpers', () => { }); const { tests } = inventory(root, node.recognition); - for (const name of ['skipped subtest', 'todo subtest']) { + for (const name of ['skipped subtest', 'chained skip']) { expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); expect(byName(tests, name).suspicions, name).toContain('no_assertion'); } - expect(byName(tests, 'options not read').suspicions).not.toContain('no_assertion'); + + // A todo subtest runs: what it does with the context counts. + for (const name of ['todo subtest', 'options not read']) + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + }); + + it('takes what a todo subtest writes through project code as run, and what a skipped one writes as not', () => { + const root = tempProject({ + 'src/run.ts': 'export const run = (fn: () => void) => fn();\n', + 'test/todo.test.ts': ` + import { test } from 'node:test'; + import assert from 'node:assert/strict'; + import { run } from '../src/run'; + test('todo writer', async (t) => { + let hit = 0; + await t.test('w', { todo: true }, () => { run(() => { hit++; }); }); + assert.equal(hit, 1); + }); + test('skipped writer', async (t) => { + let hit = 0; + await t.test('w', { skip: true }, () => { run(() => { hit++; }); }); + assert.equal(hit, 1); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + // The todo subtest's project call runs and writes what the test asserts: linked, never disconnected. + expect(byName(tests, 'todo writer').suspicions).not.toContain('target_not_called'); + expect( + byName(tests, 'todo writer').suspicions.includes('opaque_call') || + byName(tests, 'todo writer').targetCalls.some((call) => call.asserted), + ).toBe(true); + // The skipped one never runs. + expect(byName(tests, 'skipped writer').suspicions).not.toContain('opaque_call'); + }); + + it("applies the safety net to a running subtest's own context", () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/subctx.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function check(s) { s.assert.equal(value(1), 2); } + const options = { timeout: 1000 }; + test('skip false', async (t) => { + await t.test('child', { skip: false }, (s) => { Reflect.apply(check, null, [s]); }); + }); + test('const-held options', async (t) => { + await t.test('child', options, (s) => { Reflect.apply(check, null, [s]); }); + }); + test('skipped child', async (t) => { + value(1); + await t.test('child', { skip: true }, (s) => { Reflect.apply(check, null, [s]); }); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['skip false', 'const-held options']) { + expect(byName(tests, name).suspicions, name).not.toContain('no_assertion'); + expect(byName(tests, name).suspicions, name).toContain('opaque_call'); + } + expect(byName(tests, 'skipped child').suspicions).toContain('no_assertion'); + }); + + it('takes a use past the alias depth assertion counting follows as unfollowed', () => { + const aliases = Array.from({ length: 22 }, (_, index) => `const a${index + 1} = a${index};`).join('\n'); + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/deep.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + test('deep aliases', (a0) => { + ${aliases} + a22.assert.equal(value(1), 2); + }); + test('shallow aliases', (a0) => { + const a1 = a0; + const a2 = a1; + a2.assert.equal(value(1), 2); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + expect(byName(tests, 'deep aliases').suspicions).not.toContain('no_assertion'); + expect(byName(tests, 'shallow aliases').suspicions).not.toContain('no_assertion'); + expect(byName(tests, 'shallow aliases').suspicions).not.toContain('opaque_call'); }); }); From cf5bbb4276b198e4f286574255c93bac11f6da77 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 15:05:49 +0900 Subject: [PATCH 10/14] fix(test-inventory): resolve a callback's context per registration, skip types, and know builtin values - A function registered both with table rows and with a context (test.each(rows)('row', check) and test('normal', check)) got one context index for the whole file, so a row's fake object could count as an assertion depending on registration order. The context is now resolved per registration while that registration is analysed. A function registered both ways has no known context: the row registration gets no credit, and the context registration is opaque_call, never no_assertion. - Names of the context inside a type (typeof t, an annotation, the type of satisfies) are not uses of it. - A helper handed a project value calls no project code through it when the value is a primitive or a builtin of the standard library (Array, Map, Set, Date, RegExp, Promise) whose methods are declared in lib files: no opaque_call for n.toString() on an imported const two = 2. --- packages/test-inventory/src/index.ts | 128 +++++++++++++++--- .../test/context-precision.test.ts | 79 +++++++++++ 2 files changed, 191 insertions(+), 16 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index d1d7858b..8424f5f2 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -8579,15 +8579,23 @@ function registration(node: ts.CallExpression, names: Set): TestCaseType /** `readTest`, with a function the test's callback names (`it('x', check)`) read as that callback. */ function analyzeTest(...args: Parameters): TestCaseType { const previous = contextCallback; - const [, info, , , , ctx] = args; + const previousIndex = contextCallbackIndex; + const [registrationCall, info, , , , ctx] = args; const callback = info.callback && skipParens(info.callback); - contextCallback = + const fn = callback !== undefined && !isFunction(callback) ? testFunction(callback, ctx.checker) : undefined; + const index = runner.testContext ? registrationContextIndex(registrationCall) : undefined; + // Read as this registration hands it: the context at its position, none for a table row. A function registered + // both ways is not read as having a context (`readTest` leaves the registration that hands one inconclusive). + contextCallback = + fn !== undefined && index !== undefined && !contextIndexConflict(fn, ctx.checker) ? fn : undefined; + contextCallbackIndex = index; try { return readTest(...args); } finally { contextCallback = previous; + contextCallbackIndex = previousIndex; } } @@ -8617,16 +8625,22 @@ function readTest( // The test's context, for a runner that hands one (Node's `t`, Vitest's `ctx`; not Jest's `done`), at the position // its callback takes it: a table row comes first with `each`, before the context with Vitest's `test.for`. const contextIndex = runner.testContext ? registrationContextIndex(registrationCall) : undefined; - const contextNode = contextIndex !== undefined ? testFn?.parameters[contextIndex] : undefined; + // A function registered elsewhere with a table row (or the context elsewhere) has no known context here. + const contextNode = + contextIndex !== undefined && !(testFn !== undefined && contextIndexConflict(testFn, checker)) + ? testFn?.parameters[contextIndex] + : undefined; // Safety net: the context (or a member destructured from it, an alias, a cast) used in any way but a direct member // call the inventory reads (`t.assert.equal(…)`, `t.mock.fn()`, `t.test(…)`, `ctx.expect(…)`) may hold assertions // the inventory does not see, whatever is known of where it goes. const escapedContext = testFn !== undefined && contextIndex !== undefined && - ((contextNode !== undefined - ? contextUseUnfollowed(testFn, contextNode, checker) - : readsArguments(testFn)) || + // Registered elsewhere with a table row or the context elsewhere: not known which it gets here. + (contextIndexConflict(testFn, checker) || + (contextNode !== undefined + ? contextUseUnfollowed(testFn, contextNode, checker) + : readsArguments(testFn)) || // The subtests it runs are part of it: each one's own context counts too (`t.test('x', (s) => fn.call(s))`). runningSubtestCallbacks(body, checker).some((callback) => callback.parameters[0] !== undefined @@ -10869,13 +10883,14 @@ function isContextParameter( // Only for a runner that hands one (not Jest, whose first argument is `done`), at the position the callback takes // it: a table row comes first with `each`, before the context with `for`. if (!runner.testContext || !isFunctionLike(fn)) return false; + + // A function passed by name as a test, suite or hook callback (`test('x', check)`), read as the callback of the + // registration being analysed: the context is the parameter at the position that registration hands it. + if (contextCallback === fn) + return contextCallbackIndex !== undefined && fn.parameters[contextCallbackIndex] === declaration; const index = contextIndexOf(fn, checker); if (index === undefined || fn.parameters[index] !== declaration) return false; - - // A function passed by name as a test, suite or hook callback (`test('x', check)`), read as that callback: its first - // parameter is the context the runner hands it. - if (contextCallback === fn) return true; // A local function followed from its calls: a context only when every path to it hands it one (see `contextReach`); // one also reached with a plain object (`check({ assert: { equal() {} } })`) is not, and the calls that may hand it a // real context are opaque instead (`handsContextToMixedCallback`). @@ -10909,6 +10924,8 @@ function isContextParameter( /** The function passed by name (`test('x', check)`) that `analyzeTest` is reading as the test's callback, if any. */ let contextCallback: ts.Node | undefined; +/** Where the registration `analyzeTest` is reading hands `contextCallback` the context. */ +let contextCallbackIndex: number | undefined; /** * Whether a variable is never written after its declaration. Every write form counts: `x = …` and compound @@ -10998,6 +11015,17 @@ function neverReassigned(declaration: ts.VariableDeclaration, checker: ts.TypeCh ); } +/** Whether a name is written in a type (`typeof t`, an annotation, the type of `satisfies`), which runs nothing. */ +function inTypePosition(node: ts.Node): boolean { + for (let current = node.parent; current && !ts.isSourceFile(current); current = current.parent) { + if (ts.isTypeNode(current)) return true; + + if (ts.isStatement(current) || ts.isExpressionStatement(current) || isFunctionLike(current)) return false; + } + + return false; +} + /** * Whether a test's callback uses its context in any way but a direct member call the inventory reads: the context * parameter, the members destructured from it, and every `const` alias of them (also through a cast or a @@ -11087,7 +11115,7 @@ function contextUseUnfollowed( } return nodes.some((node) => { - if (!ts.isIdentifier(node) || declarations.has(node)) return false; + if (!ts.isIdentifier(node) || declarations.has(node) || inTypePosition(node)) return false; const symbol = resolve(node); if (!symbol || !symbols.has(symbol)) return false; @@ -11346,6 +11374,52 @@ function assertionReadsProjectSideEffect( return false; } +/** Builtins whose methods are the standard library's. */ +const BUILTIN_TYPES = new Set([ + 'Array', + 'ReadonlyArray', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'Date', + 'RegExp', + 'Promise', +]); + +/** + * Whether a type is a primitive (or a literal of one) or a well-known builtin declared by the standard library: + * calling its methods runs no project code. `any`, `unknown` and anything else are not. + */ +function builtinValue(type: ts.Type): boolean { + const primitive = + ts.TypeFlags.NumberLike | + ts.TypeFlags.StringLike | + ts.TypeFlags.BooleanLike | + ts.TypeFlags.BigIntLike | + ts.TypeFlags.ESSymbolLike | + ts.TypeFlags.Null | + ts.TypeFlags.Undefined; + + if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return false; + + if (type.isUnion()) return type.types.every((each) => builtinValue(each)); + + if (type.flags & primitive) return true; + const symbol = type.getSymbol(); + + return ( + symbol !== undefined && + BUILTIN_TYPES.has(symbol.name) && + (symbol.declarations ?? []).length > 0 && + (symbol.declarations ?? []).every((declaration) => { + const file = declaration.getSourceFile(); + + return file.isDeclarationFile && /[\\/]typescript[\\/]lib[\\/]lib\.[^\\/]*\.d\.ts$/.test(file.fileName); + }) + ); +} + /** * Whether a call hands a local helper a project value (an import of project code, or an instance of a project class * made there) as an argument whose parameter the helper calls or calls a method of (`function checkObj(o) { @@ -11380,6 +11454,10 @@ function projectValueCalledThroughParameter(node: Invocation, body: ts.Node, ctx if (!parameter || !ts.isIdentifier(parameter.name) || !projectValue(argument)) return false; const symbol = checker.getSymbolAtLocation(parameter.name); + // A primitive (`const two = 2`) or a well-known builtin (an array, a map, a date) has only the methods of the + // standard library, which run no project code; anything typed by project declarations, `any` or `unknown` may. + if (builtinValue(checker.getTypeAtLocation(argument))) return false; + return descendants(body).some( (child) => ts.isCallExpression(child) && @@ -11956,19 +12034,19 @@ function registrationContextIndex(call: ts.CallExpression): number | undefined { const callbackIndexCache = new WeakMap< ts.SourceFile, - { runner: RunnerApi; indexes: Map } + { runner: RunnerApi; indexes: Map> } >(); /** * Where a function takes the test context: for one a registration takes as its callback, inline or by name, the * position `registrationContextIndex` gives; for any other function its first parameter. */ -function contextIndexOf(fn: ts.Node, checker: ts.TypeChecker): number | undefined { +function registeredContextIndexes(fn: ts.Node, checker: ts.TypeChecker): Set | undefined { const source = fn.getSourceFile(); let cached = callbackIndexCache.get(source); if (!cached || cached.runner !== runner) { - const indexes = new Map(); + const indexes = new Map>(); for (const node of descendants(source)) { if (!ts.isCallExpression(node)) continue; @@ -11977,13 +12055,31 @@ function contextIndexOf(fn: ts.Node, checker: ts.TypeChecker): number | undefine if (!registration?.callback) continue; const callback = testFunction(registration.callback, checker); - if (callback) indexes.set(callback, registrationContextIndex(node)); + if (callback) + indexes.set(callback, (indexes.get(callback) ?? new Set()).add(registrationContextIndex(node))); } cached = { runner, indexes }; callbackIndexCache.set(source, cached); } - return cached.indexes.has(fn) ? cached.indexes.get(fn) : 0; + return cached.indexes.get(fn); +} + +/** + * Whether a function is registered in ways that hand it the context at different positions, or a context in one and a + * table row in another (`test.each(rows)('row', check)` and `test('normal', check)`): which one its parameter is depends on + * the registration, so outside one it is no context, and in the one that hands a context it is not known either. + */ +function contextIndexConflict(fn: ts.Node, checker: ts.TypeChecker): boolean { + return (registeredContextIndexes(fn, checker)?.size ?? 0) > 1; +} + +function contextIndexOf(fn: ts.Node, checker: ts.TypeChecker): number | undefined { + const indexes = registeredContextIndexes(fn, checker); + + if (indexes === undefined) return 0; + + return indexes.size === 1 ? [...indexes][0] : undefined; } const referencedCallbackCache = new WeakMap }>(); diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index ed306b21..cc080ec1 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -718,4 +718,83 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, 'shallow aliases').suspicions).not.toContain('no_assertion'); expect(byName(tests, 'shallow aliases').suspicions).not.toContain('opaque_call'); }); + + for (const order of ['row first', 'normal first'] as const) + it(`gives a function registered both with table rows and a context no credit from a row (${order})`, () => { + const registrations = + order === 'row first' + ? "test.each([[{ equal() {} }]])('row %#', check);\ntest('normal', check);" + : "test('normal', check);\ntest.each([[{ equal() {} }]])('row %#', check);"; + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/shared.test.ts': ` + import { test } from 'vitest'; + import { value } from '../src/svc'; + function check(e) { e.equal(value(1), 2); } + ${registrations} + `, + }); + const { tests } = inventory(root, vitest.recognition); + const row = byName(tests, 'row %#'); + const normal = byName(tests, 'normal'); + + // A row's fake object never counts as an assertion. + expect(row.assertionCount, order).toBe(0); + expect( + row.targetCalls.some((call) => call.asserted), + order, + ).toBe(false); + // Which the parameter is here is not known: inconclusive, never credited from the row either. + expect(normal.suspicions, order).toContain('opaque_call'); + expect(normal.suspicions, order).not.toContain('no_assertion'); + }); + + it('takes a context named only in a type for no use of it', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/types.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + test('typeof in an annotation', (t) => { + const copy: typeof t | undefined = undefined; + void copy; + value(1); + }); + test('satisfies a type of it', (t) => { + const options = {} satisfies Partial; + void options; + value(1); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['typeof in an annotation', 'satisfies a type of it']) { + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + expect(byName(tests, name).suspicions, name).toContain('no_assertion'); + } + }); + + it('takes builtin methods of a project primitive or builtin for no project call, and project objects for one', () => { + const root = tempProject({ + 'src/svc.ts': `${SERVICE}export const names = ['a'];\nexport const when = new Date(0);\n`, + 'test/builtins.test.ts': ` + import { expect, test } from 'vitest'; + import { names, svc, two, when } from '../src/svc'; + function asText(n) { expect(n.toString()).toBe('2'); } + function first(list) { expect(list.at(0)).toBe('a'); } + function year(d) { expect(d.getUTCFullYear()).toBe(1970); } + function price(o) { expect(o.price(1)).toBe(2); } + test('primitive', () => { asText(two); }); + test('array', () => { first(names); }); + test('date', () => { year(when); }); + test('project object', () => { price(svc); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + for (const name of ['primitive', 'array', 'date']) + expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); + expect(byName(tests, 'project object').suspicions).toContain('opaque_call'); + }); }); From 26e35a83a17931bc68c75cbf883a67e82e9e8cce Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 15:23:14 +0900 Subject: [PATCH 11/14] fix(test-inventory): run nothing under a skipped subtest at any depth, credit nothing a todo subtest asserts, and narrow builtin values - A call under a skipped subtest (or one whose options cannot be read) at any depth is not run, whatever todo marks sit above or below it, and however the call is reached: through the body, an awaited value or a binding. Calls in skipped subtests were recorded through awaited values before. - In a todo subtest, a call runs but credits nothing it asserts: no helper assertions, no assertion inside on a project call's result, no observed mock. Its helpers no longer keep a test from no_assertion either. - Side-effect writers in teardown hooks (afterEach, afterAll, after) are not counted; only setup hooks, module or suite level and the test's own body. - readsArguments stops at nested functions, methods, accessors, constructors and static blocks, and still walks into arrows, which share arguments. - The builtin exclusion of the helper-parameter rule now covers only primitives (number, string, boolean, bigint, symbol and their literals), or a const initialised directly with an array of literals, a regular expression, a builtin constructor or Promise.resolve. A value only declared with a builtin type (a project subclass of Promise) stays opaque_call. --- packages/test-inventory/src/index.ts | 207 +++++++++++++----- .../test/context-precision.test.ts | 136 ++++++++++++ 2 files changed, 288 insertions(+), 55 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index 8424f5f2..f8fe442d 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -1684,6 +1684,23 @@ interface BodyAnalysis { * Calls, assertions and result flow in a test body or helper body. Values are followed through local and * enclosing (describe-level or module-level) variables of the same file, including `let` set in a hook. */ +/** + * What a call does without what it asserts: the project calls it runs, and nothing it checks (no helper assertions, + * no assertion inside on a call's result, no observation of a mock or the page). + */ +function withoutAssertionCredit(info: CallInfo): CallInfo { + const { observesDocument: _observes, ...rest } = info; + + return { + ...rest, + helperAsserts: false, + targets: info.targets.map(({ observedBy: _observed, ...target }) => ({ + ...target, + assertedInside: false, + })), + }; +} + function analyzeBody( body: ts.Node, ctx: Ctx, @@ -1694,6 +1711,12 @@ function analyzeBody( keepDeferred = true, ): BodyAnalysis { const { checker } = ctx; + // Subtests known not to run, or whose options cannot be read, run nothing that counts, at any depth; a todo subtest + // runs (Node reports it `# TODO`), but neither its assertions nor what its calls assert gate anything. + const subtests = skippedSubtestBodies(body, checker); + const notExecuted = (node: ts.Node) => + subtests.skipped.some((fn) => !subtests.todo.includes(fn) && contains(fn, node)); + const notGating = (node: ts.Node) => subtests.skipped.some((fn) => contains(fn, node)); // Components rendered by shared setup that runs before the body (`beforeEach(() => render())`). const setupEntries = new Set(); // Where an element made outside the body is mounted in it (`render(ui)`). @@ -1714,7 +1737,12 @@ function analyzeBody( const record = (node: Invocation): boolean => { // Code in an `onClick={() => …}` handler of a DOM or third-party element runs only when an event fires. if (contains(body, node) && inUnfiredHandler(node, body, ctx)) return false; - const info = callInfo(node, ctx); + + // In a subtest that does not run, however the call is reached (through an awaited value, a binding). + if (notExecuted(node)) return false; + const called = callInfo(node, ctx); + // Called in a todo subtest: it runs, but what it asserts gates nothing. + const info = notGating(node) ? withoutAssertionCredit(called) : called; if (!recorded.has(node)) { recorded.add(node); @@ -1974,14 +2002,8 @@ function analyzeBody( // body itself, which is not among its descendants. if (ts.isCallExpression(body) && (isExpectCall(body) || isAssertCall(body) || contextAssertion(body))) assertions.push(body); - // Subtests that are skipped or todo (`t.test('x', { skip: true }, fn)`) never run: nothing in them counts. - const subtests = skippedSubtestBodies(body, checker); - const notRun = (node: ts.Node) => subtests.skipped.some((fn) => contains(fn, node)); - // A todo subtest runs (Node reports it `# TODO`): its calls run, though its assertions gate nothing. - const todo = (node: ts.Node) => subtests.todo.some((fn) => contains(fn, node)); - for (const node of descendants(body)) { - if (notRun(node) && !todo(node)) continue; + if (notExecuted(node)) continue; if (ts.isTryStatement(node) && node.catchClause?.variableDeclaration) bind( @@ -2087,7 +2109,7 @@ function analyzeBody( } if ( - !todo(node) && + !notGating(node) && ts.isCallExpression(node) && (isExpectCall(node) || isAssertCall(node) || contextAssertion(node)) ) @@ -2390,7 +2412,7 @@ function analyzeBody( // through the checker, so a shadowing local of the same name is not mistaken for it, and an imported helper // (through any re-exports) is looked up in the file that declares it. for (const node of descendants(body)) { - if (notRun(node) || !ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) continue; + if (notGating(node) || !ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) continue; let symbol = checker.getSymbolAtLocation(node.expression); if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol); const positions = (symbol?.declarations ?? []) @@ -8788,7 +8810,7 @@ function readTest( !analysis?.helperAsserts && !analysis?.assertionsUnknown && !escapedContext && - !callsHelperWithAssertion(body, source) + !callsHelperWithAssertion(body, source, checker) ) suspicions.push('no_assertion'); @@ -11335,7 +11357,12 @@ function assertionReadsProjectSideEffect( if (testRegistration(call) !== undefined) return false; - if (runner.hooks.has(runnerExport(skipParens(call.expression))?.name ?? '')) { + const hook = runnerExport(skipParens(call.expression))?.name ?? ''; + + // A teardown hook (`afterEach`, `afterAll`) runs after the assertion: nothing it writes can decide it. + if (runner.hooks.has(hook) && !runner.setup.has(hook)) return false; + + if (runner.setup.has(hook)) { let suite: ts.Node | undefined = call.parent; while ( @@ -11374,50 +11401,88 @@ function assertionReadsProjectSideEffect( return false; } -/** Builtins whose methods are the standard library's. */ -const BUILTIN_TYPES = new Set([ - 'Array', - 'ReadonlyArray', - 'Map', - 'Set', - 'WeakMap', - 'WeakSet', - 'Date', - 'RegExp', - 'Promise', -]); +/** Builtin constructors whose instances made there have only the standard library's methods. */ +const BUILTIN_CONSTRUCTORS = new Set(['Array', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Date', 'RegExp']); /** - * Whether a type is a primitive (or a literal of one) or a well-known builtin declared by the standard library: - * calling its methods runs no project code. `any`, `unknown` and anything else are not. + * Whether a value handed to a helper is shown to have only the standard library's methods: a primitive (number, + * string, boolean, bigint, symbol or a literal of one), which no class can extend; or a `const` initialised, there and + * directly, with an array of literals, a regular expression, a builtin constructor (`new Map()`, `new Date(0)`) + * or `Promise.resolve(…)`. A value only declared with a builtin type (`const lazy: Promise = new Lazy()`, a + * project subclass) is not, nor `any`, `unknown` or anything else. */ -function builtinValue(type: ts.Type): boolean { +function builtinValue(argument: ts.Expression, checker: ts.TypeChecker): boolean { const primitive = ts.TypeFlags.NumberLike | ts.TypeFlags.StringLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.BigIntLike | - ts.TypeFlags.ESSymbolLike | - ts.TypeFlags.Null | - ts.TypeFlags.Undefined; + ts.TypeFlags.ESSymbolLike; + const type = checker.getTypeAtLocation(argument); + const primitiveType = (each: ts.Type): boolean => + each.isUnion() ? each.types.every(primitiveType) : (each.flags & primitive) !== 0; - if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return false; + if (!(type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && primitiveType(type)) return true; + const value = skipValueWrappers(argument); - if (type.isUnion()) return type.types.every((each) => builtinValue(each)); + if (!ts.isIdentifier(value)) return false; + let symbol = checker.getSymbolAtLocation(value); - if (type.flags & primitive) return true; - const symbol = type.getSymbol(); + try { + if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol); + } catch { + return false; + } + const declaration = symbol?.valueDeclaration; - return ( - symbol !== undefined && - BUILTIN_TYPES.has(symbol.name) && - (symbol.declarations ?? []).length > 0 && - (symbol.declarations ?? []).every((declaration) => { - const file = declaration.getSourceFile(); + if ( + !declaration || + !ts.isVariableDeclaration(declaration) || + (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) === 0 || + !declaration.initializer + ) + return false; + const initializer = skipValueWrappers(declaration.initializer); + const lib = (identifier: ts.Expression) => + ts.isIdentifier(identifier) && + (checker.getSymbolAtLocation(identifier)?.declarations ?? []).every( + (each) => each.getSourceFile().isDeclarationFile, + ); - return file.isDeclarationFile && /[\\/]typescript[\\/]lib[\\/]lib\.[^\\/]*\.d\.ts$/.test(file.fileName); - }) - ); + // An array of literals (whose elements are no project functions either), a regular expression. + if ( + (ts.isArrayLiteralExpression(initializer) && + initializer.elements.every( + (element) => + ts.isStringLiteralLike(element) || + ts.isNumericLiteral(element) || + element.kind === ts.SyntaxKind.TrueKeyword || + element.kind === ts.SyntaxKind.FalseKeyword || + element.kind === ts.SyntaxKind.NullKeyword, + )) || + ts.isRegularExpressionLiteral(initializer) + ) + return true; + + if (ts.isNewExpression(initializer)) { + const callee = skipParens(initializer.expression); + + return ts.isIdentifier(callee) && BUILTIN_CONSTRUCTORS.has(callee.text) && lib(callee); + } + + if (ts.isCallExpression(initializer)) { + const callee = skipParens(initializer.expression); + + return ( + ts.isPropertyAccessExpression(callee) && + callee.name.text === 'resolve' && + ts.isIdentifier(skipParens(callee.expression)) && + (skipParens(callee.expression) as ts.Identifier).text === 'Promise' && + lib(skipParens(callee.expression)) + ); + } + + return false; } /** @@ -11456,7 +11521,7 @@ function projectValueCalledThroughParameter(node: Invocation, body: ts.Node, ctx // A primitive (`const two = 2`) or a well-known builtin (an array, a map, a date) has only the methods of the // standard library, which run no project code; anything typed by project declarations, `any` or `unknown` may. - if (builtinValue(checker.getTypeAtLocation(argument))) return false; + if (builtinValue(argument, checker)) return false; return descendants(body).some( (child) => @@ -11742,17 +11807,38 @@ function unrelatedFirstParameter(fn: ts.SignatureDeclaration, checker: ts.TypeCh /** Whether a function's body reads `arguments` (also in an arrow function inside it, which shares it). */ function readsArguments(fn: ts.Node): boolean { const body = (fn as ts.FunctionLikeDeclaration).body; + let found = false; + // Arrows share the function's `arguments`; a nested function, method, accessor or constructor has its own. + const visit = (node: ts.Node): void => { + if (found) return; - return ( - body !== undefined && - descendants(body).some( - (node) => - ts.isIdentifier(node) && - node.text === 'arguments' && - !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) && - !(ts.isPropertyAssignment(node.parent) && node.parent.name === node), + if ( + ts.isFunctionDeclaration(node) || + ts.isFunctionExpression(node) || + ts.isMethodDeclaration(node) || + ts.isGetAccessorDeclaration(node) || + ts.isSetAccessorDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isClassStaticBlockDeclaration(node) ) - ); + return; + + if ( + ts.isIdentifier(node) && + node.text === 'arguments' && + !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) && + !(ts.isPropertyAssignment(node.parent) && node.parent.name === node) + ) { + found = true; + + return; + } + ts.forEachChild(node, visit); + }; + + if (body !== undefined) visit(body); + + return found; } interface ContextReach { @@ -13537,12 +13623,23 @@ function nondeterminismFor(node: ts.Node, fakeTimers: boolean): string[] { return values; } -function callsHelperWithAssertion(body: ts.Node | undefined, source: ts.SourceFile): boolean { +function callsHelperWithAssertion( + body: ts.Node | undefined, + source: ts.SourceFile, + checker?: ts.TypeChecker, +): boolean { if (!body) return false; const names = new Set(); + // A call in a subtest that is skipped or a todo gates nothing. + const notGating = checker ? skippedSubtestBodies(body, checker).skipped : []; for (const node of descendants(body)) - if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) names.add(node.expression.text); + if ( + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + !notGating.some((fn) => contains(fn, node)) + ) + names.add(node.expression.text); let found = false; const visit = (node: ts.Node) => { if (ts.isFunctionDeclaration(node) && node.name && names.has(node.name.text)) { diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index cc080ec1..8e22191a 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -797,4 +797,140 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); expect(byName(tests, 'project object').suspicions).toContain('opaque_call'); }); + + it('runs nothing under a skipped subtest at any depth, whatever todo marks sit around it', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/nesting.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + test('skip inside todo', async (t) => { + await t.test('todo', { todo: true }, async (s) => { + await s.test('skip', { skip: true }, () => value(1)); + }); + }); + test('todo inside skip', async (t) => { + await t.test('skip', { skip: true }, async (s) => { + await s.test('todo', { todo: true }, () => value(1)); + }); + }); + test('todo alone', async (t) => { + await t.test('todo', { todo: true }, () => value(1)); + }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['skip inside todo', 'todo inside skip']) + expect(byName(tests, name).calledSymbols, name).toEqual([]); + // A todo subtest alone runs: its call is recorded. + expect(byName(tests, 'todo alone').calledSymbols).toEqual(['src/svc.ts#value']); + }); + + it('credits no assertion of a helper called in a todo subtest, nor in a skipped one inside it', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/helpers.test.ts': ` + import { test } from 'node:test'; + import assert from 'node:assert/strict'; + import { value } from '../src/svc'; + function check() { assert.equal(value(1), 2); } + test('helper in todo', async (t) => { + await t.test('child', { todo: true }, () => check()); + }); + test('helper in skip inside todo', async (t) => { + await t.test('todo', { todo: true }, async (s) => { + await s.test('skip', { skip: true }, () => check()); + }); + }); + test('helper in the test', () => { check(); }); + `, + }); + const { tests } = inventory(root, node.recognition); + + for (const name of ['helper in todo', 'helper in skip inside todo']) { + expect(byName(tests, name).suspicions, name).toContain('no_assertion'); + expect( + byName(tests, name).targetCalls.some((call) => call.asserted), + name, + ).toBe(false); + } + expect(byName(tests, 'helper in the test').suspicions).not.toContain('no_assertion'); + }); + + it('counts no side-effect writer in a teardown hook', () => { + const root = tempProject({ + 'src/app.ts': 'export class App { on(handler: () => void) { handler(); } }\n', + 'test/teardown.test.ts': ` + import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + import { App } from '../src/app'; + let set = false; + let torn = false; + describe('suite', () => { + beforeEach(() => { new App().on(() => { set = true; }); }); + afterEach(() => { new App().on(() => { torn = true; }); }); + it('setup writes', () => { expect(set).toBe(true); }); + it('teardown writes', () => { expect(torn).toBe(false); }); + }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + expect(byName(tests, 'setup writes').suspicions).toContain('opaque_call'); + expect(byName(tests, 'teardown writes').suspicions).not.toContain('opaque_call'); + }); + + it('reads arguments only within the function and the arrows that share it', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/arguments.test.ts': ` + import { test } from 'node:test'; + import { value } from '../src/svc'; + function nested(t) { + function inner() { return arguments.length; } + void inner; + t.assert.equal(value(1), 2); + } + function viaArrow(t) { + const read = () => arguments[0]; + void read; + t.assert.equal(1, 1); + } + test('nested function', nested); + test('arrow', viaArrow); + `, + }); + const { tests } = inventory(root, node.recognition); + + expect(byName(tests, 'nested function').suspicions).not.toContain('opaque_call'); + expect(byName(tests, 'nested function').targetCalls.some((call) => call.asserted)).toBe(true); + // The arrow shares the function's arguments: what it reads is the context, not followed. + expect(byName(tests, 'arrow').suspicions).toContain('opaque_call'); + }); + + it('keeps a project subclass declared with a builtin type opaque', () => { + const root = tempProject({ + 'src/lazy.ts': ` + export class Lazy extends Promise { + override then(onFulfilled?: (value: T) => A | PromiseLike, onRejected?: (reason: unknown) => B | PromiseLike) { + return super.then(onFulfilled, onRejected); + } + } + export const lazy: Promise = new Lazy((resolve) => resolve(1)); + export const plain = Promise.resolve(1); + `, + 'test/lazy.test.ts': ` + import { expect, test } from 'vitest'; + import { lazy, plain } from '../src/lazy'; + async function settle(p) { expect(await p.then((n) => n)).toBe(1); } + test('project subclass', async () => { await settle(lazy); }); + test('Promise.resolve', async () => { await settle(plain); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + expect(byName(tests, 'project subclass').suspicions).toContain('opaque_call'); + expect(byName(tests, 'project subclass').suspicions).not.toContain('target_not_called'); + expect(byName(tests, 'Promise.resolve').suspicions).not.toContain('opaque_call'); + }); }); From 1ab164f15036f8ea912a9eb557843dc2df0c94cb Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 15:41:36 +0900 Subject: [PATCH 12/14] fix(test-inventory): read only evaluated assertion values, keep builtin objects opaque, see every invocation, and count teardown after an earlier test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The side-effect scan collects only what an assertion evaluates (runsWithin): expect(() => hit) does not read hit. - The helper-parameter rule exempts only primitives (number, string, boolean, bigint, symbol and their literals): any object, builtin or not, may have its methods replaced, so arrays, maps, dates and promises stay opaque_call. - It counts every invocation of the parameter: calls, new, tagged templates, and the parameter handed to a call or new other than an assertion (Reflect.construct(Ctor, []), Reflect.apply(fn, …)). - A teardown hook writer counts when it runs before the analysed test: afterEach of an enclosing suite once an earlier test of it ran, afterAll of an earlier sibling suite with tests; never for the first test. --- packages/test-inventory/src/index.ts | 121 ++++++------------ .../test/context-precision.test.ts | 95 +++++++++++++- 2 files changed, 128 insertions(+), 88 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index f8fe442d..6be8c998 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -112,6 +112,8 @@ interface RunnerApi { /** The export a default import of the runner's module stands for (`import test from 'node:test'`), if any. */ defaultExport: string | undefined; beforeEach: Set; + /** Hooks that run after each test (`afterEach`). */ + afterEach: Set; /** Hooks that run before a test: `beforeEach` and `beforeAll`. */ setup: Set; hooks: Set; @@ -151,6 +153,7 @@ function runnerApi(recognition: TestRunnerRecognition): RunnerApi { optionsSetUnlessFalse: recognition.optionsSetUnlessFalse === true, defaultExport: recognition.defaultExport, beforeEach: new Set(hooks.beforeEach), + afterEach: new Set(hooks.afterEach), setup: new Set([...hooks.beforeEach, ...hooks.beforeAll]), hooks: new Set([...hooks.beforeEach, ...hooks.beforeAll, ...hooks.afterEach, ...hooks.afterAll]), runtimeExports: new Set(recognition.runtimeExports), @@ -11246,10 +11249,11 @@ function assertionReadsProjectSideEffect( if (assertions.length === 0) return false; const read = new Set(); + // Only what an assertion evaluates: `expect(() => hit)` never reads `hit`. for (const assertion of assertions) for (const value of comparedValues(assertion)) for (const node of [value, ...descendants(value)]) - if (ts.isIdentifier(node)) { + if (ts.isIdentifier(node) && runsWithin(node, value, assertion)) { const symbol = checker.getSymbolAtLocation(node); if (symbol) read.add(symbol); @@ -11359,10 +11363,7 @@ function assertionReadsProjectSideEffect( const hook = runnerExport(skipParens(call.expression))?.name ?? ''; - // A teardown hook (`afterEach`, `afterAll`) runs after the assertion: nothing it writes can decide it. - if (runner.hooks.has(hook) && !runner.setup.has(hook)) return false; - - if (runner.setup.has(hook)) { + if (runner.hooks.has(hook)) { let suite: ts.Node | undefined = call.parent; while ( @@ -11371,8 +11372,22 @@ function assertionReadsProjectSideEffect( !(isFunction(suite) && ts.isCallExpression(suite.parent) && describeRegistration(suite.parent)) ) suite = suite.parent; + const scope = suite ?? source; + const encloses = ts.isSourceFile(scope) || contains(scope, body); + + if (runner.setup.has(hook)) return encloses; + const start = body.parent.getStart(); + // A test registered in the scope before the analysed one. + const earlierTest = descendants(scope).some( + (each) => + ts.isCallExpression(each) && each.getEnd() < start && testRegistration(each) !== undefined, + ); - return suite === undefined || ts.isSourceFile(suite) || contains(suite, body); + // A teardown hook runs after a test: before the analysed one only when another test of its scope ran first + // (`afterEach` of an enclosing suite), or when its suite ended before (an earlier sibling suite's `afterAll`). + return runner.afterEach.has(hook) + ? encloses && earlierTest + : !encloses && scope.getEnd() < start && earlierTest; } } @@ -11401,15 +11416,11 @@ function assertionReadsProjectSideEffect( return false; } -/** Builtin constructors whose instances made there have only the standard library's methods. */ -const BUILTIN_CONSTRUCTORS = new Set(['Array', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Date', 'RegExp']); - /** - * Whether a value handed to a helper is shown to have only the standard library's methods: a primitive (number, - * string, boolean, bigint, symbol or a literal of one), which no class can extend; or a `const` initialised, there and - * directly, with an array of literals, a regular expression, a builtin constructor (`new Map()`, `new Date(0)`) - * or `Promise.resolve(…)`. A value only declared with a builtin type (`const lazy: Promise = new Lazy()`, a - * project subclass) is not, nor `any`, `unknown` or anything else. + * Whether a value handed to a helper is a primitive (number, string, boolean, bigint, symbol or a literal of one), + * whose methods are the standard library's: no class extends it, and no property of it can be replaced. An object, + * builtin or not, may have its methods replaced or be an instance of a project subclass; `any` and `unknown` may be + * anything. */ function builtinValue(argument: ts.Expression, checker: ts.TypeChecker): boolean { const primitive = @@ -11422,67 +11433,7 @@ function builtinValue(argument: ts.Expression, checker: ts.TypeChecker): boolean const primitiveType = (each: ts.Type): boolean => each.isUnion() ? each.types.every(primitiveType) : (each.flags & primitive) !== 0; - if (!(type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && primitiveType(type)) return true; - const value = skipValueWrappers(argument); - - if (!ts.isIdentifier(value)) return false; - let symbol = checker.getSymbolAtLocation(value); - - try { - if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol); - } catch { - return false; - } - const declaration = symbol?.valueDeclaration; - - if ( - !declaration || - !ts.isVariableDeclaration(declaration) || - (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) === 0 || - !declaration.initializer - ) - return false; - const initializer = skipValueWrappers(declaration.initializer); - const lib = (identifier: ts.Expression) => - ts.isIdentifier(identifier) && - (checker.getSymbolAtLocation(identifier)?.declarations ?? []).every( - (each) => each.getSourceFile().isDeclarationFile, - ); - - // An array of literals (whose elements are no project functions either), a regular expression. - if ( - (ts.isArrayLiteralExpression(initializer) && - initializer.elements.every( - (element) => - ts.isStringLiteralLike(element) || - ts.isNumericLiteral(element) || - element.kind === ts.SyntaxKind.TrueKeyword || - element.kind === ts.SyntaxKind.FalseKeyword || - element.kind === ts.SyntaxKind.NullKeyword, - )) || - ts.isRegularExpressionLiteral(initializer) - ) - return true; - - if (ts.isNewExpression(initializer)) { - const callee = skipParens(initializer.expression); - - return ts.isIdentifier(callee) && BUILTIN_CONSTRUCTORS.has(callee.text) && lib(callee); - } - - if (ts.isCallExpression(initializer)) { - const callee = skipParens(initializer.expression); - - return ( - ts.isPropertyAccessExpression(callee) && - callee.name.text === 'resolve' && - ts.isIdentifier(skipParens(callee.expression)) && - (skipParens(callee.expression) as ts.Identifier).text === 'Promise' && - lib(skipParens(callee.expression)) - ); - } - - return false; + return !(type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) && primitiveType(type); } /** @@ -11519,16 +11470,24 @@ function projectValueCalledThroughParameter(node: Invocation, body: ts.Node, ctx if (!parameter || !ts.isIdentifier(parameter.name) || !projectValue(argument)) return false; const symbol = checker.getSymbolAtLocation(parameter.name); - // A primitive (`const two = 2`) or a well-known builtin (an array, a map, a date) has only the methods of the - // standard library, which run no project code; anything typed by project declarations, `any` or `unknown` may. + // A primitive (`const two = 2`) has only the methods of the standard library, which run no project code. if (builtinValue(argument, checker)) return false; + const isParameter = (expression: ts.Expression | undefined) => { + const root = expression && rootIdentifierNode(skipValueWrappers(expression)); + + return root !== undefined && checker.getSymbolAtLocation(root) === symbol; + }; + // Any invocation of it or a member: a call, `new`, a tagged template; or it handed to a call or `new`, which may + // invoke it (`Reflect.construct(Ctor, [])`, `Reflect.apply(fn, null, [])`). return descendants(body).some( (child) => - ts.isCallExpression(child) && - rootIdentifierNode(skipParens(child.expression)) !== undefined && - checker.getSymbolAtLocation(rootIdentifierNode(skipParens(child.expression)) as ts.Identifier) === - symbol, + ((ts.isCallExpression(child) || ts.isNewExpression(child)) && + (isParameter(child.expression) || + // An assertion only reads what it is given. + (!(ts.isCallExpression(child) && (isExpectCall(child) || isAssertCall(child))) && + (child.arguments ?? []).some((each) => isParameter(each))))) || + (ts.isTaggedTemplateExpression(child) && isParameter(child.tag)), ); }); } diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index 8e22191a..aba672bc 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -793,9 +793,11 @@ describe('test contexts and ordinary helpers', () => { }); const { tests } = inventory(root, vitest.recognition); - for (const name of ['primitive', 'array', 'date']) - expect(byName(tests, name).suspicions, name).not.toContain('opaque_call'); - expect(byName(tests, 'project object').suspicions).toContain('opaque_call'); + expect(byName(tests, 'primitive').suspicions).not.toContain('opaque_call'); + + // An object, builtin or not, may have its methods replaced (`names.at = …`): opaque. + for (const name of ['array', 'date', 'project object']) + expect(byName(tests, name).suspicions, name).toContain('opaque_call'); }); it('runs nothing under a skipped subtest at any depth, whatever todo marks sit around it', () => { @@ -858,7 +860,7 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, 'helper in the test').suspicions).not.toContain('no_assertion'); }); - it('counts no side-effect writer in a teardown hook', () => { + it('counts a teardown hook writer only once an earlier test of its scope ran', () => { const root = tempProject({ 'src/app.ts': 'export class App { on(handler: () => void) { handler(); } }\n', 'test/teardown.test.ts': ` @@ -869,15 +871,18 @@ describe('test contexts and ordinary helpers', () => { describe('suite', () => { beforeEach(() => { new App().on(() => { set = true; }); }); afterEach(() => { new App().on(() => { torn = true; }); }); + it('teardown first', () => { expect(torn).toBe(false); }); it('setup writes', () => { expect(set).toBe(true); }); - it('teardown writes', () => { expect(torn).toBe(false); }); + it('teardown after a test', () => { expect(torn).toBe(true); }); }); `, }); const { tests } = inventory(root, vitest.recognition); expect(byName(tests, 'setup writes').suspicions).toContain('opaque_call'); - expect(byName(tests, 'teardown writes').suspicions).not.toContain('opaque_call'); + // `afterEach` runs before a test only after an earlier one. + expect(byName(tests, 'teardown first').suspicions).not.toContain('opaque_call'); + expect(byName(tests, 'teardown after a test').suspicions).toContain('opaque_call'); }); it('reads arguments only within the function and the arrows that share it', () => { @@ -931,6 +936,82 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, 'project subclass').suspicions).toContain('opaque_call'); expect(byName(tests, 'project subclass').suspicions).not.toContain('target_not_called'); - expect(byName(tests, 'Promise.resolve').suspicions).not.toContain('opaque_call'); + // A promise is an object too, whose `then` may be replaced: opaque. + expect(byName(tests, 'Promise.resolve').suspicions).toContain('opaque_call'); + }); + + it('reads no variable an assertion only names inside a function it never runs', () => { + const root = tempProject({ + 'src/app.ts': 'export class App { on(handler: () => void) { handler(); } }\n', + 'test/closure.test.ts': ` + import { expect, it } from 'vitest'; + import { App } from '../src/app'; + it('closure only', () => { + let hit = 0; + new App().on(() => { hit++; }); + expect(() => hit).toBeDefined(); + }); + it('read', () => { + let hit = 0; + new App().on(() => { hit++; }); + expect(hit).toBe(1); + }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + expect(byName(tests, 'closure only').suspicions).not.toContain('opaque_call'); + expect(byName(tests, 'closure only').targetCalls.some((call) => call.asserted)).toBe(false); + // Read: linked to the project call that runs the closure, or inconclusive. + expect( + byName(tests, 'read').suspicions.includes('opaque_call') || + byName(tests, 'read').targetCalls.some((call) => call.asserted), + ).toBe(true); + }); + + it('takes any invocation of a project value through a helper parameter for a possible project call', () => { + const root = tempProject({ + 'src/svc.ts': `${SERVICE}export class Thing { value = 1; }\nexport const tag = (parts: TemplateStringsArray) => parts.join('');\n`, + 'test/invoke.test.ts': ` + import { expect, test } from 'vitest'; + import { Thing, tag } from '../src/svc'; + function make(Ctor) { expect(new Ctor().value).toBe(1); } + function viaReflect(Ctor) { expect(Reflect.construct(Ctor, []).value).toBe(1); } + function tagged(fn) { expect(fn\`x\`).toBe('x'); } + function asserted(value) { expect(value).toBeDefined(); } + test('new', () => { make(Thing); }); + test('Reflect.construct', () => { viaReflect(Thing); }); + test('tagged template', () => { tagged(tag); }); + test('only asserted on', () => { asserted(Thing); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + for (const name of ['new', 'Reflect.construct', 'tagged template']) + expect(byName(tests, name).suspicions, name).toContain('opaque_call'); + // Handed only to an assertion, which reads it: no project call. + expect(byName(tests, 'only asserted on').suspicions).not.toContain('opaque_call'); + }); + + it("counts an earlier sibling suite's afterAll writer, and not its own suite's", () => { + const root = tempProject({ + 'src/app.ts': 'export class App { on(handler: () => void) { handler(); } }\n', + 'test/after-all.test.ts': ` + import { afterAll, describe, expect, it } from 'vitest'; + import { App } from '../src/app'; + let done = false; + describe('first', () => { + afterAll(() => { new App().on(() => { done = true; }); }); + it('inside', () => { expect(done).toBe(false); }); + }); + describe('second', () => { + it('after the first suite', () => { expect(done).toBe(true); }); + }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + expect(byName(tests, 'inside').suspicions).not.toContain('opaque_call'); + expect(byName(tests, 'after the first suite').suspicions).toContain('opaque_call'); }); }); From 4c9176deff2d93196e7148ce96e2d02368b990f7 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 15:58:40 +0900 Subject: [PATCH 13/14] fix(test-inventory): take a running assertion of a function for a call of it - A helper parameter handed to an assertion that runs it (expect(f).toThrow(), assert.throws(f) and the other running assertions, resolved through nodeAssertCall) is an invocation of a project value, so such helpers are opaque_call again, as on main. An assertion that only compares the value still is not one. - In a test body, a project function handed directly to a running assertion (assert.throws(explode), expect(explode).toThrow()) counts as a call of it, asserted, as () => explode() does. expect(explode).toBeDefined() and other matchers that only compare it do not. --- packages/test-inventory/src/index.ts | 29 +++++++++- .../test/context-precision.test.ts | 57 +++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index 6be8c998..36cae024 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -3822,6 +3822,30 @@ function callInfo(node: Invocation, ctx: Ctx): CallInfo { ...passed.map((symbol) => ({ symbol, ownArgs: false, assertedInside: false, flowsToResult: true })), ], }; + // `assert.throws(explode)`, `expect(explode).toThrow()`: an assertion that runs the project function it is given + // calls it and checks how it behaves, as `() => explode()` would. Other matchers only compare it as a value. + const run = + ts.isCallExpression(node) && (isExpectCall(node) || isAssertCall(node)) && runsCallback(node) + ? node.arguments.flatMap((argument) => { + const value = skipParens(argument); + + if (!ts.isIdentifier(value) && !ts.isPropertyAccessExpression(value)) return []; + + if (ctx.checker.getTypeAtLocation(value).getCallSignatures().length === 0) return []; + const id = projectSymbolId(aliasTarget(value, ctx.checker), ctx.checker, ctx.projectSet, ctx.root); + + return id && !known.has(id) ? [id] : []; + }) + : []; + + if (run.length > 0) + info = { + ...info, + targets: [ + ...info.targets, + ...run.map((symbol) => ({ symbol, ownArgs: false, assertedInside: true, flowsToResult: true })), + ], + }; ctx.callInfo.set(node, info); return info; @@ -11484,8 +11508,9 @@ function projectValueCalledThroughParameter(node: Invocation, body: ts.Node, ctx (child) => ((ts.isCallExpression(child) || ts.isNewExpression(child)) && (isParameter(child.expression) || - // An assertion only reads what it is given. - (!(ts.isCallExpression(child) && (isExpectCall(child) || isAssertCall(child))) && + // An assertion only reads what it is given, unless it runs it (`expect(f).toThrow()`, `assert.throws(f)`). + ((!(ts.isCallExpression(child) && (isExpectCall(child) || isAssertCall(child))) || + (ts.isCallExpression(child) && runsCallback(child))) && (child.arguments ?? []).some((each) => isParameter(each))))) || (ts.isTaggedTemplateExpression(child) && isParameter(child.tag)), ); diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index aba672bc..9aac8a73 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -1014,4 +1014,61 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, 'inside').suspicions).not.toContain('opaque_call'); expect(byName(tests, 'after the first suite').suspicions).toContain('opaque_call'); }); + + for (const [runner, recognition, header, runs, compares] of [ + [ + 'Vitest', + vitest.recognition, + "import { expect, test } from 'vitest';", + (f: string) => `expect(${f}).toThrow();`, + (f: string) => `expect(${f}).toBeDefined();`, + ], + [ + 'Jest', + jest.recognition, + '', + (f: string) => `expect(${f}).toThrow();`, + (f: string) => `expect(${f}).toBeDefined();`, + ], + [ + 'node:test', + node.recognition, + "import { test } from 'node:test';\nimport assert from 'node:assert/strict';", + (f: string) => `assert.throws(${f});`, + (f: string) => `assert.ok(${f});`, + ], + ] as const) + it(`takes an assertion that runs a project function for a call of it (${runner})`, () => { + const root = tempProject({ + 'src/explode.ts': "export function explode(): never { throw new Error('boom'); }\n", + 'test/runs.test.ts': ` + ${header} + import { explode } from '../src/explode'; + function check(f) { ${runs('f')} } + function look(f) { ${compares('f')} } + test('helper runs it', () => { check(explode); }); + test('inline helper runs it', () => { + const g = (f) => { ${runs('f')} }; + g(explode); + }); + test('runs it directly', () => { ${runs('explode')} }); + test('helper compares it', () => { look(explode); }); + test('compares it directly', () => { ${compares('explode')} }); + `, + }); + const { tests } = inventory(root, recognition); + + for (const name of ['helper runs it', 'inline helper runs it']) + expect(byName(tests, name).suspicions, `${runner} ${name}`).toContain('opaque_call'); + // Run directly by the assertion: a call of it, asserted. + const direct = byName(tests, 'runs it directly'); + expect(direct.calledSymbols, runner).toEqual(['src/explode.ts#explode']); + expect( + direct.targetCalls.some((call) => call.asserted), + runner, + ).toBe(true); + // Only compared as a value: no call. + expect(byName(tests, 'compares it directly').calledSymbols, runner).toEqual([]); + expect(byName(tests, 'helper compares it').suspicions, runner).not.toContain('opaque_call'); + }); }); From a50380bb77c8c5809c1298dc02312be4dd005e71 Mon Sep 17 00:00:00 2001 From: tanahiro2010 Date: Fri, 27 Nov 2026 16:00:31 +0900 Subject: [PATCH 14/14] fix(test-inventory): check project values called through helper parameters whatever else the helper calls, and skip dead writers - A helper that also calls resolved project code (value(1)) no longer hides a project object it calls through its parameter (o.price(1)): the parameter rule applies regardless of other targets. - A side-effect writer inside a named function that is neither exported nor referenced anywhere in the file never runs and is not counted; any other function may run and still counts. --- packages/test-inventory/src/index.ts | 36 +++++++++++++++++-- .../test/context-precision.test.ts | 36 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/packages/test-inventory/src/index.ts b/packages/test-inventory/src/index.ts index 36cae024..9e3588aa 100644 --- a/packages/test-inventory/src/index.ts +++ b/packages/test-inventory/src/index.ts @@ -3747,8 +3747,7 @@ function callInfo(node: Invocation, ctx: Ctx): CallInfo { info = { ...info, opaque: true, assertionsUnknown: true }; // `checkObj(svc)` with the helper calling `o.price(1)`: calls of project code made through its parameter, which // the helper's own analysis cannot resolve. What they reach is unknown, not absent. - else if (info.targets.length === 0 && projectValueCalledThroughParameter(node, helper, ctx)) - info = { ...info, opaque: true }; + else if (projectValueCalledThroughParameter(node, helper, ctx)) info = { ...info, opaque: true }; // What a local component renders is what it returns: calls whose result does not reach that are not shown. if (mount) @@ -11374,12 +11373,45 @@ function assertionReadsProjectSideEffect( */ // Subtests of the test known not to run (`t.test(name, { skip: true }, fn)`) write nothing for it. const notRun = skippedSubtestBodies(body, checker).definite; + /** + * Whether a function is shown never to run: declared by name (a function declaration, or a `const` holding a + * function) that is neither exported nor referenced anywhere in the file. Anything else may run. + */ + const unreferencedFunction = (fn: ts.Node): boolean => { + const name = nameOf(fn); + const declaration = ts.isFunctionDeclaration(fn) ? fn : fn.parent; + + if (!name || !ts.isIdentifier(name)) return false; + const holder = ts.isVariableDeclaration(declaration) ? declaration.parent.parent : declaration; + + if ( + ts.canHaveModifiers(holder) && + (ts.getModifiers(holder) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) + return false; + const symbol = checker.getSymbolAtLocation(name); + + return ( + symbol !== undefined && + !descendants(source).some( + (node) => + ts.isIdentifier(node) && + node !== name && + (ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node + ? checker.getShorthandAssignmentValueSymbol(node.parent) + : checker.getSymbolAtLocation(node)) === symbol, + ) + ); + }; const runsForTest = (node: ts.Node): boolean => { if (notRun.some((fn) => contains(fn, node))) return false; for (let current: ts.Node = node.parent; current && !ts.isSourceFile(current); current = current.parent) { if (current === body.parent) return true; + // A named function nothing references or exports never runs: what it writes cannot decide the assertion. + if (isFunctionLike(current) && unreferencedFunction(current)) return false; + if (!isFunction(current) || !ts.isCallExpression(current.parent)) continue; const call = current.parent; diff --git a/packages/test-inventory/test/context-precision.test.ts b/packages/test-inventory/test/context-precision.test.ts index 9aac8a73..99b6901b 100644 --- a/packages/test-inventory/test/context-precision.test.ts +++ b/packages/test-inventory/test/context-precision.test.ts @@ -1071,4 +1071,40 @@ describe('test contexts and ordinary helpers', () => { expect(byName(tests, 'compares it directly').calledSymbols, runner).toEqual([]); expect(byName(tests, 'helper compares it').suspicions, runner).not.toContain('opaque_call'); }); + + it('takes a project object called through a helper parameter for unknown even when the helper calls project code', () => { + const root = tempProject({ + 'src/svc.ts': SERVICE, + 'test/mixed.test.ts': ` + import { expect, test } from 'vitest'; + import { svc, value } from '../src/svc'; + function check(o) { value(1); expect(o.price(1)).toBe(2); } + test('both', () => { check(svc); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + expect(byName(tests, 'both').suspicions).toContain('opaque_call'); + }); + + it('counts no side-effect writer inside a function nothing references', () => { + const root = tempProject({ + 'src/app.ts': 'export class App { on(handler: () => void) { handler(); } }\n', + 'test/dead.test.ts': ` + import { expect, it } from 'vitest'; + import { App } from '../src/app'; + let dead = false; + let live = false; + function neverCalled() { new App().on(() => { dead = true; }); } + function setUp() { new App().on(() => { live = true; }); } + setUp(); + it('dead writer', () => { expect(dead).toBe(false); }); + it('live writer', () => { expect(live).toBe(true); }); + `, + }); + const { tests } = inventory(root, vitest.recognition); + + expect(byName(tests, 'dead writer').suspicions).not.toContain('opaque_call'); + expect(byName(tests, 'live writer').suspicions).toContain('opaque_call'); + }); });