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/AdminTemplateStartupScriptB...

147 lines
6.6 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/admin.js', import.meta.url), 'utf8'))
.replace('void initialize();', '')
+ '\n;globalThis.__scripts = { startupScriptState, openStartupScript, closeStartupScript, saveStartupScript, loadCatalog };\n';
class Element {
constructor() {
this.value = ''; this.textContent = ''; this.children = []; this.dataset = {};
this.disabled = false; this.readOnly = false; this.open = false; this.isConnected = true;
this.listeners = new Map(); this.attributes = new Map();
}
append(...items) { this.children.push(...items); }
replaceChildren(...items) { this.children = items; }
addEventListener(name, listener) { this.listeners.set(name, listener); }
setAttribute(name, value) { this.attributes.set(name, value); }
showModal() { this.open = true; }
close() { this.open = false; }
focus() { this.focused = true; }
}
const flush = async () => { for (let turn = 0; turn < 20; turn += 1) await Promise.resolve(); };
const generation = '0123456789abcdef0123456789abcdef';
const entry = { id: 'debian-12-template', name: '<img src=x>', state: 'active', image_bytes: 1073741824, revision: 1, generation_token: generation };
const payload = { id: entry.id, startup_script: '#!/bin/bash\necho ready\n', revision: 2, generation_token: generation };
const submit = { preventDefault() {} };
function fixture(canManage = true) {
const elements = new Map();
const get = id => { if (!elements.has(id)) elements.set(id, new Element()); return elements.get(id); };
const root = new Element(); root.dataset = { canManage: canManage ? '1' : '0', cloudAdmin: 'templates' };
const requests = [];
const context = {
document: { getElementById: get, querySelector: () => root, createElement: () => new Element() },
window: { ADMIN_CSRF_TOKEN: 'csrf-token' },
location: { protocol: 'https:', hostname: 'panel.test', assign() {} },
Headers, TextEncoder,
fetch(path, options) { return new Promise(resolve => requests.push({ path, ...options, resolve })); },
};
vm.runInNewContext(source, context, { filename: 'admin.js' });
return {
...context.__scripts, get, requests,
async respond(request, data, status = 200) {
request.resolve({ status, ok: status >= 200 && status < 300, json: async () => data });
await flush();
},
};
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [entry] });
await loading;
const button = test.get('catalog-list').children[0].children
.find(item => item.textContent === '设置启动脚本');
assert.ok(button, 'Cloud template row has no startup-script control.');
const metadata = test.get('catalog-list').children[0].children
.find(item => item.className === 'cloud-admin-meta');
assert.match(metadata.textContent, /^已就绪 · .*1\.00 GiB$/);
const opening = button.listeners.get('click')();
assert.equal(test.get('template-startup-title').textContent, `启动脚本 · ${entry.name}`);
assert.equal(test.get('template-startup-save').disabled, true);
await test.respond(test.requests[1], payload);
await opening;
assert.equal(test.get('template-startup-script').value, payload.startup_script);
assert.equal(test.get('template-startup-save').disabled, false);
test.get('template-startup-script').value = '#!/bin/bash\r\necho "中文"\r\n';
const saving = test.saveStartupScript(submit);
const request = test.requests[2];
assert.equal(request.method, 'PATCH');
assert.equal(request.headers.get('X-CSRF-Token'), 'csrf-token');
assert.deepEqual(JSON.parse(request.body), {
script: '#!/bin/bash\necho "中文"\n',
expected_revision: 2,
generation_token: generation,
});
await test.respond(request, { ...payload, startup_script: '#!/bin/bash\necho "中文"\n', revision: 3 });
await saving;
assert.equal(test.startupScriptState.revision, 3);
test.closeStartupScript();
assert.equal(test.get('template-startup-script').value, '');
assert.equal(button.focused, true);
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [{
...entry,
state: 'importing',
image_bytes: 0,
replicas: [{ host_id: 7, state: 'pending', error_code: 'agent_unavailable', operation_id: 'operation-1234' }],
}] });
await loading;
const row = test.get('catalog-list').children[0];
const save = row.children.find(item => item.textContent === '保存名称');
const remove = row.children.find(item => item.textContent === '删除');
const startup = row.children.find(item => item.textContent === '设置启动脚本');
const metadata = row.children.find(item => item.className === 'cloud-admin-meta');
assert.equal(row.dataset.catalogState, 'importing');
assert.equal(save.disabled, true);
assert.equal(startup.disabled, true);
assert.equal(remove.disabled, false, 'An operator must retain access to the catalog deletion workflow.');
assert.match(metadata.textContent, /^导入中 · .*debian-12-template$/);
assert.match(row.children.at(-1).textContent, /^宿主机 #7 · 核对中 · agent_unavailable · operation-1234$/);
}
{
const test = fixture(false);
const opening = test.openStartupScript(entry, new Element());
await test.respond(test.requests[0], payload);
await opening;
assert.equal(test.get('template-startup-script').readOnly, true);
await test.saveStartupScript(submit);
assert.equal(test.requests.length, 1, 'Read-only administrator issued a PATCH.');
}
{
const test = fixture();
const opening = test.openStartupScript(entry, new Element());
await test.respond(test.requests[0], payload);
await opening;
for (const invalid of ['中'.repeat(10923), 'echo\0bad']) {
test.get('template-startup-script').value = invalid;
await test.saveStartupScript(submit);
assert.equal(test.requests.length, 1);
}
test.get('template-startup-script').value = 'draft';
const conflict = test.saveStartupScript(submit);
await test.respond(test.requests[1], { detail: '初始化脚本已被修改,请重新打开对话框' }, 409);
await conflict;
assert.equal(test.get('template-startup-script').value, 'draft');
assert.equal(test.startupScriptState.revision, 2);
test.get('template-startup-script').value = '';
const clearing = test.saveStartupScript(submit);
await test.respond(test.requests[2], { ...payload, startup_script: '', revision: 3 });
await clearing;
assert.match(test.get('template-startup-status').textContent, /停用/);
}
console.log('Admin startup-script dialog permissions, immutable generation CAS and validation passed.');