SPB Git

Repository Public BSD-3-Clause

PlacesStoreTests.swift 12.6 KB 234 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXPlaces/Tests/ORIXPlacesTests/PlacesStoreTests.swift10// Module           : ORIXPlacesTests11// 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 Testing92@testable import ORIXPlaces9394private let mtl = Coordinate(latitude: 45.5088, longitude: -73.5878)9596@Suite struct PlacesStoreTests {97    @Test func startsWithOneCollectionAndKeepsAtLeastOne() async throws {98        let store = try PlacesStore(url: nil, defaultCollectionName: "Favoris")99        var cs = try await store.collections()100        #expect(cs.count == 1 && cs[0].name == "Favoris")101        await #expect(throws: PlacesError.lastCollection) { try await store.deleteCollection(cs[0].id) }102        let trips = try await store.createCollection(name: "  Voyages  ", symbol: "airplane", colorHex: "#3F6FB5")103        #expect(trips.name == "Voyages")104        await #expect(throws: PlacesError.emptyName) { try await store.createCollection(name: "   ") }105        try await store.reorderCollections([trips.id, cs[0].id])106        cs = try await store.collections()107        #expect(cs.map(\.name) == ["Voyages", "Favoris"])108        var renamed = trips; renamed.name = "Trips"109        try await store.update(renamed)110        #expect(try await store.collections()[0].name == "Trips")111    }112113    @Test func savesEditsFindsAndDeletesPlaces() async throws {114        let store = try PlacesStore(url: nil)115        let fav = try await store.collections()[0]116        var p = try await store.save(SavedPlace(collectionID: fav.id, name: " Café Olimpico ", note: "Meilleur espresso", coordinate: mtl, address: "124 Rue Saint-Viateur O", category: "cafe"))117        #expect(p.name == "Café Olimpico")118        p.note = "Fermé le lundi"; p.symbol = "cup.and.saucer.fill"; p.colorHex = "#C9661E"119        try await store.save(p)120        #expect(try await store.place(p.id) == p)121        #expect(try await store.places(in: fav.id).count == 1)122        #expect(try await store.counts()[fav.id] == 1)123        #expect(try await store.search("cafe olimp").map(\.id) == [p.id])124        #expect(try await store.search("FERME").map(\.id) == [p.id])125        #expect(try await store.search("zzz").isEmpty)126        #expect(try await store.search(" ").isEmpty)127        #expect(try await store.nearest(to: Geodesy.destination(from: mtl, bearing: 90, distance: 8))?.id == p.id)128        #expect(try await store.nearest(to: Geodesy.destination(from: mtl, bearing: 90, distance: 40)) == nil)129        await #expect(throws: PlacesError.invalidCoordinate) { try await store.save(SavedPlace(collectionID: fav.id, name: "x", coordinate: Coordinate(latitude: 95, longitude: 0))) }130        await #expect(throws: PlacesError.emptyName) { try await store.save(SavedPlace(collectionID: fav.id, name: " ", coordinate: mtl)) }131        await #expect(throws: PlacesError.unknownCollection) { try await store.save(SavedPlace(collectionID: UUID(), name: "x", coordinate: mtl)) }132        try await store.deletePlace(p.id)133        #expect(try await store.places().isEmpty)134    }135136    @Test func deletingACollectionDeletesItsPlaces() async throws {137        let store = try PlacesStore(url: nil)138        let c = try await store.createCollection(name: "Tmp")139        try await store.save(SavedPlace(collectionID: c.id, name: "A", coordinate: mtl))140        try await store.deleteCollection(c.id)141        #expect(try await store.places().isEmpty)142        #expect(try await store.collections().count == 1)143    }144145    @Test func persistsOnDiskAndLimitsTextLengths() async throws {146        let url = FileManager.default.temporaryDirectory.appending(path: "orix-places-\(UUID().uuidString)/places.sqlite")147        defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }148        var id: UUID?149        do {150            let store = try PlacesStore(url: url)151            let fav = try await store.collections()[0]152            id = try await store.save(SavedPlace(collectionID: fav.id, name: String(repeating: "n", count: 500), note: String(repeating: "x", count: 9_000), coordinate: mtl)).id153        }154        let reopened = try PlacesStore(url: url)155        let savedID = try #require(id)156        let p = try #require(try await reopened.place(savedID))157        #expect(p.name.count == PlacesStore.maxNameLength && p.note.count == PlacesStore.maxNoteLength)158        #expect(try await reopened.collections().count == 1)159    }160161    @Test func exportsAndImportsThroughEveryInterchangeFormat() async throws {162        let store = try PlacesStore(url: nil)163        let fav = try await store.collections()[0]164        try await store.save(SavedPlace(collectionID: fav.id, name: "Belvédère", note: "Vue <superbe> & gratuite", coordinate: mtl))165        try await store.save(SavedPlace(collectionID: fav.id, name: "Sans note", coordinate: Coordinate(latitude: 46.8139, longitude: -71.208)))166        let doc = try await store.exportDocument(collection: fav.id)167        #expect(doc.name == "Favourites" && doc.waypoints.count == 2)168        for format in ExchangeFormat.allCases {169            let other = try PlacesStore(url: nil)170            let target = try await other.collections()[0]171            let decoded = try ExchangeCodec.decode(ExchangeCodec.encode(doc, format: format), format: format)172            #expect(try await other.importDocument(decoded, into: target.id) == 2, "\(format)")173            #expect(try await other.importDocument(decoded, into: target.id) == 0, "\(format): second import must skip duplicates")174            let places = try await other.places()175            #expect(places.map(\.name).sorted() == ["Belvédère", "Sans note"] && places.first { $0.name == "Belvédère" }?.note == "Vue <superbe> & gratuite", "\(format)")176        }177        // A waypoint with no name is saved under its coordinates.178        let unnamed = ExchangeDocument(waypoints: [.init(coordinate: mtl)])179        let other = try PlacesStore(url: nil)180        let firstID = try await other.collections()[0].id181        try await other.importDocument(unnamed, into: firstID)182        #expect(try await other.places()[0].name == "45.50880, -73.58780")183    }184185    @Test func backupRestoresEverythingAndRejectsForeignFiles() async throws {186        let store = try PlacesStore(url: nil)187        let fav = try await store.collections()[0]188        let trips = try await store.createCollection(name: "Trips", symbol: "airplane", colorHex: "#3F6FB5")189        let a = try await store.save(SavedPlace(collectionID: fav.id, name: "A", note: "n", coordinate: mtl, symbol: "star", colorHex: "#FF0000", address: "1 rue X", category: "cafe"))190        try await store.save(SavedPlace(collectionID: trips.id, name: "B", coordinate: mtl))191        let data = try await store.backup()192        let fresh = try PlacesStore(url: nil)193        #expect(try await fresh.restore(data) == 2)194        #expect(try await fresh.collections().count == 3)195        let restored = try #require(try await fresh.place(a.id))196        #expect(restored.symbol == "star" && restored.address == "1 rue X" && restored.note == "n" && abs(restored.createdAt.timeIntervalSince(a.createdAt)) < 1)197        #expect(try await fresh.restore(data) == 2)198        #expect(try await fresh.places().count == 2)199        await #expect(throws: PlacesError.self) { try await fresh.restore(Data("{}".utf8)) }200        await #expect(throws: PlacesError.self) { try await fresh.restore(Data("garbage".utf8)) }201    }202203    @Test func historyDeduplicatesIsCappedAndCanBeErased() async throws {204        let store = try PlacesStore(url: nil)205        let t = Date(timeIntervalSince1970: 1_800_000_000)206        try await store.record(.search, title: "café", date: t)207        try await store.record(.place, title: "Stade olympique", subtitle: "Montréal", coordinate: mtl, date: t.addingTimeInterval(1))208        try await store.record(.search, title: "café", date: t.addingTimeInterval(2))209        try await store.record(.search, title: "   ", date: t.addingTimeInterval(3))210        var h = try await store.history()211        #expect(h.map(\.title) == ["café", "Stade olympique"] && h[1].coordinate == mtl && h[1].subtitle == "Montréal")212        try await store.deleteHistoryEntry(h[0].id)213        #expect(try await store.history().count == 1)214        for i in 0..<(PlacesStore.maxHistory + 30) { try await store.record(.search, title: "q\(i)", date: t.addingTimeInterval(Double(10 + i))) }215        h = try await store.history(limit: 1_000)216        #expect(h.count == PlacesStore.maxHistory && h[0].title == "q\(PlacesStore.maxHistory + 29)")217        try await store.eraseHistory()218        #expect(try await store.history().isEmpty)219    }220221    @Test func erasedHistoryLeavesNoTraceInTheFile() async throws {222        let url = FileManager.default.temporaryDirectory.appending(path: "orix-places-\(UUID().uuidString)/places.sqlite")223        defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }224        let store = try PlacesStore(url: url)225        let secret = "clinique-confidentielle-XYZZY"226        try await store.record(.search, title: secret)227        try await store.eraseHistory()228        for name in try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path) {229            let bytes = try Data(contentsOf: url.deletingLastPathComponent().appending(path: name))230            #expect(bytes.range(of: Data(secret.utf8)) == nil, "\(name) still contains the erased search")231        }232    }233}234
Files main
Menu

Theme