Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Tests/SPGlassFormsTests/GlassSearchAndOTPTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0313//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 Testing43import SPGlassCore44@testable import SPGlassForms4546/// Records what reached the end of a debounced search.47@MainActor48private final class Recorder {49 var calls: [String] = []50 var failures = 051}5253private struct SearchFailure: Error {}5455@Suite("GlassSearchField and GlassOTPField")56@MainActor57struct GlassSearchAndOTPTests {58 /// A debouncer whose wait is a single suspension point: fast, yet still cancellable.59 private func makeDebouncer() -> GlassSearchDebouncer {60 GlassSearchDebouncer(delay: .milliseconds(1)) { _ in61 await Task.yield()62 try Task.checkCancellation()63 }64 }6566 @Test func rapidInputsProduceOneCallWithTheLatestQuery() async {67 let debouncer = makeDebouncer()68 let recorder = Recorder()69 for query in ["s", "sw", "swi", "swift"] {70 debouncer.submit(query) { recorder.calls.append($0) }71 }72 #expect(debouncer.isPending)73 await debouncer.task?.value74 #expect(recorder.calls == ["swift"])75 #expect(!debouncer.isPending)76 }7778 @Test func cancelStopsAWaitingSearch() async {79 let debouncer = makeDebouncer()80 let recorder = Recorder()81 debouncer.submit("swift") { recorder.calls.append($0) }82 let task = debouncer.task83 debouncer.cancel()84 #expect(!debouncer.isPending)85 await task?.value86 #expect(recorder.calls.isEmpty)87 #expect(debouncer.task == nil)88 }8990 @Test func aRealDelayIsHonouredAndCancellable() async {91 let debouncer = GlassSearchDebouncer(delay: .milliseconds(20))92 let recorder = Recorder()93 debouncer.submit("a") { recorder.calls.append($0) }94 debouncer.submit("b") { recorder.calls.append($0) }95 await debouncer.task?.value96 #expect(recorder.calls == ["b"])9798 debouncer.submit("c") { recorder.calls.append($0) }99 let task = debouncer.task100 debouncer.cancel()101 await task?.value102 #expect(recorder.calls == ["b"])103 }104105 @Test func aRunningSearchIsCancelledByANewerQuery() async {106 let debouncer = makeDebouncer()107 let recorder = Recorder()108 debouncer.submit("old") { query in109 // A slow search that honours cancellation.110 try? await Task.sleep(for: .seconds(30))111 if !Task.isCancelled { recorder.calls.append(query) }112 }113 let first = debouncer.task114 for _ in 0..<5 { await Task.yield() }115 debouncer.submit("new") { recorder.calls.append($0) }116 await debouncer.task?.value117 await first?.value118 #expect(recorder.calls == ["new"])119 #expect(!debouncer.isPending)120 }121122 @Test func lateResultsOfAnOvertakenSearchAreDropped() async {123 let debouncer = makeDebouncer()124 let recorder = Recorder()125 let gate = AsyncStream<Void>.makeStream()126 // This search ignores cancellation on purpose and answers only when the gate opens.127 debouncer.submit("old", search: { query in128 for await _ in gate.stream { break }129 return query.uppercased()130 }, deliver: { recorder.calls.append($0) })131 let first = debouncer.task132 for _ in 0..<5 { await Task.yield() }133 debouncer.submit("new", search: { $0.uppercased() }, deliver: { recorder.calls.append($0) })134 await debouncer.task?.value135 gate.continuation.yield()136 gate.continuation.finish()137 await first?.value138 #expect(recorder.calls == ["NEW"])139 }140141 @Test func failuresOfTheLatestSearchAreReportedButCancellationIsNot() async {142 let debouncer = makeDebouncer()143 let recorder = Recorder()144 debouncer.submit("x", search: { _ -> String in throw SearchFailure() }, deliver: { recorder.calls.append($0) }, failure: { _ in recorder.failures += 1 })145 await debouncer.task?.value146 #expect(recorder.failures == 1 && recorder.calls.isEmpty)147148 debouncer.submit("y", search: { _ -> String in throw CancellationError() }, deliver: { recorder.calls.append($0) }, failure: { _ in recorder.failures += 1 })149 await debouncer.task?.value150 #expect(recorder.failures == 1)151 #expect(!debouncer.isPending)152 }153154 @Test func suggestionsMatchWithoutCaseOrDiacritics() {155 let suggestions = ["Café crème", "Cafetière", "Thé vert", "CAFÉ glacé"].map { GlassSearchSuggestion(title: $0) }156 #expect(GlassSearchSuggestion.matching("cafe", in: suggestions).map(\.title) == ["Café crème", "Cafetière", "CAFÉ glacé"])157 #expect(GlassSearchSuggestion.matching(" THE ", in: suggestions).map(\.title) == ["Thé vert"])158 #expect(GlassSearchSuggestion.matching("", in: suggestions).count == 4)159 #expect(GlassSearchSuggestion.matching("", in: suggestions, limit: 2).count == 2)160 #expect(GlassSearchSuggestion.matching("cafe", in: suggestions, limit: -1).isEmpty)161 #expect(GlassSearchSuggestion.matching("zzz", in: suggestions).isEmpty)162 }163164 @Test func suggestionDefaults() {165 let plain = GlassSearchSuggestion(title: "Recent")166 #expect(plain.id == "Recent" && plain.completion == "Recent")167 let custom = GlassSearchSuggestion(id: "r1", title: "In Documents", systemImage: "folder", completion: "kind:document")168 #expect(custom.id == "r1" && custom.completion == "kind:document")169 }170171 @Test("Pasted codes keep only their digits", arguments: [172 ("123456", "123456"),173 ("123 456", "123456"),174 ("123-456", "123456"),175 ("Your code is 482913.", "482913"),176 ("12345678", "123456"),177 ("12", "12"),178 ("", ""),179 ("abc", ""),180 ("123456", "123456"),181 ("١٢٣٤٥٦", "123456"),182 ("۱۲۳۴۵۶", "123456"),183 ("१२३४५६", "123456"),184 ("1️⃣2️⃣3️⃣", "123"),185 ("½Ⅷ②三", ""),186 ("4\u{301}2", "42"),187 ])188 func sanitize(input: String, expected: String) {189 #expect(GlassOTPSanitizer.sanitize(input, length: 6) == expected)190 }191192 @Test func sanitizeHonoursTheLength() {193 #expect(GlassOTPSanitizer.sanitize("123456", length: 4) == "1234")194 #expect(GlassOTPSanitizer.sanitize("123456", length: 0).isEmpty)195 #expect(GlassOTPSanitizer.sanitize("123456", length: -2).isEmpty)196 #expect(GlassOTPSanitizer.sanitize("12 34 56 78", length: 8) == "12345678")197 }198199 @Test func sanitizedCodesAreASCIIOnly() {200 let result = GlassOTPSanitizer.sanitize("١٢٣45६", length: 6)201 #expect(result == "123456")202 #expect(result.utf8.allSatisfy { (0x30...0x39).contains($0) })203 }204205 @Test func segmentsFillFromTheStart() {206 #expect(GlassOTPSanitizer.segments("12", length: 4) == ["1", "2", nil, nil])207 #expect(GlassOTPSanitizer.segments("", length: 3) == [nil, nil, nil])208 #expect(GlassOTPSanitizer.segments("98765", length: 4) == ["9", "8", "7", "6"])209 #expect(GlassOTPSanitizer.segments("12", length: 0).isEmpty)210 }211212 @Test func activeIndexAndCompletion() {213 #expect(GlassOTPSanitizer.activeIndex("", length: 6) == 0)214 #expect(GlassOTPSanitizer.activeIndex("123", length: 6) == 3)215 #expect(GlassOTPSanitizer.activeIndex("123456", length: 6) == nil)216 #expect(GlassOTPSanitizer.isComplete("123456", length: 6))217 #expect(!GlassOTPSanitizer.isComplete("12345", length: 6))218 #expect(!GlassOTPSanitizer.isComplete("12345a", length: 6))219 #expect(!GlassOTPSanitizer.isComplete("١٢٣٤٥٦", length: 6))220 #expect(!GlassOTPSanitizer.isComplete("", length: 0))221 }222223 @Test func accessibilityValueCountsDigitsWithoutReadingThem() {224 let value = GlassL10n.string(.codeDigitsEntered, 3, 6)225 #expect(value.contains("3") && value.contains("6"))226 #expect(!value.contains("123"))227 }228229 @Test func sixAndEightDigitCodesAreSplitInTwoGroups() {230 #expect(GlassOTPLayout.groupBoundary(length: 6) == 3)231 #expect(GlassOTPLayout.groupBoundary(length: 8) == 4)232 for length in [1, 4, 5, 7] {233 #expect(GlassOTPLayout.groupBoundary(length: length) == nil)234 }235 }236237 @Test func sliderTicksFollowTheStepsOrFallBackToQuarters() {238 #expect(GlassSliderMath.tickFractions(in: 0...100, step: 25) == [0, 0.25, 0.5, 0.75, 1])239 #expect(GlassSliderMath.tickFractions(in: 0.5...2, step: 0.25).count == 7)240 // A step that does not divide the range still ends with a mark at the upper bound.241 #expect(GlassSliderMath.tickFractions(in: 0...10, step: 4) == [0, 0.4, 0.8, 1])242 // Continuous, too many steps, or an empty range.243 #expect(GlassSliderMath.tickFractions(in: 0...1, step: nil) == [0, 0.25, 0.5, 0.75, 1])244 #expect(GlassSliderMath.tickFractions(in: 0...100, step: 1) == [0, 0.25, 0.5, 0.75, 1])245 #expect(GlassSliderMath.tickFractions(in: 3...3, step: 1).isEmpty)246 }247}248