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/DirectionsModelTests.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 ORIXLocation91import ORIXMapRenderer92import ORIXMapStyle93import ORIXRouting94import Testing95@testable import ORIXMaps9697/// The routing graph of Greater Montréal built by the development pipeline (git-ignored). Tests that need it are98/// skipped when it is absent.99nonisolated let montrealGraphURL = repositoryRoot.appending(path: "data/build/routing/montreal.orixgraph")100nonisolated let hasMontrealGraph = FileManager.default.fileExists(atPath: montrealGraphURL.path)101102struct DirectionsModelTests {103 final class Fixture {104 let defaults = ScratchDefaults()105 let controller = MapController()106 let spy = SpyBackend()107 let settings: AppSettings108 let location: LocationService109 let directions: DirectionsModel110 /// What a simulated drive hands the position back to when it ends.111 let device: FakeDeviceProvider112113 /// `position`: where the simulated device is; nil = no position is ever delivered.114 init(position: Coordinate? = nil, devicePermission: LocationAuthorization = .notDetermined) {115 let device = FakeDeviceProvider(authorization: devicePermission)116 self.device = device117 settings = AppSettings(defaults: defaults.defaults)118 settings.units = .metric119 settings.voiceGuidance = false120 location = LocationService(provider: SimulatedLocationProvider(samples: position.map { [.init(coordinate: $0, time: 0)] } ?? [], interval: 0.2))121 controller.attach(spy)122 controller.engineDidLoadStyle()123 directions = DirectionsModel(map: controller, location: location, settings: settings, deviceProvider: { device })124 }125126 func loadMontreal() async -> Bool {127 directions.setRegions([region("ca-qc-montreal", montrealBox, routing: montrealGraphURL)])128 return await eventually(timeout: .seconds(60)) { directions.hasRouting }129 }130131 func plan(_ from: Coordinate, _ to: Coordinate) async -> Bool {132 directions.points = [RoutePoint(title: "A", coordinate: from), RoutePoint(title: "B", coordinate: to)]133 directions.compute()134 return await eventually(timeout: .seconds(60)) { !directions.isComputing && (directions.route != nil || directions.failure != nil) }135 }136 }137138 @Test func withoutARoutingGraphTheFailureSaysSo() {139 let f = Fixture()140 f.directions.points = [RoutePoint(title: "A", coordinate: downtownMontreal), RoutePoint(title: "B", coordinate: olympicStadium)]141 f.directions.compute()142 #expect(f.directions.failure == .noRoutingData)143 #expect(f.directions.route == nil && !f.directions.isComputing)144 }145146 @Test func aSinglePointPlansNothing() {147 let f = Fixture()148 f.directions.compute()149 #expect(f.directions.failure == nil && f.directions.routes.isEmpty)150 }151152 @Test func aDamagedGraphIsNotOffered() async {153 let files = ScratchDirectory()154 let f = Fixture()155 f.directions.setRegions([region("broken", montrealBox, routing: files.file("broken.orixgraph", Data(repeating: 0xAB, count: 8192)))])156 try? await Task.sleep(for: .milliseconds(500))157 #expect(!f.directions.hasRouting && f.directions.graphInfo.isEmpty)158 }159160 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))161 func carRouteDowntownToTheOlympicStadium() async throws {162 let f = Fixture()163 try #require(await f.loadMontreal())164 #expect(f.directions.graphInfo.count == 1)165 try #require(await f.plan(downtownMontreal, olympicStadium))166 #expect(f.directions.failure == nil)167 let route = try #require(f.directions.route)168 #expect(route.distanceMeters > 7_000 && route.distanceMeters < 14_000, "got \(route.distanceMeters) m")169 #expect(route.durationSeconds > 8 * 60 && route.durationSeconds < 35 * 60, "got \(route.durationSeconds) s")170 #expect(route.maneuvers.count >= 3)171 #expect(route.maneuvers.first?.type == .depart && route.maneuvers.last?.type == .arrive)172 #expect(Geodesy.fastDistance(try #require(route.geometry.first), downtownMontreal) < 150)173 #expect(Geodesy.fastDistance(try #require(route.geometry.last), olympicStadium) < 250)174 #expect(f.directions.routes.count >= 2, "an alternative is offered between two points")175 #expect(f.spy.featureCount(OverlayID.route) == 1)176 #expect(f.spy.featureCount(OverlayID.routeAlternatives) == f.directions.routes.count - 1)177 #expect(f.spy.fits.count == 1, "the map frames the route")178179 // Choosing the alternative redraws it as the main route.180 f.directions.selectedRoute = 1181 #expect(f.directions.route == f.directions.routes[1])182 #expect(f.spy.featureCount(OverlayID.routeAlternatives) == f.directions.routes.count - 1)183184 // Instructions exist in both interface languages of the formatter.185 let text = f.directions.formatter.instruction(for: route.maneuvers[0])186 #expect(!text.isEmpty)187188 f.directions.clear()189 #expect(f.directions.route == nil && f.directions.points.count == 1 && f.directions.points[0].isMyPosition)190 #expect(f.spy.featureCount(OverlayID.route) == 0 && f.spy.featureCount(OverlayID.routeAlternatives) == 0)191 }192193 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))194 func walkingAndCyclingTakeLongerThanDriving() async throws {195 let f = Fixture()196 try #require(await f.loadMontreal())197 var durations: [TravelMode: Double] = [:]198 for mode in TravelMode.allCases {199 f.directions.mode = mode200 try #require(await f.plan(downtownMontreal, olympicStadium))201 let route = try #require(f.directions.route, "no route in mode \(mode)")202 durations[mode] = route.durationSeconds203 #expect(route.distanceMeters > 5_000 && route.distanceMeters < 14_000)204 }205 let car = try #require(durations[.car]), bike = try #require(durations[.bicycle]), walk = try #require(durations[.pedestrian])206 #expect(car < bike && bike < walk, "car \(car) s, bicycle \(bike) s, walk \(walk) s")207 #expect(walk > 60 * 60, "about 7 km on foot takes more than an hour")208 }209210 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))211 func aPointOutsideTheRegionIsNotCovered() async throws {212 let f = Fixture()213 try #require(await f.loadMontreal())214 f.directions.points = [RoutePoint(title: "A", coordinate: downtownMontreal), RoutePoint(title: "B", coordinate: quebecCity)]215 f.directions.compute()216 #expect(f.directions.failure == .notCovered)217 #expect(f.directions.route == nil)218 }219220 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))221 func fromMyPositionWithoutAFixAsksForThePosition() async throws {222 let f = Fixture(position: nil)223 try #require(await f.loadMontreal())224 f.directions.plan(to: PlaceSelection(title: "Stade", subtitle: nil, coordinate: olympicStadium, origin: .search))225 #expect(f.directions.points.count == 2 && f.directions.points[0].isMyPosition)226 #expect(f.directions.failure == .noPosition)227 #expect(f.location.usage == .browsing, "planning from my position starts position updates")228 }229230 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))231 func fromMyPositionWithAFixPlansFromThere() async throws {232 let f = Fixture(position: downtownMontreal)233 try #require(await f.loadMontreal())234 f.location.start(.browsing)235 try #require(await eventually { f.location.lastFix != nil })236 f.directions.plan(to: PlaceSelection(title: "Stade", subtitle: nil, coordinate: olympicStadium, origin: .search))237 try #require(await eventually(timeout: .seconds(60)) { f.directions.route != nil || f.directions.failure != nil })238 #expect(f.directions.failure == nil)239 let route = try #require(f.directions.route)240 #expect(Geodesy.fastDistance(try #require(route.geometry.first), downtownMontreal) < 150)241 }242243 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))244 func theRouteIsComputedWhenThePositionArrives() async throws {245 let f = Fixture(position: downtownMontreal)246 try #require(await f.loadMontreal())247 // Position updates are not running yet: planning starts them and waits.248 f.directions.plan(to: PlaceSelection(title: "Stade", subtitle: nil, coordinate: olympicStadium, origin: .search))249 #expect(f.directions.failure == .noPosition)250 #expect(await eventually(timeout: .seconds(60)) { f.directions.route != nil }, "the first fix computes the route without another request")251 #expect(f.directions.failure == nil)252 }253254 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))255 func aDeviceThatDoesNotMoveCanStillStartARoute() async throws {256 // Core Location delivers nothing while the device stays within the distance filter: the last fix gets old.257 for (age, usable) in [(60.0, true), (540.0, true), (900.0, false)] {258 let defaults = ScratchDefaults()259 let provider = FakeDeviceProvider(authorization: .authorized(precise: true))260 let location = LocationService(provider: provider)261 let settings = AppSettings(defaults: defaults.defaults)262 let directions = DirectionsModel(map: MapController(), location: location, settings: settings, deviceProvider: { provider })263 directions.setRegions([region("ca-qc-montreal", montrealBox, routing: montrealGraphURL)])264 try #require(await eventually(timeout: .seconds(60)) { directions.hasRouting })265 location.start(.browsing)266 provider.onFix?(LocationFix(coordinate: downtownMontreal, horizontalAccuracy: 8, timestamp: Date().addingTimeInterval(-age)))267 #expect(!location.isFixFresh)268 directions.plan(to: PlaceSelection(title: "Stade", subtitle: nil, coordinate: olympicStadium, origin: .search))269 if usable {270 #expect(directions.failure == nil, "a fix \(Int(age)) s old is still the position of a device that did not move")271 #expect(await eventually(timeout: .seconds(60)) { directions.route != nil })272 } else {273 #expect(directions.failure == .noPosition, "a fix \(Int(age)) s old is not trusted")274 }275 }276 }277278 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))279 func stopsCanBeAddedReversedAndRemoved() async throws {280 let f = Fixture()281 try #require(await f.loadMontreal())282 try #require(await f.plan(downtownMontreal, olympicStadium))283 let direct = try #require(f.directions.route).distanceMeters284 let detour = Coordinate(latitude: 45.5088, longitude: -73.5540) // Old Port285 f.directions.addStop(PlaceSelection(title: "Vieux-Port", subtitle: nil, coordinate: detour, origin: .search))286 #expect(f.directions.points.map(\.title) == ["A", "Vieux-Port", "B"])287 try #require(await eventually(timeout: .seconds(60)) { !f.directions.isComputing && f.directions.route != nil })288 let withStop = try #require(f.directions.route)289 #expect(withStop.distanceMeters > direct * 0.9)290 #expect(f.directions.routes.count == 1, "no alternatives with intermediate stops")291 f.directions.reverse()292 #expect(f.directions.points.map(\.title) == ["B", "Vieux-Port", "A"])293 f.directions.removePoint(f.directions.points[1].id)294 #expect(f.directions.points.map(\.title) == ["B", "A"])295 try #require(await eventually(timeout: .seconds(60)) { !f.directions.isComputing && f.directions.route != nil })296 }297298 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))299 func simulatedGuidanceRunsToArrival() async throws {300 let f = Fixture()301 try #require(await f.loadMontreal())302 // A short walk: a few blocks downtown.303 f.directions.mode = .pedestrian304 try #require(await f.plan(downtownMontreal, Coordinate(latitude: 45.5040, longitude: -73.5700)))305 try #require(f.directions.route != nil)306 var arrivals = 0307 f.directions.onArrival = { arrivals += 1 }308 f.directions.startNavigation(simulated: true)309 #expect(f.directions.isNavigating && f.directions.isSimulating)310 #expect(f.location.usage == .navigation)311 try #require(await eventually(timeout: .seconds(20)) { f.directions.progress != nil })312 #expect(await eventually(timeout: .seconds(120)) { f.directions.arrived }, "the simulated walk reaches the destination")313 #expect(arrivals == 1)314 #expect(f.directions.lastAnnouncement != nil)315 f.directions.stopNavigation()316 #expect(!f.directions.isNavigating && !f.directions.isSimulating && f.directions.progress == nil)317 #expect(f.spy.featureCount(OverlayID.routeTraveled) == 0)318 // The preview never asked for the position permission, during or after.319 #expect(f.device.authorizationRequests == 0 && f.device.started.isEmpty)320 #expect(f.location.usage == nil && f.location.authorization == .notDetermined)321 }322323 @Test(.enabled(if: hasMontrealGraph, "data/build/routing/montreal.orixgraph is not built"))324 func endingASimulatedDriveEarlyGoesBackToTheDevicePosition() async throws {325 let f = Fixture(devicePermission: .authorized(precise: true))326 try #require(await f.loadMontreal())327 try #require(await f.plan(downtownMontreal, olympicStadium))328 f.directions.startNavigation(simulated: true)329 try #require(await eventually(timeout: .seconds(20)) { f.directions.progress != nil })330 #expect(!f.directions.arrived)331 f.directions.stopNavigation()332 #expect(!f.directions.isNavigating && f.directions.progress == nil)333 #expect(f.device.authorizationRequests == 0)334 #expect(f.device.started == [.browsing], "an authorized device goes back to showing the position, not to guidance")335 #expect(f.location.usage == .browsing)336 #expect(f.directions.route != nil, "the planned route is still there")337 }338}339