Skip to content
Merged
8 changes: 8 additions & 0 deletions docs/api/advanced/test-case.md
Original file line number Diff line number Diff line change
Expand Up @@ -414,5 +414,13 @@ interface UserConsoleLog {
*/
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
}
```
5 changes: 4 additions & 1 deletion packages/browser/src/client/tester/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -136,5 +138,6 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool
taskId,
type,
size: content.length,
...(task?.type === 'test' && state.getCurrentAttempt?.(task)),
})
}
89 changes: 55 additions & 34 deletions packages/vitest/src/runtime/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,16 @@ function getTaskIdByStack(root: string) {
export function createCustomConsole(defaultState?: WorkerGlobalState): Console {
const stdoutBuffer = new Map<string, any[]>()
const stderrBuffer = new Map<string, any[]>()
const timers = new Map<string, { stdoutTime: number; stderrTime: number; cancel?: () => void }>()
const timers = new Map<
string,
{
taskId: string
attempt?: { retryIndex: number; repeatIndex: number }
stdoutTime: number
stderrTime: number
cancel?: () => void
}
>()

const { queueMicrotask } = getSafeTimers()

Expand All @@ -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 {
Expand All @@ -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 || '<empty line>',
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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -195,7 +216,7 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console {
} else {
buffer.push([data, undefined])
}
schedule(id)
schedule(key)
callback()
},
})
Expand Down
2 changes: 2 additions & 0 deletions packages/vitest/src/runtime/runners/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions packages/vitest/src/types/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ export interface UserConsoleLog {
*/
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 {
Expand Down
8 changes: 7 additions & 1 deletion packages/vitest/src/types/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -83,6 +83,12 @@ export interface WorkerGlobalState {
resolvingModules: Set<string>
moduleExecutionInfo: Map<string, any>
currentContext?: CurrentContextStore
/**
* 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
* @internal
*/
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.
Expand Down
51 changes: 50 additions & 1 deletion test/browser/specs/runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}

Expand Down Expand Up @@ -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({
Expand Down
Loading
Loading