Tests/OrgCoreTests/ColumnEditTests.swift
191 lines · 8837 bytes
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `org-columns-next-allowed-value` and `org-columns-edit-value` against Emacs.
6struct ColumnEditTests {
7 static let text = """
8 #+COLUMNS: %25ITEM %TODO %PRIORITY %Effort %Status %Done(Done){X} %SCHEDULED %DEADLINE
9 #+PROPERTY: Effort_ALL 0:10 0:30 1:00
10 * TODO [#B] Task one :work:
11 SCHEDULED: <2026-10-05 Mon> DEADLINE: <2026-10-09 Fri>
12 :PROPERTIES:
13 :Effort: 0:30
14 :Status_ALL: new open closed
15 :Status: open
16 :END:
17 * Task two
18 Body.
19
20 """
21
22 /// Tags one space after the title: Emacs aligns them against column view's overlays.
23 static func untagged(_ text: String) -> String {
24 text.replacingOccurrences(of: "[ \\t]+(:\\S+:)$", with: " $1", options: [.regularExpression])
25 .components(separatedBy: "\n").map { $0.replacingOccurrences(of: "[ \\t]+(:[^ \\t]+:)$", with: " $1", options: .regularExpression) }
26 .joined(separator: "\n")
27 }
28
29 static func run(_ command: any OrgCommand, at offset: Int) -> String {
30 var utc = Calendar(identifier: .gregorian)
31 utc.timeZone = TimeZone(identifier: "UTC")!
32 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [offset..<offset], calendar: utc)
33 guard case .commit(let result) = command.run(in: context) else { return "failed" }
34 var new = text
35 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { new = edit.apply(to: new) }
36 return new
37 }
38
39 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
40 func nextValuesLikeOrg() throws {
41 let ns = Self.text as NSString
42 let one = ns.range(of: "* TODO").location
43 let two = ns.range(of: "* Task two").location
44 let cases: [(Int, String, String?, Bool)] = [
45 (one, "Effort", nil, false), (one, "Effort", nil, true), (one, "Status", nil, false), (one, "TODO", nil, false),
46 (one, "PRIORITY", nil, false), (one, "PRIORITY", nil, true), (two, "Effort", nil, false), (two, "Done", "X", false),
47 (two, "TODO", nil, true),
48 ]
49 var oracle: [EmacsOracle.Case] = []
50 var ours: [String] = []
51 for (offset, key, summary, previous) in cases {
52 let form = """
53 (progn (org-columns)
54 (while (not (equal (get-char-property (point) 'org-columns-key) "\(key.uppercased())")) (forward-char 1))
55 (org-columns-next-allowed-value \(previous ? "t" : "nil"))
56 (org-columns-quit))
57 """
58 oracle.append(EmacsOracle.Case(text: Self.text, point: EmacsOracle.point(offset, in: Self.text), form: form))
59 ours.append(Self.run(NextColumnValue(property: key, summary: summary, previous: previous), at: offset + 2))
60 }
61 for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(oracle)).enumerated() {
62 #expect(Self.untagged(mine) == Self.untagged(theirs.text), "\(cases[i]) \(theirs.error)")
63 }
64 }
65
66 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
67 func editsLikeOrg() throws {
68 let ns = Self.text as NSString
69 let one = ns.range(of: "* TODO").location
70 let two = ns.range(of: "* Task two").location
71 let cases: [(Int, String, String)] = [
72 (one, "ITEM", "Renamed task"), (two, "ITEM", "Second"), (one, "Status", "closed"), (one, "Effort", "2:00"), (two, "Effort", "0:10"),
73 (two, "Status", "new"),
74 ]
75 var oracle: [EmacsOracle.Case] = []
76 var ours: [String] = []
77 for (offset, key, value) in cases {
78 let form = """
79 (cl-letf (((symbol-function 'read-string) (lambda (&rest _) "\(value)"))
80 ((symbol-function 'completing-read) (lambda (&rest _) "\(value)")))
81 (org-columns)
82 (while (not (equal (get-char-property (point) 'org-columns-key) "\(key.uppercased())")) (forward-char 1))
83 (org-columns-edit-value)
84 (org-columns-quit))
85 """
86 oracle.append(EmacsOracle.Case(text: Self.text, point: EmacsOracle.point(offset, in: Self.text), form: form))
87 ours.append(Self.run(SetColumnValue(property: key, value: value), at: offset))
88 }
89 for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(oracle)).enumerated() {
90 #expect(Self.untagged(mine) == Self.untagged(theirs.text), "\(cases[i]) \(theirs.error)")
91 }
92 }
93
94 /// Org 9.8.7 signals "Properties values should be strings" here; orgstar moves the date.
95 @Test func shiftsPlanningDates() {
96 let at = (Self.text as NSString).range(of: "* TODO").location + 3
97 #expect(Self.run(NextColumnValue(property: "SCHEDULED"), at: at).contains("SCHEDULED: <2026-10-06 Tue>"))
98 #expect(Self.run(NextColumnValue(property: "DEADLINE", previous: true), at: at).contains("DEADLINE: <2026-10-08 Thu>"))
99 }
100
101 @Test func specialsAndUnknowns() {
102 let at = (Self.text as NSString).range(of: "* TODO").location + 3
103 #expect(Self.run(SetColumnValue(property: "CLOCKSUM", value: "1:00"), at: at) == "failed")
104 #expect(Self.run(NextColumnValue(property: "ITEM"), at: at) == "failed")
105 #expect(Self.run(SetColumnValue(property: "TODO", value: "DONE"), at: at).contains("* DONE [#B] Task one"))
106 #expect(Self.run(SetColumnValue(property: "TAGS", value: ":home:work:"), at: at).contains(":home:work:"))
107 }
108}
109
110/// The `columnview` block's `:id` sources and `:match`, against Emacs visiting the files.
111struct ColumnViewSourceTests {
112 static let a = """
113 #+COLUMNS: %25ITEM %TODO %Effort{:}
114 #+BEGIN: columnview
115 #+END:
116 * Local :work:
117 :PROPERTIES:
118 :ID: local-one
119 :END:
120 ** TODO Child :home:
121 :PROPERTIES:
122 :Effort: 0:20
123 :END:
124 ** Other child :work:
125 :PROPERTIES:
126 :Effort: 0:40
127 :END:
128
129 """
130 static let b = """
131 #+COLUMNS: %ITEM %Owner %Effort{:}
132 * Bee project
133 :PROPERTIES:
134 :ID: bee-id
135 :END:
136 ** Task :work:
137 :PROPERTIES:
138 :Owner: Ada
139 :Effort: 1:00
140 :END:
141 * Elsewhere
142 :PROPERTIES:
143 :Owner: Bob
144 :END:
145
146 """
147
148 static let params = [
149 ":id \"file:b.org\"", ":id bee-id", ":id local-one", ":id global :match \"work\"", ":id global :match \"-home\" :maxlevel 2",
150 ":id \"file:b.org\" :match \"Owner=\\\"Ada\\\"\"", ":id local-one :match \"TODO=\\\"TODO\\\"\"",
151 ]
152
153 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
154 func sourcesLikeOrg() throws {
155 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-colview-\(UUID().uuidString)").standardizedFileURL
156 defer { try? FileManager.default.removeItem(at: folder) }
157 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
158 let aPath = folder.appendingPathComponent("a.org").path
159 let bPath = folder.appendingPathComponent("b.org").path
160 for param in Self.params {
161 let text = Self.a.replacingOccurrences(of: "#+BEGIN: columnview\n", with: "#+BEGIN: columnview \(param)\n")
162 try text.write(toFile: aPath, atomically: true, encoding: .utf8)
163 try Self.b.write(toFile: bPath, atomically: true, encoding: .utf8)
164 let form = """
165 (progn
166 (require 'org) (require 'org-colview) (require 'org-id)
167 (setq org-agenda-files (list "\(aPath)" "\(bPath)") org-id-locations-file "\(folder.path)/ids")
168 (find-file "\(aPath)")
169 (goto-char (point-min))
170 (re-search-forward "^#\\\\+BEGIN:")
171 (beginning-of-line)
172 (org-update-dblock)
173 (princ (buffer-string)))
174 """
175 let emacs = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
176 var options = EditingOptions.org
177 options.filePath = aPath
178 options.agendaFiles = [aPath, bPath]
179 let caret = (text as NSString).range(of: "#+BEGIN").location
180 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], options: options)
181 var ours = text
182 switch UpdateDynamicBlock().run(in: context) {
183 case .commit(let result):
184 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
185 case .failed(let message): ours = "failed: \(message)"
186 default: ours = "other"
187 }
188 #expect(emacs.hasSuffix(ours), "\(param)\nours:\n\(ours)\nemacs:\n\(emacs)")
189 }
190 }
191}