SPB Git

Repository Public MIT

StudioModelTests.swift 14.2 KB 280 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/KitTests/StudioModelTests.swift8// Module           : GlassStudio9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SwiftUI43import Testing44import SPGlassKit45@testable import GlassStudioKit4647@Suite("Swift literals")48struct SwiftLiteralTests {49    @Test func stringsCannotEscapeTheirLiteral() {50        #expect(SwiftLiteral.string("Save") == "\"Save\"")51        #expect(SwiftLiteral.string("a\"); exit(0); (\"") == #""a\"); exit(0); (\"""#)52        #expect(SwiftLiteral.string("\\(secret)") == #""\\(secret)""#)53        #expect(SwiftLiteral.string("line\nbreak\u{2028}") == #""line\nbreak\u{2028}""#)54        #expect(SwiftLiteral.string("日本語 🎛️ é") == "\"日本語 🎛️ é\"")55    }5657    @Test func numbersAreLocaleIndependentAndFinite() {58        #expect(SwiftLiteral.number(12) == "12")59        #expect(SwiftLiteral.number(0.5) == "0.5")60        #expect(SwiftLiteral.number(0.125) == "0.125")61        #expect(SwiftLiteral.number(.nan) == "0" && SwiftLiteral.number(.infinity) == "0")62        #expect(SwiftLiteral.number(-3) == "-3")63    }6465    @Test func enumCasesMustBeIdentifiers() {66        #expect(SwiftLiteral.enumCase("prominent", fallback: "regular") == ".prominent")67        #expect(SwiftLiteral.enumCase("x) ; exit(0) //", fallback: "regular") == ".regular")68        #expect(SwiftLiteral.enumCase("", fallback: "regular") == ".regular")69        #expect(!SwiftLiteral.isIdentifier("1abc") && !SwiftLiteral.isIdentifier("a-b") && SwiftLiteral.isIdentifier("_a1"))70    }7172    @Test func coloursAndIndentation() {73        #expect(SwiftLiteral.color(GlassRGBA(rgb: 0xFF0000)) == "Color(red: 1, green: 0, blue: 0)")74        #expect(SwiftLiteral.color(GlassRGBA(red: 0, green: 0, blue: 0, alpha: 0.5)) == "Color(red: 0, green: 0, blue: 0, opacity: 0.5)")75        #expect(SwiftLiteral.indent("a\n\nb", levels: 2) == "        a\n\n        b")76    }77}7879@Suite("Inspector fields")80struct InspectorFieldTests {81    let fields: [InspectorField] = [82        .toggle("on", "On", default: true),83        .choice("variant", "Variant", options: [.init("regular", "Regular"), .init("prominent", "Prominent")]),84        .number("count", "Count", in: 1...5, step: 1, default: 3),85        .number("ratio", "Ratio", in: 0...1, step: 0.25, default: 0.5),86        .text("title", "Title", default: "Hello", maxLength: 8),87        .color("tint", "Tint", default: .white),88        .size(),89    ]9091    @Test func defaultsAreUsedUntilAValueIsSet() {92        let values = InspectorValues(fields: fields)93        #expect(values.bool("on") && values.choice("variant") == "regular" && values.number("count") == 3)94        #expect(values.text("title") == "Hello" && values.color("tint") == .white && values.size() == .regular)95        #expect(values.isDefault)96    }9798    @Test func valuesAreValidatedOnWrite() {99        var values = InspectorValues(fields: fields)100        values["count"] = .number(99); #expect(values.number("count") == 5)101        values["count"] = .number(-4); #expect(values.number("count") == 1)102        values["count"] = .number(2.6); #expect(values.number("count") == 3)103        values["count"] = .number(.nan); #expect(values.number("count") == 3)104        values["ratio"] = .number(0.6); #expect(values.number("ratio") == 0.5)105        values["variant"] = .choice("nope"); #expect(values.choice("variant") == "regular")106        values["variant"] = .choice("prominent"); #expect(values.choice("variant") == "prominent")107        values["title"] = .text("A very long title"); #expect(values.text("title") == "A very l")108        values["title"] = .text("a\u{0}b\u{7}"); #expect(values.text("title") == "ab")109        values["on"] = .text("yes"); #expect(values.bool("on"), "a value of the wrong type falls back to the default")110        values["unknown"] = .bool(true); #expect(values["unknown"] == nil)111        #expect(!values.isDefault)112        values.reset(); #expect(values.isDefault)113    }114115    @Test func untrustedStoredValuesAreValidatedOnRead() {116        let values = InspectorValues(fields: fields, values: ["count": .number(1e9), "variant": .bool(true), "ghost": .text("x")])117        #expect(values.number("count") == 5 && values.choice("variant") == "regular" && values.dictionary["ghost"] == nil)118    }119}120121@Suite("Catalogue search")122struct CatalogFilterTests {123    @Test func queryMatchesNameCategoryKindAndSummaryIgnoringCaseAndAccents() throws {124        let button = try #require(GlassComponentCatalog.component(id: "glass-button"))125        var filter = CatalogFilter()126        #expect(filter.matches(button) && !filter.isActive)127        for query in ["button", "BUTTON", "bütton", "glass-button", "buttons native", "loading states", "SPGlassComponents"] {128            filter.query = query129            #expect(filter.matches(button), "\(query)")130        }131        filter.query = "button map"132        #expect(!filter.matches(button), "every word must match")133    }134135    @Test func facetsCombine() throws {136        let all = GlassComponentCatalog.all137        var filter = CatalogFilter()138        filter.category = .navigation139        #expect(all.filter { filter.matches($0) }.count == 5)140        filter.kind = .customGlass141        #expect(all.filter { filter.matches($0) }.map(\.id) == ["glass-breadcrumb"])142        filter = CatalogFilter()143        filter.favoritesOnly = true144        #expect(all.filter { filter.matches($0, isFavorite: $0.id == "glass-toast") }.map(\.id) == ["glass-toast"])145        filter = CatalogFilter()146        filter.platform = .macOS147        #expect(all.filter { filter.matches($0) }.count == 50)148    }149}150151@Suite("Preview configuration")152struct PreviewConfigurationTests {153    @Test func defaultsFollowTheSystemAndSimulateNothing() {154        let configuration = PreviewConfiguration()155        #expect(!configuration.hasSimulations && configuration.colorScheme == nil && configuration.dynamicTypeSize == nil)156        #expect(configuration.theme(from: .ocean) == .ocean)157    }158159    @Test func overridesAreAppliedToTheThemeAndEnvironment() {160        var configuration = PreviewConfiguration()161        configuration.density = .compact162        configuration.appearance = .dark163        configuration.textSizeIndex = 99164        #expect(configuration.theme(from: .ocean).density == .compact && configuration.colorScheme == .dark)165        #expect(configuration.dynamicTypeSize == nil, "an out-of-range index is ignored")166        configuration.textSizeIndex = PreviewConfiguration.textSizes.count - 1167        #expect(configuration.dynamicTypeSize == .accessibility5 && configuration.hasSimulations)168    }169}170171@Suite("Theme editing history")172struct ThemeEditHistoryTests {173    @Test func undoRedoAndReset() {174        var history = ThemeEditHistory(.crystal)175        #expect(!history.canUndo && !history.isModified)176        history.apply { $0.radii.medium = 4 }177        history.apply { $0.density = .compact }178        history.apply { $0.density = .compact }179        #expect(history.current.radii.medium == 4 && history.isModified)180        history.undo(); #expect(history.current.density == .regular && history.canRedo)181        history.undo(); #expect(history.current == .crystal && !history.canUndo)182        history.redo(); history.redo(); #expect(history.current.density == .compact && !history.canRedo)183        history.undo()184        history.apply { $0.name = "Mine" }185        #expect(!history.canRedo, "a new edit clears the redo stack")186        history.reset(); #expect(history.current == .crystal)187        history.undo(); #expect(history.current.name == "Mine", "reset can be undone")188    }189190    @Test func historyIsBounded() {191        var history = ThemeEditHistory(.crystal)192        for index in 0..<(ThemeEditHistory.limit + 50) { history.apply { $0.spacing.md = Double(index % 100) + 0.5 } }193        var undone = 0194        while history.canUndo { history.undo(); undone += 1 }195        #expect(undone == ThemeEditHistory.limit)196    }197}198199@Suite("Stores")200@MainActor201struct StoreTests {202    func directory() throws -> URL {203        let url = FileManager.default.temporaryDirectory.appendingPathComponent("glassstudio-tests-\(UUID().uuidString)")204        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)205        return url206    }207208    @Test func customThemesPersistAndBuiltInsAreProtected() throws {209        let directory = try directory(); defer { try? FileManager.default.removeItem(at: directory) }210        let store = ThemeStore(directory: directory)211        #expect(store.customThemes.isEmpty && store.allThemes.count == 13)212        #expect(!store.save(.aurora), "a built-in theme cannot be overwritten")213        var copy = try #require(store.duplicate(.aurora))214        #expect(copy.id == "custom-aurora" && store.isCustom(copy.id))215        copy.radii.medium = 3216        #expect(store.save(copy))217        #expect(store.duplicate(.aurora)?.id == "custom-aurora-2")218        var invalid = copy; invalid.spacing.md = 9999219        #expect(!store.save(invalid) && store.lastError == "invalid")220221        let reloaded = ThemeStore(directory: directory)222        #expect(reloaded.customThemes.count == 2 && reloaded.theme("custom-aurora")?.radii.medium == 3)223        reloaded.delete("custom-aurora-2")224        #expect(ThemeStore(directory: directory).customThemes.map(\.id) == ["custom-aurora"])225    }226227    @Test func importNeverReplacesAnExistingTheme() throws {228        let directory = try directory(); defer { try? FileManager.default.removeItem(at: directory) }229        let store = ThemeStore(directory: directory)230        let imported = try store.importTheme(from: GlassThemeCodec.encode(.ocean))231        #expect(imported.id == "custom-ocean" && store.theme("ocean") == .ocean)232        #expect(try store.importTheme(from: GlassThemeCodec.encode(.ocean)).id == "custom-ocean-2")233        #expect(throws: GlassThemeError.self) { try store.importTheme(from: Data("{".utf8)) }234        #expect(throws: GlassThemeError.self) { try store.importTheme(from: Data(repeating: 0x20, count: GlassThemeCodec.maximumBytes + 1)) }235        #expect(store.customThemes.count == 2)236    }237238    @Test func aCorruptedLibraryIsQuarantinedAndTheBackupRestored() throws {239        let directory = try directory(); defer { try? FileManager.default.removeItem(at: directory) }240        let store = ThemeStore(directory: directory)241        _ = store.duplicate(.aurora)242        _ = store.duplicate(.ocean)   // the second save keeps the first state as backup243        let file = directory.appendingPathComponent("themes.json")244        try Data("{ this is not json".utf8).write(to: file)245246        let recovered = ThemeStore(directory: directory)247        #expect(recovered.recoveryNotice?.hasPrefix("recovered:") == true)248        #expect(recovered.customThemes.map(\.id) == ["custom-aurora"], "the state of the backup is restored")249        let quarantined = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.contains("corrupted") }250        #expect(quarantined.count == 1, "the unreadable file is kept for inspection, not deleted")251        recovered.acknowledgeRecovery(); #expect(recovered.recoveryNotice == nil)252253        try Data("garbage".utf8).write(to: file)254        try Data("garbage".utf8).write(to: file.appendingPathExtension("bak"))255        let reset = ThemeStore(directory: directory)256        #expect(reset.recoveryNotice?.hasPrefix("reset:") == true && reset.customThemes.isEmpty)257        #expect(reset.duplicate(.solar) != nil, "the store is usable after a reset")258    }259260    @Test func libraryMigrationSkipsInvalidEntriesAndRefusesNewerSchemas() throws {261        let legacy = ##"{"items":[{"id":"mine","name":"Mine","colors":{"primary":"#112233"}},{"id":"Bad ID","name":"x"},{"id":"mine","name":"Duplicate"},42]}"##262        let document = try ThemeStore.migrate(Data(legacy.utf8))263        #expect(document.themes.map(\.id) == ["mine"] && document.themes[0].light[.primary] == GlassRGBA(rgb: 0x112233))264        #expect(throws: GlassThemeError.unsupportedSchema(7)) { try ThemeStore.migrate(Data(#"{"schemaVersion":7,"themes":[]}"#.utf8)) }265        #expect(throws: (any Error).self) { try ThemeStore.migrate(Data("[]".utf8)) }266    }267268    @Test func favouritesPersistAndIgnoreUnknownComponents() throws {269        let directory = try directory(); defer { try? FileManager.default.removeItem(at: directory) }270        let store = FavoritesStore(directory: directory)271        store.toggle("glass-button"); store.toggle("glass-toast"); store.toggle("not-a-component")272        #expect(store.componentIDs == ["glass-button", "glass-toast"])273        store.move(fromOffsets: IndexSet(integer: 1), toOffset: 0)274        store.toggle("glass-button")275        #expect(FavoritesStore(directory: directory).componentIDs == ["glass-toast"])276        try Data(#"{"schemaVersion":1,"componentIDs":["glass-card","removed-component"]}"#.utf8).write(to: directory.appendingPathComponent("favorites.json"))277        #expect(FavoritesStore(directory: directory).componentIDs == ["glass-card"])278    }279}280
Files main
Menu

Theme