461 lines
19 KiB
TypeScript
461 lines
19 KiB
TypeScript
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 { Assignment, Lesson } 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. 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);
|
||
});
|