-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathFileSource.basic.test.ts
More file actions
454 lines (368 loc) · 13.5 KB
/
FileSource.basic.test.ts
File metadata and controls
454 lines (368 loc) · 13.5 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
/**
* Basic tests for FileSource
*/
import { FileSource } from "../../dataflow/sources/FileSource";
import type { FileSourceConfiguration } from "../../types/file-source";
// Mock Obsidian API
const mockApp = {
vault: {
getAbstractFileByPath: jest.fn(),
cachedRead: jest.fn(),
offref: jest.fn(),
getMarkdownFiles: jest.fn(() => [])
},
metadataCache: {
getFileCache: jest.fn()
},
workspace: {
trigger: jest.fn(),
on: jest.fn(() => ({ unload: jest.fn() }))
}
} as any;
// Mock file object
const mockFile = {
path: 'test.md',
stat: {
ctime: 1000000,
mtime: 2000000
}
};
describe('FileSource', () => {
let fileSource: FileSource;
let config: Partial<FileSourceConfiguration>;
beforeEach(() => {
// Reset all mocks
jest.clearAllMocks();
config = {
enabled: false,
recognitionStrategies: {
metadata: {
enabled: true,
taskFields: ['dueDate', 'status'],
requireAllFields: false
},
tags: {
enabled: true,
taskTags: ['#task', '#todo'],
matchMode: 'exact'
},
templates: {
enabled: false,
templatePaths: [],
checkTemplateMetadata: true
},
paths: {
enabled: false,
taskPaths: [],
matchMode: 'prefix'
}
},
fileTaskProperties: {
contentSource: 'filename',
stripExtension: true,
defaultStatus: ' ',
preferFrontmatterTitle: true
},
performance: {
enableWorkerProcessing: false,
enableCaching: true,
cacheTTL: 300000
},
};
fileSource = new FileSource(mockApp, config);
});
afterEach(() => {
if (fileSource) {
fileSource.destroy();
}
});
describe('initialization', () => {
it('should initialize with provided configuration', () => {
expect(fileSource).toBeInstanceOf(FileSource);
});
it('should not initialize when disabled', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
fileSource.initialize();
expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining('[FileSource] Initializing'));
consoleSpy.mockRestore();
});
it('should initialize when enabled', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
// Enable FileSource
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('[FileSource] Initializing'));
consoleSpy.mockRestore();
});
it('should not initialize twice', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
fileSource.initialize(); // Second call
// Should only log once
const initLogs = consoleSpy.mock.calls.filter((call: any[]) =>
call[0]?.includes('[FileSource] Initializing')
);
expect(initLogs).toHaveLength(1);
consoleSpy.mockRestore();
});
});
describe('file relevance checking', () => {
beforeEach(() => {
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
});
it('should identify markdown files as relevant', async () => {
mockApp.vault.getAbstractFileByPath.mockReturnValue(mockFile);
mockApp.vault.cachedRead.mockResolvedValue('# Test content');
mockApp.metadataCache.getFileCache.mockReturnValue({});
const result = await fileSource.shouldCreateFileTask('test.md');
// Should not throw error and should process the file
expect(mockApp.vault.getAbstractFileByPath).toHaveBeenCalledWith('test.md');
});
it('should reject non-markdown files', async () => {
mockApp.vault.getAbstractFileByPath.mockReturnValue({
...mockFile,
path: 'test.txt'
});
const result = await fileSource.shouldCreateFileTask('test.txt');
expect(result).toBe(false);
expect(mockApp.vault.getAbstractFileByPath).not.toHaveBeenCalled();
});
it('should reject excluded patterns', async () => {
const result = await fileSource.shouldCreateFileTask('.obsidian/workspace.json');
expect(result).toBe(false);
expect(mockApp.vault.getAbstractFileByPath).not.toHaveBeenCalled();
});
it('should reject hidden files', async () => {
const result = await fileSource.shouldCreateFileTask('.hidden-file.md');
expect(result).toBe(false);
expect(mockApp.vault.getAbstractFileByPath).not.toHaveBeenCalled();
});
});
describe('metadata-based recognition', () => {
beforeEach(() => {
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
mockApp.vault.getAbstractFileByPath.mockReturnValue(mockFile);
mockApp.vault.cachedRead.mockResolvedValue('# Test content');
});
it('should recognize file with task metadata', async () => {
const fileCache = {
frontmatter: {
dueDate: '2024-01-01',
status: 'pending'
}
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(true);
});
it('should recognize file with any task field when requireAllFields is false', async () => {
const fileCache = {
frontmatter: {
dueDate: '2024-01-01'
// missing 'status' but requireAllFields is false
}
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(true);
});
it('should not recognize file without task metadata', async () => {
const fileCache = {
frontmatter: {
title: 'Test File',
description: 'Just a regular file'
}
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(false);
});
it('should not recognize file without frontmatter', async () => {
const fileCache = {};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(false);
});
});
describe('tag-based recognition', () => {
beforeEach(() => {
fileSource.updateConfiguration({
enabled: true,
recognitionStrategies: {
metadata: {
enabled: false,
taskFields: config.recognitionStrategies!.metadata.taskFields,
requireAllFields: config.recognitionStrategies!.metadata.requireAllFields
},
tags: {
enabled: true,
taskTags: config.recognitionStrategies!.tags.taskTags,
matchMode: config.recognitionStrategies!.tags.matchMode
},
templates: config.recognitionStrategies!.templates,
paths: config.recognitionStrategies!.paths
}
});
fileSource.initialize();
mockApp.vault.getAbstractFileByPath.mockReturnValue(mockFile);
mockApp.vault.cachedRead.mockResolvedValue('# Test content');
});
it('should recognize file with task tags', async () => {
const fileCache = {
tags: [
{ tag: '#task' },
{ tag: '#important' }
]
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(true);
});
it('should not recognize file without task tags', async () => {
const fileCache = {
tags: [
{ tag: '#note' },
{ tag: '#reference' }
]
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(false);
});
it('should not recognize file without tags', async () => {
const fileCache = {};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const result = await fileSource.shouldCreateFileTask('test.md');
expect(result).toBe(false);
});
});
describe('task creation', () => {
beforeEach(() => {
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
mockApp.vault.getAbstractFileByPath.mockReturnValue(mockFile);
mockApp.vault.cachedRead.mockResolvedValue('# Test content');
});
it('should create file task with correct structure', async () => {
const fileCache = {
frontmatter: {
dueDate: '2024-01-01',
status: 'x',
priority: 2,
project: 'Test Project'
}
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const task = await fileSource.createFileTask('test.md');
expect(task).toBeTruthy();
expect(task!.id).toBe('file-source:test.md');
expect(task!.content).toBe('test'); // filename without extension
expect(task!.filePath).toBe('test.md');
expect(task!.line).toBe(0);
expect(task!.completed).toBe(true); // status is 'x'
expect(task!.status).toBe('x');
expect(task!.metadata.source).toBe('file-source');
expect(task!.metadata.recognitionStrategy).toBe('metadata');
expect(task!.metadata.fileTimestamps.created).toBe(1000000);
expect(task!.metadata.fileTimestamps.modified).toBe(2000000);
expect(task!.metadata.priority).toBe(2);
expect(task!.metadata.project).toBe('Test Project');
});
it('should use filename as project name when frontmatter project is true', async () => {
const fileCache = {
frontmatter: {
dueDate: '2024-01-01',
project: true
}
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const task = await fileSource.createFileTask('Projects/My Awesome Project.md');
expect(task).toBeTruthy();
expect(task!.metadata.project).toBe('My Awesome Project');
});
it('should use default status when not specified', async () => {
const fileCache = {
frontmatter: {
dueDate: '2024-01-01'
}
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const task = await fileSource.createFileTask('test.md');
expect(task!.status).toBe(' '); // default status
expect(task!.completed).toBe(false);
});
it('should handle missing file gracefully', async () => {
mockApp.vault.getAbstractFileByPath.mockReturnValue(null);
const task = await fileSource.createFileTask('nonexistent.md');
expect(task).toBeNull();
});
it('should handle file read errors gracefully', async () => {
mockApp.vault.cachedRead.mockRejectedValue(new Error('File read error'));
const task = await fileSource.createFileTask('test.md');
expect(task).toBeNull();
});
it('should remove project tag when used to derive project metadata', async () => {
const fileCache = {
frontmatter: {
tags: ['context/foo']
},
tags: [
{ tag: '#project/Alpha' },
{ tag: '#task' }
]
};
mockApp.metadataCache.getFileCache.mockReturnValue(fileCache);
const task = await fileSource.createFileTask('test.md');
expect(task).toBeTruthy();
expect(task!.metadata.project).toBe('Alpha');
expect(task!.metadata.tags).toEqual(expect.arrayContaining(['#task', '#context/foo']));
expect(task!.metadata.tags).not.toContain('#project/Alpha');
});
});
describe('statistics', () => {
it('should provide initial statistics', () => {
const stats = fileSource.getStats();
expect(stats.initialized).toBe(false);
expect(stats.trackedFileCount).toBe(0);
expect(stats.recognitionBreakdown.metadata).toBe(0);
expect(stats.recognitionBreakdown.tag).toBe(0);
expect(stats.lastUpdate).toBe(0);
expect(stats.lastUpdateSeq).toBe(0);
});
});
describe('configuration updates', () => {
it('should update configuration', () => {
const newConfig = { enabled: true };
fileSource.updateConfiguration(newConfig);
// Configuration should be updated (we can't directly test it without exposing the config)
// But we can test that it doesn't throw errors
expect(() => fileSource.updateConfiguration(newConfig)).not.toThrow();
});
});
describe('cleanup', () => {
it('should destroy cleanly', () => {
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
expect(() => fileSource.destroy()).not.toThrow();
const stats = fileSource.getStats();
expect(stats.initialized).toBe(false);
expect(stats.trackedFileCount).toBe(0);
});
it('should handle destroy when not initialized', () => {
expect(() => fileSource.destroy()).not.toThrow();
});
});
describe('refresh', () => {
it('should handle refresh when disabled', async () => {
await expect(fileSource.refresh()).resolves.not.toThrow();
});
it('should handle refresh when enabled', async () => {
fileSource.updateConfiguration({ enabled: true });
fileSource.initialize();
await expect(fileSource.refresh()).resolves.not.toThrow();
});
});
});