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

22 lines
2.6 KiB
JavaScript
Raw Normal View History

import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {createRequire} from 'node:module';
import vm from 'node:vm';
const require=createRequire(import.meta.url),ts=require('typescript');
function setup(){
const writes=[],removed=[],previews=[];
class File{constructor(root,name){this.uri=name?`${root.uri}/${name}`:root;this.size=3*1024**2;this.exists=true;}open(){return {offset:0,readBytes:async n=>new Uint8Array(n),writeBytes:async b=>writes.push(b.length),close(){}};}write(b){writes.push(b.length);}delete(){removed.push(this.uri);}create(){}async canPreview(){return true;}async preview(){previews.push(this.uri);}}
class Directory{constructor(root,name){this.uri=root.uri+'/'+name;}create(){}}
const exports={},code=ts.transpileModule(readFileSync(new URL('../src/managed-files.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
vm.runInNewContext(code,{exports,require:n=>({'react-native':{Platform:{OS:'android'}},'expo-document-picker':{getDocumentAsync:async()=>({canceled:false,assets:[{uri:'file:///cache/picked.apk',name:'picked.apk'}]})},'expo-file-system':{File,Directory,FileMode:{ReadOnly:'r',WriteOnly:'w'},Paths:{cache:{uri:'file:///cache'}}},'expo-sharing':{isAvailableAsync:async()=>true,shareAsync:async()=>{}},'expo/fetch':{fetch:async()=>{}}}[n]||{})});return {api:exports,writes,removed,previews};
}
test('Android upload reads requested chunks through FileHandle and uses local URI multipart parts',async()=>{
const {api,writes,removed}=setup(),source=await api.pickManagedFile();assert.equal(source.size,3*1024**2);assert.equal((await source.read(1024**2,1024**2)).length,1024**2);const part=await source.part(new Uint8Array(1024));assert.equal(part.type,'application/octet-stream');assert.match(part.uri,/^file:\/\/\/cache\/upload-chunk-/);assert.deepEqual(writes,[1024]);source.close();assert.ok(removed.some(p=>p.endsWith('/picked.apk')));
});
test('Android downloads write streamed chunks directly to disk and only preview after successful completion',async()=>{
const {api,writes,removed,previews}=setup(),signal=new AbortController().signal;
await api.downloadManagedFile({download:async(_p,sink)=>{await sink(new Uint8Array(1024));await sink(new Uint8Array(512));}}, {id:'file',name:'a.pdf'},signal,()=>{},'open');assert.deepEqual(writes,[1024,512]);assert.equal(previews.length,1);assert.equal(removed.length,0);
await assert.rejects(api.downloadManagedFile({download:async()=>{throw Error('offline');}}, {id:'file',name:'a.pdf'},signal,()=>{},'open'),/offline/);assert.equal(previews.length,1);assert.equal(removed.length,1);
});