SPB Git

Repository Public BSD-3-Clause

RegionsModelMessageTests.swift 10.6 KB 187 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Tests/ORIXMapsTests/RegionsModelMessageTests.swift10// Module           : ORIXMapsTests11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import ORIXMapPackage90import Testing91@testable import ORIXMaps9293/// The sentences shown for the main failures of the catalog, a download and an installation. Each expectation names94/// the English source string; it is resolved in the language the tests run in, like the code under test.95struct RegionsModelMessageTests {96    private let v1 = DataVersion("2026.11.01")!, v2 = DataVersion("2026.11.24")!9798    @Test func signatureProblemsSayTheFileIsNotFromORIXLabs() {99        let expected = String(localized: "This file is not signed by ORIX Labs. It was not installed.")100        let errors: [PackageError] = [.unknownSigningKey(keyId: "k"), .revokedSigningKey(keyId: "k"), .expiredSigningKey(keyId: "k", notAfter: .distantPast),101                                      .signingKeyNotYetValid(keyId: "k", notBefore: .distantFuture), .signingKeyMismatch(header: "a", manifest: "b"), .invalidSignature]102        for e in errors {103            #expect(RegionsModel.describe(e) == expected)104            #expect(RegionsModel.describe(RegionStoreError.package(e)) == expected)105            #expect(RegionsModel.describe(DownloadError.invalidPackage(e)) == expected)106        }107    }108109    @Test func otherPackageProblems() {110        #expect(RegionsModel.describe(PackageError.badMagic) == String(localized: "This file is not a valid ORIX Maps region. It was not installed."))111        #expect(RegionsModel.describe(PackageError.emptyManifest) == String(localized: "This file is not a valid ORIX Maps region. It was not installed."))112    }113114    @Test func storeErrors() {115        #expect(RegionsModel.describe(RegionStoreError.downgradeRefused(regionId: "r", installed: v2, offered: v1)) == String(localized: "This file contains older map data than the installed version."))116        #expect(RegionsModel.describe(RegionStoreError.alreadyInstalled(regionId: "r", version: v2)) == String(localized: "This version is already installed."))117        #expect(RegionsModel.describe(RegionStoreError.regionNotInstalled(regionId: "r")) == String(localized: "The operation could not be completed on this device's storage."))118        #expect(RegionsModel.describe(RegionStoreError.noPreviousVersion(regionId: "r")) == String(localized: "The operation could not be completed on this device's storage."))119        #expect(RegionsModel.describe(RegionStoreError.cancelled) == String(localized: "Cancelled."))120    }121122    @Test func missingSpaceGivesTheMissingAmount() {123        let amount = ByteCountFormatter.string(fromByteCount: 150_000_000, countStyle: .file)124        let expected = String(localized: "Not enough free space: \(amount) more is needed.")125        #expect(expected.contains(amount))126        #expect(RegionsModel.describe(RegionStoreError.notEnoughSpace(required: 500_000_000, available: 350_000_000, missing: 150_000_000)) == expected)127        #expect(RegionsModel.describe(DownloadError.notEnoughSpace(required: 500_000_000, available: 350_000_000, missing: 150_000_000)) == expected)128    }129130    @Test func downloadErrors() {131        #expect(RegionsModel.describe(DownloadError.offline) == String(localized: "No internet connection. The download will resume where it stopped."))132        #expect(RegionsModel.describe(DownloadError.rateLimited(retryAfter: 30)) == String(localized: "The server is busy. Try again in a moment."))133        #expect(RegionsModel.describe(DownloadError.httpStatus(503)) == String(localized: "The server answered with an error (\(503))."))134        #expect(RegionsModel.describe(DownloadError.httpStatus(503)).contains("503"))135        let altered = String(localized: "The download was incomplete or altered. Try again.")136        #expect(RegionsModel.describe(DownloadError.checksumMismatch(expected: "a", actual: "b")) == altered)137        #expect(RegionsModel.describe(DownloadError.sizeMismatch(expected: 2, actual: 1)) == altered)138        #expect(RegionsModel.describe(DownloadError.serverFileChanged) == altered)139        #expect(RegionsModel.describe(DownloadError.interrupted(received: 1, expected: 2)) == altered)140        #expect(RegionsModel.describe(DownloadError.paused) == String(localized: "Paused."))141        #expect(RegionsModel.describe(DownloadError.cancelled) == String(localized: "Cancelled."))142        #expect(RegionsModel.describe(DownloadError.nothingToResume(regionId: "r")) == String(localized: "The download failed. Try again."))143        #expect(RegionsModel.describe(DownloadError.packageMismatch(.region(expected: "a", found: "b"))) == String(localized: "The downloaded file is not the map that was requested. It was not installed."))144        // An installation refusal after a download reads like the same refusal on import.145        #expect(RegionsModel.describe(DownloadError.install(.alreadyInstalled(regionId: "r", version: v2))) == String(localized: "This version is already installed."))146    }147148    @Test func catalogErrors() {149        let generic = String(localized: "The map catalog could not be loaded. Check the connection and try again.")150        #expect(RegionsModel.describe(CatalogError.offline) == generic)151        #expect(RegionsModel.describe(CatalogError.httpStatus(500)) == generic)152        #expect(RegionsModel.describe(CatalogError.notDecodable(detail: "x")) == generic)153    }154155    @Test func noMessageIsEmptyOrLeaksAFormatSpecifier() {156        let all = [RegionsModel.describe(DownloadError.offline), RegionsModel.describe(DownloadError.httpStatus(404)), RegionsModel.describe(CatalogError.offline),157                   RegionsModel.describe(PackageError.invalidSignature), RegionsModel.describe(RegionStoreError.cancelled),158                   RegionsModel.describe(RegionStoreError.notEnoughSpace(required: 2, available: 1, missing: 1))]159        for m in all { #expect(!m.isEmpty && !m.contains("%@") && !m.contains("%lld")) }160    }161162    @Test func aModelPointedAtAnUnreachableCatalogReportsItAndKeepsWorking() async {163        let root = ScratchDirectory(), caches = ScratchDirectory()164        let model = RegionsModel(root: root.url, caches: caches.url, catalogURL: URL(string: "http://127.0.0.1:9/maps/v1/"))165        #expect(model.storeError == nil)166        await model.start()167        #expect(model.installed.isEmpty && model.catalog == nil && model.downloads.isEmpty)168        await model.refreshCatalog(force: true)169        #expect(model.catalog == nil)170        #expect(model.catalogError != nil)171        #expect(!model.isLoadingCatalog)172        #expect(model.totalInstalledBytes == 0)173        #expect(model.installedRegion("ca-qc-montreal") == nil)174    }175176    @Test func importingAFileThatIsNotAPackageExplainsWhy() async {177        let root = ScratchDirectory(), caches = ScratchDirectory(), files = ScratchDirectory()178        let model = RegionsModel(root: root.url, caches: caches.url, catalogURL: URL(string: "http://127.0.0.1:9/maps/v1/"))179        await model.start()180        let ok = await model.importPackage(from: files.file("fake.orixmap", Data(repeating: 7, count: 4096)))181        #expect(!ok)182        #expect(model.lastFailure == String(localized: "This file is not a valid ORIX Maps region. It was not installed.")183                || model.lastFailure == String(localized: "This file is damaged or incomplete. It was not installed."))184        #expect(model.installed.isEmpty)185    }186}187
Files main
Menu

Theme