Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Apps/ORIXMaps/Tests/ORIXMapsTests/LibraryModelTests.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 ORIXGeoCore90import ORIXGeoExchange91import ORIXMapRenderer92import ORIXMapStyle93import ORIXPlaces94import Testing95@testable import ORIXMaps9697struct LibraryModelTests {98 /// A library on a temporary database, with the map engine replaced by a recorder.99 final class Fixture {100 let dir = ScratchDirectory()101 let defaults = ScratchDefaults()102 let controller = MapController()103 let spy = SpyBackend()104 let settings: AppSettings105 let library: LibraryModel106 init() {107 settings = AppSettings(defaults: defaults.defaults)108 controller.attach(spy)109 controller.engineDidLoadStyle()110 library = LibraryModel(databaseURL: dir.url.appending(path: "places.sqlite"), map: controller, settings: settings)111 }112 func add(_ name: String, _ c: Coordinate, note: String = "") async -> SavedPlace? {113 guard let collection = library.collections.first else { return nil }114 return await library.save(SavedPlace(collectionID: collection.id, name: name, note: note, coordinate: c))115 }116 }117118 @Test func aNewLibraryHasOneDefaultCollection() async {119 let f = Fixture()120 #expect(f.library.isAvailable)121 await f.library.reload()122 #expect(f.library.collections.map(\.name) == [String(localized: "Favourites")])123 #expect(f.library.places.isEmpty && f.library.history.isEmpty)124 }125126 @Test func savedPlacesAreFoundNearbyAndDrawnAsPins() async throws {127 let f = Fixture()128 await f.library.reload()129 let saved = try #require(await f.add("Stade olympique", olympicStadium, note: "Tour inclinée"))130 #expect(f.library.places.map(\.name) == ["Stade olympique"])131 #expect(f.library.savedPlace(near: olympicStadium)?.id == saved.id)132 #expect(f.library.savedPlace(near: Coordinate(latitude: olympicStadium.latitude + 0.0001, longitude: olympicStadium.longitude))?.id == saved.id)133 #expect(f.library.savedPlace(near: downtownMontreal) == nil)134 #expect(f.spy.featureCount(OverlayID.pins) == 1)135 f.library.hiddenCollections = [saved.collectionID]136 #expect(f.spy.featureCount(OverlayID.pins) == 0)137 f.library.hiddenCollections = []138 await f.library.delete(saved)139 #expect(f.library.places.isEmpty && f.spy.featureCount(OverlayID.pins) == 0)140 }141142 @Test func theLastCollectionCannotBeDeleted() async throws {143 let f = Fixture()144 await f.library.reload()145 let only = try #require(f.library.collections.first)146 #expect(await f.library.deleteCollection(only.id) == false)147 await f.library.createCollection(name: "Voyage", symbol: "airplane", colorHex: "#3D5AFE")148 #expect(f.library.collections.count == 2)149 #expect(await f.library.deleteCollection(only.id))150 #expect(f.library.collections.map(\.name) == ["Voyage"])151 }152153 @Test(arguments: ExchangeFormat.allCases)154 func exportThenImportIntoAnotherCollection(format: ExchangeFormat) async throws {155 let f = Fixture()156 await f.library.reload()157 _ = await f.add("Stade olympique", olympicStadium, note: "Tour")158 _ = await f.add("Centre-ville", downtownMontreal)159 let source = try #require(f.library.collections.first)160 let file = try #require(await f.library.exportFile(collection: source.id, format: format))161 #expect(file.pathExtension == format.fileExtension)162 #expect(file.deletingPathExtension().lastPathComponent == source.name)163 #expect((try Data(contentsOf: file)).count > 100)164165 await f.library.createCollection(name: "Copie", symbol: "star.fill", colorHex: "#F5A623")166 let target = try #require(f.library.collections.first { $0.name == "Copie" })167 #expect(await f.library.importFile(file, into: target.id) == .places(2))168 let copies = f.library.places(in: target.id)169 #expect(Set(copies.map(\.name)) == ["Stade olympique", "Centre-ville"])170 let stadium = try #require(copies.first { $0.name == "Stade olympique" })171 #expect(Geodesy.fastDistance(stadium.coordinate, olympicStadium) < 1)172 }173174 @Test func exportOfAnEmptyCollectionGivesNoFile() async throws {175 let f = Fixture()176 await f.library.reload()177 let id = try #require(f.library.collections.first?.id)178 #expect(await f.library.exportFile(collection: id, format: .gpx) == nil)179 }180181 @Test func backupRestoresIntoAnEmptyLibrary() async throws {182 let a = Fixture()183 await a.library.reload()184 _ = await a.add("Stade olympique", olympicStadium, note: "Tour")185 _ = await a.add("Centre-ville", downtownMontreal)186 await a.library.createCollection(name: "Voyage", symbol: "airplane", colorHex: "#3D5AFE")187 let backup = try #require(await a.library.backupFile())188 #expect(backup.lastPathComponent == "ORIX Maps places backup.json")189190 let b = Fixture()191 await b.library.reload()192 let target = try #require(b.library.collections.first?.id)193 #expect(await b.library.importFile(backup, into: target) == .restored(2))194 #expect(Set(b.library.places.map(\.name)) == ["Stade olympique", "Centre-ville"])195 #expect(b.library.places.first { $0.name == "Stade olympique" }?.note == "Tour")196 #expect(b.library.collections.contains { $0.name == "Voyage" })197 }198199 @Test func importFailuresAreExplained() async throws {200 let f = Fixture()201 await f.library.reload()202 let files = ScratchDirectory()203 let target = try #require(f.library.collections.first?.id)204 let damaged = String(localized: "The file could not be read: it is damaged or not a GPX, GeoJSON or KML file.")205 #expect(await f.library.importFile(files.file("broken.gpx", "<gpx><wpt lat=\"45\""), into: target) == .failed(damaged))206 #expect(await f.library.importFile(files.file("broken.geojson", "{\"type\": \"FeatureCollection\", \"features\": 3}"), into: target) == .failed(damaged))207 #expect(await f.library.importFile(files.file("notes.txt", "just some text"), into: target)208 == .failed(String(localized: "This file format is not supported. Use GPX, GeoJSON or KML.")))209 #expect(await f.library.importFile(URL(fileURLWithPath: "/nonexistent/places.gpx"), into: target)210 == .failed(String(localized: "The file is too large or could not be read.")))211 let trackOnly = ExchangeCodec.encode(ExchangeDocument(tracks: [.init(name: "t", segments: [[.init(coordinate: downtownMontreal), .init(coordinate: olympicStadium)]])]), format: .gpx)212 #expect(await f.library.importFile(files.file("track.gpx", trackOnly), into: target)213 == .failed(String(localized: "This file contains no places (it may contain tracks: import it from Tracks).")))214 #expect(f.library.places.isEmpty)215 }216217 @Test func historyIsRecordedOnlyWhenEnabledAndCanBeErased() async {218 let f = Fixture()219 await f.library.reload()220 await f.library.record(search: "café")221 await f.library.record(place: PlaceSelection(title: "Stade olympique", subtitle: "Montréal", coordinate: olympicStadium, origin: .search))222 #expect(f.library.history.count == 2)223 #expect(Set(f.library.history.map(\.title)) == ["café", "Stade olympique"])224 if let first = f.library.history.first {225 await f.library.deleteHistory(first)226 #expect(f.library.history.count == 1)227 }228 await f.library.eraseHistory()229 #expect(f.library.history.isEmpty)230231 f.settings.historyEnabled = false232 await f.library.record(search: "pharmacie")233 await f.library.record(place: PlaceSelection(title: "X", subtitle: nil, coordinate: downtownMontreal, origin: .droppedPin))234 f.settings.historyEnabled = true235 await f.library.reload()236 #expect(f.library.history.isEmpty, "nothing was written while history was off")237 }238239 @Test func turningHistoryOffHidesWhatWasKept() async {240 let f = Fixture()241 await f.library.reload()242 await f.library.record(search: "café")243 f.settings.historyEnabled = false244 await f.library.reload()245 #expect(f.library.history.isEmpty)246 }247248 @Test func temporaryFilesGetAUsableName() throws {249 let named = try #require(LibraryModel.temporaryFile(named: "a.gpx", data: Data("x".utf8)))250 #expect(named.lastPathComponent == "a.gpx" && FileManager.default.fileExists(atPath: named.path))251 let unnamed = try #require(LibraryModel.temporaryFile(named: "", data: Data("x".utf8)))252 #expect(unnamed.lastPathComponent == "export")253 }254}255