import { afterEach, describe, it, expect, vi } from 'vitest' import { parseQAMirrorStatus, mirrorStateChanged } from './qaMirror' import { mergeQAPages, parseQARecordPage } from './qaOps' const initial = { mode: 'local', ready: false, blocked: false, revision: 0, records: 0, source_observed_at: null, last_success_at: null, next_sync_at: null, error_code: 'initial_sync_pending', interval_seconds: 300, worker_ready: true, job: null, } afterEach(() => vi.unstubAllGlobals()) describe('local Q&A mirror contract', () => { it('refreshes records on the first already-ready snapshot so an earlier initial 503 is not stranded', () => { expect(mirrorStateChanged(undefined, { revision: 1, blocked: false, ready: true })).toBe(true) expect(mirrorStateChanged(undefined, { revision: 0, blocked: false, ready: false })).toBe(false) expect( mirrorStateChanged({ revision: 1, blocked: false, ready: true }, { revision: 1, blocked: false, ready: true }) ).toBe(false) }) it('keeps unsynchronized and successfully empty data distinct', () => { expect(parseQAMirrorStatus(initial).ready).toBe(false) expect( parseQAMirrorStatus({ ...initial, ready: true, revision: 1, error_code: '', source_observed_at: '2026-10-18T00:00:00Z', last_success_at: '2026-10-18T00:01:00Z', next_sync_at: '2026-10-18T00:06:00Z', }).records ).toBe(0) }) it('rejects fake completeness, wrong cadence and malformed progress', () => { expect(() => parseQAMirrorStatus({ ...initial, ready: true })).toThrow('响应无效') expect(() => parseQAMirrorStatus({ ...initial, interval_seconds: 60 })).toThrow('响应无效') expect(() => parseQAMirrorStatus({ ...initial, job: { id: 'j', state: 'running', loaded: 3, expected: 2, changed: 1, error_code: '' }, }) ).toThrow('响应无效') }) it('rejects equal-count pages from different local generations', () => { const p = parseQARecordPage({ items: [], columns: [], total: 0, has_more: false, next_cursor: '', as_of: '2026-10-18T00:00:00Z', local_revision: 1, }) expect(() => mergeQAPages(p, { ...p, local_revision: 2 })).toThrow('本地问答已更新') }) })