governance-smoke.test.cjs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. 'use strict';
  2. const test = require('node:test');
  3. const assert = require('node:assert/strict');
  4. const fs = require('node:fs');
  5. const path = require('node:path');
  6. const root = path.resolve(__dirname, '..');
  7. const util = require('../utils/util.js');
  8. test('登录和会话校验保留微信 SDK 合约', async t => {
  9. t.after(() => { delete global.wx; });
  10. global.wx = { login: opt => opt.success({ code: 'synthetic-code' }), checkSession: opt => opt.success() };
  11. assert.deepEqual(await util.login(), { code: 'synthetic-code' });
  12. assert.equal(await util.checkSession(), true);
  13. global.wx.checkSession = opt => opt.fail();
  14. await assert.rejects(util.checkSession(), reason => reason === false);
  15. });
  16. test('页面入口和分享可解析,移除的传输函数不再导出', t => {
  17. t.after(() => { delete global.Page; delete global.wx; });
  18. const manifest = require('../app.json');
  19. const pages = [...manifest.pages, ...manifest.subpackages.flatMap(pkg => pkg.pages.map(p => pkg.root + '/' + p))];
  20. for (const page of pages) {
  21. for (const ext of ['.js', '.wxml']) assert.ok(fs.existsSync(path.join(root, page + ext)));
  22. }
  23. let page, title;
  24. global.Page = definition => { page = definition; };
  25. global.wx = { setNavigationBarTitle: value => { title = value.title; } };
  26. require('../yuban/pages/index/index.js');
  27. page.onLoad({});
  28. assert.equal(title, '语伴');
  29. assert.ok(pages.includes(page.onShareAppMessage().path));
  30. assert.equal(Object.hasOwn(util, 'sentRes'), false);
  31. });
  32. test('通用业务页经已登记登录页恢复原目标,保留查询与片段', async () => {
  33. const vm = require('node:vm');
  34. const target = require('../utils/web-view-target');
  35. const manifest = require('../app.json');
  36. const routes = new Set([...manifest.pages,...manifest.subpackages.flatMap(pkg=>pkg.pages.map(page=>pkg.root+'/'+page))]);
  37. const history = [];
  38. const storage = new Map();
  39. let user, currentPage;
  40. const app = {Parse:{User:{current:()=>user}},globalData:{company:'synthetic'},checkAuth:async()=>Boolean(user)};
  41. const wx = {
  42. getStorageSync:key=>storage.get(key),setStorageSync:(key,value)=>storage.set(key,value),
  43. redirectTo:({url})=>{const address=new URL(url,'https://local.invalid');assert.ok(routes.has(address.pathname.slice(1)));history.push(address);},
  44. showToast(){},getLaunchOptionsSync:()=>({scene:1001}),
  45. };
  46. const load = file => {
  47. const context = vm.createContext({
  48. wx,getApp:()=>app,getCurrentPages:()=>[currentPage],console:{log(){},debug(){},error(){},warn(){}},
  49. require:name=>{
  50. if (name.endsWith('web-view-target')) return target;
  51. if (name==='./share') {
  52. const module={exports:{}};
  53. const code=fs.readFileSync(path.join(root,'common-page/pages/web-view/share.js'),'utf8');
  54. vm.runInContext('(function(module,exports){'+code+'})',context)(module,module.exports);
  55. return module.exports;
  56. }
  57. return {};
  58. },
  59. Page:def=>{currentPage={...def,data:{...def.data},setData(value){Object.assign(this.data,value);}};},
  60. });
  61. vm.runInContext(fs.readFileSync(path.join(root,file),'utf8'),context);
  62. return currentPage;
  63. };
  64. const original='https://www.yuban.co/user-profile/memory-cleanup?tab=people&label=a%26b#family';
  65. const web=load('common-page/pages/web-view/index.js');
  66. const opts={path:encodeURIComponent(original),source:'mini'};
  67. await web.onLoad(opts);
  68. const authRoute=history.pop();
  69. assert.equal(authRoute.pathname,'/components/app-auth/index');
  70. assert.equal(web.data.path,'');
  71. const expected=original.replace('#family','&source=mini#family');
  72. assert.equal(authRoute.searchParams.get('returnUrl'),expected);
  73. const auth=load('components/app-auth/index.js');auth.options=Object.fromEntries(authRoute.searchParams);
  74. user={id:'fixture-member',get:key=>({mobile:'fixture-mobile',nickname:'测试会员'})[key],getSessionToken:()=>'fixture-session'};
  75. await auth.getUserProfile();
  76. const returned=history.pop();assert.equal(returned.pathname,'/common-page/pages/web-view/index');
  77. assert.equal(returned.searchParams.get('path'),expected);
  78. const resumed=load('common-page/pages/web-view/index.js');
  79. await resumed.onLoad(Object.fromEntries(returned.searchParams));
  80. const final=new URL(resumed.data.path);
  81. assert.equal(final.pathname,'/user-profile/memory-cleanup');assert.equal(final.hash,'#family');
  82. assert.equal(final.searchParams.get('label'),'a&b');assert.equal(final.searchParams.get('source'),'mini');
  83. assert.equal(final.searchParams.has('token'),false);assert.equal(final.searchParams.has('userId'),false);assert.equal(final.searchParams.has('mobile'),false);
  84. });
  85. test('引导页会话信息与已有受控业务路径兼容', () => {
  86. const {readTarget,requestedTarget,withQuery}=require('../utils/web-view-target');
  87. const path='https://www.yuban.co/home?fromStartup=1&source=wechat-miniprogram#start';
  88. const url=new URL(requestedTarget({path:encodeURIComponent(path),skipAuth:'true',sessionToken:'fixture-session',mobile:'fixture-mobile'}));
  89. assert.equal(url.searchParams.has('sessionToken'),false);assert.equal(url.searchParams.has('mobile'),false);
  90. assert.equal(url.hash,'#start');assert.equal(url.searchParams.getAll('source').length,1);assert.equal(url.searchParams.has('skipAuth'),false);
  91. assert.equal(readTarget('%broken'),'');
  92. for(const name of ['products','cases','home']) {
  93. const legacy='https://app.fmode.cn/dev/pobingfeng/owner/nav/'+name+'?storeId=sample';
  94. assert.equal(readTarget(encodeURIComponent(legacy)),legacy);
  95. assert.equal(requestedTarget({path:legacy+'&token=sample-token&mobile=sample-mobile',source:'mini'}),legacy+'&source=mini');
  96. }
  97. });
  98. test('语伴引导与三条旧商城导航只传业务参数,保留 H5 支付回调', async () => {
  99. const vm=require('node:vm');
  100. const {requestedTarget}=require('../utils/web-view-target');
  101. let home,index,navigation;
  102. const wx={getStorageSync(){throw Error('Home must not read native identity');},redirectTo:options=>{navigation=options.url;}};
  103. vm.runInNewContext(fs.readFileSync(path.join(root,'yuban/components/home/index.js'),'utf8'),{Component:def=>{home=def.methods;},wx,require:()=>require('../utils/web-view-target')});
  104. function target(route) {
  105. const target=new URL(new URL(route,'https://local.invalid').searchParams.get('path'));
  106. for(const key of ['userId','mobile','token','sessionToken'])assert.equal(target.searchParams.has(key),false);
  107. return target;
  108. }
  109. const launch=target(home.buildWebViewPath.call(home));
  110. assert.equal(launch.pathname,'/home');assert.deepEqual([...launch.searchParams.keys()],['fromStartup','source']);
  111. wx.getStorageSync=()=>null;
  112. vm.runInNewContext(fs.readFileSync(path.join(root,'index.js'),'utf8'),{
  113. Page:def=>{index=def;},wx,require:()=>({default:{}}),requirePlugin:()=>({}),
  114. console:{log(){},error(){}},
  115. });
  116. for(const [method,itemKey,route] of [['redirectToProductDetail','productId','products'],['redirectToCaseDetail','caseId','cases'],['redirectToStoreWithPlan','planId','home']]){
  117. navigation=null;await index[method]('s&1','item?42','synthetic');
  118. const dest=target(navigation);assert.equal(dest.pathname,'/dev/pobingfeng/owner/nav/'+route);
  119. assert.equal(dest.searchParams.get(itemKey),'item?42');assert.equal(dest.searchParams.get('storeId'),'s&1');assert.equal(dest.searchParams.get('guestMode'),'true');
  120. }
  121. const pay='https://www.yuban.co/user-profile/membership-renewal?code=payment-code&state=payment-state&invite=keep';
  122. assert.equal(requestedTarget({path:pay+'&token=fixture'}),pay);
  123. assert.equal(requestedTarget({path:'https://www.yuban.co/home?sessionToken=fixture&invite=keep&code=old#part'}),'https://www.yuban.co/home?invite=keep#part');
  124. });