SPB Git

Repository Public

StoreTests.swift 8.2 KB 162 lines swift

1import Foundation2import Testing3import SettingsModel4import WorkspaceKit5@testable import SessionStore67func tempRoot() -> StoreLocations {8    StoreLocations(root: FileManager.default.temporaryDirectory.appendingPathComponent("spterm-tests-\(UUID().uuidString)"))9}1011func permissions(_ url: URL) -> Int {12    ((try? FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions]) as? NSNumber)?.intValue ?? -113}1415@Suite("Versioned stores")16struct StoreTests {17    @Test func settingsRoundTripWithOwnerOnlyPermissions() throws {18        let locations = tempRoot()19        defer { try? FileManager.default.removeItem(at: locations.root) }20        try locations.prepare()21        let stores = SessionStores(locations: locations)22        if case .missing = stores.settings.load() {} else { Issue.record("expected missing") }23        var settings = AppSettings()24        settings.fontSize = 1525        settings.keyBindings["palette"] = KeyChord("cmd+k")26        try stores.settings.save(settings)27        #expect(stores.settings.load().value == settings)28        #expect(permissions(locations.settings) == 0o600)29        #expect(permissions(locations.root) == 0o700)30        // No temporary file is left behind.31        let leftovers = try FileManager.default.contentsOfDirectory(atPath: locations.root.path).filter { $0.hasSuffix(".tmp") }32        #expect(leftovers.isEmpty)33    }3435    @Test func corruptFileIsSetAsideNotDeleted() throws {36        let locations = tempRoot()37        defer { try? FileManager.default.removeItem(at: locations.root) }38        try locations.prepare()39        try Data("{ this is not json".utf8).write(to: locations.settings)40        let stores = SessionStores(locations: locations)41        guard case .recovered(let backup, _) = stores.settings.load() else { Issue.record("expected recovery"); return }42        #expect(backup != nil)43        #expect(FileManager.default.fileExists(atPath: backup!.path))44        #expect(!FileManager.default.fileExists(atPath: locations.settings.path))45        // The app keeps working with defaults and can save again.46        try stores.settings.save(AppSettings())47        #expect(stores.settings.load().value == AppSettings())48    }4950    @Test func newerSchemaIsRefusedAndPreserved() throws {51        let locations = tempRoot()52        defer { try? FileManager.default.removeItem(at: locations.root) }53        try locations.prepare()54        try Data(#"{"schemaVersion": 99, "payload": {}}"#.utf8).write(to: locations.settings)55        let outcome = SessionStores(locations: locations).settings.load()56        guard case .recovered(let backup, let reason) = outcome else { Issue.record("expected recovery"); return }57        #expect(reason.contains("newerSchema"))58        #expect(backup != nil)59    }6061    @Test func migrationFromV1WindowsArray() throws {62        let locations = tempRoot()63        defer { try? FileManager.default.removeItem(at: locations.root) }64        try locations.prepare()65        let window = WindowModel(tabs: [TabModel(single: PaneDescriptor(workingDirectory: "/tmp"))])66        let windowsJSON = try JSONSerialization.jsonObject(with: JSONEncoder().encode([window]))67        let v1 = try JSONSerialization.data(withJSONObject: ["schemaVersion": 1, "payload": windowsJSON])68        try v1.write(to: locations.lastSession)69        let restored = SessionStores(locations: locations).loadLastSession()70        #expect(restored?.windows.count == 1)71        #expect(restored?.windows[0].tabs[0].panes[0].workingDirectory == "/tmp")72        #expect(restored?.name == "Last Session")73    }7475    @Test func lastSessionRepairsDamagedTabs() throws {76        let locations = tempRoot()77        defer { try? FileManager.default.removeItem(at: locations.root) }78        let stores = SessionStores(locations: locations)79        let good = PaneDescriptor()80        let ghost = PaneID()81        let damaged = TabModel(layout: .split(id: UUID(), axis: .horizontal, fractions: [0.5, 0.5], children: [.pane(good.id), .pane(ghost)]),82                               panes: [good], focusedPane: ghost)83        let emptyWindow = WindowModel(tabs: [])84        try stores.lastSession.save(WorkspaceSnapshot(name: "x", windows: [WindowModel(tabs: [damaged], selectedTab: TabID()), emptyWindow]))85        let restored = stores.loadLastSession()86        #expect(restored?.windows.count == 1)87        #expect(restored?.windows[0].tabs[0].isConsistent == true)88        #expect(restored?.windows[0].selectedTab == restored?.windows[0].tabs[0].id)89    }9091    @Test func settingsDecodingToleratesUnknownAndInvalidValues() throws {92        let json = #"{"fontSize": 900, "appearance": "sepia", "futureOption": true, "scrollbackLines": -4, "darkThemeID": "nope", "backgroundOpacity": 0.01}"#93        let settings = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))94        #expect(settings.fontSize == 72)95        #expect(settings.appearance == .system)96        #expect(settings.scrollbackLines == 0)97        #expect(settings.darkThemeID == "sp-graphite")98        #expect(settings.backgroundOpacity == 0.3)99        // Safe defaults for everything sensitive.100        let defaults = AppSettings()101        #expect(defaults.clipboardRead == .deny)102        #expect(defaults.clipboardWrite == .ask)103        #expect(defaults.pasteConfirmation == .multiline)104        #expect(!defaults.recordHistory)105        #expect(!defaults.assistantEnabled)106        #expect(defaults.confirmCloseRunning)107    }108109    @Test func snippetVariablesAndRendering() {110        let snippet = Snippet(name: "t", template: "tail -n {{lines:200}} -f {{file}} # {{ file }}")111        #expect(snippet.variables == [SnippetVariable(name: "lines", defaultValue: "200"), SnippetVariable(name: "file", defaultValue: "")])112        #expect(snippet.render(["file": "/var/log/my app.log"]) == "tail -n 200 -f '/var/log/my app.log' # '/var/log/my app.log'")113        // Values cannot break out of their quotes.114        let hostile = snippet.render(["file": "x'; rm -rf ~; echo '"])115        #expect(hostile.contains(#"'x'\''; rm -rf ~; echo '\'''"#))116        #expect(Snippet.shellQuoted("") == "''")117        #expect(Snippet.shellQuoted("plain-word_1.txt") == "plain-word_1.txt")118    }119120    @Test func historyIsOptInPrivateAndBounded() {121        let locations = tempRoot()122        defer { try? FileManager.default.removeItem(at: locations.root) }123        let history = HistoryStore(url: locations.history, maximumEntries: 20)124        let entry = HistoryEntry(command: "export API_TOKEN=abc123", source: "snippet")125        #expect(!history.append(entry, enabled: false, privateMode: false))126        #expect(!history.append(entry, enabled: true, privateMode: true))127        #expect(!FileManager.default.fileExists(atPath: locations.history.path))128        #expect(history.append(entry, enabled: true, privateMode: false, redact: { _ in "export API_TOKEN=[REDACTED]" }))129        #expect(history.entries().first?.command == "export API_TOKEN=[REDACTED]")130        #expect(permissions(locations.history) == 0o600)131        for index in 0..<60 { history.append(HistoryEntry(command: "cmd \(index)", source: "palette"), enabled: true, privateMode: false) }132        #expect(history.entries().count <= 22)133        #expect(history.entries().last?.command == "cmd 59")134        #expect(history.search("cmd 5").count >= 1)135        history.clear()136        #expect(history.entries().isEmpty)137    }138}139140@Suite("Key chords")141struct KeyChordTests {142    @Test func parsingAndFormatting() {143        #expect(KeyChord("cmd+shift+p") == KeyChord("p", [.command, .shift]))144        #expect(KeyChord("⌘⇧P") == KeyChord("p", [.command, .shift]))145        #expect(KeyChord("ctrl+opt+left")?.symbolic == "⌃⌥←")146        #expect(KeyChord("cmd++")?.key == "+")147        #expect(KeyChord("cmd+f5")?.key == "f5")148        #expect(KeyChord("cmd+shift") == nil)149        #expect(KeyChord("cmd+a+b") == nil)150        #expect(KeyChord("") == nil)151        #expect(KeyChord("cmd+notakey") == nil)152        #expect(KeyChord("p", [.command, .shift]).description == "shift+cmd+p")153    }154155    @Test func codable() throws {156        let chord = KeyChord("d", [.command, .shift])157        let data = try JSONEncoder().encode([chord])158        #expect(String(decoding: data, as: UTF8.self) == #"["shift+cmd+d"]"#)159        #expect(try JSONDecoder().decode([KeyChord].self, from: data) == [chord])160    }161}162
Files main
Menu

Theme