Tests/OrgCoreTests/TimestampCommandTests.swift

f18103132ab04144c6fafa0d2e50f7c201126344
orgstar/Tests/OrgCoreTests/TimestampCommandTests.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form