// Real local UI/API acceptance. Requires a private context prepared by CourseResourceAcceptance. // All created data uses a unique marker; cleanup never targets existing business content. const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') const cp = require('node:child_process') const { chromium, request } = require(process.env.COURSE_RESOURCE_PLAYWRIGHT_PATH || 'playwright') const run = path.resolve('../.local-run/course-resources-20261029/acceptance') const fixture = JSON.parse(fs.readFileSync(path.join(run, 'context.json'), 'utf8')) const reports = path.resolve('tests/e2e/reports/course-resources/live') fs.mkdirSync(reports, { recursive: true }) const rootIds = [] const passed = [] const browserErrors = [] const httpErrors = [] const warnings = [] const prefix = fixture.marker const base = '/api/course-resources' const contexts = {} let browser function pass(name) { passed.push(name); console.log('PASS:', name) } async function api(role, endpoint, method = 'GET', data, expected = 200) { const response = await contexts[role].fetch(base + endpoint, { method, ...(data !== undefined ? { data } : {}) }) assert.equal(response.status(), expected, `${role} ${method} ${endpoint}: ${await response.text()}`) const body = await response.json() return body.data } async function create(role, name, parentId = null) { const id = await api(role, '/nodes', 'POST', { name: prefix + name, parentId }) if (!parentId) rootIds.push({ id, role }) return id } async function upload(role, node, filename, overrideName) { const full = path.join(fixture.assets, prefix + filename) const response = await contexts[role].post(`${base}/nodes/${node}/files`, { multipart: { file: { name: overrideName || path.basename(full), mimeType: 'application/octet-stream', buffer: fs.readFileSync(full) } } }) assert.equal(response.status(), 200, `upload ${filename}: ${await response.text()}`) return (await response.json()).data } function files(snapshot) { return snapshot.nodes.flatMap(node => node.files) } async function browserPage(role, route) { const account = fixture[role] const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }) await context.addCookies([{ name: 'Admin-Token', value: account.token, url: fixture.origin }, { name: 'UserInfo', value: encodeURIComponent(JSON.stringify(account.userInfo)), url: fixture.origin }]) await context.addInitScript(() => sessionStorage.setItem('sessionObj', JSON.stringify({}))) const page = await context.newPage() page.on('pageerror', error => browserErrors.push({ role, message: error.message })) page.on('console', message => { if (message.type() === 'warning' && /Vue warn|ElementPlusError/.test(message.text())) warnings.push({ role, message: message.text() }) }) page.on('response', response => { if (response.status() >= 400 && new URL(response.url()).pathname.startsWith('/api/')) httpErrors.push({ role, status: response.status(), path: new URL(response.url()).pathname }) }) await page.goto(fixture.origin + '/#' + route) await page.getByRole('heading', { name: '课程资源', exact: true }).waitFor({ timeout: 60000 }) await page.locator('.el-loading-mask').first().waitFor({ state: 'hidden', timeout: 30000 }).catch(() => {}) return page } async function capture(page, role, tag = '') { await page.evaluate(() => window.scrollTo(0, 0)) await page.waitForTimeout(200) await page.screenshot({ path: path.join(reports, `${role}${tag}.png`), fullPage: true }) const geometry = await page.locator(role === 'student' ? '.student-resources' : '.course-management').evaluate(element => ({ left: element.getBoundingClientRect().left, right: element.getBoundingClientRect().right, width: element.getBoundingClientRect().width, scrollWidth: element.scrollWidth, viewport: innerWidth })) assert(geometry.left >= -1 && geometry.right <= geometry.viewport + 2, `${role} page out of viewport: ${JSON.stringify(geometry)}`) assert(geometry.scrollWidth <= geometry.width + 2, `${role} page content overflows: ${JSON.stringify(geometry)}`) const navbar = await page.locator('.navbar').evaluate(element => { const title = element.querySelector('.navTitle,.TnavTitle').getBoundingClientRect() const menu = element.querySelector('.el-ment').getBoundingClientRect() const account = element.querySelector('.right-menu').getBoundingClientRect() return { titleRight: title.right, menuLeft: menu.left, menuRight: menu.right, accountLeft: account.left } }) assert(navbar.menuLeft >= navbar.titleRight - 1 && navbar.menuRight <= navbar.accountLeft + 1, `${role} navbar overlaps: ${JSON.stringify(navbar)}`) } function helper(mode) { const backend = path.resolve('../link_commerce') const classpath = path.join(backend, 'target/classes') + ';' + fs.readFileSync(path.join(backend, 'targetcp.txt'), 'utf8').trim() cp.execFileSync('java', ['-cp', classpath, 'target/CourseResourceAcceptance.java', mode], { cwd: backend, stdio: ['ignore', 'pipe', 'pipe'], timeout: 60000 }) } async function makeMediaFixtures() { const page = await browser.newPage() await page.setContent('') const recording = await page.evaluate(async () => { const canvas = document.querySelector('canvas') const context = canvas.getContext('2d') const stream = canvas.captureStream(10) const recorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp8' }) const chunks = [] const completed = new Promise(resolve => { recorder.ondataavailable = event => chunks.push(event.data); recorder.onstop = resolve }) recorder.start() for (let frame = 0; frame < 10; frame++) { context.fillStyle = frame % 2 ? '#3b82f6' : '#eff6ff' context.fillRect(0, 0, 160, 90) await new Promise(resolve => setTimeout(resolve, 80)) } recorder.stop() await completed stream.getTracks().forEach(track => track.stop()) return Array.from(new Uint8Array(await new Blob(chunks, { type: 'video/webm' }).arrayBuffer())) }) await page.close() fs.writeFileSync(path.join(fixture.assets, prefix + '课堂演示.webm'), Buffer.from(recording)) const wav = Buffer.alloc(16044) wav.write('RIFF'); wav.writeUInt32LE(16036, 4); wav.write('WAVEfmt ', 8); wav.writeUInt32LE(16, 16) wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(8000, 24); wav.writeUInt32LE(16000, 28) wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34); wav.write('data', 36); wav.writeUInt32LE(16000, 40) fs.writeFileSync(path.join(fixture.assets, prefix + '课程音频.wav'), wav) } async function main() { for (const role of ['admin', 'teacher', 'otherTeacher', 'student', ...(fixture.otherStudent ? ['otherStudent'] : [])]) contexts[role] = await request.newContext({ baseURL: fixture.origin, extraHTTPHeaders: { Authorization: `Bearer ${fixture[role].token}` } }) try { const before = await api('admin', '/management') const root = await create('admin', '课程验收章') const section = await create('admin', '课程验收节', root) const section2 = await create('admin', '第二节', root) const leaf = await create('admin', '三级知识点', section) const second = await create('admin', '第二验收章') const current = await api('admin', '/management') if (!before.nodes.some(node => node.depth === 1)) assert.equal(current.nodes.find(node => node.id === root).defaultOpen, true) assert.equal(current.nodes.find(node => node.id === second).defaultOpen, false) await api('admin', `/nodes/${section2}/move`, 'POST', { direction: -1 }) const reordered = await api('admin', '/management') assert(reordered.nodes.findIndex(node => node.id === section2) < reordered.nodes.findIndex(node => node.id === section)) assert.equal(reordered.nodes.find(node => node.id === leaf).parentId, section) pass('三级大纲、默认第一章及同级整体排序') const uploaded = [] for (const filename of ['文本资料.txt', '教学文档.docx', '实验数据.xlsx', '教学课件.pptx', '资料包.zip']) uploaded.push({ ...(await upload('admin', root, filename)), filename }) const image = await upload('admin', section, '示意图.png') const pdf = await upload('admin', leaf, '课程讲义.pdf') const secondPdf = await upload('admin', second, '课程讲义.pdf', prefix + '第二章讲义.pdf') uploaded.push({ ...image, filename: '示意图.png' }, { ...pdf, filename: '课程讲义.pdf' }) for (const file of uploaded) { const download = await contexts.admin.get(`${base}/files/${file.id}/content`) assert.equal(download.status(), 200) assert.deepEqual(await download.body(), fs.readFileSync(path.join(fixture.assets, prefix + file.filename))) if (file.filename.endsWith('.zip')) continue const preview = await contexts.admin.get(`${base}/files/${file.id}/content?preview=true`) assert.equal(preview.status(), 200, `${file.filename} preview: ${await preview.text()}`) const bytes = await preview.body() if (/\.(docx|xlsx|pptx|pdf)$/.test(file.filename)) { assert(preview.headers()['content-type'].includes('application/pdf')) assert.equal(bytes.subarray(0, 4).toString(), '%PDF') assert(bytes.length > 500) } } pass('真实多级上传、下载字节一致及PDF/Word/Excel/PPT/图片/文本预览') const ownRoot = await create('teacher', '教师新增章') const ownSection = await create('teacher', '教师新增节', root) const ownLeaf = await create('teacher', '教师新增知识点', section) const ownFile = await upload('teacher', ownRoot, '课程讲义.pdf', prefix + '教师讲义.pdf') const ownBuiltinFile = await upload('teacher', root, '文本资料.txt', prefix + '教师补充.txt') await upload('teacher', ownLeaf, '文本资料.txt', prefix + '教师知识点.txt') const otherFile = await upload('otherTeacher', root, '文本资料.txt', prefix + '其他教师.txt') assert.equal((await api('teacher', '/management')).nodes.find(node => node.id === ownRoot).defaultOpen, true) assert(!(await api('otherTeacher', '/management')).nodes.some(node => node.id === ownRoot)) assert(!files(await api('otherTeacher', '/management')).some(file => file.id === ownBuiltinFile.id)) await api('teacher', `/nodes/${root}`, 'PUT', { name: '无权修改' }, 403) await api('teacher', `/files/${pdf.id}`, 'DELETE', undefined, 403) await api('admin', `/files/${ownFile.id}`, 'DELETE', undefined, 403) const forbidden = await contexts.otherTeacher.get(`${base}/files/${ownBuiltinFile.id}/content`) assert.equal(forbidden.status(), 403) pass('教师可扩展各层目录、默认对本人班级开放、跨教师隔离及内置数据只读') const openRows = [root, section, section2, leaf, second].map(nodeId => ({ nodeId, classId: fixture.teacher.classId, visible: nodeId !== second })) await api('teacher', '/visibility', 'PUT', openRows) if (fixture.otherTeacher.classId) await api('otherTeacher', '/visibility', 'PUT', [root, section, section2, leaf].map(nodeId => ({ nodeId, classId: fixture.otherTeacher.classId, visible: true }))) const student = await api('student', '/student') assert.equal(student.available, true) assert(files(student).some(file => file.id === ownBuiltinFile.id)) assert(!files(student).some(file => file.id === otherFile.id || file.id === secondPdf.id)) if (contexts.otherStudent) assert(!files(await api('otherStudent', '/student')).some(file => file.id === ownBuiltinFile.id || file.id === ownFile.id)) const unavailable = await contexts.student.get(`${base}/files/${secondPdf.id}/content`) assert.equal(unavailable.status(), 403) pass('学生仅获取所属教师和本班已开放资源,文件访问同步鉴权') browser = await chromium.launch({ channel: 'chrome', headless: true }) await makeMediaFixtures() for (const filename of ['课堂演示.webm', '课程音频.wav']) { const media = await upload('admin', root, filename) const preview = await contexts.teacher.get(`${base}/files/${media.id}/content?preview=true`) assert.equal(preview.status(), 200) assert(preview.headers()['content-type'].startsWith(filename.endsWith('webm') ? 'video/' : 'audio/')) } const adminPage = await browserPage('admin', '/platform-course-resources/index') await adminPage.getByRole('button', { name: '展开全部', exact: true }).click() await adminPage.getByRole('button', { name: '收起全部', exact: true }).click() await adminPage.locator(`[data-resource-node="${section}"]`).waitFor({ state: 'hidden', timeout: 5000 }) assert.equal(await adminPage.locator(`[data-resource-node="${section}"]`).isVisible(), false) await adminPage.getByRole('button', { name: '展开全部', exact: true }).click() await adminPage.locator(`[data-resource-node="${leaf}"]`).waitFor({ state: 'visible' }) await adminPage.locator(`[data-resource-node="${root}"]`).click() for (const [width, height] of [[1440, 900], [1280, 800], [1024, 768]]) { await adminPage.setViewportSize({ width, height }) await capture(adminPage, 'admin', `-${width}`) } const teacherPage = await browserPage('teacher', '/course-resources/index') await teacherPage.getByRole('button', { name: '展开全部', exact: true }).click() await teacherPage.locator(`[data-resource-node="${root}"]`).click() const publicRow = teacherPage.locator('.el-table__row').filter({ hasText: uploaded[0].name }) assert.equal(await publicRow.getByRole('button', { name: '删除', exact: true }).count(), 0) assert.equal(await teacherPage.locator('.el-table__row').filter({ hasText: ownBuiltinFile.name }).getByRole('button', { name: '删除', exact: true }).count(), 1) for (const [width, height] of [[1440, 900], [1280, 800], [1024, 768]]) { await teacherPage.setViewportSize({ width, height }) await capture(teacherPage, 'teacher', `-${width}`) } await teacherPage.setViewportSize({ width: 1440, height: 900 }) for (const [filename, tag] of [['课堂演示.webm', 'video'], ['课程音频.wav', 'audio']]) { await teacherPage.locator('.el-table__row').filter({ hasText: prefix + filename }).getByRole('button', { name: '预览', exact: true }).click() await teacherPage.waitForFunction(tag => { const media = document.querySelector(`.resource-preview ${tag}`) return media && media.readyState >= 1 && !media.error }, tag) await teacherPage.locator(`.resource-preview ${tag}`).evaluate(media => media.play()) await teacherPage.waitForTimeout(400) await teacherPage.screenshot({ path: path.join(reports, `preview-${tag}.png`), fullPage: true }) await teacherPage.locator('.el-dialog__headerbtn:visible').click() } pass('真实音视频预览加载与播放') await teacherPage.getByRole('button', { name: '班级可见范围', exact: true }).click() await teacherPage.locator('.visibility-table').waitFor() await teacherPage.waitForTimeout(350) await teacherPage.screenshot({ path: path.join(reports, 'teacher-visibility.png'), fullPage: true }) await teacherPage.getByRole('button', { name: '取消', exact: true }).click() for (const visible of [true, false]) { await teacherPage.getByRole('button', { name: '班级可见范围', exact: true }).click() await teacherPage.locator(`label[aria-label="${prefix}第二验收章对${fixture.teacher.className}可见"]`).click() await teacherPage.getByRole('button', { name: '保存设置', exact: true }).click() await teacherPage.getByText('已保存班级可见范围', { exact: true }).waitFor() assert.equal(files(await api('student', '/student')).some(file => file.id === secondPdf.id), visible) } pass('真实管理端/教师端页面、只读按钮和三种桌面宽度布局') for (let index = 0; index < 30; index++) await create('admin', `长大纲定位${index}`) await teacherPage.reload() await teacherPage.getByRole('heading', { name: '课程资源', exact: true }).waitFor() await teacherPage.getByRole('button', { name: '新增章', exact: true }).click() await teacherPage.locator('.el-message-box__input input').fill(prefix + '页面新增定位验收') await teacherPage.locator('.el-message-box').getByRole('button', { name: '确定', exact: true }).click() await teacherPage.locator('.detail-head h2').filter({ hasText: prefix + '页面新增定位验收' }).waitFor() const addedNode = await teacherPage.locator('.outline-row').filter({ hasText: prefix + '页面新增定位验收' }).boundingBox() const outlineBox = await teacherPage.locator('.outline-tree').boundingBox() assert(addedNode.y >= outlineBox.y && addedNode.y + addedNode.height <= outlineBox.y + outlineBox.height + 1, 'new directory is scrolled into the long outline viewport') const chooserReady = teacherPage.waitForEvent('filechooser') await teacherPage.locator('.detail-head').getByRole('button', { name: '上传资源', exact: true }).click() await (await chooserReady).setFiles(path.join(fixture.assets, prefix + '文本资料.txt')) await teacherPage.locator('.resource-table').getByRole('button', { name: prefix + '文本资料.txt', exact: true }).waitFor() await teacherPage.locator('.resource-table').getByRole('button', { name: '预览', exact: true }).click() await teacherPage.locator('.resource-preview iframe').waitFor() await teacherPage.locator('.el-dialog__headerbtn:visible').click() pass('页面新增后定位、真实文件上传与预览弹窗') const studentPage = await browserPage('student', '/student-course-resources/index') await studentPage.locator('.resource-card').first().waitFor() for (const [width, height] of [[1440, 900], [1280, 800], [1024, 768]]) { await studentPage.setViewportSize({ width, height }) await capture(studentPage, 'student', `-${width}`) } await studentPage.setViewportSize({ width: 1440, height: 900 }) await studentPage.getByPlaceholder('搜索章节或资源名称').fill('教师补充.txt') await studentPage.locator('.search-panel .resource-card').filter({ hasText: ownBuiltinFile.name }).click() await studentPage.getByRole('button', { name: '标记已学习', exact: true }).click() await studentPage.getByText('已标记为已学习', { exact: true }).waitFor() await studentPage.locator('.el-dialog__headerbtn:visible').click() await studentPage.reload() await studentPage.locator('.learning-progress').waitFor() const progressSnapshot = await api('student', '/student') assert(files(progressSnapshot).find(file => file.id === ownBuiltinFile.id).learned) const status = await studentPage.locator('.learning-progress b').innerText() assert.equal(status, `${progressSnapshot.learnedCount}/${progressSnapshot.total}`) pass('真实学生搜索、手动标记学习、刷新后进度持久化') await api('teacher', '/visibility', 'PUT', [{ nodeId: second, classId: fixture.teacher.classId, visible: true }]) const reopened = await api('student', '/student') const reopenedFile = files(reopened).find(file => file.id === secondPdf.id) assert(reopenedFile) assert(new Date(reopenedFile.updatedAt) > new Date(reopenedFile.createdAt)) await studentPage.reload() await studentPage.locator('.recent-file').first().filter({ hasText: secondPdf.name }).waitFor() await api('teacher', '/visibility', 'PUT', reopened.nodes.filter(node => node.parentId === 0 && node.name.startsWith(prefix)).map(node => ({ nodeId: node.id, classId: fixture.teacher.classId, visible: false }))) assert.equal((await api('student', '/student')).available, false) await studentPage.reload() await studentPage.getByText('当前班级暂无开放的课程资源').waitFor() assert.equal(await studentPage.locator('.el-ment-item').filter({ hasText: '课程资源' }).count(), 0) pass('新开放资源更新时间及全部隐藏后的学生入口移除') helper('capture') await api('teacher', `/files/${ownFile.id}`, 'DELETE') assert(!files(await api('teacher', '/management')).some(file => file.id === ownFile.id)) pass('教师可删除本人上传资源') await adminPage.reload() await adminPage.locator(`[data-resource-node="${root}"]`).waitFor() await adminPage.locator(`[data-resource-node="${root}"]`).hover() await adminPage.locator(`[data-resource-node="${root}"] [data-node-action="rename"]`).click() await adminPage.locator('.el-message-box__input input').fill(prefix + '重命名验收章') await adminPage.locator('.el-message-box').getByRole('button', { name: '确定', exact: true }).click() await adminPage.locator('.detail-head h2').filter({ hasText: prefix + '重命名验收章' }).waitFor() for (const confirm of [false, true]) { await adminPage.locator(`[data-resource-node="${root}"]`).hover() await adminPage.locator(`[data-resource-node="${root}"] [data-node-action="delete"]`).click() await adminPage.locator('.el-message-box').getByText(/包括教师在其下新增的目录和资源/).waitFor() await adminPage.locator('.el-message-box').getByRole('button', { name: confirm ? '确认删除' : '取消', exact: true }).click() if (!confirm) assert((await api('admin', '/management')).nodes.some(node => node.id === root)) } await adminPage.locator(`[data-resource-node="${root}"]`).waitFor({ state: 'hidden' }) const after = await api('teacher', '/management') assert(!after.nodes.some(node => [root, section, section2, leaf, ownSection, ownLeaf].includes(node.id))) assert(!files(after).some(file => [pdf.id, image.id, ownBuiltinFile.id].includes(file.id))) assert(!files(await api('otherTeacher', '/management')).some(file => file.id === otherFile.id)) pass('真实内置目录删除级联移除所有教师下挂目录和资源') assert.deepEqual(browserErrors, [], 'uncaught browser errors') assert.deepEqual(httpErrors, [], 'unexpected UI API failures') assert.deepEqual(warnings, [], 'Vue/Element Plus warnings') pass('验收页面无浏览器异常、接口失败及Vue/组件警告') } finally { if (browser) await browser.close() try { helper('cleanup') } catch (error) { console.error('Acceptance cleanup failed:', error.message); throw error } for (const context of Object.values(contexts)) await context.dispose() fs.writeFileSync(path.join(reports, 'result.json'), JSON.stringify({ passed, browserErrors, httpErrors, warnings }, null, 2)) } } main().catch(error => { console.error(error); process.exitCode = 1 })