import { test, before, after } from 'node:test' import assert from 'node:assert/strict' import { effectScope, ref, nextTick } from 'vue' import { createServer } from 'vite' let server, create, service, config before(async () => { server = await createServer({ server: { middlewareMode: true, watch: null }, appType: 'custom' }) create = (await server.ssrLoadModule('/src/composables/useDownloadChecks.ts')).useDownloadChecks const exports = await server.ssrLoadModule('/src/services/index.ts') service = exports.DownloadCheckService; config = exports.ConfigService }) after(async () => await server?.close()) const ok = ids => ({ code: 200, detail: ids.map(id => ({id, status: 'available', message: 'ok', checkedAt: '2026-09-18T00:00:00Z'})) }) test('manual mode does not check on mount, config load, refresh, pagination or elapsed time', async t => { const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)) const oldCheck=service.check,oldGet=config.getConfig;let calls=0 t.mock.timers.enable({apis:['setTimeout']}) try { service.check=async ids=>{calls++;return ok(ids)} config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:0}}) assert.equal(f.interval.value,0);await f.loadInterval() files.value=[{id:2}];await nextTick();files.value=[{id:2}];await nextTick() t.mock.timers.tick(3600000);assert.equal(calls,0) await f.checkIds([2]);assert.equal(calls,1) } finally {scope.stop();service.check=oldCheck;config.getConfig=oldGet;t.mock.timers.reset()} }) test('single and selected checks deduplicate IDs, run sequentially, tolerate failure and report progress',async()=>{ const scope=effectScope(),files=ref([{id:1},{id:2},{id:3}]),f=scope.run(()=>create(files)) const original=service.check;let active=0,max=0;const seen=[] try { service.check=async ids=>{active++;max=Math.max(max,active);seen.push(ids);await Promise.resolve();active--;if(ids[0]===2)throw Error('offline');return ok(ids)} await f.checkIds([1,2,1,3]);assert.deepEqual(seen,[[1],[2],[3]]);assert.equal(max,1) assert.equal(f.statusFor(1).status,'available');assert.equal(f.statusFor(2).status,'unknown') assert.deepEqual(f.progress.value,{completed:3,total:3});assert.equal(files.value.length,3) service.check=async ids=>ok(ids);await f.checkIds([2]);assert.equal(f.statusFor(2).status,'available') }finally{scope.stop();service.check=original} }) test('all-files check includes IDs outside the visible page and ignores changing list filters',async()=>{ const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)) const oldCheck=service.check,oldIds=service.listIds;const seen=[] try { service.listIds=async()=>({code:200,detail:[1,2,3,4]}) service.check=async ids=>{seen.push(ids[0]);files.value=[{id:99}];await nextTick();return ok(ids)} await f.checkAll();assert.deepEqual(seen,[1,2,3,4]);assert.equal(f.progress.value.completed,4) assert.equal(f.statusFor(4).status,'available');assert.equal(f.statusFor(99).status,'unknown') }finally{scope.stop();service.check=oldCheck;service.listIds=oldIds} }) test('cancel stops subsequent requests and stale responses cannot overwrite a new run',async()=>{ const scope=effectScope(),f=scope.run(()=>create(ref([{id:1},{id:2}]))),old=service.check let resolveFirst,signal;const seen=[] try { service.check=(ids,s)=>{signal=s;seen.push(ids[0]);return new Promise(r=>resolveFirst=r)} const first=f.checkIds([1,2]);await f.checkIds([3]);assert.deepEqual(seen,[1]) f.cancel();assert.equal(signal.aborted,true);assert.equal(f.checking.value,false) assert.equal(f.statusFor(1).status,'unknown');assert.equal(f.progressText.value,'已取消') service.check=async ids=>ok(ids);await f.checkIds([1]);const fresh=f.statusFor(1) resolveFirst({code:200,detail:[{id:1,status:'unavailable'}]});await first assert.deepEqual(f.statusFor(1),fresh);assert.deepEqual(seen,[1]) }finally{scope.stop();service.check=old} }) test('all-files enumeration handles failure, cancellation, empty results and disposal',async()=>{ const oldIds=service.listIds,oldCheck=service.check,scope=effectScope(),f=scope.run(()=>create(ref([]))) let calls=0 try { service.check=async ids=>{calls++;return ok(ids)} service.listIds=async()=>{throw Error('offline')};await f.checkAll();assert.ok(f.error.value);assert.equal(calls,0) service.listIds=async()=>({code:200,detail:[]});await f.checkAll();assert.equal(f.progressText.value,'没有可检测的文件') let resolveIds,signal;service.listIds=s=>{signal=s;return new Promise(r=>resolveIds=r)} const pending=f.checkAll();scope.stop();assert.equal(signal.aborted,true);resolveIds({code:200,detail:[1]});await pending;assert.equal(calls,0) }finally{scope.stop();service.listIds=oldIds;service.check=oldCheck} }) test('interval settings persist, save failures retain old value, manual works with timer off',async()=>{ const scope=effectScope(),f=scope.run(()=>create(ref([{id:1}]))),oldGet=config.getConfig,oldSave=config.updateConfig,oldCheck=service.check try { config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:60}});await f.loadInterval();assert.equal(f.interval.value,60) config.updateConfig=async data=>{assert.equal(data.downloadCheckInterval,0);return {code:200}} await f.saveInterval(0);assert.equal(f.interval.value,0) config.updateConfig=async()=>{throw Error('offline')};await f.saveInterval(300);assert.equal(f.interval.value,0);assert.ok(f.error.value) service.check=async ids=>ok(ids);await f.refresh();assert.equal(f.statusFor(1).status,'available') }finally{scope.stop();config.getConfig=oldGet;config.updateConfig=oldSave;service.check=oldCheck} }) test('explicitly enabled timer runs only after its interval and stops on disposal',async t=>{ const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)),oldCheck=service.check,oldGet=config.getConfig let calls=0;t.mock.timers.enable({apis:['setTimeout']}) try { service.check=async ids=>{calls++;return ok(ids)};config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:300}}) await f.loadInterval();files.value=[{id:2}];await nextTick();assert.equal(calls,0) t.mock.timers.tick(300000);await new Promise(r=>setImmediate(r));assert.equal(calls,1) scope.stop();t.mock.timers.tick(300000);assert.equal(calls,1) }finally{scope.stop();service.check=oldCheck;config.getConfig=oldGet;t.mock.timers.reset()} }) test('status component renders only label and last checked time',async()=>{ const {createSSRApp}=await import('vue'),{renderToString}=await import('vue/server-renderer') const Component=(await server.ssrLoadModule('/src/components/manage/DownloadCheckStatus.vue')).default for(const [status,label] of Object.entries({available:'可下载',unavailable:'不可下载',unknown:'未检测',checking:'检测中'})){ const html=await renderToString(createSSRApp(Component,{result:{id:1,status,message:'reason',checkedAt:'2026-09-18T00:00:00Z'},dark:false})) assert.ok(html.includes(label));assert.ok(!html.includes('reason'));assert.ok(html.includes('2026')) } })