import { afterEach, describe, expect, it, vi } from 'vitest' import { fetchBuildInfo, fetchVersionHistory, reasonLabel, syncVersionHistory } from './versionHistory' const jsonResponse = (body: unknown, status = 200) => Promise.resolve({ ok: status >= 200 && status < 300, status, json: () => Promise.resolve(body) } as Response) afterEach(() => vi.unstubAllGlobals()) // 用真实 Response(Node 全局):正文只能读一次,重复 json() 必然抛 TypeError。 // 依赖"可重复 json()"的伪 mock 会把 double-read 的 bug 掩盖成绿。 const realResponse = (body: unknown, status: number) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) const pageBody = { items: [ { commit_sha: 'a'.repeat(40), short_sha: 'aaaaaaaaaaaa', parents: [], committed_at: '2026-10-13T10:00:00Z', author_display: '姚章浩', subject: 'feat: 甲', body: '正文', record_kind: 'development', version_label: '0.1.2', version_state: 'verified', release_tags: [], release_notes: '', commit_url: 'https://gitea.example/commit/aaa', version_reason: 'counted_commits_since_base_tag', is_current_running: false, }, ], next_cursor: 'next-cursor', has_more: true, sync: { available: true, status: 'completed', complete: true, last_success_at: '2026-10-13T12:00:00Z', fetched_count: 111, expected_count: 111, error_code: '', source_head_sha: 'a'.repeat(40), active_snapshot_id: 3, repo: 'Weknora/knowledge-governance', }, current_running: { state: 'development', commit_sha: 'b'.repeat(40), display_version: '0.1.2', matched_commit_sha: '', }, } describe('fetchVersionHistory 服务端错误详情', () => { it('500 时把服务端的 error 与 code 带进异常消息(真实 Response,正文只能读一次)', async () => { const errBody = { error: '读取版本记录失败', code: 'version_history_unavailable' } const fetchMock = vi.fn(() => Promise.resolve(realResponse(errBody, 500))) vi.stubGlobal('fetch', fetchMock) await expect(fetchVersionHistory({ kind: 'all', cursor: '' })).rejects.toThrow( /HTTP 500.*读取版本记录失败.*version_history_unavailable/s ) expect(fetchMock).toHaveBeenCalledOnce() }) }) describe('versionHistory client', () => { it('loads a page, keeps the cursor and reads sync/current-running facts', async () => { const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse(pageBody)) vi.stubGlobal('fetch', fetchMock) const page = await fetchVersionHistory({ kind: 'all', cursor: '' }) expect(fetchMock).toHaveBeenCalledOnce() const url = String(fetchMock.mock.calls[0][0]) expect(url).toContain('/api/v1/version-history?') expect(url).not.toContain('kind=all') expect(url).toContain('limit=30') expect(page.items[0].version_label).toBe('0.1.2') expect(page.next_cursor).toBe('next-cursor') expect(page.has_more).toBe(true) expect(page.sync.expected_count).toBe(111) expect(page.current_running.state).toBe('development') }) it('passes the kind filter and cursor through', async () => { const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse({ ...pageBody, items: [], has_more: false }) ) vi.stubGlobal('fetch', fetchMock) await fetchVersionHistory({ kind: 'historical', cursor: 'c-1', limit: 50 }) const url = String(fetchMock.mock.calls[0][0]) expect(url).toContain('kind=historical') expect(url).toContain('cursor=c-1') expect(url).toContain('limit=50') }) it('explains an expired cursor instead of showing a raw error', async () => { vi.stubGlobal( 'fetch', vi.fn(() => jsonResponse({ code: 'cursor_expired' }, 409)) ) await expect(fetchVersionHistory({ kind: 'all', cursor: 'stale' })).rejects.toThrow('已被清理') }) it('rejects malformed payloads instead of rendering half-truths', async () => { vi.stubGlobal( 'fetch', vi.fn(() => jsonResponse({ items: 'nope' })) ) await expect(fetchVersionHistory({ kind: 'all', cursor: '' })).rejects.toThrow('响应无效') }) it('posts the sync request and reports reuse', async () => { const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse({ job_id: 'job-1', status: 'running', reused: true }) ) vi.stubGlobal('fetch', fetchMock) const accepted = await syncVersionHistory() expect(String(fetchMock.mock.calls[0][0])).toBe('/api/v1/version-history/sync') expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: 'POST' }) expect(accepted.reused).toBe(true) }) it('says admin-only when the sync is refused', async () => { vi.stubGlobal( 'fetch', vi.fn(() => jsonResponse({ code: 'forbidden_role' }, 403)) ) await expect(syncVersionHistory()).rejects.toThrow('只有管理员') }) it('never fabricates a build identity when injection is missing', async () => { vi.stubGlobal( 'fetch', vi.fn(() => jsonResponse({ release_version: '', build_kind: 'development', commit_sha: null, display_version: 'dev', built_at: '', identity_available: false, }) ) ) const info = await fetchBuildInfo() expect(info.commit_sha).toBeNull() expect(info.identity_available).toBe(false) }) it('maps every evidence reason to a human explanation', () => { expect(reasonLabel('lightweight_tag')).toContain('轻量 tag') expect(reasonLabel('no_baseline')).toContain('发布基线') expect(reasonLabel('shallow_or_incomplete_graph')).toContain('提交图不完整') expect(reasonLabel('something_new')).toBe('版本号未能核验') }) })