Tests/OrgProgramsTests/ProgramsTests.swift

586bad784d2cb2ad1bb43da0e63f0819913ed1dc
orgstar/Tests/OrgProgramsTests/ProgramsTests.swift

277 lines · 15563 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=sqrt($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 == "function sqrt of a formula")
 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 | sqrt(a)   |\n| y    | 2 | 1.4142136 |\n#+TBLFM: $3=sqrt($2)\n")
 39    }
 40
 41    /// `elisp:` links run in Emacs, in a copy of the file with point at the caret; in
 42    /// orgstar's interpreter when Emacs is missing.
 43    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 44    func evaluatesElispLinks() async throws {
 45        let notes = try Folder()
 46        let file = try notes.write("l.org", "* Head\nSee [[elisp:(org-get-heading t t)]].\n")
 47        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 48        session.open(file.path)
 49        let heading = await session.evaluateLink("(org-get-heading t t)")
 50        #expect(heading == "(org-get-heading t t) => Head")
 51        let list = await session.evaluateLink("(list 1 \"a\")")
 52        #expect(list == "(list 1 \"a\") => (1 a)")
 53        let error = await session.evaluateLink("(car 1)")
 54        #expect(error == "Wrong type argument: listp, 1")
 55        await DocumentSession.$scopedPrograms.withValue(Programs(emacs: { nil })) {
 56            #expect(await session.evaluateLink("(+ 1 2)") == "(+ 1 2) => 3")
 57            #expect(await session.evaluateLink("(org-get-heading t t)") == "This link uses Emacs Lisp that runs only in Emacs.")
 58        }
 59    }
 60
 61    /// Emacs can run each compiled language and interpreter orgstar runs, for `org-sbe`.
 62    @Test(.enabled(if: EmacsRunner.executable() != nil))
 63    func loadsEveryLanguageForOrgSbe() throws {
 64        let languages = ["C", "C++", "D", "fortran", "java", "clojure", "awk", "js", "python", "R", "ruby", "sh", "bash"]
 65        let process = Process()
 66        process.executableURL = EmacsRunner.executable()
 67        process.arguments = ["-Q", "--batch", "--eval", "(progn (require 'org) " + EmacsRunner.sbeLanguages
 68            + " (princ (mapconcat (lambda (l) (if (fboundp (intern (concat \"org-babel-execute:\" l))) \"\" l)) '(" + languages.map { "\"\($0)\"" }.joined(separator: " ") + ") \"\")))"]
 69        let out = Pipe()
 70        process.standardOutput = out
 71        process.standardError = FileHandle.nullDevice
 72        try process.run()
 73        process.waitUntilExit()
 74        #expect(String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) == "")
 75    }
 76
 77    /// `org-sbe` on a block only Emacs runs: Emacs runs it without asking again.
 78    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 79    func runsOtherLanguagesForOrgSbe() async throws {
 80        let notes = try Folder()
 81        let text = "#+NAME: f\n#+begin_src sh :var n=2\necho $((n * 3))\n#+end_src\n\n| n | f |\n|---+---|\n| 3 | |\n#+TBLFM: $2='(org-sbe f (n $1))\n"
 82        let file = try notes.write("t.org", text)
 83        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 84        session.open(file.path)
 85        let step = session.perform(TableRecalculate(all: true), path: file.path, at: (text as NSString).range(of: "#+TBLFM").location + 3, expect: nil)
 86        guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp, _, _)) = step else {
 87            Issue.record("\(step)")
 88            return
 89        }
 90        #expect(reason == "Lisp org-sbe with sh blocks")
 91        #expect(lisp)
 92        #expect(await session.recalculateInEmacs(table: table, point: point, form: form) == "Recalculated in Emacs")
 93        #expect(session.document?.text.hasSuffix("| n | f |\n|---+---|\n| 3 | 9 |\n#+TBLFM: $2='(org-sbe f (n $1))\n") == true)
 94    }
 95
 96    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 97    func cancelingARecalculationLeavesTheTable() async throws {
 98        let notes = try Folder()
 99        let text = "| n | twice |\n|---+-------|\n| a |       |\n#+TBLFM: $2=sqrt($1)\n"
100        let file = try notes.write("t.org", text)
101        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
102        session.open(file.path)
103        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil)
104        guard case .external(.emacsTable(let table, let point, let form, _, _, _, _)) = step else {
105            Issue.record("\(step)")
106            return
107        }
108        let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) }
109        task.cancel()
110        #expect(await task.value == "Recalculation canceled")
111        #expect(session.document?.text == text)
112    }
113}
114
115@MainActor
116@Suite(.programs)
117struct BabelSessionTests {
118    @Test func runsBlocksAndWritesResults() async throws {
119        let notes = try Folder()
120        let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
121        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
122        session.open(file.path)
123        let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
124        guard case .external(.babel(let job)) = step else {
125            Issue.record("\(step)")
126            return
127        }
128        #expect(await session.runBabel(job) == "Code block evaluation complete.")
129        // A column that is half numbers is right-aligned, as org-table-align does.
130        #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n|     42 |\n")
131    }
132}
133
134@MainActor
135@Suite(.programs)
136struct BabelErrorTests {
137    func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
138        guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
139            throw CancellationError()
140        }
141        return job
142    }
143
144    /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
145    @Test func reportsErrorsAndStillInsertsResults() async throws {
146        let notes = try Folder()
147        let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
148        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
149        session.open(file.path)
150        #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
151        #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
152    }
153
154    @Test func cancelsARunningBlock() async throws {
155        let notes = try Folder()
156        let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
157        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
158        session.open(file.path)
159        let start = ContinuousClock.now
160        var message: String?
161        session.startBabel(try job(session, file.path)) { message = $0 }
162        #expect(session.isRunningBabel)
163        try await Task.sleep(for: .milliseconds(200))
164        session.cancelBabel()
165        while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
166        #expect(message == "Code block canceled.")
167        #expect(!session.isRunningBabel)
168        #expect(ContinuousClock.now - start < .seconds(5))
169        #expect(session.document?.text.contains("#+RESULTS:") == false)
170    }
171}
172
173struct EmacsExportTests {
174    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
175    func exportsBesideTheFile() async throws {
176        let notes = try Folder()
177        let file = try notes.write("doc.org", "#+TITLE: On disk\n")
178        // The buffer's text is exported, not the file's.
179        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")
180        #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
181        let text = try String(contentsOfFile: written, encoding: .utf8)
182        #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
183        #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
184    }
185
186    /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used.
187    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
188    func exportsTheSubtreeBodyOnly() async throws {
189        let notes = try Folder()
190        let file = try notes.write("doc.org", "")
191        let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n"
192        let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1
193        let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true)
194        #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt")
195        let out = try String(contentsOfFile: written, encoding: .utf8)
196        #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)")
197    }
198
199    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
200    func exportUsesBabelPath() async throws {
201        let notes = try Folder()
202        let file = try notes.write("doc.org", "")
203        let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"#
204        let written = try await EmacsRunner.export(text: "", path: file.path, function: function)
205        #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"])
206    }
207
208    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
209    func cancellingStopsTheExport() async throws {
210        let notes = try Folder()
211        let file = try notes.write("doc.org", "")
212        let pidFile = notes.url.appendingPathComponent("pid")
213        let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"#
214        let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) }
215        var pid: pid_t?
216        for _ in 0..<200 where pid == nil {
217            try await Task.sleep(for: .milliseconds(50))
218            pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) }
219        }
220        let started = try #require(pid)
221        export.cancel()
222        await #expect(throws: CancellationError.self) { try await export.value }
223        var alive = true
224        for _ in 0..<100 where alive {
225            alive = kill(started, 0) == 0
226            if alive { try await Task.sleep(for: .milliseconds(50)) }
227        }
228        #expect(!alive)
229    }
230}
231
232/// js runs in JavaScriptCore when its interpreter isn't installed, and in node when it is.
233struct JavaScriptFallbackTests {
234    func run(_ text: String) async throws -> BabelOutput {
235        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
236        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
237        return try await Programs().runBabel(job, fileDirectory: FileManager.default.temporaryDirectory)
238    }
239
240    @Test func runsWithoutTheInterpreter() async throws {
241        #expect(try await run("#+begin_src js :cmd no-such-node\nreturn [1, 2]\n#+end_src\n").stdout == "[ 1, 2 ]")
242        #expect(try await run("#+begin_src js :cmd no-such-node :session s\n6 * 7\n#+end_src\n").resultFile == "42")
243    }
244
245    /// A `:cmd` with arguments isn't run in JavaScriptCore, which can't take node's options.
246    @Test func leavesACommandWithArgumentsToTheRunner() async throws {
247        let error = await #expect(throws: BabelRunner.Failure.self) {
248            try await run("#+begin_src js :cmd \"no-such-node --no-warnings\" :results output\nconsole.log(1)\n#+end_src\n")
249        }
250        #expect(error?.description == "no-such-node --no-warnings isn't installed.")
251    }
252
253    @Test(.enabled(if: BabelRunner.installed("node")))
254    func usesNodeWhenInstalled() async throws {
255        #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n")
256    }
257}
258
259/// Emacs Lisp runs in `Elisp` when Emacs isn't installed.
260struct EmacsLispFallbackTests {
261    func run(_ text: String) async throws -> BabelOutput {
262        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
263        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
264        return try await Programs(emacs: { nil }).runBabel(job, fileDirectory: FileManager.default.temporaryDirectory)
265    }
266
267    @Test func runsWithoutEmacs() async throws {
268        #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\""))
269    }
270
271    @Test func refusesWhatOnlyEmacsRuns() async throws {
272        let error = await #expect(throws: BabelRunner.Failure.self) {
273            try await run("#+begin_src emacs-lisp\n(with-temp-buffer (insert \"x\") (buffer-string))\n#+end_src\n")
274        }
275        #expect(error?.description == "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed.")
276    }
277}
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