Tests/OrgCoreTests/TimestampCommandTests.swift

9abba9cfc504b344b7d267978a97f1c925a1d5dd
orgstar/Tests/OrgCoreTests/TimestampCommandTests.swift history · blame · raw

138 lines · 8214 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct TimestampCommandTests {
  6    static let now = ReadDateTests.now
  7    static let calendar = ReadDateTests.utc
  8
  9    func run(_ command: any OrgCommand, _ text: String, caret: Int, answer: String? = nil) -> (text: String, caret: Int, failure: String?) {
 10        let context = EditContext(
 11            revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret],
 12            now: Self.now, calendar: Self.calendar, answers: answer.map { ["date": $0] } ?? [:]
 13        )
 14        switch command.run(in: context) {
 15        case .commit(let result):
 16            let new = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
 17            return (new, result.selection?.first?.lowerBound ?? caret, nil)
 18        case .failed(let message): return (text, caret, message)
 19        case .prompt(let prompt): return (text, caret, "prompt \(prompt.key)")
 20        case .external(let request): return (text, caret, "external \(request)")
 21        }
 22    }
 23
 24    @Test func examples() {
 25        #expect(run(InsertTimestamp(), "x\n", caret: 1, answer: "fri").text == "x<2026-09-11 Fri>\n")
 26        #expect(run(SetPlanning(deadline: false), "* a\n", caret: 0, answer: "+1").text == "* a\nSCHEDULED: <2026-09-11 Fri>\n")
 27        #expect(run(ShiftTimestampDay(later: true), "<2026-09-10 Thu>\n", caret: 5).text == "<2026-09-11 Fri>\n")
 28        #expect(run(ShiftTimestamp(up: true), "<2026-09-10 Thu 10:07>\n", caret: 20).text == "<2026-09-10 Thu 10:10>\n")
 29    }
 30
 31    static let texts = [
 32        "* a\n",
 33        "* a\nbody <2026-09-01 Tue> text\n",
 34        "* a\nSCHEDULED: <2026-09-01 Tue +1w>\n",
 35        "* a\nDEADLINE: <2026-09-20 Sun> SCHEDULED: <2026-09-01 Tue 10:00-11:30>\n",
 36        "* a\nCLOSED: [2026-09-02 Wed 09:00] SCHEDULED: <2026-09-01 Tue>\n",
 37        "* a\n[2026-12-31 Thu 23:58] <2026-01-31 Sat .+2m -3d>\n",
 38        "text <2026-02-28 Sat 07:03>\n",
 39    ]
 40    static let answers = ["", "+1", "fri 9:00", "2027-01-15", "10:00-11:00", "++2d"]
 41
 42    static let commands: [(any OrgCommand, String)] = [
 43        (InsertTimestamp(), "(org-timestamp nil)"),
 44        (InsertTimestamp(inactive: true), "(org-timestamp nil t)"),
 45        (SetPlanning(deadline: false), "(org-schedule nil)"),
 46        (SetPlanning(deadline: true), "(org-deadline nil)"),
 47        (RemovePlanning(deadline: false), "(org-schedule '(4))"),
 48        (ShiftTimestamp(up: true), "(org-timestamp-up)"),
 49        (ShiftTimestamp(up: false), "(org-timestamp-down)"),
 50        (ShiftTimestampDay(later: true), "(org-timestamp-up-day)"),
 51        (ShiftTimestampDay(later: false), "(org-timestamp-down-day)"),
 52    ]
 53
 54    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 55    func timestampCommandsMatchEmacs() throws {
 56        try #require(EmacsOracle.isAvailable)
 57        var cases: [EmacsOracle.Case] = []
 58        var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
 59        for text in Self.texts {
 60            let tree = OrgParser.parse(text)
 61            for caret in EmacsOracle.positions(text) {
 62                for (command, form) in Self.commands {
 63                    let prompts = command is InsertTimestamp || command is SetPlanning
 64                    if command is RemovePlanning || command is SetPlanning, entryHeading(at: caret, in: tree) == nil { continue }
 65                    if command is ShiftTimestamp || command is ShiftTimestampDay, EmacsBuffer(text, point: caret).atTimestamp() == nil { continue }
 66                    for answer in prompts ? Self.answers : [""] {
 67                        let escaped = answer.replacingOccurrences(of: "\"", with: "\\\"")
 68                        let wrapped = frozenClock(1_789_000_000, """
 69                            (cl-letf (((symbol-function 'read-string) (lambda (&rest _) "\(escaped)")))
 70                              (let ((org-read-date-popup-calendar nil)) \(form)))
 71                            """)
 72                        cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: wrapped))
 73                        let result = run(command, text, caret: caret, answer: prompts ? answer : nil)
 74                        ours.append(("\(command.id) \(answer.debugDescription) at \(caret) in \(text.debugDescription)", result.text, result.caret, result.failure != nil))
 75                    }
 76                }
 77            }
 78        }
 79        var mismatches = 0
 80        for (mine, emacs) in zip(ours, try EmacsOracle.run(cases)) {
 81            let failed = !emacs.error.isEmpty
 82            let caret = EmacsOracle.offset(emacs.point, in: emacs.text)
 83            guard mine.failed != failed || (!failed && (mine.text != emacs.text || mine.caret != caret)) else { continue }
 84            mismatches += 1
 85            if mismatches <= 12 {
 86                Issue.record("\(mine.label)\n  ours:  \(mine.failed ? "failed" : "\(mine.text.debugDescription) @\(mine.caret)")\n  emacs: \(failed ? emacs.error : "\(emacs.text.debugDescription) @\(caret)")")
 87            }
 88        }
 89        #expect(mismatches == 0, "\(mismatches) of \(ours.count) differ")
 90    }
 91
 92    static let repeating = [
 93        "* TODO a\nSCHEDULED: <2026-09-01 Tue +1w>\n",
 94        "* TODO a\nDEADLINE: <2026-09-01 Tue .+1d>\n",
 95        "* TODO a\nSCHEDULED: <2026-08-01 Sat ++1m>\nbody\n",
 96        "* TODO a :t:\n<2026-09-08 Tue 10:00 +2d>\n",
 97        "* TODO a\nDEADLINE: <2026-09-05 Sat +1w> SCHEDULED: <2026-09-01 Tue>\n",
 98        "* TODO a\nSCHEDULED: <2026-09-01 Tue +1w>\n:PROPERTIES:\n:LAST_REPEAT: [2026-09-01 Tue 08:00]\n:END:\n- State \"DONE\"       from \"TODO\"       [2026-09-01 Tue 08:00]\nnotes\n",
 99        "#+TODO: TODO STRT | DONE\n* STRT a\nSCHEDULED: <2026-09-01 Tue +1d>\n",
100        "* P [0/1]\n** TODO a\nSCHEDULED: <2026-09-01 Tue +1w>\n* Q\n",
101        "* TODO no repeat\nSCHEDULED: <2026-09-01 Tue>\n",
102        "* TODO hourly\nSCHEDULED: <2026-09-10 Thu 00:00 +1h>\n",
103    ]
104
105    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
106    func repeatsMatchEmacs() throws {
107        try #require(EmacsOracle.isAvailable)
108        var cases: [EmacsOracle.Case] = []
109        var ours: [(label: String, text: String, caret: Int)] = []
110        for text in Self.repeating {
111            let ns = text as NSString
112            let heading = ns.range(of: "\n\\*|^\\*", options: .regularExpression)
113            let start = heading.location == 0 ? 0 : heading.location + 1
114            let lineEnd = ns.range(of: "\n", range: NSRange(location: start, length: ns.length - start)).location
115            for caret in [start, start + 2, lineEnd, min(lineEnd + 3, ns.length)] {
116                cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: frozenClock(1_789_000_000, "(progn (org-todo) (when org-log-setup (org-add-log-note)))")))
117                let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Self.now, calendar: Self.calendar)
118                guard case .commit(let result) = TodoCycle().run(in: context) else {
119                    ours.append(("failed at \(caret)", "", -1))
120                    continue
121                }
122                let new = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
123                ours.append(("at \(caret) in \(text.debugDescription)", new, result.selection?.first?.lowerBound ?? caret))
124            }
125        }
126        var mismatches = 0
127        for (mine, emacs) in zip(ours, try EmacsOracle.run(cases)) {
128            let caret = EmacsOracle.offset(emacs.point, in: emacs.text)
129            guard !emacs.error.isEmpty || mine.text != emacs.text || mine.caret != caret else { continue }
130            mismatches += 1
131            if mismatches <= 10 {
132                let (a, b) = excerpts(mine.text, emacs.text)
133                Issue.record("\(mine.label)\n  ours:  \(a.debugDescription) @\(mine.caret)\n  emacs: \(emacs.error.isEmpty ? "\(b.debugDescription) @\(caret)" : emacs.error)")
134            }
135        }
136        #expect(mismatches == 0, "\(mismatches) of \(ours.count) differ")
137    }
138}