stock-bot/scripts/test/audit-secrets-repo.test.ts

53 lines
1.7 KiB
TypeScript

import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, test } from 'bun:test';
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const auditScript = fileURLToPath(new URL('../audit-secrets.ts', import.meta.url));
function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record<string, string> {
const env: Record<string, string> = {};
for (const [key, value] of Object.entries(baseEnv)) {
if (value !== undefined && !key.startsWith('GIT_')) {
env[key] = value;
}
}
return env;
}
function runAuditSecrets(cwd: string, baseEnv: NodeJS.ProcessEnv = process.env) {
const result = Bun.spawnSync([process.execPath, auditScript], {
cwd,
env: isolatedGitEnv(baseEnv),
stdout: 'pipe',
stderr: 'pipe',
});
return {
exitCode: result.exitCode,
stdout: new TextDecoder().decode(result.stdout),
stderr: new TextDecoder().decode(result.stderr),
};
}
test('audit:secrets passes on the real repository', () => {
const result = runAuditSecrets(repoRoot);
expect(result.exitCode, result.stderr).toBe(0);
expect(result.stderr).toBe('');
expect(result.stdout).toContain('Secret audit passed');
});
test('audit:secrets fails closed when git metadata is unavailable', () => {
const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-no-git-'));
try {
const result = runAuditSecrets(tempDir);
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('Cannot inspect tracked files for the secret audit');
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});