Files
magistr/frontend/tests/browser/schedule-materials.test.mjs

361 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert/strict';
import { before, after, test } from 'node:test';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { build } from 'esbuild';
import { chromium } from 'playwright';
let bundle, styles, server, origin, browser;
before(async () => {
bundle = (
await build({
stdin: {
contents: `import React from 'react'; import { createRoot } from 'react-dom/client'; import { storeAuthState } from './auth-session.js'; import { CalendarLoadsWorkspace } from './react/admin/tabs/CalendarLoadsWorkspace.jsx'; import { GroupScheduleMatrix } from './react/admin/tabs/GroupScheduleMatrix.jsx'; storeAuthState({ token: 'test-token', role: 'EDUCATION_OFFICE', userId: 1 }); createRoot(document.getElementById('root')).render(window.testMatrix ? <GroupScheduleMatrix /> : <CalendarLoadsWorkspace editHours={window.testHours} />);`,
resolveDir: process.cwd(),
loader: 'jsx',
},
bundle: true,
write: false,
format: 'iife',
jsx: 'automatic',
define: { 'process.env.NODE_ENV': '"test"' },
})
).outputFiles[0].text;
styles = (
await Promise.all(
['main.css', 'components.css'].map((name) =>
readFile(`admin/css/${name}`, 'utf8'),
),
)
).join('\n');
server = createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(
'<html data-theme="light"><body style="padding:24px"><div id="root"></div></body></html>',
);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
origin = `http://127.0.0.1:${server.address().port}`;
browser = await chromium.launch({
executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium',
});
});
after(async () => {
await browser?.close();
if (server)
await new Promise((resolve) => {
server.closeAllConnections();
server.close(resolve);
});
});
async function fixture(
t,
{ hours = false, conflict = false, matrix = false } = {},
) {
const page = await browser.newPage({
viewport: { width: 1440, height: 1200 },
});
const errors = [],
writes = [];
const details = [1, 2].map((id) => ({
context: {
assignmentId: id,
calendarId: 1,
calendarTitle: 'График профиля',
groupId: id,
groupName: `ИВТ-${id}`,
groupDepartmentId: id,
semesterId: 3,
semesterNumber: 3,
revision: 5,
},
subjects: [
{
subjectId: 20,
name: 'Операционные системы',
departmentId: 4,
academicHours: 54,
workloadHours: 72,
loads: [
{
category: 'LECTURE',
academicHours: 36,
workloadHours: 36,
teacherId: 7,
teacherName: 'Иванов И. И.',
},
{
category: 'PRACTICE',
academicHours: 0,
workloadHours: 0,
teacherId: null,
},
{
category: 'LABORATORY',
academicHours: 18,
workloadHours: 36,
splitSubgroups: true,
teacherId: null,
},
],
},
],
}));
page.on('pageerror', (error) => errors.push(error.message));
await page.route('**/api/**', async (route) => {
const req = route.request(),
url = new URL(req.url());
let response;
if (url.pathname === '/api/departments')
response = [
{ id: 1, departmentName: 'Кафедра А' },
{ id: 2, departmentName: 'Кафедра Б' },
{ id: 4, departmentName: 'Кафедра ВТ' },
];
else if (url.pathname === '/api/schedule/semesters')
response = [
{
id: 3,
academicYearTitle: '2026–2027',
semesterType: 'autumn',
startDate: '2026-09-01',
endDate: '2026-12-31',
},
];
else if (url.pathname === '/api/groups')
response = details.map((d) => ({
id: d.context.groupId,
name: d.context.groupName,
departmentId: d.context.groupDepartmentId,
}));
else if (url.pathname.endsWith('/teacher-options'))
response = [{ id: 8, fullName: 'Петров П. П.' }];
else if (url.pathname === '/api/calendar-loads') response = details;
else if (req.method() === 'PUT') {
const body = req.postDataJSON();
writes.push({ path: url.pathname, body });
if (conflict) {
await route.fulfill({
status: 409,
json: {
message:
'Нагрузка группы изменена другим пользователем. Обновите данные',
},
});
return;
}
const d = details.find((d) =>
url.pathname.includes(`/groups/${d.context.groupId}/`),
);
if (body.loads)
d.subjects[0].loads = body.loads.map((load) => ({
...load,
workloadHours:
load.academicHours * (load.splitSubgroups ? 2 : 1),
}));
else {
const load = d.subjects[0].loads.find((load) =>
url.pathname.includes(`/${load.category}/`),
);
load.teacherId = body.teacherId;
load.teacherName =
body.teacherId == null ? null : 'Петров П. П.';
}
d.subjects[0].academicHours = d.subjects[0].loads.reduce(
(sum, l) => sum + l.academicHours,
0,
);
d.subjects[0].workloadHours = d.subjects[0].loads.reduce(
(sum, l) => sum + l.workloadHours,
0,
);
d.context.revision++;
response = d;
} else if (url.pathname.includes('/time-slots/effective'))
response = [
{ id: 1, orderNumber: 1, startTime: '09:00', endTime: '10:30' },
];
else if (url.pathname === '/api/schedule') {
response = [
{
date: url.searchParams.get('startDate'),
timeSlotOrder: 1,
timeSlotId: 1,
subjectName: 'Потоковая лекция',
teacherName: 'Иванов И. И.',
startTime: '09:00',
endTime: '10:30',
lessonTypeName: 'Лекция',
classroomName: '101',
scheduleRuleSlotId: 50,
},
];
} else if (url.pathname.includes('/workload/')) response = [];
else throw new Error(`Неожиданный запрос ${url.pathname}`);
await route.fulfill({ json: response });
});
await page.goto(origin);
await page.addStyleTag({ content: styles });
await page.evaluate(
({ hours, matrix }) => {
window.testHours = hours;
window.testMatrix = matrix;
},
{ hours, matrix },
);
await page.addScriptTag({ content: bundle });
if (!matrix)
await page.locator('.materials-table tbody tr').first().waitFor();
t.after(async () => {
await page.close();
assert.deepEqual(errors, []);
});
return { page, writes };
}
async function chooseTeacher(page) {
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-1' })
.filter({ hasText: 'Лабораторные' })
.getByRole('button', { name: 'Назначить', exact: true })
.click();
await page
.getByRole('combobox', { name: 'Преподаватель нагрузки группы' })
.fill('Петров');
await page.getByRole('option', { name: 'Петров П. П.' }).click();
}
test('материалы сохраняют преподавателя одной группы, другая группа не меняется', async (t) => {
const { page, writes } = await fixture(t);
assert.deepEqual(
await page.locator('.materials-totals strong').allTextContents(),
['108', '144', '72'],
);
await chooseTeacher(page);
await page.getByRole('button', { name: 'Сохранить назначение' }).click();
await page
.getByRole('status')
.filter({ hasText: 'Преподаватель группы назначен' })
.waitFor();
assert.deepEqual(writes[0], {
path: '/api/calendar-loads/groups/1/semesters/3/subjects/20/loads/LABORATORY/teacher',
body: { teacherId: 8, expectedRevision: 5 },
});
await page.getByRole('button', { name: 'Обновить', exact: true }).click();
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-1' })
.getByText('Петров П. П.')
.waitFor();
assert.equal(
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-2' })
.filter({ hasText: 'Лабораторные' })
.getByText('Не назначен')
.count(),
1,
);
await page.locator('select').nth(1).selectOption('2', { force: true });
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-2' })
.first()
.waitFor();
assert.equal(await page.locator('.materials-table tbody tr').count(), 2);
});
test('редактор часов календарного графика сохраняет часы группы и лабораторное деление', async (t) => {
const { page, writes } = await fixture(t, { hours: true });
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-1' })
.getByRole('button', { name: 'Изменить часы' })
.click();
await page
.locator('.study-plan-load-card')
.first()
.getByRole('spinbutton')
.fill('20');
await page.getByRole('button', { name: 'Сохранить часы группы' }).click();
await page
.getByRole('status')
.filter({ hasText: 'Часы группы сохранены' })
.waitFor();
assert.equal(writes[0].body.loads[0].academicHours, 20);
assert.equal(writes[0].body.loads[2].splitSubgroups, true);
assert.equal(writes[0].body.loads[2].academicHours, 18);
await page.locator('.materials-workspace').evaluate(async (el) => {
await Promise.all(
el
.getAnimations({ subtree: true })
.filter((a) => a.effect.getTiming().iterations !== Infinity)
.map((a) => a.finished.catch(() => {})),
);
});
await page.screenshot({
path: '/tmp/magistr14-calendar-hours.png',
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth,
),
);
});
test('устаревшее распределение группы не перезаписывается', async (t) => {
const { page } = await fixture(t, { conflict: true });
await chooseTeacher(page);
await page.getByRole('button', { name: 'Сохранить назначение' }).click();
await page
.getByRole('alert')
.filter({ hasText: 'другим пользователем' })
.waitFor();
assert.deepEqual(
await page.locator('.materials-totals strong').allTextContents(),
['108', '144', '72'],
);
});
test('матрица показывает группы под кафедрами и общую лекцию в каждой колонке', async (t) => {
const { page } = await fixture(t, { matrix: true });
await page.getByText('ИВТ-1', { exact: true }).click();
await page.getByText('ИВТ-2', { exact: true }).click();
await page.getByRole('button', { name: 'Показать матрицу' }).click();
await page.locator('.group-schedule-matrix').waitFor();
assert.equal(
await page.locator('.group-schedule-matrix thead tr').count(),
2,
);
assert.deepEqual(
await page
.locator('.group-schedule-matrix thead tr')
.first()
.locator('th')
.allTextContents(),
['День / пара', 'Кафедра А', 'Кафедра Б'],
);
assert.equal(
await page
.locator('.group-schedule-matrix')
.getByText('Потоковая лекция', { exact: true })
.count(),
2,
);
await page.locator('.materials-workspace').evaluate(async (el) => {
await Promise.all(
el
.getAnimations({ subtree: true })
.filter((a) => a.effect.getTiming().iterations !== Infinity)
.map((a) => a.finished.catch(() => {})),
);
});
await page.screenshot({
path: '/tmp/magistr14-group-matrix.png',
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth,
),
);
});