SPB Git

Repository Public

QyvoraUITests.swift 22.4 KB 440 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraUITests/QyvoraUITests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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          : None specified (no license file in this repository)33//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 QyvoraCore44@testable import QyvoraUI4546@Suite struct AmountFormatTests {47    @Test func formatsBaseUnits() {48        #expect(AmountFormat.format(units: "0", decimals: 8) == "0")49        #expect(AmountFormat.format(units: "1", decimals: 8) == "0.00000001")50        #expect(AmountFormat.format(units: "100000000", decimals: 8) == "1")51        #expect(AmountFormat.format(units: "123456789", decimals: 8) == "1.23456789")52        #expect(AmountFormat.format(units: "150000000", decimals: 8) == "1.5")53        #expect(AmountFormat.format(units: "2100000000000000", decimals: 8) == "21,000,000")54        #expect(AmountFormat.format(units: "42", decimals: 0) == "42")55        #expect(AmountFormat.format(units: "1234567", decimals: 0) == "1,234,567")56    }5758    @Test func truncatesAndNeverRoundsUp() {59        #expect(AmountFormat.format(units: "199999999", decimals: 8, maxFractionDigits: 2) == "1.99")60        #expect(AmountFormat.format(units: "999999999999999999", decimals: 18, maxFractionDigits: 4) == "0.9999")61        #expect(AmountFormat.format(units: "1", decimals: 18, maxFractionDigits: 4) == "<0.0001")62        #expect(AmountFormat.format(units: "1", decimals: 8, maxFractionDigits: 0) == "<1")63        #expect(AmountFormat.format(units: "100000000", decimals: 8, maxFractionDigits: 0) == "1")64    }6566    @Test func separatorsAndPadding() {67        #expect(AmountFormat.format(units: "123456789012", decimals: 8, groupingSeparator: " ", decimalSeparator: ",") == "1 234,56789012")68        #expect(AmountFormat.format(units: "150000000", decimals: 8, minFractionDigits: 2) == "1.50")69        #expect(AmountFormat.format(units: "100000000", decimals: 8, minFractionDigits: 2) == "1.00")70        #expect(AmountFormat.format(units: "1234", decimals: 0, groupingSeparator: "") == "1234")71    }7273    @Test func toleratesUntidyInput() {74        #expect(AmountFormat.format(units: "000123", decimals: 2) == "1.23")75        #expect(AmountFormat.format(units: "", decimals: 8) == "0")76        #expect(AmountFormat.normalizedUnits("12a3") == "123")77        #expect(AmountFormat.isZero(units: "000"))78        #expect(!AmountFormat.isZero(units: "010"))79    }8081    @Test func formatsFullRange256BitValues() {82        let text = AmountFormat.format(UInt256.max, decimals: 18)83        #expect(text.hasPrefix("115,792,089,237,316,195,423,570,985,008,687,907,853,269,984,665,640,564,039,457."))84        #expect(text.hasSuffix("584007913129639935"))85        #expect(AmountFormat.format(UInt256(1_000_000_000_000_000_000), decimals: 18) == "1")86    }8788    @Test func parsesDecimalText() {89        #expect(AmountFormat.parse("1", decimals: 8) == "100000000")90        #expect(AmountFormat.parse("0.00000001", decimals: 8) == "1")91        #expect(AmountFormat.parse("1,5", decimals: 8) == "150000000")92        #expect(AmountFormat.parse(".5", decimals: 8) == "50000000")93        #expect(AmountFormat.parse("5.", decimals: 8) == "500000000")94        #expect(AmountFormat.parse(" 1 000.25 ", decimals: 2) == "100025")95        #expect(AmountFormat.parse("0", decimals: 18) == "0")96        #expect(AmountFormat.parse("7", decimals: 0) == "7")97    }9899    @Test func rejectsMalformedText() {100        #expect(AmountFormat.parse("", decimals: 8) == nil)101        #expect(AmountFormat.parse(".", decimals: 8) == nil)102        #expect(AmountFormat.parse("1.2.3", decimals: 8) == nil)103        #expect(AmountFormat.parse("abc", decimals: 8) == nil)104        #expect(AmountFormat.parse("-1", decimals: 8) == nil)105        #expect(AmountFormat.parse("1e5", decimals: 8) == nil)106        #expect(AmountFormat.parse("0.000000001", decimals: 8) == nil, "more fraction digits than the asset has")107        #expect(AmountFormat.parse("1.5", decimals: 0) == nil)108        #expect(AmountFormat.parse("١٢", decimals: 0) == nil, "non-ASCII digits are not accepted")109    }110111    @Test func parseAndFormatRoundTrip() {112        for units in ["1", "10", "123456789", "100000000", "2099999997690000", "5000000001"] {113            let text = AmountFormat.format(units: units, decimals: 8, groupingSeparator: "")114            #expect(AmountFormat.parse(text, decimals: 8) == units)115        }116    }117118    @Test func sanitizesKeyboardInput() {119        #expect(AmountFormat.sanitize("12.345", maxFractionDigits: 2) == "12.34")120        #expect(AmountFormat.sanitize("1.2.3", maxFractionDigits: 8) == "1.23")121        #expect(AmountFormat.sanitize("abc1x2", maxFractionDigits: 8) == "12")122        #expect(AmountFormat.sanitize("007", maxFractionDigits: 8) == "7")123        #expect(AmountFormat.sanitize("0", maxFractionDigits: 8) == "0")124        #expect(AmountFormat.sanitize(".5", maxFractionDigits: 8) == "0.5")125        #expect(AmountFormat.sanitize("1,5", maxFractionDigits: 8, decimalSeparator: ",") == "1,5")126        #expect(AmountFormat.sanitize("1.5", maxFractionDigits: 8, decimalSeparator: ",") == "1,5")127        #expect(AmountFormat.sanitize("1.5", maxFractionDigits: 0) == "15")128        #expect(AmountFormat.sanitize("3.", maxFractionDigits: 8) == "3.")129        #expect(AmountFormat.sanitize("", maxFractionDigits: 8) == "")130    }131132    @Test func sanitizeIsIdempotent() {133        for input in ["12.345678901", "0.0", "000.1", "9,99", "..", "1 2 3"] {134            let once = AmountFormat.sanitize(input, maxFractionDigits: 8)135            #expect(AmountFormat.sanitize(once, maxFractionDigits: 8) == once)136        }137    }138}139140/// A long address or hash shown in full must wrap without the system drawing a hyphen, and what is copied must stay141/// the exact value.142@Suite struct UnbrokenValueTests {143    static let address = "tb1q6rz28mcfaxtmd6v789l9rrlrusdprr9pqcpvkl"144    static let hash = "0x" + String(repeating: "9f", count: 32)145146    @Test func theDisplayFormBreaksAnywhereAndShowsNothing() {147        for value in [Self.address, Self.hash, "0x9858EfFD232B4033E47d90003D41EC34EcaEda94", "a", ""] {148            let shown = UnbrokenValue.wrappable(value)149            // one break opportunity after each character, nothing else added150            #expect(shown.unicodeScalars.count == value.unicodeScalars.count * 2)151            #expect(shown.unicodeScalars.filter { $0 == "\u{200B}" }.count == value.count)152            // no hyphen of any kind is introduced (hyphen-minus, soft hyphen, hyphen, non-breaking hyphen, dashes)153            let hyphens: [Unicode.Scalar] = ["-", "\u{00AD}", "\u{2010}", "\u{2011}", "\u{2012}", "\u{2013}"]154            #expect(shown.unicodeScalars.filter { hyphens.contains($0) }.count == value.unicodeScalars.filter { hyphens.contains($0) }.count)155            // no two visible characters stay glued together: the line can break between any of them156            let scalars = Array(shown.unicodeScalars)157            for i in stride(from: 0, to: scalars.count, by: 2) {158                #expect(scalars[i] != "\u{200B}" && scalars[i + 1] == "\u{200B}")159            }160            // the original comes back exactly161            #expect(UnbrokenValue.original(shown) == value)162            #expect(Array(UnbrokenValue.original(shown).utf8) == Array(value.utf8))163        }164    }165166    @Test func whatIsCopiedIsNeverTheDisplayForm() {167        // the display form differs from the value, so a component must never hand it to the clipboard168        #expect(UnbrokenValue.wrappable(Self.address) != Self.address)169        #expect(UnbrokenValue.wrappable(Self.address).count > Self.address.count)170        // a value that already carries break opportunities is normalised, not doubled171        #expect(UnbrokenValue.original(UnbrokenValue.wrappable(UnbrokenValue.wrappable(Self.hash))) == Self.hash)172        // grouping for VoiceOver is computed from the original, never from the display form173        #expect(MiddleTruncation.grouped(Self.address).split(separator: " ").joined() == Self.address)174    }175176    @Test func anAddressFieldKeepsNoWhitespace() {177        #expect(AddressInput.sanitized("  tb1q6rz28 mcfaxtmd6v789l9\nrrlrusdprr9pqcpvkl\t") == Self.address)178        #expect(AddressInput.sanitized(Self.address) == Self.address)179        #expect(AddressInput.sanitized("") == "" && AddressInput.sanitized(" \n ") == "")180        // nothing but whitespace is touched: a hyphen typed by the user stays, none is ever added181        #expect(AddressInput.sanitized("demo-invalid") == "demo-invalid")182    }183184    @Test func proseKeepsItsWordsAndOnlyLongTokensBecomeWrappable() {185        let sentence = "Pay to \(Self.address) on Bitcoin Signet"186        let shown = UnbrokenValue.wrappingLongTokens(sentence)187        #expect(shown.hasPrefix("Pay to t\u{200B}b\u{200B}1") && shown.hasSuffix(" on Bitcoin Signet"))188        #expect(UnbrokenValue.original(shown) == sentence)189        // ordinary text is returned unchanged, so that it stays selectable as it is190        for plain in ["0.00150000 BTC", "Synchronized 2 minutes ago", "m/84'/1'/0'/0/5", "", "   ", "12 of 40"] {191            #expect(UnbrokenValue.wrappingLongTokens(plain) == plain)192        }193        #expect(UnbrokenValue.wrappingLongTokens("abcdefghijklmnopqrstu", longerThan: 20) != "abcdefghijklmnopqrstu")194        #expect(UnbrokenValue.wrappingLongTokens("abcdefghijklmnopqrst", longerThan: 20) == "abcdefghijklmnopqrst")195    }196}197198@Suite struct MiddleTruncationTests {199    @Test func truncatesLongValues() {200        let value = "abcdefghijklmnopqrstuvwxyz0123456789"201        #expect(MiddleTruncation.truncate(value, head: 8, tail: 6) == "abcdefgh…456789")202        #expect(MiddleTruncation.truncate(value, head: 4, tail: 4, ellipsis: "...") == "abcd...6789")203        #expect(MiddleTruncation.truncate(value, head: 0, tail: 4) == "…6789")204    }205206    @Test func leavesShortValuesUntouched() {207        #expect(MiddleTruncation.truncate("abcdefghijklmno", head: 8, tail: 6) == "abcdefghijklmno")208        #expect(MiddleTruncation.truncate("", head: 8, tail: 6) == "")209        #expect(MiddleTruncation.truncate("abc", head: -1, tail: -1) == "…")210    }211212    @Test func neverGetsLonger() {213        for length in 0..<40 {214            let value = String(repeating: "x", count: length)215            #expect(MiddleTruncation.truncate(value).count <= length)216        }217    }218219    @Test func groupsForReading() {220        #expect(MiddleTruncation.grouped("abcdefghij") == "abcd efgh ij")221        #expect(MiddleTruncation.grouped("abcd") == "abcd")222        #expect(MiddleTruncation.grouped("abc", size: 0) == "abc")223    }224}225226@Suite struct SeedPhraseInputTests {227    @Test func splitsPastedPhrases() {228        #expect(SeedPhraseInput.split("  Alpha beta\n\tGAMMA  ") == ["alpha", "beta", "gamma"])229        #expect(SeedPhraseInput.split("") == [])230        #expect(SeedPhraseInput.split("single") == ["single"])231    }232233    @Test func normalizesOneWord() {234        #expect(SeedPhraseInput.normalizeWord(" Alpha1 ") == "alpha")235        #expect(SeedPhraseInput.normalizeWord("be-ta") == "beta")236    }237238    @Test func distributesWithoutGrowing() {239        var words = Array(repeating: "", count: 4)240        let next = SeedPhraseInput.distribute(["a", "b"], into: &words, startingAt: 1)241        #expect(words == ["", "a", "b", ""])242        #expect(next == 3)243        let end = SeedPhraseInput.distribute(["c", "d", "e"], into: &words, startingAt: 2)244        #expect(words == ["", "a", "c", "d"])245        #expect(end == nil)246        let outOfRange = SeedPhraseInput.distribute(["z"], into: &words, startingAt: 9)247        #expect(outOfRange == nil)248        #expect(words.count == 4)249    }250251    @Test func countsRecognisedWords() {252        let list: Set<String> = ["alpha", "beta"]253        #expect(SeedPhraseInput.validCount(["alpha", "", "nope", "beta"], isValid: list.contains) == 2)254        #expect(!SeedPhraseInput.isComplete(["alpha", ""], isValid: list.contains))255        #expect(!SeedPhraseInput.isComplete(["alpha", "nope"], isValid: list.contains))256        #expect(SeedPhraseInput.isComplete(["alpha", "beta"], isValid: list.contains))257        #expect(!SeedPhraseInput.isComplete([], isValid: list.contains))258    }259}260261@Suite struct SmallHelpersTests {262    @Test func countdownText() {263        #expect(CountdownFormat.text(0) == "0:00")264        #expect(CountdownFormat.text(0.2) == "0:01")265        #expect(CountdownFormat.text(42) == "0:42")266        #expect(CountdownFormat.text(725) == "12:05")267        #expect(CountdownFormat.text(3723) == "1:02:03")268        #expect(CountdownFormat.text(-5) == "0:00")269    }270271    @Test func proportions() {272        #expect(Proportions.fractions([1, 1, 2]) == [0.25, 0.25, 0.5])273        #expect(Proportions.fractions([0, 0]) == [0, 0])274        #expect(Proportions.fractions([-3, .nan, 4]) == [0, 0, 1])275        #expect(Proportions.fractions([]) == [])276        #expect(Proportions.percentText(0) == "0%")277        #expect(Proportions.percentText(0.004) == "<1%")278        #expect(Proportions.percentText(0.416) == "42%")279        #expect(Proportions.percentText(1) == "100%")280    }281282    @Test func seriesMath() {283        #expect(SeriesMath.change([100, 110]) == 0.1)284        #expect(SeriesMath.change([100]) == nil)285        #expect(SeriesMath.change([0, 5]) == nil)286        #expect(SeriesMath.drawable([1]) == nil)287        #expect(SeriesMath.drawable([1, .nan]) == nil)288        #expect(SeriesMath.drawable([1, .infinity, 2]) == [1, 2])289        #expect(SeriesMath.percentText(0.0241) == "+2.41%")290        #expect(SeriesMath.percentText(-0.008) == "−0.80%")291        #expect(SeriesMath.percentText(0.00001) == "0.00%")292        let points = (0..<5).map { ChartPoint(date: Date(timeIntervalSinceReferenceDate: Double($0) * 10), value: Double($0)) }293        #expect(SeriesMath.nearestIndex(in: points, to: Date(timeIntervalSinceReferenceDate: 23)) == 2)294        #expect(SeriesMath.nearestIndex(in: points, to: Date(timeIntervalSinceReferenceDate: 999)) == 4)295        #expect(SeriesMath.nearestIndex(in: [], to: Date()) == nil)296    }297298    @Test func passwordStrengthClampsLevel() {299        #expect(PasswordStrength(level: -2).level == 0)300        #expect(PasswordStrength(level: 9).level == 4)301        #expect(PasswordStrength(level: 2).label == "Fair")302    }303304    @Test func scanGateSingleAndSequence() {305        var gate = QRScanGate()306        let single = ["", "a", "a", "b"].map { gate.accept($0, sequence: false) }307        #expect(single == [false, true, false, false], "single mode stops after the first code")308        gate.reset()309        let afterReset = gate.accept("b", sequence: false)310        #expect(afterReset)311        var sequence = QRScanGate()312        let frames = ["f1", "f1", "f2", "f3", "f2", ""].map { sequence.accept($0, sequence: true) }313        #expect(frames == [true, false, true, true, false, false])314    }315316    @Test func scanProgressFraction() {317        #expect(QRScanProgress(collected: 3, total: 12).fraction == 0.25)318        #expect(QRScanProgress(collected: 3).fraction == nil)319        #expect(QRScanProgress(collected: 20, total: 10).fraction == 1)320        #expect(QRScanProgress(collected: 1, total: 0).fraction == nil)321    }322}323324@Suite struct QRCodeMatrixTests {325    /// 7×7 finder pattern: dark border, light ring, dark 3×3 core.326    static func isFinder(_ m: QRCodeMatrix, row: Int, column: Int) -> Bool {327        for r in 0..<7 {328            for c in 0..<7 {329                let border = r == 0 || r == 6 || c == 0 || c == 6330                let core = (2...4).contains(r) && (2...4).contains(c)331                if m[row + r, column + c] != (border || core) { return false }332            }333        }334        return true335    }336337    @Test func generatesAMatrixWithFinderPatterns() throws {338        let m = try #require(QRCodeMatrix(payload: "QYVORA test payload"))339        #expect(m.size >= 21)340        #expect((m.size - 21) % 4 == 0, "QR versions grow by four modules")341        #expect(m.modules.count == m.size * m.size)342        #expect(m.modules.contains(true) && m.modules.contains(false))343        #expect(Self.isFinder(m, row: 0, column: 0))344        #expect(Self.isFinder(m, row: 0, column: m.size - 7))345        #expect(Self.isFinder(m, row: m.size - 7, column: 0))346        #expect(!Self.isFinder(m, row: m.size - 7, column: m.size - 7), "the fourth corner has no finder: orientation is preserved")347    }348349    @Test func sizeGrowsWithPayloadAndCorrection() throws {350        let small = try #require(QRCodeMatrix(payload: "a"))351        let large = try #require(QRCodeMatrix(payload: String(repeating: "a", count: 400)))352        #expect(small.size == 21)353        #expect(large.size > small.size)354        let low = try #require(QRCodeMatrix(payload: String(repeating: "b", count: 120), correction: .low))355        let high = try #require(QRCodeMatrix(payload: String(repeating: "b", count: 120), correction: .high))356        #expect(high.size > low.size)357    }358359    @Test func isDeterministicAndPayloadDependent() throws {360        let a1 = try #require(QRCodeMatrix(payload: "payload A"))361        let a2 = try #require(QRCodeMatrix(payload: Data("payload A".utf8)))362        let b = try #require(QRCodeMatrix(payload: "payload B"))363        #expect(a1 == a2)364        #expect(a1 != b)365    }366367    @Test func rejectsEmptyAndOversizedPayloads() {368        #expect(QRCodeMatrix(payload: "") == nil)369        #expect(QRCodeMatrix(payload: Data()) == nil)370        #expect(QRCodeMatrix(payload: Data(repeating: 0x41, count: 8000)) == nil)371    }372}373374/// Regression tests of QYV-APP-006: secret material is not drawn while the screen is recorded or mirrored.375@Suite struct CaptureProtectionTests {376    @Test func theRecoveryWordsAreHiddenWheneverTheSceneIsCaptured() {377        for masked in [false, true] {378            for revealed in [false, true] {379                for redacted in [false, true] {380                    // captured: hidden whatever the caller and the user asked381                    #expect(SeedPhraseVisibility.isHidden(masked: masked, revealed: revealed, redacted: redacted, captured: true))382                    // not captured: hidden in a redacted context, and while masked and not held383                    #expect(SeedPhraseVisibility.isHidden(masked: masked, revealed: revealed, redacted: redacted, captured: false)384                        == (redacted || (masked && !revealed)))385                }386            }387        }388        #expect(!SeedPhraseVisibility.isHidden(masked: false, revealed: false, redacted: false, captured: false))389    }390391    @Test func aRevealedPasswordGoesBackToDotsWhileCaptured() {392        #expect(SeedPhraseVisibility.showsPasswordInClear(revealed: true, captured: false))393        #expect(!SeedPhraseVisibility.showsPasswordInClear(revealed: true, captured: true))394        #expect(!SeedPhraseVisibility.showsPasswordInClear(revealed: false, captured: false))395        #expect(!SeedPhraseVisibility.showsPasswordInClear(revealed: false, captured: true))396    }397398    @Test func theScreenshotWarningSaysWhatToDo() {399        #expect(ScreenshotWarning.title == "A screenshot was taken")400        #expect(ScreenshotWarning.message.contains("Delete it from Photos") && ScreenshotWarning.message.contains("Recently Deleted"))401    }402}403404/// Tests of the compromised-device warning (QYV-APP-009).405@Suite struct DeviceIntegrityTests {406    @Test func indicatorsAreThePathsThatExist() {407        #expect(DeviceIntegrity.jailbreakIndicators { _ in false }.isEmpty)408        #expect(DeviceIntegrity.jailbreakIndicators { $0 == "/Applications/Cydia.app" || $0 == "/var/jb" } == ["/Applications/Cydia.app", "/var/jb"])409        #expect(DeviceIntegrity.jailbreakIndicators { _ in true } == DeviceIntegrity.jailbreakPaths)410        // on macOS (where the tests run) and in the simulator these paths are ordinary: nothing is reported411        #expect(DeviceIntegrity.jailbreakIndicators().isEmpty)412    }413414    @Test func theWarningNamesWhatWasSeen() {415        #expect(DeviceIntegrity.warning(indicators: [], debuggerAttached: false, debuggerMatters: true) == nil)416        // a debugger is expected in a development build417        #expect(DeviceIntegrity.warning(indicators: [], debuggerAttached: true, debuggerMatters: false) == nil)418        let debugger = DeviceIntegrity.warning(indicators: [], debuggerAttached: true, debuggerMatters: true)419        #expect(debugger?.contains("a debugger is attached") == true && debugger?.contains("jailbreak") == false)420        let jailbreak = DeviceIntegrity.warning(indicators: ["/var/jb", "/etc/apt"], debuggerAttached: false, debuggerMatters: true)421        #expect(jailbreak?.contains("signs of a jailbreak (2 found)") == true)422        let both = DeviceIntegrity.warning(indicators: ["/var/jb"], debuggerAttached: true, debuggerMatters: true)423        #expect(both?.contains("jailbreak") == true && both?.contains("debugger") == true && both?.contains("recovery phrase") == true)424    }425426    @Test func theDebuggerProbeAnswersWithoutCrashing() {427        // no debugger is attached to the test runner in the audit and CI runs; the call itself must work everywhere428        _ = DeviceIntegrity.isDebuggerAttached429    }430}431432/// Every copied value expires (MASTG-TEST-0278): one minute for a sensitive one, ten for the others.433@Suite struct ClipboardPolicyTests {434    @Test func everyCopyExpires() {435        #expect(QClipboard.lifetime(sensitive: true) == 60)436        #expect(QClipboard.lifetime(sensitive: false) == 600)437        #expect(QClipboard.lifetime(sensitive: true) < QClipboard.lifetime(sensitive: false))438    }439}440
Files main
Menu

Theme