import { afterEach, describe, expect, it, vi } from 'vitest' import { fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule' const payload = { enabled: true, schedule_time: '03:30', retention_days: 7, retention_months: 3, updated_by: 'yaozhanghao', updated_at: '2026-10-09T12:00:00Z', last_applied_at: '', last_applied_summary: '', host_configured: true, host_target: 'weknora-test', host_reachable: true, host_error: '', host_schedule_enabled: true, host_schedule_time: '03:30', host_keep_days: 7, host_keep_months: 3, host_cron_lines: ['30 03 * * * root …'], host_cron_service: 'active', host_script_present: true, last_run_stamp: '20261009T052909Z', last_run_created_at: '2026-10-09T05:29:09Z', last_run_duration_seconds: 33, last_run_total_bytes: 778502144, last_run_databases: ['weknora_test'], last_run_failed_databases: [], last_run_error: '', in_sync: true, applied: true, apply_error: '', running: false, running_started_at: '', run_last_error: '', } const jsonResponse = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) afterEach(() => { vi.unstubAllGlobals() }) describe('backupSchedule 客户端', () => { it('解析计划三要素与主机回执', async () => { vi.stubGlobal( 'fetch', vi.fn(async () => jsonResponse({ data: payload })) ) const schedule = await fetchBackupSchedule() expect(schedule.schedule_time).toBe('03:30') expect(schedule.retention_days).toBe(7) expect(schedule.host_cron_lines).toHaveLength(1) expect(schedule.last_run_failed_databases).toEqual([]) }) it('缺计划字段就报错,绝不把默认值伪装成真实设置', async () => { const broken = { ...payload } as Record delete broken.retention_days vi.stubGlobal( 'fetch', vi.fn(async () => jsonResponse({ data: broken })) ) await expect(fetchBackupScheduleHost()).rejects.toThrow('存储与备份响应缺少计划字段') }) it('保存失败时把后端的中文原因透出来', async () => { vi.stubGlobal( 'fetch', vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400)) ) await expect( saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 }) ).rejects.toThrow('储存天数需在 1~365 之间,收到 0') }) it('立即备份返回 202 时识别为已启动', async () => { vi.stubGlobal( 'fetch', vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202)) ) await expect(runBackupNow()).resolves.toEqual({ started: true, running: true }) }) })