// Run with COURSE_RESOURCE_PLAYWRIGHT_PATH pointing at an existing Playwright installation. // Uses the production build and mocked HTTP responses; no business server or database writes. const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') const http = require('node:http') const { chromium } = require(process.env.COURSE_RESOURCE_PLAYWRIGHT_PATH || 'playwright') const buildRoot = path.resolve(process.env.COURSE_RESOURCE_BUILD || 'tests/e2e/reports/course-resources/build') const reports = path.resolve('tests/e2e/reports/course-resources') fs.mkdirSync(reports, { recursive: true }) const mime = { '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.woff2': 'font/woff2' } const server = http.createServer((req, res) => { const pathname = new URL(req.url, 'http://localhost').pathname let file = path.resolve(buildRoot, '.' + decodeURIComponent(pathname)) if (!file.startsWith(buildRoot + path.sep)) file = path.join(buildRoot, 'index.html') if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) file = path.join(buildRoot, 'index.html') res.setHeader('Content-Type', mime[path.extname(file)] || 'application/octet-stream') fs.createReadStream(file).pipe(res) }) function fixture(role) { const file = (id, name, ownerId) => ({ id, name, ownerId, nodeId: 1, size: 1048576, uploaderName: '张老师', createdAt: '2026-10-28T10:00:00', updatedAt: '2026-10-29T10:00:00', editable: role === 1 ? !ownerId : ownerId === 'teacher-a', learned: false }) const nodes = [ { id: 1, parentId: 0, name: '互联网产品开发基础', depth: 1, ownerId: '', defaultOpen: true, files: [file(1, '第一章学习讲义.pdf', ''), ...(role === 1 ? [] : [file(2, '课堂补充资料.txt', 'teacher-a')])] }, { id: 2, parentId: 1, name: '产品调研与需求分析', depth: 2, ownerId: '', defaultOpen: true, files: [] }, { id: 3, parentId: 2, name: '用户访谈方法', depth: 3, ownerId: '', defaultOpen: true, files: [{ ...file(3, '访谈参考图.png', ''), nodeId: 3 }] }, { id: 4, parentId: 0, name: '市场洞察与需求分析', depth: 1, ownerId: '', defaultOpen: false, files: [] }, ] if (role !== 1) nodes.push({ id: 5, parentId: 0, name: '教师补充章节', depth: 1, ownerId: 'teacher-a', defaultOpen: true, files: [] }) nodes.forEach(node => { node.editable = role === 1 ? !node.ownerId : node.ownerId === 'teacher-a' }) return { nodes, classes: role === 3 ? [{ id: 'a', name: '产品开发一班' }, { id: 'b', name: '产品开发二班' }] : [], permissions: [] } } async function main() { await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) const origin = `http://127.0.0.1:${server.address().port}` const browser = await chromium.launch({ channel: 'chrome', headless: true }) try { for (const role of [1, 3, 4]) { const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }) await context.addInitScript(() => sessionStorage.setItem('sessionObj', JSON.stringify({}))) const data = fixture(role) let visibilityWrites = 0 let lastVisibility = null const errors = [] let hiddenAll = false await context.addCookies([ { name: 'Admin-Token', value: 'course-resource-ui-test', url: origin }, { name: 'UserInfo', value: encodeURIComponent(JSON.stringify({ roleId: role, userId: role === 4 ? 'student-a' : 'teacher-a', schoolId: 'school', name: '张老师' })), url: origin }, ]) const page = await context.newPage() page.on('pageerror', error => { errors.push(error.message); console.error('Page error:', error.message) }) await page.route('**/*', async route => { const req = route.request() const url = new URL(req.url()) if (!url.pathname.includes('/api/') && !url.pathname.includes('/getInfo') && !url.pathname.includes('/dev-api/')) return route.continue() let payload = [] const endpoint = url.pathname.slice(url.pathname.indexOf('/course-resources')) if (endpoint === '/course-resources/management') payload = data else if (endpoint === '/course-resources/student') payload = { nodes: hiddenAll ? [] : data.nodes.filter(node => node.id !== 4), available: !hiddenAll, total: hiddenAll ? 0 : 3, learnedCount: 0 } else if (endpoint === '/course-resources/nodes' && req.method() === 'POST') { const body = req.postDataJSON() payload = 999 data.nodes.push({ id: payload, parentId: body.parentId || 0, name: body.name, depth: 1, ownerId: role === 1 ? '' : 'teacher-a', defaultOpen: true, files: [], editable: true }) } else if (endpoint === '/course-resources/visibility' && req.method() === 'PUT') { visibilityWrites++ lastVisibility = req.postDataJSON() data.permissions = lastVisibility } else if (/\/course-resources\/files\/\d+\/learned/.test(endpoint)) { const id = Number(endpoint.split('/')[3]) data.nodes.forEach(node => node.files.forEach(file => { if (file.id === id) file.learned = true })) } else if (endpoint.includes('/content')) { return route.fulfill({ status: 200, contentType: 'text/plain', body: '课程资源预览测试' }) } else if (/\/course-resources\/files\/\d+$/.test(endpoint) && req.method() === 'DELETE') { const id = Number(endpoint.split('/')[3]) data.nodes.forEach(node => { node.files = node.files.filter(file => file.id !== id) }) } else if (url.pathname.includes('product-config')) payload = { facultyManagementEnabled: true, majorManagementEnabled: true, adminClassManagementEnabled: true } else if (url.pathname.includes('getInfo')) payload = { roles: [role === 1 ? 'platformAdmin' : role === 3 ? 'teacher' : 'student'], user: { userName: '张老师' } } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ code: 200, msg: '成功', data: payload }) }) }) const route = role === 1 ? '/platform-course-resources/index' : role === 3 ? '/course-resources/index' : '/student-course-resources/index' await page.goto(origin + '/#' + route) try { await page.getByRole('heading', { name: '课程资源', exact: true }).waitFor() } catch (error) { console.error('Page URL:', page.url(), 'Body:', (await page.locator('body').innerText()).slice(0, 1800)); await page.screenshot({ path: path.join(reports, `failed-role-${role}.png`), fullPage: true }); throw error } if (role !== 4) { await page.getByRole('button', { name: '展开全部', exact: true }).click() await page.locator('[data-resource-node="3"]').waitFor({ state: 'visible' }) assert.equal(await page.locator('[data-resource-node="2"] .file-count').innerText(), '空') assert.equal(await page.locator('[data-resource-node="3"] .file-count').innerText(), '1') assert.equal(await page.locator('[data-resource-node="3"] .file-count .el-icon').count(), 1) await page.locator('[data-resource-node="3"]').hover() assert.equal(await page.getByRole('button', { name: '上传资源到用户访谈方法', exact: true }).count(), 1) if (role === 3) { const builtin = page.locator('[data-resource-node="1"]') await builtin.hover() assert.equal(await builtin.locator('[data-node-action="delete"]').count(), 0) assert.equal(await builtin.locator('[data-node-action="rename"]').count(), 0) assert.equal(await builtin.locator('[data-node-action="add"]').count(), 1) assert.equal(await builtin.locator('[data-node-action="upload"]').count(), 1) let sortRequests = 0 const countSort = request => { if (/\/course-resources\/nodes\/\d+\/move$/.test(request.url())) sortRequests++ } page.on('request', countSort) await builtin.locator('.node-name').dragTo(page.locator('[data-resource-node="4"] .node-name')) await page.locator('[data-resource-node="5"] .node-name').dragTo(builtin.locator('..'), { targetPosition: { x: 60, y: 2 } }) assert.equal(sortRequests, 0, 'teacher cannot drag builtin directories or reorder own nodes across ownership groups') page.off('request', countSort) const publicFile = page.locator('.el-table__row').filter({ hasText: '第一章学习讲义.pdf' }) assert.equal(await publicFile.getByRole('button', { name: '删除', exact: true }).count(), 0) const ownFile = page.locator('.el-table__row').filter({ hasText: '课堂补充资料.txt' }) assert.equal(await ownFile.getByRole('button', { name: '删除', exact: true }).count(), 1) await page.getByRole('button', { name: '班级可见范围', exact: true }).click() await page.locator('.visibility-table').waitFor() await page.waitForTimeout(400) await page.screenshot({ path: path.join(reports, 'teacher-visibility.png'), fullPage: true }) await page.locator('label[aria-label="互联网产品开发基础对产品开发一班可见"]').click() await page.getByRole('button', { name: '取消', exact: true }).click() assert.equal(visibilityWrites, 0) await page.getByRole('button', { name: '班级可见范围', exact: true }).click() await page.locator('label[aria-label="互联网产品开发基础对产品开发一班可见"]').click() await page.getByRole('button', { name: '保存设置', exact: true }).click() await page.waitForTimeout(300) assert.deepEqual(lastVisibility, [{ nodeId: 1, classId: 'a', visible: false }]) } await page.getByRole('button', { name: '新增章', exact: true }).click() await page.locator('.el-message-box__input input').fill('新增验收章节') await page.locator('.el-message-box').getByRole('button', { name: '确定', exact: true }).click() const added = page.locator('[data-resource-node="999"]') await added.waitFor({ state: 'visible' }) await page.locator('.detail-head h2').filter({ hasText: '新增验收章节' }).waitFor() await page.locator('[data-resource-node="1"]').click() await page.screenshot({ path: path.join(reports, role === 1 ? 'admin.png' : 'teacher.png'), fullPage: true }) } else { await page.locator('.resource-card').first().waitFor() await page.screenshot({ path: path.join(reports, 'student.png'), fullPage: true }) await page.getByPlaceholder('搜索章节或资源名称').fill('产品调研') assert.equal(await page.locator('.search-panel .resource-card').count(), 1) await page.getByPlaceholder('搜索章节或资源名称').fill('课堂补充') await page.locator('.search-panel .resource-card').click() await page.getByRole('button', { name: '标记已学习', exact: true }).click() await page.locator('.learning-progress b').filter({ hasText: '1/3' }).waitFor() await page.locator('.el-dialog__headerbtn:visible').click() hiddenAll = true await page.reload() await page.getByText('当前班级暂无开放的课程资源').waitFor() assert.equal(await page.locator('.el-ment-item').filter({ hasText: '课程资源' }).count(), 0) } assert.deepEqual(errors, [], `role ${role} browser errors`) console.log(`Role ${role}: browser checks passed`) await context.close() } } finally { await browser.close(); await new Promise(resolve => server.close(resolve)) } } main().catch(error => { console.error(error); server.close(); process.exitCode = 1 })