Tests/OrgCoreTests/ClockTableTests.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Tests/OrgCoreTests/ClockTableTests.swift history · blame · raw

184 lines · 10318 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct ClockTableTests {
  6    static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
  7
  8    static let body = """
  9        * Project Alpha :work:
 10        :PROPERTIES:
 11        :Effort:   3:00
 12        :END:
 13        ** TODO Design the [[https://x.org][interface]] [1/2]
 14        :LOGBOOK:
 15        CLOCK: [2026-09-07 Mon 09:00]--[2026-09-07 Mon 11:30] =>  2:30
 16        CLOCK: [2026-09-09 Wed 23:00]--[2026-09-10 Thu 01:00] =>  2:00
 17        :END:
 18        *** A very long heading title that goes on and on beyond the narrowing width
 19        CLOCK: [2026-09-10 Thu 08:00]--[2026-09-10 Thu 08:45] =>  0:45
 20        ** Write code
 21        CLOCK: [2026-08-30 Sun 10:00]--[2026-08-30 Sun 12:00] =>  2:00
 22        CLOCK: => 1:15
 23        * COMMENT Beta
 24        CLOCK: [2026-09-08 Tue 14:00]--[2026-09-09 Wed 16:00] => 26:00
 25        * Untouched
 26
 27        """
 28
 29    static let params = [
 30        ":scope file :maxlevel 2", ":maxlevel 3 :emphasize t", ":maxlevel 1", ":block thisweek", ":block lastweek",
 31        ":block today :maxlevel 3", ":block 2026-09", ":tstart \"<2026-09-08>\" :tend \"<2026-09-10>\"",
 32        ":link t :maxlevel 3", ":narrow 20! :maxlevel 3", ":tags t :level t :maxlevel 3", ":properties (\"Effort\") :formula %",
 33        ":indent nil :maxlevel 3", ":block yesterday", ":block 2026-W36 :maxlevel 3", ":fileskip0 t :block 2025",
 34        ":maxlevel nil",
 35        ":match \"work\" :maxlevel 3", ":match \"-work\" :maxlevel 3", ":match \"TODO=\\\"TODO\\\"\" :maxlevel 3",
 36        ":match \"LEVEL=2\" :maxlevel 3", ":block 2026-09 :step week", ":block 2026-09 :step day :stepskip0 t",
 37        ":tstart \"<2026-08-25>\" :tend \"<2026-09-15>\" :step week :wstart 0", ":block 2026 :step month :stepskip0 t",
 38        ":block 2026 :step quarter", ":block 2026-09 :step semimonth :stepskip0 t",
 39    ]
 40
 41    static func ours(_ text: String, caret: Int, command: any OrgCommand, answers: [String: String] = [:]) -> String {
 42        var utc = Calendar(identifier: .gregorian)
 43        utc.timeZone = TimeZone(identifier: "UTC")!
 44        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret],
 45                                  now: Date(timeIntervalSince1970: 1_789_000_000), calendar: utc, answers: answers)
 46        switch command.run(in: context) {
 47        case .commit(let result):
 48            var new = text
 49            for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
 50            return new
 51        case .failed(let message): return "failed: \(message)"
 52        default: return "other"
 53        }
 54    }
 55
 56    @Test(.enabled(if: oracle))
 57    func updatesLikeOrgUpdateDblock() throws {
 58        var cases: [EmacsOracle.Case] = []
 59        var ours: [String] = []
 60        for param in Self.params {
 61            let text = "#+BEGIN: clocktable \(param)\nold contents\n#+END:\n" + Self.body
 62            cases.append(EmacsOracle.Case(text: text, point: 1, form: frozenClock(1_789_000_000, "(org-update-dblock)")))
 63            ours.append(Self.ours(text, caret: 0, command: UpdateDynamicBlock()))
 64        }
 65        for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() {
 66            #expect(mine == theirs.text, "\(Self.params[i])\nours:\n\(mine)\nemacs:\n\(theirs.text) \(theirs.error)")
 67        }
 68    }
 69
 70    @Test(.enabled(if: oracle))
 71    func reportsLikeOrgClockReport() throws {
 72        let text = "Intro\n" + Self.body
 73        let ns = text as NSString
 74        let points = [ns.range(of: "Intro").location + 2, ns.range(of: "** Write").location + 3, ns.range(of: "CLOCK: [2026-09-07").location]
 75        let cases = points.map { EmacsOracle.Case(text: text, point: EmacsOracle.point($0, in: text), form: frozenClock(1_789_000_000, "(org-clock-report)")) }
 76        let ours = points.map { Self.ours(text, caret: $0, command: ClockReportTable()) }
 77        for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() {
 78            #expect(mine == theirs.text, "at \(points[i])\nours:\n\(mine)\nemacs:\n\(theirs.text) \(theirs.error)")
 79        }
 80    }
 81
 82    @Test(.enabled(if: oracle))
 83    func setsEffortLikeOrgSetEffort() throws {
 84        let text = "* Task\n* Other\n:PROPERTIES:\n:Effort:   1:00\n:END:\n"
 85        let cases = [(0, "0:30"), (8, "2:00")].map { EmacsOracle.Case(text: text, point: $0.0 + 1, form: "(org-set-effort nil \"\($0.1)\")") }
 86        let ours = [(0, "0:30"), (8, "2:00")].map { Self.ours(text, caret: $0.0, command: SetEffort(), answers: ["effort": $0.1]) }
 87        #expect(ours == (try EmacsOracle.run(cases)).map(\.text))
 88    }
 89
 90    @Test func durations() {
 91        #expect(ClockTable.duration(0) == "0:00" && ClockTable.duration(95) == "1:35" && ClockTable.duration(1560) == "1d 2:00")
 92    }
 93}
 94
 95/// Clock tables over several files, against Emacs visiting the same files.
 96struct ClockTableScopeTests {
 97    static let files: [(String, String)] = [
 98        ("a.org", """
 99        #+BEGIN: clocktable
100        #+END:
101        * Alpha :work:
102        CLOCK: [2026-09-07 Mon 09:00]--[2026-09-07 Mon 10:00] =>  1:00
103        ** Alpha child
104        CLOCK: [2026-09-08 Tue 09:00]--[2026-09-08 Tue 09:30] =>  0:30
105        * Beta
106        :PROPERTIES:
107        :ARCHIVE: old.org::
108        :END:
109
110        """),
111        ("a.org_archive", "* Archived :work:\nCLOCK: [2026-09-02 Wed 09:00]--[2026-09-02 Wed 11:00] =>  2:00\n"),
112        ("old.org", "* Old entry\nCLOCK: [2026-09-03 Thu 09:00]--[2026-09-03 Thu 09:15] =>  0:15\n"),
113        ("b.org", "#+TITLE: Bee file\n* Bee :work:\nCLOCK: [2026-09-09 Wed 13:00]--[2026-09-09 Wed 15:00] =>  2:00\n* Idle\n"),
114        ("sub/c.org", "* Sea\nCLOCK: [2026-08-01 Sat 13:00]--[2026-08-01 Sat 14:00] =>  1:00\n"),
115    ]
116
117    static let params = [
118        ":scope agenda", ":scope agenda-with-archives", ":scope file-with-archives", ":scope (\"b.org\" \"sub/c.org\")",
119        ":scope agenda :hidefiles t", ":scope agenda :block 2026-09 :fileskip0 t", ":scope (\"b.org\" \"sub/c.org\") :block 2026-09 :fileskip0 t",
120        ":scope agenda :link t", ":scope agenda :filetitle t :formula %", ":scope agenda :level t :tags t",
121        ":scope agenda :block 2026-09 :step week :stepskip0 t", ":scope agenda :match \"work\"",
122    ]
123
124    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
125    func scopesLikeOrg() throws {
126        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-clocktable-\(UUID().uuidString)").standardizedFileURL
127        defer { try? FileManager.default.removeItem(at: folder) }
128        var utc = Calendar(identifier: .gregorian)
129        utc.timeZone = TimeZone(identifier: "UTC")!
130        for param in Self.params {
131            for (name, text) in Self.files {
132                let url = folder.appendingPathComponent(name)
133                try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
134                try (name == "a.org" ? text.replacingOccurrences(of: "#+BEGIN: clocktable\n", with: "#+BEGIN: clocktable \(param)\n") : text)
135                    .write(to: url, atomically: true, encoding: .utf8)
136            }
137            let a = folder.appendingPathComponent("a.org").path
138            let b = folder.appendingPathComponent("b.org").path
139            let form = """
140            (progn
141              (require 'org) (require 'org-clock)
142              (add-to-list 'auto-mode-alist '("\\\\.org_archive\\\\'" . org-mode))
143              (setq org-agenda-files (list "\(a)" "\(b)"))
144              (find-file "\(a)")
145              (goto-char (point-min))
146              \(frozenClock(1_789_000_000, "(org-update-dblock)"))
147              (princ (buffer-string)))
148            """
149            let emacs = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
150            let text = try String(contentsOfFile: a, encoding: .utf8)
151            var options = EditingOptions.org
152            options.filePath = a
153            options.agendaFiles = [a, b]
154            let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<0],
155                                      now: Date(timeIntervalSince1970: 1_789_000_000), calendar: utc, options: options)
156            var ours = text
157            if case .commit(let result) = UpdateDynamicBlock().run(in: context) {
158                for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
159            } else {
160                ours = "failed"
161            }
162            #expect(emacs.hasSuffix(ours), "\(param)\nours:\n\(ours)\nemacs:\n\(emacs)")
163        }
164    }
165}
166
167extension ClockTableScopeTests {
168    /// A folder in a `:scope` list gives its org files; Emacs takes only files there.
169    @Test func folderScopes() throws {
170        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-clocktable-\(UUID().uuidString)").standardizedFileURL
171        defer { try? FileManager.default.removeItem(at: folder) }
172        try FileManager.default.createDirectory(at: folder.appendingPathComponent("sub"), withIntermediateDirectories: true)
173        try "* Sea\nCLOCK: [2026-08-01 Sat 13:00]--[2026-08-01 Sat 14:00] =>  1:00\n".write(to: folder.appendingPathComponent("sub/c.org"), atomically: true, encoding: .utf8)
174        try "* Dee\nCLOCK: [2026-08-02 Sun 13:00]--[2026-08-02 Sun 13:30] =>  0:30\n".write(to: folder.appendingPathComponent("sub/d.org"), atomically: true, encoding: .utf8)
175        let text = "#+BEGIN: clocktable :scope (\"sub\")\n#+END:\n"
176        var options = EditingOptions.org
177        options.filePath = folder.appendingPathComponent("a.org").path
178        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [0..<0], options: options)
179        guard case .commit(let result) = UpdateDynamicBlock().run(in: context) else { Issue.record("no table"); return }
180        let table = result.edits[0].apply(to: text).replacingOccurrences(of: " +", with: " ", options: .regularExpression)
181        #expect(table.contains("| c.org | *File time* | *1:00*") && table.contains("| d.org | *File time* | *0:30*"), "\(table)")
182        #expect(table.contains("*1:30*"))
183    }
184}