-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathTemplateChoiceEngine.notice.test.ts
More file actions
332 lines (285 loc) · 8.69 KB
/
TemplateChoiceEngine.notice.test.ts
File metadata and controls
332 lines (285 loc) · 8.69 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
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../quickAddSettingsTab", () => {
const defaultSettings = {
choices: [],
inputPrompt: "single-line",
devMode: false,
templateFolderPath: "",
announceUpdates: "major",
version: "0.0.0",
globalVariables: {},
onePageInputEnabled: false,
disableOnlineFeatures: true,
enableRibbonIcon: false,
showCaptureNotification: true,
showInputCancellationNotification: true,
enableTemplatePropertyTypes: false,
ai: {
defaultModel: "Ask me",
defaultSystemPrompt: "",
promptTemplatesFolderPath: "",
showAssistant: true,
providers: [],
},
migrations: {
migrateToMacroIDFromEmbeddedMacro: true,
useQuickAddTemplateFolder: false,
incrementFileNameSettingMoveToDefaultBehavior: false,
mutualExclusionInsertAfterAndWriteToBottomOfFile: false,
setVersionAfterUpdateModalRelease: false,
addDefaultAIProviders: false,
removeMacroIndirection: false,
migrateFileOpeningSettings: false,
},
};
return {
DEFAULT_SETTINGS: defaultSettings,
QuickAddSettingsTab: class {},
};
});
const { formatFileNameMock, formatFileContentMock } = vi.hoisted(() => {
const formatName = vi.fn<(format: string, prompt: string) => Promise<string>>();
const formatContent = vi
.fn<(...args: unknown[]) => Promise<string>>()
.mockResolvedValue("");
return {
formatFileNameMock: formatName,
formatFileContentMock: formatContent,
};
});
vi.mock("../formatters/completeFormatter", () => {
class CompleteFormatterMock {
constructor() {}
setLinkToCurrentFileBehavior() {}
setTitle() {}
async formatFileName(format: string, prompt: string) {
return formatFileNameMock(format, prompt);
}
async formatFileContent(...args: unknown[]) {
return await formatFileContentMock(...args);
}
getAndClearTemplatePropertyVars() {
return new Map<string, unknown>();
}
}
return {
CompleteFormatter: CompleteFormatterMock,
formatFileNameMock,
formatFileContentMock,
};
});
vi.mock("../utilityObsidian", () => ({
getTemplater: vi.fn(() => ({})),
overwriteTemplaterOnce: vi.fn(),
getAllFolderPathsInVault: vi.fn(async () => []),
insertFileLinkToActiveView: vi.fn(),
openExistingFileTab: vi.fn(() => null),
openFile: vi.fn(),
}));
vi.mock("../gui/GenericSuggester/genericSuggester", () => ({
default: {
Suggest: vi.fn(),
},
}));
vi.mock("../main", () => ({
default: class QuickAddMock {},
}));
vi.mock("obsidian-dataview", () => ({
getAPI: vi.fn(),
}));
import { TFile, type App } from "obsidian";
import { Notice } from "obsidian";
import { TemplateChoiceEngine } from "./TemplateChoiceEngine";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import type ITemplateChoice from "../types/choices/ITemplateChoice";
import { MacroAbortError } from "../errors/MacroAbortError";
import { settingsStore } from "../settingsStore";
import { fileExistsAppendToBottom, fileExistsOverwriteFile } from "../constants";
const defaultSettingsState = structuredClone(settingsStore.getState());
type NoticeTestClass = typeof Notice & {
instances: Array<{ message: string; timeout?: number }>;
};
const noticeClass = Notice as unknown as NoticeTestClass;
const createTemplateChoice = (): ITemplateChoice => ({
name: "Test Template Choice",
id: "choice-id",
type: "Template",
command: false,
templatePath: "Templates/Test.md",
folder: {
enabled: false,
folders: [],
chooseWhenCreatingNote: false,
createInSameFolderAsActiveFile: false,
chooseFromSubfolders: false,
},
fileNameFormat: { enabled: false, format: "{{VALUE}}" },
appendLink: false,
openFile: false,
fileOpening: {
location: "tab",
direction: "vertical",
mode: "source",
focus: false,
},
fileExistsMode: fileExistsAppendToBottom,
setFileExistsBehavior: false,
});
const createEngine = (
abortMessage: string,
options: { throwDuringFileName?: boolean; stubTemplateContent?: boolean } = {},
) => {
const app = {
workspace: {
getActiveFile: vi.fn(() => null),
},
fileManager: {
getNewFileParent: vi.fn(() => ({ path: "" })),
},
vault: {
getRoot: vi.fn(() => ({ path: "" })),
adapter: {
exists: vi.fn(async () => false),
},
getAbstractFileByPath: vi.fn(),
getFiles: vi.fn(() => []),
create: vi.fn(),
modify: vi.fn(),
},
} as unknown as App;
const plugin = { settings: settingsStore.getState() } as any;
const choiceExecutor: IChoiceExecutor = {
execute: vi.fn(),
variables: new Map<string, unknown>(),
signalAbort: vi.fn(),
consumeAbortSignal: vi.fn(),
};
const engine = new TemplateChoiceEngine(
app,
plugin,
createTemplateChoice(),
choiceExecutor,
);
if (options.stubTemplateContent) {
(
engine as unknown as {
getTemplateContent: () => Promise<string>;
}
).getTemplateContent = vi.fn().mockResolvedValue("stub template");
}
if (options.throwDuringFileName !== false) {
formatFileNameMock.mockImplementation(async () => {
throw new MacroAbortError(abortMessage);
});
} else {
formatFileNameMock.mockResolvedValue("Test Template");
}
return { engine, choiceExecutor, app };
};
describe("TemplateChoiceEngine cancellation notices", () => {
beforeEach(() => {
settingsStore.setState(structuredClone(defaultSettingsState));
noticeClass.instances.length = 0;
formatFileNameMock.mockReset();
formatFileContentMock.mockReset();
formatFileContentMock.mockResolvedValue("");
});
it("shows a cancellation notice when the setting is enabled", async () => {
settingsStore.setState({
...settingsStore.getState(),
showInputCancellationNotification: true,
});
const { engine } = createEngine("Input cancelled by user");
await engine.run();
expect(noticeClass.instances).toHaveLength(1);
expect(noticeClass.instances[0]?.message).toContain(
"Template execution aborted: Input cancelled by user",
);
});
it("suppresses cancellation notices when the setting is disabled", async () => {
settingsStore.setState({
...settingsStore.getState(),
showInputCancellationNotification: false,
});
const { engine } = createEngine("Input cancelled by user");
await engine.run();
expect(noticeClass.instances).toHaveLength(0);
});
it("still shows notices for other abort reasons", async () => {
settingsStore.setState({
...settingsStore.getState(),
showInputCancellationNotification: false,
});
const { engine } = createEngine("Missing template");
await engine.run();
expect(noticeClass.instances).toHaveLength(1);
expect(noticeClass.instances[0]?.message).toContain(
"Template execution aborted: Missing template",
);
});
it("signals abort back to the choice executor", async () => {
const { engine, choiceExecutor } = createEngine("Input cancelled by user");
await engine.run();
expect(choiceExecutor.signalAbort).toHaveBeenCalledTimes(1);
const [[error]] = (choiceExecutor.signalAbort as ReturnType<typeof vi.fn>).mock.calls;
expect(error).toBeInstanceOf(MacroAbortError);
});
it("signals abort when template content formatting is cancelled", async () => {
const { engine, choiceExecutor } = createEngine("ignored", {
throwDuringFileName: false,
stubTemplateContent: true,
});
formatFileContentMock.mockRejectedValueOnce(
new MacroAbortError("Input cancelled by user"),
);
await engine.run();
expect(choiceExecutor.signalAbort).toHaveBeenCalledTimes(1);
});
});
describe("TemplateChoiceEngine file casing resolution", () => {
beforeEach(() => {
settingsStore.setState(structuredClone(defaultSettingsState));
formatFileNameMock.mockReset();
formatFileContentMock.mockReset();
formatFileContentMock.mockResolvedValue("");
});
it("overwrites existing files when the path casing differs", async () => {
const { engine, app } = createEngine("ignored", {
throwDuringFileName: false,
stubTemplateContent: true,
});
const existingFile = new TFile();
existingFile.path = "Bug report.md";
existingFile.name = "Bug report.md";
existingFile.extension = "md";
existingFile.basename = "Bug report";
engine.choice.fileExistsMode = fileExistsOverwriteFile;
engine.choice.setFileExistsBehavior = true;
formatFileNameMock.mockResolvedValueOnce("Bug Report");
(app.vault.adapter.exists as ReturnType<typeof vi.fn>).mockResolvedValue(
true,
);
(app.vault.getAbstractFileByPath as ReturnType<typeof vi.fn>).mockReturnValue(
null,
);
(app.vault.getFiles as ReturnType<typeof vi.fn>).mockReturnValue([
existingFile,
]);
const overwriteSpy = vi
.spyOn(
engine as unknown as {
overwriteFileWithTemplate: (
file: TFile,
templatePath: string,
) => Promise<TFile | null>;
},
"overwriteFileWithTemplate",
)
.mockResolvedValue(existingFile);
await engine.run();
expect(overwriteSpy).toHaveBeenCalledWith(
existingFile,
engine.choice.templatePath,
);
});
});