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/TracksModelTests.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 ORIXLocation92import ORIXMapRenderer93import ORIXMapStyle94import ORIXTracks95import Testing96@testable import ORIXMaps9798struct TracksModelTests {99 /// A track model fed by a simulated position: about 400 m north along a meridian, at 10 m/s.100 final class Fixture {101 let dir: ScratchDirectory102 let controller = MapController()103 let spy = SpyBackend()104 let provider: SimulatedLocationProvider105 let location: LocationService106 let tracks: TracksModel107 let start = Date().addingTimeInterval(5)108109 init(directory: ScratchDirectory = ScratchDirectory()) {110 dir = directory111 let path = [downtownMontreal, Coordinate(latitude: downtownMontreal.latitude + 0.0036, longitude: downtownMontreal.longitude)]112 // The provider's own clock is not used: the tests step it with `seek`.113 provider = SimulatedLocationProvider(path: path, speed: 10, rate: 1, interval: 3_600)114 location = LocationService(provider: provider)115 controller.attach(spy)116 controller.engineDidLoadStyle()117 tracks = TracksModel(directory: dir.url, location: location, map: controller)118 }119120 /// Plays the path from `from` to `to` path-seconds, one fix every two seconds.121 func play(from: Double, to: Double) {122 var t = from123 while t <= to { provider.seek(to: t, now: start.addingTimeInterval(t)); t += 2 }124 }125 }126127 @Test func recordingASimulatedWalkProducesASavedTrack() async throws {128 let f = Fixture()129 #expect(f.tracks.isAvailable && !f.tracks.isRecording && f.tracks.summaries.isEmpty)130 f.tracks.startRecording(name: "Essai")131 #expect(f.tracks.isRecording)132 #expect(f.location.usage == .recording)133 f.play(from: 0, to: 40)134 let live = try #require(f.tracks.liveStatistics)135 #expect(live.distance > 380 && live.distance < 420, "about 400 m were travelled, got \(live.distance)")136 #expect(f.spy.featureCount(OverlayID.track) == 1, "the live line is drawn")137138 let summary = try #require(await f.tracks.stopRecording())139 #expect(summary.name == "Essai")140 #expect(summary.statistics.distance > 380 && summary.statistics.distance < 420)141 #expect(try #require(summary.statistics.duration) >= 38)142 #expect(!f.tracks.isRecording && f.tracks.recorder == nil && f.tracks.liveStatistics == nil)143 #expect(f.tracks.summaries.map(\.id) == [summary.id])144 #expect(f.spy.featureCount(OverlayID.track) == 0, "the live line is cleared")145 #expect(f.location.usage == .browsing, "the position falls back to browsing after a recording")146147 let saved = try #require(await f.tracks.track(summary.id))148 #expect(saved.segments.count == 1 && saved.segments[0].count >= 15)149 }150151 @Test func pausingStopsRecordingAndResumingStartsANewSegment() async throws {152 let f = Fixture()153 f.tracks.startRecording(name: "Pause")154 f.play(from: 0, to: 10)155 f.tracks.pauseRecording()156 #expect(f.tracks.isPaused && !f.tracks.isRecording)157 let paused = try #require(f.tracks.recorder?.track.sampleCount)158 f.play(from: 12, to: 20)159 #expect(f.tracks.recorder?.track.sampleCount == paused, "nothing is recorded while paused")160 f.tracks.resumeRecording()161 f.play(from: 22, to: 40)162 let summary = try #require(await f.tracks.stopRecording())163 let saved = try #require(await f.tracks.track(summary.id))164 #expect(saved.segments.count == 2)165 #expect(summary.statistics.distance < 320, "the distance covered during the pause is not counted")166 }167168 @Test func aRecordingWithFewerThanTwoPointsIsNotSaved() async {169 let f = Fixture()170 f.tracks.startRecording(name: "Vide")171 f.provider.seek(to: 0, now: f.start)172 #expect(await f.tracks.stopRecording() == nil)173 #expect(f.tracks.summaries.isEmpty)174 }175176 @Test func impreciseFixesAreNotRecorded() async {177 let dir = ScratchDirectory()178 let provider = SimulatedLocationProvider(samples: [.init(coordinate: downtownMontreal, time: 0), .init(coordinate: olympicStadium, time: 600)], interval: 3_600, accuracy: 500)179 let location = LocationService(provider: provider)180 let tracks = TracksModel(directory: dir.url, location: location, map: MapController())181 tracks.startRecording(name: "Flou")182 let start = Date().addingTimeInterval(5)183 for t in stride(from: 0.0, through: 60, by: 5) { provider.seek(to: t, now: start.addingTimeInterval(t)) }184 #expect(tracks.liveStatistics == nil)185 #expect(await tracks.stopRecording() == nil)186 }187188 @Test func aSecondStartDoesNotReplaceTheRunningRecording() {189 let f = Fixture()190 f.tracks.startRecording(name: "A")191 f.tracks.startRecording(name: "B")192 #expect(f.tracks.recorder?.track.name == "A")193 }194195 @Test func anInterruptedRecordingIsOfferedAfterRelaunchAndCanBeContinued() async throws {196 let dir = ScratchDirectory()197 do {198 let f = Fixture(directory: dir)199 f.tracks.startRecording(name: "Interrompu")200 f.play(from: 0, to: 30) // more than ten points: a snapshot was written201 _ = await eventually { FileManager.default.fileExists(atPath: dir.url.path) && ((try? FileManager.default.contentsOfDirectory(atPath: dir.url.path))?.isEmpty == false) }202 // The application stops here without `stopRecording`.203 }204 let g = Fixture(directory: dir)205 await g.tracks.reload()206 let interrupted = try #require(g.tracks.interrupted)207 #expect(interrupted.name == "Interrompu" && interrupted.sampleCount >= 10)208 #expect(g.tracks.summaries.isEmpty)209 g.tracks.resumeInterrupted()210 #expect(g.tracks.isRecording && g.tracks.interrupted == nil)211 g.play(from: 32, to: 40)212 let summary = try #require(await g.tracks.stopRecording())213 #expect(summary.name == "Interrompu")214 #expect(g.tracks.summaries.count == 1)215 await g.tracks.reload()216 #expect(g.tracks.interrupted == nil)217 }218219 @Test func anInterruptedRecordingCanBeSavedAsItIsOrDiscarded() async throws {220 for save in [true, false] {221 let dir = ScratchDirectory()222 do {223 let f = Fixture(directory: dir)224 f.tracks.startRecording(name: "Interrompu")225 f.play(from: 0, to: 30)226 f.tracks.pauseRecording() // pausing writes the snapshot227 _ = await eventually { (try? FileManager.default.contentsOfDirectory(atPath: dir.url.path))?.isEmpty == false }228 }229 let g = Fixture(directory: dir)230 await g.tracks.reload()231 try #require(g.tracks.interrupted != nil)232 if save { await g.tracks.saveInterrupted() } else { g.tracks.discardInterrupted() }233 #expect(g.tracks.interrupted == nil)234 _ = await eventually { g.tracks.summaries.count == (save ? 1 : 0) }235 await g.tracks.reload()236 #expect(g.tracks.summaries.count == (save ? 1 : 0))237 #expect(g.tracks.interrupted == nil)238 }239 }240241 @Test(arguments: ExchangeFormat.allCases)242 func exportThenImport(format: ExchangeFormat) async throws {243 let f = Fixture()244 f.tracks.startRecording(name: "Sortie: matin/soir")245 f.play(from: 0, to: 40)246 let summary = try #require(await f.tracks.stopRecording())247 let file = try #require(await f.tracks.exportFile(summary.id, format: format))248 #expect(file.lastPathComponent == "Sortie matinsoir.\(format.fileExtension)")249 #expect(await f.tracks.importFile(file) == 1)250 #expect(f.tracks.summaries.count == 2)251 let imported = try #require(f.tracks.summaries.first { $0.id != summary.id })252 #expect(abs(imported.statistics.distance - summary.statistics.distance) < 5)253 }254255 @Test func importOfAnUnusableFileGivesNil() async {256 let f = Fixture()257 let files = ScratchDirectory()258 #expect(await f.tracks.importFile(files.file("broken.gpx", "<gpx><trk>")) == nil)259 #expect(await f.tracks.importFile(URL(fileURLWithPath: "/nonexistent/a.gpx")) == nil)260 let placesOnly = ExchangeCodec.encode(ExchangeDocument(waypoints: [.init(coordinate: downtownMontreal, name: "A")]), format: .gpx)261 #expect(await f.tracks.importFile(files.file("places.gpx", placesOnly)) == 0)262 #expect(f.tracks.summaries.isEmpty)263 }264265 @Test func showingRenamingAndDeletingASavedTrack() async throws {266 let f = Fixture()267 f.tracks.startRecording(name: "Avant")268 f.play(from: 0, to: 40)269 let summary = try #require(await f.tracks.stopRecording())270 let track = try #require(await f.tracks.track(summary.id))271 f.tracks.show(track)272 #expect(f.tracks.displayed?.id == summary.id && f.spy.featureCount(OverlayID.track) == 1 && f.spy.fits.count == 1)273 await f.tracks.rename(summary.id, name: "Après", note: "Belle sortie")274 #expect(f.tracks.summaries.first?.name == "Après")275 #expect(await f.tracks.track(summary.id)?.note == "Belle sortie")276 await f.tracks.delete(summary.id)277 #expect(f.tracks.summaries.isEmpty && f.tracks.displayed == nil && f.spy.featureCount(OverlayID.track) == 0)278 }279}280