Tests/OrgCoreTests/ClockTests.swift

33ad34b336e89f4757cb2613ed86e9fe0b674e52
orgstar/Tests/OrgCoreTests/ClockTests.swift

186 lines · 10334 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    func compare(_ texts: [String], lisp: String = "t", log: String = "nil", options: EditingOptions = .org) throws {
 61        let t1 = 1_789_000_000   // Thu 2026-09-10 00:26
 62        let t2 = t1 + 3 * 3600 + 17 * 60 + 42
 63        var cases: [EmacsOracle.Case] = []
 64        var ours: [(String, String)] = []
 65        for text in texts {
 66            let caret = (text as NSString).range(of: "Task").location
 67            for mode in ["out", "cancel"] {
 68                // Clock in at t1, then out (or cancel) at t2.
 69                let first = run(ClockIn(), text, caret: caret, at: t1, options: options)
 70                guard let start = ClockIn.runningStart(in: first.text, near: caret) else {
 71                    ours.append(("no running clock: \(first.failure ?? "")", text))
 72                    cases.append(EmacsOracle.Case(text: text, point: 1, form: "nil"))
 73                    continue
 74                }
 75                let second = run(ClockOut(start: start, cancel: mode == "cancel"), first.text, caret: first.caret, at: t2, options: options)
 76                ours.append((second.text, first.text))
 77                let out = mode == "cancel" ? "(org-clock-cancel)" : "(org-clock-out)"
 78                cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
 79                (progn
 80                  (require 'org-clock)
 81                  (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))
 82                  \(frozenClock(t1, "(org-clock-in)"))
 83                  (setq orgstar-after-in (buffer-substring-no-properties (point-min) (point-max)))
 84                  \(frozenClock(t2, out)))
 85                """))
 86            }
 87        }
 88        let emacs = try EmacsOracle.run(cases)
 89        for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
 90            #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)")
 91        }
 92    }
 93}
 94
 95
 96struct ClockReportTests {
 97    static let config = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/doom/config.el")
 98
 99    static let sample = """
100    * TODO [#A] Audit work :work:
101    :LOGBOOK:
102    CLOCK: [2026-02-20 Fri 10:00]--[2026-02-20 Fri 16:00] =>  6:00
103    CLOCK: [2026-02-17 Tue 16:22]--[2026-02-17 Tue 16:45] =>  0:23
104    CLOCK: [2026-02-17 Tue 08:15]--[2026-02-17 Tue 08:50] =>  0:35
105    :END:
106    * Meetings
107    :LOGBOOK:
108    CLOCK: [2026-02-24 Tue 09:30]--[2026-02-24 Tue 10:00] =>  0:30
109    CLOCK: [2026-03-02 Mon 09:00]
110    CLOCK: [2026-02-17 Tue 09:28]--[2026-02-17 Tue 09:55] =>  0:27
111    :END:
112    """
113
114    @Test func totalsPerHeading() {
115        let entries = ClockReport.entries(Self.sample)
116        let all = ClockReport.byHeading(entries)
117        #expect(all.map(\.heading) == ["Audit work", "Meetings"] && all.map(\.minutes) == [418, 57])
118        #expect(all[1].start == (Self.sample as NSString).range(of: "* Meetings").location)
119        #expect(ClockReport.byHeading(entries, from: "2026-02-18", to: "2026-02-24").map(\.minutes) == [360, 30])
120    }
121
122    /// Your own `tr/generate-report`, loaded from config.el in batch Emacs.
123    static func emacsReport(_ text: String, start: String?, end: String?) throws -> String {
124        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-tr-\(UUID().uuidString)")
125        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
126        defer { try? FileManager.default.removeItem(at: folder) }
127        let input = folder.appendingPathComponent("time.org")
128        let output = folder.appendingPathComponent("report.org")
129        try text.write(to: input, atomically: true, encoding: .utf8)
130        func lisp(_ s: String?) -> String { s.map { "\"\($0)\"" } ?? "nil" }
131        let script = folder.appendingPathComponent("tr.el")
132        try """
133        (require 'org)
134        (require 'cl-lib)
135        (require 'subr-x)
136        (with-temp-buffer
137          (insert-file-contents "\(config.path)")
138          (goto-char (point-min))
139          (condition-case nil
140              (while t
141                (let ((form (read (current-buffer))))
142                  (when (and (eq (car-safe form) 'defun) (string-prefix-p "tr/" (symbol-name (cadr form))))
143                    (eval form t))))
144            (end-of-file nil)))
145        (tr/generate-report "\(input.path)" "\(output.path)" \(lisp(start)) \(lisp(end)))
146        """.write(to: script, atomically: true, encoding: .utf8)
147        _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
148        return try String(contentsOf: output, encoding: .utf8)
149    }
150
151    @Test(.enabled(if: FileManager.default.fileExists(atPath: ClockReportTests.config.path) && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
152    func matchesYourReport() throws {
153        var texts = [Self.sample]
154        let work = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("git/cmc/work-notes/time.org")
155        if let real = try? String(contentsOf: work, encoding: .utf8) { texts.append(real) }
156        for text in texts {
157            for (start, end) in [(nil, nil), ("2026-02-18", nil), (nil, "2026-02-20"), ("2026-02-17", "2026-02-17")] as [(String?, String?)] {
158                let ours = ClockReport.timeReport(ClockReport.entries(text), start: start, end: end)
159                let theirs = try Self.emacsReport(text, start: start, end: end)
160                #expect(ours == theirs, "\(start ?? "-")..\(end ?? "-")\nours:\n\(ours)\ntheirs:\n\(theirs)")
161            }
162        }
163    }
164}
165
166struct ClockDrawerStartupTests {
167    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
168    func startupLogdrawerMatchesEmacs() throws {
169        let text = "#+STARTUP: nologdrawer\n* Task\nBody\n"
170        let caret = (text as NSString).range(of: "Task").location
171        let t1 = 1_789_000_000
172        var options = EditingOptions.org
173        options.logIntoDrawer = "NOTES"
174        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], now: Date(timeIntervalSince1970: Double(t1)), calendar: ClockTests.utc, options: options)
175        guard case .commit(let result) = ClockIn().run(in: context) else { Issue.record("no commit"); return }
176        let ours = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
177        let emacs = try EmacsOracle.run([EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: """
178            (progn (require 'org-clock)
179              (setq org-clock-persist nil org-clock-idle-time nil org-clock-auto-clock-resolution nil org-clock-into-drawer t)
180              (setq-default org-log-into-drawer "NOTES")
181              (org-mode)
182              \(frozenClock(t1, "(org-clock-in)")))
183            """)])
184        #expect(ours == emacs[0].text, "ours: \(ours.debugDescription)\nemacs: \(emacs[0].text.debugDescription) \(emacs[0].error)")
185    }
186}
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