Tests/OrgAppTests/UserConfigTests.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Tests/OrgAppTests/UserConfigTests.swift history · blame · raw

243 lines · 14773 bytes

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