stock-bot/test/unit/in-process-test-isolation.test.ts
2026-11-27 12:33:45 -05:00

54 lines
2.1 KiB
TypeScript

import { readdirSync, readFileSync } from 'fs';
import { join, relative } from 'path';
import { describe, expect, it } from 'bun:test';
// Guards T-16: all test files share one bun process, so process-global mocks in one
// file silently change the modules and globals other files see. Restorable `spyOn`
// is the supported pattern; child-process harnesses (test/integration) are exempt.
const root = join(import.meta.dir, '..', '..');
const scannedRoots = ['libs'];
const forbidden: Array<{ label: string; pattern: RegExp }> = [
{ label: 'mock.module(', pattern: /\bmock\.module\s*\(/ },
{ label: 'Bun.serve assignment', pattern: /\bBun\.serve\s*=(?!=)/ },
{ label: 'process.on assignment', pattern: /\bprocess\.(on|once|off)\s*=(?!=)/ },
{ label: 'process.exit assignment', pattern: /\bprocess\.exit\s*=(?!=)/ },
{ label: 'global console assignment', pattern: /\b(global|globalThis)\.console\s*=(?!=)/ },
];
function collectTestFiles(dir: string, out: string[]): void {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.')) {
continue;
}
const full = join(dir, entry.name);
if (entry.isDirectory()) {
collectTestFiles(full, out);
} else if (/\.(test|spec)\.tsx?$/.test(entry.name)) {
out.push(full);
}
}
}
describe('in-process test isolation', () => {
it('library tests never install process-global mocks or overwrite process/Bun globals', () => {
const files: string[] = [];
for (const dir of scannedRoots) {
collectTestFiles(join(root, dir), files);
}
expect(files.length).toBeGreaterThan(0);
const violations: string[] = [];
for (const file of files) {
const lines = readFileSync(file, 'utf8').split('\n');
lines.forEach((line, index) => {
for (const { label, pattern } of forbidden) {
if (pattern.test(line)) {
violations.push(`${relative(root, file)}:${index + 1} ${label}`);
}
}
});
}
expect(violations).toEqual([]);
});
});