Tests/OrgstarCLITests/ToolTests.swift
335 lines · 15545 bytes
1import Foundation
2import Testing
3@testable import OrgstarCLI
4
5/// A configuration folder, a data folder and a folder of notes in a temporary folder, and the
6/// tool run over them at a fixed time.
7@MainActor
8final class Sandbox {
9 let folder: URL
10 let config: URL
11 let data: URL
12 let notes: URL
13 var now: Date
14 var calendar: Calendar
15 var opened: [[String]] = []
16
17 init() throws {
18 folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-cli-\(UUID().uuidString)").resolvingSymlinksInPath()
19 config = folder.appendingPathComponent("config")
20 data = folder.appendingPathComponent("data")
21 notes = folder.appendingPathComponent("notes")
22 for url in [config, data, notes] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
23 calendar = Calendar(identifier: .gregorian)
24 calendar.timeZone = TimeZone(identifier: "UTC")!
25 // Thursday 26 November 2026, 10:00.
26 now = calendar.date(from: DateComponents(year: 2026, month: 11, day: 26, hour: 10))!
27 }
28
29 deinit { try? FileManager.default.removeItem(at: folder) }
30
31 func write(_ text: String, _ name: String, in folder: URL? = nil) throws {
32 let url = (folder ?? notes).appendingPathComponent(name)
33 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
34 try text.write(to: url, atomically: true, encoding: .utf8)
35 }
36
37 func read(_ name: String) throws -> String {
38 try String(contentsOf: notes.appendingPathComponent(name), encoding: .utf8)
39 }
40
41 func run(_ arguments: String..., input: String? = nil, environment: [String: String] = [:]) -> (status: Int32, out: String, err: String) {
42 var out = Data()
43 var err = ""
44 var host = Host(
45 environment: ["ORGSTAR_CONFIG_DIR": config.path, "ORGSTAR_DATA_DIR": data.path, "ORGSTAR_ROOT": notes.path, "PATH": folder.path]
46 .merging(environment) { $1 },
47 now: now, calendar: calendar, currentDirectory: notes.path,
48 input: { input }, output: { out.append($0) }, error: { err += $0 }, open: { _ in 0 },
49 executable: folder.appendingPathComponent("orgstar")
50 )
51 host.open = { [weak self] arguments in
52 self?.opened.append(arguments)
53 return 0
54 }
55 let status = Tool.run(arguments, host: host)
56 return (status, String(decoding: out, as: UTF8.self), err)
57 }
58}
59
60@MainActor
61struct AgendaTests {
62 static let tasks = """
63 #+TITLE: Tasks
64 * TODO Write report
65 SCHEDULED: <2026-11-26 Thu>
66 * TODO Pay rent :home:
67 DEADLINE: <2026-11-27 Fri>
68 * TODO Call Sam
69 * DONE Old thing
70 """
71
72 @Test func printsTheDayAsEmacsDoes() throws {
73 let sandbox = try Sandbox()
74 try sandbox.write("org-agenda-span = 1\n", "config.toml", in: sandbox.config)
75 try sandbox.write(Self.tasks, "tasks.org")
76 let (status, out, err) = sandbox.run("agenda")
77 #expect(status == 0, "\(err)")
78 let lines = out.split(separator: "\n").map(String.init)
79 #expect(lines.first == "Day-agenda (W48):")
80 #expect(lines.contains("Thursday 26 November 2026"))
81 #expect(lines.contains { $0.hasPrefix(" tasks:") && $0.hasSuffix("Scheduled: TODO Write report") })
82 #expect(lines.contains { $0.contains("In 1 d.: TODO Pay rent") && $0.hasSuffix(":home:") })
83 #expect(!out.contains("Call Sam"))
84 }
85
86 @Test func listsAViewAsJSONWithLines() throws {
87 let sandbox = try Sandbox()
88 try sandbox.write(Self.tasks, "tasks.org")
89 let (status, out, _) = sandbox.run("agenda", "todo list", "--json")
90 #expect(status == 0)
91 let json = try #require(try JSONSerialization.jsonObject(with: Data(out.utf8)) as? [String: Any])
92 #expect(json["view"] as? String == "TODO List")
93 let block = try #require((json["blocks"] as? [[String: Any]])?.first)
94 #expect(block["type"] as? String == "todo")
95 let entries = try #require(block["entries"] as? [[String: Any]])
96 #expect(entries.map { $0["title"] as? String } == ["TODO Write report", "TODO Pay rent", "TODO Call Sam"])
97 #expect(entries.map { $0["line"] as? Int } == [2, 4, 6])
98 #expect(entries[1]["tags"] as? [String] == ["home"])
99 #expect(entries[0]["file"] as? String == sandbox.notes.appendingPathComponent("tasks.org").path)
100 }
101
102 @Test func runsAViewOfViewsToml() throws {
103 let sandbox = try Sandbox()
104 try sandbox.write(Self.tasks, "tasks.org")
105 try sandbox.write("[[view]]\nname = \"Home\"\ntype = \"match\"\nmatch = \"home\"\n", "views.toml", in: sandbox.config)
106 let (status, out, _) = sandbox.run("agenda", "Home")
107 #expect(status == 0)
108 #expect(out.hasPrefix("Headlines with TAGS match: home\n"))
109 #expect(out.contains("TODO Pay rent"))
110 #expect(!out.contains("Write report"))
111 let missing = sandbox.run("agenda", "Nope")
112 #expect(missing.status == 3)
113 #expect(missing.err.contains("No agenda view named Nope"))
114 }
115}
116
117@MainActor
118struct CaptureTests {
119 static let templates = """
120 [[template]]
121 key = "t"
122 name = "Todo"
123 file = "inbox.org"
124 headline = "Inbox"
125 template = "* TODO %?%i"
126
127 [[template]]
128 key = "m"
129 name = "Meeting"
130 file = "inbox.org"
131 headline = "Meetings"
132 template = "* %^{Who} %^{Where|office}\\n%i"
133 """
134
135 @Test func filesTheTextUnderTheHeadline() throws {
136 let sandbox = try Sandbox()
137 try sandbox.write(Self.templates, "capture.toml", in: sandbox.config)
138 try sandbox.write("* Inbox\n* Meetings\n", "inbox.org")
139 let (status, out, err) = sandbox.run("capture", "t", "Buy milk")
140 #expect(status == 0, "\(err)")
141 #expect(out == "Captured to \(sandbox.notes.appendingPathComponent("inbox.org").path):2\n")
142 #expect(try sandbox.read("inbox.org") == "* Inbox\n** TODO Buy milk\n* Meetings\n")
143 let piped = sandbox.run("capture", "t", input: "Call the bank\n")
144 #expect(piped.status == 0)
145 #expect(try sandbox.read("inbox.org") == "* Inbox\n** TODO Buy milk\n** TODO Call the bank\n* Meetings\n")
146 }
147
148 @Test func refusesQuestionsWithoutAnswers() throws {
149 let sandbox = try Sandbox()
150 try sandbox.write(Self.templates, "capture.toml", in: sandbox.config)
151 try sandbox.write("* Inbox\n* Meetings\n", "inbox.org")
152 let refused = sandbox.run("capture", "m", "Notes")
153 #expect(refused.status == 4)
154 #expect(refused.err.contains("asks \"Who\""))
155 #expect(try sandbox.read("inbox.org") == "* Inbox\n* Meetings\n")
156 let answered = sandbox.run("capture", "m", "Notes", "--set", "Who=Sam")
157 #expect(answered.status == 0, "\(answered.err)")
158 #expect(try sandbox.read("inbox.org") == "* Inbox\n* Meetings\n** Sam office\nNotes\n")
159 }
160
161 @Test func createsAMissingFileAndNamesUnknownTemplates() throws {
162 let sandbox = try Sandbox()
163 try sandbox.write("[[template]]\nkey = \"j\"\nname = \"Journal\"\nfile = \"journal/log.org\"\ntemplate = \"* %i\"\n", "capture.toml", in: sandbox.config)
164 #expect(sandbox.run("capture", "j", "First").status == 0)
165 #expect(try sandbox.read("journal/log.org") == "* First\n")
166 let unknown = sandbox.run("capture", "x", "text")
167 #expect(unknown.status == 3)
168 #expect(unknown.err.contains("j (Journal)"))
169 }
170
171 /// Capture hooks run only in the app: the tool files without them and says so.
172 @Test func filesWithoutCaptureHooks() throws {
173 let sandbox = try Sandbox()
174 try sandbox.write(Self.templates, "capture.toml", in: sandbox.config)
175 try sandbox.write("api = 1\n[[hook]]\nevent = \"capture-before-finalize\"\nfile = \"check.js\"\nfunction = \"check\"\n", "commands.toml", in: sandbox.config)
176 try sandbox.write("* Inbox\n* Meetings\n", "inbox.org")
177 let (status, _, err) = sandbox.run("capture", "t", "Buy milk")
178 #expect(status == 0)
179 #expect(err == "orgstar: capture-before-finalize hooks in commands.toml run only in the app; captured without them\n")
180 #expect(try sandbox.read("inbox.org") == "* Inbox\n** TODO Buy milk\n* Meetings\n")
181 }
182}
183
184@MainActor
185struct ClockTests {
186 @Test func clocksInAndOutAndSwitches() throws {
187 let sandbox = try Sandbox()
188 try sandbox.write("* Report\n* Email\n", "work.org")
189 #expect(sandbox.run("clock", "status").status == 3)
190 let clockIn = sandbox.run("clock", "in", "work.org::Report")
191 #expect(clockIn.status == 0, "\(clockIn.err)")
192 #expect(clockIn.out == "Clock starts at [2026-11-26 Thu 10:00] in \"Report\"\n")
193 #expect(try sandbox.read("work.org") == "* Report\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 10:00]\n:END:\n* Email\n")
194
195 sandbox.now += 25 * 60
196 let status = sandbox.run("clock", "status", "--json")
197 let json = try #require(try JSONSerialization.jsonObject(with: Data(status.out.utf8)) as? [String: Any])
198 let running = try #require(json["running"] as? [String: Any])
199 #expect(running["heading"] as? String == "Report")
200 #expect(running["minutes"] as? Int == 25)
201
202 sandbox.now += 5 * 60
203 let switched = sandbox.run("clock", "in", "work.org::*Email")
204 #expect(switched.status == 0, "\(switched.err)")
205 #expect(switched.out == "Clock stopped after 0:30 in \"Report\"\nClock starts at [2026-11-26 Thu 10:30] in \"Email\"\n")
206
207 sandbox.now += 60 * 60
208 let out = sandbox.run("clock", "out")
209 #expect(out.out == "Clock stopped after 1:00 in \"Email\"\n")
210 #expect(try sandbox.read("work.org") == """
211 * Report
212 :LOGBOOK:
213 CLOCK: [2026-11-26 Thu 10:00]--[2026-11-26 Thu 10:30] => 0:30
214 :END:
215 * Email
216 :LOGBOOK:
217 CLOCK: [2026-11-26 Thu 10:30]--[2026-11-26 Thu 11:30] => 1:00
218 :END:
219
220 """)
221 let none = sandbox.run("clock", "out")
222 #expect(none.status == 3)
223 #expect(none.err == "orgstar: No active clock\n")
224 }
225
226 @Test func clocksInByID() throws {
227 let sandbox = try Sandbox()
228 try sandbox.write("* Report\n:PROPERTIES:\n:ID: abc-123\n:END:\n", "work.org")
229 #expect(sandbox.run("clock", "in", "id:abc-123").status == 0)
230 #expect(try sandbox.read("work.org").contains(":END:\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 10:00]\n:END:\n"))
231 #expect(sandbox.run("clock", "in", "work.org::Nothing").status == 3)
232 }
233
234 @Test func keepsAVersionInRecovery() throws {
235 let sandbox = try Sandbox()
236 try sandbox.write("* Report\n", "work.org")
237 #expect(sandbox.run("clock", "in", "work.org::Report").status == 0)
238 let recovery = sandbox.data.appendingPathComponent("Recovery")
239 let kept = try FileManager.default.subpathsOfDirectory(atPath: recovery.path).filter { $0.hasSuffix("work.org") }
240 #expect(kept.count == 1)
241 }
242}
243
244@MainActor
245struct ExportTests {
246 static let text = "#+TITLE: Notes\n* One\nSome *bold* text.\n"
247
248 @Test func exportsBesideTheFile() throws {
249 let sandbox = try Sandbox()
250 try sandbox.write(Self.text, "notes.org")
251 for (format, ext, contains) in [("html", "html", "<strong>bold</strong>"), ("md", "md", "**bold**"), ("latex", "tex", "\\textbf{bold}"), ("txt", "txt", "*bold*"), ("reveal", "html", "One")] {
252 let (status, out, err) = sandbox.run("export", "notes.org", "--to", format)
253 #expect(status == 0, "\(format): \(err)")
254 let path = sandbox.notes.appendingPathComponent("notes.\(ext)").path
255 #expect(out == "Exported to \(path)\n")
256 #expect(try String(contentsOfFile: path, encoding: .utf8).contains(contains), "\(format)")
257 }
258 #expect(sandbox.run("export", "notes.org", "--to", "odt", "-o", "out/notes.odt").status == 0)
259 let odt = try Data(contentsOf: sandbox.notes.appendingPathComponent("out/notes.odt"))
260 #expect(odt.prefix(2) == Data("PK".utf8))
261 }
262
263 @Test func writesToStandardOutput() throws {
264 let sandbox = try Sandbox()
265 try sandbox.write(Self.text, "notes.org")
266 let (status, out, _) = sandbox.run("export", "notes.org", "--to=md", "-o", "-")
267 #expect(status == 0)
268 #expect(out.contains("# One"))
269 #expect(!FileManager.default.fileExists(atPath: sandbox.notes.appendingPathComponent("notes.md").path))
270 }
271
272 @Test(.enabled(if: !FileManager.default.fileExists(atPath: "/Library/TeX/texbin/pdflatex"))) func pdfWithoutTeXSaysWhatItNeeds() throws {
273 let sandbox = try Sandbox()
274 try sandbox.write(Self.text, "notes.org")
275 let (status, _, err) = sandbox.run("export", "notes.org", "--to", "pdf")
276 #expect(status == 1)
277 #expect(err.contains("needs TeX"))
278 }
279
280 @Test func tanglesBlocks() throws {
281 let sandbox = try Sandbox()
282 try sandbox.write("* Script\n#+begin_src sh :tangle out/run.sh :mkdirp yes\necho hi\n#+end_src\n", "code.org")
283 let (status, out, err) = sandbox.run("tangle", "code.org")
284 #expect(status == 0, "\(err)")
285 #expect(out == "Tangled 1 code block from code.org\n")
286 #expect(try sandbox.read("out/run.sh") == "echo hi\n")
287 }
288}
289
290@MainActor
291struct ArgumentTests {
292 @Test func usageErrorsExitWithTwo() throws {
293 let sandbox = try Sandbox()
294 try sandbox.write("* A\n", "a.org")
295 #expect(sandbox.run().status == 2)
296 #expect(sandbox.run("frobnicate").status == 2)
297 #expect(sandbox.run("agenda", "--bogus").status == 2)
298 #expect(sandbox.run("agenda", "one", "two").status == 2)
299 #expect(sandbox.run("export", "a.org").status == 2)
300 #expect(sandbox.run("export", "a.org", "--to", "doc").status == 2)
301 #expect(sandbox.run("export", "a.org", "--to").status == 2)
302 #expect(sandbox.run("capture").status == 2)
303 #expect(sandbox.run("capture", "t", "x", "--set", "novalue").status == 2)
304 #expect(sandbox.run("clock").status == 2)
305 #expect(sandbox.run("clock", "in").status == 2)
306 #expect(sandbox.run("clock", "in", "a.org").status == 2)
307 #expect(sandbox.run("export", "missing.org", "--to", "md").status == 3)
308 }
309
310 @Test func helpAndVersion() throws {
311 let sandbox = try Sandbox()
312 let help = sandbox.run("--help")
313 #expect(help.status == 0)
314 #expect(help.out.contains("Exit status:"))
315 for command in ["agenda", "capture", "clock", "export", "tangle", "open"] {
316 let result = sandbox.run(command, "--help")
317 #expect(result.status == 0)
318 #expect(result.out.hasPrefix("Usage: orgstar \(command)"))
319 }
320 #expect(sandbox.run("help", "clock").out.hasPrefix("Usage: orgstar clock"))
321 #expect(sandbox.run("--version").out == "orgstar (development build)\n")
322 }
323
324 @Test func opensTheEntryInTheApp() throws {
325 let sandbox = try Sandbox()
326 try sandbox.write("* A\n* B\n", "a.org")
327 #expect(sandbox.run("open", "a.org::B").status == 0)
328 let path = sandbox.notes.appendingPathComponent("a.org").path
329 var link = URLComponents()
330 link.scheme = "orgstar"
331 link.host = "entry"
332 link.queryItems = [URLQueryItem(name: "path", value: path), URLQueryItem(name: "offset", value: "4")]
333 #expect(sandbox.opened == [[link.url!.absoluteString]])
334 }
335}