Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/utils/src/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface SafeTimers {
clearTimeout: typeof clearTimeout
setImmediate: typeof setImmediate
clearImmediate: typeof clearImmediate
queueMicrotask: typeof queueMicrotask
}

export function getSafeTimers(): SafeTimers {
Expand All @@ -18,6 +19,7 @@ export function getSafeTimers(): SafeTimers {
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask,
} = (globalThis as any)[SAFE_TIMERS_SYMBOL] || globalThis

const { nextTick: safeNextTick } = (globalThis as any)[SAFE_TIMERS_SYMBOL]
Expand All @@ -31,6 +33,7 @@ export function getSafeTimers(): SafeTimers {
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask,
}
}

Expand All @@ -42,6 +45,7 @@ export function setSafeTimers(): void {
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask,
} = globalThis

const { nextTick: safeNextTick } = globalThis.process || {
Expand All @@ -56,6 +60,7 @@ export function setSafeTimers(): void {
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask,
};

(globalThis as any)[SAFE_TIMERS_SYMBOL] = timers
Expand Down
24 changes: 17 additions & 7 deletions packages/vitest/src/runtime/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,31 @@ export function createCustomConsole(defaultState?: WorkerGlobalState) {
const stderrBuffer = new Map<string, any[]>()
const timers = new Map<
string,
{ stdoutTime: number; stderrTime: number; timer: any }
{ stdoutTime: number; stderrTime: number; cancel?: () => void }
>()

const { setTimeout, clearTimeout } = getSafeTimers()
const { queueMicrotask } = getSafeTimers()

function queueCancelableMicrotask(callback: () => void) {
let canceled = false
queueMicrotask(() => {
if (!canceled) {
callback()
}
})
return () => {
canceled = true
}
}

const state = () => defaultState || getWorkerState()

// group sync console.log calls with macro task
// group sync console.log calls with micro task
function schedule(taskId: string) {
const timer = timers.get(taskId)!
const { stdoutTime, stderrTime } = timer
clearTimeout(timer.timer)
timer.timer = setTimeout(() => {
timer.cancel?.()
timer.cancel = queueCancelableMicrotask(() => {
if (stderrTime < stdoutTime) {
sendStderr(taskId)
sendStdout(taskId)
Expand Down Expand Up @@ -128,7 +140,6 @@ export function createCustomConsole(defaultState?: WorkerGlobalState) {
timer = {
stdoutTime: RealDate.now(),
stderrTime: RealDate.now(),
timer: 0,
}
timers.set(id, timer)
}
Expand Down Expand Up @@ -168,7 +179,6 @@ export function createCustomConsole(defaultState?: WorkerGlobalState) {
timer = {
stderrTime: RealDate.now(),
stdoutTime: RealDate.now(),
timer: 0,
}
timers.set(id, timer)
}
Expand Down
37 changes: 37 additions & 0 deletions test/config/fixtures/console-batch/basic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, test } from 'vitest'

beforeAll(() => {
console.log('[beforeAll 1]')
})
beforeAll(() => {
console.log('[beforeAll 2]')
})

afterAll(() => {
console.log('[afterAll 1]')
})
afterAll(() => {
console.log('[afterAll 2]')
})

beforeEach(() => {
console.log('[beforeEach 1]')
})
beforeEach(() => {
console.log('[beforeEach 2]')
})

afterEach(() => {
console.log('[afterEach 1]')
})
afterEach(() => {
console.log('[afterEach 2]')
})

test('test', async () => {
console.log('[test 1]')
console.log('[test 2]')
await Promise.resolve()
console.log('[test 3]')
console.log('[test 4]')
})
Copy link
Contributor Author

@hi-ogawa hi-ogawa Jan 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What this PR changes is only to split these 4 logs into 2-2.

before

stdout | basic.test.ts > test
[test 1]
[test 2]
[test 3]
[test 4]

after

stdout | basic.test.ts > test
[test 1]
[test 2]

stdout | basic.test.ts > test
[test 3]
[test 4]

42 changes: 42 additions & 0 deletions test/config/test/console.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { UserConsoleLog } from 'vitest'
import { expect, test, vi } from 'vitest'
import { runVitest } from '../../test-utils'

Expand All @@ -21,3 +22,44 @@ test.each(['threads', 'vmThreads'] as const)(`disable intercept pool=%s`, async
const call = spy.mock.lastCall![0]
expect(call.toString()).toBe('__test_console__\n')
})

test('group synchronous console logs', async () => {
const logs: UserConsoleLog[] = []
await runVitest({
root: './fixtures/console-batch',
reporters: [
'default',
{
onUserConsoleLog(log) {
logs.push(log)
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of asserting onUserConsoleLog, could we directly check the stdout of the process? I feel like that would provide more confidence of the fix from user's perspective.

Something like:

test('group synchronous console logs', async () => {
  const { stdout } = await runVitest({
    root: './fixtures/console-batch',
    reporters: ['default'],
  })

  const logs = stdout
    .split('\n')
    .filter(row => row.length === 0 || row.startsWith('stdout') || row.startsWith('['))
    .join('\n')
    .trim()

  expect(logs).toMatchInlineSnapshot(...)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice trick! I didn't think there's a robust way to test stdout directly 😮

},
],
})
expect(logs.map(log => log.content)).toMatchInlineSnapshot(`
[
"[beforeAll 1]
",
"[beforeAll 2]
",
"[beforeEach 1]
",
"[beforeEach 2]
",
"[test 1]
[test 2]
",
"[test 3]
[test 4]
",
"[afterEach 2]
",
"[afterEach 1]
",
"[afterAll 2]
",
"[afterAll 1]
",
]
`)
})
Loading