Files
opencode-proxy/test/key-store.test.js
T

37 lines
1.5 KiB
JavaScript

import { describe, expect, it } from 'vitest';
import { createKeyRotator, createRedisKeyRotator, loadConfiguredKeys, parseKeys, parseKeysJson } from '../src/key-store.js';
describe('key store', () => {
it('parses JSON keys and prefers the environment variable', async () => {
expect(parseKeysJson('[" a ","b"]')).toEqual(['a', 'b']);
expect(() => parseKeysJson('{"key":"a"}')).toThrow();
await expect(loadConfiguredKeys({ env: { OPENCODE_API_KEYS: '["env-key"]' }, path: '/does-not-exist' })).resolves.toEqual(['env-key']);
});
it('parses keys, blank lines, and comments', () => {
expect(parseKeys(' first \n\nsecond # note\n# ignored\n')).toEqual(['first', 'second']);
});
it('rotates keys round-robin', () => {
const rotator = createKeyRotator(['a', 'b']);
expect([rotator.next(), rotator.next(), rotator.next()]).toEqual(['a', 'b', 'a']);
});
it('shares a Redis-backed rotation sequence across rotators', async () => {
const counters = new Map();
const client = {
incr: async (key) => {
const next = (counters.get(key) || 0) + 1;
counters.set(key, next);
return String(next);
},
};
const firstInstance = createRedisKeyRotator({ client, keys: ['a', 'b'], key: 'test:key-rotation' });
const restartedInstance = createRedisKeyRotator({ client, keys: ['a', 'b'], key: 'test:key-rotation' });
await expect(firstInstance.next()).resolves.toBe('a');
await expect(firstInstance.next()).resolves.toBe('b');
await expect(restartedInstance.next()).resolves.toBe('a');
});
});