Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/KitTests/StudioAppTests.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("Studio catalogue coverage")48@MainActor49struct StudioCoverageTests {50 @Test func everyComponentHasADescriptorWithFieldsVariantsDocumentationAndExample() {51 let catalog = ComponentCatalog.standard52 #expect(catalog.descriptors.map(\.id) == GlassComponentCatalog.all.map(\.id))53 for descriptor in catalog.descriptors {54 #expect(descriptor.fields.count >= 2, "\(descriptor.id)")55 #expect(!descriptor.variants.isEmpty, "\(descriptor.id)")56 #expect(StudioDocs.markdown(for: descriptor.id)?.contains("## Accessibility") == true, "\(descriptor.id): documentation page not bundled")57 #expect(Bundle.module.url(forResource: "example-\(descriptor.id)", withExtension: "txt") != nil, "\(descriptor.id): example not bundled")58 }59 #expect(catalog.composable.count >= 30)60 }6162 @Test func fractionalStepsProduceExactValues() {63 let field = InspectorField.number("x", "X", in: 0...1, step: 0.1, default: 0.5)64 #expect(field.validated(.number(0.3)) == .number(0.3))65 #expect(field.validated(.number(0.34)) == .number(0.3))66 #expect(field.validated(.number(0.7000000001)) == .number(0.7))67 }6869 @Test("Every playground template is valid and renders code", arguments: PlaygroundTemplate.allCases)70 func templates(template: PlaygroundTemplate) throws {71 let catalog = ComponentCatalog.standard72 let document = template.document(catalog: catalog)73 try PlaygroundDocument.validate(document.root, knownComponents: catalog.composableIDs)74 #expect(document.root.componentIDs.count >= 3, "\(template.rawValue) lost components: \(document.root.componentIDs)")75 let export = PlaygroundCodeGenerator.export(document, catalog: catalog)76 #expect(export.source.contains("struct ") && !export.source.contains("unknown component"))77 #expect(export.installCommand.hasPrefix("spglass add "))78 }79}8081@Suite("Studio state")82@MainActor83struct StudioModelTests {84 func model(_ arguments: [String] = []) throws -> (StudioModel, URL) {85 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("glassstudio-model-\(UUID().uuidString)")86 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)87 return (StudioModel(launch: StudioLaunchOptions(arguments: ["app", "-studioDataDirectory", directory.path] + arguments)), directory)88 }8990 @Test func launchOptionsSelectSectionComponentThemeAndAppearance() throws {91 let (model, directory) = try model(["-studioComponent", "glass-toast", "-studioTheme", "aurora", "-studioAppearance", "dark", "-studioLanguage", "fr", "-studioTab", "code"])92 defer { try? FileManager.default.removeItem(at: directory) }93 #expect(model.section == .catalog && model.selectedComponentID == "glass-toast")94 #expect(model.preview.themeID == "aurora" && model.preview.appearance == .dark)95 #expect(model.launch.language == "fr" && model.launch.detailTab == "code")96 }9798 @Test func invalidLaunchOptionsAreIgnored() throws {99 let (model, directory) = try model(["-studioComponent", "../../etc", "-studioTheme", "No Such Theme", "-studioSection", "admin", "-studioLanguage", "xx", "-studioAppearance"])100 defer { try? FileManager.default.removeItem(at: directory) }101 #expect(model.section == .home && model.selectedComponentID == nil && model.preview.themeID == "system" && model.launch.language == nil)102 }103104 @Test func deepLinks() throws {105 let (model, directory) = try model()106 defer { try? FileManager.default.removeItem(at: directory) }107 #expect(model.open(url: try #require(URL(string: "glassstudio://component/glass-chart"))))108 #expect(model.section == .catalog && model.selectedComponentID == "glass-chart")109 #expect(model.open(url: try #require(URL(string: "glassstudio://theme/ocean"))) && model.preview.themeID == "ocean")110 #expect(model.open(url: try #require(URL(string: "glassstudio://section/playground"))) && model.section == .playground)111 for bad in ["glassstudio://component/nope", "glassstudio://theme/nope", "glassstudio://section/root", "https://example.com/component/glass-chart", "glassstudio://run/rm"] {112 #expect(!model.open(url: try #require(URL(string: bad))), "\(bad)")113 }114 #expect(model.section == .playground)115 }116117 @Test func thePlaygroundIsPersistedAndACorruptFileFallsBackToATemplate() throws {118 let (model, directory) = try model()119 defer { try? FileManager.default.removeItem(at: directory) }120 model.resetPlayground(to: .dashboard)121 try model.playground.insert(.component("glass-button"), into: model.playground.root.id)122 let saved = model.playground123 let reloaded = StudioModel(launch: StudioLaunchOptions(arguments: ["app", "-studioDataDirectory", directory.path]))124 #expect(reloaded.playground == saved)125 try Data("{\"schemaVersion\":1,\"name\":\"x\",\"root\":{\"id\":\"not-a-uuid\"}}".utf8).write(to: directory.appendingPathComponent("playground.json"))126 let recovered = StudioModel(launch: StudioLaunchOptions(arguments: ["app", "-studioDataDirectory", directory.path]))127 #expect(recovered.playground.root.isStack && recovered.playground.root.nodeCount > 1)128 }129130 @Test func filteringAndFavourites() throws {131 let (model, directory) = try model()132 defer { try? FileManager.default.removeItem(at: directory) }133 #expect(model.filteredDescriptors.count == 50)134 model.filter.query = "carte"135 #expect(model.filteredDescriptors.isEmpty, "search is on the English catalogue text")136 model.filter.query = "map"137 #expect(model.filteredDescriptors.count >= 5)138 model.favorites.toggle("glass-map-pin")139 model.filter.favoritesOnly = true140 #expect(model.filteredDescriptors.map(\.id) == ["glass-map-pin"] && model.favoriteDescriptors.count == 1)141 }142143 #if os(macOS)144 @Test("Every Studio screen lays out", arguments: StudioSection.allCases)145 func screens(section: StudioSection) throws {146 let (model, directory) = try model(["-studioComponent", "glass-button"])147 defer { try? FileManager.default.removeItem(at: directory) }148 model.section = section149 for sizeClass in [UserInterfaceSizeClass.compact, .regular] {150 let host = NSHostingView(rootView: StudioRootView(model: model).environment(\.horizontalSizeClass, sizeClass).frame(width: sizeClass == .compact ? 390 : 1100, height: 760))151 host.frame = NSRect(x: 0, y: 0, width: sizeClass == .compact ? 390 : 1100, height: 760)152 host.layoutSubtreeIfNeeded()153 #expect(host.fittingSize.height > 0)154 }155 }156157 @Test func detailAndEditorLayOutForEveryComponent() throws {158 let (model, directory) = try model()159 defer { try? FileManager.default.removeItem(at: directory) }160 for descriptor in model.catalog.descriptors {161 let host = NSHostingView(rootView: NavigationStack { ComponentDetailView(model: model, descriptor: descriptor) }.frame(width: 900, height: 800))162 host.frame = NSRect(x: 0, y: 0, width: 900, height: 800)163 host.layoutSubtreeIfNeeded()164 }165 let editor = NSHostingView(rootView: NavigationStack { ThemeEditorView(model: model, theme: .aurora) {} }.frame(width: 800, height: 900))166 editor.frame = NSRect(x: 0, y: 0, width: 800, height: 900)167 editor.layoutSubtreeIfNeeded()168 #expect(editor.fittingSize.width > 0)169 }170 #endif171}172173@Suite("Studio localisation and resources")174struct StudioResourcesTests {175 static let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()176177 func table(_ name: String, _ language: String) throws -> [String: String] {178 let url = Self.root.appendingPathComponent("Apps/GlassStudio/Kit/Resources/\(language).lproj/\(name).strings")179 return try #require(NSDictionary(contentsOf: url) as? [String: String])180 }181182 @Test func everyInterfaceStringUsedInTheSourcesIsTranslated() throws {183 let english = try table("Studio", "en"), french = try table("Studio", "fr")184 #expect(Set(english.keys) == Set(french.keys))185 var used: Set<String> = []186 let sources = Self.root.appendingPathComponent("Apps/GlassStudio/Kit")187 let enumerator = FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil)188 while let url = enumerator?.nextObject() as? URL {189 guard url.pathExtension == "swift", !url.path.contains("/Descriptors/") else { continue }190 let text = try String(contentsOf: url, encoding: .utf8)191 for match in text.matches(of: /\bL\("((?:[^"\\]|\\.)*)"\)/) { used.insert(String(match.output.1)) }192 }193 #expect(used.count > 200)194 for key in used { #expect(french[key] != nil, "no French translation for \"\(key)\"") }195 for (key, value) in english { #expect(key == value, "\(key)") }196 let identical = french.filter { $0.key == $0.value }.keys197 #expect(identical.count < 25, "suspiciously many untranslated French strings: \(identical.sorted())")198 }199200 @Test("Field tables have the same keys in both languages", arguments: StudioL10n.tables.dropFirst())201 func fieldTables(name: String) throws {202 #expect(Set(try table(name, "en").keys) == Set(try table(name, "fr").keys))203 }204205 @Test func formatSpecifiersMatchBetweenLanguages() throws {206 let english = try table("Studio", "en"), french = try table("Studio", "fr")207 for (key, value) in english {208 let a = value.matches(of: /%(\d+\$)?lld/).map { String($0.output.0) }.sorted()209 let b = (french[key] ?? "").matches(of: /%(\d+\$)?lld/).map { String($0.output.0) }.sorted()210 #expect(a == b, "\(key)")211 }212 }213214 @Test func languageOverrideSwitchesLookups() {215 #expect(StudioL10n.string("Themes", language: "fr") == "Thèmes")216 #expect(StudioL10n.string("Themes", language: "en") == "Themes")217 #expect(StudioL10n.string("no such key", language: "fr") == nil)218 #expect(L("no such key") == "no such key")219 }220221 @Test func bundledDocumentationMatchesTheRepositoryPages() throws {222 for info in GlassComponentCatalog.all {223 let page = try String(contentsOf: Self.root.appendingPathComponent("docs/components/\(info.id).md"), encoding: .utf8)224 #expect(StudioDocs.markdown(for: info.id) == page, "\(info.id): run Scripts/sync-studio-resources.sh")225 }226 }227228 @Test func markdownParsing() {229 let blocks = MarkdownBlock.parse("# Title\n\nFirst line\nsecond line.\n\n- one\n- two\n\n```swift\nlet a = 1\n\n# not a heading\n```\n\n| A | B |\n|---|---|\n| `x` | y |\n| z | |\n## Next")230 #expect(blocks == [231 .heading(level: 1, text: "Title"), .paragraph("First line second line."), .bullets(["one", "two"]),232 .code("let a = 1\n\n# not a heading"), .table(header: ["A", "B"], rows: [["`x`", "y"], ["z", ""]]), .heading(level: 2, text: "Next"),233 ])234 #expect(MarkdownBlock.parse("").isEmpty)235 #expect(MarkdownBlock.parse("```\nunterminated") == [.code("unterminated")])236 }237}238