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

159 lines
8.9 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-system-logs.js', import.meta.url), 'utf8');
class Node {
constructor(tag = 'div') {
this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {};
this.listeners = new Map(); this.hidden = false; this.disabled = false;
this.open = false; this.value = ''; this._text = ''; this.attributes = new Map();
this.options = this.children;
this.parentNode = null; this.isConnected = true; this.focused = false;
this.classList = {values: new Set(), add: (...names) => names.forEach(name => this.classList.values.add(name)),
remove: (...names) => names.forEach(name => this.classList.values.delete(name)),
contains: name => this.classList.values.has(name)};
this.style = {values: new Map(), setProperty: (name, value) => this.style.values.set(name, value),
removeProperty: name => this.style.values.delete(name)};
}
set textContent(value) { this._text = String(value); this.children = []; }
get textContent() { return this._text + this.children.map(child => child.textContent).join(''); }
append(...values) { values.forEach(value => { if (value && typeof value === 'object') value.parentNode = this; this.children.push(value); }); }
add(option) { this.append(option); }
replaceChildren(...values) { this._text = ''; this.children.forEach(child => { if (child) child.parentNode = null; }); this.children = []; this.append(...values); }
setAttribute(key, value) { this.attributes.set(key, String(value)); }
addEventListener(key, handler) { const list = this.listeners.get(key) || []; list.push(handler); this.listeners.set(key, list); }
dispatch(key, fields = {}) {
const event = { target: this, cancelBubble: false, preventDefault() {}, ...fields };
let current = this;
while (current) {
event.currentTarget = current;
for (const listener of current.listeners.get(key) || []) listener(event);
if (event.cancelBubble) break;
current = current.parentNode;
}
}
querySelector(selector) {
return selector === 'button[type="submit"]' ? this.submitButton : null;
}
showModal() { this.open = true; }
close() { this.open = false; }
focus() { this.focused = true; }
}
class Option extends Node {
constructor(label, value) { super('option'); this.textContent = label; this.value = String(value); }
}
const flush = async () => { for (let i = 0; i < 24; i += 1) await Promise.resolve(); };
const cursor = 's=abc;i=1';
const page = {
items: [{ timestamp: '2026-10-06T08:01:37.115460Z', unit: 'virt-cloud-engine.service', priority: 3,
level: '错误', message: 'short preview', pid: '12', process: 'python', hostname: 'host-a', cursor }],
units: ['virt-cloud-engine.service'],
summary: { total: 1, error_count: 1, warning_count: 0, latest_at: '2026-10-06T08:01:37.115460Z' },
filters: {}, pagination: { next_cursor: null, has_more: false },
};
const detail = { item: { ...page.items[0], monotonic_timestamp: '1234', message: 'full diagnostic message',
fields: { CODE_FILE: '/srv/engine.py', MESSAGE: 'full diagnostic message' }, omitted_fields: [], truncated_fields: [],
message_redacted: true, redacted_fields: ['ACCESS_TOKEN'] } };
const ids = [...source.matchAll(/byId\('([^']+)'\)/g)].map(match => match[1]);
ids.push('admin-system-logs-bootstrap');
const nodes = Object.fromEntries([...new Set(ids)].map(id => [id, new Node()]));
nodes['admin-system-logs-bootstrap'].textContent = 'null';
nodes['system-logs-filter'].elements = { namedItem: name => nodes[
({ unit: 'system-logs-unit', priority: 'system-logs-priority', query: 'system-logs-query',
since: 'system-logs-since', until: 'system-logs-until', limit: 'system-logs-limit' })[name]
] };
nodes['system-logs-filter'].submitButton = new Node('button');
const root = new Node(); root.dataset.timezone = 'UTC';
const document = new Node(); document.documentElement = new Node(); document.body = new Node();
document.getElementById = id => nodes[id];
document.createElement = tag => new Node(tag);
document.querySelector = selector => selector === '[data-admin-system-logs]' ? root : null;
const window = new Node(); window.__VENIX_SYSTEM_LOGS__ = { apiUrl: '/api/v1/admin/system-logs', timezone: 'UTC' };
window.scrollX = 0; window.scrollY = 0; window.scrollTo = ({left, top}) => { window.scrollX = left; window.scrollY = top; };
let motionOpenCount = 0; let motionCloseCount = 0;
window.VenixDrawerMotion = {
openDrawerWithMotion(dialog) { motionOpenCount += 1; dialog.showModal(); dialog.classList.add('is-drawer-visible'); return true; },
closeDrawerWithMotion(dialog) { motionCloseCount += 1; dialog.classList.remove('is-drawer-visible'); dialog.close(); return Promise.resolve(true); },
};
const location = { origin: 'https://example.test', href: 'https://example.test/admin/system-logs' };
window.location = location;
const history = { state: null, pushState(value, _, url) { this.state = value; location.href = String(url); } };
let now = 0; let timerId = 0; const timers = new Map(); const requests = [];
const setTimeout = (callback, delay) => { const id = ++timerId; timers.set(id, { callback, due: now + delay }); return id; };
const clearTimeout = id => timers.delete(id);
window.setTimeout = setTimeout; window.clearTimeout = clearTimeout;
const fetch = (url, options) => new Promise((resolve, reject) => {
const request = { url: String(url), options, resolve, reject, settled: false };
requests.push(request);
options.signal?.addEventListener('abort', () => {
if (!request.settled) { request.settled = true; reject(new Error('aborted')); }
});
});
vm.runInNewContext(source, { document, window, location, history, URL, Node, Option, Date,
AbortController, fetch, setTimeout, clearTimeout, console }, { filename: 'admin-system-logs.js' });
async function respond(request, payload, status = 200) {
assert.ok(request); request.settled = true;
request.resolve({ ok: status < 300, status, json: async () => payload });
await flush();
}
async function advance(milliseconds) {
const end = now + milliseconds;
while (true) {
const next = [...timers.entries()].filter(([, item]) => item.due <= end)
.sort((a, b) => a[1].due - b[1].due)[0];
if (!next) break;
now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush();
}
now = end; await flush();
}
assert.equal(requests.length, 1, 'The page must load logs through the API after first paint.');
await respond(requests[0], page);
assert.match(nodes['system-logs-body'].textContent, /short preview/);
nodes['system-logs-body'].children[0].children[3].children[0].dispatch('click');
await flush();
assert.equal(requests.length, 2, 'Clicking the row message must request its complete journal entry.');
assert.equal(motionOpenCount, 1, 'Opening a detail must use the shared drawer motion controller.');
assert.equal(nodes['system-logs-detail'].open, true, 'The detail drawer must be open after a row click.');
assert.equal(nodes['system-logs-detail'].classList.contains('is-drawer-visible'), true, 'The detail drawer must be visible, not translated off-screen.');
assert.equal(document.documentElement.classList.contains('admin-instance-detail-open'), true, 'Opening details must lock the page scroll.');
assert.match(requests[1].url, /\/api\/v1\/admin\/system-logs\/detail\?cursor=s%3Dabc%3Bi%3D1&unit=virt-cloud-engine\.service&timestamp=2026-10-06T08%3A01%3A37\.115460Z/);
await respond(requests[1], detail);
assert.match(nodes['system-logs-detail-message'].textContent, /full diagnostic message/);
assert.match(nodes['system-logs-detail-fields'].textContent, /CODE_FILE/);
assert.match(nodes['system-logs-detail-state'].textContent, /凭据/);
nodes['system-logs-detail-close'].dispatch('click');
await flush();
assert.equal(motionCloseCount, 1, 'Closing a detail must use the shared drawer motion controller.');
assert.equal(nodes['system-logs-detail'].open, false);
assert.equal(document.documentElement.classList.contains('admin-instance-detail-open'), false);
nodes['system-logs-body'].children[0].dispatch('keydown', {key: 'Enter'});
await flush();
assert.equal(requests.length, 3, 'Enter must open the focused row detail.');
await respond(requests[2], detail);
nodes['system-logs-detail-close'].dispatch('click');
await flush();
nodes['system-logs-body'].children[0].dispatch('keydown', {key: ' '});
await flush();
assert.equal(requests.length, 4, 'Space must open the focused row detail.');
await respond(requests[3], detail);
nodes['system-logs-detail-close'].dispatch('click');
await flush();
nodes['system-logs-refresh'].dispatch('click');
assert.equal(requests.length, 5);
await advance(15000);
assert.equal(requests[4].options.signal.aborted, true, 'List reads must have a client deadline.');
assert.match(nodes['system-logs-notice'].textContent, /超时/);
assert.equal(nodes['system-logs-cancel'].hidden, true, 'Timeout must release the cancel control.');
console.log('System log async loading, detail retrieval and timeout behavior passed.');