Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(test): detect Vitest module reset aliases by binding

MagicLizicf8ea5b8f8ef
diff --git a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
index 0adbe8c4a2..beed5f5660 100644
--- a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
+++ b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
@@ -1,6 +1,6 @@
import { readFileSync } from 'node:fs';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
CODEX_DEFAULT_LIMIT_BUCKET,
@@ -344,10 +344,8 @@ describe('module subscription install (behavior)', () => {
},
};
try {
- const { resetModules } = await import('vitest').then((m) => ({
- resetModules: m.vi.resetModules,
- }));
- resetModules();
+ // reset-modules: observe first installation of the module-level usage listener in this initialization test.
+ vi.resetModules();
const [{ useAccountUsage: freshUseAccountUsage }, { renderToString }, React] =
await Promise.all([
import('@/hooks/useAccountUsage'),
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.md
index 793584569d..c883809cda 100644
--- a/docs/dev-rules/desktop-unit-test-performance.md
+++ b/docs/dev-rules/desktop-unit-test-performance.md
@@ -75,6 +75,9 @@ Linux 及 package script 的启动方式不变。回归测试通过真实 runner
仓库的 CLI 回归覆盖首次登记、收紧、手改抬高、删除与读取失败,4 项 scanner 自测
约 2.7 秒。侧栏清角标回归并入既有通知测试,通过真实生产 effects 与点击回调验证
打开、聚焦、重复点击及监听清理,23 项约 3.1 秒;生产行为与 375 文件基线均未改。
+模块重载检测同样按 Vitest 绑定追踪解构、赋值与 namespace 别名,并检查 hook 及其
+本地准备/清理函数;同名参数和非 Vitest 对象不会误判。既有账号用量初始化回归
+改为带明确理由的单次直接重载,原 34 项通过(约 0.7 秒),不新增逐用例重载。
### 2026-10-16 实验与落地
diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjs
index 6f32b4787d..cc48585380 100644
--- a/scripts/__tests__/check-test-hygiene.test.mjs
+++ b/scripts/__tests__/check-test-hygiene.test.mjs
@@ -28,6 +28,26 @@ test("hygiene scans both test and spec files", () => {
test("scanTestSource counts only unjustified hits for each rule", () => {
const cases = [
["per-test module reset", "beforeEach(() => { vi.resetModules(); });", { resetModules: 1 }],
+ ["destructured reset keeps the Vitest binding", "const { resetModules } = vi; beforeEach(() => resetModules());", { resetModules: 1 }],
+ ["named Vitest import aliases keep reset identity", "import { vi as tools } from 'vitest'; const reload = tools.resetModules; const reset = reload; reset();", { resetModules: 1 }],
+ ["Vitest namespace aliases keep reset identity", "import * as api from 'vitest'; const namespace = api; const { vitest: tools } = namespace; tools.resetModules();", { resetModules: 1 }],
+ ["assigned mock and reset aliases keep reset identity", "import { vitest } from 'vitest'; let tools, reload; tools = vitest; reload = tools.resetModules; reload();", { resetModules: 1 }],
+ ["destructuring assignments keep reset identity", "let reload; ({ resetModules: reload } = vi); reload();", { resetModules: 1 }],
+ ["a reason cannot exempt a directly registered reset alias", "const { resetModules: reload } = vi;\n// reset-modules: cached state\nbeforeEach(reload);", { resetModules: 1 }],
+ ["a reason cannot exempt aliases in a cleanup helper", "import { afterEach as cleanup, vi } from 'vitest'; const tools = vi; const { resetModules: reload } = tools; function finish() {\n// reset-modules: cached state\nreload();\n} cleanup(finish);", { resetModules: 1 }],
+ ["namespace hooks cannot exempt a reset alias", "import * as api from 'vitest'; const reload = api.vi.resetModules; api.beforeEach(() => {\n// reset-modules: cached state\nreload();\n});", { resetModules: 1 }],
+ ["assigned cleanup helpers cannot exempt a reset alias", "const reload = vi.resetModules; let finish; finish = () => {\n// reset-modules: cached state\nreload();\n}; afterEach(finish);", { resetModules: 1 }],
+ ["a justified explicit alias restart stays exempt", "const { resetModules: reload } = vitest; it('restart', () => {\n// reset-modules: persisted state after restart\nreload();\n});", { resetModules: 0 }],
+ ["an unused reset alias does not reload modules", "const { resetModules: reload } = vi; beforeEach(() => {});", { resetModules: 0 }],
+ ["a parameter shadows a real Vitest import", "import { vi } from 'vitest'; function example(vi) { vi.resetModules(); }", { resetModules: 0 }],
+ ["a method parameter shadows a real Vitest import", "import { vi } from 'vitest'; const fixture = { run(vi) { vi.resetModules(); } };", { resetModules: 0 }],
+ ["a local function shadows a reset alias", "const { resetModules: reload } = vi; function example() { function reload() {} beforeEach(() => reload()); }", { resetModules: 0 }],
+ ["destructured parameters shadow a reset alias", "const { resetModules: reload } = vi; function example({ reload }) { beforeEach(() => reload()); }", { resetModules: 0 }],
+ ["a local object shadows the global Vitest name", "const vi = { resetModules() {} }; const { resetModules: reload } = vi; reload(); vi.resetModules();", { resetModules: 0 }],
+ ["computed runtime keys are not static reset aliases", "const resetModules = 'other'; vi[resetModules]();", { resetModules: 0 }],
+ ["non-Vitest imports cannot acquire reset identity", "import { vi } from './fixture'; import * as tools from './other'; vi.resetModules(); tools.vi.resetModules();", { resetModules: 0 }],
+ ["type-only imports cannot acquire reset identity", "import type { vi } from 'vitest'; vi.resetModules();", { resetModules: 0 }],
+ ["local hooks do not turn a justified restart into a per-test reload", "function beforeEach(callback) {} function restart() {\n// reset-modules: verify persisted state\nvi.resetModules();\n} beforeEach(restart);", { resetModules: 0 }],
[
"a reason cannot exempt a per-test hook",
"beforeEach(() => {\n// reset-modules: cached state\nvi.resetModules();\n});",
diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs
index d12455c74f..ed0b5a9999 100644
--- a/scripts/check-test-hygiene.mjs
+++ b/scripts/check-test-hygiene.mjs
@@ -101,13 +101,19 @@ function hasJustification(lines, line, marker) {
/** A per-test hook cannot turn repeated module loading into an exemption. */
function countModuleResets(code, lines) {
- const resets = [...code.matchAll(/\bvi\.resetModules\s*\(/g)];
- if (resets.length === 0) return 0;
+ if (!/\bresetModules\b/.test(code)) return 0;
const ts = typescript ??= requireDesktop('typescript');
const source = parseTestSource(ts, code);
const nodeScopes = new WeakMap();
- const hooks = [];
- const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);
+ const calls = [];
+ const writes = new Map();
+ const isFunction = node => ts.isFunctionLike(node) && Boolean(node.body);
+ function declare(name, declaration, scope) {
+ if (ts.isIdentifier(name)) scope.bindings.set(name.text, declaration);
+ else for (const element of name.elements) {
+ if (ts.isBindingElement(element)) declare(element.name, element, scope);
+ }
+ }
function collect(node, scope) {
if (ts.isFunctionDeclaration(node) && node.name) scope.bindings.set(node.name.text, node);
if (ts.isSourceFile(node) || ts.isBlock(node) || isFunction(node)) {
@@ -115,25 +121,117 @@ function countModuleResets(code, lines) {
}
nodeScopes.set(node, scope);
if (isFunction(node)) {
- if (node.name) scope.bindings.set(node.name.text, node);
- for (const parameter of node.parameters) {
- if (ts.isIdentifier(parameter.name)) scope.bindings.set(parameter.name.text, null);
- }
- }
- if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
- scope.bindings.set(node.name.text, node.initializer && isFunction(node.initializer) ? node.initializer : null);
+ if (node.name && (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node))) scope.bindings.set(node.name.text, node);
+ for (const parameter of node.parameters) declare(parameter.name, parameter, scope);
}
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)
- && /^(?:beforeEach|afterEach)$/.test(node.expression.text)) hooks.push(...node.arguments);
+ if (ts.isVariableDeclaration(node)) declare(node.name, node, scope);
+ if (ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node) && node.name) scope.bindings.set(node.name.text, node);
+ if (ts.isCallExpression(node)) calls.push(node);
ts.forEachChild(node, child => collect(child, scope));
}
collect(source, null);
- function resolveHelper(identifier) {
+ function binding(identifier) {
for (let scope = nodeScopes.get(identifier); scope; scope = scope.parent) {
if (scope.bindings.has(identifier.text)) return scope.bindings.get(identifier.text);
}
return null;
}
+ function unwrap(node) {
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node)) node = node.expression;
+ return node;
+ }
+ function propertyName(node) {
+ return node && (ts.isIdentifier(node) || ts.isStringLiteral(node)) ? node.text : null;
+ }
+ function recordWrite(target, expression, property = null) {
+ target = unwrap(target);
+ if (ts.isIdentifier(target)) {
+ const bound = binding(target);
+ if (bound) {
+ if (!writes.has(bound)) writes.set(bound, []);
+ writes.get(bound).push({ expression, property });
+ }
+ } else if (ts.isObjectLiteralExpression(target)) {
+ for (const member of target.properties) {
+ if (ts.isShorthandPropertyAssignment(member)) recordWrite(member.name, expression, member.name.text);
+ else if (ts.isPropertyAssignment(member)) recordWrite(member.initializer, expression, propertyName(member.name));
+ }
+ }
+ }
+ function collectWrites(node) {
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) recordWrite(node.left, node.right);
+ ts.forEachChild(node, collectWrites);
+ }
+ collectWrites(source);
+ function importedFromVitest(bound) {
+ let declaration = bound;
+ while (declaration && !ts.isImportDeclaration(declaration)) declaration = declaration.parent;
+ return declaration && !declaration.importClause?.isTypeOnly && !bound.isTypeOnly
+ && ts.isStringLiteral(declaration.moduleSpecifier) && declaration.moduleSpecifier.text === 'vitest';
+ }
+ function propertyMatches(expression, property, kind, seen) {
+ if (kind === 'mock' && /^(?:vi|vitest)$/.test(property)) return matches(expression, 'namespace', seen);
+ if (kind === 'reset' && property === 'resetModules') return matches(expression, 'mock', seen);
+ if (kind === 'hook' && /^(?:beforeEach|afterEach)$/.test(property)) return matches(expression, 'namespace', seen);
+ return false;
+ }
+ function boundMatches(bound, kind, seen) {
+ if (!bound || seen.has(bound)) return false;
+ seen = new Set(seen).add(bound);
+ if (importedFromVitest(bound)) {
+ if (kind === 'namespace') return ts.isNamespaceImport(bound);
+ if (ts.isImportSpecifier(bound)) {
+ const name = bound.propertyName?.text ?? bound.name.text;
+ return kind === 'mock' && /^(?:vi|vitest)$/.test(name)
+ || kind === 'hook' && /^(?:beforeEach|afterEach)$/.test(name);
+ }
+ }
+ if (ts.isBindingElement(bound) && ts.isObjectBindingPattern(bound.parent) && !bound.dotDotDotToken) {
+ const property = propertyName(bound.propertyName ?? bound.name);
+ const owner = bound.parent.parent;
+ if (kind === 'mock' && /^(?:vi|vitest)$/.test(property) && boundMatches(owner, 'namespace', seen)
+ || kind === 'reset' && property === 'resetModules' && boundMatches(owner, 'mock', seen)
+ || kind === 'hook' && /^(?:beforeEach|afterEach)$/.test(property) && boundMatches(owner, 'namespace', seen)) return true;
+ }
+ if (ts.isVariableDeclaration(bound) && bound.initializer && matches(bound.initializer, kind, seen)) return true;
+ // Follow only local static aliases, not arbitrary returned objects or callbacks.
+ return (writes.get(bound) ?? []).some(write => write.property
+ ? propertyMatches(write.expression, write.property, kind, seen) : matches(write.expression, kind, seen));
+ }
+ function matches(node, kind, seen = new Set()) {
+ node = unwrap(node);
+ if (ts.isIdentifier(node)) {
+ const bound = binding(node);
+ if (bound) return boundMatches(bound, kind, seen);
+ return kind === 'mock' && /^(?:vi|vitest)$/.test(node.text)
+ || kind === 'hook' && /^(?:beforeEach|afterEach)$/.test(node.text);
+ }
+ if (ts.isPropertyAccessExpression(node)) return propertyMatches(node.expression, node.name.text, kind, seen);
+ if (ts.isElementAccessExpression(node) && ts.isStringLiteral(node.argumentExpression)) return propertyMatches(node.expression, node.argumentExpression.text, kind, seen);
+ return false;
+ }
+ function resolveHelper(node, seen = new Set()) {
+ node = unwrap(node);
+ if (isFunction(node)) return node;
+ if (!ts.isIdentifier(node)) return null;
+ const bound = binding(node);
+ if (!bound || seen.has(bound)) return null;
+ seen = new Set(seen).add(bound);
+ if (isFunction(bound)) return bound;
+ if (ts.isVariableDeclaration(bound) && bound.initializer) {
+ const helper = resolveHelper(bound.initializer, seen);
+ if (helper) return helper;
+ }
+ for (const write of writes.get(bound) ?? []) {
+ if (!write.property) {
+ const helper = resolveHelper(write.expression, seen);
+ if (helper) return helper;
+ }
+ }
+ return null;
+ }
+ const resets = new Map(calls.filter(call => matches(call.expression, 'reset')).map(call => [call.getStart(source), call]));
+ const hooks = calls.filter(call => matches(call.expression, 'hook')).flatMap(call => [...call.arguments]);
const perTest = new Set();
const visitedFunctions = new Set();
function visitFunction(node) {
@@ -147,21 +245,19 @@ function countModuleResets(code, lines) {
if (isFunction(node)) return;
if (ts.isCallExpression(node)) {
const expression = node.expression;
- if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression)
- && expression.expression.text === 'vi' && expression.name.text === 'resetModules') {
- perTest.add(expression.getStart(source));
- }
- if (ts.isIdentifier(expression)) visitFunction(resolveHelper(expression));
- else if (isFunction(expression)) visitFunction(expression);
+ if (matches(expression, 'reset')) perTest.add(node.getStart(source));
+ visitFunction(resolveHelper(expression));
}
ts.forEachChild(node, visit);
}
for (const hook of hooks) {
- if (isFunction(hook)) visitFunction(hook);
- else if (ts.isIdentifier(hook)) visitFunction(resolveHelper(hook));
+ if (matches(hook, 'reset')) {
+ resets.set(hook.getStart(source), hook);
+ perTest.add(hook.getStart(source));
+ } else visitFunction(resolveHelper(hook));
}
- return resets.filter(match => perTest.has(match.index)
- || !hasJustification(lines, lineOf(code, match.index), 'reset-modules')).length;
+ return [...resets.keys()].filter(index => perTest.has(index)
+ || !hasJustification(lines, lineOf(code, index), 'reset-modules')).length;
}
/** Mask string contents while preserving line numbers and call-site punctuation. */
@@ -737,7 +833,7 @@ export function scanTestSource(source, { isGuard = false } = {}) {
const code = stripComments(source);
const lines = source.split(/\r?\n/);
const executableCode = maskStrings(code);
- const resetModules = countModuleResets(executableCode, lines);
+ const resetModules = countModuleResets(code, lines);
const realWaits = countRealWaits(executableCode, lines, code);
let sourceReads = 0;
if (!isGuard && /\breadFileSync\b|\breadFile\s*\(|\?raw/.test(code)) {