Files
ccs/tests/unit/cliproxy/version-checker-stale-cache.test.ts
T
Sergey Galuza a7871283d4 test(cliproxy): replace process-wide mock.module with DI seams
Bun's `mock.module()` is process-wide and is NOT undone by `mock.restore()`.
Two test files used module-level mocks that leaked across test runs,
silently breaking unrelated suites that imported the mocked modules
transitively:

- tests/unit/cliproxy/version-checker-stale-cache.test.ts mocked
  binary/version-checker, contaminating cliproxy-stats-routes-install
  and cliproxy-stats-routes-model-update suites that import a route
  module which transitively imports version-checker.
- tests/unit/cliproxy/service-manager-startup.test.ts mocked 8 modules
  at top level (binary-manager, stats-fetcher, etc.), contaminating any
  later file that imports them.

CI happens to be green because file ordering on the GitHub runner places
victim files BEFORE contaminators in `bun test`. On Linux locally the
order is reversed, producing 6 reproducible test failures on every
`bun run test:fast` run. A change in OS, bun version, or new test files
that import the mocked modules could silently flip the CI runner's
order and surface these failures unexpectedly.

Replaced module-level mocks with explicit dependency-injection seams in
production code, following the existing pattern in version-checker.ts
and version-cache.ts (`fetchJsonFn?`, `fetchLatestVersionFn?`):

- src/cliproxy/types.ts: `BinaryManagerConfig.checkForUpdatesFn` (optional)
- src/cliproxy/binary/lifecycle.ts: route through new fn with default
- src/cliproxy/service-manager.ts: `ensureCliproxyService(deps?)` with
  optional `ensureBinaryFn`, `detectRunningProxyFn`,
  `configNeedsRegenerationFn`, `withStartupLockFn`

All deps fields are optional with real-implementation defaults, so
production callers are unchanged. Tests now inject deterministic stubs
through call-site parameters instead of module-level mocks.

Verified locally: \`bun run validate\` is now 2540 pass / 0 fail
(previously 2534 pass / 6 fail at the same upstream/main HEAD).

Built [OnSteroids](https://onsteroids.ai)
2026-04-26 09:43:09 +02:00

133 lines
4.6 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
describe('version-checker stale cache fallback', () => {
let originalCcsHome: string | undefined;
let tempHome = '';
beforeEach(() => {
originalCcsHome = process.env.CCS_HOME;
tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-version-checker-'));
process.env.CCS_HOME = tempHome;
});
afterEach(() => {
mock.restore();
if (originalCcsHome !== undefined) {
process.env.CCS_HOME = originalCcsHome;
} else {
delete process.env.CCS_HOME;
}
if (tempHome && fs.existsSync(tempHome)) {
fs.rmSync(tempHome, { recursive: true, force: true });
}
});
it('uses a stale latest-version cache when GitHub lookup fails', async () => {
const {
getVersionCachePath,
writeInstalledVersion,
} = await import('../../../src/cliproxy/binary/version-cache');
const { VERSION_CACHE_DURATION_MS } = await import('../../../src/cliproxy/binary/types');
const { checkForUpdates } = await import('../../../src/cliproxy/binary/version-checker');
const plusBinDir = path.join(tempHome, '.ccs', 'cliproxy', 'bin', 'plus');
fs.mkdirSync(plusBinDir, { recursive: true });
writeInstalledVersion(plusBinDir, '6.6.80');
fs.writeFileSync(
getVersionCachePath('plus'),
JSON.stringify({
latestVersion: '6.9.23-0',
checkedAt: Date.now() - VERSION_CACHE_DURATION_MS - 1_000,
}),
'utf8'
);
const result = await checkForUpdates(plusBinDir, '6.6.80', false, 'plus', {
fetchLatestVersionFn: async () => {
throw new Error('GitHub API error: HTTP 403');
},
});
expect(result.latestVersion).toBe('6.9.23-0');
expect(result.currentVersion).toBe('6.6.80');
expect(result.hasUpdate).toBe(true);
expect(result.fromCache).toBe(true);
});
it('uses a stale release-list cache when GitHub list lookup fails', async () => {
const { getVersionListCachePath } = await import('../../../src/cliproxy/binary/version-cache');
const { VERSION_CACHE_DURATION_MS } = await import('../../../src/cliproxy/binary/types');
const { fetchAllVersions } = await import('../../../src/cliproxy/binary/version-checker');
const plusBinDir = path.join(tempHome, '.ccs', 'cliproxy', 'bin', 'plus');
fs.mkdirSync(plusBinDir, { recursive: true });
fs.writeFileSync(
getVersionListCachePath('plus'),
JSON.stringify({
versions: ['6.9.23-0', '6.9.22-0', '6.9.19-0'],
latestStable: '6.9.23-0',
latest: '6.9.23-0',
checkedAt: Date.now() - VERSION_CACHE_DURATION_MS - 1_000,
}),
'utf8'
);
const result = await fetchAllVersions(false, 'plus', {
fetchJsonFn: async () => {
throw new Error('GitHub API error: HTTP 403');
},
});
expect(result.versions).toEqual(['6.9.23-0', '6.9.22-0', '6.9.19-0']);
expect(result.latestStable).toBe('6.9.23-0');
expect(result.latest).toBe('6.9.23-0');
expect(result.fromCache).toBe(true);
});
it('skips update lookups when runtime startup prefers the installed binary', async () => {
const { getExecutableName } = await import('../../../src/cliproxy/platform-detector');
const { ensureBinary } = await import('../../../src/cliproxy/binary/lifecycle');
const plusBinDir = path.join(tempHome, '.ccs', 'cliproxy', 'bin', 'plus');
fs.mkdirSync(plusBinDir, { recursive: true });
fs.writeFileSync(path.join(plusBinDir, getExecutableName('plus')), 'binary');
// Verify the contract via dependency injection rather than mock.module().
// bun's mock.module() is process-wide and is NOT undone by mock.restore(),
// which previously leaked a stubbed version-checker into unrelated test
// files (cliproxy-stats-routes-*) that transitively import it.
let checkForUpdatesCalls = 0;
const checkForUpdatesSpy = async () => {
checkForUpdatesCalls += 1;
return {
hasUpdate: false,
currentVersion: '6.8.2-0',
latestVersion: '6.8.2-0',
fromCache: false,
checkedAt: Date.now(),
};
};
const binaryPath = await ensureBinary({
version: '6.8.2-0',
releaseUrl: 'https://example.com/releases/download',
binPath: plusBinDir,
maxRetries: 1,
verbose: false,
forceVersion: false,
skipAutoUpdate: true,
allowInstall: true,
backend: 'plus',
checkForUpdatesFn: checkForUpdatesSpy,
});
expect(binaryPath).toBe(path.join(plusBinDir, getExecutableName('plus')));
expect(checkForUpdatesCalls).toBe(0);
});
});