-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathloadNotificationsFile.test.ts
More file actions
465 lines (400 loc) · 16.8 KB
/
Copy pathloadNotificationsFile.test.ts
File metadata and controls
465 lines (400 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Unit Test File for NotificationsService: loadNotificationFile
import { ConfigService } from '@nestjs/config';
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NotificationIni } from '@app/core/types/states/notification.js';
import {
Notification,
NotificationImportance,
NotificationType,
} from '@app/unraid-api/graph/resolvers/notifications/notifications.model.js';
import { NotificationsService } from '@app/unraid-api/graph/resolvers/notifications/notifications.service.js';
const { mockWatch } = vi.hoisted(() => {
const watcher = {
on: vi.fn().mockReturnThis(),
close: vi.fn().mockResolvedValue(undefined),
};
return {
mockWatch: vi.fn(() => watcher),
};
});
// Mock fs/promises for unit tests
vi.mock('fs/promises', async () => {
const actual = await vi.importActual<typeof import('fs/promises')>('fs/promises');
const mockReadFile = vi.fn();
const mockStat = vi.fn(actual.stat);
return {
...actual,
readFile: mockReadFile,
stat: mockStat,
};
});
vi.mock('chokidar', () => ({
watch: mockWatch,
}));
// Mock getters.dynamix, Logger, and pubsub
vi.mock('@app/store/index.js', () => {
const testNotificationsDir = join(tmpdir(), 'unraid-api-test-notifications');
return {
getters: {
dynamix: vi.fn().mockReturnValue({
notify: { path: testNotificationsDir },
display: {
date: 'Y-m-d',
time: 'H:i:s',
},
}),
},
};
});
vi.mock('@app/core/pubsub.js', () => ({
pubsub: {
publish: vi.fn(),
},
PUBSUB_CHANNEL: {
NOTIFICATION_OVERVIEW: 'notification_overview',
NOTIFICATION_ADDED: 'notification_added',
},
}));
vi.mock('@nestjs/common', async (importOriginal) => {
const original = await importOriginal<typeof import('@nestjs/common')>();
return {
...original,
Logger: vi.fn(() => ({
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
verbose: vi.fn(),
})),
};
});
// Create a temporary test directory path for use in integration tests
const testNotificationsDir = join(tmpdir(), 'unraid-api-test-notifications');
const createNotificationsService = (notificationPath = testNotificationsDir) => {
const configService = new ConfigService({
store: {
dynamix: {
notify: {
path: notificationPath,
},
},
},
});
return new NotificationsService(configService);
};
describe('NotificationsService - loadNotificationFile (minimal mocks)', () => {
let service: NotificationsService;
let mockReadFile: typeof import('fs/promises').readFile;
let mockStat: typeof import('fs/promises').stat;
beforeEach(async () => {
const fsPromises = await import('fs/promises');
mockReadFile = fsPromises.readFile;
mockStat = fsPromises.stat;
vi.mocked(mockReadFile).mockClear();
vi.mocked(mockStat).mockClear();
mockWatch.mockClear();
Reflect.set(NotificationsService, 'watcher', null);
service = createNotificationsService();
await Reflect.get(service, 'initialization');
});
afterEach(() => {
Reflect.set(NotificationsService, 'watcher', null);
});
it('creates the notifications watcher without replaying existing files', () => {
// The configured path (testNotificationsDir) is not the tmpfs default, so the
// always-off-disk active dir falls outside it and is watched as a second path.
expect(mockWatch).toHaveBeenCalledWith(
[testNotificationsDir, '/tmp/notifications/active'],
expect.objectContaining({
ignoreInitial: true,
})
);
});
it('replays buffered add events after overview hydration', async () => {
const bufferedPath = `${testNotificationsDir}/unread/buffered.notify`;
const hydratedService = createNotificationsService();
const processNotificationAdd = vi.fn().mockResolvedValue(undefined);
const handleNotificationAdd = (
Reflect.get(hydratedService, 'handleNotificationAdd') as (path: string) => Promise<void>
).bind(hydratedService);
Reflect.set(
hydratedService,
'ensureNotificationDirectories',
vi.fn().mockResolvedValue(undefined)
);
Reflect.set(hydratedService, 'publishOverview', vi.fn().mockResolvedValue(undefined));
Reflect.set(hydratedService, 'processNotificationAdd', processNotificationAdd);
Reflect.set(
hydratedService,
'getNotificationsWatcher',
vi.fn().mockImplementation(async () => {
await handleNotificationAdd(bufferedPath);
return {
close: vi.fn().mockResolvedValue(undefined),
on: vi.fn().mockReturnThis(),
};
})
);
Reflect.set(
hydratedService,
'buildOverviewSnapshot',
vi.fn().mockResolvedValue({
errorOccurred: false,
overview: {
unread: { alert: 0, info: 0, warning: 0, total: 0 },
archive: { alert: 0, info: 0, warning: 0, total: 0 },
},
seenPaths: new Set<string>(),
})
);
await Reflect.get(hydratedService, 'initializeNotificationsState').call(
hydratedService,
testNotificationsDir,
true
);
expect(processNotificationAdd).toHaveBeenCalledWith(bufferedPath);
});
it('debounces a single authoritative recalc when notification files are unlinked', async () => {
vi.useFakeTimers();
try {
const recalc = vi
.spyOn(service, 'recalculateOverview')
.mockResolvedValue({ error: false, overview: service.getOverview() });
Reflect.set(service, 'publishWarningsAndAlerts', vi.fn().mockResolvedValue(undefined));
const handleUnlink = (
Reflect.get(service, 'handleNotificationUnlink') as (path: string) => void
).bind(service);
// Non-notification files are ignored entirely.
handleUnlink(`${testNotificationsDir}/active/not-a-notification.txt`);
// A burst of real removals collapses into one rebuild.
handleUnlink(`${testNotificationsDir}/active/a.notify`);
handleUnlink(`${testNotificationsDir}/active/b.notify`);
handleUnlink(`${testNotificationsDir}/unread/c.notify`);
expect(recalc).not.toHaveBeenCalled(); // still within the debounce window
await vi.advanceTimersByTimeAsync(200);
expect(recalc).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});
it('should load and validate a valid notification file', async () => {
const mockFileContent = `timestamp=1609459200
event=Test Event
subject=Test Subject
description=Test Description
importance=alert
link=http://example.com`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/test.notify',
NotificationType.UNREAD
);
expect(result).toEqual(
expect.objectContaining({
id: 'test.notify',
type: NotificationType.UNREAD,
title: 'Test Event',
subject: 'Test Subject',
description: 'Test Description',
importance: NotificationImportance.ALERT,
link: 'http://example.com',
timestamp: '2021-01-01T00:00:00.000Z',
})
);
});
it('should return masked warning notification on validation error (missing required fields)', async () => {
const mockFileContent = `timestamp=1609459200
subject=Test Subject
description=Test Description
importance=alert`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/invalid.notify',
NotificationType.UNREAD
);
expect(result.id).toBe('invalid.notify');
expect(result.importance).toBe(NotificationImportance.WARNING);
expect(result.description).toContain('invalid and cannot be displayed');
});
it('should handle invalid enum values', async () => {
const mockFileContent = `timestamp=1609459200
event=Test Event
subject=Test Subject
description=Test Description
importance=not-a-valid-enum`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/invalid-enum.notify',
NotificationType.UNREAD
);
expect(result.id).toBe('invalid-enum.notify');
// Implementation falls back to INFO for unknown importance
expect(result.importance).toBe(NotificationImportance.INFO);
// Should not be a masked warning notification, just fallback to INFO
expect(result.description).toBe('Test Description');
});
it('should allow a missing description field (empty is valid, not masked)', async () => {
const mockFileContent = `timestamp=1609459200
event=Test Event
subject=Test Subject
importance=normal`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/test.notify',
NotificationType.UNREAD
);
// A missing description is allowed: condition/banner notifications carry their
// meaning in the title + Active badge, and the UI hides the empty line. It must
// not be masked as invalid.
expect(result.id).toBe('test.notify');
expect(result.description).toBe('');
expect(result.description).not.toContain('invalid and cannot be displayed');
expect(result.importance).toBe(NotificationImportance.INFO);
});
it('should preserve passthrough data from notification file (only known fields)', async () => {
const mockFileContent = `timestamp=1609459200
event=Test Event
subject=Test Subject
description=Test Description
importance=normal
link=http://example.com
customField=custom value`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/test.notify',
NotificationType.UNREAD
);
expect(result).toEqual(
expect.objectContaining({
link: 'http://example.com',
// customField should NOT be present
description: 'Test Description',
id: 'test.notify',
type: NotificationType.UNREAD,
title: 'Test Event',
subject: 'Test Subject',
importance: NotificationImportance.INFO,
timestamp: '2021-01-01T00:00:00.000Z',
})
);
expect((result as any).customField).toBeUndefined();
});
it('should handle missing timestamp field gracefully', async () => {
const mockFileContent = `event=Test Event
subject=Test Subject
description=Test Description
importance=alert`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/missing-timestamp.notify',
NotificationType.UNREAD
);
expect(result.id).toBe('missing-timestamp.notify');
expect(result.importance).toBe(NotificationImportance.ALERT);
expect(result.description).toBe('Test Description');
expect(result.timestamp).toBeUndefined(); // Missing timestamp results in undefined
expect(result.formattedTimestamp).toBe(undefined); // Also undefined since timestamp is missing
});
it('should handle malformed timestamp field gracefully', async () => {
const mockFileContent = `timestamp=not-a-timestamp
event=Test Event
subject=Test Subject
description=Test Description
importance=alert`;
vi.mocked(mockReadFile).mockResolvedValue(mockFileContent);
const result = await (service as any).loadNotificationFile(
'/test/path/malformed-timestamp.notify',
NotificationType.UNREAD
);
expect(result.id).toBe('malformed-timestamp.notify');
expect(result.importance).toBe(NotificationImportance.ALERT);
expect(result.description).toBe('Test Description');
expect(result.timestamp).toBeUndefined(); // Malformed timestamp results in undefined
expect(result.formattedTimestamp).toBe('not-a-timestamp'); // Returns original string when parsing fails
});
it('limits concurrent notification file reads', async () => {
const fileCount = 96;
const files = Array.from({ length: fileCount }, (_, index) => `/test/path/${index}.notify`);
let activeReads = 0;
let maxConcurrentReads = 0;
vi.mocked(mockReadFile).mockImplementation(async () => {
activeReads += 1;
maxConcurrentReads = Math.max(maxConcurrentReads, activeReads);
await new Promise((resolve) => setTimeout(resolve, 5));
activeReads -= 1;
return `timestamp=1609459200
event=Test Event
subject=Test Subject
description=Test Description
importance=alert`;
});
const [notifications] = await Reflect.get(service, 'loadNotificationsFromPaths').call(
service,
files,
{}
);
expect(notifications).toHaveLength(fileCount);
expect(maxConcurrentReads).toBeLessThanOrEqual(32);
});
it('surfaces stat failures when listing notification files', async () => {
const unreadPath = join(testNotificationsDir, 'unread');
const filePath = join(unreadPath, 'stat-failure.notify');
writeFileSync(filePath, 'timestamp=1609459200');
vi.mocked(mockStat).mockRejectedValueOnce(new Error('stat failed'));
await expect(
Reflect.get(service, 'listFilesInFolder').call(service, unreadPath)
).rejects.toThrow();
});
});
describe('NotificationsService - deleteNotification (integration test)', () => {
let service: NotificationsService;
beforeEach(async () => {
// Clean up any existing test directory
if (existsSync(testNotificationsDir)) {
rmSync(testNotificationsDir, { recursive: true, force: true });
}
// Create fresh directory structure
mkdirSync(testNotificationsDir, { recursive: true });
mkdirSync(join(testNotificationsDir, 'unread'), { recursive: true });
mkdirSync(join(testNotificationsDir, 'archive'), { recursive: true });
service = createNotificationsService();
await Reflect.get(service, 'initialization');
});
afterEach(() => {
// Clean up after each test
if (existsSync(testNotificationsDir)) {
rmSync(testNotificationsDir, { recursive: true, force: true });
}
});
it('should successfully delete an invalid notification file from disk', async () => {
// Create a truly invalid notification with only timestamp - missing all required fields
const invalidNotificationContent = `
timestamp=1609459200
`.trim();
const notificationId = 'invalid-test.notify';
const filePath = join(testNotificationsDir, 'unread', notificationId);
// Create actual invalid notification file on disk
writeFileSync(filePath, invalidNotificationContent);
// Verify file exists before deletion
expect(existsSync(filePath)).toBe(true);
const result = await service.deleteNotification({
id: notificationId,
type: NotificationType.UNREAD,
});
// The key integration test: verify file was actually deleted from disk
expect(existsSync(filePath)).toBe(false);
// Verify the service returns a notification object (even if mocked content)
expect(result.notification).toBeDefined();
expect(result.notification.id).toBe(notificationId);
expect(result.notification.type).toBe(NotificationType.UNREAD);
// Verify overview is returned and updated
expect(result.overview).toBeDefined();
expect(result.overview.unread).toBeDefined();
expect(result.overview.archive).toBeDefined();
// The service should be able to handle deletion of any file, valid or invalid
expect(result.notification.importance).toMatch(/ALERT|WARNING|INFO/);
});
});