diff --git a/docs/api/advanced/test-case.md b/docs/api/advanced/test-case.md index f962dd3423f3..efd76cf633e8 100644 --- a/docs/api/advanced/test-case.md +++ b/docs/api/advanced/test-case.md @@ -389,3 +389,5 @@ function logs(): ReadonlyArray ``` Console logs recorded during the test execution. + +Each log printed during an attempt has the `retryIndex` and `repeatIndex` of that attempt, so it can be matched with an entry of [`attempts()`](#attempts). diff --git a/packages/browser/src/client/tester/logger.ts b/packages/browser/src/client/tester/logger.ts index 30961bea362a..e7817fb5ddb8 100644 --- a/packages/browser/src/client/tester/logger.ts +++ b/packages/browser/src/client/tester/logger.ts @@ -122,7 +122,9 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool } const unknownTestId = '__vitest__unknown_test__' // @ts-expect-error untyped global - const taskId = globalThis.__vitest_worker__?.current?.id ?? unknownTestId + const state = globalThis.__vitest_worker__ + const task = state?.current + const taskId = task?.id ?? unknownTestId const origin = getConfig().printConsoleTrace && !disableStack ? new Error('STACK_TRACE').stack?.split('\n').slice(1).join('\n') @@ -136,5 +138,6 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool taskId, type, size: content.length, + ...(task?.type === 'test' && state.getCurrentAttempt?.(task)), }) } diff --git a/packages/vitest/src/runtime/console.ts b/packages/vitest/src/runtime/console.ts index 2ea7839e4173..ab791ab66959 100644 --- a/packages/vitest/src/runtime/console.ts +++ b/packages/vitest/src/runtime/console.ts @@ -37,7 +37,16 @@ function getTaskIdByStack(root: string) { export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const stdoutBuffer = new Map() const stderrBuffer = new Map() - const timers = new Map void }>() + const timers = new Map< + string, + { + taskId: string + attempt?: { retryIndex: number; repeatIndex: number } + stdoutTime: number + stderrTime: number + cancel?: () => void + } + >() const { queueMicrotask } = getSafeTimers() @@ -55,45 +64,54 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const state = () => defaultState || getWorkerState() + function getLogTarget() { + const s = state() + const task = getCurrentTask() ?? s.current + const taskId = task?.id || getTaskIdByStack(s.config.root) + const attempt = task?.type === 'test' ? s.getCurrentAttempt?.(task) : undefined + const key = attempt ? `${taskId}:${attempt.repeatIndex}:${attempt.retryIndex}` : taskId + return { key, taskId, attempt } + } + // group sync console.log calls with micro task - function schedule(taskId: string) { - const timer = timers.get(taskId)! + function schedule(key: string) { + const timer = timers.get(key)! const { stdoutTime, stderrTime } = timer timer.cancel?.() timer.cancel = queueCancelableMicrotask(() => { if (stderrTime < stdoutTime) { - sendStderr(taskId) - sendStdout(taskId) + sendStderr(key) + sendStdout(key) } else { - sendStdout(taskId) - sendStderr(taskId) + sendStdout(key) + sendStderr(key) } }) } - function sendStdout(taskId: string) { - sendBuffer('stdout', taskId) + function sendStdout(key: string) { + sendBuffer('stdout', key) } - function sendStderr(taskId: string) { - sendBuffer('stderr', taskId) + function sendStderr(key: string) { + sendBuffer('stderr', key) } - function sendBuffer(type: 'stdout' | 'stderr', taskId: string) { + function sendBuffer(type: 'stdout' | 'stderr', key: string) { const buffers = type === 'stdout' ? stdoutBuffer : stderrBuffer - const buffer = buffers.get(taskId) + const buffer = buffers.get(key) if (!buffer) { return } if (state().config.printConsoleTrace) { buffer.forEach(([buffer, origin]) => { - sendLog(type, taskId, String(buffer), buffer.length, origin) + sendLog(type, key, String(buffer), buffer.length, origin) }) } else { const content = buffer.map((i) => String(i[0])).join('') - sendLog(type, taskId, content, buffer.length) + sendLog(type, key, content, buffer.length) } - const timer = timers.get(taskId)! - buffers.delete(taskId) + const timer = timers.get(key)! + buffers.delete(key) if (type === 'stderr') { timer.stderrTime = 0 } else { @@ -103,21 +121,22 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { function sendLog( type: 'stderr' | 'stdout', - taskId: string, + key: string, content: string, size: number, origin?: string, ) { - const timer = timers.get(taskId)! + const timer = timers.get(key)! const time = type === 'stderr' ? timer.stderrTime : timer.stdoutTime state() .rpc.onUserConsoleLog({ type, content: content || '', - taskId, + taskId: timer.taskId, time: time || RealDate.now(), size, origin, + ...timer.attempt, }) .catch((error) => { // the log is already sent, the worker only closed before the reporter answered @@ -129,22 +148,23 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const stdout = new Writable({ write(data, encoding, callback) { - const s = state() - const id = (getCurrentTask() ?? s.current)?.id || getTaskIdByStack(s.config.root) - let timer = timers.get(id) + const { key, taskId, attempt } = getLogTarget() + let timer = timers.get(key) if (timer) { timer.stdoutTime = timer.stdoutTime || RealDate.now() } else { timer = { + taskId, + attempt, stdoutTime: RealDate.now(), stderrTime: 0, } - timers.set(id, timer) + timers.set(key, timer) } - let buffer = stdoutBuffer.get(id) + let buffer = stdoutBuffer.get(key) if (!buffer) { buffer = [] - stdoutBuffer.set(id, buffer) + stdoutBuffer.set(key, buffer) } if (state().config.printConsoleTrace) { const limit = Error.stackTraceLimit @@ -156,28 +176,29 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { } else { buffer.push([data, undefined]) } - schedule(id) + schedule(key) callback() }, }) const stderr = new Writable({ write(data, encoding, callback) { - const s = state() - const id = (getCurrentTask() ?? s.current)?.id || getTaskIdByStack(s.config.root) - let timer = timers.get(id) + const { key, taskId, attempt } = getLogTarget() + let timer = timers.get(key) if (timer) { timer.stderrTime = timer.stderrTime || RealDate.now() } else { timer = { + taskId, + attempt, stderrTime: RealDate.now(), stdoutTime: 0, } - timers.set(id, timer) + timers.set(key, timer) } - let buffer = stderrBuffer.get(id) + let buffer = stderrBuffer.get(key) if (!buffer) { buffer = [] - stderrBuffer.set(id, buffer) + stderrBuffer.set(key, buffer) } if (state().config.printConsoleTrace) { const limit = Error.stackTraceLimit @@ -195,7 +216,7 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { } else { buffer.push([data, undefined]) } - schedule(id) + schedule(key) callback() }, }) diff --git a/packages/vitest/src/runtime/runners/test.ts b/packages/vitest/src/runtime/runners/test.ts index 5f8e5fa7d3bf..4bd6c4e4e937 100644 --- a/packages/vitest/src/runtime/runners/test.ts +++ b/packages/vitest/src/runtime/runners/test.ts @@ -28,6 +28,7 @@ import { createBench, kFinalize } from '../benchmark' import { rpc } from '../rpc' import { getTestFakes, hasOwnRandomFakes, setTestFakesRestore } from '../runner/fakes' import { getFn, getHooks } from '../runner/map' +import { getCurrentAttempt } from '../runner/run' import { createTaskCollector, getCurrentSuite } from '../runner/suite' import { getCurrentTest } from '../runner/test-state' import { createChainable } from '../runner/utils/chain' @@ -59,6 +60,7 @@ export class TestRunner implements VitestTestRunner { const environment = this.workerState.environment this.viteEnvironment = environment.viteEnvironment || environment.name this.viteModuleRunner = config.experimental.viteModuleRunner + this.workerState.getCurrentAttempt = getCurrentAttempt // vm pools downgrade worker-scoped fixtures to file scope, so the hook has // nothing to tear down there; registering it anyway would keep the // listener, an in-context closure, alive for the lifetime of the worker diff --git a/packages/vitest/src/types/general.ts b/packages/vitest/src/types/general.ts index 0c7ac8be8c9f..459c19925644 100644 --- a/packages/vitest/src/types/general.ts +++ b/packages/vitest/src/types/general.ts @@ -20,6 +20,10 @@ export interface UserConsoleLog { taskId?: string time: number size: number + /** The zero-based retry index of the attempt that printed the log. */ + retryIndex?: number + /** The zero-based repeat index of the attempt that printed the log. */ + repeatIndex?: number } interface ModuleGraphModules { diff --git a/packages/vitest/src/types/worker.ts b/packages/vitest/src/types/worker.ts index 43e4f2fe4ef1..983ffce15b92 100644 --- a/packages/vitest/src/types/worker.ts +++ b/packages/vitest/src/types/worker.ts @@ -3,7 +3,7 @@ import type { EvaluatedModules } from 'vite/module-runner' import type { SerializedConfig } from '../runtime/config' import type { GetterTracker } from '../runtime/getter-tracker' import type { CurrentContextStore } from '../runtime/runner/test-state' -import type { CancelReason, FileSpecification, Task } from '../runtime/runner/types' +import type { CancelReason, FileSpecification, Task, Test } from '../runtime/runner/types' import type { Traces } from '../utils/traces' import type { Environment } from './environment' import type { RunnerRPC, RuntimeRPC } from './rpc' @@ -83,6 +83,12 @@ export interface WorkerGlobalState { resolvingModules: Set moduleExecutionInfo: Map currentContext?: CurrentContextStore + /** + * @internal + * vm pools load the runner modules twice, so the console reads the attempt through the worker state, + * which both copies share, to see the same attempts as the runner + */ + getCurrentAttempt?: (test: Test) => { retryIndex: number; repeatIndex: number } | undefined /** * Module ids and file paths loaded by the current test file. Only set when * `experimental.recordDependencies` is enabled. diff --git a/test/browser/specs/runner.test.ts b/test/browser/specs/runner.test.ts index 5246ff9468e4..0bf7e53019e0 100644 --- a/test/browser/specs/runner.test.ts +++ b/test/browser/specs/runner.test.ts @@ -4,7 +4,7 @@ import { readdirSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { beforeAll, describe, expect, onTestFailed, test } from 'vitest' import { buildTestTree } from '../../test-utils' -import { instances, provider, runBrowserTests } from './utils' +import { instances, provider, runBrowserTests, runInlineBrowserTests } from './utils' function noop() {} @@ -282,6 +282,55 @@ test('disableConsoleIntercept', async () => { expect(result.stdout).not.toContain('hello from console.log') }) +test('console logs have the attempt that printed them', async () => { + const logs: string[] = [] + const { stderr, testTree } = await runInlineBrowserTests( + { + 'basic.test.ts': ` + import { beforeAll, expect, test } from 'vitest' + + beforeAll(() => { + console.log('beforeAll') + }) + + let runs = 0 + test('repeats', { repeats: 1, retry: 1 }, () => { + console.log('test') + expect(++runs % 2).toBe(0) + }) + `, + }, + { + browser: { instances: [instances[0]] }, + reporters: [ + { + onUserConsoleLog(log) { + logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.content.trim()}`) + }, + }, + ], + }, + ) + + expect(stderr).toBe('') + expect(testTree()).toMatchInlineSnapshot(` + { + "basic.test.ts": { + "repeats": "passed", + }, + } + `) + expect(logs).toMatchInlineSnapshot(` + [ + "undefined/undefined beforeAll", + "0/0 test", + "0/1 test", + "1/0 test", + "1/1 test", + ] + `) +}) + test(`stack trace points to correct file in every browser when failed`, async () => { expect.assertions(30) const { stderr } = await runBrowserTests({ diff --git a/test/e2e/test/console.test.ts b/test/e2e/test/console.test.ts index 8bfa7e550fde..771e4ec3d127 100644 --- a/test/e2e/test/console.test.ts +++ b/test/e2e/test/console.test.ts @@ -194,3 +194,60 @@ test('console log sent while the worker closes is not reported as an error', asy } `) }) + +test.for(['threads', 'vmThreads'])( + 'console logs have the attempt that printed them in %s', + async (pool) => { + const logs: string[] = [] + const { stderr, testTree } = await runInlineTests( + { + 'basic.test.ts': ts` + import { beforeAll, expect, test } from 'vitest' + + beforeAll(() => { + console.log('beforeAll') + }) + + let runs = 0 + test('repeats', { repeats: 1, retry: 1 }, () => { + console.log('stdout') + console.error('stderr') + expect(++runs % 2).toBe(0) + }) + `, + }, + { + pool, + reporters: [ + { + onUserConsoleLog(log) { + logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.content.trim()}`) + }, + }, + ], + }, + ) + + expect(stderr).toBe('') + expect(testTree()).toMatchInlineSnapshot(` + { + "basic.test.ts": { + "repeats": "passed", + }, + } + `) + expect(logs).toMatchInlineSnapshot(` + [ + "undefined/undefined beforeAll", + "0/0 stdout", + "0/0 stderr", + "0/1 stdout", + "0/1 stderr", + "1/0 stdout", + "1/0 stderr", + "1/1 stdout", + "1/1 stderr", + ] + `) + }, +)