You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudPageBootstrapBehaviorT...

127 lines
6.8 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const source = (await readFile(new URL('../public/cloud/app.js', import.meta.url), 'utf8'))
.replaceAll('import.meta.url', JSON.stringify('https://panel.example.test/cloud/app.js?v=fixture'))
.replaceAll('import(', 'loadModule(');
const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
async function start(taskModule, pageModule) {
const requested = [];
const nodes = new Map(['cloud-page-error', 'panel-task-state'].map(id => [id, { textContent: '', hidden: true }]));
vm.runInNewContext(source, {
URL,
document: { body: { dataset: { cloudPage: 'deploy' } }, getElementById: id => nodes.get(id) },
loadModule: async href => {
const path = new URL(href).pathname;
requested.push(path);
return path === '/cloud/task-center.js' ? taskModule() : pageModule();
},
});
await tick();
return { requested, nodes };
}
{
const task = deferred();
let pageReady = false, taskReady = false;
const test = await start(() => task.promise, () => ({ initialize() { pageReady = true; } }));
assert.equal(pageReady, true, 'A pending task-center module blocks the page.');
assert(test.requested.includes('/cloud/deploy.js'));
task.resolve({ initializeTaskCenter() { taskReady = true; } });
await tick();
assert.equal(taskReady, true);
}
{
let pageReady = false;
const test = await start(() => Promise.reject(new Error('fixture task download failure')),
() => ({ initialize() { pageReady = true; } }));
assert.equal(pageReady, true, 'A failed task-center download prevents page initialization.');
assert.equal(test.nodes.get('cloud-page-error').textContent, '');
assert.match(test.nodes.get('panel-task-state').textContent, /任务中心/);
}
{
let taskReady = false;
const test = await start(() => ({ initializeTaskCenter() { taskReady = true; } }),
() => ({ initialize: async () => { throw new Error('fixture page failure'); } }));
assert.equal(taskReady, true);
assert.equal(test.nodes.get('cloud-page-error').textContent, 'fixture page failure',
'An asynchronous page initialization error escapes the shared error handler.');
}
const runtime = await readFile(new URL('../public/cloud/runtime.js', import.meta.url), 'utf8');
const session = runtime.slice(runtime.indexOf('async function initializeSession('), runtime.indexOf('async function selectVmByApiId('));
{
const vpcs = await readFile(new URL('../public/cloud/vpcs.js', import.meta.url), 'utf8');
const initialize = vpcs.slice(vpcs.indexOf('export async function initialize()')).replace('export ', '');
const bootstrap = { user: { user_id: '7', csrf_token: 'fixture' }, items: [], instances: [], regions: [] };
let rendered = false;
const context = vm.createContext({ state: {}, readBootstrap: () => bootstrap,
applyCloudUser() {}, api() { throw Error('Unexpected first-paint session or library fetch'); },
byId: () => ({ addEventListener() {} }), apply() { rendered = true; },
setPageStatus() {}, bindBatchConfirmation() {}, createVpc() {}, routeChanged() {},
window: { addEventListener() {} }, location: { assign() {} }, showError(id, message) { throw Error(message); },
});
vm.runInContext(session + '\n' + initialize, context);
await vm.runInContext('initialize()', context);
assert.equal(rendered, true, 'VPC bootstrap requires an additional session or library request.');
}
{
const isos = await readFile(new URL('../public/cloud/iso-images.js', import.meta.url), 'utf8');
const apply = isos.slice(isos.indexOf('function applyIsoPayload('), isos.indexOf('function taskFailureMessage('));
const initialize = isos.slice(isos.indexOf('export async function initialize()')).replace('export ', '');
const bootstrap = { user: { user_id: '7' }, isos: [{ id: 'iso-one' }], can_import: false,
active_import_job: { task_id: '41', completed: false } };
const pageState = { isos: [], importObserver: null };
let observed = '', rendered = false;
const context = vm.createContext({ state: {}, pageState, readBootstrap: () => bootstrap,
applyCloudUser() {}, api() { throw Error('Unexpected initial ISO request'); },
byId: () => ({ addEventListener() {} }), bindPageCleanup() {},
renderIsos() { rendered = true; }, taskUrl: receipt => receipt.status_url,
setImportStatus() {}, updateImportAvailability() {}, watchImport(receipt) { observed = receipt.task_id; },
importIso() {}, window: { addEventListener() {} }, location: { assign() {} },
showError(id, message) { throw Error(message); },
});
vm.runInContext(session + '\n' + apply + '\n' + initialize, context);
await vm.runInContext('initialize()', context);
assert.equal(rendered, true);
assert.equal(pageState.canImport, false);
assert.equal(observed, '41', 'ISO hydration failed to observe the original in-flight task.');
}
{
const sales = runtime.slice(runtime.indexOf('function saleRegions('), runtime.indexOf('function setDeploymentStepEnabled('));
const pricing = runtime.slice(runtime.indexOf('function selectedSaleOffer('), runtime.indexOf('function updateCreateAvailability('));
const openCreate = runtime.slice(runtime.indexOf('async function openCreate('), runtime.indexOf('async function loadGlobalTemplates('));
const nodes = new Map();
const byId = id => {
if (!nodes.has(id)) nodes.set(id, { value: '', checked: false, dataset: {}, classList: { toggle() {} }, addEventListener() {} });
return nodes.get(id);
};
byId('vm-automatic-backup').checked = true;
const bootstrap = { regions: [{ id: 1 }], lines: [{ id: 1, region_id: 1, is_default: true }],
offers: [{ id: 1, region_id: 1, line_id: 1, currency: 'USD', sellable: true, price: '10.00', backup_price: '2.00' }],
default_offer_id: 1, templates: [], ssh_keys: [] };
const context = vm.createContext({ state: { regions: [], lines: [], offers: [], templates: [], selectedKeys: {} }, byId,
bootstrapItems: (value, key) => value[key] || [], showError() {},
renderRegionPicker() {}, renderLinePicker() {}, renderOfferPicker() {}, renderTemplateCatalog() {}, renderKeyCards() {},
setDeploymentStepEnabled() {}, updateCreateAvailability() {}, formatUsd: value => `$${Number(value).toFixed(2)} USD`,
});
vm.runInContext(sales + '\n' + pricing + '\n' + openCreate, context);
context.bootstrap = bootstrap;
await vm.runInContext('openCreate(bootstrap)', context);
assert.equal(byId('vm-automatic-backup').checked, true, 'Hydration clears a backup choice made while the module was loading.');
assert.equal(byId('vm-order-total-price').textContent, '$12.00 USD');
}
console.log('Independent page/task boot, embedded VPC/ISO hydration, original task resumption and deployment selection preservation passed.');