Tests/OrgProgramsTests/ProgramsTests.swift

0dbf01d3bc8b68b775dfc3a8385b84bd682b85dd
orgstar/Tests/OrgProgramsTests/ProgramsTests.swift

406 lines · 24062 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=floor($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 floor 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 | floor(a) |\n| y    | 2 | 2        |\n#+TBLFM: $3=floor($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=floor($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    /// A `:cmd` the shell expands, such as `~/../../opt/homebrew/bin/node`, runs node, as in Org.
259    @Test(.enabled(if: BabelRunner.installed("node")))
260    func expandsTheCommandAsTheShellDoes() async throws {
261        let node = try #require(BabelRunner.environment["PATH"]?.split(separator: ":").map { "\($0)/node" }
262            .first { FileManager.default.isExecutableFile(atPath: $0) })
263        let home = NSHomeDirectory()
264        let up = String(repeating: "../", count: home.split(separator: "/").count)
265        for cmd in ["~/" + up + node.dropFirst(), "$HOME/" + up + node.dropFirst(), "'\(node)'"] {
266            let output = try await run("#+begin_src js :cmd \"\(cmd)\" :results output\nconsole.log(typeof __filename)\n#+end_src\n")
267            #expect(output.stdout == "string\n", "\(cmd)")
268        }
269    }
270
271    /// An expanded `:cmd` that isn't installed runs in JavaScriptCore.
272    @Test func expandedCommandFallsBack() async throws {
273        #expect(try await run("#+begin_src js :cmd ~/no-such-node\nreturn [1, 2]\n#+end_src\n").stdout == "[ 1, 2 ]")
274    }
275}
276
277/// Interpreters run through `/bin/sh`, as Org runs them.
278struct ShellCommandTests {
279    @Test func words() {
280        #expect(BabelRunner.words("node --no-warnings") == ["node", "--no-warnings"])
281        #expect(BabelRunner.words("~/bin/node") == [NSHomeDirectory() + "/bin/node"])
282        #expect(BabelRunner.words("'a b' \"$HOME\"") == ["a b", NSHomeDirectory()])
283    }
284
285    /// A command substitution in the command runs once, when the block runs, as in Org.
286    @Test(arguments: ["js :cmd", "python :python", "ruby :ruby"])
287    func substitutionRunsOnce(header: String) async throws {
288        #expect(BabelRunner.words("$(echo node)").isEmpty)
289        #expect(BabelRunner.words("`echo node`").isEmpty)
290        let folder = try Folder()
291        let count = folder.url.appendingPathComponent("count").path
292        let text = "#+begin_src \(header) \"$(echo x >> '\(count)'; echo cat)\" :results output\n1\n#+end_src\n"
293        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
294        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
295        _ = try await Programs().runBabel(job, fileDirectory: folder.url)
296        #expect(try String(contentsOfFile: count, encoding: .utf8) == "x\n")
297    }
298
299    @Test(.enabled(if: BabelRunner.installed("python3")))
300    func pythonWithOptions() async throws {
301        let text = "#+begin_src python :python \"python3 -X utf8\" :results output\nimport sys\nprint(sys.flags.utf8_mode)\n#+end_src\n"
302        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
303        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
304        #expect(try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory).stdout == "1\n")
305    }
306
307    /// Standard input is a file, as `org-babel-eval` gives it.
308    @Test(.enabled(if: BabelRunner.installed("node")))
309    func standardInputIsAFile() async throws {
310        let text = "#+begin_src js :results output\nconst s = require('fs').fstatSync(0)\nconsole.log(s.isFile(), s.isFIFO(), process.stdin.constructor.name)\n#+end_src\n"
311        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
312        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
313        #expect(try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory).stdout == "true false ReadStream\n")
314    }
315}
316
317/// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them.
318@MainActor
319@Suite(.programs)
320struct NodeFileTests {
321    static let cases = [
322        "#+begin_src js :results output\nconsole.log(typeof require, typeof module, typeof exports, process.argv.length, require.main === module)\n#+end_src\n",
323        "#+begin_src js :results output\nconst path = require('path'), fs = require('fs')\nconsole.log(path.dirname(__filename) === __dirname, __dirname === process.cwd(), "
324            + "path.dirname(__dirname) === fs.realpathSync(require('os').tmpdir()), path.basename(process.argv[1]) === path.basename(__filename))\n#+end_src\n",
325        "#+begin_src js\nreturn [typeof require, typeof module, process.argv.length, this === module.exports]\n#+end_src\n",
326        "#+begin_src js :results output\ntry { require('./helper'); console.log('found') } catch (e) { console.log(e.code) }\nconsole.log(require(process.cwd() + '/helper'))\n#+end_src\n",
327        "#+begin_src js :results output\nimport os from 'os'\nconsole.log(typeof require, typeof os.tmpdir)\n#+end_src\n",
328        "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n",
329        "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n",
330        "#+begin_src js :results output\nconsole.log('top'); return; console.log('not reached')\n#+end_src\n",
331        "#+begin_src js :results output\nconst s = require('fs').fstatSync(0)\nconsole.log(s.isFile(), s.isFIFO(), process.stdin.constructor.name)\n#+end_src\n",
332    ]
333
334    /// The results Emacs inserts. `org-babel-temporary-directory` is set as interactive Emacs
335    /// sets it; `--batch` leaves it nil and writes the file straight into the temporary folder.
336    @Test(.enabled(if: EmacsRunner.executable() != nil && BabelRunner.installed("node") && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
337    func resultsMatchEmacs() async throws {
338        let folder = try Folder()
339        try folder.write("helper.js", "module.exports = 1\n")
340        var forms: [String] = []
341        var ours: [String] = []
342        for text in Self.cases {
343            let file = try folder.write("b.org", text)
344            let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
345            session.open(file.path)
346            guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else {
347                Issue.record("not planned: \(text)")
348                return
349            }
350            _ = await session.runBabel(job)
351            ours.append(session.document?.text ?? "")
352            let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
353            forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char 3) (org-babel-execute-src-block) (princ (concat (buffer-string) \"\\f\")))")
354        }
355        let process = Process()
356        process.executableURL = EmacsRunner.executable()
357        process.currentDirectoryURL = folder.url
358        process.arguments = ["-Q", "--batch", "--eval", """
359            (progn (require 'org) (require 'ob-js)
360              (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node" org-babel-temporary-directory (make-temp-file "babel-" t))
361              \(forms.joined(separator: "\n"))
362              (delete-directory org-babel-temporary-directory t))
363            """]
364        let out = Pipe()
365        process.standardOutput = out
366        process.standardError = FileHandle.nullDevice
367        try process.run()
368        let emacs = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
369            .split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
370        process.waitUntilExit()
371        for (i, text) in Self.cases.enumerated() {
372            #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
373        }
374    }
375
376    /// The file is gone once the block has run.
377    @Test(.enabled(if: BabelRunner.installed("node")))
378    func removesTheFile() async throws {
379        let text = "#+begin_src js :results output\nconsole.log(__filename)\n#+end_src\n"
380        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
381        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
382        let output = try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory)
383        let file = output.stdout.trimmingCharacters(in: .newlines)
384        #expect(file.hasPrefix("/") && !FileManager.default.fileExists(atPath: file))
385    }
386}
387
388/// Emacs Lisp runs in `Elisp` when Emacs isn't installed.
389struct EmacsLispFallbackTests {
390    func run(_ text: String) async throws -> BabelOutput {
391        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
392        guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
393        return try await Programs(emacs: { nil }).runBabel(job, fileDirectory: FileManager.default.temporaryDirectory)
394    }
395
396    @Test func runsWithoutEmacs() async throws {
397        #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\""))
398    }
399
400    @Test func refusesWhatOnlyEmacsRuns() async throws {
401        let error = await #expect(throws: BabelRunner.Failure.self) {
402            try await run("#+begin_src emacs-lisp\n(with-temp-buffer (insert \"x\") (buffer-string))\n#+end_src\n")
403        }
404        #expect(error?.description == "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed.")
405    }
406}
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