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.
dianshang-qianduan/tests/course-resource-row-actions...

195 lines
13 KiB
JavaScript

// Uses an authorized environment and deletes only its uniquely named, empty fixture tree.
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const { chromium } = require(process.env.COURSE_RESOURCE_PLAYWRIGHT_PATH || 'playwright')
const origin = process.env.QA_ORIGIN
const username = process.env.QA_ADMIN_USERNAME
const password = process.env.QA_ADMIN_PASSWORD
assert(origin && username && password, 'Provide the authorized QA origin and admin credentials')
const reports = path.resolve(process.env.QA_REPORT_DIR || 'tests/e2e/reports/course-resource-row-actions')
fs.mkdirSync(reports, { recursive: true })
async function main() {
const browser = await chromium.launch({ channel: 'chrome', headless: true })
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } })
const page = await context.newPage()
await page.addInitScript(() => {
window.qaDragTrace = []
for (const type of ['dragstart', 'dragover', 'drop', 'dragend']) document.addEventListener(type, event => {
const row = event.target.closest?.('[data-resource-node]')
window.qaDragTrace.push({ type, node: row?.getAttribute('data-resource-node'), target: event.target.className?.baseVal || event.target.className, y: event.clientY, top: row?.getBoundingClientRect().top, height: row?.getBoundingClientRect().height })
if (window.qaDragTrace.length > 50) window.qaDragTrace.shift()
}, true)
})
const result = { errors: [], warnings: [], passed: [] }
let rootId
let token
let currentStep = 'login'
const marker = 'QA_ROW_ACTIONS_' + Date.now() + '_'
page.on('pageerror', error => result.errors.push(error.message))
page.on('console', message => {
if (['warning', 'error'].includes(message.type())) result.warnings.push({ step: currentStep, message: message.text() })
})
async function api(endpoint, method = 'GET', data) {
const response = await context.request.fetch(origin + '/api/course-resources' + endpoint, {
method, headers: { Authorization: 'Bearer ' + token }, ...(data !== undefined ? { data } : {}),
})
assert.equal(response.status(), 200, method + ' ' + endpoint)
return (await response.json()).data
}
const row = id => page.locator(`[data-resource-node="${id}"]`)
async function action(id, command) {
currentStep = command
await row(id).hover()
await row(id).locator(`[data-node-action="${command}"]`).click()
}
async function drag(id, targetId, position) {
currentStep = 'drag ' + position
await page.locator('.outline-tree').evaluate(async element => { await Promise.all(element.getAnimations({ subtree: true }).map(animation => animation.finished.catch(() => {}))) })
await row(targetId).scrollIntoViewIfNeeded()
const source = await row(id).boundingBox()
const target = await row(targetId).boundingBox()
await page.mouse.move(source.x + 100, source.y + source.height / 2)
await page.mouse.down()
await page.mouse.move(source.x + 110, source.y + source.height / 2, { steps: 4 })
await page.mouse.move(target.x + 100, target.y + (position === 'before' ? 2 : target.height - 2), { steps: 12 })
await page.mouse.up()
}
async function childOrder() {
return (await api('/management')).nodes.filter(node => node.parentId === rootId).map(node => node.id)
}
async function triggerFocused(id) {
await page.waitForFunction(id => document.activeElement?.closest('[data-resource-node]')?.getAttribute('data-resource-node') === String(id), id, { timeout: 5000 }).catch(async error => {
result.focusDiagnostic = await page.evaluate(() => ({ active: document.activeElement?.outerHTML.slice(0, 1000) }))
throw error
})
assert(await row(id).locator('.node-actions').isVisible())
}
try {
await page.goto(origin + '/#/login')
await page.getByPlaceholder('账号', { exact: true }).fill(username)
await page.getByPlaceholder('密码', { exact: true }).fill(password)
await page.getByRole('button', { name: '登 录', exact: true }).click()
await page.waitForURL(url => !url.hash.includes('/login'))
token = (await context.cookies()).find(cookie => cookie.name === 'Admin-Token').value
rootId = await api('/nodes', 'POST', { name: marker + '章' })
const firstId = await api('/nodes', 'POST', { name: marker + '甲节', parentId: rootId })
const childId = await api('/nodes', 'POST', { name: marker + '乙节', parentId: rootId })
const thirdId = await api('/nodes', 'POST', { name: marker + '丙节', parentId: rootId })
await page.goto(origin + '/#' + (process.env.QA_RESOURCE_ROUTE || '/platform-course-resources/index'))
await page.getByRole('heading', { name: '课程资源', exact: true }).waitFor()
await page.getByRole('button', { name: '展开全部', exact: true }).click()
await row(rootId).locator('.node-name').click()
await page.getByRole('heading', { name: '课程资源', exact: true }).hover()
assert.equal(await row(rootId).locator('.node-actions button:visible').count(), 6)
assert.equal(await row(childId).locator('.file-count').innerText(), '空')
assert.equal(await row(childId).locator('.node-actions').isVisible(), false)
result.passed.push('selected row retains six inline actions; unselected empty rows retain their empty badge')
await row(childId).hover()
assert.equal(await row(childId).locator('.node-actions button:visible').count(), 6)
result.passed.push('hover reveals actions on an unselected row')
await row(childId).locator('.node-name').click()
for (const width of [1440, 1280, 1024]) {
await page.setViewportSize({ width, height: 900 })
await page.getByRole('heading', { name: '课程资源', exact: true }).hover()
assert.equal(await row(childId).locator('.node-actions button:visible').count(), 6)
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth))
const outline = await page.locator('.outline-panel').boundingBox()
const last = await row(childId).locator('[data-node-action="delete"]').boundingBox()
assert(last.x >= outline.x && last.x + last.width <= outline.x + outline.width)
await page.screenshot({ path: path.join(reports, 'inline-actions-' + width + '.png'), fullPage: true, animations: 'disabled' })
}
result.passed.push('selected actions remain visible and inside the outline at 1440, 1280 and 1024 widths')
const chooser = page.waitForEvent('filechooser')
await action(childId, 'upload')
await (await chooser).setFiles([])
result.passed.push('inline attachment action opens the file chooser for its directory')
await action(childId, 'add')
await page.getByRole('textbox', { name: '请输入目录名称', exact: true }).fill(marker + '知识点')
const managementReload = page.waitForResponse(response => response.url().endsWith('/course-resources/management') && response.request().method() === 'GET')
await page.locator('.el-message-box').getByRole('button', { name: '确定', exact: true }).click()
const leaf = await (await managementReload).json()
const leafId = leaf.data.nodes.find(node => node.name === marker + '知识点').id
await row(leafId).locator('.node-name').waitFor()
assert.equal(await row(leafId).locator('[data-node-action="add"]').count(), 0)
result.passed.push('inline add creates a child and stops at the existing three-level limit')
await action(childId, 'rename')
await page.getByRole('textbox', { name: '请输入目录名称', exact: true }).fill(marker + '改名节')
await page.locator('.el-message-box').getByRole('button', { name: '确定', exact: true }).click()
await page.locator(`[data-resource-node="${childId}"] .node-name`).filter({ hasText: marker + '改名节' }).waitFor()
await triggerFocused(childId)
result.passed.push('rename dialog restores focus to the inline action')
for (const command of ['up', 'down']) {
const oldNumber = await page.locator(`[data-resource-node="${childId}"] .node-number`).innerText()
await action(childId, command)
await page.waitForFunction(({ id, oldNumber }) => document.querySelector(`[data-resource-node="${id}"] .node-number`)?.textContent !== oldNumber, { id: childId, oldNumber })
await triggerFocused(childId)
}
result.passed.push('inline move actions update numbering and preserve visible focus')
let loadedOrder = page.waitForResponse(response => response.url().endsWith('/course-resources/management') && response.request().method() === 'GET')
await drag(thirdId, firstId, 'before')
await loadedOrder
await page.locator('.el-loading-mask').first().waitFor({ state: 'hidden' })
assert.deepEqual(await childOrder(), [thirdId, firstId, childId])
await page.reload()
await page.getByRole('heading', { name: '课程资源', exact: true }).waitFor()
await page.getByRole('button', { name: '展开全部', exact: true }).click()
await row(thirdId).waitFor()
assert.equal(await row(thirdId).locator('.node-number').innerText(), (await row(rootId).locator('.node-number').innerText()) + '.1')
result.passed.push('dragging across two siblings persists the order after reload')
loadedOrder = page.waitForResponse(response => response.url().endsWith('/course-resources/management') && response.request().method() === 'GET')
await drag(thirdId, childId, 'after')
await loadedOrder
await page.locator('.el-loading-mask').first().waitFor({ state: 'hidden' })
assert.deepEqual(await childOrder(), [firstId, childId, thirdId])
const moveRoute = new RegExp('/api/course-resources/nodes/' + thirdId + '/move$')
let attempts = 0
await page.route(moveRoute, async route => {
if (++attempts === 2) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ code: 400, msg: '验收:排序保存失败' }) })
return route.continue()
})
loadedOrder = page.waitForResponse(response => response.url().endsWith('/course-resources/management') && response.request().method() === 'GET')
await drag(thirdId, firstId, 'before')
await loadedOrder
await page.getByText('验收:排序保存失败', { exact: true }).waitFor()
await page.locator('.el-loading-mask').first().waitFor({ state: 'hidden' })
assert.deepEqual(await childOrder(), [firstId, thirdId, childId])
assert.equal(await row(thirdId).locator('.node-number').innerText(), (await row(rootId).locator('.node-number').innerText()) + '.2')
await page.unroute(moveRoute)
result.passed.push('interrupted sorting shows the rejection and reloads the actual saved order')
loadedOrder = page.waitForResponse(response => response.url().endsWith('/course-resources/management') && response.request().method() === 'GET')
await drag(thirdId, childId, 'after')
await loadedOrder
await page.locator('.el-loading-mask').first().waitFor({ state: 'hidden' })
await drag(firstId, leafId, 'before')
assert.deepEqual(await childOrder(), [firstId, childId, thirdId])
assert.equal((await api('/management')).nodes.find(node => node.id === leafId).parentId, childId)
result.passed.push('reverse drag works and cross-parent dropping preserves hierarchy')
await page.screenshot({ path: path.join(reports, 'drag-saved.png'), fullPage: true, animations: 'disabled' })
await page.locator('.outline-panel').screenshot({ path: path.join(reports, 'outline-actions.png'), animations: 'disabled' })
await action(childId, 'delete')
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click()
await triggerFocused(childId)
assert((await api('/management')).nodes.some(node => node.id === childId))
result.passed.push('cancel deletion restores focus and preserves the directory')
await page.screenshot({ path: path.join(reports, 'inline-focus-restored.png'), fullPage: true, animations: 'disabled' })
await action(childId, 'delete')
await page.locator('.el-message-box').getByRole('button', { name: '确认删除', exact: true }).click()
await page.locator(`[data-resource-node="${childId}"]`).waitFor({ state: 'hidden' })
result.passed.push('confirmed deletion still removes the directory')
assert.deepEqual(result.errors, [])
assert.deepEqual(result.warnings, [])
console.log('PASS: selected/hover inline actions, empty badges, upload, add, rename, move and delete without browser warnings')
} catch (error) {
result.failure = error.message
result.dragTrace = await page.evaluate(() => window.qaDragTrace)
await page.screenshot({ path: path.join(reports, 'failure.png'), fullPage: true, animations: 'disabled' })
throw error
} finally {
if (rootId) await api('/nodes/' + rootId, 'DELETE')
fs.writeFileSync(path.join(reports, 'result.json'), JSON.stringify(result, null, 2))
await browser.close()
}
}
main().catch(error => { console.error(error.message); process.exitCode = 1 })