import { afterEach, describe, expect, it, vi } from 'vitest' import { fetchAllQARecords } from './qaOps' const row = (id: string) => ({ id, status: 'succeeded', question: '明确合成问题', answer: '明确合成答案', asked_at: '2026-10-14T03:00:00Z', time_source: 'request_message.created_at', asker: '合成夹具', trigger_person: '', department: '', region: '', references: [], media: [], source_coverage: { verdict: '', reason_code: '', evaluator_version: '' }, feedback: { asker_value: '', up: 0, down: 0 }, coverage: { state: 'pending', rule_version: 'fixture-rule' }, }) const page = (ids: string[], total: number, cursor = '') => ({ items: ids.map(row), columns: [], total, has_more: Boolean(cursor), next_cursor: cursor, as_of: '2026-10-14T04:00:00Z', }) const query = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T08:00:00Z', keyword: '%_原文', cursor: 'stale-cursor' } const respond = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 }) afterEach(() => vi.unstubAllGlobals()) describe('all QA records without manual pagination', () => { it('retains only the verified prefix when a later local version changes', async () => { const first = { ...page(['a'], 2, 'n'), local_revision: 1 }, second = { ...page(['b'], 2), local_revision: 2 } vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(respond(first)).mockResolvedValueOnce(respond(second))) const batches = vi.fn() await expect(fetchAllQARecords(query, undefined, undefined, batches)).rejects.toThrow('本地问答已更新') expect(batches).toHaveBeenCalledTimes(1) }) it('carries every active quality filter and summary projection to every batch', async () => { const fetcher = vi .fn() .mockResolvedValueOnce(respond(page(['a'], 2, 'n'))) .mockResolvedValueOnce(respond(page(['b'], 2))) vi.stubGlobal('fetch', fetcher) const filters = { coverage: '是', is_correct: '否', product_category: 'MG400', problem_type: '参数', root_cause: '__empty__', } await fetchAllQARecords({ ...query, dataset: 'master', projection: 'summary', filters }) for (const [url] of fetcher.mock.calls) { const u = new URL(String(url), 'http://localhost') expect(u.searchParams.get('projection')).toBe('summary') for (const [key, value] of Object.entries(filters)) expect(u.searchParams.get(key)).toBe(value) } }) it('publishes a usable first batch before the next response completes', async () => { let release!: (response: Response) => void const waiting = new Promise((resolve) => { release = resolve }) vi.stubGlobal( 'fetch', vi .fn() .mockResolvedValueOnce(respond(page(['a'], 2, 'n'))) .mockReturnValueOnce(waiting) ) const batches = vi.fn() const done = fetchAllQARecords(query, undefined, undefined, batches) await vi.waitFor(() => expect(batches).toHaveBeenCalledTimes(1)) expect(batches.mock.calls[0][0].items.map((r: { id: string }) => r.id)).toEqual(['a']) expect(batches.mock.calls[0][0].has_more).toBe(true) release(respond(page(['b'], 2))) expect((await done).items).toHaveLength(2) expect(batches).toHaveBeenCalledTimes(2) }) it('rejects incomplete, duplicate, drifting and cycling batches', async () => { const cases = [ [page(['a'], 2)], [page(['a'], 2, 'n'), page(['a'], 2)], [page(['a'], 2, 'n'), page(['b'], 3)], [page(['a'], 3, 'n'), page(['b'], 3, 'n')], ] for (const pages of cases) { const fetcher = vi.fn() pages.forEach((data) => fetcher.mockResolvedValueOnce(respond(data))) vi.stubGlobal('fetch', fetcher) await expect(fetchAllQARecords(query)).rejects.toThrow() } }) it('surfaces a later source failure instead of returning the first batch', async () => { const fetcher = vi .fn() .mockResolvedValueOnce(respond(page(['a'], 2, 'n'))) .mockResolvedValueOnce(new Response(JSON.stringify({ error: '明确合成源不可用' }), { status: 503 })) vi.stubGlobal('fetch', fetcher) await expect(fetchAllQARecords(query)).rejects.toThrow('明确合成源不可用') }) it('accepts a genuinely empty complete scope', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(respond(page([], 0)))) expect((await fetchAllQARecords(query)).items).toEqual([]) }) it('does not start or continue requests after cancellation', async () => { const controller = new AbortController() controller.abort() const fetcher = vi.fn().mockResolvedValue(respond(page([], 0))) vi.stubGlobal('fetch', fetcher) await expect(fetchAllQARecords(query, controller.signal)).rejects.toMatchObject({ name: 'AbortError' }) expect(fetcher).not.toHaveBeenCalled() }) it('reads every transport batch and verifies final count before returning', async () => { const fetcher = vi .fn() .mockResolvedValueOnce(respond(page(['a', 'b'], 3, 'next'))) .mockResolvedValueOnce(respond(page(['c'], 3))) vi.stubGlobal('fetch', fetcher) const progress = vi.fn() const result = await fetchAllQARecords(query, undefined, progress) expect(result.items.map((r) => r.id)).toEqual(['a', 'b', 'c']) expect(result.has_more).toBe(false) expect(result.total).toBe(3) expect(progress.mock.calls).toEqual([ [2, 3], [3, 3], ]) const urls = fetcher.mock.calls.map((call) => new URL(String(call[0]), 'http://localhost')) expect(urls.map((url) => url.searchParams.get('cursor'))).toEqual(['', 'next']) expect( urls.every((url) => url.searchParams.get('limit') === '100' && url.searchParams.get('keyword') === query.keyword) ).toBe(true) }) })