cmvr-wms/mobile-app/tests/package-update-native-flow.test.mjs
lixiaolong 6b43b0104f feat(app): 优化移动端应用配置和功能实现
- 添加生产环境服务器地址配置支持内外网切换
- 实现采购列表只看我创建的功能开关
- 更新构建脚本中的默认生产环境API地址
- 优化采购单表格单元格编辑体验改用自动补全组件
- 调整应用更新检查逻辑增强生产环境兼容性
- 修复开发服务器切换时的一些验证问题
- 增强应用启动时的服务地址配置灵活性
2026-10-30 15:02:54 +08:00

71 lines
11 KiB
JavaScript

import test from 'node:test';import assert from 'node:assert/strict';import {createRequire} from 'node:module';import {readFileSync} from 'node:fs';import vm from 'node:vm';
import * as core from '../src/core/package-update.ts';import * as native from '../src/core/native-package-download.ts';import {ApiClient} from '../src/core/network.ts';
import * as cacheCore from '../src/core/package-cache.ts';import {createHash} from 'node:crypto';
const require=createRequire(import.meta.url),ts=require('typescript');
function setup(shared={files:new Map(),preferences:new Map()},scope='one',version=10){
shared.metadata??=new Map();
const bytes=Buffer.alloc(100,7),hash=createHash('sha256').update(bytes).digest('hex');
const release={versionCode:version,versionName:'1.0.2',sha256:hash,size:100,notes:'',environment:'dev',downloadPath:'/system/mobile-release/'+hash+'/content'};
const slots=[],effects=[];let cursor=0,result,listener,id,options,finish,fail,deleted=0,installed=0,cancelled=0,digests=0,reads=0,signatureChecks=0;
const same=(a,b)=>a&&b&&a.length===b.length&&a.every((v,i)=>Object.is(v,b[i]));
const react={useState:value=>{const i=cursor++;if(!(i in slots))slots[i]=typeof value==='function'?value():value;return[slots[i],next=>slots[i]=typeof next==='function'?next(slots[i]):next]},useRef:value=>{const i=cursor++;return slots[i]??={current:value}},useCallback:(fn,deps)=>{const i=cursor++;if(!same(slots[i]?.deps,deps))slots[i]={deps,value:fn};return slots[i].value},useEffect:(fn,deps)=>{const i=cursor++;if(!same(slots[i]?.deps,deps))effects.push(()=>{slots[i]?.cleanup?.();slots[i]={deps,cleanup:fn()}})}};
const bridge={download:(requestId,value)=>{id=requestId;options=value;return new Promise((resolve,reject)=>{finish=()=>{shared.files.set(value.uri,bytes);resolve({uri:value.uri,sha256:value.sha256,size:value.size,connections:4})};fail=reject})},cancelDownload:()=>{cancelled++;fail?.(Error('cancelled'))},verify:async()=>{signatureChecks++;return true}};
class File{constructor(_dir,name){this.name=name;this.uri='file:///cache/app-updates/'+name}get exists(){return shared.files.has(this.uri)}get size(){return shared.files.get(this.uri)?.length??0}create(){shared.files.set(this.uri,Buffer.alloc(0))}info(){if(!this.exists)return{exists:false};let meta=shared.metadata.get(this.uri);if(!meta){meta={modificationTime:1700000000000,creationTime:1700000000000};shared.metadata.set(this.uri,meta)}return{exists:true,size:this.size,...meta}}async digest(algorithm){assert.equal(algorithm,'SHA-256');digests++;return createHash('sha256').update(shared.files.get(this.uri)).digest('hex')}open(mode){if(mode!=='read')throw Error('JS file writing must not run on native path');let offset=0;return{readBytes:async n=>{reads++;const part=shared.files.get(this.uri).subarray(offset,offset+n);offset+=part.length;return part},close(){}}}delete(){shared.files.delete(this.uri);deleted++}async preview(){installed++}}
class Directory{get exists(){return true}create(){}list(){return[...shared.files.keys()].map(uri=>new File(this,uri.split('/').at(-1)))}}
const preferences={readPreference:async(scope,key)=>shared.preferences.get(scope+'|'+key)||null,savePreference:async(scope,key,value)=>shared.preferences.set(scope+'|'+key,value)};
const fileSystem={File,Directory,Paths:{cache:'cache'},FileMode:{ReadOnly:'read'}};
const cacheExports={};vm.runInNewContext(ts.transpileModule(readFileSync(new URL('../src/package-cache.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{exports:cacheExports,require:name=>({'expo-file-system':fileSystem,'./core/preferences':preferences,'./core/package-cache':cacheCore}[name])});
const api=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>new Response(JSON.stringify({code:200,data:release}),{headers:{'Content-Type':'application/json'}}));api.authenticate('test');
const mocks={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Platform:{OS:'android'},NativeModules:{CmvrApkVerification:bridge},DeviceEventEmitter:{addListener:(_name,fn)=>{listener=fn;return{remove(){listener=null}}}},AppState:{addEventListener:()=>({remove(){}})}},'expo-constants':{default:{expoConfig:{extra:{environment:'dev'}}}},'expo-application':{nativeBuildVersion:'9'},'expo-file-system':fileSystem,'expo/fetch':{},'./core/package-update':core,'./core/native-package-download':native,'./core/preferences':preferences,'./core/package-cache':cacheCore,'./package-cache':cacheExports,'./ui':{},'./typography':{},'./UpdateNotes':{UpdateNotes:'UpdateNotes'}};
const code=ts.transpileModule(readFileSync(new URL('../src/PackageUpdates.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText,exports={};vm.runInNewContext(code,{exports,require:name=>Object.hasOwn(mocks,name)?mocks[name]:require(name),AbortController,Date,Number,Math,setTimeout,clearTimeout});
const render=()=>{cursor=0;result=exports.usePackageUpdates(api,scope,true);while(effects.length)effects.shift()();return result};
return{render,api,release,shared,emit:(phase,bytes)=>listener?.({id,phase,bytes,total:100,connections:4}),finish:()=>finish(),options:()=>options,state:()=>({deleted,installed,cancelled,digests,reads,signatureChecks}),get:()=>result};
}
const settle=()=>new Promise(r=>setTimeout(r,5));
test('update hook uses the native engine, renders real progress and installs only after native verification',async()=>{
const h=setup();h.render();await settle();let c=h.render();assert.equal(c.release.versionCode,10);c.download();await settle();
assert.equal(h.options().headers.Authorization,'Bearer test');h.emit('downloading',42);c=h.render();assert.equal(c.progress,42);assert.equal(c.transfer.connections,4);assert.equal(c.phase,'downloading');
h.emit('verifying',80);c=h.render();assert.equal(c.phase,'verifying');assert.equal(c.verifyProgress,80);assert.equal(h.state().installed,0);
h.finish();await settle();c=h.render();assert.equal(c.phase,'ready');assert.equal(c.progress,100);c.install();await settle();assert.equal(h.state().installed,1);assert.equal(h.state().deleted,0);
});
test('account change cancels the active native transfer and discards its partial file',async()=>{
const h=setup();h.render();await settle();h.render().download();await settle();h.emit('downloading',42);h.api.clear();await settle();const c=h.render();assert.equal(c.phase,'idle');assert.ok(h.state().cancelled>0);assert.equal(h.state().deleted,1);assert.equal(h.state().installed,0);
});
test('completed download survives a full hook restart and goes straight to install without network download',async()=>{
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();assert.equal(h.render().phase,'ready');
const restarted=setup(h.shared);restarted.render();await settle();const c=restarted.render();assert.equal(c.phase,'ready');assert.equal(c.progress,100);assert.equal(restarted.options(),undefined);assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);assert.equal(restarted.state().signatureChecks,0);c.install();await settle();assert.equal(restarted.state().installed,1);assert.equal(restarted.state().digests,0);assert.equal(restarted.state().signatureChecks,1);
});
test('complete packages from the previous implementation are recovered even without a saved download record',async()=>{
const h=setup();const name=h.release.sha256+'-123-abc.apk';h.shared.files.set('file:///cache/app-updates/'+name,Buffer.alloc(100,7));h.render();await settle();assert.equal(h.render().phase,'ready');assert.equal(h.options(),undefined);assert.equal(h.state().digests,1);assert.equal(h.state().reads,0);
});
test('old completion records migrate using one native hash, then restart without rereading the APK',async()=>{
const h=setup(),name=h.release.sha256+'-123-abc.apk';h.shared.files.set('file:///cache/app-updates/'+name,Buffer.alloc(100,7));h.shared.preferences.set('one|downloaded-package',cacheCore.savedPackage(h.release,name));
h.render();await settle();assert.equal(h.render().phase,'ready');assert.equal(h.state().digests,1);assert.equal(h.state().reads,0);assert.equal(h.shared.preferences.get('one|downloaded-package').schema,2);
const restarted=setup(h.shared);restarted.render();await settle();assert.equal(restarted.render().phase,'ready');assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);
});
test('changed metadata revalidates the file and corruption never bypasses the recorded completion',async()=>{
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();h.render();const uri=h.options().uri;
h.shared.metadata.get(uri).modificationTime++;
const changed=setup(h.shared);changed.render();await settle();assert.equal(changed.render().phase,'ready');assert.equal(changed.state().digests,1);
h.shared.files.set(uri,Buffer.alloc(100,8));h.shared.metadata.get(uri).modificationTime++;
const corrupted=setup(h.shared);corrupted.render();await settle();assert.equal(corrupted.render().phase,'idle');assert.equal(corrupted.state().digests,1);assert.equal(corrupted.state().installed,0);
});
test('changing a ready file before installation is detected and never opens the installer',async()=>{
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();const c=h.render(),uri=h.options().uri;
h.shared.files.set(uri,Buffer.alloc(100,8));h.shared.metadata.get(uri).modificationTime++;c.install();await settle();assert.equal(h.render().phase,'idle');assert.equal(h.state().installed,0);assert.equal(h.state().signatureChecks,0);assert.match(h.render().error,/变化/);
});
test('truncated, corrupted or missing files never restore as ready',async()=>{
for(const bad of [null,Buffer.alloc(99,7),Buffer.alloc(100,8)]){const h=setup();if(bad)h.shared.files.set('file:///cache/app-updates/'+h.release.sha256+'-123-abc.apk',bad);h.render();await settle();assert.equal(h.render().phase,'idle');assert.equal(h.state().installed,0);}
});
test('ignore persists across restarts, manual check still opens the version, newer versions notify again',async()=>{
const h=setup();h.render();await settle();let c=h.render();assert.equal(c.visible,true);c.ignoreVersion();await settle();c=h.render();assert.equal(c.visible,false);assert.equal(c.ignored,true);
const restarted=setup(h.shared);restarted.render();await settle();c=restarted.render();assert.equal(c.visible,false);assert.equal(c.ignored,true);c.check();await settle();c=restarted.render();assert.equal(c.visible,true);assert.equal(c.release.versionCode,10);
const newer=setup(h.shared,'one',11);newer.render();await settle();assert.equal(newer.render().visible,true);assert.equal(newer.render().ignored,false);
const otherUser=setup(h.shared,'two');otherUser.render();await settle();assert.equal(otherUser.render().visible,true);
});
test('ignoring a downloaded version does no file work on startup and manual check reuses its verification',async()=>{
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();h.render().ignoreVersion();await settle();
const restarted=setup(h.shared);restarted.render();await settle();let c=restarted.render();assert.equal(c.visible,false);assert.equal(c.ignored,true);assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);
c.check();await settle();c=restarted.render();assert.equal(c.visible,true);assert.equal(c.phase,'ready');assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);
});