BeKultur/test/run-tests.ts
2026-10-21 21:07:54 +00:00

788 lines
32 KiB
TypeScript
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.

import assert from 'assert';
import { LocalDatabase } from '../src/services/db';
import { InsightService } from '../src/services/insight';
import { ScraperService } from '../src/services/scraper';
import { SyllabusService } from '../src/services/syllabus';
import { ExamService } from '../src/services/exam';
import { Assignment, Lesson, ExamReportDetail } from '../src/types';
async function runAllTests() {
console.log('========================================================');
console.log(' BeKultur - Automated Test Suite');
console.log('========================================================\n');
let passed = 0;
let failed = 0;
function test(name: string, fn: () => void | Promise<void>) {
return (async () => {
try {
await fn();
console.log(` ✓ ${name}`);
passed++;
} catch (err: any) {
console.error(` ✗ ${name}`);
console.error(` Error: ${err.message}\n`);
failed++;
}
})();
}
// 1. Date Parsing
await test('InsightService: parsePortalDate parses Turkish DD.MM.YYYY correctly', () => {
const d1 = InsightService.parsePortalDate('20.10.2026');
assert(d1 !== null, 'Date should not be null');
assert.strictEqual(d1.getFullYear(), 2026);
assert.strictEqual(d1.getMonth(), 9);
assert.strictEqual(d1.getDate(), 20);
const d2 = InsightService.parsePortalDate('8.11.2026');
assert(d2 !== null);
assert.strictEqual(d2.getMonth(), 10);
assert.strictEqual(d2.getDate(), 8);
const invalid = InsightService.parsePortalDate('');
assert.strictEqual(invalid, null);
});
// 2. Teacher Note Extraction
await test('InsightService: extractTeacherCheckNote detects various teacher notes', () => {
const n1 = InsightService.extractTeacherCheckNote('fenomen ayt 237-242 kontrol tarihi 26-30 ekim');
assert.strictEqual(n1?.toLowerCase(), '26-30 ekim');
const n2 = InsightService.extractTeacherCheckNote('3D TYT sf. 99-118 + 3D AYT sf. 123-130 (kontrol tarihi 27 Ekim)');
assert.strictEqual(n2?.toLowerCase(), '27 ekim');
const n3 = InsightService.extractTeacherCheckNote('12 MF:X YAYINCILIK (ÖDEVLER 26-30 EKİM ARASINDA KONTROL EDİLECEKTİR.)');
assert.strictEqual(n3?.toLowerCase(), '26-30 ekim');
const n4 = InsightService.extractTeacherCheckNote('AYT 1. KİTAP [26-56] ÇÖZÜLECEKTİR. 26 10 KONTROL');
assert.strictEqual(n4?.toLowerCase(), '26 ekim');
const nNone = InsightService.extractTeacherCheckNote('Toprak Yayınları Bölüm 4 çözülecek.');
assert.strictEqual(nNone, null);
});
// 3. Status Computation
await test('InsightService: computeStatus correctly handles completed, next-week, and overdue', () => {
const refDate = new Date(2026, 9, 21);
const s1 = InsightService.computeStatus({
id: 'test1',
subject: 'Matematik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '10.10.2026',
endDate: '25.10.2026',
parsedStartDate: '2026-10-10',
parsedEndDate: '2026-10-25',
description: 'Test',
detectedCheckDate: null,
completed: true,
completedAt: '2026-10-21T10:00:00Z'
}, refDate);
assert.strictEqual(s1, 'completed');
const s2 = InsightService.computeStatus({
id: 'test2',
subject: 'Biyoloji',
type: 'Yayın',
unit: '',
topic: '',
startDate: '01.10.2026',
endDate: '19.10.2026',
parsedStartDate: '2026-10-01',
parsedEndDate: '2026-10-19',
description: 'Old test',
detectedCheckDate: null,
completed: false,
completedAt: null
}, refDate);
assert.strictEqual(s2, 'overdue');
const s3 = InsightService.computeStatus({
id: 'test3',
subject: 'AYT Kimya',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'ayt 237-242 kontrol tarihi 26-30 ekim',
detectedCheckDate: '26-30 ekim',
completed: false,
completedAt: null
}, refDate);
assert.strictEqual(s3, 'next-week');
});
// 4. Statistics Calculation
await test('InsightService: calculateStats computes accurate completion rates and subject breakdown', () => {
const sampleAssignments: Assignment[] = [
{
id: '1',
subject: 'Kimya',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'Test 1',
detectedCheckDate: null,
status: 'next-week',
completed: false,
completedAt: null
},
{
id: '2',
subject: 'Kimya',
type: 'Yayın',
unit: '',
topic: '',
startDate: '10.10.2026',
endDate: '15.10.2026',
parsedStartDate: '2026-10-10',
parsedEndDate: '2026-10-15',
description: 'Test 2',
detectedCheckDate: null,
status: 'completed',
completed: true,
completedAt: '2026-10-21T10:00:00Z'
},
{
id: '3',
subject: 'Fizik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '01.10.2026',
endDate: '10.10.2026',
parsedStartDate: '2026-10-01',
parsedEndDate: '2026-10-10',
description: 'Test 3',
detectedCheckDate: null,
status: 'overdue',
completed: false,
completedAt: null
}
];
const stats = InsightService.calculateStats(sampleAssignments);
assert.strictEqual(stats.total, 3);
assert.strictEqual(stats.completed, 1);
assert.strictEqual(stats.checkedNextWeek, 1);
assert.strictEqual(stats.overdue, 1);
assert.strictEqual(stats.completionRate, 33);
assert.strictEqual(stats.bySubject['Kimya'].total, 2);
assert.strictEqual(stats.bySubject['Kimya'].completed, 1);
assert.strictEqual(stats.bySubject['Kimya'].percentage, 50);
// Test with an excluded (disincluded) assignment
const sampleWithExcluded: Assignment[] = [
...sampleAssignments,
{
id: '4',
subject: 'Fizik',
type: 'Yayın',
unit: '',
topic: '',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'Other class homework',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null,
excluded: true
}
];
const statsExcluded = InsightService.calculateStats(sampleWithExcluded);
assert.strictEqual(statsExcluded.total, 3, 'Disincluded assignment must NOT increase total count');
assert.strictEqual(statsExcluded.excludedCount, 1);
assert.strictEqual(statsExcluded.bySubject['Fizik'].total, 1, 'Disincluded assignment must NOT be in subject total');
});
// 5. Local Database
await test('LocalDatabase: save, merge, and toggle checkboxes in db.json', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_${Date.now()}`;
const testItem: Assignment = {
id: `hash_${Date.now()}`,
subject: 'Matematik',
type: 'Yayın',
unit: 'Fonksiyonlar',
topic: 'Test',
startDate: '20.10.2026',
endDate: '26.10.2026',
parsedStartDate: '2026-10-20',
parsedEndDate: '2026-10-26',
description: 'Sayfa 50-60',
detectedCheckDate: null,
status: 'active',
completed: false,
completedAt: null
};
db.mergeAssignments(testStudentId, [testItem]);
let store = db.getStudentStore(testStudentId);
assert(store.assignments[testItem.id]);
assert.strictEqual(store.assignments[testItem.id].completed, false);
const updated = db.toggleAssignment(testStudentId, testItem.id, true);
assert.strictEqual(updated?.completed, true);
assert(updated?.completedAt !== null);
db.mergeAssignments(testStudentId, [{
...testItem,
completed: false
}]);
store = db.getStudentStore(testStudentId);
assert.strictEqual(
store.assignments[testItem.id].completed,
true,
'mergeAssignments MUST preserve user checked status!'
);
// Test disinclude / exclude toggle & preservation across merge
const excludedRes = db.toggleExcludeAssignment(testStudentId, testItem.id, true);
assert.strictEqual(excludedRes?.excluded, true);
// Re-merge from scraper (which always returns excluded undefined or false)
db.mergeAssignments(testStudentId, [{
...testItem,
completed: false
}]);
store = db.getStudentStore(testStudentId);
assert.strictEqual(
store.assignments[testItem.id].excluded,
true,
'mergeAssignments MUST preserve disincluded (excluded) status across scraper syncs!'
);
// Restore / Include back
db.toggleExcludeAssignment(testStudentId, testItem.id, false);
store = db.getStudentStore(testStudentId);
assert.strictEqual(store.assignments[testItem.id].excluded, false);
db.saveCredentials(testStudentId, 'test_pass');
const creds = db.getRememberedCredentials(testStudentId);
assert.strictEqual(creds?.password, 'test_pass');
db.clearCredentials(testStudentId);
assert.strictEqual(db.getRememberedCredentials(testStudentId), null);
});
// 6. Syllabus & Station Filtering Tests
await test('SyllabusService: getWeekMetadata computes accurate ISO week and Monday-Friday dates', () => {
const refDate = new Date(2026, 9, 21); // Wednesday 21 Oct 2026
const meta = SyllabusService.getWeekMetadata(refDate);
assert(meta.weekId.includes('2026-W43') || meta.weekId.includes('2026-W'), 'Must have valid week ID');
assert(meta.weekRange.includes('19.10.2026 - 23.10.2026'), `Expected 19.10 - 23.10, got ${meta.weekRange}`);
});
await test('SyllabusService: normalizeStation handles various formats', () => {
assert.strictEqual(SyllabusService.normalizeStation('İst4'), 'İst-4');
assert.strictEqual(SyllabusService.normalizeStation('İst-4'), 'İst-4');
assert.strictEqual(SyllabusService.normalizeStation('ist1'), 'İst-1');
assert.strictEqual(SyllabusService.normalizeStation('2'), 'İst-2');
assert.strictEqual(SyllabusService.normalizeStation(null), null);
});
await test('SyllabusService: filterLessonsForStation isolates student station and keeps class lessons', () => {
const rawWednesdayLessons: Lesson[] = [
// Period 1 has 5 stations + duplicates
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst1', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst2', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst3', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
{ period: '1. Ders', periodNumber: 1, subject: 'Türk Edebiyatı', teacher: 'OĞUZHAN YİĞİT', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst5', day: 3, dayName: 'Çarşamba' },
// Period 2 is whole-class (no station)
{ period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
];
// Filter for İst-4
const filteredForIst4 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-4');
assert.strictEqual(filteredForIst4.length, 2, 'Should have exactly 2 lessons: 1 for İst-4 and 1 for class');
assert.strictEqual(filteredForIst4[0].subject, 'TYT Kimya');
assert.strictEqual(filteredForIst4[0].station, 'İst4');
assert.strictEqual(filteredForIst4[1].subject, 'TYT Matematik');
assert.strictEqual(filteredForIst4[1].station, null);
// Filter for İst-5
const filteredForIst5 = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'İst-5');
assert.strictEqual(filteredForIst5.length, 2);
assert.strictEqual(filteredForIst5[0].subject, 'Türk Edebiyatı');
assert.strictEqual(filteredForIst5[0].station, 'İst5');
// Filter for "all"
const filteredAll = SyllabusService.filterLessonsForStation(rawWednesdayLessons, 'all');
assert.strictEqual(filteredAll.length, 6, 'Should show all 5 stations + 1 class lesson');
});
await test('SyllabusService: getCurrentLessonStatus correctly detects active and upcoming lessons', () => {
const lessons: Lesson[] = [
{ period: '1. Ders', periodNumber: 1, subject: 'TYT Kimya', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '09:30', endTime: '10:05', time: '09:30 - 10:05', station: 'İst4', day: 3, dayName: 'Çarşamba' },
{ period: '2. Ders', periodNumber: 2, subject: 'TYT Matematik', teacher: 'BİRKAN BOZKURT', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 3, dayName: 'Çarşamba' }
];
// Simulate Wednesday at 09:45 (during 1. Ders)
const activeTime = new Date(2026, 9, 21, 9, 45);
const activeRes = SyllabusService.getCurrentLessonStatus(lessons, 3, activeTime);
assert(activeRes.currentLesson !== null);
assert.strictEqual(activeRes.currentLesson?.subject, 'TYT Kimya');
// Simulate Wednesday at 10:08 (break before 2. Ders)
const breakTime = new Date(2026, 9, 21, 10, 8);
const breakRes = SyllabusService.getCurrentLessonStatus(lessons, 3, breakTime);
assert.strictEqual(breakRes.currentLesson, null);
assert(breakRes.nextLesson !== null);
assert.strictEqual(breakRes.nextLesson?.subject, 'TYT Matematik');
});
await test('LocalDatabase: saveSyllabus, getSyllabus, and setStudentStation persist in db.json', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_syl_${Date.now()}`;
db.saveSyllabus(testStudentId, '2026-W43', '19.10.2026 - 23.10.2026', {
1: [],
2: [],
3: [],
4: [],
5: []
});
let s = db.getSyllabus(testStudentId);
assert(s !== null);
assert.strictEqual(s.weekId, '2026-W43');
db.setStudentStation(testStudentId, 'İst-4');
s = db.getSyllabus(testStudentId);
assert.strictEqual(s.selectedStation, 'İst-4');
});
// 7. Advisory Teacher & Private Lessons Tests
await test('SyllabusService: advisoryTeacher filtering collapses multiple Danışmanlık teachers down to student advisor', () => {
// 5 advisory variations for period 2
const tuesdayLessons: Lesson[] = [
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'ÜLKÜ ESEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'CAN TÜRKOĞLU', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'SEVGİ BİKİL', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MERVE BAŞTAN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' },
{ period: '2. Ders', periodNumber: 2, subject: 'Danışmanlık', teacher: 'MUSTAFA ŞEN', teacherPhoto: null, startTime: '10:15', endTime: '10:51', time: '10:15 - 10:51', station: null, day: 2, dayName: 'Salı' }
];
// Filter with CAN TÜRKOĞLU
const filteredForCan = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'CAN TÜRKOĞLU');
assert.strictEqual(filteredForCan.length, 1, 'Should filter out the other 4 teachers and keep exactly 1');
assert.strictEqual(filteredForCan[0].teacher, 'CAN TÜRKOĞLU');
// Filter with ÜLKÜ ESEN
const filteredForUlku = SyllabusService.filterLessonsForStation(tuesdayLessons, 'İst-4', 'ÜLKÜ ESEN');
assert.strictEqual(filteredForUlku.length, 1);
assert.strictEqual(filteredForUlku[0].teacher, 'ÜLKÜ ESEN');
});
await test('LocalDatabase: savePrivateLessons, getPrivateLessons, and advisory teacher persistence', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_pl_${Date.now()}`;
const mockLessons = [
{
id: 'pl_1',
subject: 'Coğrafya',
teacherName: 'SEVDA KILIÇOĞLU',
teacherPhoto: 'http://example.com/2337.jpg',
date: '26.10.2026',
parsedDate: '2026-10-26',
isUpcoming: true
},
{
id: 'pl_2',
subject: 'Danışmanlık',
teacherName: 'CAN TÜRKOĞLU',
teacherPhoto: 'http://example.com/2211.jpg',
date: '20.10.2026',
parsedDate: '2026-10-20',
isUpcoming: false
}
];
db.savePrivateLessons(testStudentId, mockLessons, undefined, 'CAN TÜRKOĞLU');
const plStore = db.getPrivateLessons(testStudentId);
assert(plStore !== null);
assert.strictEqual(plStore.lessons.length, 2);
assert.strictEqual(plStore.detectedAdvisor, 'CAN TÜRKOĞLU');
// Verify auto-set advisory teacher
assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'CAN TÜRKOĞLU');
// Manual override
db.setStudentAdvisoryTeacher(testStudentId, 'SEVGİ BİKİL');
assert.strictEqual(db.getStudentAdvisoryTeacher(testStudentId), 'SEVGİ BİKİL');
});
// 6. Exam Reports & Analytics Tests
await test('ExamService: categorizeExam correctly segregates TYT and AYT', () => {
assert.strictEqual(ExamService.categorizeExam('12 YKS-01_MF'), 'TYT');
assert.strictEqual(ExamService.categorizeExam('12 YKS-04 MF'), 'TYT');
assert.strictEqual(ExamService.categorizeExam('TYT Deneme Sınavı 3'), 'TYT');
assert.strictEqual(ExamService.categorizeExam('12 AYT-01 MF'), 'AYT');
assert.strictEqual(ExamService.categorizeExam('AYT Sayısal Deneme'), 'AYT');
assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 80), 'AYT');
assert.strictEqual(ExamService.categorizeExam('Bilinmeyen Sınav', 120), 'TYT');
});
await test('ExamService: computeDeltasAndRatings calculates Net deltas, Rank deltas, and difficulty-adjusted ratings', () => {
const mockExams: ExamReportDetail[] = [
{
summary: {
id: '3322',
name: '12 YKS-01_MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 78,
totalWrong: 22,
totalEmpty: 20,
totalNet: 72.50,
totalScore: 72.50,
generalRank: 16
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 6, emptyCount: 4, net: 28.5, score: 28.5, percentage: 71 }
],
hasAnswerKey: true
},
{
summary: {
id: '3326',
name: '12 YKS-02_MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 88,
totalWrong: 18,
totalEmpty: 14,
totalNet: 83.50,
totalScore: 83.50,
generalRank: 14
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 35, wrongCount: 2, emptyCount: 3, net: 34.5, score: 34.5, percentage: 86 }
],
hasAnswerKey: true
},
{
summary: {
id: '3340',
name: '12 YKS-03 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 92,
totalWrong: 16,
totalEmpty: 12,
totalNet: 88.00,
totalScore: 88.00,
generalRank: 8
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 36, wrongCount: 2, emptyCount: 2, net: 35.5, score: 35.5, percentage: 89 }
],
hasAnswerKey: true
},
{
summary: {
id: '3366',
name: '12 YKS-04 MF',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 86,
totalWrong: 14,
totalEmpty: 20,
totalNet: 82.50, // Net dropped due to harder test
totalScore: 82.50,
generalRank: 9 // Held single-digit rank #9
},
subjects: [
{ subjectId: '1', subjectName: 'Türkçe', questionCount: 40, correctCount: 30, wrongCount: 7, emptyCount: 3, net: 28.25, score: 28.25, percentage: 75 }
],
hasAnswerKey: true
}
];
const processed = ExamService.computeDeltasAndRatings(mockExams);
assert.strictEqual(processed.length, 4);
// Map by ID for assertion
const yks1 = processed.find(p => p.summary.id === '3322')!;
const yks2 = processed.find(p => p.summary.id === '3326')!;
const yks3 = processed.find(p => p.summary.id === '3340')!;
const yks4 = processed.find(p => p.summary.id === '3366')!;
// Exam 1: Baseline
assert.strictEqual(yks1.summary.deltaNet, undefined);
assert.strictEqual(yks1.summary.deltaRank, undefined);
// Exam 2: Net +11.00, Rank improved from 16 to 14 (+2 places climbed) -> Breakthrough
assert.strictEqual(yks2.summary.deltaNet, 11.00);
assert.strictEqual(yks2.summary.deltaRank, 2);
assert.strictEqual(yks2.summary.rating?.label, 'Breakthrough');
assert.strictEqual(yks2.subjects[0].deltaNet, 6.00); // 34.5 - 28.5
// Exam 3: Net +4.50, Rank improved from 14 to 8 (+6 places climbed) -> Breakthrough
assert.strictEqual(yks3.summary.deltaNet, 4.50);
assert.strictEqual(yks3.summary.deltaRank, 6);
assert.strictEqual(yks3.summary.rating?.label, 'Breakthrough');
// Exam 4: Net -5.50 (harder exam), but rank held in top 10 (#9) -> Outperformed Curve!
assert.strictEqual(yks4.summary.deltaNet, -5.50);
assert.strictEqual(yks4.summary.deltaRank, -1);
assert.strictEqual(yks4.summary.rating?.label, 'Outperformed Curve');
});
await test('ExamService: calculateKPIs correctly computes aggregate metrics', () => {
const mockDetails: ExamReportDetail[] = [
{
summary: {
id: '1',
name: 'Exam 1',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 80,
totalWrong: 20,
totalEmpty: 20,
totalNet: 75.0,
totalScore: 75.0,
generalRank: 15
},
subjects: [],
hasAnswerKey: false
},
{
summary: {
id: '2',
name: 'Exam 2',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 90,
totalWrong: 15,
totalEmpty: 15,
totalNet: 85.0,
totalScore: 85.0,
generalRank: 5
},
subjects: [],
hasAnswerKey: false
}
];
const kpis = ExamService.calculateKPIs(mockDetails);
assert.strictEqual(kpis.latestNet, 75.0);
assert.strictEqual(kpis.bestNet, 85.0);
assert.strictEqual(kpis.averageNet, 80.0);
assert.strictEqual(kpis.bestRank, 5);
assert.strictEqual(kpis.averageRank, 10);
assert.strictEqual(kpis.totalExams, 2);
});
await test('LocalDatabase: saveExamReports and saveTopicWeaknesses persistence', () => {
const db = LocalDatabase.getInstance();
const testStudentId = `test_student_exam_${Date.now()}`;
const mockDetail: ExamReportDetail = {
summary: {
id: '9999',
name: 'Test Exam',
examType: 'TYT',
totalQuestions: 120,
totalCorrect: 80,
totalWrong: 20,
totalEmpty: 20,
totalNet: 75.0,
totalScore: 75.0,
generalRank: 10
},
subjects: [],
hasAnswerKey: false
};
db.saveExamReports(testStudentId, [mockDetail]);
const examStore = db.getExamReports(testStudentId);
assert(examStore !== null);
assert(examStore.reports['9999'] !== undefined);
assert.strictEqual(examStore.reports['9999'].summary.name, 'Test Exam');
// Topic weaknesses
const mockWeakness = [
{
examId: '9999',
examName: 'Test Exam',
subjectName: 'Türkçe',
topicName: 'Paragraf',
totalCount: 5,
correctCount: 2,
wrongCount: 3,
emptyCount: 0,
successRate: 40
}
];
db.saveTopicWeaknesses(testStudentId, '9999', mockWeakness);
const retrieved = db.getTopicWeaknesses(testStudentId, '9999');
assert(retrieved !== null);
assert.strictEqual(retrieved.length, 1);
assert.strictEqual(retrieved[0].topicName, 'Paragraf');
});
// 7. PWA & Offline Support Tests
await test('PWA: manifest.json is valid and contains standard required PWA fields and icons', () => {
const fs = require('fs');
const path = require('path');
const manifestPath = path.resolve(__dirname, '../public/manifest.json');
assert(fs.existsSync(manifestPath), 'manifest.json must exist in public directory');
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
assert.strictEqual(manifest.name, 'BeKultur');
assert.strictEqual(manifest.short_name, 'BeKultur');
assert.strictEqual(manifest.display, 'standalone');
assert.strictEqual(manifest.start_url, '/');
assert(Array.isArray(manifest.icons) && manifest.icons.length >= 2, 'manifest must declare icons');
// Verify all referenced icons physically exist
manifest.icons.forEach((ic: { src: string }) => {
const iconPath = path.resolve(__dirname, '../public', ic.src.replace(/^\//, ''));
assert(fs.existsSync(iconPath), `Icon file ${ic.src} must exist at ${iconPath}`);
});
});
await test('PWA: sw.js contains static asset pre-caching and offline cache fallback strategies', () => {
const fs = require('fs');
const path = require('path');
const swPath = path.resolve(__dirname, '../public/sw.js');
assert(fs.existsSync(swPath), 'sw.js must exist in public directory');
const swContent = fs.readFileSync(swPath, 'utf-8');
assert(swContent.includes('CACHE_NAME'), 'sw.js must define cache name');
assert(swContent.includes('STATIC_ASSETS'), 'sw.js must define static assets array');
assert(swContent.includes("addEventListener('install'"), 'sw.js must have install event listener');
assert(swContent.includes("addEventListener('activate'"), 'sw.js must have activate event listener');
assert(swContent.includes("addEventListener('fetch'"), 'sw.js must have fetch event listener');
assert(swContent.includes('caches.match'), 'sw.js must contain cache match fallback');
});
await test('PWA: pwa.js contains offline detection and UI safeguard handlers', () => {
const fs = require('fs');
const path = require('path');
const pwaPath = path.resolve(__dirname, '../public/js/pwa.js');
assert(fs.existsSync(pwaPath), 'pwa.js must exist in public/js directory');
const pwaContent = fs.readFileSync(pwaPath, 'utf-8');
assert(pwaContent.includes(".register('/sw.js'"), 'pwa.js must register service worker');
assert(pwaContent.includes("addEventListener('online'"), 'pwa.js must listen for online event');
assert(pwaContent.includes("addEventListener('offline'"), 'pwa.js must listen for offline event');
assert(pwaContent.includes('offlineBanner'), 'pwa.js must manage offline banner');
assert(pwaContent.includes('assignment-toggle'), 'pwa.js must manage homework checkboxes in offline mode');
assert(pwaContent.includes('privateLessonForm'), 'pwa.js must manage private lesson request form in offline mode');
assert(pwaContent.includes('btnSync'), 'pwa.js must manage sync buttons in offline mode');
});
// 6. Security & Hardening Tests
await test('LocalDatabase: saveCredentials encrypts with AES-256-GCM and getRememberedCredentials decrypts', () => {
const fs = require('fs');
const path = require('path');
const db = LocalDatabase.getInstance();
const dbFile = path.resolve(process.cwd(), 'data', 'db.json');
const testId = 'audit_security_student';
const rawPass = 'SuperSecret123!';
db.saveCredentials(testId, rawPass);
// Verify stored format on disk is encrypted
const onDiskRaw = JSON.parse(fs.readFileSync(dbFile, 'utf-8'));
const storedCred = onDiskRaw.students[testId]?.rememberedCredentials;
assert(storedCred, 'Credentials must be saved');
assert(storedCred.password.startsWith('enc:'), 'Stored password must be encrypted with enc: prefix');
assert(!storedCred.password.includes(rawPass), 'Raw password must not be present in database file');
// Verify retrieval returns decrypted password
const retrieved = db.getRememberedCredentials(testId);
assert(retrieved !== null, 'Retrieved credentials must not be null');
assert.strictEqual(retrieved.password, rawPass, 'Decrypted password must match original raw password');
// Clean up
db.clearCredentials(testId);
});
await test('LocalDatabase: saveExamQuestions and getExamQuestions persists question review cache', () => {
const db = LocalDatabase.getInstance();
const testId = 'audit_exam_student';
const examKey = '3366_Y';
const sampleQuestions = [
{
questionNumber: 1,
correctAnswer: 'A',
studentAnswer: 'C',
imageUrl: 'https://panel.example.com/soru/1.png',
status: 'wrong' as const,
subjectId: '10',
subjectName: 'Türkçe'
}
];
db.saveExamQuestions(testId, examKey, sampleQuestions);
const cached = db.getExamQuestions(testId, examKey);
assert(cached !== null, 'Cached questions should exist');
assert.strictEqual(cached.length, 1);
assert.strictEqual(cached[0].questionNumber, 1);
assert.strictEqual(cached[0].correctAnswer, 'A');
});
await test('PWA: sw.js contains route-specific offline fallbacks and ignoreSearch', () => {
const fs = require('fs');
const path = require('path');
const swPath = path.resolve(__dirname, '../public/sw.js');
const swContent = fs.readFileSync(swPath, 'utf-8');
assert(swContent.includes('ignoreSearch: true'), 'sw.js must match cache ignoring query strings');
assert(swContent.includes("url.pathname.startsWith('/exams')"), 'sw.js must have route fallback for exams');
assert(swContent.includes("url.pathname.startsWith('/syllabus')"), 'sw.js must have route fallback for syllabus');
assert(swContent.includes("url.pathname.startsWith('/private-lessons')"), 'sw.js must have route fallback for private lessons');
});
// 7. Optional Live Portal Test (via environment variables only)
const testStudentId = process.env.TEST_STUDENT_ID;
const testPassword = process.env.TEST_PASSWORD;
if (testStudentId && testPassword) {
await test('ScraperService: Live portal authentication and scraping', async () => {
const loginRes = await ScraperService.login(testStudentId, testPassword);
assert.strictEqual(loginRes.success, true, `Login failed: ${loginRes.error}`);
const scrapeRes = await ScraperService.scrapePage(loginRes.cookies, 1, testStudentId);
assert(scrapeRes.assignments.length > 0, 'Page 1 must contain homework cards');
});
} else {
console.log(' - Live portal test skipped (set TEST_STUDENT_ID and TEST_PASSWORD to run)');
}
console.log('\n--------------------------------------------------------');
console.log(`Test Results: ${passed} passed, ${failed} failed`);
console.log('--------------------------------------------------------\n');
if (failed > 0) {
process.exit(1);
}
}
runAllTests().catch(err => {
console.error('Fatal test error:', err);
process.exit(1);
});