Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFeatureConvert/Tests/ORIXFeatureConvertTests/CurrencyModelTests.swift3// Description: Currency tests — no request without the explicit action, manual rates, fake ECB download, provenance, staleness, failures.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXExpression10import ORIXUI11import ORIXUnits1213@testable import ORIXFeatureConvert1415/// Records every call; answers with a canned document or error.16final class FakeDownloader: RatesDownloading, @unchecked Sendable {17 private let lock = NSLock()18 private var answer: Result<Data, any Error>19 private var count = 02021 init(_ answer: Result<Data, any Error>) { self.answer = answer }2223 var calls: Int { lock.withLock { count } }24 func setAnswer(_ answer: Result<Data, any Error>) { lock.withLock { self.answer = answer } }2526 func downloadDailyRates() async throws -> Data {27 let current = lock.withLock { () -> Result<Data, any Error> in28 count += 129 return answer30 }31 return try current.get()32 }33}3435/// A settable clock.36final class Clock: @unchecked Sendable {37 private let lock = NSLock()38 private var value: Date39 init(_ iso: String) { value = Clock.date(iso) }40 var now: Date { lock.withLock { value } }41 func set(_ iso: String) { lock.withLock { value = Clock.date(iso) } }42 static func date(_ iso: String) -> Date { ISO8601DateFormatter().date(from: iso)! }43}4445@MainActor46func makeCurrencyModel(downloader: FakeDownloader, clock: Clock, store: CurrencyStore = CurrencyStore(), from: String = "USD", to: String = "CAD", input: String = "100") -> ConvertModel {47 var state = ConvertState()48 state.categoryID = "currency"49 state.inputText = input50 state.pairs["currency"] = UnitPair(from: from, to: to)51 return ConvertModel(state: state, currency: store, downloader: downloader, now: { clock.now })52}5354@MainActor @Suite struct CurrencyModelTests {55 @Test func nothingIsShownAndNothingIsRequestedWithoutRates() async {56 let downloader = FakeDownloader(.success(ECBFixture.data))57 let model = makeCurrencyModel(downloader: downloader, clock: Clock("2026-11-20T18:00:00Z"))58 guard case .needsRates(let message) = model.outcome else { Issue.record("expected needsRates"); return }59 #expect(message == "No exchange rate is stored on this device.")60 #expect(model.resultText == nil)61 #expect(model.rows.allSatisfy { $0.value == nil })62 #expect(model.pairProvenance == nil)63 #expect(model.historyEntry() == nil)6465 // Using every other feature never reaches the network.66 model.press(.digit(5)); model.swap(); model.setTo("EUR"); model.setFrom("GBP")67 model.selectCategory("length"); model.selectCategory("rates"); model.selectCategory("currency")68 model.acceptPendingValue(42)69 _ = model.setManualRate(text: "1.25")70 model.removeManualRate()71 await Task.yield()72 #expect(downloader.calls == 0)73 #expect(model.downloadCount == 0)74 #expect(model.downloadState == .idle)75 }7677 @Test func manualRateIsStoredAndFlagged() throws {78 let downloader = FakeDownloader(.success(ECBFixture.data))79 let clock = Clock("2026-11-20T14:30:00Z")80 let model = makeCurrencyModel(downloader: downloader, clock: clock)81 #expect(model.setManualRate(text: "1.38") == nil)82 let value = try #require(model.outcome.value)83 #expect(value.decimal == decimal("138"))84 #expect(value.relation == "≈")85 let provenance = try #require(value.provenance)86 #expect(provenance.isManual)87 #expect(provenance.staleness == .manual)88 #expect(provenance.text.hasPrefix("Manual rate, entered 2026-11-20"))89 #expect(provenance.text.hasSuffix("— less than 1 hour old"))90 #expect(provenance.shortText == "Manual")91 #expect(model.hasManualRateForPair)92 #expect(model.resultText == "138.00")93 #expect(model.pairRateLine == "1 USD ≈ 1.38 CAD")9495 // The inverse direction uses the same manual rate.96 model.swap()97 #expect(model.outcome.value?.provenance?.isManual == true)98 #expect(model.resultText == "72.46")99 model.swap()100101 // Persisted with its flag.102 let restored = try JSONDecoder().decode(CurrencyStore.self, from: JSONEncoder().encode(model.currency))103 #expect(restored == model.currency)104 #expect(restored.manualPairs.first?.rate(for: "CAD")?.isManual == true)105106 #expect(model.setManualRate(text: "0") != nil)107 #expect(model.setManualRate(text: "-2") != nil)108 #expect(model.setManualRate(text: "abc") != nil)109 #expect(model.currency.manualPairs.count == 1)110 #expect(model.setManualRate(text: "1.40") == nil)111 #expect(model.currency.manualPairs.count == 1)112 #expect(model.outcome.value?.decimal == decimal("140"))113114 model.removeManualRate()115 #expect(!model.currency.hasAnyRate)116 #expect(model.outcome.value == nil)117 #expect(downloader.calls == 0)118 }119120 @Test func explicitUpdateStoresTheTableWithSourceAndTimestamp() async throws {121 let downloader = FakeDownloader(.success(ECBFixture.data))122 let clock = Clock("2026-11-20T18:00:00Z")123 let model = makeCurrencyModel(downloader: downloader, clock: clock, from: "EUR", to: "USD")124 await model.updateRates()125 #expect(downloader.calls == 1)126 #expect(model.downloadCount == 1)127 guard case .updated = model.downloadState else { Issue.record("expected updated"); return }128129 let reference = try #require(model.currency.reference)130 #expect(reference.base == "EUR")131 #expect(reference.source == CurrencyRates.ecbSourceName)132 #expect(reference.timestamp == Clock.date("2026-11-20T15:00:00Z"))133 #expect(reference.codes.count == 30)134 #expect(model.currency.downloadedAt == clock.now)135136 let value = try #require(model.outcome.value)137 #expect(value.decimal == decimal("109.9"))138 #expect(model.resultText == "109.90")139 let provenance = try #require(value.provenance)140 #expect(provenance.text == "ECB reference rates, 2026-11-20 16:00 CET — 3 hours old")141 #expect(provenance.shortText == "ECB 2026-11-20")142 #expect(provenance.staleWarning == nil)143 #expect(!provenance.isManual)144 #expect(model.historyEntry()?.explanation.assumptions.contains(provenance.text) == true)145146 // Cross rate through the base, and every row carries its provenance.147 model.setFrom("USD"); model.setTo("JPY")148 #expect(model.outcome.value?.decimal == (try reference.convert(decimal("100"), from: "USD", to: "JPY")))149 #expect(model.resultText == "15864")150 #expect(model.rows.filter { $0.value != nil }.count == 30)151 #expect(model.rows.filter { $0.value != nil }.allSatisfy { $0.value?.provenance != nil })152 // A currency of the ISO list that the ECB table does not quote has no number.153 #expect(model.rows.first { $0.choice.id == "AED" }?.value == nil)154155 // Stored through the app's persistence, restored with source and timestamp.156 let defaults = UserDefaults(suiteName: "orix.convert.tests.\(UUID().uuidString)")!157 let app = AppModel(settings: AppSettings(defaults: defaults), inMemory: true)158 app.saveState(model.currency, key: ConvertStorage.currencyKey)159 let restored = try #require(app.loadState(CurrencyStore.self, key: ConvertStorage.currencyKey))160 #expect(restored == model.currency)161 #expect(restored.reference?.timestamp == reference.timestamp)162 }163164 @Test func stalenessWarning() async throws {165 let downloader = FakeDownloader(.success(ECBFixture.data))166 let clock = Clock("2026-11-20T18:00:00Z")167 let model = makeCurrencyModel(downloader: downloader, clock: clock, from: "EUR", to: "USD")168 await model.updateRates()169 #expect(model.pairProvenance?.staleWarning == nil)170171 clock.set("2026-11-21T16:00:00Z")172 let provenance = try #require(model.pairProvenance)173 #expect(provenance.text == "ECB reference rates, 2026-11-20 16:00 CET — 1 day old")174 guard case .stale = provenance.staleness else { Issue.record("expected stale"); return }175 #expect(provenance.staleWarning?.contains("1 day old") == true)176177 clock.set("2026-11-23T08:00:00Z")178 #expect(model.pairProvenance?.text.hasSuffix("— 2 days old") == true)179 #expect(model.referenceProvenance?.staleWarning != nil)180181 // A manual rate for the pair is not "stale": it has no market timestamp.182 #expect(model.setManualRate(text: "1.10") == nil)183 #expect(model.pairProvenance?.staleness == .manual)184 #expect(model.outcome.value?.decimal == decimal("110"))185 model.removeManualRate()186 #expect(model.outcome.value?.decimal == decimal("109.9"))187 }188189 @Test func failedUpdateKeepsThePreviousRates() async throws {190 let downloader = FakeDownloader(.success(ECBFixture.data))191 let clock = Clock("2026-11-20T18:00:00Z")192 let model = makeCurrencyModel(downloader: downloader, clock: clock, from: "EUR", to: "USD")193 await model.updateRates()194 let before = model.currency195196 downloader.setAnswer(.failure(URLError(.notConnectedToInternet)))197 await model.updateRates()198 guard case .failed(let message) = model.downloadState else { Issue.record("expected failed"); return }199 #expect(message.hasPrefix("The rates were not updated:"))200 #expect(message.hasSuffix("The previous rates are kept."))201 #expect(model.currency == before)202 #expect(model.outcome.value?.decimal == decimal("109.9"))203204 downloader.setAnswer(.success(Data("<html>maintenance</html>".utf8)))205 await model.updateRates()206 guard case .failed(let malformed) = model.downloadState else { Issue.record("expected failed"); return }207 #expect(malformed.contains("Malformed ECB document"))208 #expect(model.currency == before)209210 downloader.setAnswer(.failure(RatesDownloadError.http(status: 503)))211 await model.updateRates()212 guard case .failed(let http) = model.downloadState else { Issue.record("expected failed"); return }213 #expect(http.contains("503"))214 #expect(downloader.calls == 4)215 model.dismissDownloadMessage()216 #expect(model.downloadState == .idle)217 }218219 @Test func failedFirstUpdateLeavesNoRates() async {220 let downloader = FakeDownloader(.failure(URLError(.timedOut)))221 let model = makeCurrencyModel(downloader: downloader, clock: Clock("2026-11-20T18:00:00Z"))222 await model.updateRates()223 guard case .failed(let message) = model.downloadState else { Issue.record("expected failed"); return }224 #expect(message.hasSuffix("No rates were stored."))225 #expect(!model.currency.hasAnyRate)226 guard case .needsRates = model.outcome else { Issue.record("expected needsRates"); return }227 }228229 @Test func summerTimestampUsesCEST() {230 #expect(RateProvenanceText.frankfurtStamp(Clock.date("2026-07-01T14:00:00Z")) == "2026-07-01 16:00 CEST")231 #expect(RateProvenanceText.ageText(0) == "less than 1 hour old")232 #expect(RateProvenanceText.ageText(3600) == "1 hour old")233 #expect(RateProvenanceText.ageText(3 * 86_400 + 5) == "3 days old")234 }235}236