Files
WhatIDo/backup.selftest.js
T
dev ef4d7cc472 Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0
- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js)
- Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js)
- Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES
- Обновление AGENTS.md под новый функционал тестов/опросов
2026-12-02 14:27:57 +03:00

405 lines
25 KiB
JavaScript
Raw 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.
const {
BACKUP_FORMAT_VERSION,
BACKUP_TABLES,
BACKUP_SEQUENCE_TABLES,
isSupportedBackupVersion,
restoredCounts,
isSafeUploadPath,
normalizeRestoreData,
} = require('./backup-restore');
const {
parseBackupLimitMb,
backupRequestTimeoutMs,
} = require('./lib/restore');
let failed = 0;
function ok(label, cond, extra) {
console.log(`${cond ? 'PASS' : 'FAIL'} ${label}${extra !== undefined && !cond ? ' -> ' + JSON.stringify(extra) : ''}`);
if (!cond) failed++;
}
function throws(label, fn) {
let threw = false;
try { fn(); } catch (e) { threw = true; }
ok(label, threw);
}
ok('формат 1 (старый архив) поддерживается', isSupportedBackupVersion({ version: 1, groups: [] }));
ok(`формат ${BACKUP_FORMAT_VERSION} поддерживается`, isSupportedBackupVersion({ version: BACKUP_FORMAT_VERSION, groups: [] }));
ok('формат 0 отклоняется', !isSupportedBackupVersion({ version: 0, groups: [] }));
ok('формат из будущего отклоняется', !isSupportedBackupVersion({ version: BACKUP_FORMAT_VERSION + 1, groups: [] }));
ok('без groups отклоняется', !isSupportedBackupVersion({ version: BACKUP_FORMAT_VERSION }));
ok('не объект отклоняется', !isSupportedBackupVersion(null));
ok('BACKUP_UPLOAD_LIMIT_MB: пусто и 0 — без ограничения',
parseBackupLimitMb('') === 0 && parseBackupLimitMb('0') === 0 && parseBackupLimitMb(undefined) === 0);
ok('BACKUP_UPLOAD_LIMIT_MB: число сохраняется', parseBackupLimitMb('4096') === 4096);
ok('backupRequestTimeoutMs: без лимита — 24 часа',
backupRequestTimeoutMs({ limitMb: 0, uploadTimeoutMs: 1500000 }) === 86400000);
ok('backupRequestTimeoutMs: лимит растягивает таймаут',
backupRequestTimeoutMs({ limitMb: 4096, uploadTimeoutMs: 1500000 }) === 30720000);
ok('backupRequestTimeoutMs: явный таймаут важнее',
backupRequestTimeoutMs({ limitMb: 4096, uploadTimeoutMs: 1500000, explicitMs: '600000' }) === 600000);
ok('в бэкап входят audit_log/notifications/banned_ips',
['audit_log', 'notifications', 'notification_reads', 'banned_ips'].every(t => BACKUP_TABLES.includes(t)),
BACKUP_TABLES);
ok('sessions не попадают в бэкап', !BACKUP_TABLES.includes('sessions'));
ok('sequences сбрасываются для audit_log и notifications',
BACKUP_SEQUENCE_TABLES.includes('audit_log') && BACKUP_SEQUENCE_TABLES.includes('notifications'));
const counts = restoredCounts({ groups: [1, 2], settings: { a: '1', b: '2' }, audit_log: [1] });
ok('restoredCounts считает строки и settings', counts.groups === 2 && counts.settings === 2 && counts.audit_log === 1, counts);
ok('restoredCounts для отсутствующей таблицы = 0', restoredCounts({ groups: [] }).notifications === 0);
ok('безопасный путь загрузки принимается', isSafeUploadPath('/uploads/1700000000000-abc123.jpg'));
ok('path traversal отклоняется', !isSafeUploadPath('/uploads/../../etc/passwd'));
ok('вложенный путь отклоняется', !isSafeUploadPath('/uploads/.originals/x.jpg'));
ok('чужой префикс отклоняется', !isSafeUploadPath('/etc/passwd'));
const base = { version: BACKUP_FORMAT_VERSION, groups: [], entries: [], users: [], branches: [] };
const originals = normalizeRestoreData({
...base,
entries: [{ id: 1, student_name: 'S', group_id: 1, description: 'd', photo_path: '/uploads/e.jpg', photo_original_path: '/uploads/.originals/e.jpg' }],
group_photos: [{ id: 1, group_id: 1, photo_path: '/uploads/g.jpg', photo_original_path: '/uploads/.originals/g.jpg' }],
});
ok('entries.photo_original_path принимает .originals',
originals.entries[0].photo_original_path === '/uploads/.originals/e.jpg', originals.entries[0]);
ok('group_photos.photo_original_path принимает .originals',
originals.group_photos[0].photo_original_path === '/uploads/.originals/g.jpg', originals.group_photos[0]);
const legacyOriginals = normalizeRestoreData({
...base,
group_photos: [{ id: 1, group_id: 1, photo_path: '/uploads/g.jpg', photo_original_path: '/uploads/g-orig.jpg' }],
});
ok('group_photos.photo_original_path принимает старый плоский путь',
legacyOriginals.group_photos[0].photo_original_path === '/uploads/g-orig.jpg', legacyOriginals.group_photos[0]);
const userAvatar = normalizeRestoreData({
...base,
users: [{ id: 1, username: 'u', password_hash: 'h', avatar: '/uploads/avatar.jpg' }],
});
ok('users.avatar сохраняется', userAvatar.users[0].avatar === '/uploads/avatar.jpg', userAvatar.users[0]);
const userColor = normalizeRestoreData({
...base,
users: [{ id: 1, username: 'u', password_hash: 'h', color: '#ff5733' }],
});
ok('users.color сохраняется', userColor.users[0].color === '#ff5733', userColor.users[0]);
const badUserColor = normalizeRestoreData({
...base,
users: [{ id: 1, username: 'u', password_hash: 'h', color: 'red' }],
});
ok('users.color невалидный заменяется дефолтом', badUserColor.users[0].color === '#2563eb', badUserColor.users[0]);
const branchColor = normalizeRestoreData({
...base,
branches: [{ id: 1, name: 'Центральный', color: '#16a34a' }],
});
ok('branches.color сохраняется', branchColor.branches[0].color === '#16a34a', branchColor.branches[0]);
const badBranchColor = normalizeRestoreData({
...base,
branches: [{ id: 1, name: 'Центральный', color: '#zzz' }],
});
ok('branches.color невалидный заменяется дефолтом', badBranchColor.branches[0].color === '#2563eb', badBranchColor.branches[0]);
const prompts = normalizeRestoreData({
...base,
user_settings: [{ user_id: 1, key: 'feedback_prompts', value: 'x'.repeat(20000) }],
});
ok('user_settings.feedback_prompts длиннее 16000 принимается',
prompts.user_settings[0].value.length === 20000, prompts.user_settings[0].value.length);
throws('user_settings.feedback_prompts длиннее 320000 отклоняется', () => normalizeRestoreData({
...base,
user_settings: [{ user_id: 1, key: 'feedback_prompts', value: 'x'.repeat(320001) }],
}));
const emptySettings = normalizeRestoreData({ ...base, settings: { system_logo: '', ai_prompt: 'x'.repeat(20000) } });
ok('пустое значение настройки принимается', emptySettings.settings.system_logo === '', emptySettings.settings.system_logo);
ok('длинный ai_prompt (20000) принимается', emptySettings.settings.ai_prompt.length === 20000);
const emptyFeedback = normalizeRestoreData({
...base,
feedbacks: [{ id: 1, group_id: 1, resident: 'R', text: '' }],
});
ok('пустой текст отзыва принимается', emptyFeedback.feedbacks[0].text === '', emptyFeedback.feedbacks[0].text);
const n = normalizeRestoreData({
...base,
groups: [{ id: 1, name: 'G', deleted_at: '2026-01-02T03:04:05.000Z', purge_at: '2026-02-03T04:05:06.000Z' }],
});
ok('groups.deleted_at больше не теряется', n.groups[0].deleted_at === '2026-01-02T03:04:05.000Z', n.groups[0]);
ok('groups.purge_at больше не теряется', n.groups[0].purge_at === '2026-02-03T04:05:06.000Z', n.groups[0]);
const e = normalizeRestoreData({
...base,
entries: [{ id: 1, student_name: 'S', group_id: 1, description: 'd', deleted_at: '2026-01-02T03:04:05.000Z', purge_at: '2026-03-04T05:06:07.000Z' }],
});
ok('entries.purge_at больше не теряется', e.entries[0].purge_at === '2026-03-04T05:06:07.000Z', e.entries[0]);
const nt = normalizeRestoreData({
...base,
notifications: [{ id: 5, type: 'entry.new', level: 'warning', title: 'T', body: 'B', link: 'l', target: { a: 1 }, admin_only: true, branch_id: 2, user_id: 3 }],
notification_reads: [{ user_id: 1, notification_id: 5 }],
audit_log: [{ id: 7, user_id: 1, action: 'backup.download', target: { size: 5 }, ip: '1.2.3.4' }],
banned_ips: [{ ip: '203.0.113.7', reason: 'manual', banned_until: '2026-05-05T00:00:00.000Z' }],
});
ok('notifications нормализуются', nt.notifications[0].level === 'warning' && nt.notifications[0].title === 'T', nt.notifications[0]);
ok('notifications.target остаётся JSON-строкой', nt.notifications[0].target === '{"a":1}', nt.notifications[0].target);
ok('notifications.user_id сохраняется', nt.notifications[0].user_id === 3, nt.notifications[0].user_id);
ok('notification_reads нормализуются', nt.notification_reads[0].notification_id === 5);
ok('audit_log нормализуется', nt.audit_log[0].action === 'backup.download' && nt.audit_log[0].target === '{"size":5}', nt.audit_log[0]);
ok('banned_ips нормализуются', nt.banned_ips[0].ip === '203.0.113.7');
const ch = normalizeRestoreData({
...base,
chat_threads: [{ id: 3, tutor_id: 1, last_message_text: 'привет', tutor_unread: 2, admin_unread: 1 }],
chat_messages: [{ id: 9, thread_id: 3, sender_id: 1, body: 'привет' }],
chat_attachments: [{ id: 4, message_id: 9, token: 'a'.repeat(32), path: '/uploads/1700000000000-abc123.png', name: 'photo.png', size: 1234 }],
});
ok('chat_threads нормализуются', ch.chat_threads[0].tutor_id === 1 && ch.chat_threads[0].tutor_unread === 2, ch.chat_threads[0]);
ok('chat_messages нормализуются', ch.chat_messages[0].thread_id === 3 && ch.chat_messages[0].body === 'привет', ch.chat_messages[0]);
ok('chat_attachments нормализуются', ch.chat_attachments[0].name === 'photo.png' && ch.chat_attachments[0].size === 1234, ch.chat_attachments[0]);
const sm = normalizeRestoreData({
...base,
short_messages: [{ id: 1, resident: 'Иванов И.И.', lesson_date: '2026-05-05', topic: 'T', message: 'текст', used: true, used_at: '2026-05-06', author_id: 1, deleted_at: '2026-05-07T00:00:00.000Z', purge_at: '2027-05-07T00:00:00.000Z' }],
});
ok('short_messages нормализуются', sm.short_messages[0].resident === 'Иванов И.И.' && sm.short_messages[0].used === true && sm.short_messages[0].used_at === '2026-05-06', sm.short_messages[0]);
ok('short_messages сохраняет purge_at', sm.short_messages[0].deleted_at === '2026-05-07T00:00:00.000Z' && sm.short_messages[0].purge_at === '2027-05-07T00:00:00.000Z', sm.short_messages[0]);
let smBadDate = false;
try {
normalizeRestoreData({ ...base, short_messages: [{ id: 1, resident: 'X', lesson_date: '05.05.2026', message: 't' }] });
} catch (e) {
smBadDate = true;
}
ok('кривая дата занятия в short_messages отклоняется', smBadDate);
let smNoResident = false;
try {
normalizeRestoreData({ ...base, short_messages: [{ id: 1, resident: '', lesson_date: '2026-05-05', message: 't' }] });
} catch (e) {
smNoResident = true;
}
ok('пустой резидент в short_messages отклоняется', smNoResident);
const chEdits = normalizeRestoreData({
...base,
chat_messages: [
{ id: 10, thread_id: 3, sender_id: 1, body: 'правлено', edited_at: '2026-01-02T10:00:00.000Z' },
{ id: 11, thread_id: 3, sender_id: 1, body: '', deleted_at: '2026-01-03T10:00:00.000Z' },
],
});
ok('edited_at сообщения сохраняется', chEdits.chat_messages[0].edited_at === '2026-01-02T10:00:00.000Z', chEdits.chat_messages[0]);
ok('deleted_at сообщения сохраняется', chEdits.chat_messages[1].deleted_at === '2026-01-03T10:00:00.000Z', chEdits.chat_messages[1]);
let chatBad = false;
try {
normalizeRestoreData({ ...base, chat_messages: [{ id: 1, thread_id: 3, sender_id: 1, body: 'x'.repeat(5001) }] });
} catch (e) {
chatBad = true;
}
ok('слишком длинный текст сообщения отклоняется', chatBad);
let chatPathBad = false;
try {
normalizeRestoreData({ ...base, chat_attachments: [{ id: 1, message_id: 1, token: 'b'.repeat(32), path: '/etc/passwd', name: 'x' }] });
} catch (e) {
chatPathBad = true;
}
ok('путь вложения вне uploads отклоняется', chatPathBad);
const badLevel = normalizeRestoreData({ ...base, notifications: [{ id: 1, type: 'x', level: 'drop-table', title: 'T' }] });
ok('неизвестный level уведомления -> info', badLevel.notifications[0].level === 'info', badLevel.notifications[0]);
throws('мусорный ip в banned_ips отклоняется', () => normalizeRestoreData({ ...base, banned_ips: [{ ip: 'не ip', reason: 'r', banned_until: '2026-01-01T00:00:00.000Z' }] }));
throws('пустой banned_until отклоняется', () => normalizeRestoreData({ ...base, banned_ips: [{ ip: '1.2.3.4', reason: 'r' }] }));
throws('пустой action в audit_log отклоняется', () => normalizeRestoreData({ ...base, audit_log: [{ id: 1, action: ' ' }] }));
throws('не-объект в notifications.target отклоняется', () => normalizeRestoreData({ ...base, notifications: [{ id: 1, type: 'x', title: 'T', target: [1, 2, 3] }] }));
throws('группа без id отклоняется', () => normalizeRestoreData({ ...base, groups: [{ name: 'G' }] }));
throws('путь вне uploads отклоняется', () => normalizeRestoreData({ ...base, students: [{ id: 1, name: 'S', photo_path: '/etc/passwd' }] }));
const stuStatus = normalizeRestoreData({ ...base, students: [{ id: 1, name: 'S', status: 'left' }, { id: 2, name: 'T', status: 'nope' }] });
ok('статус ученика сохраняется, неизвестный -> active', stuStatus.students[0].status === 'left' && stuStatus.students[1].status === 'active', stuStatus.students);
throws('notifications не массив отклоняется', () => normalizeRestoreData({ ...base, notifications: { nope: 1 } }));
const legacy = normalizeRestoreData({ version: 1, groups: [{ id: 1, name: 'G' }] });
ok('старый архив без новых таблиц восстанавливается', Array.isArray(legacy.audit_log) && legacy.audit_log.length === 0 && legacy.groups.length === 1, Object.keys(legacy));
ok('bookmarks входят в бэкап и sequences', BACKUP_TABLES.includes('bookmarks') && BACKUP_SEQUENCE_TABLES.includes('bookmarks'));
const bkm = normalizeRestoreData({
...base,
bookmarks: [{ id: 1, title: 'T', url: 'https://ex.com', description: 'd', photo_path: '/uploads/1700000000000-abc123.png', image_mode: 'cover', open_new_tab: false, is_active: false, sort_order: 3 }],
});
ok('bookmarks нормализуются', bkm.bookmarks[0].image_mode === 'cover' && bkm.bookmarks[0].is_active === false && bkm.bookmarks[0].photo_path === '/uploads/1700000000000-abc123.png', bkm.bookmarks[0]);
let bkmBadPath = false;
try {
normalizeRestoreData({ ...base, bookmarks: [{ id: 1, title: 'T', url: 'https://ex.com', photo_path: '/etc/passwd' }] });
} catch (e) {
bkmBadPath = true;
}
ok('путь картинки закладки вне uploads отклоняется', bkmBadPath);
ok('student_work_marks входят в бэкап и sequences', BACKUP_TABLES.includes('student_work_marks') && BACKUP_SEQUENCE_TABLES.includes('student_work_marks'));
const swm = normalizeRestoreData({
...base,
student_work_marks: [
{ id: 1, student_id: 1, group_id: 1, author_id: 1, short_message_id: 1, delta: 1, created_at: '2026-01-02T03:04:05.000Z' },
{ id: 2, student_id: 1, group_id: null, author_id: null, short_message_id: 2, delta: -1, created_at: null },
{ id: 3, student_id: 1, short_message_id: 3, delta: 7, created_at: null },
{ id: 4, student_id: 1, short_message_id: 3, delta: 0, created_at: null },
],
});
ok('student_work_marks нормализуются и delta приводится к -1/0/1',
swm.student_work_marks.length === 3 &&
swm.student_work_marks[0].delta === 1 && swm.student_work_marks[1].delta === -1 &&
swm.student_work_marks[2].delta === 0 &&
swm.student_work_marks[1].group_id === null && swm.student_work_marks[1].author_id === null,
swm.student_work_marks);
let swmBad = false;
try {
normalizeRestoreData({ ...base, student_work_marks: [{ id: 5, student_id: 1, short_message_id: 3 }] });
} catch (e) {
swmBad = true;
}
ok('student_work_marks без delta не восстанавливаются', !swmBad);
const swmBadDelta = normalizeRestoreData({
...base,
student_work_marks: [{ id: 6, student_id: 1, short_message_id: 3, delta: 7 }, { id: 7, student_id: 1, short_message_id: 3 }],
});
ok('некорректный delta отметки отбрасывается', swmBadDelta.student_work_marks.length === 0, swmBadDelta.student_work_marks);
const faceGeo = normalizeRestoreData({
...base,
group_photos: [{ id: 1, group_id: 1, photo_path: '/uploads/a.jpg', face_scanned_at: '2026-01-02T03:04:05.000Z', face_img_width: 4000, face_img_height: 3000 }],
entry_photos: [{ id: 1, entry_id: 1, photo_path: '/uploads/b.jpg', face_img_width: 2000, face_img_height: 1500 }],
});
ok('размеры фото для рамок лиц сохраняются',
faceGeo.group_photos[0].face_img_width === 4000 && faceGeo.group_photos[0].face_img_height === 3000
&& faceGeo.entry_photos[0].face_img_width === 2000 && faceGeo.entry_photos[0].face_img_height === 1500,
faceGeo.group_photos[0]);
const faceGeoNone = normalizeRestoreData({
...base,
entry_photos: [{ id: 1, entry_id: 1, photo_path: '/uploads/b.jpg' }],
});
ok('пустые размеры рамок лиц остаются null',
faceGeoNone.entry_photos[0].face_scanned_at === null && faceGeoNone.entry_photos[0].face_img_width === null,
faceGeoNone.entry_photos[0]);
let faceGeoBad = false;
try {
normalizeRestoreData({ ...base, entry_photos: [{ id: 1, entry_id: 1, photo_path: '/uploads/b.jpg', face_img_width: 0 }] });
} catch (e) {
faceGeoBad = true;
}
ok('некорректный размер рамки лица отклоняется', faceGeoBad);
ok('calendar_events входят в бэкап и sequences', BACKUP_TABLES.includes('calendar_events') && BACKUP_SEQUENCE_TABLES.includes('calendar_events'));
const calRestore = normalizeRestoreData({
...base,
calendar_events: [
{ id: 1, user_id: 1, is_common: true, title: 'Созвон', notes: 'n', location: 'Zoom', color: 'nope', starts_at: '2026-11-24T07:30:00.000Z', ends_at: '2026-11-24T08:30:00.000Z', all_day: false, repeat_rule: 'weekly', repeat_until: '2026-12-31', reminder_minutes: [10, 10, 999] },
{ id: 2, user_id: 1, title: 'Без времени' },
],
});
ok('calendar_events нормализуются: цвет/повтор/напоминания',
calRestore.calendar_events.length === 1 &&
calRestore.calendar_events[0].color === 'blue' &&
calRestore.calendar_events[0].repeat_rule === 'weekly' &&
calRestore.calendar_events[0].repeat_until === '2026-12-31' &&
calRestore.calendar_events[0].reminder_minutes.join(',') === '10' &&
calRestore.calendar_events[0].is_common === true,
calRestore.calendar_events);
ok('calendar_action_log входит в бэкап и sequences', BACKUP_TABLES.includes('calendar_action_log') && BACKUP_SEQUENCE_TABLES.includes('calendar_action_log'));
const calLogRestore = normalizeRestoreData({
...base,
calendar_action_log: [
{ id: 1, event_ids: [1], user_id: 1, user_name: 'Админ', action: 'created', title: 'Созвон', before_state: [], after_state: [{ id: 1, user_id: 1, title: 'Созвон', color: 'nope', starts_at: '2026-11-24T07:30:00.000Z', ends_at: '2026-11-24T08:30:00.000Z', repeat_rule: 'weekly', reminder_minutes: [10, 999], created_at: '2026-11-24T07:00:00.000Z', updated_at: '2026-11-24T07:05:00.000Z' }], created_at: '2026-11-24T07:30:00.000Z' },
{ id: 2, event_ids: [2], action: 'bogus', before_state: [], after_state: [] },
{ id: 3, event_ids: [], before_state: [], after_state: [] },
],
});
ok('calendar_action_log нормализуется: action/snapshot/actor',
calLogRestore.calendar_action_log.length === 1 &&
calLogRestore.calendar_action_log[0].action === 'created' &&
calLogRestore.calendar_action_log[0].user_name === 'Админ' &&
calLogRestore.calendar_action_log[0].after_state[0].color === 'blue' &&
calLogRestore.calendar_action_log[0].after_state[0].reminder_minutes.join(',') === '10' &&
calLogRestore.calendar_action_log[0].after_state[0].created_at === '2026-11-24T07:00:00.000Z' &&
calLogRestore.calendar_action_log[0].after_state[0].updated_at === '2026-11-24T07:05:00.000Z',
calLogRestore.calendar_action_log);
ok('quizzes входят в бэкап и sequences',
BACKUP_TABLES.includes('quizzes') && BACKUP_TABLES.includes('quiz_questions') &&
BACKUP_TABLES.includes('quiz_options') && BACKUP_TABLES.includes('quiz_assets') &&
BACKUP_TABLES.includes('quiz_attempts') && BACKUP_TABLES.includes('quiz_attempt_answers') &&
BACKUP_TABLES.includes('quiz_grade_scales') && BACKUP_TABLES.includes('quiz_grade_ranges') &&
BACKUP_SEQUENCE_TABLES.includes('quizzes') && BACKUP_SEQUENCE_TABLES.includes('quiz_attempt_answers') &&
BACKUP_SEQUENCE_TABLES.includes('quiz_grade_scales') && BACKUP_SEQUENCE_TABLES.includes('quiz_grade_ranges'));
const quizRestore = normalizeRestoreData({
...base,
quizzes: [
{ id: 1, title: 'Тест', kind: 'test', pass_percent: 150, max_attempts: 0, time_limit_min: -5, cover_path: '/uploads/cover.jpg', deleted_at: '2026-11-24T07:00:00.000Z', purge_at: '2026-12-24T07:00:00.000Z' },
{ id: 2, kind: 'survey', title: 'Опрос', allow_anonymous: true },
{ id: 3, kind: 'test', title: 'Тест 2', allow_anonymous: true, show_answers: false, grade_scale_id: 5 },
],
quiz_grade_scales: [
{ id: 5, name: 'Шкала на 15 баллов', description: 'Описание', sort_order: 3, created_by: 1 },
{ id: 0, name: 'Битая', sort_order: 0 },
],
quiz_grade_ranges: [
{ id: 7, scale_id: 5, min_score: 0, max_score: 5, label: 'Плохо', image_path: '/uploads/range.png' },
{ id: 8, scale_id: 99, min_score: 0, max_score: 1, label: 'Сирота' },
{ id: 9, scale_id: 5, min_score: 6, max_score: 15, label: '' },
],
quiz_questions: [
{ id: 1, quiz_id: 1, kind: 'multiple', text: 'Вопрос', weight: 2, partial_credit: true },
{ id: 2, quiz_id: 1, kind: 'nope', text: 'Вопрос 2' },
{ id: 3, quiz_id: 1, kind: 'text', text: 'Вопрос 3', text_match: 'contains', accepted_answers: [' 4 ', 'четыре', '4', 5] },
{ id: 4, quiz_id: 1, kind: 'line', text: 'Вопрос 4', min_length: 3, options_inline: true },
{ id: 5, quiz_id: 1, kind: 'single', text: 'Вопрос 5', min_length: 9999, options_inline: false },
],
quiz_options: [
{ id: 1, question_id: 1, text: 'Да', is_correct: true, weight: 0.5 },
],
quiz_assets: [
{ id: 1, kind: 'image', path: '/uploads/q.png', quiz_id: 1 },
],
quiz_attempts: [{ id: 1, quiz_id: 1, user_id: 1, status: 'done', score: 1.5, max_score: 2, percent: 75, passed: true }],
quiz_attempt_answers: [{ id: 1, attempt_id: 1, question_id: 1, option_ids: [1], text_answer: 'a', score: 1.5, max_score: 2, is_correct: true }],
});
ok('quizzes нормализуются: тип/порог/попытки/пути',
quizRestore.quizzes.length === 3 &&
quizRestore.quizzes[0].kind === 'test' &&
quizRestore.quizzes[0].pass_percent === 100 &&
quizRestore.quizzes[0].max_attempts === 1 &&
quizRestore.quizzes[0].time_limit_min === 0 &&
quizRestore.quizzes[0].deleted_at === '2026-11-24T07:00:00.000Z' &&
quizRestore.quizzes[1].kind === 'survey' &&
quizRestore.quizzes[1].allow_anonymous === true &&
quizRestore.quizzes[2].allow_anonymous === true &&
quizRestore.quizzes[2].show_answers === false &&
quizRestore.quizzes[2].grade_scale_id === 5 &&
quizRestore.quiz_grade_scales.length === 1 &&
quizRestore.quiz_grade_scales[0].sort_order === 3 &&
quizRestore.quiz_grade_scales[0].created_by === 1 &&
quizRestore.quiz_grade_ranges.length === 1 &&
quizRestore.quiz_grade_ranges[0].scale_id === 5 &&
quizRestore.quiz_grade_ranges[0].image_path === '/uploads/range.png' &&
quizRestore.quiz_questions.length === 5 &&
quizRestore.quiz_questions[1].kind === 'single' &&
quizRestore.quiz_questions[2].text_match === 'contains' &&
quizRestore.quiz_questions[2].accepted_answers.length === 2 &&
quizRestore.quiz_questions[3].min_length === 3 &&
quizRestore.quiz_questions[3].options_inline === true &&
quizRestore.quiz_questions[4].min_length === 2000 &&
quizRestore.quiz_options.length === 1 &&
quizRestore.quiz_options[0].weight === 0.5 &&
quizRestore.quiz_assets.length === 1 &&
quizRestore.quiz_attempts.length === 1 &&
quizRestore.quiz_attempts[0].anon_token === null &&
quizRestore.quiz_attempt_answers.length === 1,
{ quizzes: quizRestore.quizzes, questions: quizRestore.quiz_questions });
throws('файл материала теста вне uploads отклоняется', () => normalizeRestoreData({
...base,
quiz_assets: [{ id: 1, kind: 'image', path: 'etc/passwd', quiz_id: 1 }],
}));
throws('обложка теста вне uploads отклоняется', () => normalizeRestoreData({
...base,
quizzes: [{ id: 1, title: 'Т', cover_path: '../../etc/passwd' }],
}));
console.log(failed ? `\n${failed} проверок провалено` : '\nBACKUP SELFTEST OK');
process.exit(failed ? 1 : 0);