Tests/OrgProgramsTests/ProgramsTests.swift
222 lines · 11972 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6@testable import OrgPrograms
7
8/// Runs each test with `Programs` as the session's runner, scoped to the test's task so
9/// suites without one are unaffected.
10struct WithPrograms: SuiteTrait, TestTrait, TestScoping {
11 func provideScope(for test: Test, testCase: Test.Case?, performing function: @Sendable () async throws -> Void) async throws {
12 try await DocumentSession.$scopedPrograms.withValue(Programs()) { try await function() }
13 }
14}
15
16extension Trait where Self == WithPrograms {
17 static var programs: Self { WithPrograms() }
18}
19
20@MainActor
21@Suite(.programs)
22struct EmacsFallbackTests {
23 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
24 func recalculatesTablesNativeCodeCannot() async throws {
25 let notes = try Folder()
26 let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n")
27 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
28 session.open(file.path)
29 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
30 guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp, _, _)) = step else {
31 Issue.record("\(step)")
32 return
33 }
34 #expect(reason == "non-numeric field a")
35 #expect(!lisp)
36 let message = await session.recalculateInEmacs(table: table, point: point, form: form)
37 #expect(message == "Recalculated in Emacs")
38 #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | 2 a |\n| y | 2 | 4 |\n#+TBLFM: $3=$2*2\n")
39 }
40
41 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
42 func cancelingARecalculationLeavesTheTable() async throws {
43 let notes = try Folder()
44 let text = "| n | twice |\n|---+-------|\n| a | |\n#+TBLFM: $2=$1*2\n"
45 let file = try notes.write("t.org", text)
46 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
47 session.open(file.path)
48 let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil)
49 guard case .external(.emacsTable(let table, let point, let form, _, _, _, _)) = step else {
50 Issue.record("\(step)")
51 return
52 }
53 let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) }
54 task.cancel()
55 #expect(await task.value == "Recalculation canceled")
56 #expect(session.document?.text == text)
57 }
58}
59
60@MainActor
61@Suite(.programs)
62struct BabelSessionTests {
63 @Test func runsBlocksAndWritesResults() async throws {
64 let notes = try Folder()
65 let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
66 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
67 session.open(file.path)
68 let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
69 guard case .external(.babel(let job)) = step else {
70 Issue.record("\(step)")
71 return
72 }
73 #expect(await session.runBabel(job) == "Code block evaluation complete.")
74 // A column that is half numbers is right-aligned, as org-table-align does.
75 #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n| 42 |\n")
76 }
77}
78
79@MainActor
80@Suite(.programs)
81struct BabelErrorTests {
82 func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
83 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
84 throw CancellationError()
85 }
86 return job
87 }
88
89 /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
90 @Test func reportsErrorsAndStillInsertsResults() async throws {
91 let notes = try Folder()
92 let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
93 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
94 session.open(file.path)
95 #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
96 #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
97 }
98
99 @Test func cancelsARunningBlock() async throws {
100 let notes = try Folder()
101 let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
102 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
103 session.open(file.path)
104 let start = ContinuousClock.now
105 var message: String?
106 session.startBabel(try job(session, file.path)) { message = $0 }
107 #expect(session.isRunningBabel)
108 try await Task.sleep(for: .milliseconds(200))
109 session.cancelBabel()
110 while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
111 #expect(message == "Code block canceled.")
112 #expect(!session.isRunningBabel)
113 #expect(ContinuousClock.now - start < .seconds(5))
114 #expect(session.document?.text.contains("#+RESULTS:") == false)
115 }
116}
117
118struct EmacsExportTests {
119 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
120 func exportsBesideTheFile() async throws {
121 let notes = try Folder()
122 let file = try notes.write("doc.org", "#+TITLE: On disk\n")
123 // The buffer's text is exported, not the file's.
124 let written = try await EmacsRunner.export(text: "#+TITLE: In the buffer\n\n* Heading\nBody.\n", path: file.path, function: "org-ascii-export-to-ascii")
125 #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
126 let text = try String(contentsOfFile: written, encoding: .utf8)
127 #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
128 #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
129 }
130
131 /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used.
132 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
133 func exportsTheSubtreeBodyOnly() async throws {
134 let notes = try Folder()
135 let file = try notes.write("doc.org", "")
136 let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n"
137 let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1
138 let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true)
139 #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt")
140 let out = try String(contentsOfFile: written, encoding: .utf8)
141 #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)")
142 }
143
144 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
145 func exportUsesBabelPath() async throws {
146 let notes = try Folder()
147 let file = try notes.write("doc.org", "")
148 let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"#
149 let written = try await EmacsRunner.export(text: "", path: file.path, function: function)
150 #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"])
151 }
152
153 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
154 func cancellingStopsTheExport() async throws {
155 let notes = try Folder()
156 let file = try notes.write("doc.org", "")
157 let pidFile = notes.url.appendingPathComponent("pid")
158 let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"#
159 let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) }
160 var pid: pid_t?
161 for _ in 0..<200 where pid == nil {
162 try await Task.sleep(for: .milliseconds(50))
163 pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) }
164 }
165 let started = try #require(pid)
166 export.cancel()
167 await #expect(throws: CancellationError.self) { try await export.value }
168 var alive = true
169 for _ in 0..<100 where alive {
170 alive = kill(started, 0) == 0
171 if alive { try await Task.sleep(for: .milliseconds(50)) }
172 }
173 #expect(!alive)
174 }
175}
176
177/// js runs in JavaScriptCore when its interpreter isn't installed, and in node when it is.
178struct JavaScriptFallbackTests {
179 func run(_ text: String) async throws -> BabelOutput {
180 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
181 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
182 return try await Programs().runBabel(job, fileDirectory: FileManager.default.temporaryDirectory)
183 }
184
185 @Test func runsWithoutTheInterpreter() async throws {
186 #expect(try await run("#+begin_src js :cmd no-such-node\nreturn [1, 2]\n#+end_src\n").stdout == "[ 1, 2 ]")
187 #expect(try await run("#+begin_src js :cmd no-such-node :session s\n6 * 7\n#+end_src\n").resultFile == "42")
188 }
189
190 /// A `:cmd` with arguments isn't run in JavaScriptCore, which can't take node's options.
191 @Test func leavesACommandWithArgumentsToTheRunner() async throws {
192 let error = await #expect(throws: BabelRunner.Failure.self) {
193 try await run("#+begin_src js :cmd \"no-such-node --no-warnings\" :results output\nconsole.log(1)\n#+end_src\n")
194 }
195 #expect(error?.description == "no-such-node --no-warnings isn't installed.")
196 }
197
198 @Test(.enabled(if: BabelRunner.installed("node")))
199 func usesNodeWhenInstalled() async throws {
200 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n")
201 }
202}
203
204/// Emacs Lisp runs in `Elisp` when Emacs isn't installed.
205struct EmacsLispFallbackTests {
206 func run(_ text: String) async throws -> BabelOutput {
207 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
208 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
209 return try await Programs(emacs: { nil }).runBabel(job, fileDirectory: FileManager.default.temporaryDirectory)
210 }
211
212 @Test func runsWithoutEmacs() async throws {
213 #expect(try await run("#+begin_src emacs-lisp\n(cl-loop for i from 1 to 4 sum i)\n#+end_src\n").stdout.contains("\"s\":\"10\""))
214 }
215
216 @Test func refusesWhatOnlyEmacsRuns() async throws {
217 let error = await #expect(throws: BabelRunner.Failure.self) {
218 try await run("#+begin_src emacs-lisp\n(with-temp-buffer (insert \"x\") (buffer-string))\n#+end_src\n")
219 }
220 #expect(error?.description == "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed.")
221 }
222}