SPB Git

Repository Public

DesignSystemTests.swift 29.8 KB 552 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraUITests/DesignSystemTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//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 CoreGraphics43import Testing44import QyvoraCore45@testable import QyvoraUI4647/// The four appearances every colour is checked in.48private let appearances: [(name: String, dark: Bool, high: Bool)] = [49    ("light", false, false), ("dark", true, false), ("light, increased contrast", false, true), ("dark, increased contrast", true, true),50]5152@Suite struct ContrastTests {53    @Test func ratioArithmetic() {54        #expect(abs(QContrast.ratio(0x000000, 0xFFFFFF) - 21) < 0.001)55        #expect(abs(QContrast.ratio(0x777777, 0x777777) - 1) < 0.001)56        #expect(QContrast.ratio(0x123456, 0xABCDEF) == QContrast.ratio(0xABCDEF, 0x123456))57        #expect(QContrast.composite(0xFFFFFF, opacity: 0, over: 0x102030) == 0x102030)58        #expect(QContrast.composite(0xFFFFFF, opacity: 1, over: 0x102030) == 0xFFFFFF)59        #expect(QContrast.composite(0xFFFFFF, opacity: 0.5, over: 0x000000) == 0x808080)60    }6162    @Test func everyTextColourReadsOnEverySurface() {63        for appearance in appearances {64            for surface in QPalette.surfaces {65                let background = surface.spec.rgb(dark: appearance.dark, highContrast: appearance.high)66                for foreground in QPalette.textForegrounds {67                    let ratio = QContrast.ratio(foreground.spec.rgb(dark: appearance.dark, highContrast: appearance.high), background)68                    #expect(ratio >= QContrast.text, "\(foreground.name) on \(surface.name), \(appearance.name): \(ratio)")69                }70            }71        }72    }7374    @Test func controlBoundariesAreVisible() {75        for appearance in appearances {76            for surface in QPalette.surfaces {77                let background = surface.spec.rgb(dark: appearance.dark, highContrast: appearance.high)78                let ratio = QContrast.ratio(QPalette.strokeStrong.rgb(dark: appearance.dark, highContrast: appearance.high), background)79                #expect(ratio >= QContrast.graphic, "strokeStrong on \(surface.name), \(appearance.name): \(ratio)")80            }81        }82    }8384    @Test func whiteTextReadsOnThePrimaryAction() {85        for dark in [false, true] {86            for fill in [QPalette.violetFill, QPalette.blueFill] {87                #expect(QContrast.ratio(QPalette.onAccent.rgb(dark: dark), fill.rgb(dark: dark)) >= QContrast.text)88            }89        }90    }9192    @Test func chainTintsReadOnTheirContainer() {93        for chain in QChain.allCases {94            for dark in [false, true] {95                let tint = chain.tint.rgb(dark: dark)96                // the glyph container is the raised surface; pills and legends put the tint on the others97                #expect(QContrast.ratio(tint, QPalette.surfaceRaised.rgb(dark: dark)) >= QContrast.text, "\(chain) dark=\(dark)")98                for surface in QPalette.surfaces {99                    #expect(QContrast.ratio(tint, surface.spec.rgb(dark: dark)) >= QContrast.text, "\(chain) on \(surface.name) dark=\(dark)")100                }101            }102        }103    }104105    @Test func tokenTintsReadOnTheirContainer() {106        for (index, spec) in QTokenTint.palette.enumerated() {107            for dark in [false, true] {108                #expect(QContrast.ratio(spec.rgb(dark: dark), QPalette.surfaceRaised.rgb(dark: dark)) >= QContrast.text, "token tint \(index) dark=\(dark)")109            }110        }111    }112113    @Test func legacyAssetTintsStillRead() {114        for spec in [QPalette.bitcoin, QPalette.ethereum] {115            for dark in [false, true] {116                #expect(QContrast.ratio(spec.rgb(dark: dark), QPalette.surfaceRaised.rgb(dark: dark)) >= QContrast.text)117            }118        }119    }120}121122@Suite struct ChainIdentityTests {123    @Test func thirteenChainsInFourFamilies() {124        #expect(QChain.allCases.count == 13)125        #expect(QChain.allCases.filter { $0.family == .utxo }.count == 4)126        #expect(QChain.allCases.filter { $0.family == .evm }.count == 7)127        #expect(QChain.allCases.filter { $0.family == .solana } == [.solana])128        #expect(QChain.allCases.filter { $0.family == .tron } == [.tron])129        #expect(Set(QChain.allCases.map(\.name)).count == 13)130        #expect(Set(QChain.allCases.map(\.nativeDecimals)) == [8, 18, 9, 6])131    }132133    @Test func everyChainHasItsOwnGlyphAndTint() {134        var glyphs = Set<String>()135        var tints = Set<UInt32>()136        var descriptions = Set<String>()137        for chain in QChain.allCases {138            let path = ChainMark.unitPath(chain)139            #expect(!path.isEmpty, "\(chain) has no glyph")140            let box = path.boundingRect141            // the same optical box for every mark: inside the 24-unit grid with margins, and centred142            #expect(box.minX >= 4 && box.maxX <= 20 && box.minY >= 4 && box.maxY <= 20, "\(chain) leaves the grid: \(box)")143            #expect(box.width >= 6 && box.height >= 10, "\(chain) is too small: \(box)")144            #expect(abs(box.midX - 12) <= 1.5 && abs(box.midY - 12) <= 1.5, "\(chain) is off centre: \(box)")145            glyphs.insert(path.description)146            tints.insert(chain.tint.dark)147            tints.insert(chain.tint.light &+ 0x0100_0000)148            descriptions.insert(chain.glyphDescription)149        }150        #expect(glyphs.count == 13)151        #expect(tints.count == 26)152        #expect(descriptions.count == 13)153    }154155    @Test func glyphScalesToItsFrame() {156        let rect = CGRect(x: 0, y: 0, width: 48, height: 48)157        for chain in QChain.allCases {158            let box = ChainMark(chain).path(in: rect).boundingRect159            #expect(rect.insetBy(dx: 7.9, dy: 7.9).contains(box), "\(chain): \(box)")160        }161    }162163    @Test func networkNames() {164        #expect(QNetwork.mainnet(.ethereum).fullName == "Ethereum")165        #expect(QNetwork.test(.ethereum).fullName == "Ethereum Sepolia")166        #expect(QNetwork.test(.base).fullName == "Base Sepolia")167        #expect(QNetwork.test(.arbitrum).fullName == "Arbitrum Sepolia")168        #expect(QNetwork.test(.optimism).fullName == "OP Sepolia")169        #expect(QNetwork.test(.polygon).fullName == "Polygon Amoy")170        #expect(QNetwork.test(.bsc).fullName == "BNB Testnet")171        #expect(QNetwork.test(.avalanche).fullName == "Avalanche Fuji")172        #expect(QNetwork.test(.bitcoin).fullName == "Bitcoin Testnet")173        #expect(QNetwork.test(.bitcoin, name: "Signet").fullName == "Bitcoin Signet")174        #expect(QNetwork.test(.bitcoinCash).fullName == "Bitcoin Cash Testnet")175        #expect(QNetwork.test(.solana).fullName == "Solana Devnet")176        #expect(QNetwork.test(.tron, name: "Shasta").fullName == "TRON Shasta")177        #expect(QNetwork.test(.tron).spokenName == "TRON Nile, test network")178        #expect(QNetwork.mainnets.count == 13 && QNetwork.mainnets.allSatisfy { !$0.isTest })179        #expect(QNetwork.testnets.count == 13 && QNetwork.testnets.allSatisfy(\.isTest))180        #expect(Set((QNetwork.mainnets + QNetwork.testnets).map(\.id)).count == 26)181    }182183    @Test func coreNetworksMap() {184        for network in EthereumNetwork.allCases {185            let mapped = QNetwork(network)186            #expect(mapped.isTest == network.isTest)187            #expect(mapped.chain.family == .evm)188            #expect(mapped.detail == "Chain ID \(network.chainID)")189            #expect(mapped.chain.nativeSymbol == network.nativeSymbol, "\(network)")190        }191        #expect(QNetwork(EthereumNetwork.arbitrumSepolia).fullName == "Arbitrum Sepolia")192        #expect(QNetwork(EthereumNetwork.polygonAmoy).fullName == "Polygon Amoy")193        #expect(QNetwork(BitcoinNetwork.mainnet) == .mainnet(.bitcoin))194        #expect(QNetwork(BitcoinNetwork.signet).fullName == "Bitcoin Signet")195        #expect(QNetwork(BitcoinNetwork.testnet).isTest)196    }197198    /// The names shown for a network of `QyvoraCore` are that module's own: nothing is composed from a chain name and199    /// a short name ("Arbitrum Arb Sepolia"), and the full name never repeats a word.200    @Test func coreNetworkNamesAreNotComposed() {201        var full = [String]()202        for network in EthereumNetwork.allCases {203            let mapped = QNetwork(network)204            #expect(mapped.fullName == network.displayName)205            #expect(mapped.name == network.shortName)206            full.append(mapped.fullName)207        }208        for network in BitcoinNetwork.allCases {209            let mapped = QNetwork(network)210            #expect(mapped.fullName == network.displayName)211            #expect(mapped.name == network.shortName)212            #expect(mapped.isTest == network.isTest)213            #expect(mapped.chain.nativeSymbol == network.mainCounterpart.ticker, "\(network)")214            full.append(mapped.fullName)215        }216        #expect(Set(full).count == full.count)217        for name in full {218            let words = name.lowercased().split(separator: " ").map(String.init)219            #expect(Set(words).count == words.count, "\(name)")220            for (a, b) in zip(words, words.dropFirst()) { #expect(!b.hasPrefix(a) && !a.hasPrefix(b), "\(name)") }221        }222        #expect(QNetwork(EthereumNetwork.arbitrumSepolia).name == "Arb Sepolia")223        #expect(QNetwork(EthereumNetwork.bscTestnet).fullName == "BNB Smart Chain Testnet")224        #expect(QNetwork(BitcoinNetwork.signet).name == "Signet")225        #expect(QNetwork(BitcoinNetwork.litecoinTestnet).name == "Testnet")226        #expect(QNetwork(BitcoinNetwork.bitcoinCashTestnet).name == "Testnet4")227        #expect(QNetwork(BitcoinNetwork.bitcoinCashTestnet).fullName == "Bitcoin Cash Testnet4")228        #expect(QNetwork(BitcoinNetwork.dogecoin).name == "Dogecoin")229        // a network built with both names keeps them, whatever the chain is called230        #expect(QNetwork(chain: .arbitrum, name: "Arb Sepolia", fullName: "Arbitrum Sepolia", isTest: true).fullName == "Arbitrum Sepolia")231    }232233    @Test func tokenTintIsDeterministic() {234        #expect(QTokenTint.index(for: "USDC") == 4)235        #expect(QTokenTint.index(for: "usdc") == 4)236        #expect(QTokenTint.index(for: "USDT") == 1)237        #expect(QTokenTint.index(for: "DAI") == 5)238        #expect(QTokenTint.index(for: "ARB") == 0)239        for symbol in ["", "A", "WBTC", "ひらがな", String(repeating: "X", count: 200)] {240            let index = QTokenTint.index(for: symbol)241            #expect(index >= 0 && index < QTokenTint.palette.count)242            #expect(index == QTokenTint.index(for: symbol))243            #expect(QTokenTint.spec(for: symbol) == QTokenTint.palette[index])244        }245    }246247    @Test func tokenMonogram() {248        #expect(QTokenTint.monogram(for: "usdc") == "USDC")249        #expect(QTokenTint.monogram(for: "1inch") == "1INC")250        #expect(QTokenTint.monogram(for: "$wif") == "WIF")251        #expect(QTokenTint.monogram(for: "eth") == "ETH")252        #expect(QTokenTint.monogram(for: "  ") == "?")253        #expect(QTokenTint.monogram(for: "") == "?")254    }255256    @Test func assetIdentityCarriesItsNetwork() {257        let base = QNetwork.mainnet(.base)258        #expect(QAssetIdentity.token(symbol: "USDC", network: base).network == base)259        #expect(QAssetIdentity.native(base).network == base)260        #expect(QAssetIdentity.token(symbol: "USDC", network: base) != QAssetIdentity.token(symbol: "USDC", network: .mainnet(.arbitrum)))261    }262}263264@Suite struct ChainFormattingTests {265    @Test func displayPrecisionPerMagnitude() {266        // 8 decimals (Bitcoin family)267        #expect(AssetPrecision.fractionDigits(units: "123456789012", decimals: 8) == 2)   // 1,234.56…268        #expect(AssetPrecision.fractionDigits(units: "123456789", decimals: 8) == 4)      // 1.2345…269        #expect(AssetPrecision.fractionDigits(units: "12345678", decimals: 8) == 4)       // 0.1234270        #expect(AssetPrecision.fractionDigits(units: "12345", decimals: 8) == 7)          // 0.0001234271        #expect(AssetPrecision.fractionDigits(units: "1", decimals: 8) == 8)              // one satoshi stays visible272        // 18 decimals (EVM): capped at 8 digits273        #expect(AssetPrecision.fractionDigits(units: "1500000000000000000", decimals: 18) == 4)274        #expect(AssetPrecision.fractionDigits(units: "1500000000000000", decimals: 18) == 6)275        #expect(AssetPrecision.fractionDigits(units: "1", decimals: 18) == 8)276        // 9 (Solana) and 6 (TRON)277        #expect(AssetPrecision.fractionDigits(units: "5000", decimals: 9) == 8)278        #expect(AssetPrecision.fractionDigits(units: "1", decimals: 6) == 6)279        #expect(AssetPrecision.fractionDigits(units: "2500000", decimals: 6) == 4)280        // stable tokens and zero281        #expect(AssetPrecision.fractionDigits(units: "1234567", decimals: 6, kind: .stable) == 2)282        #expect(AssetPrecision.fractionDigits(units: "0", decimals: 18) == 2)283        #expect(AssetPrecision.fractionDigits(units: "42", decimals: 0) == 0)284        #expect(AssetPrecision.entryFractionDigits(decimals: 18) == 8)285        #expect(AssetPrecision.entryFractionDigits(decimals: 6) == 6)286    }287288    @Test func displayNeverRoundsUp() {289        #expect(AmountFormat.display(units: "199999999", decimals: 8) == "1.9999")290        #expect(AmountFormat.display(units: "12345", decimals: 8) == "0.0001234")291        #expect(AmountFormat.display(units: "1", decimals: 8) == "0.00000001")292        #expect(AmountFormat.display(units: "1", decimals: 18) == "<0.00000001")293        #expect(AmountFormat.display(units: "999999999999999999", decimals: 18) == "0.9999")294        #expect(AmountFormat.display(units: "1999999", decimals: 6, kind: .stable) == "1.99")295        #expect(AmountFormat.display(units: "5000000", decimals: 6, kind: .stable) == "5.00")296        #expect(AmountFormat.display(units: "0", decimals: 9) == "0")297        #expect(AmountFormat.display(units: "123456789012", decimals: 8, groupingSeparator: " ", decimalSeparator: ",") == "1 234,56")298    }299300    @Test func compactNotation() {301        #expect(AmountFormat.compact(units: "999999", decimals: 0) == nil)302        #expect(AmountFormat.compact(units: "1000000", decimals: 0) == "1M")303        #expect(AmountFormat.compact(units: "1239999", decimals: 0) == "1.23M")304        #expect(AmountFormat.compact(units: "45678900000", decimals: 2) == "456M")305        #expect(AmountFormat.compact(units: "12345678901", decimals: 0) == "12.3B")306        #expect(AmountFormat.compact(units: "999999999999", decimals: 0) == "999B")307        #expect(AmountFormat.compact(units: "1000000000000", decimals: 0) == "1T")308        #expect(AmountFormat.compact(units: "1234567890123456", decimals: 0) == "1.23Q")309        #expect(AmountFormat.compact(units: "1234567890123456789012", decimals: 0) == "1,234,567Q")310        #expect(AmountFormat.compact(units: "420690000000000000000000000000", decimals: 18) == "420B")311        #expect(AmountFormat.compact(units: "1", decimals: 18) == nil)312        #expect(AmountFormat.compact(units: "1500000", decimals: 0, decimalSeparator: ",") == "1,5M")313        #expect(AmountFormat.display(units: "420690000000000000000000000000", decimals: 18, kind: .token, compactLarge: true) == "420B")314        #expect(AmountFormat.display(units: "1500000000000000000", decimals: 18, kind: .token, compactLarge: true) == "1.5")315    }316317    @Test func fiatByCurrency() {318        let us = Locale(identifier: "en_US")319        #expect(FiatFormat.format(1234.567, currency: "USD", locale: us) == "$1,234.56")320        #expect(FiatFormat.format(0, currency: "USD", locale: us) == "$0.00")321        #expect(FiatFormat.format(0.004, currency: "USD", locale: us) == "<$0.01")322        #expect(FiatFormat.format(-12.5, currency: "USD", locale: us) == "−$12.50")323        #expect(FiatFormat.format(1234.5, currency: "cad", locale: us) == "CA$1,234.50")324        #expect(FiatFormat.format(1234.5, currency: "JPY", locale: us) == "¥1,234")325        #expect(FiatFormat.format(2_500_000, currency: "USD", locale: us, compactLarge: true) == "$2.5M")326        #expect(FiatFormat.format(3_210_000_000, currency: "USD", locale: us, compactLarge: true) == "$3.21B")327        #expect(FiatFormat.format(999_999, currency: "USD", locale: us, compactLarge: true) == "$999,999.00")328        #expect(FiatFormat.format(.nan, currency: "USD", locale: us) == nil)329        #expect(FiatFormat.format(.infinity, currency: "USD", locale: us) == nil)330        let french = FiatFormat.format(1234.5, currency: "EUR", locale: Locale(identifier: "fr_FR"))331        #expect(french?.hasSuffix("€") == true)332        #expect(french?.contains("234,50") == true)333        #expect(FiatFormat.insert("M", afterFigureIn: "1,2 €") == "1,2M €")334    }335336    @Test func percentChangeAlwaysCarriesItsSign() {337        #expect(FiatFormat.percentChange(0.0241) == "+2.41%")338        #expect(FiatFormat.percentChange(-0.008) == "−0.80%")339        #expect(FiatFormat.percentChange(0) == "0.00%")340        #expect(FiatFormat.percentChange(0.00001) == "0.00%")341        #expect(FiatFormat.percentChange(-0.00001) == "0.00%")342        #expect(FiatFormat.percentChange(1.5, fractionDigits: 0) == "+150%")343        #expect(FiatFormat.percentChange(0.0241, decimalSeparator: ",") == "+2,41%")344        #expect(FiatFormat.percentChange(.nan) == nil)345        #expect(QChange(fraction: 0.0241).direction == .up)346        #expect(QChange(fraction: -0.008).direction == .down)347        #expect(QChange(fraction: 0.00001).direction == .flat)348        #expect(QChange(fraction: 0.0241).spoken == "Up 2.41% over 24 h")349        #expect(QChange(fraction: -0.008, period: "7 d").spoken == "Down 0.80% over 7 d")350        #expect(QChange(fraction: 0).spoken == "Unchanged over 24 h")351    }352353    @Test func relativeTime() {354        let now = Date(timeIntervalSinceReferenceDate: 800_000_000)355        func ago(_ seconds: TimeInterval) -> String { RelativeTime.text(for: now.addingTimeInterval(-seconds), now: now) }356        #expect(ago(-30) == "just now")357        #expect(ago(5) == "just now")358        #expect(ago(59) == "just now")359        #expect(ago(60) == "1 min ago")360        #expect(ago(3599) == "59 min ago")361        #expect(ago(3600) == "1 h ago")362        #expect(ago(86_399) == "23 h ago")363        #expect(ago(86_400) == "yesterday")364        #expect(ago(2 * 86_400) == "2 d ago")365        #expect(ago(6 * 86_400 + 5) == "6 d ago")366        var calendar = Calendar(identifier: .gregorian)367        calendar.timeZone = TimeZone(identifier: "UTC")!368        let dated = RelativeTime.text(for: now.addingTimeInterval(-30 * 86_400), now: now, calendar: calendar, locale: Locale(identifier: "en_US"))369        #expect(dated == "Apr 9")370        let older = RelativeTime.text(for: now.addingTimeInterval(-400 * 86_400), now: now, calendar: calendar, locale: Locale(identifier: "en_US"))371        #expect(older == "Apr 4, 2025")372        #expect(RelativeTime.spoken(for: now.addingTimeInterval(-60), now: now) == "1 minute ago")373        #expect(RelativeTime.spoken(for: now.addingTimeInterval(-7200), now: now) == "2 hours ago")374        #expect(RelativeTime.spoken(for: now.addingTimeInterval(-3 * 86_400), now: now) == "3 days ago")375    }376}377378@Suite struct AddressChunkTests {379    // Synthetic values with the shape of real addresses; none is a real address.380    static let evm = "0x" + "0123456789abcdef0123456789abcdef01234567"381    static let bech = "tb1q" + String(repeating: "x0y1", count: 9) + "zz"382    static let cash = "bitcoincash:" + String(repeating: "q", count: 42)383384    @Test func groupsRebuildTheAddressExactly() {385        for address in [Self.evm, Self.bech, Self.cash, "", "abc", "T" + String(repeating: "A1b2", count: 8) + "x"] {386            #expect(AddressChunks.chunks(address).map(\.text).joined() == address)387            #expect(AddressChunks.chunks(address, size: 5, emphasizedGroups: 1).map(\.text).joined() == address)388        }389    }390391    @Test func prefixIsSetApart() {392        #expect(AddressChunks.prefix(of: Self.evm) == "0x")393        #expect(AddressChunks.prefix(of: Self.cash) == "bitcoincash:")394        #expect(AddressChunks.prefix(of: Self.bech) == "")395        let chunks = AddressChunks.chunks(Self.evm)396        #expect(chunks.first?.role == .prefix)397        #expect(chunks.first?.text == "0x")398        #expect(chunks.count == 11)399        #expect(chunks.dropFirst().allSatisfy { $0.text.count == 4 })400    }401402    @Test func firstAndLastGroupsAreEmphasised() {403        let chunks = AddressChunks.chunks(Self.evm)404        let roles = chunks.dropFirst().map(\.role)405        #expect(roles == [.emphasized, .emphasized, .plain, .plain, .plain, .plain, .plain, .plain, .emphasized, .emphasized])406        let bech = AddressChunks.chunks(Self.bech)407        #expect(bech.first?.role == .emphasized)408        #expect(bech.last?.text == "zz")409        #expect(bech.last?.role == .emphasized)410        #expect(bech.filter { $0.role == .emphasized }.count == 4)411        let one = AddressChunks.chunks(Self.evm, emphasizedGroups: 1).dropFirst().map(\.role)412        #expect(one.first == .emphasized && one.last == .emphasized && one.filter { $0 == .emphasized }.count == 2)413    }414415    @Test func shortValuesAreNotEmphasised() {416        #expect(AddressChunks.chunks("abcdefgh").allSatisfy { $0.role == .plain })417        #expect(AddressChunks.chunks("abcdefghijklmnop").allSatisfy { $0.role == .plain })418        #expect(AddressChunks.chunks("abcdefghijklmnopq").contains { $0.role == .emphasized })419        #expect(AddressChunks.chunks("").isEmpty)420    }421422    @Test func idsAreUniqueAndSpokenFormSpellsGroups() {423        let chunks = AddressChunks.chunks(Self.cash)424        #expect(Set(chunks.map(\.id)).count == chunks.count)425        #expect(AddressChunks.spoken("0xabcdef12") == "0x abcd ef12")426    }427}428429@Suite struct AllocationTests {430    @Test func wholePercentsAddUpToOneHundred() {431        #expect(AllocationMath.wholePercents([1, 1, 1]) == [34, 33, 33])432        #expect(AllocationMath.wholePercents([50, 30, 20]) == [50, 30, 20])433        #expect(AllocationMath.wholePercents([0.5, 0.25, 0.125, 0.125]) == [50, 25, 13, 12])434        #expect(AllocationMath.wholePercents([1]) == [100])435        #expect(AllocationMath.wholePercents([]) == [])436        #expect(AllocationMath.wholePercents([0, 0]) == [0, 0])437        #expect(AllocationMath.wholePercents([-5, .nan, 10]) == [0, 0, 100])438        for values in [[3.0, 3, 3, 1], [1, 2, 3, 4, 5, 6, 7], [0.001, 999], [13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13]] {439            #expect(AllocationMath.wholePercents(values).reduce(0, +) == 100, "\(values)")440        }441    }442443    @Test func tinySharesAreNotShownAsZero() {444        let shares = AllocationMath.shares([0.001, 999])445        let percents = AllocationMath.wholePercents(shares)446        #expect(AllocationMath.percentText(share: shares[0], wholePercent: percents[0]) == "<1%")447        #expect(AllocationMath.percentText(share: shares[1], wholePercent: percents[1]) == "100%")448        #expect(AllocationMath.percentText(share: 0, wholePercent: 0) == "0%")449    }450451    @Test func smallEntriesFoldIntoOther() {452        let thirteen = (1...13).map(Double.init)453        let grouping = AllocationMath.grouping(thirteen, maxSegments: 5)454        #expect(grouping.kept == [12, 11, 10, 9])455        #expect(grouping.other.count == 9)456        #expect(Set(grouping.kept + grouping.other) == Set(0..<13))457        #expect(AllocationMath.grouping([5, 0, 3, -1, .nan], maxSegments: 5).kept == [0, 2])458        #expect(AllocationMath.grouping([5, 0, 3], maxSegments: 5).other.isEmpty)459        #expect(AllocationMath.grouping([2, 2, 2], maxSegments: 3).kept == [0, 1, 2])460        #expect(AllocationMath.grouping([1, 2, 3], maxSegments: 1).kept.isEmpty)461        #expect(AllocationMath.grouping([1, 2, 3], maxSegments: 1).other == [2, 1, 0])462        #expect(AllocationMath.grouping([], maxSegments: 5).kept.isEmpty)463    }464465    @MainActor @Test func segmentsCarryPatternsAndPercentages() {466        let items = QChain.allCases.enumerated().map { AllocationItem(chain: $0.element, value: Double(13 - $0.offset)) }467        let segments = AllocationSegments.resolve(items, maxSegments: 5, otherLabel: "Other")468        #expect(segments.count == 5)469        #expect(segments.map(\.label) == ["Bitcoin", "Litecoin", "Dogecoin", "Bitcoin Cash", "Other (9)"])470        #expect(segments.last?.pattern == .hollow)471        // neighbours never share a pattern, around the ring as well472        for (a, b) in zip(segments, segments.dropFirst() + segments.prefix(1)) { #expect(a.pattern != b.pattern) }473        #expect(abs(segments.map(\.share).reduce(0, +) - 1) < 1e-9)474        #expect(AllocationSegments.resolve([], maxSegments: 5, otherLabel: "Other").isEmpty)475        #expect(AllocationSegments.resolve([AllocationItem(label: "A", value: 0, color: .clear)], maxSegments: 5, otherLabel: "Other").isEmpty)476    }477}478479@Suite struct ComponentLogicTests {480    @Test func slideConfirmsOnlyNearTheEnd() {481        #expect(!SlideToConfirm.confirms(offset: 0, travel: 300))482        #expect(!SlideToConfirm.confirms(offset: 250, travel: 300))483        #expect(SlideToConfirm.confirms(offset: 264, travel: 300))484        #expect(SlideToConfirm.confirms(offset: 300, travel: 300))485        #expect(!SlideToConfirm.confirms(offset: 10, travel: 0))486    }487488    @Test func syncStateLabels() {489        #expect(QSyncState.idle(updated: nil).shortLabel == "Up to date")490        #expect(!QSyncState.idle(updated: nil).isVisibleInRow)491        #expect(QSyncState.syncing(progress: nil).shortLabel == "Syncing")492        #expect(QSyncState.syncing(progress: 0.426).shortLabel == "Syncing 42%")493        #expect(QSyncState.syncing(progress: 7).fraction == 1)494        #expect(QSyncState.syncing(progress: -1).fraction == 0)495        #expect(QSyncState.syncing(progress: .nan).fraction == nil)496        #expect(QSyncState.stale(since: nil).shortLabel == "From previous session")497        #expect(QSyncState.stale(since: nil).isVisibleInRow)498        #expect(QSyncState.failed(reason: "x").shortLabel == "Sync failed")499        #expect(QSyncState.failed(reason: "The endpoint did not answer.").detail() == "The endpoint did not answer.")500        let now = Date(timeIntervalSinceReferenceDate: 800_000_000)501        #expect(QSyncState.stale(since: now.addingTimeInterval(-7200)).detail(now: now)502                == "These figures were saved 2 h ago and have not been refreshed yet.")503        #expect(QSyncState.idle(updated: now.addingTimeInterval(-120)).detail(now: now) == "Updated 2 min ago.")504        // each state has its own glyph: the state never rests on colour505        let images = [QSyncState.idle(updated: nil), .syncing(progress: nil), .stale(since: nil), .failed(reason: "")].map(\.systemImage)506        #expect(Set(images).count == 4)507    }508509    @Test func sparklineGeometry() {510        #expect(ValueSparkline.unitPoints([]) == nil)511        #expect(ValueSparkline.unitPoints([1]) == nil)512        let points = ValueSparkline.unitPoints([10, 20, 15])513        #expect(points == [CGPoint(x: 0, y: 0), CGPoint(x: 0.5, y: 1), CGPoint(x: 1, y: 0.5)])514        #expect(ValueSparkline.unitPoints([3, 3, 3])?.allSatisfy { $0.y == 0.5 } == true)515    }516517    @Test func feeTierDefaults() {518        #expect(FeeTier.Kind.allCases.map { FeeTier.defaultTitle($0) } == ["Slow", "Normal", "Fast", "Custom"])519        #expect(FeeTier(.fast, fee: nil).title == "Fast")520        #expect(FeeTier(.custom, title: "Manual", fee: nil).title == "Manual")521    }522523    @Test func toastsAndNotes() {524        #expect(QToastMessage.copied().text == "Copied")525        #expect(QToastMessage.copied("Address").text == "Address copied")526        #expect(QToastMessage("a").id != QToastMessage("a").id)527        let notes = [RecipientNote.firstPayment(), .ownAddress(), .checksumValid(), .noChecksum()]528        #expect(Set(notes.map(\.id)).count == 4)529        #expect(Set(notes.map(\.systemImage)).count == 4)530    }531532    @Test func motionRespectsReduceMotion() {533        #expect(QMotion.resolved(QMotion.emphasized, reduceMotion: true) == QMotion.reduced)534        #expect(QMotion.resolved(QMotion.emphasized, reduceMotion: false) == QMotion.emphasized)535        #expect(QMotion.resolved(QMotion.numeric, reduceMotion: true) == QMotion.reduced)536    }537538    @Test func staleRowsUseAShortLabel() {539        #expect(QSyncState.stale(since: nil).rowLabel == "Saved earlier")540        #expect(QSyncState.syncing(progress: 0.5).rowLabel == "Syncing 50%")541        #expect(QSyncState.failed(reason: "x").rowLabel == "Sync failed")542    }543544    @Test func assetCaptionNamesTheNetwork() {545        #expect(AssetRow.caption(for: .native(.mainnet(.bitcoin)), name: "Bitcoin") == "Native coin")546        #expect(AssetRow.caption(for: .native(.mainnet(.ethereum)), name: "Ether") == "Ethereum")547        #expect(AssetRow.caption(for: .native(.test(.ethereum)), name: "Ether") == "Ethereum Sepolia")548        #expect(AssetRow.caption(for: .token(symbol: "USDC", network: .mainnet(.base)), name: "USD Coin") == "Base")549        #expect(AssetRow.caption(for: .token(symbol: "USDC", network: .mainnet(.arbitrum)), name: "USD Coin") == "Arbitrum")550    }551}552
Files main
Menu

Theme