import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { createDatabase, type Db } from './db'; import { SqliteCache } from './cache'; describe('SqliteCache', () => { let db: Db; let cache: SqliteCache; beforeEach(() => { db = createDatabase(':memory:'); cache = new SqliteCache(db); }); afterEach(() => { db.close(); }); it('returns undefined for a missing key', async () => { expect(await cache.get('nope')).toBeUndefined(); }); it('stores and retrieves a value', async () => { await cache.set('k', { hello: 'world' }); expect(await cache.get<{ hello: string }>('k')).toEqual({ hello: 'world' }); }); it('overwrites an existing key', async () => { await cache.set('k', 1); await cache.set('k', 2); expect(await cache.get('k')).toBe(2); }); it('expires values after their ttl', async () => { await cache.set('k', 'v', -1); expect(await cache.get('k')).toBeUndefined(); }); it('keeps values without a ttl', async () => { await cache.set('k', 'v'); expect(await cache.get('k')).toBe('v'); }); it('deletes a key', async () => { await cache.set('k', 'v'); await cache.delete('k'); expect(await cache.get('k')).toBeUndefined(); }); it('getOrLoad loads and caches on miss, then serves from cache', async () => { let calls = 0; const load = async () => { calls++; return 'loaded'; }; expect(await cache.getOrLoad('k', 1000, load)).toBe('loaded'); expect(await cache.getOrLoad('k', 1000, load)).toBe('loaded'); expect(calls).toBe(1); }); it('prune removes only expired rows', async () => { await cache.set('fresh', 'v', 10000); await cache.set('stale', 'v', -1); cache.prune(); expect(await cache.get('fresh')).toBe('v'); expect(await cache.get('stale')).toBeUndefined(); }); });