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

163 lines
5.0 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const moduleSource = await readFile(
new URL('../public/cloud/traffic.js', import.meta.url),
'utf8',
);
const source = `const state = ${moduleSource.split('const state = ')[1]}`
.replace('export async function initialize()', 'async function initialize()');
class Node {
constructor(tag) {
Object.assign(this, {
tagName: tag.toUpperCase(), children: [], attributes: new Map(),
className: '', text: '', hidden: false, disabled: false, open: false,
});
}
set textContent(value) { this.text = String(value); this.replaceChildren(); }
get textContent() {
return this.text + this.children.map(child => child.textContent).join('');
}
append(...children) {
for (const child of children) {
child.parent = this;
this.children.push(child);
}
}
replaceChildren(...children) {
this.children = [];
this.append(...children);
}
setAttribute(name, value) { this.attributes.set(name, String(value)); }
getAttribute(name) { return this.attributes.get(name) ?? null; }
querySelectorAll(selector) {
const matches = node => selector
=== 'details.cloud-traffic-region[data-region-key]'
&& node.tagName === 'DETAILS'
&& node.className.split(/\s+/).includes('cloud-traffic-region')
&& node.attributes.has('data-region-key');
return this.children.flatMap(child => [
...(matches(child) ? [child] : []),
...child.querySelectorAll(selector),
]);
}
}
const nodes = new Map([
['cloud-traffic-list', new Node('div')],
['cloud-traffic-count', new Node('span')],
['cloud-traffic-refresh', new Node('button')],
]);
const document = { createElement: tag => new Node(tag) };
const context = vm.createContext({
document,
window: { addEventListener() {} },
URL,
AbortController,
console,
byId: id => nodes.get(id),
api: async () => { throw new Error('Unexpected request'); },
initializeSession: async () => true,
readBootstrap: () => ({}),
showError() {},
});
vm.runInContext(`${source}\nglobalThis.traffic = { applyPayload };`, context, {
filename: 'traffic.js',
});
const pool = (id, name = `线路 ${id}`) => ({
group_id: id,
name,
projection_ready: true,
state: 'available',
network_restriction_state: 'clear',
active_entitlement_bytes: 1024,
active_consumed_bytes: 0,
available_bytes: 1024,
overage_bytes: 0,
next_expiry_at: null,
next_expiry_bytes: 0,
last_observed_at: null,
instances: [],
region_scope: { kind: 'region', regions: [{ code: 'hkg', name: '香港' }] },
});
const region = (key, overrides = {}) => ({
key,
kind: 'region',
name: key === 'region:hkg' ? '香港' : '新加坡',
description: '按线路独立核算共享额度',
pool_count: 1,
instance_count: 0,
summary_state: 'available',
requires_attention: false,
default_open: false,
items: [pool(key === 'region:hkg' ? 1 : 2)],
...overrides,
});
const payload = regions => ({
region_groups: regions,
region_count: regions.length,
pool_count: regions.length,
});
const details = () => nodes.get('cloud-traffic-list')
.querySelectorAll('details.cloud-traffic-region[data-region-key]');
context.traffic.applyPayload(payload([
region('region:hkg', { default_open: true }),
region('region:sgp'),
]));
assert.deepEqual(details().map(item => item.open), [true, false],
'Server default-open projection was not applied.');
assert.equal(nodes.get('cloud-traffic-count').textContent,
'2 个地区分组 · 2 个流量池');
details()[0].open = false;
details()[1].open = true;
context.traffic.applyPayload(payload([
region('region:hkg', { default_open: true }),
region('region:sgp'),
]));
assert.deepEqual(details().map(item => item.open), [false, true],
'Refresh did not retain both expanded and collapsed user choices.');
context.traffic.applyPayload(payload([
region('region:hkg', {
summary_state: 'attention', requires_attention: true, default_open: true,
}),
region('region:sgp'),
]));
assert.deepEqual(details().map(item => item.open), [true, true],
'A region that changed from healthy to attention remained hidden.');
details()[0].open = false;
context.traffic.applyPayload(payload([
region('region:hkg', {
summary_state: 'attention', requires_attention: true, default_open: true,
}),
region('region:sgp'),
]));
assert.deepEqual(details().map(item => item.open), [false, true],
'A user-collapsed attention region reopened on every refresh.');
context.traffic.applyPayload(payload([
region('region:hkg', {
summary_state: 'attention', requires_attention: true, default_open: true,
}),
region('region:sgp'),
region('region:unassigned', {
kind: 'unassigned', name: '地区待配置',
summary_state: 'attention', requires_attention: true, default_open: true,
items: [pool(3)],
}),
]));
assert.deepEqual(details().map(item => item.open), [false, true, true],
'A newly appearing attention region did not use its server default.');
console.log('Cloud traffic-pool region behavior checks passed.');