Tests/OrgstarCLITests/ToolTests.swift

72f19c1f379646b2cfc45c5053a72e5997fbef36
orgstar/Tests/OrgstarCLITests/ToolTests.swift

323 lines · 14740 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
172@MainActor
173struct ClockTests {
174    @Test func clocksInAndOutAndSwitches() throws {
175        let sandbox = try Sandbox()
176        try sandbox.write("* Report\n* Email\n", "work.org")
177        #expect(sandbox.run("clock", "status").status == 3)
178        let clockIn = sandbox.run("clock", "in", "work.org::Report")
179        #expect(clockIn.status == 0, "\(clockIn.err)")
180        #expect(clockIn.out == "Clock starts at [2026-11-26 Thu 10:00] in \"Report\"\n")
181        #expect(try sandbox.read("work.org") == "* Report\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 10:00]\n:END:\n* Email\n")
182
183        sandbox.now += 25 * 60
184        let status = sandbox.run("clock", "status", "--json")
185        let json = try #require(try JSONSerialization.jsonObject(with: Data(status.out.utf8)) as? [String: Any])
186        let running = try #require(json["running"] as? [String: Any])
187        #expect(running["heading"] as? String == "Report")
188        #expect(running["minutes"] as? Int == 25)
189
190        sandbox.now += 5 * 60
191        let switched = sandbox.run("clock", "in", "work.org::*Email")
192        #expect(switched.status == 0, "\(switched.err)")
193        #expect(switched.out == "Clock stopped after 0:30 in \"Report\"\nClock starts at [2026-11-26 Thu 10:30] in \"Email\"\n")
194
195        sandbox.now += 60 * 60
196        let out = sandbox.run("clock", "out")
197        #expect(out.out == "Clock stopped after 1:00 in \"Email\"\n")
198        #expect(try sandbox.read("work.org") == """
199        * Report
200        :LOGBOOK:
201        CLOCK: [2026-11-26 Thu 10:00]--[2026-11-26 Thu 10:30] =>  0:30
202        :END:
203        * Email
204        :LOGBOOK:
205        CLOCK: [2026-11-26 Thu 10:30]--[2026-11-26 Thu 11:30] =>  1:00
206        :END:
207
208        """)
209        let none = sandbox.run("clock", "out")
210        #expect(none.status == 3)
211        #expect(none.err == "orgstar: No active clock\n")
212    }
213
214    @Test func clocksInByID() throws {
215        let sandbox = try Sandbox()
216        try sandbox.write("* Report\n:PROPERTIES:\n:ID: abc-123\n:END:\n", "work.org")
217        #expect(sandbox.run("clock", "in", "id:abc-123").status == 0)
218        #expect(try sandbox.read("work.org").contains(":END:\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 10:00]\n:END:\n"))
219        #expect(sandbox.run("clock", "in", "work.org::Nothing").status == 3)
220    }
221
222    @Test func keepsAVersionInRecovery() throws {
223        let sandbox = try Sandbox()
224        try sandbox.write("* Report\n", "work.org")
225        #expect(sandbox.run("clock", "in", "work.org::Report").status == 0)
226        let recovery = sandbox.data.appendingPathComponent("Recovery")
227        let kept = try FileManager.default.subpathsOfDirectory(atPath: recovery.path).filter { $0.hasSuffix("work.org") }
228        #expect(kept.count == 1)
229    }
230}
231
232@MainActor
233struct ExportTests {
234    static let text = "#+TITLE: Notes\n* One\nSome *bold* text.\n"
235
236    @Test func exportsBesideTheFile() throws {
237        let sandbox = try Sandbox()
238        try sandbox.write(Self.text, "notes.org")
239        for (format, ext, contains) in [("html", "html", "<strong>bold</strong>"), ("md", "md", "**bold**"), ("latex", "tex", "\\textbf{bold}"), ("txt", "txt", "*bold*"), ("reveal", "html", "One")] {
240            let (status, out, err) = sandbox.run("export", "notes.org", "--to", format)
241            #expect(status == 0, "\(format): \(err)")
242            let path = sandbox.notes.appendingPathComponent("notes.\(ext)").path
243            #expect(out == "Exported to \(path)\n")
244            #expect(try String(contentsOfFile: path, encoding: .utf8).contains(contains), "\(format)")
245        }
246        #expect(sandbox.run("export", "notes.org", "--to", "odt", "-o", "out/notes.odt").status == 0)
247        let odt = try Data(contentsOf: sandbox.notes.appendingPathComponent("out/notes.odt"))
248        #expect(odt.prefix(2) == Data("PK".utf8))
249    }
250
251    @Test func writesToStandardOutput() throws {
252        let sandbox = try Sandbox()
253        try sandbox.write(Self.text, "notes.org")
254        let (status, out, _) = sandbox.run("export", "notes.org", "--to=md", "-o", "-")
255        #expect(status == 0)
256        #expect(out.contains("# One"))
257        #expect(!FileManager.default.fileExists(atPath: sandbox.notes.appendingPathComponent("notes.md").path))
258    }
259
260    @Test(.enabled(if: !FileManager.default.fileExists(atPath: "/Library/TeX/texbin/pdflatex"))) func pdfWithoutTeXSaysWhatItNeeds() throws {
261        let sandbox = try Sandbox()
262        try sandbox.write(Self.text, "notes.org")
263        let (status, _, err) = sandbox.run("export", "notes.org", "--to", "pdf")
264        #expect(status == 1)
265        #expect(err.contains("needs TeX"))
266    }
267
268    @Test func tanglesBlocks() throws {
269        let sandbox = try Sandbox()
270        try sandbox.write("* Script\n#+begin_src sh :tangle out/run.sh :mkdirp yes\necho hi\n#+end_src\n", "code.org")
271        let (status, out, err) = sandbox.run("tangle", "code.org")
272        #expect(status == 0, "\(err)")
273        #expect(out == "Tangled 1 code block from code.org\n")
274        #expect(try sandbox.read("out/run.sh") == "echo hi\n")
275    }
276}
277
278@MainActor
279struct ArgumentTests {
280    @Test func usageErrorsExitWithTwo() throws {
281        let sandbox = try Sandbox()
282        try sandbox.write("* A\n", "a.org")
283        #expect(sandbox.run().status == 2)
284        #expect(sandbox.run("frobnicate").status == 2)
285        #expect(sandbox.run("agenda", "--bogus").status == 2)
286        #expect(sandbox.run("agenda", "one", "two").status == 2)
287        #expect(sandbox.run("export", "a.org").status == 2)
288        #expect(sandbox.run("export", "a.org", "--to", "doc").status == 2)
289        #expect(sandbox.run("export", "a.org", "--to").status == 2)
290        #expect(sandbox.run("capture").status == 2)
291        #expect(sandbox.run("capture", "t", "x", "--set", "novalue").status == 2)
292        #expect(sandbox.run("clock").status == 2)
293        #expect(sandbox.run("clock", "in").status == 2)
294        #expect(sandbox.run("clock", "in", "a.org").status == 2)
295        #expect(sandbox.run("export", "missing.org", "--to", "md").status == 3)
296    }
297
298    @Test func helpAndVersion() throws {
299        let sandbox = try Sandbox()
300        let help = sandbox.run("--help")
301        #expect(help.status == 0)
302        #expect(help.out.contains("Exit status:"))
303        for command in ["agenda", "capture", "clock", "export", "tangle", "open"] {
304            let result = sandbox.run(command, "--help")
305            #expect(result.status == 0)
306            #expect(result.out.hasPrefix("Usage: orgstar \(command)"))
307        }
308        #expect(sandbox.run("help", "clock").out.hasPrefix("Usage: orgstar clock"))
309        #expect(sandbox.run("--version").out == "orgstar (development build)\n")
310    }
311
312    @Test func opensTheEntryInTheApp() throws {
313        let sandbox = try Sandbox()
314        try sandbox.write("* A\n* B\n", "a.org")
315        #expect(sandbox.run("open", "a.org::B").status == 0)
316        let path = sandbox.notes.appendingPathComponent("a.org").path
317        var link = URLComponents()
318        link.scheme = "orgstar"
319        link.host = "entry"
320        link.queryItems = [URLQueryItem(name: "path", value: path), URLQueryItem(name: "offset", value: "4")]
321        #expect(sandbox.opened == [[link.url!.absoluteString]])
322    }
323}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form