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/ORIXNavigation/Tests/ORIXNavigationTests/NavigationTests.swift10// Module : ORIXNavigationTests11// 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 ORIXNavigation92@testable import ORIXRouting9394private let t0 = Date(timeIntervalSince1970: 1_800_000_000)95private let a = Coordinate(latitude: 45.5000, longitude: -73.6000)96/// East 1 000 m, then north 600 m, then (second leg) east 400 m.97private let b = Geodesy.destination(from: a, bearing: 90, distance: 1_000)98private let c = Geodesy.destination(from: b, bearing: 0, distance: 600)99private let d = Geodesy.destination(from: c, bearing: 90, distance: 400)100101private func maneuver(_ type: ManeuverType, _ modifier: ManeuverModifier? = nil, at: Coordinate, range: ClosedRange<Int>, distance: Double, duration: Double, name: String?, leg: Int = 0, waypoint: Int? = nil) -> Maneuver {102 Maneuver(type: type, modifier: modifier, roundaboutExit: nil, waypointIndex: waypoint, location: at, bearingBefore: 0, bearingAfter: 0, name: name, ref: nil,103 roadClass: .residential, distanceMeters: distance, durationSeconds: duration, geometryRange: range, legIndex: leg)104}105106/// A two-leg route a→b→c (stop) →d, at 10 m/s.107private func makeRoute(twoLegs: Bool = true) -> Route {108 let geometry = twoLegs ? [a, b, c, d] : [a, b, c]109 var maneuvers = [110 maneuver(.depart, at: a, range: 0...1, distance: 1_000, duration: 100, name: "Rue Est"),111 maneuver(.turn, .left, at: b, range: 1...2, distance: 600, duration: 60, name: "Avenue Nord"),112 ]113 var legs = [RouteLeg(fromWaypointIndex: 0, toWaypointIndex: 1, distanceMeters: 1_600, durationSeconds: 160, geometryRange: 0...2, maneuverRange: 0..<3)]114 if twoLegs {115 maneuvers.append(maneuver(.waypoint, at: c, range: 2...3, distance: 400, duration: 40, name: "Rue du Parc", leg: 1, waypoint: 1))116 maneuvers.append(maneuver(.arrive, at: d, range: 3...3, distance: 0, duration: 0, name: nil, leg: 1, waypoint: 2))117 legs.append(RouteLeg(fromWaypointIndex: 1, toWaypointIndex: 2, distanceMeters: 400, durationSeconds: 40, geometryRange: 2...3, maneuverRange: 2..<4))118 } else {119 maneuvers.append(maneuver(.arrive, at: c, range: 2...2, distance: 0, duration: 0, name: nil, waypoint: 1))120 }121 let total = twoLegs ? 2_000.0 : 1_600.0122 return Route(geometry: geometry, distanceMeters: total, durationSeconds: total / 10, cost: total / 10, legs: legs, maneuvers: maneuvers, segments: [],123 boundingBox: BoundingBox(enclosing: geometry)!, warnings: [], assumedSpeedDistanceMeters: 0, elevationProfile: nil, waypoints: [], mode: .car, profileName: "car")124}125126/// Position `along` metres along the route, `offset` metres to the right of it.127private func position(_ route: Route, along: Double, offset: Double = 0) -> (Coordinate, Double) {128 let p = Geodesy.point(along: route.geometry, at: along)!129 return (offset == 0 ? p.point : Geodesy.destination(from: p.point, bearing: p.bearing + 90, distance: offset), p.bearing)130}131132private func drive(_ session: inout NavigationSession, from: Double, to: Double, step: Double = 10, speed: Double = 10, offset: Double = 0, start: TimeInterval = 0) -> [NavigationEvent] {133 var events: [NavigationEvent] = []134 var along = from, t = start135 while along <= to {136 let (p, bearing) = position(session.route, along: along, offset: offset)137 events += session.update(NavigationFix(coordinate: p, accuracy: 5, speed: speed, course: bearing, time: t0.addingTimeInterval(t)))138 along += step; t += step / speed139 }140 return events141}142143private func announcements(_ events: [NavigationEvent]) -> [Announcement] {144 events.compactMap { if case .announce(let x) = $0 { x } else { nil } }145}146147@Suite struct ProgressTests {148 @Test func matchesThePositionAndComputesRemainingDistanceAndTime() throws {149 var session = NavigationSession(route: makeRoute())150 let (p, _) = position(session.route, along: 250, offset: 8)151 let events = session.update(NavigationFix(coordinate: p, accuracy: 5, speed: 10, course: 90, time: t0))152 guard case .progress(let pr) = try #require(events.first) else { Issue.record("no progress"); return }153 #expect(pr.isOnRoute && abs(pr.deviation - 8) < 0.5 && abs(pr.distanceTraveled - 250) < 1)154 #expect(abs(pr.distanceRemaining - 1_750) < 1 && abs(pr.durationRemaining - 175) < 0.5)155 #expect(pr.nextManeuverIndex == 1 && abs(pr.distanceToNextManeuver - 750) < 1 && abs(pr.matchedBearing - 90) < 0.5)156 #expect(pr.legIndex == 0 && abs(pr.legDistanceRemaining - 1_350) < 1 && abs(pr.legDurationRemaining - 135) < 0.5)157 #expect(abs(Geodesy.distance(pr.matchedCoordinate, position(session.route, along: 250).0)) < 0.5)158 #expect(abs(pr.eta(from: t0).timeIntervalSince(t0) - 175) < 0.5)159 }160161 @Test func jitterWhileStoppedDoesNotMoveProgressBackwards() {162 var session = NavigationSession(route: makeRoute())163 _ = drive(&session, from: 0, to: 500)164 let before = session.progress!.distanceTraveled165 for (i, back) in [8.0, 15, 4, 20, 0].enumerated() {166 let (p, _) = position(session.route, along: 500 - back, offset: 3)167 _ = session.update(NavigationFix(coordinate: p, accuracy: 10, speed: 0, course: nil, time: t0.addingTimeInterval(100 + Double(i))))168 #expect(session.progress!.isOnRoute && session.progress!.distanceTraveled >= before - 40)169 }170 }171172 @Test func invalidFixesAndDegenerateRoutesAreIgnored() {173 var session = NavigationSession(route: makeRoute())174 #expect(session.update(NavigationFix(coordinate: Coordinate(latitude: 99, longitude: 0), accuracy: 5, time: t0)).isEmpty)175 var route = makeRoute(); route.geometry = [a]176 var empty = NavigationSession(route: route)177 #expect(empty.update(NavigationFix(coordinate: a, accuracy: 5, time: t0)).isEmpty)178 }179}180181@Suite struct AnnouncementTests {182 @Test func saysHowToStartThenPreparesThenInstructs() {183 var session = NavigationSession(route: makeRoute(twoLegs: false), options: NavigationOptions(language: .english, units: .metric))184 let said = announcements(drive(&session, from: 0, to: 1_000))185 // Depart, prepare for the left turn, then the turn itself — once each, in order.186 #expect(said.count == 3)187 #expect(said[0].maneuverIndex == 0 && said[0].stage == .now)188 #expect(said[1].maneuverIndex == 1 && said[1].stage == .prepare && said[1].text.hasPrefix("In ") && said[1].text.lowercased().contains("turn left") && said[1].text.contains("Avenue Nord"))189 #expect(said[2].maneuverIndex == 1 && said[2].stage == .now && said[2].text.hasPrefix("Turn left"))190 }191192 @Test func frenchAndImperialFollowTheOptions() {193 var fr = NavigationSession(route: makeRoute(twoLegs: false), options: NavigationOptions(language: .french, units: .metric))194 let said = announcements(drive(&fr, from: 0, to: 1_000))195 #expect(said[1].text.hasPrefix("Dans ") && said[1].text.contains("mètres") && said[2].text.hasPrefix("Tournez à gauche"))196 var us = NavigationSession(route: makeRoute(twoLegs: false), options: NavigationOptions(language: .english, units: .imperial))197 let imperial = announcements(drive(&us, from: 0, to: 900))198 #expect(imperial[1].text.contains("feet") || imperial[1].text.contains("mile"))199 }200201 @Test func warnsEarlierAtHighSpeed() {202 // At 30 m/s the "prepare" call comes about 14 s ahead (420 m) instead of 140 m at 10 m/s.203 var fast = NavigationSession(route: makeRoute(twoLegs: false))204 let events = drive(&fast, from: 0, to: 700, step: 30, speed: 30)205 var prepareAt: Double?206 var lastProgress: NavigationProgress?207 for e in events {208 if case .progress(let p) = e { lastProgress = p }209 if case .announce(let x) = e, x.stage == .prepare, prepareAt == nil { prepareAt = lastProgress?.distanceToNextManeuver }210 }211 #expect(prepareAt != nil && prepareAt! > 380 && prepareAt! <= 450)212 }213214 @Test func longStretchesGetAFollowUpAndAnAdvanceWarning() {215 // 10 km straight before a turn, driven at 28 m/s.216 let far = Geodesy.destination(from: a, bearing: 90, distance: 10_000), end = Geodesy.destination(from: far, bearing: 0, distance: 500)217 var route = makeRoute(twoLegs: false)218 route.geometry = [a, far, end]219 route.maneuvers = [maneuver(.depart, at: a, range: 0...1, distance: 10_000, duration: 357, name: "Autoroute 40"),220 maneuver(.offRamp, .slightRight, at: far, range: 1...2, distance: 500, duration: 30, name: nil),221 maneuver(.arrive, at: end, range: 2...2, distance: 0, duration: 0, name: nil, waypoint: 1)]222 route.legs = [RouteLeg(fromWaypointIndex: 0, toWaypointIndex: 1, distanceMeters: 10_500, durationSeconds: 387, geometryRange: 0...2, maneuverRange: 0..<3)]223 var session = NavigationSession(route: route)224 let said = announcements(drive(&session, from: 0, to: 10_000, step: 28, speed: 28))225 #expect(said.map(\.stage) == [.now, .followUp, .advance, .prepare, .now])226 #expect(said[1].text.hasPrefix("Continue for") && said[2].text.hasPrefix("In 2"))227 }228}229230@Suite struct OffRouteTests {231 @Test func reroutesOnlyAfterSustainedDeviation() {232 var session = NavigationSession(route: makeRoute())233 _ = drive(&session, from: 0, to: 300)234 // One wild fix does nothing.235 let (wild, _) = position(session.route, along: 310, offset: 120)236 var events = session.update(NavigationFix(coordinate: wild, accuracy: 5, speed: 10, course: 90, time: t0.addingTimeInterval(31)))237 #expect(!events.contains { if case .rerouteNeeded = $0 { true } else { false } })238 events = drive(&session, from: 320, to: 340, start: 32)239 #expect(session.progress!.isOnRoute && !session.isAwaitingReroute)240 // Leaving for good: 80 m to the side for several seconds.241 events = drive(&session, from: 350, to: 450, offset: 80, start: 40)242 let reroutes = events.compactMap { if case .rerouteNeeded(let from, let course) = $0 { (from, course) } else { nil } }243 #expect(reroutes.count == 1 && reroutes[0].1 != nil && session.isAwaitingReroute)244 #expect(events.contains { if case .progress(let p) = $0 { !p.isOnRoute && p.deviation > 70 } else { false } })245 // While waiting for the new route nothing else is requested, and nothing is announced.246 let more = drive(&session, from: 460, to: 520, offset: 80, start: 55)247 #expect(!more.contains { if case .rerouteNeeded = $0 { true } else { false } } && announcements(more).isEmpty)248 }249250 @Test func aFailedRerouteIsRetriedAfterTheInterval() {251 var session = NavigationSession(route: makeRoute())252 _ = drive(&session, from: 0, to: 100)253 _ = drive(&session, from: 110, to: 200, offset: 90, start: 11)254 #expect(session.isAwaitingReroute)255 session.rerouteFailed()256 let soon = drive(&session, from: 210, to: 220, offset: 90, start: 21)257 #expect(!soon.contains { if case .rerouteNeeded = $0 { true } else { false } })258 let later = drive(&session, from: 230, to: 300, offset: 90, start: 40)259 #expect(later.filter { if case .rerouteNeeded = $0 { true } else { false } }.count == 1)260 }261262 @Test func impreciseFixesNeverTriggerAReroute() {263 var session = NavigationSession(route: makeRoute())264 _ = drive(&session, from: 0, to: 100)265 var events: [NavigationEvent] = []266 for i in 0..<20 {267 let (p, _) = position(session.route, along: 110 + Double(i) * 10, offset: 150)268 events += session.update(NavigationFix(coordinate: p, accuracy: 120, speed: 10, course: 90, time: t0.addingTimeInterval(11 + Double(i))))269 }270 #expect(!events.contains { if case .rerouteNeeded = $0 { true } else { false } } && !session.isAwaitingReroute)271 }272273 @Test func drivingTheWrongWayOnTheRouteLineIsOffRoute() {274 var session = NavigationSession(route: makeRoute())275 _ = drive(&session, from: 0, to: 400)276 var events: [NavigationEvent] = []277 for i in 0..<8 {278 let (p, _) = position(session.route, along: 390 - Double(i) * 10)279 events += session.update(NavigationFix(coordinate: p, accuracy: 5, speed: 10, course: 270, time: t0.addingTimeInterval(41 + Double(i))))280 }281 #expect(events.contains { if case .rerouteNeeded = $0 { true } else { false } })282 }283284 @Test func aNewRouteRestartsGuidanceAndComingBackClearsTheState() {285 var session = NavigationSession(route: makeRoute())286 _ = drive(&session, from: 0, to: 100)287 _ = drive(&session, from: 110, to: 200, offset: 90, start: 11)288 session.setRoute(makeRoute(twoLegs: false))289 #expect(!session.isAwaitingReroute && session.progress == nil)290 let said = announcements(drive(&session, from: 0, to: 50, start: 30))291 #expect(said.first?.maneuverIndex == 0)292 // Drifting off then returning before the hysteresis expires requests nothing.293 var s2 = NavigationSession(route: makeRoute())294 _ = drive(&s2, from: 0, to: 100)295 let (off, _) = position(s2.route, along: 110, offset: 70)296 _ = s2.update(NavigationFix(coordinate: off, accuracy: 5, speed: 10, course: 90, time: t0.addingTimeInterval(11)))297 let back = drive(&s2, from: 120, to: 200, start: 12)298 #expect(!back.contains { if case .rerouteNeeded = $0 { true } else { false } } && s2.progress!.isOnRoute)299 }300}301302@Suite struct ArrivalTests {303 @Test func reachesTheStopThenTheDestinationExactlyOnce() {304 var session = NavigationSession(route: makeRoute())305 let events = drive(&session, from: 0, to: 2_000)306 let stops = events.compactMap { if case .waypointReached(let i) = $0 { i } else { nil } }307 #expect(stops == [1])308 #expect(events.filter { $0 == .arrived }.count == 1 && session.hasArrived)309 let last = announcements(events).last310 #expect(last?.stage == .now && last?.maneuverIndex == 3)311 // After arrival the session is finished.312 #expect(session.update(NavigationFix(coordinate: d, accuracy: 5, time: t0.addingTimeInterval(999))).isEmpty)313 // Order: the stop is reached before the arrival.314 let iStop = events.firstIndex { if case .waypointReached = $0 { true } else { false } }!, iEnd = events.firstIndex(of: .arrived)!315 #expect(iStop < iEnd)316 }317318 @Test func aRouteThatPassesNearItsEndEarlyDoesNotArriveEarly() {319 // Out-and-back: a → b → back to a point 20 m from the start.320 let end = Geodesy.destination(from: a, bearing: 0, distance: 20)321 var route = makeRoute(twoLegs: false)322 route.geometry = [a, b, Geodesy.destination(from: b, bearing: 0, distance: 20), end]323 route.maneuvers = [maneuver(.depart, at: a, range: 0...1, distance: 1_000, duration: 100, name: "Aller"),324 maneuver(.uTurn, .uTurn, at: b, range: 1...3, distance: 1_020, duration: 110, name: "Retour"),325 maneuver(.arrive, at: end, range: 3...3, distance: 0, duration: 0, name: nil, waypoint: 1)]326 route.legs = [RouteLeg(fromWaypointIndex: 0, toWaypointIndex: 1, distanceMeters: 2_020, durationSeconds: 210, geometryRange: 0...3, maneuverRange: 0..<3)]327 var session = NavigationSession(route: route)328 let outbound = drive(&session, from: 0, to: 600)329 #expect(!outbound.contains(.arrived) && abs(session.progress!.distanceTraveled - 600) < 2)330 let rest = drive(&session, from: 610, to: 2_020, start: 61)331 #expect(rest.contains(.arrived))332 }333}334335@MainActor @Suite struct VoiceTests {336 @Test func recordingGuideRespectsTheEnabledFlag() {337 let guide = RecordingVoiceGuide()338 guide.speak("Turn left", language: "en", urgent: true)339 guide.isEnabled = false340 guide.speak("Tournez à droite", language: "fr", urgent: false)341 #expect(guide.spoken.count == 1 && guide.spoken[0].text == "Turn left" && guide.spoken[0].urgent)342 }343}344