Tests/OrgAppTests/UserHookTests.swift
194 lines · 9224 bytes
12 symbols in this file
UserHookTestsMessagescycleaStateChangeHookEditsAsItsOwnUndoSteprunsForTheEditorsCommandsaHooksOwnChangesRunNoHooksaFailingHookLeavesTheChangeAndReportsaChangedBufferRefusesTheHooksEditsrunsForAFileThatIsntOpenuntrustedHooksDontRunSilentlyaCaptureHookRewritesTheTextOrCancelsnoHostRunsNoHooks
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// `[[hook]]`s run through the real command host after TODO changes and before captures.
8@MainActor
9@Suite(.serialized)
10struct UserHookTests {
11 static let manifest = """
12 api = 1
13
14 [[hook]]
15 event = "after-todo-state-change"
16 file = "todo.js"
17 function = "logState"
18
19 [[hook]]
20 event = "capture-before-finalize"
21 file = "capture.js"
22 function = "check"
23 """
24 static let todo = """
25 export async function logState(org, { entry, from, to }) {
26 if (entry.title === "Broken") throw new Error("broken");
27 if (entry.title === "Again") {
28 await org.run("org.todo.cycle");
29 await org.message(`again ${from ?? "none"} -> ${to}`);
30 return;
31 }
32 if (entry.title === "Typed") await org.message("typing");
33 const text = await org.text();
34 const line = text.indexOf("\\n", entry.start) + 1;
35 await org.message(`${entry.title}: ${from ?? "none"} -> ${to ?? "none"}`);
36 return { edits: [{ from: line, text: `- State ${to ?? "none"} from ${from ?? "none"}\\n` }] };
37 }
38 """
39 static let capture = """
40 export async function check(org, { text, template }) {
41 if (text.includes("cancel")) return org.fail(`Not filed with ${template}`);
42 if (template === "s") return { selection: 0 };
43 const heading = await org.heading(0);
44 return { edits: [{ from: heading.titleStart, to: heading.titleEnd, text: heading.title.toUpperCase() }], message: "checked" };
45 }
46 """
47 static let file = "* Plan\nbody\n* Broken\n* Again\n* Typed\n"
48
49 let config: Folder
50 let notes: Folder
51 let path: String
52 let session: DocumentSession
53 let buffer: StateBuffer
54 let trust: TrustStore
55 var reported: [String] { messages.list }
56 let messages = Messages()
57 final class Messages { var list: [String] = [] }
58
59 init() throws {
60 config = try Folder()
61 notes = try Folder()
62 try config.write("commands.toml", Self.manifest)
63 try config.write("commands/todo.js", Self.todo)
64 try config.write("commands/capture.js", Self.capture)
65 path = try notes.write("a.org", Self.file).path
66 session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
67 session.saveMode = .explicit
68 session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
69 session.userCommands = UserCommands()
70 #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
71 session.open(path)
72 buffer = StateBuffer(try #require(session.document))
73 session.attach(buffer)
74 trust = TrustStore(file: notes.url.appendingPathComponent("trusted.json"))
75 let messages = messages
76 session.hooks = UserHookHost(trust: trust, ask: { _, reply in reply(.runOnce) }, report: { messages.list.append($0) })
77 }
78
79 /// Changes the TODO keyword of the heading titled `title`, as the agenda does, and waits for
80 /// the hooks.
81 func cycle(_ title: String, in path: String? = nil) async throws {
82 let path = path ?? self.path
83 let text = try #require(session.document(of: path)?.text ?? (try? String(contentsOfFile: path, encoding: .utf8)))
84 let found = (text as NSString).range(of: " \(title)\n")
85 try #require(found.location != NSNotFound)
86 let offset = (text as NSString).lineRange(for: found).location
87 guard case .commit = session.perform(TodoCycle(), path: path, at: offset, expect: nil) else {
88 Issue.record("cycling \(title) didn't commit")
89 return
90 }
91 await session.hooksFinished()
92 }
93
94 @Test func aStateChangeHookEditsAsItsOwnUndoStep() async throws {
95 try await cycle("Plan")
96 #expect(buffer.document.text == "* TODO Plan\n- State TODO from none\nbody\n* Broken\n* Again\n* Typed\n")
97 #expect(reported == ["Plan: none -> TODO"])
98 #expect(buffer.update { $0.undo() } != nil)
99 #expect(buffer.document.text == "* TODO Plan\nbody\n* Broken\n* Again\n* Typed\n")
100 #expect(buffer.update { $0.undo() } != nil)
101 #expect(buffer.document.text == Self.file)
102 }
103
104 /// The editor's route: the command's effect, handed to the session.
105 @Test func runsForTheEditorsCommands() async throws {
106 buffer.selection = [2..<2]
107 guard case .commit(let result) = buffer.perform(SetTodo(keyword: "DONE"), now: Date(), answers: [:]) else {
108 Issue.record("SetTodo didn't commit")
109 return
110 }
111 session.afterTodoStateChange(result.effects, in: path)
112 await session.hooksFinished()
113 #expect(buffer.document.text.hasPrefix("* DONE Plan\n- State DONE from none\n"))
114 }
115
116 /// A hook's own TODO changes, through `org.run`, run no hooks.
117 @Test func aHooksOwnChangesRunNoHooks() async throws {
118 try await cycle("Again")
119 #expect(reported == ["again none -> TODO"])
120 #expect(buffer.document.text.contains("* DONE Again\n"))
121 }
122
123 @Test func aFailingHookLeavesTheChangeAndReports() async throws {
124 try await cycle("Broken")
125 #expect(reported == ["logState in commands/todo.js: broken"])
126 #expect(buffer.document.text == "* Plan\nbody\n* TODO Broken\n* Again\n* Typed\n")
127 }
128
129 /// Typing while a hook runs refuses its edits.
130 @Test func aChangedBufferRefusesTheHooksEdits() async throws {
131 let messages = messages
132 session.hooks?.report = { [buffer] message in
133 messages.list.append(message)
134 if message == "typing" {
135 _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
136 }
137 }
138 try await cycle("Typed")
139 #expect(reported == ["typing", "Typed: none -> TODO", "a.org changed while logState in commands/todo.js ran; its changes weren't made."])
140 #expect(buffer.document.text == "* Plan\nbody\n* Broken\n* Again\n* TODO Typed\ntyped\n")
141 }
142
143 /// A file that isn't open is changed on disk.
144 @Test func runsForAFileThatIsntOpen() async throws {
145 let other = try notes.write("b.org", "* Call\n").path
146 try await cycle("Call", in: other)
147 #expect(try String(contentsOfFile: other, encoding: .utf8) == "* TODO Call\n- State TODO from none\n")
148 }
149
150 @Test func untrustedHooksDontRunSilently() async throws {
151 // Where orgstar can't ask, they are skipped with a message.
152 session.hooks?.ask = nil
153 try await cycle("Plan")
154 #expect(reported == ["logState in commands/todo.js: commands/todo.js isn't trusted on this device yet, and orgstar can't ask here."])
155 #expect(buffer.document.text == "* TODO Plan\nbody\n* Broken\n* Again\n* Typed\n")
156 // Don't Run runs nothing; Always runs it and doesn't ask again.
157 var asked: [UserCommandTrust.Question] = []
158 session.hooks?.ask = { question, reply in
159 asked.append(question)
160 reply(.dontRun)
161 }
162 try await cycle("Plan")
163 #expect(reported.last == "logState in commands/todo.js: Not run")
164 #expect(asked == [UserCommandTrust.Question(file: "commands/todo.js", hook: .afterTodoStateChange)])
165 session.hooks?.ask = { question, reply in
166 asked.append(question)
167 reply(.always)
168 }
169 try await cycle("Plan")
170 try await cycle("Plan")
171 #expect(asked.count == 2)
172 #expect(buffer.document.text.hasPrefix("* TODO Plan\n- State TODO from none\n- State none from DONE\nbody\n"))
173 }
174
175 @Test func aCaptureHookRewritesTheTextOrCancels() async throws {
176 #expect(await session.runCaptureHooks("* buy milk :shop:\n", template: "t", interactive: true) == .success("* BUY MILK :shop:\n"))
177 #expect(reported == ["checked"])
178 #expect(await session.runCaptureHooks("* cancel this\n", template: "t", interactive: true)
179 == .failure(CaptureError(message: "Not filed with t")))
180 #expect(await session.runCaptureHooks("* x\n", template: "s", interactive: true)
181 == .failure(CaptureError(message: "check in commands/capture.js: a hook returns only edits and message")))
182 // Without a way to ask, an untrusted hook is skipped and the capture goes on unchanged.
183 session.hooks?.ask = { _, _ in Issue.record("asked without a way to ask") }
184 #expect(await session.runCaptureHooks("* cancel this\n", template: "t", interactive: false) == .success("* cancel this\n"))
185 #expect(reported.last == "check in commands/capture.js: commands/capture.js isn't trusted on this device yet, and orgstar can't ask here.")
186 }
187
188 @Test func noHostRunsNoHooks() async throws {
189 session.hooks = nil
190 try await cycle("Plan")
191 #expect(buffer.document.text == "* TODO Plan\nbody\n* Broken\n* Again\n* Typed\n")
192 #expect(await session.runCaptureHooks("* cancel\n", template: "t", interactive: true) == .success("* cancel\n"))
193 }
194}