Tests/OrgCoreTests/TimerTests.swift

177 lines · 10554 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// org-timer against Emacs with the clock frozen: the text the commands insert, and the
  6/// messages and timers the others leave.
  7struct TimerOracleTests {
  8    static let now = 1_789_000_000
  9    static func date(_ seconds: Int) -> Date { Date(timeIntervalSince1970: TimeInterval(seconds)) }
 10
 11    /// The timer as Lisp sets it, and as ours.
 12    static let timers: [(lisp: String, timer: OrgTimer?)] = [
 13        ("", nil),
 14        ("(setq org-timer-start-time (seconds-to-time \(now - 75)))", OrgTimer(start: date(now - 75))),
 15        ("(setq org-timer-start-time (seconds-to-time \(now - 100)) org-timer-pause-time (seconds-to-time \(now - 40)))",
 16         OrgTimer(start: date(now - 100), paused: date(now - 40))),
 17        ("(setq org-timer-start-time (seconds-to-time \(now + 3725)) org-timer-countdown-timer (run-with-timer 3725 nil #'ignore) org-timer-countdown-timer-title \"T\")",
 18         OrgTimer(start: date(now + 3725), isCountdown: true, title: "T")),
 19    ]
 20
 21    static func context(_ text: String, caret: Int, timer: OrgTimer?, selection: Range<Int>? = nil, answers: [String: String] = [:]) -> EditContext {
 22        var options = EditingOptions.org
 23        options.timer = timer
 24        var utc = Calendar(identifier: .gregorian)
 25        utc.timeZone = TimeZone(identifier: "UTC")!
 26        return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection ?? caret..<caret],
 27                           now: date(now), calendar: utc, answers: answers, options: options)
 28    }
 29
 30    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 31    func insertingMatchesEmacs() throws {
 32        let texts = ["* H\n\n", "* H\nfoo\n", "- 0:00:05 :: a\n- 0:01:00 :: b\n", "- a\n- b\n", "  text\n", "1. 0:00:03 :: x\n", "- [ ] 0:00:01 :: c\n"]
 33        let commands: [(command: any OrgCommand, form: String)] = [
 34            (InsertTimer(), "(org-timer)"),
 35            (InsertTimerItem(), "(org-timer-item)"),
 36            (InsertItem(), "(or (org-insert-item) (error \"Not in an item\"))"),
 37        ]
 38        var cases: [EmacsOracle.Case] = []
 39        var ours: [(label: String, text: String, caret: Int, failed: Bool)] = []
 40        for text in texts {
 41            for offset in EmacsOracle.positions(text) {
 42                for (lisp, timer) in Self.timers {
 43                    for (command, form) in commands {
 44                        cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(offset, in: text),
 45                                                      form: frozenClock(Self.now, "(progn (require 'org-timer) (setq org-timer-start-time nil org-timer-pause-time nil org-timer-countdown-timer nil) \(lisp) \(form))")))
 46                        let label = "\(command.id) at \(offset) with \(lisp) in \(text.debugDescription)"
 47                        switch command.run(in: Self.context(text, caret: offset, timer: timer)) {
 48                        case .commit(let result):
 49                            let new = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
 50                            ours.append((label, new, result.selection?.first?.lowerBound ?? offset, false))
 51                        default:
 52                            ours.append((label, text, offset, true))
 53                        }
 54                    }
 55                }
 56            }
 57        }
 58        let results = try EmacsOracle.run(cases)
 59        var mismatches = 0
 60        for (mine, theirs) in zip(ours, results) {
 61            let theirCaret = theirs.text.unicodeScalars.prefix(theirs.point - 1).reduce(0) { $0 + $1.utf16.count }
 62            let same = mine.failed ? !theirs.error.isEmpty : theirs.error.isEmpty && mine.text == theirs.text && mine.caret == theirCaret
 63            if !same {
 64                mismatches += 1
 65                if mismatches <= 15 { Issue.record("\(mine.label)\n ours:  \(mine.failed ? "failed" : mine.text.debugDescription) @\(mine.caret)\n emacs: \(theirs.error.isEmpty ? theirs.text.debugDescription : theirs.error) @\(theirCaret)") }
 66            }
 67        }
 68        #expect(mismatches == 0, "\(mismatches) of \(cases.count) cases differ")
 69    }
 70
 71    /// What a command leaves: its message, and the timer as `start paused countdown title`.
 72    static let report = """
 73        (format "%s|%s" msg
 74          (if org-timer-start-time
 75              (format "%s %s %s %s" (format-time-string "%s" org-timer-start-time)
 76                      (if org-timer-pause-time (format-time-string "%s" org-timer-pause-time) "nil")
 77                      (if org-timer-countdown-timer "t" "nil")
 78                      (if org-timer-countdown-timer org-timer-countdown-timer-title "nil"))
 79            "none"))
 80        """
 81
 82    static func ourReport(_ step: CommandStep, before: OrgTimer?) -> String {
 83        var message = ""
 84        var timer = before
 85        switch step {
 86        case .commit(let result):
 87            for effect in result.effects {
 88                if case .message(let m) = effect { message = m }
 89                if case .timer(let t) = effect { timer = t }
 90            }
 91        case .failed(let m): message = m
 92        default: message = "prompt"
 93        }
 94        let state = timer.map { t in
 95            "\(Int(t.start.timeIntervalSince1970)) \(t.paused.map { String(Int($0.timeIntervalSince1970)) } ?? "nil") \(t.isCountdown ? "t" : "nil") \(t.isCountdown ? (t.title ?? "nil") : "nil")"
 96        } ?? "none"
 97        return message + "|" + state
 98    }
 99
