Tests/OrgCoreTests/ClockTableTests.swift

design-themes-widgets
orgstar/Tests/OrgCoreTests/ClockTableTests.swift history · blame · raw

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