import { beforeEach, describe, expect, it, vi } from 'vitest'; const queryMock = vi.fn(); const releaseMock = vi.fn(); const connectMock = vi.fn(async () => ({ query: queryMock, release: releaseMock, })); vi.mock('../src/db', () => ({ pool: { connect: connectMock }, })); vi.mock('../src/services/redisClient', () => ({ isRedisConfigured: () => false, getRedisClient: () => null, })); describe('withDistributedLock PG fallback', () => { beforeEach(() => { queryMock.mockReset(); releaseMock.mockReset(); connectMock.mockClear(); }); it('runs fn when pg_try_advisory_lock succeeds', async () => { queryMock .mockResolvedValueOnce({ rows: [{ ok: true }] }) // try lock .mockResolvedValueOnce({ rows: [{ pg_advisory_unlock: true }] }); // unlock const { withDistributedLock } = await import('../src/services/distributedLock'); const ran = vi.fn(async () => 'ok'); const result = await withDistributedLock('scheduled-jobs-tick', 60, ran); expect(result).toBe('ok'); expect(ran).toHaveBeenCalledTimes(1); expect(releaseMock).toHaveBeenCalledTimes(1); }); it('skips fn when pg lock is held', async () => { queryMock.mockResolvedValueOnce({ rows: [{ ok: false }] }); const { withDistributedLock } = await import('../src/services/distributedLock'); const ran = vi.fn(async () => 'ok'); const result = await withDistributedLock('scheduled-jobs-tick', 60, ran); expect(result).toBeNull(); expect(ran).not.toHaveBeenCalled(); expect(releaseMock).toHaveBeenCalledTimes(1); }); });