Tests/OrgProgramsTests/ProgramsTests.swift

175 lines · 9354 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}