Tests/OrgCoreTests/ClockTests.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Tests/OrgCoreTests/ClockTests.swift history · blame · raw

204 lines · 11466 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct ClockTests {
  6    static let texts = [
  7        "* TODO Task\n",
  8        "* TODO Task\nBody text.\n",
  9        "* Task\nSCHEDULED: <2026-10-05 Mon>\n:PROPERTIES:\n:ID: x\n:END:\nBody\n",
 10        "* Task\n:LOGBOOK:\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] =>  1:00\n:END:\nNotes\n",
 11        "* Task\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] =>  1:00\nNotes\n",
 12        "* Task\n** Child\nChild body\n* Next\n",
 13        "* Task",
 14        "Preamble\n* Task\n- item\n",
 15        "* Task\n:LOGBOOK:\n- State \"DONE\" from \"TODO\" [2026-10-01 Thu 10:00]\n:END:\n",
 16    ]
 17
 18    static var utc: Calendar {
 19        var c = Calendar(identifier: .gregorian)
 20        c.timeZone = TimeZone(identifier: "UTC")!
 21        return c
 22    }
 23
 24    func run(_ command: any OrgCommand, _ text: String, caret: Int, at seconds: Int, options: EditingOptions = .org) -> (text: String, caret: Int, failure: String?) {
 25        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Date(timeIntervalSince1970: Double(seconds)), calendar: Self.utc, options: options)
 26        switch command.run(in: context) {
 27        case .commit(let result):
 28            var new = text
 29            for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
 30            return (new, result.selection?.first?.lowerBound ?? caret, nil)
 31        case .failed(let message): return (text, caret, message)
 32        default: return (text, caret, "other")
 33        }
 34    }
 35
 36    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 37    func matchesEmacs() throws {
 38        try compare(Self.texts)
 39    }
 40
 41    /// `org-clock-into-drawer` values, `org-log-into-drawer`, and the CLOCK_INTO_DRAWER and
 42    /// LOG_INTO_DRAWER properties.
 43    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 44    func intoDrawerMatchesEmacs() throws {
 45        let texts = Self.texts + [
 46            "* Task\nCLOCK: [2026-10-03 Sat 09:00]--[2026-10-03 Sat 10:00] =>  1:00\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] =>  1:00\n",
 47            "* Task\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: nil\n:END:\nBody\n",
 48            "* Parent\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: TIMES\n:END:\n** Task\nBody\n",
 49            "* Task\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: 2\n:END:\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] =>  1:00\n",
 50            "* Task\n:PROPERTIES:\n:CLOCK_INTO_DRAWER: t\n:LOG_INTO_DRAWER: NOTES\n:END:\n",
 51        ]
 52        for (lisp, value, log) in [("nil", "nil", nil), ("2", "2", nil), ("3", "3", nil), ("\"CLOCKS\"", "CLOCKS", nil), ("t", nil, "NOTES"), ("2", "2", "NOTES")] as [(String, String?, String?)] {
 53            var options = EditingOptions.org
 54            options.clockIntoDrawer = value
 55            options.logIntoDrawer = log
 56            try compare(texts, lisp: lisp, log: log.map { "\"\($0)\"" } ?? "nil", options: options)
 57        }
 58    }
 59
 60    /// `org-clock-rounding-minutes`, `org-clock-out-remove-zero-time-clocks` and
 61    /// `org-clock-in-switch-to-state`.
 62    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 63    func optionsMatchEmacs() throws {
 64        let texts = Self.texts + ["#+TODO: TODO NEXT | DONE\n* TODO Task\n", "#+TODO: TODO NEXT | DONE\n* NEXT Task\nBody\n"]
 65        var rounding = EditingOptions.org
 66        rounding.clockRoundingMinutes = 5
 67        try compare(texts, extra: "org-clock-rounding-minutes 5", options: rounding)
 68        try compare(texts, extra: "org-clock-rounding-minutes 15", options: { var o = EditingOptions.org; o.clockRoundingMinutes = 15; return o }(), length: 7 * 60)
 69        var zero = EditingOptions.org
 70        zero.clockOutRemoveZeroTimeClocks = true
 71        try compare(texts, extra: "org-clock-out-remove-zero-time-clocks t", options: zero, length: 20)
 72        var state = EditingOptions.org
 73        state.clockInSwitchToState = "NEXT"
 74        try compare(texts, extra: "org-clock-in-switch-to-state \"NEXT\"", options: state)
 75    }
 76
 77    func compare(_ texts: [String], lisp: String = "t", log: String = "nil", extra: String = "", options: EditingOptions = .org,
 78                 length: Int = 3 * 3600 + 17 * 60 + 42) throws {
 79        let t1 = 1_789_000_000   // Thu 2026-09-10 00:26
 80        let t2 = t1 + length
 81        var cases: [EmacsOracle.Case] = []
 82        var ours: [(String, String)] = []
 83        for text in texts {
 84            let caret = (text as NSString).range(of: "Task").location
 85            for mode in ["out", "cancel"] {
 86                // Clock in at t1, then out (or cancel) at t2.
 87                let first = run(ClockIn(), text, caret: caret, at: t1, options: options)
 88                // Clocking in failed: the text stays, as Emacs's does when it signals.
 89                if let start = ClockIn.runningStart(in: first.text, near: caret) {
 90                    let second = run(ClockOut(start: start, cancel: mode == "cancel"), first.text, caret: first.caret, at: t2, options: options)
 91                    ours.append((second.text, first.text))
 92                } else {
 93                    ours.append((first.text, first.failure ?? ""))
 94                }
 95                let out = mode == "cancel" ? "(org-clock-cancel)" : "(org-clock-out)"
 96                cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
 97                (progn
 98                  (require 'org-clock)
 99                  (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer \(lisp) org-log-into-drawer \(log) \(extra))
100                  \(frozenClock(t1, "(org-clock-in)"))
101                  (setq orgstar-after-in (buffer-substring-no-properties (point-min) (point-max)))
102                  \(frozenClock(t2, out)))
103                """))
104            }
105        }
106        let emacs = try EmacsOracle.run(cases)
107        for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
108            #expect(mine.0 == theirs.text, "case \(i) \(lisp) \(cases[i].form.contains("cancel") ? "cancel" : "out")\n\(cases[i].text.debugDescription)\nafter in (ours): \(mine.1.debugDescription)\nours:  \(mine.0.debugDescription)\nemacs: \(theirs.text.debugDescription) \(theirs.error)")
109        }
110    }
111}
112
113
114struct ClockReportTests {
115    static let config = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/doom/config.el")
116
117    static let sample = """
118    * TODO [#A] Audit work :work:
119    :LOGBOOK:
120    CLOCK: [2026-02-20 Fri 10:00]--[2026-02-20 Fri 16:00] =>  6:00
121    CLOCK: [2026-02-17 Tue 16:22]--[2026-02-17 Tue 16:45] =>  0:23
122    CLOCK: [2026-02-17 Tue 08:15]--[2026-02-17 Tue 08:50] =>  0:35
123    :END:
124    * Meetings
125    :LOGBOOK:
126    CLOCK: [2026-02-24 Tue 09:30]--[2026-02-24 Tue 10:00] =>  0:30
127    CLOCK: [2026-03-02 Mon 09:00]
128    CLOCK: [2026-02-17 Tue 09:28]--[2026-02-17 Tue 09:55] =>  0:27
129    :END:
130    """
131
132    @Test func totalsPerHeading() {
133        let entries = ClockReport.entries(Self.sample)
134        let all = ClockReport.byHeading(entries)
135        #expect(all.map(\.heading) == ["Audit work", "Meetings"] && all.map(\.minutes) == [418, 57])
136        #expect(all[1].start == (Self.sample as NSString).range(of: "* Meetings").location)
137        #expect(ClockReport.byHeading(entries, from: "2026-02-18", to: "2026-02-24").map(\.minutes) == [360, 30])
138    }
139
140    /// Your own `tr/generate-report`, loaded from config.el in batch Emacs.
141    static func emacsReport(_ text: String, start: String?, end: String?) throws -> String {
142        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-tr-\(UUID().uuidString)")
143        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
144        defer { try? FileManager.default.removeItem(at: folder) }
145        let input = folder.appendingPathComponent("time.org")
146        let output = folder.appendingPathComponent("report.org")
147        try text.write(to: input, atomically: true, encoding: .utf8)
148        func lisp(_ s: String?) -> String { s.map { "\"\($0)\"" } ?? "nil" }
149        let script = folder.appendingPathComponent("tr.el")
150        try """
151        (require 'org)
152        (require 'cl-lib)
153        (require 'subr-x)
154        (with-temp-buffer
155          (insert-file-contents "\(config.path)")
156          (goto-char (point-min))
157          (condition-case nil
158              (while t
159                (let ((form (read (current-buffer))))
160                  (when (and (eq (car-safe form) 'defun) (string-prefix-p "tr/" (symbol-name (cadr form))))
161                    (eval form t))))
162            (end-of-file nil)))
163        (tr/generate-report "\(input.path)" "\(output.path)" \(lisp(start)) \(lisp(end)))
164        """.write(to: script, atomically: true, encoding: .utf8)
165        _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
166        return try String(contentsOf: output, encoding: .utf8)
167    }
168
169    @Test(.enabled(if: FileManager.default.fileExists(atPath: ClockReportTests.config.path) && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
170    func matchesYourReport() throws {
171        var texts = [Self.sample]
172        let work = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("git/cmc/work-notes/time.org")
173        if let real = try? String(contentsOf: work, encoding: .utf8) { texts.append(real) }
174        for text in texts {
175            for (start, end) in [(nil, nil), ("2026-02-18", nil), (nil, "2026-02-20"), ("2026-02-17", "2026-02-17")] as [(String?, String?)] {
176                let ours = ClockReport.timeReport(ClockReport.entries(text), start: start, end: end)
177                let theirs = try Self.emacsReport(text, start: start, end: end)
178                #expect(ours == theirs, "\(start ?? "-")..\(end ?? "-")\nours:\n\(ours)\ntheirs:\n\(theirs)")
179            }
180        }
181    }
182}
183
184struct ClockDrawerStartupTests {
185    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
186    func startupLogdrawerMatchesEmacs() throws {
187        let text = "#+STARTUP: nologdrawer\n* Task\nBody\n"
188        let caret = (text as NSString).range(of: "Task").location
189        let t1 = 1_789_000_000
190        var options = EditingOptions.org
191        options.logIntoDrawer = "NOTES"
192        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Date(timeIntervalSince1970: Double(t1)), calendar: ClockTests.utc, options: options)
193        guard case .commit(let result) = ClockIn().run(in: context) else { Issue.record("no commit"); return }
194        let ours = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
195        let emacs = try EmacsOracle.run([EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
196            (progn (require 'org-clock)
197              (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer t)
198              (setq-default org-log-into-drawer "NOTES")
199              (org-mode)
200              \(frozenClock(t1, "(org-clock-in)")))
201            """)])
202        #expect(ours == emacs[0].text, "ours: \(ours.debugDescription)\nemacs: \(emacs[0].text.debugDescription) \(emacs[0].error)")
203    }
204}