100    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
101    func timerStateMatchesEmacs() throws {
102        let text = "* TODO Write :work:\n:PROPERTIES:\n:Effort:   0:25\n:END:\n* Plain\n- 0:02:10 :: x\n"
103        let plain = (text as NSString).range(of: "* Plain").location
104        let stamp = (text as NSString).range(of: "0:02:10").location + 3
105        // Command, Lisp, caret, answers, and the stubbed minibuffer answer.
106        let commands: [(command: any OrgCommand, form: String, caret: Int, answers: [String: String])] = [
107            (TimerStart(), "(org-timer-start)", 0, [:]),
108            (TimerStart(offset: true), "(org-timer-start '(4))", 0, ["offset": "1:30"]),
109            (TimerStart(offset: true), "(org-timer-start '(4))", stamp, ["offset": ""]),
110            (TimerPauseOrContinue(), "(org-timer-pause-or-continue)", 0, [:]),
111            (TimerStop(), "(org-timer-stop)", 0, [:]),
112            (TimerShowRemaining(), "(org-timer-show-remaining-time)", 0, [:]),
113            (TimerSetCountdown(), "(org-timer-set-timer)", 0, ["replace": "n"]),
114            (TimerSetCountdown(), "(org-timer-set-timer)", plain, ["minutes": "10", "replace": "y"]),
115            (TimerSetCountdown(), "(org-timer-set-timer)", plain, ["minutes": "1:02:03", "replace": "n"]),
116            (InsertTimer(), "(org-timer)", 0, [:]),
117        ]
118        var cases: [EmacsOracle.Case] = []
119        var ours: [String] = []
120        for (lisp, timer) in Self.timers {
121            for (command, form, caret, answers) in commands {
122                let minibuffer = answers["minutes"] ?? answers["offset"] ?? ""
123                let yes = answers["replace"] == "y" ? "t" : "nil"
124                let body = """
125                    (progn (require 'org-timer)
126                      (let ((msg ""))
127                        (cl-letf (((symbol-function 'message) (lambda (f &rest a) (setq msg (if f (apply #'format f a) ""))))
128                                  ((symbol-function 'read-string) (lambda (&rest _) \(minibuffer.debugDescription)))
129                                  ((symbol-function 'read-from-minibuffer) (lambda (&rest _) \(minibuffer.debugDescription)))
130                                  ((symbol-function 'y-or-n-p) (lambda (&rest _) \(yes)))
131                                  )
132                          (setq org-timer-start-time nil org-timer-pause-time nil org-timer-countdown-timer nil)
133                          \(lisp)
134                          (condition-case e \(form) (error (setq msg (error-message-string e))))
135                          (let ((r \(Self.report))) (erase-buffer) (insert r)))))
136                    """
137                cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: frozenClock(Self.now, body)))
138                ours.append(Self.ourReport(command.run(in: Self.context(text, caret: caret, timer: timer, answers: answers)), before: timer))
139            }
140        }
141        let results = try EmacsOracle.run(cases)
142        for (index, (mine, theirs)) in zip(ours, results).enumerated() {
143            #expect(mine == theirs.text, "case \(index) ours \(mine.debugDescription) emacs \(theirs.text.debugDescription) \(theirs.error)")
144        }
145    }
146
147    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
148    func changingTimesMatchesEmacs() throws {
149        let text = "- 0:01:10 :: a\n- 0:02:00 :: b\n- -0:00:05 x 10:00:00\n"
150        let region = 0..<(text as NSString).length
151        var cases: [EmacsOracle.Case] = []
152        var ours: [String] = []
153        for delta in ["", "0:01:00", "-30", "1:00:00:00", "0:00:00"] {
154            cases.append(EmacsOracle.Case(text: text, point: 1, form: """
155                (progn (require 'org-timer) (org-timer-change-times-in-region (point-min) (point-max) \(delta.debugDescription)))
156                """))
157            switch TimerChangeTimes().run(in: Self.context(text, caret: 0, timer: nil, selection: region, answers: ["delta": delta])) {
158            case .commit(let result): ours.append(result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) })
159            case .failed(let message): ours.append("error: " + message)
160            default: ours.append("prompt")
161            }
162        }
163        let results = try EmacsOracle.run(cases)
164        for (mine, theirs) in zip(ours, results) {
165            #expect(mine == (theirs.error.isEmpty ? theirs.text : "error: " + theirs.error), "ours \(mine.debugDescription) emacs \(theirs.text.debugDescription)")
166        }
167    }
168
169    @Test func conversions() {
170        #expect(OrgTimer.hms(3725) == "1:02:05")
171        #expect(OrgTimer.hms(-65) == "-0:01:05")
172        #expect(OrgTimer.seconds("-1:00:01") == -3601)
173        #expect(OrgTimer.fixIncomplete("5") == "0:00:05")
174        #expect(OrgTimer.fixIncomplete("2:30") == "0:02:30")
175        #expect(OrgTimer(start: Self.date(Self.now - 75)).modeLine(now: Self.date(Self.now)) == " <0:01:15>")
176    }
177}