Tests/OrgAppTests/UserConfigTests.swift
310 lines · 19717 bytes
25 symbols in this file
UserConfigTestsdefaultslineNumbersTypestemplateRoundTripsdefaultTemplateHasEveryDefaultproblemsAndRemovedLineseditsKeepCommentsAndOrdermissingSectionsAreAddedlegacyFilesAreRewrittenstructureTemplatesTablelegacyNamesMoveInPlacesyncsBothWayswritesThroughASymlinkThemeConfigTeststhemeTablesAreNotSettingsProblemsthemeFileInASubfolderIsRecognizedThemeReadingTestsconfigColorsOverThemeFileOverDefaultnoThemeFileIsTheDefaultWithConfigColorsproblemschosenPalettesSitUnderTheThemeFileAndConfignoThemeSettingsGiveTheDefaultThemecopyingAThemeNeverOverwritesaThemePickedInTheAppAppliesAtOncesandboxIgnoresEnvironmentFoldersOutsideTheContainer
1import Foundation
2import OrgCore
3import OrgPresentation
4import Testing
5@testable import OrgApp
6
7@MainActor
8struct UserConfigTests {
9 func defaults() -> UserDefaults { TestDefaults("orgstar-config") }
10
11 @Test func lineNumbersTypes() throws {
12 let d = defaults()
13 let setting = try #require(UserConfig.settings.first { $0.key == "display-line-numbers-type" })
14 #expect(UserConfig.store(.string("relative"), setting, in: d) == nil)
15 #expect(d.bool(forKey: "showLineNumbers") && d.string(forKey: "lineNumbersType") == "relative")
16 #expect(UserConfig.value(setting, in: d) == .string("relative"))
17 #expect(UserConfig.store(.bool(true), setting, in: d) == nil)
18 #expect(UserConfig.value(setting, in: d) == .bool(true))
19 #expect(UserConfig.store(.bool(false), setting, in: d) == nil)
20 #expect(UserConfig.value(setting, in: d) == .bool(false))
21 #expect(UserConfig.store(.string("sideways"), setting, in: d) != nil)
22 }
23
24 @Test func templateRoundTrips() {
25 let source = defaults()
26 source.set("doom", forKey: "keymap")
27 source.set(3, forKey: "optionAsMeta")
28 source.set(72, forKey: "fillColumn")
29 source.set(false, forKey: "showLineNumbers")
30 let text = UserConfig.template(from: source)
31 #expect(text.contains("keymap = \"doom\""))
32 #expect(text.contains("\nfill-column = 72"))
33 #expect(text.contains("org-agenda-start-day = \"+0d\""))
34 #expect(text.contains("option-as-meta = \"both\""))
35 let target = defaults()
36 #expect(UserConfig.apply(text, to: target).isEmpty)
37 #expect(target.string(forKey: "keymap") == "doom")
38 #expect(target.integer(forKey: "optionAsMeta") == 3)
39 #expect(target.integer(forKey: "fillColumn") == 72)
40 #expect(target.bool(forKey: "showLineNumbers") == false)
41 }
42
43 @Test func defaultTemplateHasEveryDefault() {
44 #expect(UserConfig.defaultTemplate == UserConfig.template(from: defaults()))
45 let target = defaults()
46 #expect(UserConfig.apply(UserConfig.defaultTemplate, to: target).isEmpty)
47 for setting in UserConfig.settings {
48 #expect(UserConfig.value(setting, in: target) == setting.fallback, "\(setting.key)")
49 }
50 }
51
52 @Test func problemsAndRemovedLines() {
53 let target = defaults()
54 target.set(60, forKey: "fillColumn")
55 let problems = UserConfig.apply("fill-column = \"wide\"\norg-agenda-start-day = \"soon\"\n[orgstar]\nkeymap = \"vim\"\ncolour = 1\n", to: target)
56 #expect(problems.count == 4)
57 #expect(target.integer(forKey: "fillColumn") == 60)
58 #expect(UserConfig.apply("[orgstar]\n", to: target).isEmpty)
59 #expect(target.object(forKey: "fillColumn") == nil)
60 }
61
62 @Test func editsKeepCommentsAndOrder() {
63 let text = "# mine\n[editor]\nfill-column = 80 # wide\nline-numbers = true\n\n[agenda]\nspan = 10\n"
64 #expect(UserConfig.setting(text, section: "editor", key: "fill-column", to: .integer(72))
65 == "# mine\n[editor]\nfill-column = 72 # wide\nline-numbers = true\n\n[agenda]\nspan = 10\n")
66 #expect(UserConfig.setting(text, section: "editor", key: "show-markup", to: .bool(true))
67 == "# mine\n[editor]\nfill-column = 80 # wide\nline-numbers = true\nshow-markup = true\n\n[agenda]\nspan = 10\n")
68 #expect(UserConfig.setting(text, section: "capture", key: "global-hotkey", to: .bool(false))
69 == "# mine\n[editor]\nfill-column = 80 # wide\nline-numbers = true\n\n[agenda]\nspan = 10\n\n[capture]\nglobal-hotkey = false\n")
70 #expect(UserConfig.setting("[general]\nkeymap = \"emacs#1\" # c\n", section: "general", key: "keymap", to: .string("doom"))
71 == "[general]\nkeymap = \"doom\" # c\n")
72 #expect(UserConfig.setting("# top\n\n[orgstar]\nsave = \"explicit\"\n", section: "", key: "fill-column", to: .integer(70))
73 == "# top\nfill-column = 70\n\n[orgstar]\nsave = \"explicit\"\n")
74 }
75
76 @Test func missingSectionsAreAdded() {
77 let text = "# mine\nfill-column = 70\n\n[orgstar]\nsave = \"explicit\"\n"
78 let completed = UserConfig.addingMissingSections(text, from: defaults())
79 #expect(completed.hasPrefix(text))
80 #expect(completed.contains("\n[theme]\nfont = \"\"") && !completed.contains("keymap"))
81 #expect(UserConfig.addingMissingSections(completed, from: defaults()) == completed)
82 }
83
84 @Test func legacyFilesAreRewritten() throws {
85 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-config-\(UUID().uuidString)")
86 defer { try? FileManager.default.removeItem(at: folder) }
87 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
88 let url = folder.appendingPathComponent("config.toml")
89 try "[editor]\nfill-column = 64\n[general]\nkeymap = \"doom\"\n".write(to: url, atomically: true, encoding: .utf8)
90 let store = defaults()
91 ConfigSync(url: url, defaults: store).start(watch: false)
92 #expect(store.integer(forKey: "fillColumn") == 64)
93 let text = try String(contentsOf: url, encoding: .utf8)
94 #expect(text.contains("\nfill-column = 64") && text.contains("keymap = \"doom\"") && !text.contains("[editor]"))
95 }
96
97 @Test func structureTemplatesTable() throws {
98 let store = defaults()
99 #expect(OrgPreferences.options(store).structureTemplates == nil)
100 let problems = UserConfig.apply("fill-column = 70\n[org-structure-template-alist]\npy = \"src python\"\ns = \"src sh\"\nn = 3\n", to: store)
101 #expect(problems == ["config.toml: org-structure-template-alist.n must be a block type, such as \"src python\""])
102 let templates = try #require(OrgPreferences.options(store).structureTemplates)
103 #expect(templates.first { $0.key == "s" }?.type == "src sh" && templates.last == StructureTemplate(key: "py", type: "src python"))
104 #expect(templates.count == StructureTemplate.defaults.count + 1)
105 // Without the table, Org's templates.
106 #expect(UserConfig.apply("fill-column = 70\n", to: store).isEmpty)
107 #expect(OrgPreferences.options(store).structureTemplates == nil)
108
109 // One added in the app goes into the file.
110 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-config-\(UUID().uuidString)")
111 defer { try? FileManager.default.removeItem(at: folder) }
112 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
113 let url = folder.appendingPathComponent("config.toml")
114 try "fill-column = 70\n[org-structure-template-alist]\npy = \"src python\"\n".write(to: url, atomically: true, encoding: .utf8)
115 let synced = defaults()
116 let sync = ConfigSync(url: url, defaults: synced)
117 sync.start(watch: false)
118 UserConfig.setStructureTemplates(UserConfig.structureTemplates(synced) + [.init(key: "el", type: "src emacs-lisp")], in: synced)
119 let text = try String(contentsOf: url, encoding: .utf8)
120 #expect(text.contains("[org-structure-template-alist]\npy = \"src python\"\nel = \"src emacs-lisp\"\n"), "\(text)")
121 }
122
123 @Test func legacyNamesMoveInPlace() {
124 let text = "# mine\n[editor]\n# my editor\nfill-column = 64 # narrow\n\n[agenda]\nspan = 7\n\n[theme]\nfont-size = 15\n"
125 let migrated = UserConfig.migratingLegacyNames(text)
126 #expect(migrated == "# mine\nfill-column = 64 # narrow\norg-agenda-span = 7\n[editor]\n# my editor\n\n[theme]\nfont-size = 15\n")
127 #expect(!UserConfig.usesLegacyNames(migrated))
128 let store = defaults()
129 #expect(UserConfig.apply(migrated, to: store).isEmpty)
130 #expect(store.integer(forKey: "fillColumn") == 64 && store.integer(forKey: "agendaSpan") == 7 && store.integer(forKey: "themeFontSize") == 15)
131 // The new name wins over the old one.
132 #expect(UserConfig.migratingLegacyNames("fill-column = 70\n[editor]\nfill-column = 64\n") == "fill-column = 70\n")
133 }
134
135 @Test func syncsBothWays() throws {
136 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-config-\(UUID().uuidString)")
137 defer { try? FileManager.default.removeItem(at: folder) }
138 let url = folder.appendingPathComponent("config.toml")
139 let store = defaults()
140 let sync = ConfigSync(url: url, defaults: store)
141 sync.start(watch: false)
142 #expect(try String(contentsOf: url, encoding: .utf8).contains("\nfill-column = 80"))
143
144 store.set(66, forKey: "fillColumn")
145 #expect(try String(contentsOf: url, encoding: .utf8).contains("fill-column = 66"))
146
147 var text = try String(contentsOf: url, encoding: .utf8)
148 text = text.replacingOccurrences(of: "org-agenda-span = 10", with: "org-agenda-span = 7")
149 .replacingOccurrences(of: "org-agenda-start-day = \"-3d\"", with: "org-agenda-start-day = \"+0d\"")
150 try text.write(to: url, atomically: true, encoding: .utf8)
151 sync.reload()
152 #expect(store.integer(forKey: "agendaSpan") == 7)
153 #expect(store.integer(forKey: "agendaStartOffset") == 0)
154 #expect(sync.problems.isEmpty)
155 }
156
157 /// A config.toml linked to another folder's (as the iOS app's) stays a link when the
158 /// Settings window writes it.
159 @Test func writesThroughASymlink() throws {
160 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-config-\(UUID().uuidString)")
161 defer { try? FileManager.default.removeItem(at: folder) }
162 let shared = folder.appendingPathComponent("notes/config.toml")
163 let link = folder.appendingPathComponent("orgstar/config.toml")
164 try FileManager.default.createDirectory(at: shared.deletingLastPathComponent(), withIntermediateDirectories: true)
165 try FileManager.default.createDirectory(at: link.deletingLastPathComponent(), withIntermediateDirectories: true)
166 try "fill-column = 80\n".write(to: shared, atomically: true, encoding: .utf8)
167 try FileManager.default.createSymbolicLink(at: link, withDestinationURL: shared)
168 let store = defaults()
169 let sync = ConfigSync(url: link, defaults: store)
170 sync.start(watch: false)
171 store.set(66, forKey: "fillColumn")
172 #expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == shared.path)
173 #expect(try String(contentsOf: shared, encoding: .utf8).contains("fill-column = 66"))
174 }
175}
176
177@MainActor
178struct ThemeConfigTests {
179 @Test func themeTablesAreNotSettingsProblems() throws {
180 let defaults = TestDefaults("orgstar-theme")
181 let problems = UserConfig.apply("[theme]\nfont-size = 15\nlink = \"#123456\"\n[theme.dark]\nlink = \"#654321\"\n", to: defaults)
182 #expect(problems.isEmpty)
183 #expect(defaults.integer(forKey: "themeFontSize") == 15)
184
185 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-theme-\(UUID().uuidString)")
186 defer { try? FileManager.default.removeItem(at: folder) }
187 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
188 try "[theme.light]\nlink = \"#000001\"\ntodo = \"#000002\"\n".write(to: folder.appendingPathComponent("mine.toml"), atomically: true, encoding: .utf8)
189 try "[theme]\ntheme-file = \"mine.toml\"\nlink = \"#000003\"\n".write(to: folder.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
190 let sync = ConfigSync(url: folder.appendingPathComponent("config.toml"), defaults: defaults)
191 sync.start(watch: false)
192 #expect(sync.problems.isEmpty, "\(sync.problems)")
193 #expect(sync.theme.light["link"]?.hex == "#000003")
194 #expect(sync.theme.light["todo"]?.hex == "#000002")
195 #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("default-theme.toml").path))
196 }
197
198 @Test func themeFileInASubfolderIsRecognized() throws {
199 let defaults = TestDefaults("orgstar-theme")
200 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-theme-\(UUID().uuidString)")
201 defer { try? FileManager.default.removeItem(at: folder) }
202 try FileManager.default.createDirectory(at: folder.appendingPathComponent("themes"), withIntermediateDirectories: true)
203 try "[theme]\ntheme-file = \"themes/x.toml\"\n".write(to: folder.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
204 let sync = ConfigSync(url: folder.appendingPathComponent("config.toml"), defaults: defaults)
205 sync.start(watch: false)
206 // The watcher reports paths under the folder with symlinks resolved (/private/var/…).
207 let reported = folder.resolvingSymlinksInPath().appendingPathComponent("themes/x.toml")
208 #expect(sync.isThemeFile(reported))
209 #expect(!sync.isThemeFile(folder.appendingPathComponent("x.toml")))
210 }
211}
212
213struct ThemeReadingTests {
214 let folder = URL(fileURLWithPath: "/config")
215
216 @Test func configColorsOverThemeFileOverDefault() throws {
217 var read: [String] = []
218 let config = "[theme]\ntheme-file = \"themes/mine.toml\"\nlink = \"#000003\"\n[theme.dark]\nbackground = \"#000004\"\n"
219 let result = try #require(UserConfig.theme(config: config, themeFile: "themes/mine.toml", in: folder) { url in
220 read.append(url.path)
221 return "[theme.light]\nlink = \"#000001\"\ntodo = \"#000002\"\n[theme.todo]\nWAIT = \"#000005\"\n"
222 })
223 #expect(read == ["/config/themes/mine.toml"])
224 #expect(result.problems.isEmpty, "\(result.problems)")
225 #expect(result.theme.light["link"]?.hex == "#000003" && result.theme.dark["link"]?.hex == "#000003")
226 #expect(result.theme.light["todo"]?.hex == "#000002")
227 #expect(result.theme.dark["todo"] == ThemeSpec.default.dark["todo"])
228 #expect(result.theme.dark["background"]?.hex == "#000004" && result.theme.light["background"] == ThemeSpec.default.light["background"])
229 #expect(result.theme.todo["WAIT"]?.hex == "#000005")
230 }
231
232 @Test func noThemeFileIsTheDefaultWithConfigColors() throws {
233 let result = try #require(UserConfig.theme(config: "[theme]\nfont-size = 15\n", themeFile: "", in: folder) { _ in
234 Issue.record("read a theme file")
235 return nil
236 })
237 #expect(result.theme == ThemeSpec.default && result.problems.isEmpty)
238 }
239
240 @Test func problems() throws {
241 let missing = try #require(UserConfig.theme(config: "", themeFile: "gone.toml", in: folder) { _ in nil })
242 #expect(missing.problems == ["config.toml: theme-file gone.toml can't be read"])
243 let bad = try #require(UserConfig.theme(config: "[theme]\nlink = \"blue\"\n", themeFile: "t.toml", in: folder) { _ in "[theme]\nnope = \"#000000\"\n" })
244 #expect(bad.problems == ["t.toml: unknown theme color nope", "config.toml: theme.link must be a color such as \"#1f2328\""])
245 #expect(UserConfig.theme(config: "[theme", themeFile: nil, in: folder)?.theme == nil)
246 }
247
248 @Test @MainActor func chosenPalettesSitUnderTheThemeFileAndConfig() throws {
249 let defaults = TestDefaults("orgstar-palette")
250 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(defaults.name)
251 defer { try? FileManager.default.removeItem(at: folder) }
252 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
253 try "[theme.dark]\nlink = \"#000001\"\n".write(to: folder.appendingPathComponent("mine.toml"), atomically: true, encoding: .utf8)
254 try "[theme]\nlight-theme = \"paper\"\ndark-theme = \"nord\"\ntheme-file = \"mine.toml\"\n[theme.dark]\ntodo = \"#000002\"\n"
255 .write(to: folder.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
256 let sync = ConfigSync(url: folder.appendingPathComponent("config.toml"), defaults: defaults)
257 sync.start(watch: false)
258 #expect(sync.problems.isEmpty, "\(sync.problems)")
259 #expect(defaults.string(forKey: "themeLight") == "paper" && defaults.string(forKey: "themeDark") == "nord")
260 let nord = try #require(ThemeSpec.palette("nord", .dark))
261 #expect(sync.theme.light["background"] == ThemeSpec.palette("paper", .light)?.colors["background"])
262 #expect(sync.theme.dark["background"] == nord.colors["background"])
263 #expect(sync.theme.dark["link"]?.hex == "#000001")
264 #expect(sync.theme.dark["todo"]?.hex == "#000002")
265 }
266
267 @Test func noThemeSettingsGiveTheDefaultTheme() throws {
268 let folder = FileManager.default.temporaryDirectory
269 let theme = try #require(UserConfig.theme(config: "", themeFile: nil, lightTheme: nil, darkTheme: nil, in: folder))
270 #expect(theme.theme == ThemeSpec.default && theme.problems.isEmpty)
271 }
272
273 @Test func copyingAThemeNeverOverwrites() throws {
274 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-copy-\(UUID().uuidString)")
275 defer { try? FileManager.default.removeItem(at: folder) }
276 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
277 let light = try #require(ThemeSpec.palette("paper", .light))
278 let dark = try #require(ThemeSpec.palette("nord", .dark))
279 #expect(try UserConfig.copyTheme(light: light, dark: dark, to: folder))
280 let file = folder.appendingPathComponent(UserConfig.copiedThemeFile)
281 #expect(try String(contentsOf: file, encoding: .utf8) == ThemeSpec.themeFile(light: light, dark: dark))
282 try "mine".write(to: file, atomically: true, encoding: .utf8)
283 #expect(try !UserConfig.copyTheme(light: light, dark: dark, to: folder))
284 #expect(try String(contentsOf: file, encoding: .utf8) == "mine")
285 }
286
287 @Test @MainActor func aThemePickedInTheAppAppliesAtOnce() throws {
288 let defaults = TestDefaults("orgstar-pick")
289 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(defaults.name)
290 defer { try? FileManager.default.removeItem(at: folder) }
291 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
292 try "[theme]\n".write(to: folder.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8)
293 let sync = ConfigSync(url: folder.appendingPathComponent("config.toml"), defaults: defaults)
294 sync.start(watch: false)
295 defaults.set("nord", forKey: "themeDark")
296 sync.writeBack()
297 #expect(try String(contentsOf: folder.appendingPathComponent("config.toml"), encoding: .utf8).contains("dark-theme = \"nord\""))
298 #expect(sync.theme.dark["background"] == ThemeSpec.palette("nord", .dark)?.colors["background"])
299 }
300
301 @Test func sandboxIgnoresEnvironmentFoldersOutsideTheContainer() {
302 let home = "/Users/me/Library/Containers/sh.krz.orgstar/Data"
303 let outside = ["XDG_CONFIG_HOME": "/Users/me/.config", "ORGSTAR_CONFIG_DIR": "/Users/me/orgstar"]
304 #expect(UserConfig.defaultDirectory(environment: outside, home: home, sandboxed: true).path == home + "/.config/orgstar")
305 #expect(UserConfig.defaultDirectory(environment: outside, home: home, sandboxed: false).path == "/Users/me/orgstar")
306 #expect(UserConfig.defaultDirectory(environment: ["XDG_CONFIG_HOME": "/Users/me/.config"], home: home, sandboxed: false).path == "/Users/me/.config/orgstar")
307 let inside = ["XDG_CONFIG_HOME": home + "/xdg"]
308 #expect(UserConfig.defaultDirectory(environment: inside, home: home, sandboxed: true).path == home + "/xdg/orgstar")
309 }
310}