Tests/OrgCoreTests/TimestampCommandTests.swift

359666677e3403c6c38599c91ff884b7aa3787cd
orgstar/Tests/OrgCoreTests/TimestampCommandTests.swift history · blame · raw

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