SPB Git

Repository Public

ThemeEngineTests.swift 13.6 KB 293 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Tests/ThemeEngineTests/ThemeEngineTests.swift10// Description      : Colour maths, built-in theme guarantees (count, identity,11//                    legibility), normalisation and the validated import/export12//                    of themes.13// Module           : ThemeEngineTests14// Repository       : https://git.spboucher.ai/sp-keyboard15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import XCTest91import SecureStorage92@testable import ThemeEngine9394final class ThemeEngineTests: XCTestCase {95    func testHexRoundTrip() {96        XCTAssertEqual(RGBA(hex: "#FF8000")?.hex, "#FF8000")97        XCTAssertEqual(RGBA(hex: "ff800080")?.hex, "#FF800080")98        XCTAssertNil(RGBA(hex: "#12345"))99        XCTAssertNil(RGBA(hex: "#GGGGGG"))100        XCTAssertNil(RGBA(hex: ""))101    }102103    func testContrastMaths() {104        XCTAssertEqual(RGBA.white.contrast(with: .black), 21, accuracy: 0.01)105        XCTAssertEqual(RGBA.white.contrast(with: .white), 1, accuracy: 0.001)106        XCTAssertEqual(RGBA("#777777").contrast(with: .white), 4.48, accuracy: 0.05)107    }108109    func testEighteenDistinctBuiltIns() {110        XCTAssertEqual(BuiltInThemes.all.count, 18)111        XCTAssertEqual(Set(BuiltInThemes.all.map(\.id)).count, 18)112        XCTAssertEqual(Set(BuiltInThemes.all.map(\.name)).count, 18)113        XCTAssertEqual(BuiltInThemes.signature.count, 7)114        XCTAssertEqual(BuiltInThemes.expressive.count, 11)115        XCTAssertEqual(BuiltInThemes.default.id, BuiltInThemes.defaultID)116        XCTAssertEqual(BuiltInThemes.default.name, "Atelier Clair")117        XCTAssertFalse(BuiltInThemes.default.isDark)118        XCTAssertTrue(BuiltInThemes.defaultDark.isDark)119        XCTAssertNotNil(BuiltInThemes.theme(id: "monochrome"))120        XCTAssertNil(BuiltInThemes.theme(id: "nope"))121    }122123    func testBuiltInsAreLegibleAsShipped() {124        for theme in BuiltInThemes.all {125            XCTAssertEqual(theme, theme.normalized(), "\(theme.id) is not normalised")126            XCTAssertGreaterThanOrEqual(theme.minimumContrast, 4.5, "\(theme.id) contrast \(theme.minimumContrast)")127            let strict = theme.resolved(increaseContrast: true, reduceMotion: true)128            XCTAssertGreaterThanOrEqual(strict.minimumContrast, 7, "\(theme.id) high contrast")129            XCTAssertEqual(strict.motion, .off)130        }131    }132133    func testLegibleRepairsUnreadableTheme() {134        var theme = BuiltInThemes.aurora135        theme.letterKey.text = RGBA("#0B1E3A") // dark text on dark glass136        XCTAssertLessThan(theme.contrast(of: theme.letterKey), 2)137        let fixed = theme.legible()138        XCTAssertGreaterThanOrEqual(fixed.contrast(of: fixed.letterKey), 4.5)139    }140141    func testNormalisationClampsEverything() {142        var theme = BuiltInThemes.lava143        theme.metrics = ThemeMetrics(cornerRadius: 500, heightScale: 9, spacing: -4, keyOpacity: 0, glowIntensity: 7, contrastBoost: .nan, borderWidth: 99)144        theme.name = "   "145        theme.background.colors = Array(repeating: .white, count: 40)146        theme.backgroundImage = "../../etc/passwd"147        theme.imageDim = 4148        let n = theme.normalized()149        XCTAssertEqual(n.metrics.cornerRadius, 18)150        XCTAssertEqual(n.metrics.heightScale, 1.25)151        XCTAssertEqual(n.metrics.spacing, 3)152        XCTAssertEqual(n.metrics.keyOpacity, 0.35)153        XCTAssertEqual(n.metrics.glowIntensity, 1)154        XCTAssertEqual(n.metrics.contrastBoost, 0)155        XCTAssertEqual(n.metrics.borderWidth, 2.5)156        XCTAssertFalse(n.name.isEmpty)157        XCTAssertEqual(n.background.colors.count, Theme.maxGradientColors)158        XCTAssertNil(n.backgroundImage)159        XCTAssertEqual(n.imageDim, 0.85)160    }161162    func testImageNameSafety() {163        XCTAssertTrue(Theme.isSafeImageName("background-1.jpg"))164        XCTAssertFalse(Theme.isSafeImageName("https://example.com/a.jpg"))165        XCTAssertFalse(Theme.isSafeImageName("a/b.png"))166        XCTAssertFalse(Theme.isSafeImageName("a.exe"))167    }168169    func testTintPrecedence() {170        var theme = BuiltInThemes.aurora171        theme.keyTints["a"] = RGBA("#123456")172        XCTAssertEqual(theme.tint(forKey: "a", row: 1, fallback: .white), RGBA("#123456"))173        XCTAssertEqual(theme.tint(forKey: "s", row: 1, fallback: .white), theme.rowTints[1])174        XCTAssertEqual(theme.tint(forKey: "s", row: 9, fallback: .white), .white)175    }176177    func testExportImportRoundTrip() throws {178        var theme = BuiltInThemes.galaxy179        theme.backgroundImage = "photo.jpg"180        let data = try ThemeCodec.export(theme)181        XCTAssertFalse(String(decoding: data, as: UTF8.self).contains("photo.jpg"))182        let imported = try ThemeCodec.import(data, newID: { "custom-test" })183        XCTAssertEqual(imported.id, "custom-test")184        XCTAssertFalse(imported.isBuiltIn)185        XCTAssertNil(imported.backgroundImage)186        var expected = theme.normalized()187        expected.id = "custom-test"188        expected.backgroundImage = nil189        XCTAssertEqual(imported, expected)190    }191192    func testImportRejectsBadInput() throws {193        XCTAssertThrowsError(try ThemeCodec.import(Data(count: ThemeCodec.maxImportBytes + 1))) { XCTAssertEqual($0 as? ThemeCodecError, .tooLarge) }194        XCTAssertThrowsError(try ThemeCodec.import(Data("not json".utf8))) { XCTAssertEqual($0 as? ThemeCodecError, .notJSON) }195        XCTAssertThrowsError(try ThemeCodec.import(Data(#"{"format":"other","schemaVersion":1}"#.utf8))) { XCTAssertEqual($0 as? ThemeCodecError, .wrongFormat) }196        XCTAssertThrowsError(try ThemeCodec.import(Data(#"{"format":"sp-keyboard-theme","schemaVersion":99,"theme":{}}"#.utf8))) {197            XCTAssertEqual($0 as? ThemeCodecError, .unsupportedVersion(99))198        }199        XCTAssertThrowsError(try ThemeCodec.import(Data(#"{"format":"sp-keyboard-theme","schemaVersion":1,"theme":{"id":"x"}}"#.utf8))) {200            guard case .malformed = $0 as? ThemeCodecError else { return XCTFail("expected malformed, got \($0)") }201        }202        // A bad colour inside an otherwise valid theme is rejected, not silently replaced.203        let good = String(decoding: try ThemeCodec.export(BuiltInThemes.lava), as: UTF8.self)204        let bad = good.replacingOccurrences(of: "\"#FFD9A0\"", with: "\"javascript:alert(1)\"")205        XCTAssertNotEqual(good, bad)206        XCTAssertThrowsError(try ThemeCodec.import(Data(bad.utf8)))207    }208209    func testStoredThemeFallsBackOnCorruption() {210        XCTAssertNil(ThemeCodec.decodeStored(nil))211        XCTAssertNil(ThemeCodec.decodeStored(Data("{".utf8)))212        let data = ThemeCodec.encodeStored(BuiltInThemes.candyGlass)213        XCTAssertEqual(ThemeCodec.decodeStored(data), BuiltInThemes.candyGlass)214    }215216    func testGradientGeometry() {217        let horizontal = GradientSpec([.white, .black], angle: 0).unitPoints218        XCTAssertEqual(horizontal.start.x, 0, accuracy: 1e-9)219        XCTAssertEqual(horizontal.end.x, 1, accuracy: 1e-9)220        let vertical = GradientSpec([.white, .black], angle: 90).unitPoints221        XCTAssertEqual(vertical.start.y, 0, accuracy: 1e-9)222        XCTAssertEqual(vertical.end.y, 1, accuracy: 1e-9)223    }224225    func testSignatureThemesAreFlatAndStill() {226        for theme in BuiltInThemes.signature {227            XCTAssertEqual(theme.effect, .none, theme.id)228            XCTAssertEqual(theme.motion, .off, theme.id)229            XCTAssertEqual(theme.metrics.glowIntensity, 0, theme.id)230            XCTAssertGreaterThanOrEqual(theme.minimumContrast, 7, "\(theme.id) should pass AAA as shipped")231            XCTAssertEqual(theme.resolved(increaseContrast: false, reduceMotion: false), theme.normalized(), "\(theme.id) needs no repair")232        }233    }234235    func testThemeStoredByOneDotXStillDecodes() throws {236        // 1.x themes carry neither `typeface` nor `metrics.depth`.237        var object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(BuiltInThemes.aurora)) as? [String: Any])238        object["typeface"] = nil239        var metrics = try XCTUnwrap(object["metrics"] as? [String: Any])240        metrics["depth"] = nil241        object["metrics"] = metrics242        let decoded = try JSONDecoder().decode(Theme.self, from: JSONSerialization.data(withJSONObject: object))243        XCTAssertNil(decoded.typeface)244        XCTAssertNil(decoded.metrics.depth)245        XCTAssertEqual(decoded.metrics.edgeDepth, 0.5)246        var translucent = decoded247        translucent.metrics.keyOpacity = 0.5248        XCTAssertEqual(translucent.metrics.edgeDepth, 0.3)249        var deep = decoded250        deep.metrics.depth = 7251        XCTAssertEqual(deep.normalized().metrics.depth, 1)252    }253254    func testLibraryPairFollowsAppearance() {255        var library = ThemeLibrary()256        XCTAssertTrue(library.followsAppearance)257        XCTAssertEqual(library.theme(dark: false).id, "atelier-clair")258        XCTAssertEqual(library.theme(dark: true).id, "atelier-nuit")259        library.activate(BuiltInThemes.lava)260        XCTAssertFalse(library.followsAppearance)261        XCTAssertEqual(library.theme(dark: false).id, "lava")262        XCTAssertEqual(library.theme(dark: true).id, "lava")263        library.activatePair(light: BuiltInThemes.craie, dark: BuiltInThemes.ardoise)264        XCTAssertEqual(library.theme(dark: true).id, "ardoise")265    }266267    func testLibraryMigrationFromOneDotX() throws {268        func stored(active: Theme) throws -> ThemeLibrary {269            var old = ThemeLibrary()270            old.activate(active)271            var object = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(old)) as? [String: Any])272            object["schemaVersion"] = 1273            object["darkVariant"] = nil274            let store = InMemorySettingsStore()275            store.set(try JSONSerialization.data(withJSONObject: object), forKey: ThemeLibrary.storageKey)276            let (library, outcome) = store.load(ThemeLibrary.self)277            XCTAssertEqual(outcome, .stored)278            return library279        }280        // The untouched 1.0 default becomes the 2.0 pair.281        let upgraded = try stored(active: BuiltInThemes.aurora)282        XCTAssertEqual(upgraded.active.id, "atelier-clair")283        XCTAssertEqual(upgraded.darkVariant?.id, "atelier-nuit")284        // A deliberate choice is kept, for both appearances.285        let kept = try stored(active: BuiltInThemes.cyberpunk)286        XCTAssertEqual(kept.active.id, "cyberpunk")287        XCTAssertNil(kept.darkVariant)288        var tuned = BuiltInThemes.aurora289        tuned.metrics.cornerRadius = 3290        XCTAssertEqual(try stored(active: tuned).active.metrics.cornerRadius, 3)291    }292}293
Files main
Menu

Theme