Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(test): track aliased Vitest timer mode changes
MagicLizia93bfd75ee17
diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex a5f9f50c0c..dfe5024c26 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -96,6 +96,9 @@ CI 仍须重新通过。其模块重载与真实等待规则仍适用,新普通脚本测试读取应用源码会失败。扫描器自测4 项约 2.4 秒,全仓 AST 扫描约 20 秒(比最初的文本扫描成本更高)。通过 `--update`只删除 zero-wiring 内嵌 fixture 造成的 8 次误报,基线从 375 收紧为 374 个文件。+计时器模式也沿真实 Vitest 绑定追踪属性、解构、namespace 和静态赋值别名,并在+实际调用或 hook 执行处生效;恢复真实时钟后,后续测试的长等待不会沿用假时钟豁免。+未调用的别名、局部同名对象及 fixture 字符串不改变模式,基线未放宽。导入设置恢复真实组件挂载回归,验证首次自动扫描与重入时先显示缓存、再更新结果,2 项单文件命令约 2.2 秒。slash 空结果、目录队列插入与语音输入保护并入既有 ChatInput文件,经过真实编辑器/hook 验证键盘消费、目录 chip、语音全生命周期只读与顶层弹层diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjsindex 619567c23b..da6c03d3aa 100644--- a/scripts/__tests__/check-test-hygiene.test.mjs+++ b/scripts/__tests__/check-test-hygiene.test.mjs@@ -103,6 +103,21 @@ test("scanTestSource counts only unjustified hits for each rule", () => {["a registered timer helper applies as a hook", "function enableFake() { vi.useFakeTimers(); } beforeEach(enableFake); it('fake', () => setTimeout(done, 200));", { realWaits: 0 }],["transitive timer helper calls preserve their order", "function fake() { vi.useFakeTimers(); } const setup = () => { fake(); vi.useRealTimers(); }; it('real', () => { setup(); setTimeout(done, 200); });", { realWaits: 1 }],["inline Promise executors inherit test hooks", "beforeEach(() => vi.useFakeTimers()); it('fake', async () => { await new Promise(resolve => setTimeout(resolve, 200)); });", { realWaits: 0 }],+ ["a real-timer alias restores the clock between tests", "vi.useFakeTimers(); const restore = vi.useRealTimers; afterEach(() => restore()); it('first', () => setTimeout(done, 100)); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["destructured timer aliases retain imported Vitest identity", "import { vi as tools, afterEach as cleanup } from 'vitest'; tools.useFakeTimers(); const { useRealTimers: restore } = tools; cleanup(restore); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["assigned namespace timer aliases retain the restoring hook", "import * as api from 'vitest'; api.vi.useFakeTimers(); let restore; ({ useRealTimers: restore } = api.vi); api.afterEach(() => restore()); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["a later static assignment replaces an initial timer alias", "vi.useFakeTimers(); let restore = vi.useFakeTimers; restore = vi.useRealTimers; afterEach(restore); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["a later static assignment replaces an initial cleanup helper", "vi.useFakeTimers(); let cleanup = () => vi.useFakeTimers(); cleanup = () => vi.useRealTimers(); afterEach(cleanup); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["a local replacement clears the old fake-timer identity", "let enable = vi.useFakeTimers; enable = () => {}; beforeEach(enable); it('real', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["a later assignment replaces a declared cleanup helper", "vi.useFakeTimers(); function cleanup() { vi.useFakeTimers(); } cleanup = () => vi.useRealTimers(); afterEach(cleanup); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["a later assignment replaces a destructured timer alias", "vi.useFakeTimers(); let { useFakeTimers: restore } = vi; restore = vi.useRealTimers; afterEach(restore); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["timer aliases follow calls through cleanup helpers", "vi.useFakeTimers(); const restore = vi.useRealTimers; const cleanup = () => restore(); const finish = cleanup; afterEach(finish); it('first', () => {}); it('later', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["unused timer aliases do not change the clock", "vi.useFakeTimers(); const restore = vi.useRealTimers; it('fake', () => setTimeout(done, 100));", { realWaits: 0 }],+ ["fake-timer aliases apply only at actual calls", "const enable = vi.useFakeTimers; beforeEach(enable); it('fake', () => setTimeout(done, 100));", { realWaits: 0 }],+ ["timer aliases preserve switching order", "const fake = vi.useFakeTimers; const real = vi.useRealTimers; it('real', () => { fake(); real(); setTimeout(done, 100); });", { realWaits: 1 }],+ ["a parameter shadows a real timer alias", "vi.useFakeTimers(); const restore = vi.useRealTimers; it('fake', (restore) => { restore(); setTimeout(done, 100); });", { realWaits: 0 }],+ ["lookalike local Vitest objects cannot exempt real waits", "const vi = { useFakeTimers() {} }; vi.useFakeTimers(); it('real', () => setTimeout(done, 100));", { realWaits: 1 }],+ ["timer calls inside fixture strings do not change the clock", "const fixture = 'vi.useFakeTimers()'; it('real', () => setTimeout(done, 100));", { realWaits: 1 }],["fake-timer file","vi.useFakeTimers();\nsetTimeout(tick, 5_000);",diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjsindex 6536501c3a..f39da17441 100644--- a/scripts/check-test-hygiene.mjs+++ b/scripts/check-test-hygiene.mjs@@ -440,48 +440,127 @@ function timerScopes(code, timerEvents) {const callbackKinds = new WeakMap();const registeredHelpers = [];const calls = [];- const isFunction = node => ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);- function rootName(expression) {- if (ts.isIdentifier(expression)) return expression.text;- if (ts.isPropertyAccessExpression(expression) || ts.isCallExpression(expression)) return rootName(expression.expression);- if (ts.isTaggedTemplateExpression(expression)) return rootName(expression.tag);- return '';+ const functions = [];+ const writes = new Map();+ const isFunction = node => ts.isFunctionLike(node) && Boolean(node.body);+ const isTimer = name => /^(?:useFakeTimers|useRealTimers)$/.test(name);+ const isFramework = name => /^(?:describe|it|test|beforeEach|beforeAll|afterEach|afterAll)$/.test(name);+ 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 visit(node, lexicalScope) {if (ts.isFunctionDeclaration(node) && node.name) lexicalScope.bindings.set(node.name.text, node);if (ts.isSourceFile(node) || ts.isBlock(node) || isFunction(node)) lexicalScope = { parent: lexicalScope, bindings: new Map() };nodeScopes.set(node, lexicalScope);if (isFunction(node)) {- scopes.push({ kind: callbackKinds.get(node) ?? 'helper', start: node.getStart(source), end: node.end });- for (const parameter of node.parameters) {- if (ts.isIdentifier(parameter.name)) lexicalScope.bindings.set(parameter.name.text, null);+ functions.push(node);+ if (node.name && (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node))) lexicalScope.bindings.set(node.name.text, node);+ for (const parameter of node.parameters) declare(parameter.name, parameter, lexicalScope);+ }+ if (ts.isVariableDeclaration(node)) declare(node.name, node, lexicalScope);+ if (ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportClause(node) && node.name) lexicalScope.bindings.set(node.name.text, node);+ if (ts.isCallExpression(node)) calls.push(node);+ ts.forEachChild(node, child => visit(child, lexicalScope));+ }+ visit(source, null);+ 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;+ }+ const propertyName = node => 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) writes.set(bound, [...(writes.get(bound) ?? []), { 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));}}- if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) lexicalScope.bindings.set(node.name.text, node.initializer && isFunction(node.initializer) ? node.initializer : null);- if (ts.isCallExpression(node)) {- calls.push(node);- const kind = rootName(node.expression);- if (/^(?:describe|it|test|beforeEach|beforeAll|afterEach|afterAll)$/.test(kind)) {- for (const argument of node.arguments) {- if (isFunction(argument)) callbackKinds.set(argument, kind);- else if (ts.isIdentifier(argument)) {- const scope = { kind, start: argument.getStart(source), end: argument.end };- scopes.push(scope);- registeredHelpers.push({ argument, scope });- }- }+ }+ 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 member(owner, name) {+ if (owner === 'namespace') return /^(?:vi|vitest)$/.test(name) ? 'mock' : isFramework(name) ? name : '';+ return owner === 'mock' && isTimer(name) ? name : '';+ }+ function boundIdentity(bound, seen) {+ if (!bound || seen.has(bound)) return '';+ seen = new Set(seen).add(bound);+ let declaration = bound;+ while (declaration && !ts.isImportDeclaration(declaration)) declaration = declaration.parent;+ if (declaration && !declaration.importClause?.isTypeOnly && !bound.isTypeOnly+ && ts.isStringLiteral(declaration.moduleSpecifier) && declaration.moduleSpecifier.text === 'vitest') {+ if (ts.isNamespaceImport(bound)) return 'namespace';+ if (ts.isImportSpecifier(bound)) return member('namespace', bound.propertyName?.text ?? bound.name.text);+ }+ const write = writes.get(bound)?.at(-1);+ if (write) return write.property ? member(identity(write.expression, seen), write.property) : identity(write.expression, seen);+ if (ts.isBindingElement(bound) && ts.isObjectBindingPattern(bound.parent) && !bound.dotDotDotToken) {+ return member(boundIdentity(bound.parent.parent, seen), propertyName(bound.propertyName ?? bound.name));+ }+ if (ts.isVariableDeclaration(bound) && bound.initializer) return identity(bound.initializer, seen);+ return '';+ }+ // Resolve static Vitest bindings, not lookalike fixture objects or names in+ // strings. Definitions alone never switch the clock; only reachable calls do.+ function identity(expression, seen = new Set()) {+ expression = unwrap(expression);+ if (ts.isIdentifier(expression)) {+ const bound = binding(expression);+ return bound ? boundIdentity(bound, seen)+ : /^(?:vi|vitest)$/.test(expression.text) ? 'mock' : isFramework(expression.text) ? expression.text : '';+ }+ if (ts.isPropertyAccessExpression(expression)) return member(identity(expression.expression, seen), expression.name.text);+ if (ts.isElementAccessExpression(expression) && ts.isStringLiteral(expression.argumentExpression)) return member(identity(expression.expression, seen), expression.argumentExpression.text);+ return '';+ }+ function frameworkName(expression) {+ const name = identity(expression);+ if (isFramework(name)) return name;+ if (ts.isPropertyAccessExpression(expression) || ts.isCallExpression(expression)) return frameworkName(expression.expression);+ if (ts.isTaggedTemplateExpression(expression)) return frameworkName(expression.tag);+ return '';+ }+ for (const call of calls) {+ const kind = frameworkName(call.expression);+ if (!isFramework(kind)) continue;+ for (const argument of call.arguments) {+ if (isFunction(argument)) callbackKinds.set(argument, kind);+ else if (ts.isIdentifier(argument) || isTimer(identity(argument))) {+ const scope = { kind, start: argument.getStart(source), end: argument.end };+ scopes.push(scope);+ registeredHelpers.push({ argument, scope });}}- ts.forEachChild(node, child => visit(child, lexicalScope));}- visit(source, null);+ for (const node of functions) scopes.push({ kind: callbackKinds.get(node) ?? 'helper', start: node.getStart(source), end: node.end });scopes.sort((a, b) => (a.end - a.start) - (b.end - b.start));- function helper(expression) {+ function helper(expression, seen = new Set()) {+ expression = unwrap(expression);if (isFunction(expression)) return expression;if (!ts.isIdentifier(expression)) return null;- for (let scope = nodeScopes.get(expression); scope; scope = scope.parent) {- if (scope.bindings.has(expression.text)) return scope.bindings.get(expression.text);- }+ const bound = binding(expression);+ if (!bound || seen.has(bound)) return null;+ seen = new Set(seen).add(bound);+ const write = writes.get(bound)?.at(-1);+ if (write) return write.property ? null : helper(write.expression, seen);+ if (isFunction(bound)) return bound;+ if (ts.isVariableDeclaration(bound) && bound.initializer) return helper(bound.initializer, seen);return null;}function helperEvents(fn, seen = new Set()) {@@ -492,8 +571,8 @@ function timerScopes(code, timerEvents) {if (isFunction(node)) return;if (ts.isCallExpression(node)) {const expression = node.expression;- if (ts.isPropertyAccessExpression(expression) && expression.expression.getText(source) === 'vi'- && /^(?:useFakeTimers|useRealTimers)$/.test(expression.name.text)) events.push(expression.name.text);+ const name = identity(expression);+ if (isTimer(name)) events.push(name);else events.push(...helperEvents(helper(expression), seen));}ts.forEachChild(node, inspect);@@ -509,9 +588,13 @@ function timerScopes(code, timerEvents) {for (const call of calls) {const index = call.getStart(source);if (scopes.find(scope => scope.start <= index && index < scope.end)?.kind === 'helper') continue;- addEvents(helperEvents(helper(call.expression)), index);+ const name = identity(call.expression);+ addEvents(isTimer(name) ? [name] : helperEvents(helper(call.expression)), index);+ }+ for (const { argument, scope } of registeredHelpers) {+ const name = identity(argument);+ addEvents(isTimer(name) ? [name] : helperEvents(helper(argument)), scope.start);}- for (const { argument, scope } of registeredHelpers) addEvents(helperEvents(helper(argument)), scope.start);timerEvents.sort((a, b) => a.index - b.index);return scopes;}@@ -562,8 +645,8 @@ function timerStateAt(index, timerEvents, scopes) {}function countRealWaits(code, lines, sourceCode = code) {- const timerEvents = [...code.matchAll(/\bvi\.(useFakeTimers|useRealTimers)\s*\(/g)];- const scopes = timerEvents.length > 0 ? timerScopes(code, timerEvents) : [];+ const timerEvents = [];+ const scopes = /\buse(?:Fake|Real)Timers\b/.test(sourceCode) ? timerScopes(sourceCode, timerEvents) : [];let count = 0;const waits = staticWaitCalls(sourceCode).sort((a, b) => a.index - b.index);for (const wait of waits) {