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/ORIXRouting/Tests/ORIXRoutingTests/FormatTests.swift10// Module : ORIXRoutingTests11// 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 ORIXRouting9293@Suite struct FormatTests {94 static func sample() -> TestGraph {95 var g = TestGraph()96 g.node("a", 0, 0); g.node("b", 200, 0, flags: [.trafficSignal]); g.node("c", 200, 200); g.node("d", 0, 200, flags: [.blocksCar])97 g.node("island1", 5000, 5000); g.node("island2", 5100, 5000)98 g.edge("a", "b", .road("Rue Sherbrooke Ouest", .primary, speed: 50, ref: "138", wayID: 111), shape: [(50, 10), (120, -15)])99 g.edge("b", "c", .oneWay("Avenue du Parc", .secondary))100 g.edge("c", "d", .road("Chemin de la Côte-Sainte-Catherine", .tertiary, flags: [.toll, .bridge], surface: .unpaved, wayID: 222))101 g.edge("d", "a", .road(nil, .footway, access: RoutingGraphWriter.EdgeAttributes.footOnly, surface: .unknown, wayID: 333))102 g.edge("island1", "island2", .road("Île", .ferry, speed: 12.5))103 g.restrict(from: "a-b", via: "b", to: "b-c", .prohibitive, modes: [.car])104 return g105 }106107 @Test func roundTrip() throws {108 let g = Self.sample()109 let (data, summary) = try g.writer.build()110 #expect(summary.fileBytes == data.count)111 #expect(summary.sectionBytes["EDGE"] == 5 * 28)112 let graph = try RoutingGraph(data: data)113 #expect(graph.nodeCount == 6)114 #expect(graph.edgeCount == 5)115 #expect(graph.restrictionCount == 1)116 #expect(graph.metadata.regionID == "test")117 #expect(graph.metadata.formatMajor == 1)118 #expect(graph.metadata.attribution.contains("OpenStreetMap"))119 #expect(graph.metadata.buildDate == Date(timeIntervalSince1970: 1_800_000_000))120 #expect(graph.metadata.osmTimestamp == nil)121 #expect(graph.metadata.maxTaggedSpeedKmh == 50)122 #expect(graph.metadata.maxFerrySpeedKmh == 12.5)123 #expect(graph.metadata.ferryEdgeCount == 1)124125 let ab = try #require(graph.edge(at: g.edges["a-b"]!))126 #expect(ab.name == "Rue Sherbrooke Ouest")127 #expect(ab.ref == "138")128 #expect(ab.wayID == 111)129 #expect(ab.roadClass == .primary)130 #expect(ab.taggedSpeedKmh == 50)131 #expect(ab.surface == .paved)132 #expect(ab.access == .all)133 let geometry = graph.geometry(ofEdge: ab.index)134 #expect(geometry.count == 4)135 #expect(Geodesy.distance(geometry[1], p(50, 10)) < 0.02)136 #expect(Geodesy.distance(geometry[2], p(120, -15)) < 0.02)137 #expect(abs(ab.lengthMeters - Geodesy.length(of: geometry)) <= 0.1)138 #expect(ab.lengthMeters >= Geodesy.distance(geometry[0], geometry[3]))139 #expect(abs(Geodesy.bearingDelta(ab.bearingAtA, Geodesy.bearing(from: geometry[0], to: geometry[1]))) < 1.5)140 #expect(abs(Geodesy.bearingDelta(ab.bearingAtB, Geodesy.bearing(from: geometry[2], to: geometry[3]))) < 1.5)141142 let bc = try #require(graph.edge(at: g.edges["b-c"]!))143 #expect(bc.access == [.carForward, .bicycleForward, .pedestrianForward, .pedestrianBackward])144 #expect(bc.taggedSpeedKmh == nil)145 let cd = try #require(graph.edge(at: g.edges["c-d"]!))146 #expect(cd.flags.contains(.toll) && cd.flags.contains(.bridge) && cd.surface == .unpaved)147 let da = try #require(graph.edge(at: g.edges["d-a"]!))148 #expect(da.name == nil && da.surface == .unknown && da.roadClass == .footway)149 let ferry = try #require(graph.edge(at: g.edges["island1-island2"]!))150 #expect(ferry.flags.contains(.ferry) && ferry.taggedSpeedKmh == 12.5)151152 #expect(graph.flags(ofNode: g.nodes["b"]!) == [.trafficSignal, .hasRestriction])153 #expect(graph.flags(ofNode: g.nodes["d"]!) == [.blocksCar])154 #expect(graph.coordinate(ofNode: 99) == nil)155 #expect(graph.edge(at: 99) == nil)156 #expect(graph.geometry(ofEdge: 99).isEmpty)157 #expect(Set(graph.directedEdges(leaving: g.nodes["a"]!)) == [g.edges["a-b"]! << 1, g.edges["d-a"]! << 1 | 1])158159 // The main network and the island are different components for pedestrians.160 #expect(graph.componentRank(ofNode: g.nodes["a"]!, mode: .pedestrian) == 1)161 #expect(graph.componentRank(ofNode: g.nodes["island1"]!, mode: .pedestrian) == 2)162 #expect(graph.componentNodeCount(rank: 1, mode: .pedestrian) == 4)163 // Node d is a barrier for cars: it belongs to no car component.164 #expect(graph.componentRank(ofNode: g.nodes["d"]!, mode: .car) == nil)165166 // The forbidden turn is stored for cars only.167 #expect(!graph.turnAllowed(fromEdge: g.edges["a-b"]!, via: g.nodes["b"]!, toEdge: g.edges["b-c"]!, modeBit: 1))168 #expect(graph.turnAllowed(fromEdge: g.edges["a-b"]!, via: g.nodes["b"]!, toEdge: g.edges["b-c"]!, modeBit: 2))169 }170171 @Test func spatialReorderingKeepsTheGraph() throws {172 var plain = Self.sample()173 var reordered = Self.sample()174 reordered.writer.options.reorderSpatially = true175 plain.writer.options.reorderSpatially = false176 let a = try RoutingGraph(data: plain.writer.build().data), b = try RoutingGraph(data: reordered.writer.build().data)177 func signature(_ g: RoutingGraph) -> [String] {178 (0..<UInt32(g.edgeCount)).map { g.edge(at: $0)! }.map { e in179 let ca = g.coordinate(ofNode: e.nodeA)!, cb = g.coordinate(ofNode: e.nodeB)!180 return "\(ca.e7) \(cb.e7) \(e.name ?? "-") \(e.wayID) \(e.access.rawValue) \(e.flags.rawValue) \(e.lengthMeters)"181 }.sorted()182 }183 #expect(signature(a) == signature(b))184 let r = try Router(graph: b).compute(request([p(10, 0), p(200, 190)], .pedestrian))185 let s = try Router(graph: a).compute(request([p(10, 0), p(200, 190)], .pedestrian))186 #expect(r.route.cost == s.route.cost)187 #expect(b.restrictionCount == 1)188 }189190 @Test func rejectsWrongMagicAndVersions() throws {191 let data = Self.sample().data()192 var bad = data193 bad[0] = 0x58194 #expect(throws: RoutingGraphError.badMagic) { try RoutingGraph(data: bad) }195 var future = data196 future[8] = 2197 #expect(throws: RoutingGraphError.unsupportedVersion(major: 2, minor: 0)) { try RoutingGraph(data: future) }198 var past = data199 past[8] = 0200 #expect(throws: RoutingGraphError.unsupportedVersion(major: 0, minor: 0)) { try RoutingGraph(data: past) }201 // A newer minor version of the same major stays readable.202 var minor = data203 minor[10] = 7204 #expect(try RoutingGraph(data: minor).edgeCount == 5)205 #expect(throws: RoutingGraphError.self) { try RoutingGraph(data: Data()) }206 #expect(throws: RoutingGraphError.self) { try RoutingGraph(url: URL(fileURLWithPath: "/nonexistent/routing.orixgraph")) }207 }208209 @Test func truncatedFilesAreRejected() throws {210 let data = Self.sample().data()211 for length in stride(from: 0, to: data.count, by: 7) {212 #expect(throws: RoutingGraphError.self, "prefix of \(length) bytes") { try RoutingGraph(data: data.prefix(length)) }213 }214 // Appending bytes is also detected (declared size mismatch).215 #expect(throws: RoutingGraphError.self) { try RoutingGraph(data: data + Data([0, 0, 0, 0, 0, 0, 0, 0])) }216 }217218 @Test func outOfRangeIndicesAreRejected() throws {219 let g = Self.sample()220 let data = g.data()221 // Locate the EDGE section through the section table and corrupt node B of edge 0.222 func sectionOffset(_ name: String) -> Int {223 let count = Int(data[16])224 for i in 0..<count {225 let o = 64 + i * 32226 if data[o..<(o + 4)].elementsEqual(Array(name.utf8)) {227 return data[(o + 8)..<(o + 16)].enumerated().reduce(0) { $0 | Int($1.element) << (8 * $1.offset) }228 }229 }230 return -1231 }232 let edges = sectionOffset("EDGE")233 #expect(edges > 0)234 var corrupted = data235 corrupted[edges + 4] = 0xFF; corrupted[edges + 5] = 0xFF236 #expect(throws: RoutingGraphError.self) { try RoutingGraph(data: corrupted) }237 // Structural validation alone accepts the file, and using it must still be safe.238 let loose = try RoutingGraph(data: corrupted, validation: .structure)239 _ = try? Router(graph: loose).compute(request([p(10, 0), p(200, 190)], .pedestrian))240 _ = loose.geometry(ofEdge: 0)241242 var badShape = data243 let shapeField = edges + 12244 badShape[shapeField] = 0xF0; badShape[shapeField + 1] = 0xFF; badShape[shapeField + 2] = 0xFF; badShape[shapeField + 3] = 0x7F245 #expect(throws: RoutingGraphError.self) { try RoutingGraph(data: badShape) }246 let looseShape = try RoutingGraph(data: badShape, validation: .structure)247 #expect(looseShape.geometry(ofEdge: 0).count == 2)248249 var badAdjacency = data250 let adjacency = sectionOffset("ADJ ")251 badAdjacency[adjacency + 3] = 0x70252 #expect(throws: RoutingGraphError.self) { try RoutingGraph(data: badAdjacency) }253 }254255 /// Random corruption: opening either fails with a typed error or yields a graph that can be used without crashing.256 @Test func fuzzedFilesNeverCrash() throws {257 let data = Self.sample().data()258 var rng = SeededGenerator(seed: 0xC0FFEE)259 var opened = 0, rejected = 0260 for iteration in 0..<1500 {261 var bytes = data262 let flips = Int.random(in: 1...6, using: &rng)263 for _ in 0..<flips {264 let i = Int.random(in: 0..<bytes.count, using: &rng)265 bytes[i] = iteration % 3 == 0 ? UInt8.random(in: 0...255, using: &rng) : bytes[i] ^ (1 << UInt8.random(in: 0..<8, using: &rng))266 }267 if iteration % 10 == 0 { bytes = bytes.prefix(Int.random(in: 0..<bytes.count, using: &rng)) }268 for validation in [RoutingGraph.Validation.full, .structure] {269 do {270 let graph = try RoutingGraph(data: bytes, validation: validation)271 opened += 1272 for mode in TravelMode.allCases {273 _ = try? Router(graph: graph).compute(request([p(10, 0), p(200, 190)], .standard(for: mode), alternatives: 1))274 _ = try? graph.nearestRoad(to: p(5050, 5000), mode: mode)275 }276 for e in 0..<UInt32(graph.edgeCount + 2) { _ = graph.edge(at: e); _ = graph.geometry(ofEdge: e) }277 for n in 0..<UInt32(graph.nodeCount + 2) { _ = graph.directedEdges(leaving: n); _ = graph.componentRank(ofNode: n, mode: .car) }278 } catch is RoutingGraphError {279 rejected += 1280 }281 }282 }283 #expect(opened > 0)284 #expect(rejected > 0)285 }286287 @Test func writerRejectsInvalidInput() throws {288 var w = RoutingGraphWriter(options: .init(regionID: "x"))289 #expect(throws: RoutingGraphWriterError.empty) { try w.build() }290 #expect(throws: RoutingGraphWriterError.self) { try w.addNode(Coordinate(latitude: 95, longitude: 0)) }291 let a = try w.addNode(p(0, 0)), b = try w.addNode(p(100, 0)), c = try w.addNode(p(100, 100))292 #expect(throws: RoutingGraphWriterError.invalidNodeIndex(9)) { try w.addEdge(from: a, to: 9, attributes: .init()) }293 let ab = try w.addEdge(from: a, to: b, attributes: .init())294 let bc = try w.addEdge(from: b, to: c, attributes: .init())295 #expect(throws: RoutingGraphWriterError.self) { try w.addRestriction(from: ab, via: a, to: bc, kind: .prohibitive) }296 #expect(throws: RoutingGraphWriterError.invalidEdgeIndex(7)) { try w.addRestriction(from: 7, via: b, to: bc, kind: .prohibitive) }297 try w.addRestriction(from: ab, via: b, to: bc, kind: .mandatory)298 #expect(try RoutingGraph(data: w.build().data).restrictionCount == 1)299 }300301 @Test func aGraphWithoutEdgesOpensAndRoutesNothing() throws {302 var w = RoutingGraphWriter(options: .init(regionID: "empty"))303 try w.addNode(p(0, 0))304 let graph = try RoutingGraph(data: w.build().data)305 #expect(graph.edgeCount == 0)306 #expect(throws: RoutingError.pointTooFarFromRoad(waypointIndex: 0, maxDistanceMeters: 200)) {307 try Router(graph: graph).compute(request([p(0, 0), p(10, 0)]))308 }309 }310}311