Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Tests/SPGlassThemesTests/GlassThemeTests.swift8// Module : SPGlassThemesTests9// 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 SPGlassCore45import SPGlassTokens46@testable import SPGlassThemes4748@Suite("Built-in themes")49struct BuiltInThemeTests {50 static let designed = GlassTheme.builtIn.filter { $0.id != "system" }5152 @Test func catalogueHoldsSystemAndTheSevenDesignedThemes() {53 #expect(GlassTheme.builtIn.map(\.id.rawValue) == ["system", "crystal", "obsidian", "aurora", "emerald", "solar", "ocean", "neon"])54 #expect(GlassTheme.examples.count == 5)55 #expect(Set((GlassTheme.builtIn + GlassTheme.examples).map(\.id)).count == 13)56 }5758 @Test("Every built-in and example theme passes validation without error", arguments: GlassTheme.builtIn + GlassTheme.examples)59 func valid(theme: GlassTheme) {60 #expect(GlassThemeValidator.validate(theme).filter { $0.severity == .error }.isEmpty)61 }6263 @Test("Designed themes define all twelve roles in light and dark", arguments: designed)64 func complete(theme: GlassTheme) {65 #expect(theme.light.definedTokens == GlassColorToken.allCases)66 #expect(theme.dark.definedTokens == GlassColorToken.allCases)67 }6869 @Test("Designed themes reach AA text contrast in light and dark, with no warning", arguments: designed)70 func contrast(theme: GlassTheme) {71 let warnings = GlassThemeValidator.validate(theme).filter { $0.severity == .warning }72 #expect(warnings.isEmpty, "\(theme.id): \(warnings.map(\.message))")73 for palette in [theme.light, theme.dark] {74 let text = palette[.textPrimary]!, background = palette[.background]!75 #expect(text.contrastRatio(against: background) >= 7, "\(theme.id) primary text should reach AAA on background")76 }77 }7879 @Test("Light palettes are light and dark palettes are dark", arguments: designed)80 func polarity(theme: GlassTheme) {81 #expect(theme.light[.background]!.relativeLuminance > 0.7)82 #expect(theme.dark[.background]!.relativeLuminance < 0.05)83 }8485 @Test func systemThemeLeavesEveryRoleToTheSystem() {86 #expect(GlassTheme.system.light.isEmpty && GlassTheme.system.dark.isEmpty)87 let resolved = GlassThemeResolver.resolve(.system, colorScheme: .dark)88 for token in GlassColorToken.allCases {89 #expect(resolved.rgba(token) == nil)90 #expect(resolved.color(token) == GlassSystemColors.color(for: token))91 }92 }9394 @Test func exampleThemesAreLabelledAndOnlySetBrandRoles() {95 for theme in GlassTheme.examples {96 #expect(theme.name.hasSuffix("(example)"))97 #expect(theme.id.rawValue.hasPrefix("example-"))98 #expect(theme.light.definedTokens == [.primary, .accent, .focusRing])99 #expect(theme.summary.contains("Not the product's actual brand colours"))100 }101 }102}103104@Suite("Theme resolution")105struct GlassThemeResolverTests {106 @Test("Resolution picks the palette of the colour scheme", arguments: [ColorScheme.light, .dark])107 func scheme(scheme: ColorScheme) {108 let resolved = GlassThemeResolver.resolve(.ocean, colorScheme: scheme)109 #expect(resolved.isDark == (scheme == .dark))110 #expect(resolved.rgba(.background) == (scheme == .dark ? GlassTheme.ocean.dark : GlassTheme.ocean.light)[.background])111 }112113 @Test func forcedAppearanceWinsOverTheColourScheme() {114 var theme = GlassTheme.crystal115 theme.appearance = .dark116 #expect(GlassThemeResolver.resolve(theme, colorScheme: .light).isDark)117 theme.appearance = .light118 #expect(!GlassThemeResolver.resolve(theme, colorScheme: .dark).isDark)119 }120121 @Test func densityScalesSpacingOnly() {122 var theme = GlassTheme.crystal123 theme.density = .comfortable124 let resolved = GlassThemeResolver.resolve(theme, colorScheme: .light)125 #expect(resolved.spacing.md == 19)126 #expect(resolved.radii == theme.radii)127 }128129 @Test func increasedContrastStrengthensSecondaryTextAndSeparators() {130 let standard = GlassThemeResolver.resolve(.crystal, colorScheme: .light)131 let increased = GlassThemeResolver.resolve(.crystal, colorScheme: .light, contrast: .increased)132 #expect(standard.rgba(.textSecondary) != standard.rgba(.textPrimary))133 #expect(increased.rgba(.textSecondary) == increased.rgba(.textPrimary))134 #expect(increased.rgba(.separator) == increased.rgba(.textPrimary))135 #expect(increased.rgba(.primary) == standard.rgba(.primary))136 }137138 @Test("Text drawn on a fill is the more legible of white and near-black", arguments: BuiltInThemeTests.designed)139 func onColour(theme: GlassTheme) {140 for scheme in [ColorScheme.light, .dark] {141 let resolved = GlassThemeResolver.resolve(theme, colorScheme: scheme)142 for token in [GlassColorToken.primary, .accent, .destructive] {143 let fill = resolved.rgba(token)!144 let chosen = resolved.onColor(token) == .white ? GlassRGBA.white : GlassRGBA(rgb: 0x0B0B0F)145 #expect(chosen.contrastRatio(against: fill) >= 4.5, "\(theme.id) \(token) \(scheme)")146 }147 }148 }149150 @Test func glassTintFollowsTheThemeToken() {151 #expect(GlassThemeResolver.resolve(.crystal, colorScheme: .light).glassTint == nil)152 let aurora = GlassThemeResolver.resolve(.aurora, colorScheme: .light)153 #expect(aurora.glassTint == aurora.color(.primary))154 }155156 @Test func platformDrivesMetrics() {157 #expect(GlassThemeResolver.resolve(.system, colorScheme: .light, platform: .macOS).metrics.minimumHitTarget == 24)158 #expect(GlassThemeResolver.resolve(.system, colorScheme: .light, platform: .iOS).metrics.minimumHitTarget == 44)159 }160161 @Test func reduceMotionShortensAnimations() {162 var theme = GlassTheme.neon163 theme.motion.slow = 1.2164 let resolved = GlassThemeResolver.resolve(theme, colorScheme: .dark)165 #expect(resolved.animation(.slow, reduceMotion: true) == .easeInOut(duration: 0.2))166 #expect(resolved.animation(.slow, reduceMotion: false) == .bouncy(duration: 1.2))167 }168}169170@Suite("Theme inheritance and overrides")171@MainActor172struct GlassThemeEnvironmentTests {173 @Test func defaultEnvironmentThemeIsSystem() {174 #expect(EnvironmentValues().glassTheme == .system)175 }176177 @Test func settingTheEnvironmentReplacesTheTheme() {178 var environment = EnvironmentValues()179 environment.glassTheme = .aurora180 #expect(environment.glassTheme.id == "aurora")181 }182183 @Test func overrideChangesOnlyWhatItTouches() {184 let overridden = GlassThemeOverride.apply({ $0.radii.medium = 4; $0.density = .compact }, to: .ocean)185 #expect(overridden.radii.medium == 4 && overridden.density == .compact)186 #expect(overridden.light == GlassTheme.ocean.light && overridden.id == GlassTheme.ocean.id)187 #expect(GlassTheme.ocean.radii.medium == 14, "the inherited theme is a value and is not mutated")188 }189190 @Test func nestedOverridesCompose() {191 let outer = GlassThemeOverride.apply({ $0.glass.tint = .accent }, to: .crystal)192 let inner = GlassThemeOverride.apply({ $0.typography.design = .serif }, to: outer)193 #expect(inner.glass.tint == .accent && inner.typography.design == .serif)194 }195196 @Test func hotSwapProducesADifferentResolvedTheme() {197 let before = GlassThemeResolver.resolve(.crystal, colorScheme: .light)198 let after = GlassThemeResolver.resolve(.neon, colorScheme: .light)199 #expect(before != after)200 #expect(before.color(.primary) != after.color(.primary))201 #expect(before == GlassThemeResolver.resolve(.crystal, colorScheme: .light), "resolution is deterministic")202 }203}204205@Suite("Theme files")206struct GlassThemeCodecTests {207 @Test("Round trip keeps every field", arguments: GlassTheme.builtIn + GlassTheme.examples)208 func roundTrip(theme: GlassTheme) throws {209 let data = try GlassThemeCodec.encode(theme)210 #expect(try GlassThemeCodec.decode(data) == theme)211 }212213 @Test func encodingIsStable() throws {214 #expect(try GlassThemeCodec.encode(.aurora) == GlassThemeCodec.encode(.aurora))215 let text = String(decoding: try GlassThemeCodec.encode(.aurora), as: UTF8.self)216 #expect(text.contains("\"schemaVersion\" : 1"))217 #expect(text.contains("\"primary\" : \"#4F46E5\""))218 }219220 @Test func minimalFileUsesDefaults() throws {221 let theme = try GlassThemeCodec.decode(Data(##"{"id":"mine","name":"Mine"}"##.utf8))222 #expect(theme.spacing == .standard && theme.appearance == .system && theme.light.isEmpty)223 #expect(theme.schemaVersion == GlassKitInfo.schemaVersion)224 }225226 @Test func version0FilesAreMigrated() throws {227 let legacy = ##"{"schemaVersion":0,"id":"old","name":"Old","colors":{"primary":"#112233"},"cornerRadius":10}"##228 let theme = try GlassThemeCodec.decode(Data(legacy.utf8))229 #expect(theme.schemaVersion == 1)230 #expect(theme.light[.primary] == GlassRGBA(rgb: 0x112233) && theme.dark[.primary] == GlassRGBA(rgb: 0x112233))231 #expect(theme.radii == GlassRadii(small: 5, medium: 10, large: 15, extraLarge: 20))232 }233234 @Test func unversionedLegacyFileIsDetectedByItsColorsField() throws {235 let theme = try GlassThemeCodec.decode(Data(##"{"id":"old","name":"Old","colors":{"accent":"#FF0080"}}"##.utf8))236 #expect(theme.light[.accent] == GlassRGBA(rgb: 0xFF0080))237 }238239 @Test func newerSchemaIsRefused() {240 #expect(throws: GlassThemeError.unsupportedSchema(99)) {241 try GlassThemeCodec.decode(Data(##"{"schemaVersion":99,"id":"x","name":"X"}"##.utf8))242 }243 }244245 @Test("Malformed input is refused with a structured error", arguments: [246 "", "[]", "\"text\"", "{", ##"{"name":"No id"}"##, ##"{"id":"x","name":"X","light":{"primary":"blue"}}"##,247 ##"{"id":"x","name":"X","light":{"refraction":"#FFFFFF"}}"##, ##"{"id":"x","name":"X","density":"huge"}"##,248 ##"{"id":"x","name":"X","schemaVersion":"1"}"##, ##"{"id":"x","name":"X","spacing":{"md":"wide"}}"##,249 ])250 func malformed(json: String) {251 #expect(throws: GlassThemeError.self) { try GlassThemeCodec.decode(Data(json.utf8)) }252 }253254 @Test("Invalid values are refused", arguments: [255 ##"{"id":"Bad ID","name":"X"}"##, ##"{"id":"x","name":" "}"##, ##"{"id":"x","name":"X","spacing":{"md":900}}"##,256 ##"{"id":"x","name":"X","radii":{"large":-3}}"##, ##"{"id":"x","name":"X","motion":{"slow":30}}"##, ##"{"id":"../x","name":"X"}"##,257 ])258 func invalid(json: String) {259 #expect {260 try GlassThemeCodec.decode(Data(json.utf8))261 } throws: { error in262 if case GlassThemeError.invalid = error { true } else { false }263 }264 }265266 @Test func oversizedInputIsRefusedBeforeParsing() {267 let data = Data(repeating: 0x20, count: GlassThemeCodec.maximumBytes + 1)268 #expect(throws: GlassThemeError.tooLarge(bytes: data.count, limit: GlassThemeCodec.maximumBytes)) { try GlassThemeCodec.decode(data) }269 }270271 @Test func deeplyNestedInputIsRefused() {272 let nested = String(repeating: "{\"a\":", count: 12) + "1" + String(repeating: "}", count: 12)273 #expect(throws: GlassThemeError.tooDeep(limit: GlassThemeCodec.maximumDepth)) { try GlassThemeCodec.decode(Data(nested.utf8)) }274 }275}276277@Suite("Theme validation")278struct GlassThemeValidatorTests {279 @Test func lowContrastTextIsReportedAsAWarning() {280 var theme = GlassTheme.crystal281 theme.light[.textSecondary] = GlassRGBA(rgb: 0xD1D5DB)282 let issues = GlassThemeValidator.validate(theme)283 #expect(issues.contains { $0.code == .lowTextContrast && $0.severity == .warning })284 #expect(GlassThemeValidator.isUsable(theme), "warnings never block a theme")285 }286287 @Test func translucentTextIsFlaggedBecauseItsContrastDependsOnTheBackdrop() {288 var theme = GlassTheme.crystal289 theme.dark[.textPrimary] = GlassRGBA.white.opacity(0.7)290 #expect(GlassThemeValidator.validate(theme).contains { $0.code == .translucentText })291 }292293 @Test func systemRolesAreNotJudged() {294 #expect(GlassThemeValidator.validate(.system).isEmpty)295 }296297 @Test func identifierRules() {298 #expect(GlassThemeID("lou-ka-2").isValid)299 for bad in ["", "A", "a b", "-a", "a-", "é", "a/b", String(repeating: "a", count: 65)] {300 #expect(!GlassThemeID(bad).isValid, "\(bad)")301 }302 }303304 @Test func descendingSpacingIsAWarning() {305 var theme = GlassTheme.crystal306 theme.spacing.lg = 2307 #expect(GlassThemeValidator.validate(theme).contains { $0.code == .spacingNotAscending && $0.severity == .warning })308 }309}310311@Suite("Swift export")312struct GlassThemeSwiftExporterTests {313 @Test func stringLiteralsAreEscaped() {314 #expect(GlassThemeSwiftExporter.literal("a\"b\\c\nd") == #""a\"b\\c\nd""#)315 #expect(GlassThemeSwiftExporter.literal("\u{2028}x\u{07}") == #""\u{2028}x\u{7}""#)316 #expect(GlassThemeSwiftExporter.literal("Été — 日本 🎨") == "\"Été — 日本 🎨\"")317 #expect(GlassThemeSwiftExporter.literal(#"\(exit(1))"#) == #""\\(exit(1))""#)318 }319320 @Test func propertyNamesAreValidIdentifiers() {321 #expect(GlassThemeSwiftExporter.propertyName(for: "example-lou-ka") == "exampleLouKa")322 #expect(GlassThemeSwiftExporter.propertyName(for: "2026-edition") == "theme2026Edition")323 #expect(GlassThemeSwiftExporter.propertyName(for: "default") == "`default`")324 #expect(GlassThemeSwiftExporter.propertyName(for: "---") == "customTheme")325 #expect(GlassThemeSwiftExporter.propertyName(for: "custom-aurora") == "customAurora")326 for theme in GlassTheme.builtIn {327 let name = GlassThemeSwiftExporter.propertyName(for: theme.id)328 #expect(name == theme.id.rawValue + "Theme", "an export of a built-in theme must not redeclare GlassTheme.\(theme.id)")329 }330 }331332 @Test func exportContainsEveryDefinedColour() {333 let source = GlassThemeSwiftExporter.source(for: .aurora)334 #expect(source.contains("static let auroraTheme = GlassTheme("))335 #expect(source.contains(".primary: GlassRGBA(rgb: 0x4F46E5)"))336 #expect(source.contains("import SPGlassKit"))337 #expect(source.contains("glass: GlassMaterialTokens(variant: .regular, tint: .primary)"))338 #expect(source.contains("design: .rounded"))339 #expect(!GlassThemeSwiftExporter.source(for: .aurora, moduleImport: nil).contains("import SPGlassKit"))340 }341342 @Test func hostileNamesCannotBreakOutOfTheGeneratedFile() {343 var theme = GlassTheme.crystal344 theme.name = "X\"\n} import Darwin; exit(1) //"345 theme.summary = "*/ \\(1) \u{2028}"346 let source = GlassThemeSwiftExporter.source(for: theme)347 let firstLine = source.split(separator: "\n").first.map(String.init) ?? ""348 #expect(firstLine.hasPrefix("// Theme") && !firstLine.contains("*/"))349 #expect(source.contains(#"name: "X\"\n} import Darwin; exit(1) //","#))350 #expect(source.components(separatedBy: "\n").filter { $0.hasPrefix("import ") } == ["import SwiftUI", "import SPGlassKit"])351 }352}353