|
| 1 | +import { afterEach, beforeEach, expect } from 'vitest'; |
| 2 | +import { format } from 'node:util'; |
| 3 | + |
| 4 | +type ConsoleMethod = 'log' | 'info' | 'debug' | 'warn' | 'error'; |
| 5 | +type StreamKind = 'stdout' | 'stderr'; |
| 6 | + |
| 7 | +type OutputEvent = { |
| 8 | + kind: StreamKind; |
| 9 | + source: 'console' | 'stream'; |
| 10 | + method?: ConsoleMethod; |
| 11 | + message: string; |
| 12 | +}; |
| 13 | + |
| 14 | +const mode = (process.env.TEST_STDIO_MODE ?? 'error').toLowerCase(); |
| 15 | +const guardEnabled = mode !== 'off'; |
| 16 | +const MAX_EVENTS = 20; |
| 17 | + |
| 18 | +const consoleToStream: Record<ConsoleMethod, StreamKind> = { |
| 19 | + log: 'stdout', |
| 20 | + info: 'stdout', |
| 21 | + debug: 'stdout', |
| 22 | + warn: 'stderr', |
| 23 | + error: 'stderr', |
| 24 | +}; |
| 25 | + |
| 26 | +const consoleMethods = Object.keys(consoleToStream) as ConsoleMethod[]; |
| 27 | +const baselineConsole = new Map<ConsoleMethod, (...args: unknown[]) => void>(); |
| 28 | +for (const method of consoleMethods) { |
| 29 | + baselineConsole.set(method, console[method].bind(console)); |
| 30 | +} |
| 31 | + |
| 32 | +const originalStdoutWrite = process.stdout.write.bind(process.stdout); |
| 33 | +const originalStderrWrite = process.stderr.write.bind(process.stderr); |
| 34 | + |
| 35 | +let consoleWriteDepth = 0; |
| 36 | +let allowAll = false; |
| 37 | +let droppedEvents = 0; |
| 38 | +const allowedKinds = new Set<ConsoleMethod | StreamKind>(); |
| 39 | +let outputEvents: OutputEvent[] = []; |
| 40 | + |
| 41 | +function normalizeChunk(chunk: unknown, encoding?: BufferEncoding): string { |
| 42 | + if (typeof chunk === 'string') { |
| 43 | + return chunk; |
| 44 | + } |
| 45 | + if (chunk instanceof Uint8Array) { |
| 46 | + return Buffer.from(chunk).toString(encoding); |
| 47 | + } |
| 48 | + return String(chunk); |
| 49 | +} |
| 50 | + |
| 51 | +function truncate(message: string, maxLength = 200): string { |
| 52 | + const trimmed = message.trimEnd(); |
| 53 | + if (trimmed.length <= maxLength) { |
| 54 | + return trimmed; |
| 55 | + } |
| 56 | + return `${trimmed.slice(0, maxLength)}...`; |
| 57 | +} |
| 58 | + |
| 59 | +function isAllowed(kind: StreamKind, method?: ConsoleMethod): boolean { |
| 60 | + if (allowAll) { |
| 61 | + return true; |
| 62 | + } |
| 63 | + if (allowedKinds.has(kind)) { |
| 64 | + return true; |
| 65 | + } |
| 66 | + if (method && allowedKinds.has(method)) { |
| 67 | + return true; |
| 68 | + } |
| 69 | + return false; |
| 70 | +} |
| 71 | + |
| 72 | +function record(event: OutputEvent): void { |
| 73 | + if (outputEvents.length >= MAX_EVENTS) { |
| 74 | + droppedEvents += 1; |
| 75 | + return; |
| 76 | + } |
| 77 | + outputEvents.push({ ...event, message: event.message.trimEnd() }); |
| 78 | +} |
| 79 | + |
| 80 | +export function allowConsole(kinds?: Array<ConsoleMethod | StreamKind>): void { |
| 81 | + if (!guardEnabled) { |
| 82 | + return; |
| 83 | + } |
| 84 | + if (!kinds || kinds.length === 0) { |
| 85 | + allowAll = true; |
| 86 | + return; |
| 87 | + } |
| 88 | + for (const kind of kinds) { |
| 89 | + allowedKinds.add(kind); |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +function patchConsole(): void { |
| 94 | + for (const method of consoleMethods) { |
| 95 | + const original = baselineConsole.get(method); |
| 96 | + if (!original) { |
| 97 | + continue; |
| 98 | + } |
| 99 | + |
| 100 | + console[method] = (...args: unknown[]) => { |
| 101 | + const kind = consoleToStream[method]; |
| 102 | + const message = format(...args); |
| 103 | + |
| 104 | + if (!isAllowed(kind, method)) { |
| 105 | + record({ kind, source: 'console', method, message }); |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + consoleWriteDepth += 1; |
| 110 | + try { |
| 111 | + original(...args); |
| 112 | + } finally { |
| 113 | + consoleWriteDepth -= 1; |
| 114 | + } |
| 115 | + }; |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +function patchStream(kind: StreamKind): void { |
| 120 | + const stream = kind === 'stdout' ? process.stdout : process.stderr; |
| 121 | + const originalWrite = |
| 122 | + kind === 'stdout' ? originalStdoutWrite : originalStderrWrite; |
| 123 | + |
| 124 | + stream.write = ((chunk: unknown, encoding?: unknown, cb?: unknown) => { |
| 125 | + const callback = |
| 126 | + typeof encoding === 'function' |
| 127 | + ? (encoding as (err?: Error) => void) |
| 128 | + : (cb as ((err?: Error) => void) | undefined); |
| 129 | + const resolvedEncoding = |
| 130 | + typeof encoding === 'string' ? (encoding as BufferEncoding) : undefined; |
| 131 | + |
| 132 | + // Avoid double counting console.* calls that delegate to stream writes. |
| 133 | + if (consoleWriteDepth === 0) { |
| 134 | + const message = normalizeChunk(chunk, resolvedEncoding); |
| 135 | + if (!isAllowed(kind)) { |
| 136 | + record({ kind, source: 'stream', message }); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + if (isAllowed(kind)) { |
| 141 | + return originalWrite( |
| 142 | + chunk as any, |
| 143 | + resolvedEncoding as any, |
| 144 | + callback as any, |
| 145 | + ); |
| 146 | + } |
| 147 | + |
| 148 | + callback?.(); |
| 149 | + return true; |
| 150 | + }) as typeof stream.write; |
| 151 | +} |
| 152 | + |
| 153 | +function patchAll(): void { |
| 154 | + if (!guardEnabled) { |
| 155 | + return; |
| 156 | + } |
| 157 | + patchConsole(); |
| 158 | + patchStream('stdout'); |
| 159 | + patchStream('stderr'); |
| 160 | +} |
| 161 | + |
| 162 | +function formatEvent(event: OutputEvent): string { |
| 163 | + const label = |
| 164 | + event.source === 'console' |
| 165 | + ? `console.${event.method}` |
| 166 | + : `${event.kind}.write`; |
| 167 | + return `${label}: ${truncate(event.message)}`; |
| 168 | +} |
| 169 | + |
| 170 | +function buildFailureMessage(): string { |
| 171 | + const testName = expect.getState().currentTestName ?? '<unknown test>'; |
| 172 | + const lines = outputEvents.map(formatEvent); |
| 173 | + if (droppedEvents > 0) { |
| 174 | + lines.push(`...and ${droppedEvents} more event(s).`); |
| 175 | + } |
| 176 | + return [ |
| 177 | + `Unexpected stdout/stderr during test: ${testName}`, |
| 178 | + ...lines.map((line) => ` - ${line}`), |
| 179 | + 'Use allowConsole([...]) in a test when output is intentional.', |
| 180 | + 'Set TEST_STDIO_MODE=off to disable this guard locally.', |
| 181 | + ].join('\n'); |
| 182 | +} |
| 183 | + |
| 184 | +patchAll(); |
| 185 | + |
| 186 | +beforeEach(() => { |
| 187 | + if (!guardEnabled) { |
| 188 | + return; |
| 189 | + } |
| 190 | + // Reapply patches in case a previous test restored mocked console methods. |
| 191 | + patchAll(); |
| 192 | + allowAll = false; |
| 193 | + droppedEvents = 0; |
| 194 | + allowedKinds.clear(); |
| 195 | + outputEvents = []; |
| 196 | +}); |
| 197 | + |
| 198 | +afterEach(() => { |
| 199 | + if (!guardEnabled || outputEvents.length === 0) { |
| 200 | + return; |
| 201 | + } |
| 202 | + const message = buildFailureMessage(); |
| 203 | + if (mode === 'warn') { |
| 204 | + originalStderrWrite(`${message}\n`); |
| 205 | + return; |
| 206 | + } |
| 207 | + throw new Error(message); |
| 208 | +}); |
0 commit comments