Tests/OrgCoreTests/BabelPostTests.swift

design-themes-widgets
orgstar/Tests/OrgCoreTests/BabelPostTests.swift history · blame · raw

224 lines · 12266 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// `:post` with `*this*`, and noweb references that run a block.
  6struct BabelPostTests {
  7    static let helpers = """
  8        #+NAME: wrap
  9        #+begin_src emacs-lisp :var x="" :var y=">"
 10        (format "<%s%s" x y)
 11        #+end_src
 12
 13        #+NAME: double
 14        #+begin_src emacs-lisp :var n=0
 15        (* 2 n)
 16        #+end_src
 17
 18        #+NAME: bump
 19        #+begin_src emacs-lisp :var rows='()
 20        (mapcar (lambda (row) (mapcar #'1+ row)) rows)
 21        #+end_src
 22
 23        #+NAME: pair
 24        #+begin_src emacs-lisp :var x=""
 25        (list (list x (length x)))
 26        #+end_src
 27
 28        #+NAME: twice
 29        #+begin_src emacs-lisp :var n=0 :post double(n=*this*)
 30        (* 2 n)
 31        #+end_src
 32
 33        #+NAME: said
 34        #+begin_src sh :results output :var x=""
 35        echo "said $x"
 36        #+end_src
 37
 38        #+NAME: greet
 39        #+begin_src sh
 40        echo hello
 41        #+end_src
 42
 43        #+NAME: lines
 44        #+begin_src sh :results output
 45        printf 'a\\nb\\n'
 46        #+end_src
 47
 48        #+NAME: grid
 49        #+begin_src emacs-lisp
 50        '((1 2) (3 4))
 51        #+end_src
 52
 53        #+NAME: inc
 54        #+begin_src sh :noweb yes
 55        echo <<double(n=5)>>
 56        #+end_src
 57
 58        #+NAME: drawn
 59        #+begin_src sh :results file :file orgstar-post-ref.txt
 60        echo drawn
 61        #+end_src
 62
 63
 64        """
 65
 66    /// Each ends with the block to run, which `MAIN` marks.
 67    static let cases: [String] = [
 68        "#+begin_src sh :post wrap(x=*this*)\necho hello\n#+end_src\n",
 69        "#+begin_src sh :post double(n=*this*)\necho 21\n#+end_src\n",
 70        "#+begin_src sh :post wrap(x=*this*, y=\"!\")\necho hello\n#+end_src\n",
 71        "#+begin_src sh :post bump(rows=*this*)\nprintf '1 2\\n3 4\\n'\n#+end_src\n",
 72        "#+begin_src sh :post pair(x=*this*)\necho hello\n#+end_src\n",
 73        "#+begin_src sh :post twice(n=*this*)\necho 3\n#+end_src\n",
 74        "#+begin_src sh :post said(x=*this*)\necho hello\n#+end_src\n",
 75        "#+begin_src sh :post wrap(x=*this*) :results output\necho one; echo two\n#+end_src\n",
 76        "#+begin_src sh :post wrap(x=*this*) :results file :file orgstar-post.txt\necho data\n#+end_src\n",
 77        "#+begin_src sh :post wrap(x=*this*) :results file drawer :file orgstar-post.txt :file-desc out\necho data\n#+end_src\n",
 78        "#+begin_src sh :post wrap(x=*this*) :results file\necho orgstar-post.txt\n#+end_src\n",
 79        "#+begin_src sh :post wrap(x=*this*) :results raw\necho hello\n#+end_src\n",
 80        "#+begin_src sh :post bump(rows=*this*) :results list\nprintf '1 2\\n3 4\\n'\n#+end_src\n",
 81        "#+begin_src sh :post wrap(x=*this*)\necho new\n#+end_src\n\n#+RESULTS:\n: old\n",
 82        "#+NAME: main\n#+begin_src sh :post double(n=*this*) :var a=double(n=2)\necho $a\n#+end_src\n",
 83        "#+begin_src emacs-lisp :post double(n=*this*) :cache yes\n(+ 1 2)\n#+end_src\n",
 84        "#+begin_src sh :post grid\necho gone\n#+end_src\n",
 85        "#+begin_src sh :var p=drawn\necho $p\n#+end_src\n",
 86        "Text src_sh[:post wrap(x=*this*)]{echo hello} here.\n",
 87        "#+CALL: greet() :post wrap(x=*this*)\n",
 88        "#+begin_src sh :noweb yes\necho <<double(n=4)>>\n#+end_src\n",
 89        "#+begin_src sh :noweb yes\necho <<greet()>> world\n#+end_src\n",
 90        "#+begin_src emacs-lisp :noweb yes\n(length '<<grid()>>)\n#+end_src\n",
 91        "#+begin_src emacs-lisp :noweb yes\n(format \"%S\" '<<bump(rows=grid)>>)\n#+end_src\n",
 92        "#+begin_src sh :noweb yes :results output\n# <<lines()>>\necho done\n#+end_src\n",
 93        "#+begin_src sh :noweb yes :noweb-prefix no :results output\necho <<lines()>>\n#+end_src\n",
 94        "#+begin_src sh :results output\necho '<<double(n=4)>>'\n#+end_src\n",
 95        "#+begin_src sh :noweb eval\necho <<twice(n=2)>>\n#+end_src\n",
 96        "#+begin_src sh :noweb tangle :results output\necho '<<double(n=4)>>'\n#+end_src\n",
 97        "#+begin_src sh :noweb yes\n<<inc>>\n#+end_src\n",
 98        "#+begin_src sh :var v=inc\necho $v\n#+end_src\n",
 99        "#+begin_src sh :noweb yes\necho <<drawn()>>\n#+end_src\n",
100        "#+begin_src sh :noweb yes :post double(n=*this*)\necho <<double(n=1)>>\n#+end_src\n",
101    ]
102
103    static func caret(_ text: String) -> Int { helpers.utf16.count + (text.hasPrefix("#+NAME") ? 14 : text.hasPrefix("Text") ? 8 : 2) }
104
105    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
106    func matchesEmacs() throws {
107        let folder = FileManager.default.temporaryDirectory
108        var emacsCases: [EmacsOracle.Case] = []
109        var ours: [(text: String, failure: String?)] = []
110        for last in Self.cases {
111            let text = Self.helpers + last
112            ours.append(try TestBabelRunner.execute(text, caret: Self.caret(last), directory: folder))
113            emacsCases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(Self.caret(last), in: text), form: """
114            (progn
115              (require 'ob-shell)
116              (setq org-confirm-babel-evaluate nil
117                    default-directory temporary-file-directory)
118              (org-ctrl-c-ctrl-c))
119            """))
120        }
121        let emacs = try EmacsOracle.run(emacsCases)
122        for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
123            #expect(mine.text == theirs.text && (mine.failure != nil) == !theirs.error.isEmpty,
124                    "case \(i):\nours (\(mine.failure ?? "")):\n\(mine.text.dropFirst(Self.helpers.count))\nemacs (\(theirs.error)):\n\(theirs.text.dropFirst(Self.helpers.count))")
125            #expect(mine.text != Self.helpers + Self.cases[i], "case \(i) changed nothing")
126        }
127    }
128
129    /// Emacs Lisp in the interpreter, as on iOS and in the Mac App Store version.
130    @Test func runsInTheInterpreter() throws {
131        let folder = FileManager.default.temporaryDirectory
132        for (last, result) in [
133            ("#+begin_src emacs-lisp :post double(n=*this*)\n(+ 1 2)\n#+end_src\n", "#+RESULTS:\n: 6\n"),
134            ("#+begin_src emacs-lisp :post bump(rows=*this*)\n'((1 2) (3 4))\n#+end_src\n", "#+RESULTS:\n| 2 | 3 |\n| 4 | 5 |\n"),
135            ("#+begin_src emacs-lisp :noweb yes\n(+ 1 <<double(n=4)>>)\n#+end_src\n", "#+RESULTS:\n: 9\n"),
136        ] {
137            let ran = try TestBabelRunner.execute(Self.helpers + last, caret: Self.caret(last), directory: folder, native: true)
138            #expect(ran.failure == nil && ran.text.hasSuffix(result), "\(last)\n\(ran)")
139        }
140    }
141
142    static func plan(_ text: String, at marker: String = "#+begin_src") -> Result<BabelJob, Babel.Failure> {
143        let caret = (text as NSString).range(of: marker, options: .backwards).location + 2
144        return Babel.plan(EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret]))
145    }
146
147    @Test func refusesBeforeAnythingRuns() {
148        for (text, message) in [
149            ("#+NAME: a\n#+begin_src sh :post a()\necho\n#+end_src\n", "a refers to itself through :post"),
150            ("#+NAME: b\n#+begin_src sh :post a()\necho\n#+end_src\n#+NAME: a\n#+begin_src sh :post b()\necho\n#+end_src\n", "b refers to itself through :post"),
151            ("#+NAME: a\n#+begin_src sh :noweb yes\necho <<a()>>\n#+end_src\n", "a refers to itself through a noweb reference"),
152            ("#+NAME: b\n#+begin_src sh :var x=a\necho\n#+end_src\n#+NAME: a\n#+begin_src sh :noweb yes\necho <<b()>>\n#+end_src\n", "b refers to itself through a noweb reference"),
153            ("#+NAME: off\n#+begin_src sh :eval never\necho\n#+end_src\n#+begin_src sh :post off(x=*this*)\necho\n#+end_src\n",
154             "Evaluation of this sh code block (off) is disabled."),
155            ("#+NAME: off\n#+begin_src sh :eval never\necho\n#+end_src\n#+begin_src sh :noweb yes\necho <<off()>>\n#+end_src\n",
156             "Evaluation of this sh code block (off) is disabled."),
157            ("#+NAME: off\n#+begin_src sh :eval never\necho\n#+end_src\n#+NAME: gen\n#+begin_src sh\necho\n#+end_src\n#+begin_src sh :var v=gen :post off(x=*this*)\necho\n#+end_src\n",
158             "Evaluation of this sh code block (off) is disabled."),
159            ("#+begin_src sh :post missing(x=*this*)\necho\n#+end_src\n", "References like missing(x=*this*) aren't supported yet."),
160            ("#+begin_src sh :noweb yes\necho <<missing()>>\n#+end_src\n", "References like missing() aren't supported yet."),
161            ("#+NAME: other\n#+begin_src cobol\nDISPLAY\n#+end_src\n#+begin_src sh :post other()\necho\n#+end_src\n", "No way to run cobol blocks yet."),
162        ] {
163            guard case .failure(.message(let got)) = Self.plan(text) else {
164                Issue.record("planned: \(text)")
165                continue
166            }
167            #expect(got == message)
168        }
169    }
170
171    /// The trust prompt covers the block and every block its `:post` and noweb references run.
172    @Test func asksOnceForEveryBlockReached() throws {
173        let post = "#+NAME: p\n#+begin_src sh :var x=\"\" :noweb yes\necho <<q()>>\n#+end_src\n#+NAME: q\n#+begin_src sh\necho q\n#+end_src\n"
174            + "#+NAME: inc\n#+begin_src sh :noweb yes\necho <<r()>>\n#+end_src\n#+NAME: r\n#+begin_src sh :eval query\necho r\n#+end_src\n"
175        for main in ["#+begin_src sh :post p(x=*this*)\necho main\n#+end_src\n", "#+begin_src sh :noweb yes\necho <<p()>>\n#+end_src\n"] {
176            guard case .success(let job) = Self.plan(post + main), let need = job.needs.first else {
177                Issue.record("not planned: \(main)")
178                continue
179            }
180            #expect(job.approved.count == 3 && job.approved.contains(need.job.blockText) && job.referenced == ["sh", "sh"])
181            #expect(job.blockText.contains("echo main") || job.blockText.contains("echo <<p()>>"))
182            #expect(job.blockText.contains("echo <<q()>>") && job.blockText.contains("echo q") && !job.alwaysAsk)
183        }
184        // Through a reference that brings a body in, and `:eval query` on the block it runs.
185        guard case .success(let job) = Self.plan(post + "#+begin_src sh :noweb yes\n<<inc>>\n#+end_src\n") else {
186            Issue.record("not planned")
187            return
188        }
189        #expect(job.alwaysAsk && job.approved.count == 2 && job.blockText.contains("echo r"))
190    }
191
192    /// The block runs before its `:post` reference, which gets its result; a block that isn't
193    /// among those agreed to is not handed back as the next to run.
194    @Test func runsTheBlockThenItsPost() throws {
195        let text = Self.helpers + "#+begin_src sh :post double(n=*this*)\necho 21\n#+end_src\n"
196        let tree = OrgParser.parse(text)
197        guard case .success(let first) = Self.plan(text), let main = first.needs.first else {
198            Issue.record("not planned")
199            return
200        }
201        #expect(first.known == nil && main.job.input.contains("echo 21"))
202        guard case .success(let second) = Babel.resume(first, need: main, output: BabelOutput(stdout: "21\n"), text: text, tree: tree),
203              let post = second.needs.first else {
204            Issue.record("not resumed")
205            return
206        }
207        #expect(post.job.lispForm?.contains("(n '21)") == true && first.approved.contains(post.job.blockText))
208        let output = BabelOutput(stdout: #"{"s":"42","S":"42","string":false,"rows":null}"#)
209        guard case .success(let last) = Babel.resume(second, need: post, output: output, text: text, tree: tree) else {
210            Issue.record("not resumed")
211            return
212        }
213        #expect(last.needs.isEmpty && last.known == BabelOutput(stdout: "42") && first.approved.contains(last.blockText))
214    }
215
216    @Test func tanglingRefusesAReferenceThatRuns() throws {
217        let text = Self.helpers + "#+begin_src sh :noweb yes :tangle out.sh\necho <<double(n=4)>>\n#+end_src\n"
218        let model = DocumentModel(tree: OrgParser.parse(text))
219        let block = model.srcBlocks.last!
220        #expect(throws: Babel.Failure.message("The noweb reference <<double(n=4)>> would run a block while tangling, which isn't supported yet; nothing was tangled.")) {
221            try Babel.expandNoweb(block, params: try Babel.Params(block: block, model: model, text: text as NSString), model: model, text: text as NSString, tangling: true)
222        }
223    }
224}