test-advanced-acceptance.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /** 离线执行真实验收分支;文件、云端、CDP、ADB 均由内存夹具替换。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import vm from 'node:vm';
  5. import assert from 'node:assert/strict';
  6. import { createHash } from 'node:crypto';
  7. import { test } from 'node:test';
  8. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
  9. const runnerSource = fs.readFileSync(new URL('./verify-new-account.mjs', import.meta.url), 'utf8')
  10. .replace(/^import[^\n]*\n/gm, '');
  11. const oldIds = ['agent-node-app-trial', 'agent-node-app-original'];
  12. const originalRestore = { attempted: true, at: '2026-11-29T06:00:00.000Z', target: 'new-job/原恢复动作', restartedAt: '2026-11-29T06:00:01.000Z' };
  13. const originalRestoreFailure = { stage: 'advanced-restore', message: '原进度按钮定位等待超时,保留首次失败', at: '2026-11-29T06:01:00.000Z' };
  14. function fixture({ stage = 'advanced-status', unavailableCdp = false, page = 'valid', terminal = false, source = runnerSource, alter = () => {} } = {}) {
  15. const job = { jobId: 'new-job', agentId: 'NewAgent', planCode: 'advanced', status: 'provisioning', stage: 'prepare', steps: [{ stage: 'prepare', status: 'running' }], currentStep: { stage: 'prepare', status: 'running' } };
  16. const oldJob = { jobId: 'old-job', agentId: 'original', planCode: 'advanced', status: 'ready' };
  17. const data = {
  18. job,
  19. jobs: [job, oldJob],
  20. agents: [...oldIds, 'agent-node-app-newagent'].map(agentId => ({ agentId })),
  21. state: {
  22. phone: '18100000000', userId: 'fixture', run: 'offline-advanced', checks: [], assets: [],
  23. trial: { agentId: oldIds[0] },
  24. actions: {
  25. originalProof: { attempted: true, proof: { completion: 'retained-original-reaction' } },
  26. advancedCreate: { attempted: true, jobId: job.jobId, jobsBefore: [oldJob], agentIdsBefore: [...oldIds], latestStatus: { ...job }, statusObservations: ['old-observation.json'] },
  27. },
  28. },
  29. };
  30. if (terminal) { data.job.status = 'ready'; data.jobs[0].status = 'ready'; }
  31. alter(data);
  32. let state = structuredClone(data.state), pending;
  33. const calls = [], writes = new Map();
  34. const fakeFs = {
  35. existsSync: () => true,
  36. openSync() { calls.push({ type: 'lock' }); return 7; },
  37. closeSync() { calls.push({ type: 'close-lock' }); },
  38. unlinkSync() { calls.push({ type: 'unlock' }); },
  39. readFileSync(file) {
  40. if (String(file).endsWith('state.json')) { calls.push({ type: 'read-ledger' }); return JSON.stringify(state); }
  41. return JSON.stringify({ token: 'offline-only', userId: 'fixture' });
  42. },
  43. writeFileSync(file, value) {
  44. if (String(file).endsWith('state.json.next')) pending = JSON.parse(value);
  45. else if (typeof file === 'string') writes.set(file, value);
  46. },
  47. renameSync() { assert.ok(pending, '内存账本需先写后替换'); state = pending; pending = undefined; },
  48. };
  49. const fetchImpl = async (_url, options) => {
  50. const { id, params } = JSON.parse(options.body);
  51. calls.push({ type: 'api', id, params });
  52. let response;
  53. if (id === 'VtW1GT93Ax' && params.op === 'list') response = { items: data.jobs };
  54. else if (id === 'VtW1GT93Ax' && params.op === 'status') response = data.job;
  55. else if (id === 'xlosi3m46q' && params.op === 'query') response = { agents: data.agents };
  56. else throw Error('离线夹具禁止申请、重试或其他业务接口:' + id + '/' + params.op);
  57. return { ok: true, json: async () => ({ code: 200, ...structuredClone(response) }) };
  58. };
  59. const location = { pathname: '/mobile/messages', search: '' };
  60. const events = [];
  61. const changeRoute = url => {
  62. const parsed = new URL(url, 'https://localhost');
  63. location.pathname = parsed.pathname; location.search = parsed.search;
  64. if (location.pathname === '/provision') events.push({ method: 'Network.responseReceived', params: { requestId: 'page-status', response: { url: 'https://server.fmode.cn/api/functions' } } });
  65. };
  66. const button = { innerText: terminal ? '查看我的容器' : '查看开通进度', disabled: false, getClientRects: () => [{}], scrollIntoView() {}, getBoundingClientRect: () => ({ x: 0, y: 0, width: 100, height: 40 }) };
  67. // 与 MbPlansPage 模板一致:section.plans-job 与 div.plans-job-actions 是兄弟。
  68. const plansSection = { innerText: terminal ? '已就绪\n容器创建由平台自动完成' : '正在开通\n容器创建由平台自动完成', querySelector: () => null, querySelectorAll: () => [] };
  69. const plansActions = { get innerText() { return button.innerText; }, querySelector: selector => selector === 'button' ? button : null, querySelectorAll: selector => selector === 'button' ? [button] : [] };
  70. const pageText = () => location.pathname === '/plans' ? plansSection.innerText + '\n' + plansActions.innerText
  71. : location.pathname !== '/provision' ? '消息 我的容器'
  72. : page === 'blank' ? '' : page === 'error' ? '加载开通状态失败\n重新加载\n返回套餐' : terminal ? '容器已就绪' : '正在创建容器\n准备环境\n开通在服务器上进行';
  73. const element = { get innerText() { return pageText(); }, getClientRects: () => [{}] };
  74. const document = {
  75. body: { get innerText() { return pageText(); } },
  76. documentElement: { scrollWidth: 360 },
  77. querySelector(selector) {
  78. if (/app-mobile-shell|app-m-tab-bar|app-m-drawer/.test(selector)) return null;
  79. if (location.pathname === '/plans' && selector === '.plans-job') return plansSection;
  80. if (location.pathname === '/plans' && selector === '.plans-job-actions') return plansActions;
  81. if (location.pathname === '/plans' && selector === '.plans-job-actions button') return button;
  82. if (location.pathname === '/plans' && selector === '.plans-job button') return null;
  83. if (location.pathname === '/provision' && page !== 'blank' && /app-dk-provision-page|app-mb-provision-page|\.prov/.test(selector)) return element;
  84. if (location.pathname === '/provision' && page === 'valid' && /progressbar|prov-stage|prov-title|prov-step/.test(selector)) return element;
  85. return null;
  86. },
  87. querySelectorAll(selector) {
  88. if (selector === 'input') return [];
  89. if (selector === 'button' || selector === '.plans-job-actions button') return location.pathname === '/plans' ? [button] : [];
  90. if (selector === '.plans-job button') return [];
  91. if (/prov-stage/.test(selector)) return page === 'valid' ? Array(6).fill(element) : [];
  92. return [];
  93. },
  94. };
  95. const context = vm.createContext({ location, document, innerWidth: 360, innerHeight: 780, URLSearchParams,
  96. localStorage: { getItem: key => key === 'fmode_me' ? JSON.stringify({ id: 'fixture' }) : key === 'fmode_active_provision_job' ? 'new-job' : 'offline-only' },
  97. history: { pushState: (_state, _title, url) => changeRoute(url) }, dispatchEvent() {}, PopStateEvent: class {},
  98. });
  99. const c = {
  100. events,
  101. async evaluate(fn, value) { calls.push({ type: 'evaluate', source: fn.toString() }); return vm.runInContext('(' + fn.toString() + ')', context)(value); },
  102. async waitFor(fn, value) { assert.ok(await this.evaluate(fn, value), '离线页面等待条件未满足:' + fn.toString()); },
  103. async send(method) {
  104. calls.push({ type: 'cdp', method });
  105. if (method === 'Network.getResponseBody') return { body: JSON.stringify({ code: 200, ...data.job }), base64Encoded: false };
  106. if (method === 'Input.dispatchTouchEvent' && location.pathname === '/plans') changeRoute('/provision?jobId=new-job');
  107. return {};
  108. },
  109. async screenshot() {},
  110. close() { calls.push({ type: 'close-cdp' }); },
  111. };
  112. const connect = async () => {
  113. calls.push({ type: 'connect-cdp' });
  114. if (unavailableCdp) throw Error('CDP unavailable');
  115. return c;
  116. };
  117. const spawn = (command, args) => {
  118. assert.equal(command, 'adb', '不得运行其他子进程');
  119. calls.push({ type: 'adb', args });
  120. return { status: 0, stdout: args.includes('pidof') ? '1234' : '', stderr: '' };
  121. };
  122. const execute = new AsyncFunction('fs', 'path', 'assert', 'createHash', 'connectWebView', 'spawnSync', 'process', 'console', 'recordProgress', 'fetch', 'captureNativeScreenshot', source);
  123. return {
  124. calls, writes, data, get state() { return state; },
  125. async run() {
  126. try {
  127. await execute(fakeFs, path, assert, createHash, connect, spawn,
  128. { argv: ['node', 'runner', '--stage=' + stage, '--phone=18100000000'], pid: 7, cwd: () => process.cwd() },
  129. { log() {} }, () => {}, fetchImpl, () => {});
  130. } finally {
  131. assert.ok(calls.find(x => x.type === 'unlock'), '成功和错误均需释放自己持有的账本锁');
  132. assert.deepEqual(state.actions.originalProof, data.state.actions.originalProof, '历史回执应保持不变');
  133. }
  134. },
  135. };
  136. }
  137. test('恢复夹具任务说明区和操作区与真实移动模板保持兄弟层级', () => {
  138. const template = fs.readFileSync(new URL('../src/app/mobile/pages/plans/plans.ts', import.meta.url), 'utf8');
  139. assert.match(template, /<section class="plans-job"[\s\S]*?<\/section>\s*<div class="plans-job-actions">/);
  140. });
  141. test('恢复夹具能够拒绝把操作按钮错定位到任务说明区', async () => {
  142. const source = runnerSource.replaceAll('.plans-job-actions button', '.plans-job button');
  143. assert.notEqual(source, runnerSource, '需实际模拟错误的子元素定位');
  144. const run = fixture({ stage: 'advanced-restore', source });
  145. await assert.rejects(() => run.run(), /离线页面等待条件未满足/);
  146. assert.notEqual(run.state.actions.advancedRestore?.receipt?.restored, true);
  147. });
  148. test('advanced-restore-readback 沿用原重启回执且不再执行任何 ADB 动作', async () => {
  149. const run = fixture({ stage: 'advanced-restore-readback', alter(data) {
  150. data.state.actions.advancedRestore = { ...originalRestore };
  151. data.state.lastFailure = { ...originalRestoreFailure };
  152. } });
  153. await run.run();
  154. assert.equal(run.calls.filter(x => x.type === 'adb').length, 0);
  155. assert.equal(run.state.actions.advancedRestore.at, originalRestore.at);
  156. assert.equal(run.state.actions.advancedRestore.restartedAt, originalRestore.restartedAt);
  157. assert.equal(run.state.actions.advancedRestore.receipt.restored, true);
  158. assert.equal(run.state.actions.advancedRestore.receipt.jobId, 'new-job');
  159. assert.deepEqual(run.state.lastFailure, originalRestoreFailure, '补查成功不能抹掉首次失败');
  160. assert.ok(run.calls.some(x => x.type === 'cdp' && x.method === 'Network.getResponseBody'));
  161. });
  162. for (const [label, original] of [
  163. ['缺少原恢复动作', undefined],
  164. ['缺少重启回执', { attempted: true, at: originalRestore.at, target: originalRestore.target }],
  165. ['原恢复已确认', { ...originalRestore, confirmedAt: '2026-11-29T06:02:00.000Z', receipt: { restored: true, jobId: 'new-job' } }],
  166. ]) {
  167. test('advanced-restore-readback 拒绝' + label + '并且不执行 ADB 或接口查询', async () => {
  168. const run = fixture({ stage: 'advanced-restore-readback', alter(data) {
  169. if (original) data.state.actions.advancedRestore = structuredClone(original);
  170. } });
  171. await assert.rejects(() => run.run(), /原恢复|重启|未完成|回执/);
  172. assert.equal(run.calls.filter(x => x.type === 'adb' || x.type === 'api').length, 0);
  173. assert.deepEqual(run.state.actions.advancedRestore, original);
  174. });
  175. }
  176. test('advanced-status 在 CDP 不可用时仍只读回验原 job 和独立新资产', async () => {
  177. const run = fixture({ unavailableCdp: true });
  178. await run.run();
  179. assert.equal(run.calls.filter(x => x.type === 'connect-cdp').length, 0);
  180. assert.ok(run.calls.some(x => x.type === 'api' && x.params.op === 'status' && x.params.jobId === 'new-job'));
  181. assert.equal(run.state.actions.advancedCreate.latestStatus.jobId, 'new-job');
  182. assert.ok(run.state.actions.advancedCreate.statusObservations.includes('old-observation.json'));
  183. assert.ok(run.calls.findIndex(x => x.type === 'lock') < run.calls.findIndex(x => x.type === 'read-ledger'));
  184. });
  185. for (const [label, alter] of [
  186. ['错误套餐', data => { data.job.planCode = 'enterprise'; }],
  187. ['状态回包错 job', data => { data.job = { ...data.job, jobId: 'other-job' }; }],
  188. ['复用旧 agent', data => { data.job.agentId = 'Original'; }],
  189. ['原资产丢失', data => { data.agents = data.agents.filter(x => x.agentId !== oldIds[0]); }],
  190. ]) {
  191. test('advanced-status 拒绝' + label, async () => {
  192. const run = fixture({ unavailableCdp: true, alter });
  193. await assert.rejects(() => run.run(), error => error.code === 'ERR_ASSERTION' && !/CDP|离线夹具/.test(error.message));
  194. assert.equal(run.state.actions.advancedCreate.statusObservations.length, 1, '失败不得追加通过回执');
  195. assert.ok(run.state.lastFailure, '失败原因需保留到账本');
  196. });
  197. }
  198. for (const page of ['blank', 'error']) {
  199. test('advanced-restore 不将' + (page === 'blank' ? '空白页' : '加载失败页') + '记为恢复成功', async () => {
  200. const run = fixture({ stage: 'advanced-restore', page });
  201. await assert.rejects(() => run.run(), /离线页面等待条件未满足|进阶|等待|恢复|加载/);
  202. assert.ok(run.calls.some(x => x.type === 'adb' && x.args.includes('force-stop')), '需实际进入内存模拟的强停恢复分支');
  203. assert.ok(run.calls.some(x => x.type === 'evaluate' && x.source.includes('app-dk-provision-page')), '负例应走到实际等待页核对处');
  204. assert.notEqual(run.state.actions.advancedRestore?.receipt?.restored, true);
  205. assert.ok(run.state.lastFailure, '恢复失败需保留原因');
  206. });
  207. }
  208. for (const terminal of [false, true]) {
  209. test('advanced-restore 可恢复原任务' + (terminal ? '恰好终结的真实终态' : '真实在途进度'), async () => {
  210. const run = fixture({ stage: 'advanced-restore', terminal });
  211. await run.run();
  212. assert.equal(run.state.actions.advancedRestore.receipt.restored, true);
  213. assert.equal(run.state.actions.advancedRestore.receipt.jobId, 'new-job');
  214. assert.equal(run.state.actions.advancedRestore.receipt.status, terminal ? 'ready' : 'provisioning');
  215. assert.ok(run.calls.some(x => x.type === 'cdp' && x.method === 'Network.getResponseBody'), '恢复必须依赖页面真实状态回包');
  216. assert.equal(run.state.actions.advancedRestore.receipt.creates, 0);
  217. });
  218. }