File size: 8,693 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | const assert = require('node:assert/strict');
const path = require('path');
const { pathToFileURL } = require('url');
const { chromium } = require('playwright');
const { editQuestion } = require('./edit_question');
const sel = id => `[data-testid="${id}"]`;
async function questionStates(rows) {
return rows.evaluateAll(elements => elements.map(row => ({
text: row.innerText.trim(),
states: [row, ...row.querySelectorAll('[aria-pressed], [aria-checked], [aria-label], [title]')]
.map(element => ['aria-pressed', 'aria-checked', 'aria-label', 'title']
.map(attribute => element.getAttribute(attribute))),
})));
}
function publicationLabel([row]) {
const text = [row.text, ...row.states.flat()].join(' ');
const published = /\bpublished\b|已发布|已上线/i.test(text);
const unpublished = /\bunpublished\b|未发布|已下线/i.test(text);
return published === unpublished ? null : published;
}
async function quietPointer(page) {
await page.mouse.move(0, 0);
await page.evaluate(() => document.activeElement?.blur());
}
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1200, height: 900 } });
await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' });
// --- Sections must exist ---
for (const id of ['admin-dashboard', 'question-bank', 'user-management', 'permission-management']) {
if (!(await page.locator(sel(id)).first().isVisible())) throw new Error(`missing section ${id}`);
}
const items = page.locator('[data-testid="question-item"]');
const input = page.locator('[data-testid="question-input"]');
const uploadBtn = page.locator('[data-testid="upload-question"]');
// --- 1. Upload/add: adding a question grows the list and shows the text ---
const before = await items.count();
await input.fill('集合论入门题');
await uploadBtn.click();
if ((await items.count()) !== before + 1) throw new Error('uploading a question should add it to the question bank');
const added = items.last();
if (!((await added.textContent()) || '').includes('集合论入门题')) {
throw new Error('the newly added question text should be rendered');
}
// Use two independently identifiable records. Check visible status and capture
// snapshots so an icon or other painted change need not alter the row text.
await input.fill('对照题目');
await uploadBtn.click();
const target = items.filter({hasText: '集合论入门题'});
const peer = items.filter({hasText: '对照题目'});
const active = await questionStates(target);
const other = await questionStates(peer);
await quietPointer(page);
const targetFrame = await target.screenshot({animations: 'disabled'});
const peerFrame = await peer.screenshot({animations: 'disabled'});
const peerBox = await peer.boundingBox();
await target.locator(sel('offline-question')).click();
await quietPointer(page);
const updated = await questionStates(target);
const updatedFrame = await target.screenshot({animations: 'disabled'});
assert(!targetFrame.equals(updatedFrame), 'changing publication state must visibly update the selected question');
assert.deepEqual(await questionStates(peer), other, 'changing publication affected another question');
const updatedPeerBox = await peer.boundingBox();
if (JSON.stringify(peerBox) === JSON.stringify(updatedPeerBox)) {
assert(peerFrame.equals(await peer.screenshot({animations: 'disabled'})),
'changing publication changed another question’s status indicators');
}
await target.locator(sel('offline-question')).click();
await quietPointer(page);
const restored = await questionStates(target);
const restoredFrame = await target.screenshot({animations: 'disabled'});
assert(JSON.stringify(restored) !== JSON.stringify(updated) || !restoredFrame.equals(updatedFrame),
'republishing the question must visibly reverse the status change');
const statuses = [active, updated, restored].map(publicationLabel);
if (statuses.every(status => status !== null)) {
assert(statuses[0] !== statuses[1] && statuses[0] === statuses[2],
'visible publication labels do not follow the toggle');
}
assert.deepEqual(await questionStates(peer), other, 'republishing affected another question');
// --- 3. Edit: editing marks/changes the question ---
const peerBeforeEdit = await questionStates(peer);
const countBeforeEdit = await items.count();
await input.fill('集合论进阶题');
await editQuestion(page, target.locator(sel('edit-question')), '集合论进阶题');
const editedItem = items.filter({hasText: '集合论进阶题'});
if (!((await editedItem.textContent()) || '').includes('集合论进阶题')) {
throw new Error('editing a question should update its content');
}
assert.equal(await items.count(), countBeforeEdit, 'editing changed the number of questions');
assert.equal(await target.count(), 0, 'editing must replace the previous question text');
assert.deepEqual(await questionStates(peer), peerBeforeEdit, 'editing changed another question');
// --- 4. Permission: as normal user, the admin-only delete control is hidden ---
const roleSelect = page.locator(sel('role-select')).first();
const options = await roleSelect.locator('option').evaluateAll(es => es.map(e => ({value:e.value,text:e.textContent||''})));
const normal = options.find(x => /normal user|普通用户/i.test(x.value+' '+x.text));
const admin = options.find(x => /admin|管理员/i.test(x.value+' '+x.text));
if (!normal || !admin) throw new Error('role selector should distinguish administrator and normal user');
await roleSelect.selectOption(normal.value);
const actions = ['edit-question', 'offline-question', 'delete-question', 'upload-question'];
const contentAsNormal = await questionStates(items);
page.on('dialog', dialog => dialog.type() === 'prompt' ? dialog.accept('权限绕过题') : dialog.dismiss());
for (const id of actions) {
if (id === 'upload-question') {
await input.evaluateAll(controls => controls.forEach(control => {
control.value = '权限绕过题';
control.dispatchEvent(new Event('input', {bubbles: true}));
control.dispatchEvent(new Event('change', {bubbles: true}));
}));
}
for (const control of await page.locator(sel(id)).all()) {
assert(!await control.isVisible() || !await control.isEnabled(),
`normal user has an active ${id} control`);
const visibleRows = await page.locator('[data-testid="question-item"]:visible').all();
const beforeClick = await Promise.all(visibleRows.map(row => row.screenshot({animations: 'disabled'})));
await control.evaluate(element => element.click());
assert.deepEqual(await questionStates(items), contentAsNormal,
`normal user changed the question bank via ${id}`);
const afterClick = await Promise.all(visibleRows.map(row => row.screenshot({animations: 'disabled'})));
assert(afterClick.every((frame, index) => frame.equals(beforeClick[index])),
`normal user changed the painted question state via ${id}`);
}
}
await roleSelect.selectOption(admin.value);
const beforeDelete = await items.count();
await editedItem.locator(sel('delete-question')).click();
assert.equal(await items.count(), beforeDelete - 1, 'admin must be able to delete a question');
assert.equal(await editedItem.count(), 0, 'deletion must remove the requested question');
assert.equal(await peer.count(), 1, 'deletion removed another question');
// --- 6. User management exposes answer records ---
if ((await page.locator(sel('answer-record')).count()) < 1) {
throw new Error('user management should expose answer records');
}
const records = await page.locator(sel('answer-record')).allTextContents();
if (records.some(text => !text.trim())) throw new Error('answer records must contain actual visible record text');
const userText = (await page.locator(sel('user-management')).first().textContent()) || '';
if (!userText.trim()) throw new Error('user management should show basic information');
// --- 7. Permission management distinguishes admin and normal user roles ---
const roleText = ((await page.locator(sel('permission-management')).first().textContent()) || '').toLowerCase();
if (!(/admin|管理员/.test(roleText)) || !(/normal user|普通用户/.test(roleText))) {
throw new Error('permission management must distinguish admin and normal user roles');
}
await browser.close();
})().catch(err => { console.error(err && err.stack || err); process.exit(1); });
|