SPB Git

Repository Public MIT

ConvertModelTests.swift 20.6 KB 483 lines swift

1// ORIX Calc2// File: Packages/ORIXFeatureConvert/Tests/ORIXFeatureConvertTests/ConvertModelTests.swift3// Description: View-model tests — keypad entry, exact pass-through, swap, category memory, hand-off, temperature, fuel economy, rates, history.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10import ORIXUI11import ORIXUnits1213@testable import ORIXFeatureConvert1415func decimal(_ text: String) -> Decimal { Decimal(string: text, locale: Locale(identifier: "en_US_POSIX"))! }1617@MainActor18func makeModel(category: String = "length", input: String = "1", separator: String = ".", configure: (inout ConvertState) -> Void = { _ in }) -> ConvertModel {19    var state = ConvertState()20    state.categoryID = category21    state.inputText = input22    configure(&state)23    var format = NumberFormat()24    format.decimalSeparator = separator25    return ConvertModel(state: state, numberFormat: format, downloader: FailingDownloader())26}2728/// A downloader that must never be reached.29struct FailingDownloader: RatesDownloading {30    func downloadDailyRates() async throws -> Data { throw URLError(.notConnectedToInternet) }31}3233@Suite struct KeypadEntryTests {34    @Test func digitsAndLeadingZero() {35        var entry = KeypadEntry(text: "")36        entry.press(.digit(0)); entry.press(.digit(0)); entry.press(.digit(5)); entry.press(.digit(0))37        #expect(entry.text == "50")38    }3940    @Test func decimalSeparatorOncePerNumber() {41        var entry = KeypadEntry(text: "")42        entry.press(.decimal); entry.press(.digit(5)); entry.press(.decimal); entry.press(.digit(2))43        #expect(entry.text == "0.52")44    }4546    @Test func localeDecimalSeparator() {47        var entry = KeypadEntry(text: "", decimalSeparator: ",")48        entry.press(.digit(2)); entry.press(.decimal); entry.press(.digit(5)); entry.press(.decimal)49        #expect(entry.text == "2,5")50        entry.type(".")51        #expect(entry.text == "2,5")52    }5354    @Test func signTogglesNumberAndExpression() {55        var entry = KeypadEntry(text: "12")56        entry.press(.sign)57        #expect(entry.text == "-12")58        entry.press(.sign)59        #expect(entry.text == "12")60        entry = KeypadEntry(text: "5*12")61        entry.press(.sign)62        #expect(entry.text == "-(5*12)")63        entry.press(.sign)64        #expect(entry.text == "5*12")65        entry = KeypadEntry(text: "")66        entry.press(.sign); entry.press(.digit(3))67        #expect(entry.text == "-3")68    }6970    @Test func exponentEntry() {71        var entry = KeypadEntry(text: "")72        entry.press(.exponent)73        #expect(entry.text == "")74        entry.press(.digit(1)); entry.press(.decimal); entry.press(.digit(5)); entry.press(.exponent)75        #expect(entry.text == "1.5E")76        entry.press(.exponent); entry.press(.decimal)77        #expect(entry.text == "1.5E")78        entry.press(.sign); entry.press(.digit(3))79        #expect(entry.text == "1.5E-3")80        entry.press(.sign)81        #expect(entry.text == "1.5E3")82        entry.press(.decimal)83        #expect(entry.text == "1.5E3")84    }8586    @Test func backspaceAndClear() {87        var entry = KeypadEntry(text: "12.5")88        entry.press(.backspace)89        #expect(entry.text == "12.")90        entry.press(.clear)91        #expect(entry.text == "")92        entry.press(.backspace)93        #expect(entry.text == "")94    }9596    @Test func replacesAfterHandOff() {97        var entry = KeypadEntry(text: "30.48", replacesOnNextInput: true)98        entry.press(.digit(7))99        #expect(entry.text == "7")100        #expect(!entry.replacesOnNextInput)101        entry = KeypadEntry(text: "30.48", replacesOnNextInput: true)102        entry.press(.backspace)103        #expect(entry.text == "30.4")104        entry = KeypadEntry(text: "30.48", replacesOnNextInput: true)105        entry.type("*")106        #expect(entry.text == "30.48*")107    }108109    @Test func hardwareTypingBuildsExpression() {110        var entry = KeypadEntry(text: "")111        for character in "5*12" { entry.type(character) }112        #expect(entry.text == "5*12")113        entry.type("x")114        #expect(entry.text == "5*12")115    }116}117118@MainActor @Suite struct ExactConversionTests {119    @Test func twelveInchesIsExactly3048Centimetres() {120        let model = makeModel(input: "12") { $0.pairs["length"] = UnitPair(from: "length.in", to: "length.cm") }121        let value = try! #require(model.outcome.value)122        #expect(value.decimal == decimal("30.48"))123        #expect(value.isExact)124        #expect(value.relation == "=")125        #expect(value.kind == .exact)126        #expect(model.resultText == "30.48")127    }128129    @Test func defaultLengthPairIsInchToCentimetre() {130        let model = makeModel()131        #expect(model.from?.symbol == "in")132        #expect(model.to?.symbol == "cm")133    }134135    @Test func typedExpressionStaysExact() {136        let model = makeModel(input: "0.1 + 0.2") { $0.pairs["length"] = UnitPair(from: "length.m", to: "length.cm") }137        #expect(model.input == .number(ExactNumber(rational: BigRational(decimalLiteral: "0.3")!, isExact: true)))138        let value = try! #require(model.outcome.value)139        #expect(value.decimal == decimal("30"))140        #expect(value.isExact)141        model.setInputText("5*12")142        #expect(model.outcome.value?.decimal == decimal("6000"))143    }144145    @Test func manyDigitDecimalPassesThroughUntouched() {146        let digits = "1.2345678901234567890123456789012345678"147        let model = makeModel(input: digits) { $0.pairs["length"] = UnitPair(from: "length.m", to: "length.mm") }148        let value = try! #require(model.outcome.value)149        #expect(value.decimal == decimal("1234.5678901234567890123456789012345678"))150        #expect(value.isExact)151        #expect(model.fullText(value) == "1234.5678901234567890123456789012345678")152    }153154    @Test func nonTerminatingRationalUsesTheExactRatio() {155        let model = makeModel(input: "1/3") { $0.pairs["length"] = UnitPair(from: "length.ft", to: "length.in") }156        let value = try! #require(model.outcome.value)157        #expect(value.decimal == decimal("4"))158        #expect(value.isExact)159    }160161    @Test func nonTerminatingResultIsApproximate() {162        let model = makeModel(input: "1") { $0.pairs["length"] = UnitPair(from: "length.m", to: "length.ft") }163        let value = try! #require(model.outcome.value)164        #expect(!value.isExact)165        #expect(value.relation == "≈")166        #expect(value.kind == .rounded)167        #expect(model.resultText == "3.28083989501")168        #expect(model.hasMoreDigits)169        #expect(model.fullText(value).hasPrefix("3.2808398950131233595800524934383202"))170        model.showsFullPrecision = true171        #expect(model.resultText == model.fullText(value))172    }173174    @Test func irrationalAndApproximateUnitsAreFlagged() {175        let angle = makeModel(category: "angle", input: "180")176        #expect(angle.from?.symbol == "°")177        let radians = try! #require(angle.outcome.value)178        #expect(radians.kind == .irrational)179        #expect(!radians.isExact)180        #expect(radians.note.contains("π"))181        #expect(angle.resultText == "3.14159265359")182183        let speed = makeModel(category: "speed", input: "1")184        let mach = try! #require(UnitCatalog.standard.search("mach", in: .speed).first)185        speed.setTo(mach.id)186        let value = try! #require(speed.outcome.value)187        #expect(value.kind == .approximate)188        #expect(value.note.hasPrefix("Approximate."))189    }190191    @Test func floatingPointInputIsNotExact() {192        let model = makeModel(input: "sqrt(2)") { $0.pairs["length"] = UnitPair(from: "length.m", to: "length.cm") }193        let value = try! #require(model.outcome.value)194        #expect(value.kind == .inexactInput)195        #expect(!value.isExact)196    }197198    @Test func commaLocaleInput() {199        let model = makeModel(input: "2,5", separator: ",") { $0.pairs["length"] = UnitPair(from: "length.m", to: "length.cm") }200        #expect(model.outcome.value?.decimal == decimal("250"))201        model.press(.clear); model.press(.digit(1)); model.press(.decimal); model.press(.digit(5))202        #expect(model.state.inputText == "1,5")203        #expect(model.outcome.value?.decimal == decimal("150"))204        #expect(model.resultText == "150")205        // A pasted or typed "." is still read as the decimal point in a comma locale.206        model.setInputText("2.5")207        #expect(model.outcome.value?.decimal == decimal("250"))208    }209210    @Test func emptyIncompleteAndInvalidInput() {211        let model = makeModel(input: "")212        #expect(model.outcome == .empty)213        model.setInputText("5*")214        #expect(model.input == .incomplete)215        #expect(model.outcome == .empty)216        model.setInputText("2E")217        #expect(model.outcome.value != nil)218        model.setInputText("foo(")219        #expect(model.outcome == .empty)220        model.setInputText("1 $ 2")221        #expect(model.outcome.failure != nil)222    }223224    @Test func decimalBridgeRoundTrips() {225        let nines = String(repeating: "9", count: 38)226        let big = try! #require(DecimalBridge.decimal(from: BigRational(decimalLiteral: nines)!))227        #expect(big.isExact)228        #expect(big.decimal == decimal(nines))229        #expect(DecimalBridge.rational(from: big.decimal) == BigRational(decimalLiteral: nines))230231        let tiny = try! #require(DecimalBridge.decimal(from: -BigRational(decimalLiteral: "1.5e-100")!))232        #expect(tiny.isExact)233        #expect(DecimalBridge.rational(from: tiny.decimal) == -BigRational(decimalLiteral: "1.5e-100")!)234235        let third = try! #require(DecimalBridge.decimal(from: BigRational(decimalLiteral: "1")! / BigRational(3)))236        #expect(!third.isExact)237        #expect(DecimalBridge.decimal(from: BigRational(decimalLiteral: "1e200")!) == nil)238        #expect(NumberText.canonical(decimal("-30.480")) == "-30.48")239    }240}241242@MainActor @Suite struct SelectionTests {243    @Test func swapExchangesUnitsAndKeepsTheValue() {244        let model = makeModel(input: "12")245        model.swap()246        #expect(model.from?.symbol == "cm")247        #expect(model.to?.symbol == "in")248        #expect(model.state.inputText == "12")249        #expect(model.outcome.value?.isExact == false)250        model.setInputText("30.48")251        #expect(model.outcome.value?.decimal == decimal("12"))252    }253254    @Test func pickingTheOtherSideSwaps() {255        let model = makeModel()256        model.setFrom("length.cm")257        #expect(model.pair == UnitPair(from: "length.cm", to: "length.in"))258        model.setTo("length.km")259        #expect(model.pair == UnitPair(from: "length.cm", to: "length.km"))260        #expect(model.recentChoices.map(\.id) == ["length.km", "length.cm"])261        model.setTo("mass.kg")262        #expect(model.pair?.to == "length.km")263    }264265    @Test func categoryChangeKeepsSensibleUnits() {266        let model = makeModel(input: "12")267        model.setTo("length.km")268        model.selectCategory("mass")269        #expect(model.from?.symbol == "lb")270        #expect(model.to?.symbol == "kg")271        #expect(model.state.inputText == "12")272        #expect(model.outcome.value?.decimal == decimal("5.44310844"))273        model.selectCategory("length")274        #expect(model.pair == UnitPair(from: "length.in", to: "length.km"))275        #expect(model.state.recentCategories == ["length", "mass"])276        model.selectCategory("nonsense")277        #expect(model.state.categoryID == "length")278    }279280    @Test func everyCategoryHasTwoDistinctUnits() {281        let model = makeModel()282        #expect(model.categories.count == 35)283        for category in model.categories where category.kind != .rates {284            model.selectCategory(category.id)285            let pair = try! #require(model.pair)286            #expect(pair.from != pair.to, "\(category.id)")287            #expect(model.from != nil && model.to != nil, "\(category.id)")288            if case .units = category.kind { #expect(model.outcome.value != nil, "\(category.id)") }289        }290    }291292    @Test func invalidStoredStateIsRepaired() {293        let model = makeModel(category: "gone") { $0.pairs["length"] = UnitPair(from: "length.nope", to: "length.nope") }294        #expect(model.state.categoryID == "length")295        #expect(model.from != nil && model.to != nil && model.from != model.to)296    }297298    @Test func categorySectionsPutFavouritesAndRecentsFirst() {299        let model = makeModel()300        model.selectCategory("mass")301        model.selectCategory("volume")302        model.toggleFavourite("temperature")303        let sections = model.categorySections(query: "")304        #expect(sections.map(\.title) == ["Favourites", "Recent", "All categories"])305        #expect(sections[0].categories.map(\.id) == ["temperature"])306        #expect(sections[1].categories.map(\.id) == ["volume", "mass"])307        #expect(Set(sections.flatMap { $0.categories.map(\.id) }).count == 35)308        #expect(model.categorySections(query: "gallon").flatMap { $0.categories.map(\.id) }.contains("volume"))309        #expect(model.categorySections(query: "euro").flatMap { $0.categories.map(\.id) } == ["currency"])310        #expect(model.searchChoices("gal").first?.symbol == "gal (US)")311    }312313    @Test func allUnitsRows() {314        let model = makeModel(input: "12")315        let units = UnitCatalog.standard.category(.length)!.units316        #expect(model.rows.count == units.count)317        #expect(model.rows.filter(\.isTarget).map(\.choice.id) == ["length.cm"])318        #expect(model.rows.first { $0.choice.id == "length.ft" }?.text == "1")319        #expect(model.rows.first { $0.choice.id == "length.in" }?.text == "12")320        model.setTo("length.ft")321        #expect(model.resultText == "1")322    }323324    @Test func stateSurvivesEncoding() throws {325        let model = makeModel(input: "12")326        model.selectCategory("mass")327        model.toggleFavourite("mass")328        let data = try JSONEncoder().encode(model.state)329        let restored = ConvertModel(state: try JSONDecoder().decode(ConvertState.self, from: data), downloader: FailingDownloader())330        #expect(restored.state == model.state)331        #expect(restored.outcome == model.outcome)332        #expect(try JSONDecoder().decode(ConvertState.self, from: Data("{}".utf8)) == ConvertState())333    }334}335336@MainActor @Suite struct HandOffAndHistoryTests {337    func makeApp() -> AppModel {338        let defaults = UserDefaults(suiteName: "orix.convert.tests.\(UUID().uuidString)")!339        return AppModel(settings: AppSettings(defaults: defaults), inMemory: true)340    }341342    @Test func pendingConvertValueBecomesTheInput() {343        let app = makeApp()344        let model = makeModel(input: "1")345        model.consumePendingValue(from: app)346        #expect(model.state.inputText == "1")347        app.pendingConvertValue = 30.48348        model.consumePendingValue(from: app)349        #expect(app.pendingConvertValue == nil)350        #expect(model.state.inputText == "30.48")351        #expect(model.outcome.value?.decimal == decimal("77.4192"))352        // The next keypad digit starts a new value.353        model.press(.digit(5))354        #expect(model.state.inputText == "5")355    }356357    @Test func pendingValueFormatting() {358        #expect(ExactInput.editingText(12, decimalSeparator: ".") == "12")359        #expect(ExactInput.editingText(0.1, decimalSeparator: ",") == "0,1")360        #expect(ExactInput.editingText(1e-7, decimalSeparator: ".") == "1E-7")361        #expect(ExactInput.editingText(-2.5e30, decimalSeparator: ".") == "-2.5E30")362        let model = makeModel()363        model.acceptPendingValue(1e-7)364        #expect(model.input.number?.rational == BigRational(decimalLiteral: "1e-7"))365        model.acceptPendingValue(.nan)366        #expect(model.state.inputText == "1E-7")367    }368369    @Test func saveLogsOneHistoryLine() {370        let app = makeApp()371        let model = makeModel(input: "12")372        let entry = try! #require(model.historyEntry())373        #expect(entry.input == "12 in → cm")374        #expect(entry.display == "30.48 cm")375        #expect(entry.canonical == "30.48")376        #expect(entry.isExact)377        #expect(entry.explanation.formula == "1 in = 2.54 cm")378        #expect(app.history.isEmpty)379        model.press(.digit(3))380        #expect(app.history.isEmpty)381        #expect(model.save(to: app))382        #expect(app.history.count == 1)383        #expect(app.history.first?.mode == .convert)384        #expect(app.history.first?.input == "123 in → cm")385        #expect(app.history.first?.display == "312.42 cm")386        #expect(app.history.first?.canonical == "312.42")387        #expect(model.savedNotice != nil)388        model.setInputText("")389        #expect(!model.save(to: app))390        #expect(app.history.count == 1)391        #expect(model.shareText == nil)392    }393394    @Test func persistenceThroughTheAppStore() {395        let app = makeApp()396        let model = makeModel(input: "12")397        model.selectCategory("volume")398        app.saveState(model.state, key: ConvertStorage.stateKey)399        #expect(app.loadState(ConvertState.self, key: ConvertStorage.stateKey) == model.state)400    }401}402403@MainActor @Suite struct TemperatureAndFuelTests {404    @Test func temperatureReadingAndDifference() {405        let model = makeModel(category: "temperature", input: "10")406        model.setFrom("temperature.degC")407        #expect(model.to?.symbol == "°F")408        #expect(model.outcome.value?.decimal == decimal("50"))409        #expect(model.outcome.value?.isExact == true)410        model.state.temperatureDifference = true411        #expect(model.conversionMode == .interval)412        #expect(model.outcome.value?.decimal == decimal("18"))413        model.selectCategory("length")414        #expect(model.conversionMode == .absolute)415    }416417    @Test func bodyTemperature() {418        let model = makeModel(category: "temperature", input: "98.6")419        #expect(model.from?.symbol == "°F")420        #expect(model.outcome.value?.decimal == decimal("37"))421    }422423    @Test func fuelEconomyReciprocalAndZero() {424        let model = makeModel(category: "fuelEconomy", input: "8")425        #expect(model.from?.symbol == "L/100 km")426        #expect(model.to?.symbol == "mpg (US)")427        #expect(model.resultText == "29.4018229167")428        let kmPerLitre = try! #require(model.rows.first { $0.choice.symbol == "km/L" })429        #expect(kmPerLitre.text == "12.5")430        model.setInputText("0")431        let failure = try! #require(model.outcome.failure)432        #expect(failure.title == "Undefined at zero")433        #expect(failure.message.contains("L/100 km"))434        #expect(model.rows.allSatisfy { $0.value == nil })435    }436}437438@MainActor @Suite struct RateConventionTests {439    @Test func sixPercentSemiAnnual() {440        let model = makeModel(category: "rates")441        #expect(model.isRates)442        guard case .table(let table) = model.rateOutcome else { Issue.record("no table"); return }443        #expect(table.inputConvention == .semiannual)444        #expect(abs(table.effectiveAnnual - 0.0609) < 1e-15)445        #expect(table.pivotFormula == "i = (1 + 0.06/2)^2 − 1")446        #expect(table.pivotText == "6.09\u{00A0}%")447        let monthly = try! #require(table.rows.first { $0.convention == .monthly })448        #expect(monthly.text == "5.92634643744\u{00A0}%")449        #expect(monthly.formula == "j = 12·((1 + i)^(1/12) − 1)")450        #expect(table.rows.first { $0.isInput }?.convention == .semiannual)451        #expect(table.rows.contains { $0.convention == .continuous })452        #expect(table.rows.contains { $0.convention == .effectiveDiscount })453        #expect(table.rows.contains { $0.convention == .periodic(periodsPerYear: 2) })454        #expect(Set(table.rows.map(\.id)).count == table.rows.count)455    }456457    @Test func keypadEditsTheRate() {458        let model = makeModel(category: "rates")459        model.press(.clear); model.press(.digit(5))460        #expect(model.state.rateText == "5")461        #expect(model.state.inputText == "1")462        model.state.rateKind = .effectiveAnnual463        guard case .table(let table) = model.rateOutcome else { Issue.record("no table"); return }464        #expect(table.pivotText == "5\u{00A0}%")465        let entry = try! #require(model.historyEntry())466        #expect(entry.display == "5\u{00A0}% effective annual")467    }468469    @Test func outOfDomainRateIsExplained() {470        let model = makeModel(category: "rates") { $0.rateText = "100"; $0.rateKind = .effectiveDiscount }471        guard case .failure(let failure) = model.rateOutcome else { Issue.record("expected a failure"); return }472        #expect(failure.title == "Rate out of domain")473        #expect(model.historyEntry() == nil)474    }475476    @Test func customPeriodsAddRows() {477        let model = makeModel(category: "rates") { $0.ratePeriods = 26 }478        guard case .table(let table) = model.rateOutcome else { Issue.record("no table"); return }479        #expect(table.rows.contains { $0.convention == .nominal(periodsPerYear: 26) && $0.isInput })480        #expect(table.rows.contains { $0.convention == .nominalDiscount(periodsPerYear: 26) })481    }482}483
Files main
Menu

Theme