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

283 lines
13 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
import { mountAdminCatalogFilter } from '../public/cloud/admin-catalog-filter.js';
const adminSource = await readFile(new URL('../public/cloud/admin-catalog-runtime.js', import.meta.url), 'utf8');
const requestRuntimeSource = await readFile(
new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8');
const source = adminSource.slice(adminSource.indexOf('const root ='))
.replace('export { initialize };', '')
+ '\n;globalThis.__scripts = { startupScriptState, openStartupScript, closeStartupScript, saveStartupScript, loadCatalog, applyCatalogFilters, setCatalogFilter: filter => { catalogFilter = filter; } };\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; }
querySelectorAll(selector) {
return descendants(this).slice(1).filter(item => {
if (selector.startsWith('.')) return String(item.className || '').split(/\s+/).includes(selector.slice(1));
const key = selector.slice(6, -1).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
return Object.hasOwn(item.dataset || {}, key);
});
}
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
}
const flush = async () => { for (let turn = 0; turn < 20; turn += 1) await Promise.resolve(); };
const generation = '0123456789abcdef0123456789abcdef';
const entry = { id: 'debian-12-template', catalog_key: 'debian-12', version_label: '20261030', is_default: true, name: '<img src=x>', os_family: 'Debian', os_version: '12', state: 'active', image_bytes: 1073741824, sha256: 'a'.repeat(64), 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() {} };
const descendants = node => [node, ...(node?.children || []).flatMap(descendants)];
const findText = (node, text) => descendants(node).find(item => item.textContent === text);
const findClass = (node, className) => descendants(node).find(item => String(item.className || '').split(/\s+/).includes(className));
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() },
ADMIN_CSRF_TOKEN: 'a'.repeat(64),
VenixAdminDangerDialog: { confirm: async () => true },
taskUrl: value => value?.task_id && value?.status_url ? value.status_url : '',
location: { protocol: 'https:', hostname: 'panel.test', assign() {} },
Headers, TextEncoder, AbortController, setTimeout, clearTimeout,
fetch(path, options) { return new Promise(resolve => requests.push({ path, ...options, resolve })); },
};
context.window = context;
vm.runInNewContext(requestRuntimeSource, context, { filename: 'admin-request-runtime.js' });
vm.runInNewContext(source, context, { filename: 'admin-catalog-runtime.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 matrixEntry = {
...entry,
replica_summary: { hosts: 1, eligible: 1, ready: 0, repairable: 1, attention: 1 },
replicas: [{
host_id: 7, host_name: 'HKG-A', host_region: 'HongKong',
host_eligible: true, host_record_present: true, state: 'missing',
revision: 0, observed_revision: 0, exact: false,
repair_action: 'import', repair_reason: 'replica_missing',
}],
};
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [matrixEntry] });
await loading;
const repair = findText(test.get('catalog-list'), '补齐副本');
assert.ok(repair, 'A proven missing eligible replica has no repair control.');
const repairing = repair.listeners.get('click')();
await flush();
const request = test.requests[1];
assert.equal(request.path, '/api/v1/admin/cloud-templates/debian-12-template/replicas/7/repair');
assert.equal(request.method, 'POST');
assert.deepEqual(JSON.parse(request.body), {});
await test.respond(request, { scheduled: false });
await test.respond(test.requests[2], { templates: [{
...matrixEntry,
replica_summary: { hosts: 1, eligible: 1, ready: 1, repairable: 0, attention: 0 },
replicas: [{ ...matrixEntry.replicas[0], state: 'active', revision: 1, exact: true, repair_action: null, repair_reason: 'exact' }],
}] });
await repairing;
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [entry] });
await loading;
const list = test.get('catalog-list');
const button = findText(list, '启动脚本');
assert.ok(button, 'Cloud template row has no startup-script control.');
assert.equal(findText(list, '当前默认版本')?.textContent, '当前默认版本');
assert.equal(findText(list, '1.00 GiB')?.textContent, '1.00 GiB');
assert.match(findClass(list, 'cloud-template-version-card')?.dataset.catalogState, /^active$/);
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-Admin-CSRF-Token'), 'a'.repeat(64));
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, host_name: 'HKG-A', host_region: 'HongKong', host_eligible: true, host_record_present: true, state: 'pending', exact: false, repair_action: null, repair_reason: 'mutation_in_progress', error_code: 'agent_unavailable', operation_id: 'operation-1234' }],
}] });
await loading;
const row = findClass(test.get('catalog-list'), 'cloud-template-version-card');
const save = findText(row, '保存名称');
const remove = findText(row, '删除版本');
const startup = findText(row, '启动脚本');
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.ok(findText(row, '分发中'));
assert.ok(findText(row, '等待分发'));
assert.ok(findText(row, 'HKG-A'));
assert.match(findClass(row, 'cloud-template-diagnostic').textContent, /agent_unavailable/);
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [{
...entry,
state: 'delete_failed',
cleanup_reason: 'partial_delete',
replicas: [
{ host_id: 7, host_name: 'HKG-A', host_eligible: true, host_record_present: true, state: 'delete_failed', exact: false, repair_action: null, error_code: 'operation_failed' },
{ host_id: 8, host_name: 'HKG-B', host_eligible: true, host_record_present: true, state: 'delete_succeeded', exact: false, repair_action: null },
],
}] });
await loading;
const row = findClass(test.get('catalog-list'), 'cloud-template-version-card');
const cleanup = findText(row, '清理残留');
assert.ok(cleanup, 'A proven partial template has no cleanup control.');
assert.equal(cleanup.disabled, false);
assert.ok(findText(row, '删除失败'));
assert.ok(findText(row, '删除待核查'));
assert.ok(findText(row, '已删除'));
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [{
...entry, state: 'error', cleanup_reason: 'partial_import',
replicas: [{ host_id: 7, host_name: 'HKG-A', host_eligible: true, host_record_present: true, state: 'failed', exact: false, repair_action: null, repair_reason: 'failure_fenced' }],
}] });
await loading;
const row = findClass(test.get('catalog-list'), 'cloud-template-version-card');
assert.ok(findText(row, '失败并已锁定'));
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [
entry,
{
...entry,
id: 'debian-12-source-failed',
version_label: '20261030-failed',
is_default: false,
state: 'source_failed',
artifact: { state: 'failed', error_code: 'template_source_publish_failed' },
},
] });
await loading;
assert.equal(
test.get('cloud-admin-status').textContent,
'已加载 2 条云镜像记录:1 个可用,1 个不可用。',
);
assert.ok(findText(test.get('catalog-list'), '1 可用 / 2 条记录'));
}
{
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, /停用/);
}
{
const test = fixture();
const loading = test.loadCatalog();
await test.respond(test.requests[0], { templates: [entry] }); await loading;
const list = test.get('catalog-list');
const card = findClass(list, 'cloud-template-version-card');
const form = findClass(card, 'cloud-template-version-form');
const name = findClass(card, 'cloud-template-name-field').children[1];
name.value = '未保存的名称';
const saving = form.listeners.get('submit')(submit);
await test.respond(test.requests[1], { detail: '连接中断,效果未知' }, 502); await saving;
const save = findText(card, '保存名称');
assert.equal(save.disabled, true);
const q = { value: '' }; const status = { value: '' }; const events = {};
const filter = mountAdminCatalogFilter({ form: {
elements: { namedItem: key => key === 'catalog_q' ? q : status },
addEventListener: (key, handler) => { events[key] = handler; }, removeEventListener() {},
}, count: {}, onChange: test.applyCatalogFilters, locationImpl: null, historyImpl: null });
test.setCatalogFilter(filter);
q.value = 'does-not-match'; events.input(); assert.equal(card.hidden, true);
events.reset(submit); assert.equal(card.hidden, false);
assert.equal(findClass(list, 'cloud-template-version-card'), card,
'Changing filters must preserve the current card and mutation fence.');
assert.equal(save.disabled, true, 'Filtering re-enabled a possibly-applied mutation.');
assert.equal(name.value, '未保存的名称', 'Filtering discarded the in-progress name field.');
assert.equal(test.requests.length, 2, 'Local filtering must not resubmit or refetch actions.');
}
console.log('Admin startup-script permissions, generation CAS and catalog mutation fences passed.');