Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Packages/ORIXLocation/Tests/ORIXLocationTests/LocationTests.swift10// Module : ORIXLocationTests11// 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 Testing91@testable import ORIXLocation9293@MainActor private final class FakeProvider: LocationProvider {94 var authorization: LocationAuthorization95 var onAuthorization: ((LocationAuthorization) -> Void)?96 var onFix: ((LocationFix) -> Void)?97 var onHeading: ((HeadingFix) -> Void)?98 var onError: ((LocationError) -> Void)?99 var log: [String] = []100 var answer: LocationAuthorization = .authorized(precise: true)101 init(_ a: LocationAuthorization) { authorization = a }102 func requestAuthorization() { log.append("request"); authorization = answer; onAuthorization?(answer) }103 func start(_ usage: LocationUsage) { log.append("start \(usage)") }104 func stop() { log.append("stop") }105 func startHeading() { log.append("heading on") }106 func stopHeading() { log.append("heading off") }107}108109private let t0 = Date(timeIntervalSince1970: 1_800_000_000)110private func fix(_ lat: Double, _ t: TimeInterval, accuracy: Double = 5) -> LocationFix {111 LocationFix(coordinate: Coordinate(latitude: lat, longitude: -73.5), horizontalAccuracy: accuracy, timestamp: t0.addingTimeInterval(t))112}113114@MainActor @Suite struct LocationServiceTests {115 @Test func permissionIsRequestedOnlyWhenAFeatureStarts() {116 let p = FakeProvider(.notDetermined)117 let s = LocationService(provider: p)118 #expect(p.log.isEmpty && s.authorization == .notDetermined)119 s.start(.browsing)120 #expect(p.log == ["request", "start browsing"] && s.usage == .browsing && s.authorization == .authorized(precise: true))121 }122123 @Test func refusalIsReportedAndNothingStarts() {124 let p = FakeProvider(.notDetermined); p.answer = .denied125 let s = LocationService(provider: p)126 s.start(.navigation)127 #expect(s.lastError == .denied && s.usage == nil && !p.log.contains { $0.hasPrefix("start") })128 s.start(.browsing)129 #expect(p.log.filter { $0 == "request" }.count == 1 && s.lastError == .denied)130 }131132 @Test func revokingPermissionClearsThePosition() {133 let p = FakeProvider(.authorized(precise: true))134 let s = LocationService(provider: p)135 s.start(.browsing); p.onFix?(fix(45.5, 0))136 #expect(s.lastFix != nil)137 p.authorization = .denied; p.onAuthorization?(.denied)138 #expect(s.lastFix == nil && s.usage == nil && s.lastError == .denied && p.log.last == "stop")139 }140141 @Test func usageTransitionsAndBackgroundRule() {142 let p = FakeProvider(.authorized(precise: false))143 let s = LocationService(provider: p)144 s.start(.browsing); s.start(.browsing); s.start(.navigation)145 #expect(p.log == ["start browsing", "start navigation"])146 s.end(.recording)147 #expect(s.usage == .navigation)148 s.end(.navigation)149 #expect(s.usage == .browsing && p.log.last == "start browsing")150 s.end(.browsing)151 #expect(s.usage == nil && p.log.last == "stop")152 #expect(!LocationUsage.browsing.continuesInBackground && LocationUsage.navigation.continuesInBackground && LocationUsage.recording.continuesInBackground)153 }154155 @Test func fixesAreFilteredOrderedAndFannedOut() {156 let p = FakeProvider(.authorized(precise: true))157 var clock = t0.addingTimeInterval(1)158 let s = LocationService(provider: p, now: { clock })159 var received: [Double] = []160 let token = s.addConsumer { received.append($0.coordinate.latitude) }161 s.start(.browsing)162 p.onFix?(fix(45.5, 0)); p.onFix?(fix(45.4, -10)); p.onFix?(fix(45.6, 1, accuracy: -1))163 p.onFix?(LocationFix(coordinate: Coordinate(latitude: 99, longitude: 0), horizontalAccuracy: 5, timestamp: t0.addingTimeInterval(2)))164 #expect(received == [45.5] && s.lastFix?.coordinate.latitude == 45.5 && s.isFixFresh)165 clock = t0.addingTimeInterval(60)166 #expect(!s.isFixFresh)167 s.removeConsumer(token); p.onFix?(fix(45.7, 61))168 #expect(received == [45.5] && s.lastFix?.coordinate.latitude == 45.7)169 #expect(!fix(45, 0, accuracy: 500).isUsable(now: t0))170 }171172 @Test func headingIsReferenceCountedAndInvalidHeadingsAreDropped() {173 let p = FakeProvider(.authorized(precise: true))174 let s = LocationService(provider: p)175 s.retainHeading(); s.retainHeading()176 p.onHeading?(HeadingFix(trueHeading: nil, magneticHeading: 90, accuracy: 10))177 #expect(s.heading?.best == 90)178 p.onHeading?(HeadingFix(trueHeading: 10, magneticHeading: 20, accuracy: -1))179 #expect(s.heading == nil)180 s.releaseHeading()181 #expect(p.log == ["heading on"])182 s.releaseHeading(); s.releaseHeading()183 #expect(p.log == ["heading on", "heading off"])184 }185186 @Test func switchingToASimulationKeepsTheUsageRunning() {187 let real = FakeProvider(.authorized(precise: true)), sim = FakeProvider(.authorized(precise: true))188 let s = LocationService(provider: real)189 s.start(.navigation); s.retainHeading(); real.onFix?(fix(45.5, 0))190 s.setProvider(sim)191 #expect(real.log.suffix(2) == ["stop", "heading off"] && sim.log == ["start navigation", "heading on"] && s.lastFix == nil)192 real.onFix?(fix(45.9, 5))193 #expect(s.lastFix == nil)194 }195}196197@MainActor @Suite struct SimulatedProviderTests {198 private let path = [Coordinate(latitude: 45.5, longitude: -73.6), Coordinate(latitude: 45.5, longitude: -73.59), Coordinate(latitude: 45.51, longitude: -73.59)]199200 @Test func interpolatesOnThePathOnly() throws {201 let p = SimulatedLocationProvider(path: path, speed: 10)202 let total = try #require(p.samples.last?.time)203 #expect(abs(total - Geodesy.length(of: path) / 10) < 0.01)204 let mid = try #require(p.fix(at: p.samples[1].time / 2, now: t0))205 #expect(abs(mid.coordinate.longitude - -73.595) < 1e-9 && mid.coordinate.latitude == 45.5)206 #expect(abs(mid.speed! - 10) < 0.01 && abs(mid.course! - 90) < 0.1)207 let turned = try #require(p.fix(at: p.samples[1].time + 5, now: t0))208 #expect(abs(turned.course!) < 0.1 && turned.coordinate.longitude == -73.59)209 // Before the start and after the end the position stays on the end points.210 #expect(p.fix(at: -50, now: t0)?.coordinate == path[0])211 #expect(p.fix(at: total + 500, now: t0)?.coordinate == path[2])212 #expect(SimulatedLocationProvider(samples: []).fix(at: 0, now: t0) == nil)213 }214215 @Test func seekEmitsFixesAndCourseAsHeading() {216 let p = SimulatedLocationProvider(path: path, speed: 10)217 var fixes: [LocationFix] = [], headings: [Double] = []218 p.onFix = { fixes.append($0) }; p.onHeading = { headings.append($0.best) }219 p.startHeading()220 p.seek(to: 10, now: t0); p.seek(to: 1_000, now: t0.addingTimeInterval(1))221 #expect(fixes.count == 2 && p.isFinished && fixes[1].coordinate == path[2])222 #expect(headings.count == 2 && abs(headings[0] - 90) < 0.1)223 }224225 @Test func playsInRealTimeAtARate() async throws {226 let p = SimulatedLocationProvider(path: path, speed: 10, rate: 400, interval: 0.05)227 var count = 0228 p.onFix = { _ in count += 1 }229 p.start(.navigation)230 try await Task.sleep(for: .milliseconds(600))231 p.stop()232 #expect(count >= 3 && p.isFinished)233 }234}235