import { afterEach, describe, expect, it, vi } from 'vitest' import { createLibraryRestoreAuthorization, enqueueLibraryRestore, fetchLibraryRestoreAvailability, } from './librarySnapshots' const jsonResponse = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) afterEach(() => { vi.unstubAllGlobals() }) describe('整库恢复的前端契约', () => { it('读取恢复条件时把原因与授权状态原样带回来', async () => { vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue( jsonResponse({ allowed: false, reasons: ['没有针对该快照的恢复授权:先签发 restore 授权(绑定同一快照)'], scope: 'internal', snapshot_id: 'snap-1', authorization: { state: 'none', reason: '没有与目标快照匹配的有效发布授权' }, }) ) ) const availability = await fetchLibraryRestoreAvailability('internal', 'snap-1') expect(availability?.allowed).toBe(false) expect(availability?.reasons).toHaveLength(1) expect(availability?.authorization.state).toBe('none') const requested = (vi.mocked(fetch).mock.calls[0]?.[0] as string) ?? '' expect(requested).toContain('scope=internal') expect(requested).toContain('snapshot_id=snap-1') }) it('签发恢复授权必须声明 action=restore 与有限有效期', async () => { vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue( jsonResponse( { authorization: { id: 'libauth-restore-1', authorized_by: 'yaozhanghao', expires_at: '2026-10-29T09:00:00Z', }, }, 201 ) ) ) const grant = await createLibraryRestoreAuthorization('internal', 'snap-1') expect(grant.id).toBe('libauth-restore-1') const init = vi.mocked(fetch).mock.calls[0]?.[1] as RequestInit const body = JSON.parse(String(init.body)) as Record expect(body.action).toBe('restore') expect(body.expires_in_minutes).toBe(30) }) it('恢复被拒时把逐条原因说给用户,而不是只说 HTTP 状态', async () => { vi.stubGlobal( 'fetch', vi .fn() .mockResolvedValue( jsonResponse({ code: 'library_restore_blocked', reasons: ['生产写入闸口关闭', '没有该快照的恢复授权'] }, 503) ) ) await expect(enqueueLibraryRestore('internal', 'snap-1')).rejects.toThrow('生产写入闸口关闭;没有该快照的恢复授权') }) it('投递成功时返回作业号,供页面显示真实进度', async () => { vi.stubGlobal( 'fetch', vi .fn() .mockResolvedValue( jsonResponse({ job: { id: 'librestore-internal-1', scope: 'internal' }, reused: false }, 202) ) ) const accepted = await enqueueLibraryRestore('internal', 'snap-1') expect(accepted.job_id).toBe('librestore-internal-1') expect(accepted.reused).toBe(false) }) })