import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import * as fs from 'fs/promises' vi.mock('fs/promises', () => ({ readFile: vi.fn(), readdir: vi.fn(), stat: vi.fn(), unlink: vi.fn(), })) const { mockWriteFileAtomic } = vi.hoisted(() => ({ mockWriteFileAtomic: vi.fn(), })) vi.mock('../../src/utils/fs-safe', () => ({ mkdirSafe: vi.fn().mockResolvedValue(undefined), mkdirSyncSafe: vi.fn(), writeFileAtomic: mockWriteFileAtomic, })) vi.mock('bun:sqlite', () => ({ Database: vi.fn(), })) const { mockGetSettings, mockUpdateSettings } = vi.hoisted(() => ({ mockGetSettings: vi.fn(), mockUpdateSettings: vi.fn(), })) vi.mock('../../src/services/settings', () => ({ SettingsService: vi.fn().mockImplementation(() => ({ getSettings: mockGetSettings, updateSettings: mockUpdateSettings, })), })) const { mockNormalizeToBaseUrl, mockDiscoverModelsCached, mockDiscoverCached } = vi.hoisted(() => ({ mockNormalizeToBaseUrl: vi.fn((url: string) => url.replace(/\/+$/, '')), mockDiscoverModelsCached: vi.fn(), mockDiscoverCached: vi.fn(), })) vi.mock('../../src/utils/discovery-cache', () => ({ normalizeToBaseUrl: mockNormalizeToBaseUrl, discoverModelsCached: mockDiscoverModelsCached, discoverCached: mockDiscoverCached, })) vi.mock('../../src/utils/logger', () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), }, })) const mockReadFile = fs.readFile as any const mockReaddir = fs.readdir as any const mockStat = fs.stat as any const mockUnlink = fs.unlink as any import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, ensureCacheDir, getCachedAudio, getCacheSize, cleanupOldestFiles, cacheAudio, clearCache } from '../../src/routes/tts' function createTtsConfig(overrides: Record = {}) { return { enabled: true, apiKey: 'test-api-key', endpoint: 'https://tts.example.com', voice: 'alloy', model: 'tts-1', speed: 1, availableVoices: [], ...overrides, } } describe('TTS Routes', () => { let mockDb: any beforeEach(() => { vi.clearAllMocks() mockDb = {} as any createTTSRoutes(mockDb) mockGetSettings.mockReturnValue({ preferences: { tts: createTtsConfig() } }) mockUpdateSettings.mockReturnValue(undefined) mockDiscoverModelsCached.mockResolvedValue({ models: ['tts-1'], cached: false }) mockDiscoverCached.mockImplementation(async (options: { fetcher: () => Promise }) => ({ value: await options.fetcher(), cached: false, })) }) describe('generateCacheKey', () => { const params = { text: 'Hello world', endpoint: 'https://tts.example.com', apiKey: 'test-api-key', voice: 'alloy', model: 'tts-1', speed: 1.0, } it('should generate consistent cache keys for identical inputs', () => { const key1 = generateCacheKey(params) const key2 = generateCacheKey({ ...params }) expect(key1).toBe(key2) expect(key1).toMatch(/^[a-f0-9]{64}$/) }) it('should generate different cache keys for different text', () => { expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, text: 'Other' })) }) it('should generate different cache keys for different voices', () => { expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, voice: 'echo' })) }) it('should generate different cache keys for different models', () => { expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, model: 'tts-1-hd' })) }) it('should generate different cache keys for different speeds', () => { expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, speed: 1.5 })) }) it('should generate different cache keys for different api keys', () => { expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, apiKey: 'other-api-key' })) }) it('should generate different cache keys for different endpoints', () => { expect(generateCacheKey(params)).not.toBe(generateCacheKey({ ...params, endpoint: 'https://other.example.com' })) }) it('should normalize endpoints so trailing slashes share a key', () => { expect(generateCacheKey(params)).toBe(generateCacheKey({ ...params, endpoint: 'https://tts.example.com/' })) }) it('should avoid delimiter ambiguity between concatenated fields', () => { const key1 = generateCacheKey({ ...params, text: 'a', voice: 'b|c' }) const key2 = generateCacheKey({ ...params, text: 'a|b', voice: 'c' }) expect(key1).not.toBe(key2) }) }) describe('clearCache', () => { it('should delete every .mp3 file and count them', async () => { mockReaddir.mockResolvedValue(['a.mp3', 'b.mp3'] as any) mockUnlink.mockResolvedValue(undefined) const cleared = await clearCache() expect(cleared).toBe(2) expect(mockUnlink).toHaveBeenCalledTimes(2) expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('a.mp3')) expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('b.mp3')) }) it('should tolerate a missing cache directory', async () => { mockReaddir.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })) const cleared = await clearCache() expect(cleared).toBe(0) expect(mockUnlink).not.toHaveBeenCalled() }) it('should tolerate a file removed by a race and keep clearing the rest', async () => { mockReaddir.mockResolvedValue(['gone.mp3', 'present.mp3'] as any) mockUnlink .mockRejectedValueOnce(Object.assign(new Error('gone'), { code: 'ENOENT' })) .mockResolvedValueOnce(undefined) const cleared = await clearCache() expect(cleared).toBe(1) expect(mockUnlink).toHaveBeenCalledTimes(2) }) it('should throw unexpected filesystem errors', async () => { mockReaddir.mockResolvedValue(['a.mp3'] as any) mockUnlink.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' })) await expect(clearCache()).rejects.toThrow('denied') }) it('should leave .tmp, atomic temp and unrelated files untouched', async () => { mockReaddir.mockResolvedValue(['a.mp3', 'pending.tmp', '.a.mp3.ocm-tmp-1-2', 'notes.txt'] as any) mockUnlink.mockResolvedValue(undefined) const cleared = await clearCache() expect(cleared).toBe(1) expect(mockUnlink).toHaveBeenCalledTimes(1) expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('a.mp3')) }) }) describe('ensureCacheDir', () => { it('should create cache directory when it does not exist', async () => { await expect(ensureCacheDir()).resolves.toBeUndefined() }) }) describe('getCachedAudio', () => { beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { vi.useRealTimers() }) it('should return cached audio when file exists and is not expired', async () => { const cacheKey = 'test-key' const audioBuffer = Buffer.from('audio data') mockStat.mockResolvedValue({ mtimeMs: Date.now() - 1000, size: 1024, } as any) mockReadFile.mockResolvedValue(audioBuffer) const result = await getCachedAudio(cacheKey) expect(result).toBe(audioBuffer) expect(mockReadFile).toHaveBeenCalledWith( expect.stringContaining(`${cacheKey}.mp3`) ) }) it('should return null when cached file has expired', async () => { const cacheKey = 'test-key' mockStat.mockResolvedValue({ mtimeMs: Date.now() - 25 * 60 * 60 * 1000, size: 1024, } as any) mockUnlink.mockResolvedValue(undefined) const result = await getCachedAudio(cacheKey) expect(result).toBeNull() expect(mockUnlink).toHaveBeenCalledWith( expect.stringContaining(`${cacheKey}.mp3`) ) }) it('should return null when cached file does not exist', async () => { const cacheKey = 'nonexistent-key' mockStat.mockRejectedValue(new Error('File not found')) const result = await getCachedAudio(cacheKey) expect(result).toBeNull() }) }) describe('getCacheSize', () => { it('should calculate correct cache size', async () => { mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'readme.txt'] as any) mockStat .mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() } as any) .mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() } as any) const size = await getCacheSize() expect(size).toBe(3072) // 1024 + 2048 }) it('should handle cache directory errors gracefully', async () => { mockReaddir.mockRejectedValue(new Error('Permission denied')) const size = await getCacheSize() expect(size).toBe(0) }) }) describe('cleanupMethods', () => { it('should remove oldest files when cache size limit exceeded', async () => { mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'file3.mp3'] as any) mockStat .mockResolvedValueOnce({ size: 1024, mtimeMs: 1000 } as any) .mockResolvedValueOnce({ size: 2048, mtimeMs: 2000 } as any) .mockResolvedValueOnce({ size: 1536, mtimeMs: 3000 } as any) mockUnlink.mockResolvedValue(undefined) await cleanupOldestFiles(1500) // Need 1500 bytes freed expect(mockUnlink).toHaveBeenCalledWith( expect.stringContaining('file1.mp3') ) }) it('should return cache statistics for files', async () => { const currentTime = Date.now() mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3'] as any) mockStat .mockResolvedValueOnce({ size: 1024, mtimeMs: currentTime } as any) .mockResolvedValueOnce({ size: 2048, mtimeMs: currentTime } as any) const stats = await getCacheStats() expect(stats.count).toBe(2) expect(stats.sizeBytes).toBe(3072) expect(stats.sizeMB).toBeCloseTo(0, 1) }) it('should cleanup expired cache files', async () => { mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'expired.mp3'] as any) mockStat .mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() } as any) .mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() } as any) .mockResolvedValueOnce({ size: 1536, mtimeMs: Date.now() - 25 * 60 * 60 * 1000 } as any) mockUnlink.mockResolvedValue(undefined) const cleaned = await cleanupExpiredCache() expect(cleaned).toBe(1) expect(mockUnlink).toHaveBeenCalledWith( expect.stringContaining('expired.mp3') ) }) }) }) describe('TTS route handlers', () => { let app: ReturnType let mockDb: any beforeEach(() => { vi.clearAllMocks() mockDb = {} as any app = createTTSRoutes(mockDb) mockGetSettings.mockReturnValue({ preferences: { tts: createTtsConfig() } }) mockUpdateSettings.mockReturnValue(undefined) mockDiscoverModelsCached.mockResolvedValue({ models: ['tts-1'], cached: false }) mockDiscoverCached.mockImplementation(async (options: { fetcher: () => Promise }) => ({ value: await options.fetcher(), cached: false, })) }) afterEach(() => { vi.unstubAllGlobals() }) it('returns 400 when TTS is not enabled', async () => { mockGetSettings.mockReturnValue({ preferences: { tts: createTtsConfig({ enabled: false }) } }) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(400) expect(await res.json()).toEqual({ error: 'TTS is not enabled' }) }) it('returns 400 when the TTS API key is missing', async () => { mockGetSettings.mockReturnValue({ preferences: { tts: createTtsConfig({ apiKey: '' }) } }) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(400) expect(await res.json()).toEqual({ error: 'TTS API key is not configured' }) }) it('returns 400 for an invalid synthesize body', async () => { const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: '' }), }) expect(res.status).toBe(400) const body = await res.json() as { error: string; details: unknown[] } expect(body.error).toBe('Invalid request') expect(body.details.length).toBeGreaterThan(0) }) it('serves cached audio with a cache hit header', async () => { mockStat.mockResolvedValue({ mtimeMs: Date.now(), size: 5 } as any) mockReadFile.mockResolvedValue(Buffer.from('cached')) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(200) expect(res.headers.get('X-Cache')).toBe('HIT') expect(Buffer.from(await res.arrayBuffer()).toString()).toBe('cached') }) it('synthesizes and caches audio on a cache miss', async () => { mockStat.mockRejectedValue(new Error('not found')) mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockResolvedValue(undefined) const fetchMock = vi.fn().mockResolvedValue({ ok: true, arrayBuffer: async () => Buffer.from('fresh-audio'), }) vi.stubGlobal('fetch', fetchMock) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(200) expect(res.headers.get('X-Cache')).toBe('MISS') expect(Buffer.from(await res.arrayBuffer()).toString()).toBe('fresh-audio') expect(fetchMock).toHaveBeenCalledWith( 'https://tts.example.com/v1/audio/speech', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ Authorization: 'Bearer test-api-key' }), signal: expect.any(AbortSignal), }), ) expect(mockWriteFileAtomic).toHaveBeenCalledWith( expect.stringMatching(/\.mp3$/), expect.any(Buffer), ) }) it('returns synthesized audio when the cache write fails', async () => { mockStat.mockRejectedValue(new Error('not found')) mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockRejectedValue(new Error('disk full')) const fetchMock = vi.fn().mockResolvedValue({ ok: true, arrayBuffer: async () => Buffer.from('fresh-audio'), }) vi.stubGlobal('fetch', fetchMock) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(200) expect(res.headers.get('X-Cache')).toBe('MISS') expect(Buffer.from(await res.arrayBuffer()).toString()).toBe('fresh-audio') }) it('deduplicates concurrent synthesis requests for the same text', async () => { mockStat.mockRejectedValue(new Error('not found')) mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockResolvedValue(undefined) let resolveFetch: ((value: { ok: boolean; arrayBuffer: () => Promise }) => void) | undefined const fetchMock = vi.fn().mockImplementation( () => new Promise((resolve) => { resolveFetch = resolve }), ) vi.stubGlobal('fetch', fetchMock) const request = () => app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) const first = request() const second = request() await new Promise((resolve) => setTimeout(resolve, 0)) expect(fetchMock).toHaveBeenCalledTimes(1) resolveFetch!({ ok: true, arrayBuffer: async () => Buffer.from('shared-audio'), }) const [firstRes, secondRes] = await Promise.all([first, second]) expect(fetchMock).toHaveBeenCalledTimes(1) expect(firstRes.status).toBe(200) expect(secondRes.status).toBe(200) expect(Buffer.from(await firstRes.arrayBuffer()).toString()).toBe('shared-audio') expect(Buffer.from(await secondRes.arrayBuffer()).toString()).toBe('shared-audio') }) it('does not share an in-flight synthesis across different endpoints or API keys', async () => { mockStat.mockRejectedValue(new Error('not found')) mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockResolvedValue(undefined) mockGetSettings.mockImplementation((userId: string) => ({ preferences: { tts: createTtsConfig( userId === 'first' ? { endpoint: 'https://first.example.com', apiKey: 'first-key' } : { endpoint: 'https://second.example.com', apiKey: 'second-key' }, ), }, })) const resolvers: Array<(value: { ok: boolean; arrayBuffer: () => Promise }) => void> = [] const fetchMock = vi.fn().mockImplementation( () => new Promise((resolve) => { resolvers.push(resolve) }), ) vi.stubGlobal('fetch', fetchMock) const request = (userId: string) => app.request('/synthesize?userId=' + userId, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Isolated text' }), }) const first = request('first') const second = request('second') await new Promise((resolve) => setTimeout(resolve, 0)) expect(fetchMock).toHaveBeenCalledTimes(2) resolvers[0]!({ ok: true, arrayBuffer: async () => Buffer.from('first-audio') }) resolvers[1]!({ ok: true, arrayBuffer: async () => Buffer.from('second-audio') }) const [firstRes, secondRes] = await Promise.all([first, second]) expect(firstRes.status).toBe(200) expect(secondRes.status).toBe(200) expect(Buffer.from(await firstRes.arrayBuffer()).toString()).toBe('first-audio') expect(Buffer.from(await secondRes.arrayBuffer()).toString()).toBe('second-audio') }) it('isolates the disk cache across providers for identical text', async () => { mockStat.mockRejectedValue(new Error('not found')) mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockResolvedValue(undefined) mockGetSettings.mockImplementation((userId: string) => ({ preferences: { tts: createTtsConfig( userId === 'first' ? { endpoint: 'https://first.example.com', apiKey: 'first-key' } : { endpoint: 'https://second.example.com', apiKey: 'second-key' }, ), }, })) vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, arrayBuffer: async () => Buffer.from('audio'), })) const request = (userId: string) => app.request('/synthesize?userId=' + userId, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Shared text' }), }) await request('first') await request('second') const statPaths = mockStat.mock.calls.map((call: unknown[]) => call[0] as string) expect(statPaths).toHaveLength(2) expect(statPaths[0]).not.toBe(statPaths[1]) }) it('returns the upstream error details when synthesis fails', async () => { mockStat.mockRejectedValue(new Error('not found')) vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 400, text: async () => JSON.stringify({ detail: { error: { message: 'Voice not supported' } } }), })) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(400) expect(await res.json()).toEqual({ error: 'TTS API request failed', details: 'Voice not supported', voice: 'alloy', availableVoices: [], }) }) it('returns an upstream error when synthesis times out', async () => { mockStat.mockRejectedValue(new Error('not found')) vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('The operation timed out.', 'TimeoutError'))) const res = await app.request('/synthesize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'Hello' }), }) expect(res.status).toBe(500) expect(await res.json()).toEqual({ error: 'TTS API request failed', details: 'TTS upstream request timed out', voice: 'alloy', availableVoices: [], }) }) it('lists models and stores them when not cached', async () => { mockDiscoverModelsCached.mockResolvedValue({ models: ['tts-1', 'tts-1-hd'], cached: false }) const res = await app.request('/models') expect(res.status).toBe(200) expect(await res.json()).toEqual({ models: ['tts-1', 'tts-1-hd'], cached: false }) expect(mockUpdateSettings).toHaveBeenCalledWith( expect.objectContaining({ tts: expect.objectContaining({ availableModels: ['tts-1', 'tts-1-hd'] }) }), 'default', ) }) it('returns 400 when models are requested without configuration', async () => { mockGetSettings.mockReturnValue({ preferences: { tts: createTtsConfig({ endpoint: '' }) } }) const res = await app.request('/models') expect(res.status).toBe(400) expect(await res.json()).toEqual({ error: 'TTS not configured' }) }) it('lists voices from the OpenAI data response format', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [{ id: 'alloy' }, { name: 'echo' }] }), })) const res = await app.request('/voices') expect(res.status).toBe(200) expect(await res.json()).toEqual({ voices: ['alloy', 'echo'], cached: false }) expect(mockUpdateSettings).toHaveBeenCalledWith( expect.objectContaining({ tts: expect.objectContaining({ availableVoices: ['alloy', 'echo'] }) }), 'default', ) }) it('lists voices from the simple array response format', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ['alloy', { voice: 'echo' }], })) const res = await app.request('/voices') expect(res.status).toBe(200) expect(await res.json()).toEqual({ voices: ['alloy', 'echo'], cached: false }) }) it('falls back to the default voices when every endpoint fails', async () => { vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))) const res = await app.request('/voices') expect(res.status).toBe(200) expect(await res.json()).toEqual({ voices: ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'], cached: false, }) }) it('returns 400 when voices are requested without configuration', async () => { mockGetSettings.mockReturnValue({ preferences: { tts: createTtsConfig({ endpoint: '' }) } }) const res = await app.request('/voices') expect(res.status).toBe(400) expect(await res.json()).toEqual({ error: 'TTS not configured' }) }) it('returns the cache status', async () => { mockReaddir.mockResolvedValue(['cached.mp3'] as any) mockStat.mockResolvedValue({ size: 1024, mtimeMs: Date.now() } as any) const res = await app.request('/status') expect(res.status).toBe(200) expect(await res.json()).toEqual({ enabled: true, configured: true, cache: { count: 1, sizeBytes: 1024, sizeMB: 0, maxSizeMB: 200, ttlHours: 24 }, }) }) it('clears the cache through the DELETE /cache route', async () => { mockReaddir.mockResolvedValue(['a.mp3', 'b.mp3', 'pending.tmp', '.a.mp3.ocm-tmp-1-2'] as any) mockUnlink.mockResolvedValue(undefined) const res = await app.request('/cache', { method: 'DELETE' }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ cleared: 2 }) expect(mockUnlink).toHaveBeenCalledTimes(2) }) it('returns zero when the cache directory is missing', async () => { mockReaddir.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })) const res = await app.request('/cache', { method: 'DELETE' }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ cleared: 0 }) }) it('returns 500 when clearing the cache fails unexpectedly', async () => { mockReaddir.mockResolvedValue(['a.mp3'] as any) mockUnlink.mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' })) const res = await app.request('/cache', { method: 'DELETE' }) expect(res.status).toBe(500) expect(await res.json()).toEqual({ error: 'Failed to clear TTS cache' }) }) }) describe('cacheAudio', () => { beforeEach(() => { vi.clearAllMocks() }) it('writes audio and frees space when the cache limit would be exceeded', async () => { mockReaddir.mockResolvedValue(['big.mp3'] as any) mockStat.mockResolvedValue({ size: 200 * 1024 * 1024, mtimeMs: 1000 } as any) mockUnlink.mockResolvedValue(undefined) mockWriteFileAtomic.mockResolvedValue(undefined) await cacheAudio('cache-key', Buffer.from('audio')) expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('big.mp3')) expect(mockWriteFileAtomic).toHaveBeenCalledWith( expect.stringContaining('cache-key.mp3'), expect.any(Buffer), ) }) it('writes audio without cleanup when the cache has room', async () => { mockReaddir.mockResolvedValue(['small.mp3'] as any) mockStat.mockResolvedValue({ size: 1024, mtimeMs: 1000 } as any) mockWriteFileAtomic.mockResolvedValue(undefined) await cacheAudio('cache-key', Buffer.from('audio')) expect(mockUnlink).not.toHaveBeenCalled() expect(mockWriteFileAtomic).toHaveBeenCalledWith( expect.stringContaining('cache-key.mp3'), expect.any(Buffer), ) }) it('writes the audio buffer atomically to the final .mp3 path', async () => { mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockResolvedValue(undefined) await cacheAudio('cache-key', Buffer.from('audio')) expect(mockWriteFileAtomic).toHaveBeenCalledTimes(1) const [writtenPath, writtenData] = mockWriteFileAtomic.mock.calls[0]! expect(writtenPath).toContain('cache-key.mp3') expect(writtenData).toEqual(Buffer.from('audio')) }) it('propagates an atomic write failure', async () => { mockReaddir.mockResolvedValue([] as any) mockWriteFileAtomic.mockRejectedValue(new Error('rename failed')) await expect(cacheAudio('cache-key', Buffer.from('audio'))).rejects.toThrow('rename failed') }) })