Tests/OrgCoreTests/UserCommandTests.swift
277 lines · 13955 bytes
23 symbols in this file
UserCommandManifestTestsparsereadsCommandsreportsProblemsByCommandAndKeyneedsAKnownAPIwhenHidesTheCommandWhereItDoesntApplycontextregistryUserCommandAPITestscontextoffsetheadingAtThePointoutlineSelectionTextFileAndSettingsresultreadsTheResultrefusesEditsThatCantApplyproblempromptsUserCommandStateTestscontextcomposesIntoOneResultrefusesWhatIsntBuiltInrefusal
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct UserCommandManifestTests {
6 func parse(_ toml: String, files: Set<String> = ["review.js", "lib/dates.mjs"]) throws -> ([UserCommand], [String]) {
7 var problems: [String] = []
8 let commands = try UserCommands.parse(toml, problems: &problems) { files.contains($0) }
9 return (commands, problems)
10 }
11
12 @Test func readsCommands() throws {
13 let (commands, problems) = try parse("""
14 api = 1
15
16 [[command]]
17 name = "weekly-review"
18 title = "Start Weekly Review"
19 file = "review.js"
20 function = "weeklyReview"
21 when = "heading"
22 timeout = 5
23
24 [[command]]
25 name = "dates"
26 file = "lib/dates.mjs"
27 function = "$fix_dates"
28 """)
29 #expect(problems == [])
30 #expect(commands == [
31 UserCommand(name: "weekly-review", title: "Start Weekly Review", file: "review.js", function: "weeklyReview", when: "heading", timeout: 5),
32 UserCommand(name: "dates", title: "dates", file: "lib/dates.mjs", function: "$fix_dates", timeout: 2),
33 ])
34 #expect(commands[0].id == "user.weekly-review")
35 }
36
37 @Test func reportsProblemsByCommandAndKey() throws {
38 let (commands, problems) = try parse("""
39 api = 1
40 extra = true
41
42 [[command]]
43 name = "ok"
44 file = "review.js"
45 function = "ok"
46 colour = "red"
47
48 [[command]]
49 name = "missing"
50 file = "gone.js"
51 function = "f"
52
53 [[command]]
54 name = "outside"
55 file = "../secret.js"
56 function = "f"
57
58 [[command]]
59 name = "bad function"
60 file = "review.js"
61 function = "f"
62
63 [[command]]
64 name = "fn"
65 file = "review.js"
66 function = "1f"
67
68 [[command]]
69 name = "ctx"
70 file = "review.js"
71 function = "f"
72 when = "everywhere"
73
74 [[command]]
75 name = "slow"
76 file = "review.js"
77 function = "f"
78 timeout = 60
79
80 [[command]]
81 name = "ok"
82 file = "review.js"
83 function = "again"
84
85 [other]
86 """)
87 #expect(commands.map(\.name) == ["ok"])
88 #expect(problems == [
89 "unknown key extra",
90 "command ok: unknown key colour",
91 "command missing: no file commands/gone.js",
92 "command outside: file must be a .js or .mjs file in commands/",
93 "line 20: command needs a name of letters, digits, - and _",
94 "command fn: function must be the name of an exported function",
95 "command ctx: unknown context everywhere",
96 "command slow: timeout must be 1 to 30 seconds",
97 "command ok: defined twice",
98 "line 47: unknown table [other]",
99 ])
100 }
101
102 @Test func needsAKnownAPI() throws {
103 let command = "\n[[command]]\nname = \"a\"\nfile = \"review.js\"\nfunction = \"a\"\n"
104 #expect(try parse(command) == ([], ["missing api = 1"]))
105 #expect(try parse("api = 2\n" + command) == ([], ["api 2 needs a newer orgstar"]))
106 #expect(try parse("api = 0\n" + command) == ([], ["unknown api 0"]))
107 #expect(try parse("") == ([], []))
108 #expect(throws: TOML.ParseError.self) { _ = try parse("api = \n[[command") }
109 }
110
111 @Test func whenHidesTheCommandWhereItDoesntApply() {
112 let text = "intro\n* Heading\nbody\n"
113 let command = UserCommand(name: "h", title: "H", file: "a.js", function: "h", when: "heading")
114 func context(_ caret: Int) -> EditContext { EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]) }
115 #expect(!command.applies(in: context(0)))
116 #expect(command.applies(in: context(8)))
117 #expect(UserCommand(name: "e", title: "E", file: "a.js", function: "e").applies(in: context(0)))
118 #expect(command.run(in: context(8)) == .external(.userCommand(UserCommandRequest(command: command, revision: 3, selection: [8..<8]))))
119 }
120
121 @Test func registry() {
122 let store = UserCommands()
123 let command = UserCommand(name: "a", title: "A", file: "a.js", function: "a")
124 store.replace([command], folder: URL(fileURLWithPath: "/c/commands"))
125 #expect(store.command("user.a") == command)
126 #expect(store.command("user.b") == nil)
127 #expect(store.command("a") == nil)
128 #expect(store.folder?.path == "/c/commands")
129 }
130}
131
132struct UserCommandAPITests {
133 static let text = """
134 #+FILETAGS: :home:
135 intro
136 * TODO [#A] Plan the week :work:
137 SCHEDULED: <2026-11-30 Mon> DEADLINE: <2026-12-04 Fri>
138 :PROPERTIES:
139 :EFFORT: 1:00
140 :END:
141 ** Sub é
142 * Done
143 """
144
145 func context(_ caret: Int, selection: [Range<Int>]? = nil) -> EditContext {
146 EditContext(revision: 7, text: Self.text, tree: OrgParser.parse(Self.text), selection: selection ?? [caret..<caret], knownTags: { ["work", "home"] })
147 }
148
149 func offset(_ needle: String) -> Int { (Self.text as NSString).range(of: needle).location }
150
151 @Test func headingAtThePoint() throws {
152 let context = context(offset("EFFORT"))
153 let heading = try #require(UserCommandAPI.answer("heading", NSNull(), context: context, file: nil) as? [String: Any])
154 #expect(heading["level"] as? Int == 1)
155 #expect(heading["keyword"] as? String == "TODO")
156 #expect(heading["done"] as? Bool == false)
157 #expect(heading["priority"] as? String == "A")
158 #expect(heading["title"] as? String == "Plan the week")
159 #expect(heading["tags"] as? [String] == ["work"])
160 #expect(heading["start"] as? Int == offset("* TODO"))
161 #expect(heading["end"] as? Int == offset("* Done"))
162 let titleStart = try #require(heading["titleStart"] as? Int), titleEnd = try #require(heading["titleEnd"] as? Int)
163 #expect((Self.text as NSString).substring(with: NSRange(titleStart..<titleEnd)) == "Plan the week")
164 #expect(heading["scheduled"] as? String == "<2026-11-30 Mon>")
165 #expect(heading["deadline"] as? String == "<2026-12-04 Fri>")
166 #expect(heading["closed"] is NSNull)
167 #expect(heading["properties"] as? [String: String] == ["EFFORT": "1:00"])
168 // Before the first heading, none; with an offset, the heading there.
169 #expect(UserCommandAPI.answer("heading", NSNull(), context: self.context(0), file: nil) is NSNull)
170 let sub = try #require(UserCommandAPI.answer("heading", offset("Sub") as NSNumber, context: context, file: nil) as? [String: Any])
171 #expect(sub["title"] as? String == "Sub é")
172 #expect(sub["level"] as? Int == 2)
173 #expect(sub["keyword"] is NSNull)
174 }
175
176 @Test func outlineSelectionTextFileAndSettings() throws {
177 let context = context(0, selection: [3..<5, 9..<9])
178 let outline = try #require(UserCommandAPI.answer("outline", NSNull(), context: context, file: nil) as? [[String: Any]])
179 #expect(outline.map { $0["title"] as? String } == ["Plan the week", "Sub é", "Done"])
180 #expect(outline.last?["end"] as? Int == (Self.text as NSString).length)
181 #expect(UserCommandAPI.answer("text", NSNull(), context: context, file: nil) as? String == Self.text)
182 #expect(UserCommandAPI.answer("selection", NSNull(), context: context, file: nil) as? [[String: Int]] == [["from": 3, "to": 5], ["from": 9, "to": 9]])
183 #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: "notes/a.org") as? String == "notes/a.org")
184 #expect(UserCommandAPI.answer("file", NSNull(), context: context, file: nil) is NSNull)
185 let settings = try #require(UserCommandAPI.answer("settings", NSNull(), context: context, file: nil) as? [String: Any])
186 #expect(settings["todoKeywords"] as? [String] == ["TODO"])
187 #expect(settings["doneKeywords"] as? [String] == ["DONE"])
188 #expect(settings["fileTags"] as? [String] == ["home"])
189 #expect(settings["tags"] as? [String] == ["work", "home"])
190 #expect(settings["fillColumn"] as? Int == 70)
191 #expect(UserCommandAPI.answer("nope", NSNull(), context: context, file: nil) == nil)
192 }
193
194 func result(_ json: String) -> Result<EditResult, UserCommandAPI.Problem> {
195 UserCommandAPI.result(json, in: EditContext(revision: 4, text: "ab😀cd", tree: OrgParser.parse("ab😀cd"), selection: [0..<0]))
196 }
197
198 @Test func readsTheResult() {
199 #expect(result("null") == .success(EditResult(baseRevision: 4, edits: [])))
200 #expect(result(#"{"edits": [{"from": 5, "to": 6, "text": "D"}, {"from": 0, "to": 1}, {"from": 2, "text": "+"}], "selection": {"from": 1, "to": 2}, "message": "done", "copy": "x"}"#)
201 == .success(EditResult(baseRevision: 4, edits: [
202 TextEdit(range: 0..<1, replacement: ""), TextEdit(range: 2..<2, replacement: "+"), TextEdit(range: 5..<6, replacement: "D"),
203 ], selection: [1..<2], effects: [.message("done"), .copy("x")])))
204 #expect(result(#"{"selection": [3, {"from": 5, "to": 1}]}"#) == .success(EditResult(baseRevision: 4, edits: [], selection: [3..<3, 1..<5])))
205 }
206
207 @Test func refusesEditsThatCantApply() {
208 func problem(_ json: String) -> String? {
209 if case .failure(let problem) = result(json) { return problem.message }
210 return nil
211 }
212 #expect(problem(#"{"edits": [{"from": 0, "to": 2}, {"from": 1, "to": 4}]}"#) == "edits overlap")
213 #expect(problem(#"{"edits": [{"from": 1, "text": "a"}, {"from": 1, "text": "b"}]}"#) == "edits overlap")
214 #expect(problem(#"{"edits": [{"from": 5, "to": 9}]}"#) == "edit 1 is outside the text")
215 #expect(problem(#"{"edits": [{"from": 2, "to": 1}]}"#) == "edit 1 is outside the text")
216 #expect(problem(#"{"edits": [{"from": -1}]}"#) == "edit 1 is outside the text")
217 #expect(problem(#"{"edits": [{"from": 3}]}"#) == "edit 1 splits a character")
218 #expect(problem(#"{"edits": [{"from": 0.5}]}"#) == "edit 1 needs a from offset")
219 #expect(problem(#"{"edits": [{"from": 0, "text": 3}]}"#) == "edit 1 has a text that isn't a string")
220 #expect(problem(#"{"edits": {"from": 0}}"#) == "edits must be a list")
221 #expect(problem(#"{"edit": []}"#) == "returned an unknown key edit")
222 #expect(problem(#"{"selection": 7}"#) == "selection is outside the text")
223 #expect(problem(#"{"edits": [{"from": 0, "to": 6}], "selection": 2}"#) == "selection is outside the text")
224 #expect(problem(#"{"message": 3}"#) == "message must be a string")
225 #expect(problem(#""text""#) == "returned something other than an object")
226 }
227
228 @Test func prompts() {
229 let prompt = UserCommandAPI.prompt(["message": "Week: ", "initial": "W48", "choices": ["W48", "W49"], "requireMatch": true] as [String: Any])
230 #expect(prompt == Prompt(key: "user", message: "Week: ", initial: "W48", choices: ["W48", "W49"], requireMatch: true))
231 #expect(UserCommandAPI.prompt(["message": "Any: ", "requireMatch": true] as [String: Any]).requireMatch == false)
232 let date = UserCommandAPI.prompt(["message": "When? ", "date": true] as [String: Any])
233 #expect(date.date == Prompt.DateRead(defaultDate: nil))
234 var utc = Calendar(identifier: .gregorian)
235 utc.timeZone = TimeZone(identifier: "UTC")!
236 let now = Date(timeIntervalSince1970: 1_795_000_000) // 2026-11-18
237 #expect(UserCommandAPI.answer("+2d", to: date, now: now, calendar: utc) == "2026-11-20")
238 #expect(UserCommandAPI.answer("2026-12-01 9:30", to: date, now: now, calendar: utc) == "2026-12-01 09:30")
239 #expect(UserCommandAPI.answer("+2d", to: prompt, now: now, calendar: utc) == "+2d")
240 }
241}
242
243struct UserCommandStateTests {
244 func context(_ text: String, caret: Int) -> EditContext {
245 EditContext(revision: 3, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
246 }
247
248 /// Commands run one after another on the text the last one left; the command's own edits
249 /// are in that text, and the result is one change from the text it started with.
250 @Test func composesIntoOneResult() throws {
251 var state = UserCommandState(context("* a\n* b\n", caret: 2), defaults: .default)
252 guard case .commit = state.run(TodoCycle(), answers: [:]) else { Issue.record("no commit"); return }
253 #expect(state.context.text == "* TODO a\n* b\n")
254 #expect(state.context.selection == [7..<7])
255 #expect(state.reply["text"] as? String == "* TODO a\n* b\n")
256 guard case .commit = state.run(NextHeading(), answers: [:]) else { Issue.record("no commit"); return }
257 let result = try state.result(#"{"edits": [{"from": 11, "text": "!"}]}"#).get()
258 #expect(result.baseRevision == 3)
259 #expect(result.edits.count == 1)
260 var text = state.start.text
261 for edit in result.edits.reversed() { text = edit.apply(to: text) }
262 #expect(text == "* TODO a\n* !b\n")
263 #expect(result.selection == [9..<9])
264 }
265
266 @Test func refusesWhatIsntBuiltIn() {
267 func refusal(_ id: String) -> String? {
268 if case .failure(let problem) = UserCommandAPI.builtIn(id) { return problem.message }
269 return nil
270 }
271 #expect(refusal("org.todo.cycle") == nil)
272 #expect(refusal("app.export.html") == "app.export.html is a command of the app, which user commands can't run")
273 #expect(refusal("user.other") == "A user command can't run another: user.other")
274 #expect(refusal("org.cycle") == "No built-in command org.cycle")
275 #expect(UserCommandAPI.safeAppCommands == ["app.save"])
276 }
277}