Tests/OrgCoreTests/ICalendarTests.swift
328 lines · 13633 bytes
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct ICalendarTests {
6 static func lisp(_ s: String) -> String {
7 "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
8 }
9
10 /// Random UIDs, which differ between runs.
11 static func normalized(_ s: String) -> String {
12 s.replacing(#/(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/#, with: "UUID")
13 }
14
15 static let seconds = 1_791_000_000
16
17 static var utc: Calendar {
18 var c = Calendar(identifier: .gregorian)
19 c.timeZone = TimeZone(identifier: "UTC")!
20 return c
21 }
22
23 /// `org-icalendar-export-to-ics` on each file with `setup`, a `setq` body, in UTC; or with
24 /// `combine`, `org-icalendar-combine-agenda-files` over all of them.
25 static func emacs(_ files: [String], setup: String, combine: Bool = false) throws -> [String] {
26 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-ics-\(UUID().uuidString)")
27 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
28 defer { try? FileManager.default.removeItem(at: folder) }
29 var paths: [String] = []
30 for (i, file) in files.enumerated() {
31 let path = folder.appendingPathComponent("cal\(i).org").path
32 try file.write(toFile: path, atomically: true, encoding: .utf8)
33 paths.append(path)
34 }
35 let combined = folder.appendingPathComponent("combined.ics").path
36 let body = combine
37 ? "(let ((org-agenda-files '(\(paths.map(lisp).joined(separator: " "))))) (org-icalendar-combine-agenda-files))"
38 : paths.map { "(with-current-buffer (find-file-noselect \(lisp($0))) (org-icalendar-export-to-ics))" }.joined(separator: "\n")
39 let script = folder.appendingPathComponent("ics.el")
40 try """
41 ;;; -*- lexical-binding: t -*-
42 (require 'org)
43 (require 'ox-icalendar)
44 (setq org-adapt-indentation nil user-full-name "Ann" org-export-use-babel nil
45 org-icalendar-combined-agenda-file \(lisp(combined)))
46 (setq \(setup))
47 \(frozenClock(seconds, "(progn " + body + ")"))
48 """.write(to: script, atomically: true, encoding: .utf8)
49 let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
50 let outputs = combine ? [combined] : paths.map { ($0 as NSString).deletingPathExtension + ".ics" }
51 return try outputs.map { path in
52 guard let data = FileManager.default.contents(atPath: path) else { throw EmacsOracle.EvaluateError(log: log) }
53 return String(decoding: data, as: UTF8.self)
54 }
55 }
56
57 static func ours(_ file: String, index: Int, options: ICalendarOptions) -> String {
58 var options = options
59 options.timezone = "UTC"
60 options.userFullName = "Ann"
61 return ICalendarExport.calendar(file, name: "cal\(index).org", options: options, now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc)
62 }
63
64 static let files = [
65 """
66 #+TITLE: My /Cal/
67 #+AUTHOR: Ann
68 * TODO Meeting with *Bob* and [[https://x.org][site]] :work:
69 SCHEDULED: <2026-10-12 Mon 10:00>
70 :PROPERTIES:
71 :ID: abc-1
72 :LOCATION: Room 1, floor 2
73 :END:
74 Short line with /italic/ and =code= and ~verb~.
75 A second line that goes on and on and on and on and on and on and on and on past seventy-two columns for sure.
76
77 - item one
78 - item two <2026-10-13 Tue>
79 continued
80
81 #+begin_src sh
82 echo hi
83 #+end_src
84
85 | a | b |
86 |---+---|
87 | 1 | 2 |
88 ** DONE Child :home:
89 DEADLINE: <2026-10-20 Tue>
90 Text with <2026-10-21 Wed 9:00-10:30> and [2026-10-22 Thu].
91 * Plain heading <2026-10-25 Sun +1w>
92 CLOSED: [2026-10-01 Thu 10:00]
93 :LOGBOOK:
94 CLOCK: [2026-10-01 Thu 09:00]--[2026-10-01 Thu 10:00] => 1:00
95 :END:
96 Body.
97 """,
98 """
99 #+CATEGORY: errands
100 #+TODO: TODO NEXT | DONE
101 * TODO [#A] Pay rent :home:money:
102 DEADLINE: <2026-11-01 Sun -3d +1m>
103 :PROPERTIES:
104 :ID: rent
105 :APPT_WARNTIME: 15
106 :END:
107 * NEXT Write report
108 SCHEDULED: <2026-10-14 Wed 09:30 +1w> DEADLINE: <2026-12-01 Tue>
109 :PROPERTIES:
110 :ID: report
111 :CATEGORY: work
112 :SUMMARY: The quarterly report; draft
113 :DESCRIPTION: Numbers, charts \\ and text
114 :CLASS: PRIVATE
115 :TIMEZONE: Europe/Paris
116 :END:
117 * TODO Project
118 :PROPERTIES:
119 :ORDERED: t
120 :ID: proj
121 :END:
122 ** TODO First step
123 :PROPERTIES:
124 :ID: step1
125 :END:
126 ** TODO Second step
127 :PROPERTIES:
128 :ID: step2
129 :END:
130 * Trip <2026-10-30 Fri>--<2026-11-02 Mon>
131 :PROPERTIES:
132 :ID: trip
133 :END:
134 Dates --- and ranges... with an entity \\alpha and a footnote[fn:1].
135 Also <2026-10-31 Sat 18:00>--<2026-11-01 Sun 02:30> and an e.g. case that must not break after the period because it is near the edge.
136 * Hidden :noexport:
137 <2026-10-15 Thu>
138 * COMMENT Commented
139 <2026-10-16 Fri>
140 * Old :ARCHIVE:
141 SCHEDULED: <2026-10-17 Sat>
142 <2026-10-18 Sun>
143 * Deep
144 :PROPERTIES:
145 :ID: deep
146 :END:
147 ** Deeper
148 :PROPERTIES:
149 :ID: deeper
150 :END:
151 *** Deepest
152 :PROPERTIES:
153 :ID: deepest
154 :END:
155 **** Low level <2026-10-19 Mon>
156 :PROPERTIES:
157 :ID: low
158 :END:
159 A paragraph under a low level heading, which ox-ascii fills to a narrower width than usual, so this wraps.
160 1. first
161 2. [X] second, done
162 - nested
163 3. third
164 - term :: definition
165
166 #+begin_quote
167 A quoted paragraph that is long enough to wrap at the narrower width inside the quote block margins here.
168 #+end_quote
169 * Footnotes
170 [fn:1] The note.
171 """,
172 """
173 #+ICALENDAR_EXCLUDE_TAGS: private
174 #+ICAL-TTL: PT1H
175 #+OPTIONS: <:t
176 * Event <2026-10-20 Tue 14:00>
177 :PROPERTIES:
178 :ID: ev
179 :END:
180 Logged [2026-10-21 Wed] as well.
181 * Secret :private:
182 <2026-10-22 Thu>
183 * Noexport stays :noexport:
184 :PROPERTIES:
185 :ID: stays
186 :END:
187 <2026-10-23 Fri>
188 """,
189 """
190 * Notes <2026-10-24 Sat 08:00>
191 :PROPERTIES:
192 :ID: notes
193 :TIMEZONE: UTC
194 :APPT_WARNTIME: 5
195 :END:
196 | Item | Cost |
197 |--------+------|
198 | Apples | 1.5 |
199 | Pears | 12 |
200 |--------+------|
201 | Total | 13.5 |
202
203 -----
204
205 #+begin_example
206 indented
207 example
208 #+end_example
209
210 : fixed width
211 : line
212
213 :NOTES:
214 In a drawer, see [[*Other][the other]] and [[file:other.org][other]] and https://example.com/x and [[Other]].
215 :END:
216
217 - [ ] open box
218 - [-] partial
219 1. sub one
220 2. sub two
221
222 H_{2}O and x^2 \\
223 on a line of its own.
224
225 <2026-10-26 Mon>
226
227 #+begin_verse
228 Roses are red
229 violets blue
230 #+end_verse
231 * Other
232 """,
233 ]
234
235 static let optionSets: [(lisp: String, ours: ICalendarOptions)] = {
236 var sets: [(String, ICalendarOptions)] = [("org-icalendar-timezone \"UTC\"", ICalendarOptions())]
237 var todo = ICalendarOptions()
238 todo.includeTodo = .unfinished
239 todo.useScheduled = ["event-if-todo", "event-if-not-todo", "todo-start"]
240 todo.useDeadline = ["event-if-todo-not-done", "todo-due"]
241 sets.append(("org-icalendar-include-todo t org-icalendar-use-scheduled '(event-if-todo event-if-not-todo todo-start) org-icalendar-use-deadline '(event-if-todo-not-done todo-due)", todo))
242 var all = ICalendarOptions()
243 all.includeTodo = .all
244 all.categories = ["todo-state", "all-tags", "category"]
245 all.alarmTime = 10
246 all.withTimestamps = "t"
247 all.todoUnscheduledStart = "deadline-warning"
248 sets.append(("org-icalendar-include-todo 'all org-icalendar-categories '(todo-state all-tags category) org-icalendar-alarm-time 10 org-icalendar-with-timestamps t org-icalendar-todo-unscheduled-start 'deadline-warning", all))
249 var unblocked = ICalendarOptions()
250 unblocked.includeTodo = .unblocked
251 unblocked.dateTimeFormat = ":%Y%m%dT%H%M%SZ"
252 unblocked.includeBody = .characters(20)
253 unblocked.scheduledSummaryPrefix = "Sched; "
254 sets.append(("org-icalendar-include-todo 'unblocked org-icalendar-date-time-format \":%Y%m%dT%H%M%SZ\" org-icalendar-include-body 20 org-icalendar-scheduled-summary-prefix \"Sched; \"", unblocked))
255 var keywords = ICalendarOptions()
256 keywords.includeTodo = .keywords(["NEXT"])
257 keywords.includeBody = .none
258 keywords.excludeTags = ["work"]
259 keywords.todoUnscheduledStart = "nil"
260 sets.append(("org-icalendar-include-todo '(\"NEXT\") org-icalendar-include-body nil org-icalendar-exclude-tags '(\"work\") org-icalendar-todo-unscheduled-start nil", keywords))
261 return sets
262 }()
263
264 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: optionSets.indices)
265 func filesMatchEmacs(set: Int) throws {
266 let (setup, options) = Self.optionSets[set]
267 let emacs = try Self.emacs(Self.files, setup: "org-icalendar-timezone \"UTC\" " + setup)
268 for (i, (file, expected)) in zip(Self.files, emacs).enumerated() {
269 let mine = Self.normalized(Self.ours(file, index: i, options: options))
270 let theirs = Self.normalized(expected)
271 #expect(mine == theirs, "file \(i), options \(set)\n\(Self.diff(mine, theirs))")
272 }
273 }
274
275 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
276 func combinedMatchesEmacs() throws {
277 let emacs = try Self.emacs(Self.files, setup: "org-icalendar-timezone \"UTC\" org-icalendar-include-todo t", combine: true)
278 var options = ICalendarOptions()
279 options.timezone = "UTC"
280 options.userFullName = "Ann"
281 options.includeTodo = .unfinished
282 let mine = ICalendarExport.combined(Self.files.enumerated().map { ("cal\($0.offset).org", $0.element, OrgSettings.default) },
283 options: options, now: Date(timeIntervalSince1970: Double(Self.seconds)), calendar: Self.utc)
284 #expect(Self.normalized(mine) == Self.normalized(emacs[0]), "\(Self.diff(Self.normalized(mine), Self.normalized(emacs[0])))")
285 }
286
287 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
288 func subtreeMatchesEmacs() throws {
289 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-ics-\(UUID().uuidString)")
290 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
291 defer { try? FileManager.default.removeItem(at: folder) }
292 let file = Self.files[1]
293 let path = folder.appendingPathComponent("cal1.org").path
294 try file.write(toFile: path, atomically: true, encoding: .utf8)
295 let offset = (file as NSString).range(of: "* Deep").location
296 let script = folder.appendingPathComponent("ics.el")
297 try """
298 ;;; -*- lexical-binding: t -*-
299 (require 'org)
300 (require 'ox-icalendar)
301 (setq org-adapt-indentation nil user-full-name "Ann" org-icalendar-timezone "UTC")
302 \(frozenClock(Self.seconds, "(with-current-buffer (find-file-noselect \(Self.lisp(path))) (goto-char \(offset + 3)) (org-icalendar-export-to-ics nil t))"))
303 """.write(to: script, atomically: true, encoding: .utf8)
304 let log = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["TZ": "UTC"])
305 guard let data = FileManager.default.contents(atPath: folder.appendingPathComponent("cal1.ics").path) else { throw EmacsOracle.EvaluateError(log: log) }
306 var options = ICalendarOptions()
307 options.timezone = "UTC"
308 options.userFullName = "Ann"
309 let mine = Self.normalized(ICalendarExport.calendar(file, name: "cal1.org", options: options, subtree: offset + 2, now: Date(timeIntervalSince1970: Double(Self.seconds)), calendar: Self.utc))
310 let theirs = Self.normalized(String(decoding: data, as: UTF8.self))
311 #expect(mine == theirs, "\(Self.diff(mine, theirs))")
312 }
313
314 @Test func foldsLongLinesAndEscapes() {
315 #expect(ICalendarExport.cleanup("a,b;c\\d\n e") == "a\\,b\\;c\\\\d\\n e")
316 let line = String(repeating: "x", count: 160)
317 #expect(ICalendarExport.fold(line) == String(repeating: "x", count: 75) + "\n " + String(repeating: "x", count: 74) + "\n " + String(repeating: "x", count: 11) + "\n")
318 }
319
320 /// The first lines that differ.
321 static func diff(_ a: String, _ b: String) -> String {
322 let x = a.components(separatedBy: "\r\n"), y = b.components(separatedBy: "\r\n")
323 for i in 0..<max(x.count, y.count) where (i < x.count ? x[i] : nil) != (i < y.count ? y[i] : nil) {
324 return "line \(i)\nours: \((i < x.count ? x[i] : "<none>").debugDescription)\nemacs: \((i < y.count ? y[i] : "<none>").debugDescription)"
325 }
326 return "same"
327 }
328}