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

149 lines
7.0 KiB
JavaScript

import assert from 'node:assert/strict';
import { createAdminInstanceBackups } from '../public/cloud/admin-instance-backups.js';
class FakeNode {
constructor(tag = 'div') {
this.tagName = String(tag).toLowerCase(); this.open = false;
this.value = ''; this.children = []; this.handlers = {};
this.dataset = {}; this.disabled = false; this.hidden = false;
this.checked = false; this.textContent = '';
}
append(...children) { this.children.push(...children); }
replaceChildren(...children) { this.children = children; }
setAttribute() {}
addEventListener(name, handler) { this.handlers[name] = handler; }
removeEventListener() {}
querySelector() { return null; }
querySelectorAll(selector) {
const tags = new Set(selector.split(',').map(value => value.trim()));
return descendants(this).filter(child => tags.has(child.tagName));
}
}
function node(tag = 'div') { return new FakeNode(tag); }
function descendants(root) {
const found = [];
for (const child of root.children || []) {
if (!(child instanceof FakeNode)) continue;
found.push(child, ...descendants(child));
}
return found;
}
const ids = new Map(['backup-library', 'backup-library-filter', 'backup-library-items',
'backup-library-notice', 'backup-library-page', 'backup-library-previous',
'backup-library-next', 'backup-library-close'].map(id => [id, node()]));
const controls = new Map(['q', 'state', 'user_id', 'instance_id', 'host_id'].map(key => [key, node()]));
const form = ids.get('backup-library-filter');
form.elements = { namedItem: key => controls.get(key) };
globalThis.Node = FakeNode;
globalThis.Option = class extends FakeNode {
constructor(label, value) {
super('option'); this.textContent = String(label); this.value = String(value);
}
};
globalThis.document = { createElement: node,
createTextNode(value) {
const text = node('#text'); text.textContent = String(value); return text;
},
body: { style: { setProperty() {}, removeProperty() {} } },
documentElement: { classList: { add() {}, remove() {} } } };
globalThis.window = { addEventListener() {}, removeEventListener() {},
VenixDrawerMotion: { openDrawerWithMotion(dialog) { dialog.open = true; } } };
const requests = [];
const mutations = [];
const backups = createAdminInstanceBackups({
byId: id => ids.get(id), createMigration: () => ({}),
actions: { enqueue(path, body) {
mutations.push({ path, body });
return Promise.resolve({ task_id: '77', url: '/tasks/77' });
}, watch() { return { url: '/tasks/77', stop() {} }; }, read(path, controller) {
return new Promise(resolve => requests.push({ path, controller, resolve }));
} },
});
const payload = (page, total = 40) => ({ items: [], pagination: { page, total_pages: 2, total } });
const settle = async (index, data) => { requests[index].resolve(data); await new Promise(resolve => setImmediate(resolve)); };
const event = { preventDefault() {} };
backups.start(); backups.openLibrary(null);
controls.get('q').value = '备份 & test'; controls.get('user_id').value = '77';
controls.get('instance_id').value = '999'; controls.get('host_id').value = '8';
controls.get('state').value = 'failed';
const filterPromise = form.handlers.submit(event);
assert.equal(requests[0].controller.signal.aborted, true);
const filteredUrl = new URL(requests[1].path, 'https://panel.test');
assert.equal(filteredUrl.searchParams.get('q'), '备份 & test');
assert.equal(filteredUrl.searchParams.get('user_id'), '77');
assert.equal(filteredUrl.searchParams.get('instance_id'), '999');
assert.equal(filteredUrl.searchParams.get('host_id'), '8');
assert.equal(filteredUrl.searchParams.get('state'), 'failed');
assert.equal(filteredUrl.searchParams.get('page'), '1');
await settle(1, payload(1)); await filterPromise;
await settle(0, payload(2, 999));
assert.match(ids.get('backup-library-page').textContent, /共 40 个/,
'A replaced request must not overwrite the current filters.');
const nextPromise = ids.get('backup-library-next').handlers.click();
const nextUrl = new URL(requests[2].path, 'https://panel.test');
assert.equal(nextUrl.searchParams.get('page'), '2');
assert.equal(nextUrl.searchParams.get('q'), '备份 & test');
await settle(2, payload(2)); await nextPromise;
const resetPromise = form.handlers.reset(event);
const resetUrl = new URL(requests[3].path, 'https://panel.test');
assert.equal(resetUrl.searchParams.get('q'), null);
assert.equal(resetUrl.searchParams.get('user_id'), null);
assert.equal(resetUrl.searchParams.get('page'), '1');
assert.equal(controls.get('state').value, '');
await settle(3, payload(1, 0)); await resetPromise;
const compositeLoad = backups.openLibrary(null);
await settle(4, {
can_manage: true,
items: [{
id: '19', name: 'portable-backup', state: 'ready', consistency: 'crash',
can_delete: false,
restore_targets: [{
host_id: '8', host_name: 'HKG-A', region: 'Hong Kong',
line: 'International', resource_pool_id: '31',
resource_pool: 'HKG International', available_ip_count: 2,
network_selector: 'bridge:br1',
target_plan_sha256: 'a'.repeat(64),
is_source_host: true,
}, {
host_id: '8', host_name: 'HKG-A', region: 'Hong Kong',
line: 'International', resource_pool_id: '31',
resource_pool: 'HKG International', available_ip_count: 1,
network_selector: 'bridge:br2',
target_plan_sha256: 'b'.repeat(64),
is_source_host: true,
}],
source: { instance_id: '999', host_id: '8', user_id: '77' },
}],
pagination: { page: 1, total_pages: 1, total: 1 },
});
await compositeLoad;
const rendered = descendants(ids.get('backup-library-items'));
const restoreSelect = rendered.find(child => child.tagName === 'select'
&& child.name === 'target_identity');
assert.ok(restoreSelect, 'Restore target selector was not rendered.');
assert.equal(restoreSelect.children[1].value, `8:31:${'a'.repeat(64)}`,
'Restore target did not preserve the frozen plan identity.');
assert.equal(restoreSelect.children[2].value, `8:31:${'b'.repeat(64)}`,
'A second attachment on the same host/pool was collapsed.');
assert.match(restoreSelect.children[1].textContent, /bridge:br1/);
assert.match(restoreSelect.children[2].textContent, /bridge:br2/);
restoreSelect.value = `8:31:${'b'.repeat(64)}`;
const restoreForm = rendered.find(child => child.tagName === 'form'
&& typeof child.handlers.submit === 'function');
assert.ok(restoreForm, 'Restore form was not rendered.');
const restoreInputs = descendants(restoreForm);
restoreInputs.find(child => child.tagName === 'input'
&& child.name === 'name').value = 'restored-vm';
restoreInputs.find(child => child.tagName === 'input'
&& child.name === 'confirm_new_instance').checked = true;
await restoreForm.handlers.submit({ preventDefault() {} });
assert.deepEqual(mutations.at(-1)?.body, {
target_host_id: 8,
target_resource_pool_id: 31,
target_plan_sha256: 'b'.repeat(64),
name: 'restored-vm',
confirm_new_instance: true,
}, 'Restore request lost the exact frozen target-plan identity.');
console.log('Administrator backup library filtering, paging and stale response protection passed.');