Tests/OrgCoreTests/CaptureTests.swift

87e24faa398b297d22cbc8cb585e8bb0a666c4ec
orgstar/Tests/OrgCoreTests/CaptureTests.swift history · blame · raw

127 lines · 6839 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct CaptureTests {
  6    struct Case {
  7        var file: String
  8        var template: CaptureTemplate
  9        var typed: String
 10    }
 11
 12    static func lisp(_ s: String) -> String {
 13        "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
 14    }
 15
 16    /// Captures each case in `emacs --batch`: the target file afterwards.
 17    static func emacs(_ cases: [Case], seconds: Int) throws -> [String] {
 18        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-capture-\(UUID().uuidString)")
 19        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 20        defer { try? FileManager.default.removeItem(at: folder) }
 21        var forms: [String] = []
 22        for (i, c) in cases.enumerated() {
 23            let path = folder.appendingPathComponent("target\(i).org").path
 24            try c.file.write(toFile: path, atomically: true, encoding: .utf8)
 25            let target: String
 26            switch c.template.target {
 27            case .file: target = "(file \(lisp(path)))"
 28            case .headline(_, let h): target = "(file+headline \(lisp(path)) \(lisp(h)))"
 29            case .outline(_, let p): target = "(file+olp \(lisp(path)) \(p.map(lisp).joined(separator: " ")))"
 30            }
 31            forms.append("""
 32            (let ((org-capture-templates '(("x" "case" \(c.template.kind.rawValue) \(target) \(lisp(c.template.template))\(c.template.prepend ? " :prepend t" : "")))))
 33              (org-capture nil "x")
 34              (insert \(lisp(c.typed)))
 35              (org-capture-finalize)
 36              (with-current-buffer (find-buffer-visiting \(lisp(path)))
 37                (push (buffer-substring-no-properties (point-min) (point-max)) results)))
 38            """)
 39        }
 40        let output = folder.appendingPathComponent("out.json")
 41        let script = folder.appendingPathComponent("capture.el")
 42        try """
 43        ;;; -*- lexical-binding: t -*-
 44        (require 'org)
 45        (require 'org-capture)
 46        (require 'json)
 47        (setq org-adapt-indentation nil)
 48        (defvar results nil)
 49        \(frozenClock(seconds, "(progn " + forms.joined(separator: "\n") + ")"))
 50        (with-temp-file \(lisp(output.path)) (insert (json-encode (vconcat (nreverse results)))))
 51        """.write(to: script, atomically: true, encoding: .utf8)
 52        _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
 53        return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
 54    }
 55
 56    static func ours(_ c: Case, now: Date) -> String {
 57        var utc = Calendar(identifier: .gregorian)
 58        utc.timeZone = TimeZone(identifier: "UTC")!
 59        guard case .success(let filled) = Capture.fill(c.template.template, context: CaptureContext(now: now, calendar: utc)) else { return "fill failed" }
 60        var text = filled.text
 61        let index = String.Index(utf16Offset: filled.cursor, in: text)
 62        text.insert(contentsOf: c.typed, at: index)
 63        switch Capture.place(text, template: c.template, in: c.file) {
 64        case .success(let result): return result
 65        case .failure(.message(let message)): return "failed: \(message)"
 66        }
 67    }
 68
 69    static let files = [
 70        "#+TITLE: Todo\n* Inbox\n** TODO Old\n* Later\nText\n",
 71        "* Inbox\n\n** TODO Old\n\n* Later\n",
 72        "* Inbox\n",
 73        "* Inbox",
 74        "",
 75        "Preamble\n* Other\n",
 76        "* Inbox\nSome notes.\n- one\n- two\n\n** Child\n",
 77        "* Projects\n** Work\n*** Active\n** Home\n",
 78        "* Inbox\n:PROPERTIES:\n:ID: x\n:END:\nBody\n",
 79    ]
 80
 81    static let templates: [CaptureTemplate] = [
 82        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
 83        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
 84        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "* TODO %?", prepend: true),
 85        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Missing"), template: "* %?"),
 86        CaptureTemplate(key: "x", name: "", target: .file(""), template: "* Note %U\n%?"),
 87        CaptureTemplate(key: "x", name: "", target: .file(""), template: "** Deep %?", prepend: true),
 88        CaptureTemplate(key: "x", name: "", target: .headline(file: "", headline: "Inbox"), template: "Plain %? text", ),
 89        CaptureTemplate(key: "x", name: "", kind: .plain, target: .headline(file: "", headline: "Inbox"), template: "Plain line %?"),
 90        CaptureTemplate(key: "x", name: "", kind: .plain, target: .file(""), template: "%<%Y-%m-%d>: %?"),
 91        CaptureTemplate(key: "x", name: "", kind: .item, target: .headline(file: "", headline: "Inbox"), template: "%?"),
 92        CaptureTemplate(key: "x", name: "", kind: .checkitem, target: .headline(file: "", headline: "Inbox"), template: "[ ] %?"),
 93        CaptureTemplate(key: "x", name: "", target: .outline(file: "", path: ["Projects", "Work"]), template: "* TODO %?\n  Added %T"),
 94    ]
 95
 96    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 97    func matchesEmacs() throws {
 98        let seconds = 1_789_000_000
 99        var cases: [Case] = []
100        for template in Self.templates {
101            for file in Self.files {
102                if case .outline = template.target, !file.contains("Projects") { continue }
103                if template.kind == .item || template.kind == .checkitem, !file.contains("Inbox") { continue }
104                cases.append(Case(file: file, template: template, typed: "Buy milk"))
105            }
106        }
107        let emacs = try Self.emacs(cases, seconds: seconds)
108        let now = Date(timeIntervalSince1970: Double(seconds))
109        for (c, expected) in zip(cases, emacs) {
110            let mine = Self.ours(c, now: now)
111            #expect(mine == expected, "\(c.template.template.debugDescription) \(c.template.kind) prepend \(c.template.prepend) into \(c.file.debugDescription)\nours:\n\(mine.debugDescription)\nemacs:\n\(expected.debugDescription)")
112        }
113    }
114
115    @Test func fillsPrompts() {
116        let template = "* %^{Title|untitled} for %^{Who}\n%\\1 again"
117        #expect(Capture.questions(template) == [
118            Capture.Question(prompt: "Title", defaultValue: "untitled", choices: []),
119            Capture.Question(prompt: "Who", defaultValue: "", choices: []),
120        ])
121        guard case .success(let filled) = Capture.fill(template, context: CaptureContext(), answers: ["", "me"]) else {
122            Issue.record("fill failed")
123            return
124        }
125        #expect(filled.text == "* untitled for me\nuntitled again\n")
126    }
127}