cmvr-wms/mobile-app/tests/managed-files.test.mjs

32 lines
4.6 KiB
JavaScript
Raw Normal View History

import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {uploadManagedFile} from '../src/core/managed-transfer.ts';
import {ApiClient} from '../src/core/network.ts';
import {noticeBlocks,safeNoticeUrl} from '../src/core/notice-content.ts';
import {createMessageCenter} from '../src/core/message-center.ts';
test('notice rendering preserves ordered/bullet lists and excludes executable elements and unsafe URLs',()=>{
const html='<p>标题<strong>加粗</strong></p><ol><li data-list="ordered"><span class="ql-ui"></span>第一项</li><li data-list="bullet">小点</li><li data-list="ordered">重新编号</li></ol><ul><li><p>带段落</p></li></ul><script>bad()</script><img src="javascript:bad()">';
const rows=noticeBlocks(html);assert.deepEqual(rows.filter(r=>r.prefix).map(r=>r.prefix),['1.','•','1.','•']);assert.ok(rows[0].parts.some(p=>p.bold));assert.ok(!JSON.stringify(rows).includes('bad()"}'));assert.equal(safeNoticeUrl('javascript:alert(1)','http://127.0.0.1:8080'),null);assert.equal(safeNoticeUrl('https://user:pass@example.com','http://127.0.0.1'),null);assert.equal(safeNoticeUrl('/profile/a.png','http://127.0.0.1:8080'),'http://127.0.0.1:8080/profile/a.png');
});
test('history announcement pagination carries query, keeps attachments and never marks read automatically',async()=>{
const calls=[];let page=0;const center=createMessageCenter({request:async(p,o)=>{calls.push([p,o]);return p==='/system/notice/published'?{data:++page===1?{items:[{noticeId:9}],hasMore:true,nextCursor:9}:{items:[{noticeId:8}],hasMore:false,nextCursor:8}}:{data:{noticeContent:'<ol><li>A</li></ol>',attachments:[{id:'file'}]}};}},()=>{});
await center.tab('notices');await center.load(true);assert.equal(calls[1][1].query.beforeId,'9');assert.equal(center.snapshot().notices.length,2);await center.detail({noticeId:9});assert.equal(center.snapshot().detail.attachments[0].id,'file');assert.match(center.snapshot().detail.html,/<ol>/);assert.ok(calls.every(([,o])=>!o?.method));
});
test('resumable upload bounds reads to 1MB and skips acknowledged chunks, then revalidates completion',async()=>{
const bytes=Buffer.alloc(2*1024**2+17,42),calls=[],reads=[],progress=[];let closed=false;
const api={captureSession:()=>1,isSessionCurrent:()=>true,request:async(path,o)=>{calls.push([path,o]);if(path==='/common/file-transfers'){assert.equal(o.body.sha256,createHash('sha256').update(bytes).digest('hex'));return {data:{id:'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',size:bytes.length,chunkSize:1024**2,totalChunks:3,uploaded:[0]}};}return path.endsWith('/complete')?{data:{complete:true,result:{id:'saved'}}}:{code:200};}};
const saved=await uploadManagedFile(api,{name:'large.apk',size:bytes.length,read:async(start,n)=>{reads.push(n);return bytes.subarray(start,start+n);},close:()=>{closed=true;}},new AbortController().signal,p=>progress.push(p));
assert.equal(saved.id,'saved');assert.ok(closed);assert.ok(reads.every(n=>n<=1024**2));assert.equal(calls.filter(([p])=>p.includes('/chunks/')).length,2);assert.ok(calls.at(-1)[0].endsWith('/complete'));assert.equal(progress.at(-1).percent,100);
});
test('upload cancellation and account changes do not complete a transfer',async()=>{
let closed=false;const ctl=new AbortController();const api={captureSession:()=>1,isSessionCurrent:()=>false,request:()=>{throw Error('must not send');}};await assert.rejects(uploadManagedFile(api,{name:'x',size:1,read:async()=>new Uint8Array([1]),close:()=>closed=true},ctl.signal,()=>{}),/账号/);assert.ok(closed);
});
test('download streams to sink, rejects JSON errors, limits and session changes',async()=>{
const make=(headers,body)=>new Response(body,{status:200,headers}),out=[];
const api=new ApiClient('http://127.0.0.1:8080',()=>{},async(_url,o)=>{assert.equal(o.redirect,'error');assert.equal(o.headers.Authorization,'Bearer fake');return make({'Content-Length':'4','Content-Type':'application/octet-stream'},new Uint8Array([1,2,3,4]));});api.authenticate('fake');assert.equal(await api.download('/system/files/id/content',async b=>out.push(...b)),4);assert.deepEqual(out,[1,2,3,4]);
await assert.rejects(api.download('/system/files/id/content',async()=>{}, {maxBytes:2}),/大小限制/);
const denied=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>make({'Content-Type':'application/json'},'{"code":403}'));await assert.rejects(denied.download('/system/files/id/content',async()=>{throw Error('must not write');}),/权限/);
const stale=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>{stale.clear();return make({'Content-Type':'application/octet-stream'},'abc');});await assert.rejects(stale.download('/system/files/id/content',async()=>{}),/账号/);
});