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/ORIXGeoExchange/Tests/ORIXGeoExchangeTests/ExchangeTests.swift10// Module : ORIXGeoExchangeTests11// 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 ORIXGeoExchange9293private let t0 = Date(timeIntervalSince1970: 1_795_000_000)94private func pt(_ lat: Double, _ lon: Double, _ ele: Double? = nil, _ dt: TimeInterval? = nil) -> ExchangeDocument.TrackPoint {95 .init(coordinate: Coordinate(latitude: lat, longitude: lon), elevation: ele, time: dt.map { t0.addingTimeInterval($0) })96}97private let sample = ExchangeDocument(98 name: "Sortie <Mont-Royal> & \"amis\"",99 waypoints: [.init(coordinate: Coordinate(latitude: 45.5048, longitude: -73.5878), elevation: 233, time: t0, name: "Belvédère Kondiaronk", note: "Vue sur le centre-ville & le fleuve"),100 .init(coordinate: Coordinate(latitude: 45.5, longitude: -73.6))],101 tracks: [.init(name: "Montée", note: "Chemin Olmsted", segments: [[pt(45.5, -73.59, 60, 0), pt(45.501, -73.589, 75.5, 30), pt(45.502, -73.588, 90, 60)], [pt(45.503, -73.587, 120, 300), pt(45.504, -73.5865, 140, 330)]])],102 areas: [.init(name: "Lac aux Castors", rings: [[Coordinate(latitude: 45.498, longitude: -73.598), Coordinate(latitude: 45.499, longitude: -73.597), Coordinate(latitude: 45.498, longitude: -73.596)]])])103104@Suite struct GPXTests {105 @Test func roundTripKeepsPointsSegmentsTimesAndText() throws {106 let data = ExchangeCodec.encode(sample, format: .gpx)107 let back = try ExchangeCodec.decode(data, format: .gpx)108 #expect(back.name == sample.name)109 #expect(back.waypoints == sample.waypoints)110 // The area comes back as a closed track: GPX has no polygons.111 #expect(back.tracks.count == 2 && back.tracks[0] == sample.tracks[0])112 #expect(back.tracks[1].name == "Lac aux Castors" && back.tracks[1].segments[0].count == 4 && back.tracks[1].segments[0].first == back.tracks[1].segments[0].last)113 }114115 @Test func readsForeignFilesRoutesAndIgnoresExtensions() throws {116 let gpx = """117 <?xml version="1.0"?>118 <gpx version="1.0" creator="other" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1">119 <wpt lat="46.8139" lon="-71.2080"><name>Québec</name><sym>Flag</sym></wpt>120 <wpt lat="999" lon="0"><name>bad</name></wpt>121 <rte><name>Plan</name><rtept lat="46.81" lon="-71.21"/><rtept lat="46.82" lon="-71.22"><ele>12.5</ele></rtept></rte>122 <trk><name>T</name><trkseg>123 <trkpt lat="46.8" lon="-71.2"><ele>10</ele><time>2026-11-24T12:00:00.250Z</time><extensions><gpxtpx:TrackPointExtension><gpxtpx:hr>140</gpxtpx:hr></gpxtpx:TrackPointExtension></extensions></trkpt>124 <trkpt lat="46.801" lon="-71.201"><ele>nan</ele><time>garbage</time></trkpt>125 <trkpt lon="-71.2"/>126 </trkseg><trkseg></trkseg></trk>127 </gpx>128 """129 let doc = try ExchangeCodec.decode(Data(gpx.utf8), format: .gpx)130 #expect(doc.waypoints.count == 1 && doc.waypoints[0].name == "Québec")131 #expect(doc.tracks.count == 2)132 #expect(doc.tracks[0].name == "Plan" && doc.tracks[0].segments == [[pt(46.81, -71.21), pt(46.82, -71.22, 12.5)]])133 let seg = doc.tracks[1].segments134 #expect(seg.count == 1 && seg[0].count == 2 && seg[0][0].elevation == 10 && seg[0][0].time != nil && seg[0][1].elevation == nil && seg[0][1].time == nil)135 }136}137138@Suite struct GeoJSONTests {139 @Test func roundTrip() throws {140 let back = try ExchangeCodec.decode(ExchangeCodec.encode(sample, format: .geojson), format: .geojson)141 #expect(back.name == sample.name && back.waypoints == sample.waypoints && back.tracks == sample.tracks)142 #expect(back.areas.count == 1 && back.areas[0].name == "Lac aux Castors" && back.areas[0].rings[0].count == 4)143 }144145 @Test func readsEveryGeometryType() throws {146 let json = """147 {"type":"FeatureCollection","features":[148 {"type":"Feature","properties":{"title":"A","note":"n"},"geometry":{"type":"Point","coordinates":[-73.5,45.5,12]}},149 {"type":"Feature","properties":null,"geometry":{"type":"MultiPoint","coordinates":[[-73.5,45.5],[-73.6,45.6],[500,0],"x"]}},150 {"type":"Feature","properties":{},"geometry":{"type":"MultiLineString","coordinates":[[[-73,45],[-73.1,45.1]],[[-73.2,45.2]]]}},151 {"type":"Feature","properties":{"name":"P"},"geometry":{"type":"MultiPolygon","coordinates":[[[[0,0],[1,0],[1,1],[0,0]]],[[[2,2],[3,2],[3,3],[2,2]],[[2.2,2.2],[2.4,2.2],[2.4,2.4],[2.2,2.2]]]]}},152 {"type":"Feature","properties":{"name":"G"},"geometry":{"type":"GeometryCollection","geometries":[{"type":"Point","coordinates":[1,2]},{"type":"LineString","coordinates":[[1,2],[3,4]]}]}},153 {"type":"Feature","geometry":null},154 {"type":"Feature","properties":{},"geometry":{"type":"Circle","coordinates":[1,2]}}155 ]}156 """157 let doc = try ExchangeCodec.decode(Data(json.utf8), format: .geojson)158 #expect(doc.waypoints.count == 4 && doc.waypoints[0].name == "A" && doc.waypoints[0].note == "n" && doc.waypoints[0].elevation == 12 && doc.waypoints[3].name == "G")159 #expect(doc.tracks.count == 2 && doc.tracks[0].segments.count == 1 && doc.tracks[1].name == "G")160 #expect(doc.areas.count == 2 && doc.areas[1].rings.count == 2)161 let bare = try ExchangeCodec.decode(Data(#"{"type":"LineString","coordinates":[[0,0],[1,1]]}"#.utf8), format: .geojson)162 #expect(bare.tracks.count == 1)163 }164}165166@Suite struct KMLTests {167 @Test func roundTrip() throws {168 let back = try ExchangeCodec.decode(ExchangeCodec.encode(sample, format: .kml), format: .kml)169 #expect(back.name == sample.name && back.waypoints.map(\.name) == sample.waypoints.map(\.name) && back.waypoints[0].note == sample.waypoints[0].note)170 #expect(back.waypoints[0].coordinate == sample.waypoints[0].coordinate && back.waypoints[0].elevation == 233)171 #expect(back.tracks == sample.tracks)172 #expect(back.areas.count == 1 && back.areas[0].rings[0].count == 4)173 }174175 @Test func readsForeignPlacemarksAndUntimedLines() throws {176 let kml = """177 <?xml version="1.0" encoding="UTF-8"?>178 <kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Doc</name><Style id="s"><LineStyle><color>ff0000ff</color></LineStyle></Style>179 <Folder><name>F</name>180 <Placemark><name>Line</name><styleUrl>#s</styleUrl><LineString><tessellate>1</tessellate><coordinates>181 -73.5,45.5,10 -73.6,45.6182 bad -73.7,45.7,x 400,0183 </coordinates></LineString></Placemark>184 <Placemark><name>Poly</name><Polygon><innerBoundaryIs><LinearRing><coordinates>0.2,0.2 0.4,0.2 0.4,0.4 0.2,0.2</coordinates></LinearRing></innerBoundaryIs>185 <outerBoundaryIs><LinearRing><coordinates>0,0 1,0 1,1 0,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>186 <Placemark><Point><coordinates>-71.2,46.8</coordinates></Point></Placemark>187 </Folder></Document></kml>188 """189 let doc = try ExchangeCodec.decode(Data(kml.utf8), format: .kml)190 #expect(doc.name == "Doc" && doc.waypoints.count == 1 && doc.waypoints[0].name == nil)191 #expect(doc.tracks.count == 1 && doc.tracks[0].segments[0].count == 3 && doc.tracks[0].segments[0][0].elevation == 10 && doc.tracks[0].segments[0][2].elevation == nil)192 #expect(doc.areas.count == 1 && doc.areas[0].rings.count == 2 && doc.areas[0].rings[0][1] == Coordinate(latitude: 0, longitude: 1))193 }194}195196@Suite struct RobustnessTests {197 @Test func detection() {198 #expect(ExchangeFormat.detect(fileExtension: "GPX", data: Data()) == .gpx)199 #expect(ExchangeFormat.detect(fileExtension: nil, data: Data("<?xml version=\"1.0\"?><kml>".utf8)) == .kml)200 #expect(ExchangeFormat.detect(fileExtension: "txt", data: Data(" {\"type\":\"FeatureCollection\"}".utf8)) == .geojson)201 #expect(ExchangeFormat.detect(fileExtension: "json", data: Data("[1,2]".utf8)) == nil)202 }203204 @Test func rejectsWrongEmptyAndOversizedInput() {205 #expect(throws: ExchangeError.self) { try ExchangeCodec.decode(Data("<kml></kml>".utf8), format: .gpx) }206 #expect(throws: ExchangeError.empty) { try ExchangeCodec.decode(Data("<gpx></gpx>".utf8), format: .gpx) }207 #expect(throws: ExchangeError.empty) { try ExchangeCodec.decode(Data(#"{"type":"FeatureCollection","features":[]}"#.utf8), format: .geojson) }208 #expect(throws: ExchangeError.self) { try ExchangeCodec.decode(Data("<gpx><wpt lat=\"1\" lon=\"1\">".utf8), format: .gpx) }209 #expect(throws: ExchangeError.self) { try ExchangeCodec.decode(Data("[]".utf8), format: .geojson) }210 #expect(throws: ExchangeError.unsupportedFormat) { try ExchangeCodec.decode(Data("hello".utf8), fileExtension: "txt") }211 #expect(throws: ExchangeError.tooLarge(ExchangeLimits.maxBytes + 1)) { try ExchangeCodec.decode(Data(count: ExchangeLimits.maxBytes + 1), format: .gpx) }212 }213214 @Test func externalEntitiesAreNotResolved() throws {215 let xxe = """216 <?xml version="1.0"?><!DOCTYPE gpx [<!ENTITY x SYSTEM "file:///etc/passwd">]>217 <gpx><wpt lat="1" lon="1"><name>&x;</name></wpt></gpx>218 """219 let doc = try? ExchangeCodec.decode(Data(xxe.utf8), format: .gpx)220 #expect(doc?.waypoints.first?.name?.contains("root:") != true)221 }222223 @Test func mutatedFilesNeverCrash() {224 var rng = SystemRandomNumberGenerator()225 for format in ExchangeFormat.allCases {226 let good = ExchangeCodec.encode(sample, format: format)227 for _ in 0..<300 {228 var bad = good229 for _ in 0..<Int.random(in: 1...12, using: &rng) { bad[Int.random(in: 0..<bad.count, using: &rng)] = UInt8.random(in: 0...255, using: &rng) }230 if Bool.random(using: &rng) { bad = bad.prefix(Int.random(in: 0..<bad.count, using: &rng)) }231 _ = try? ExchangeCodec.decode(bad, format: format)232 }233 }234 }235236 @Test func textIsEscapedAndCapped() throws {237 var doc = ExchangeDocument(waypoints: [.init(coordinate: Coordinate(latitude: 1, longitude: 2), name: "a\u{0}b]]><x>&", note: String(repeating: "é", count: 10_000))])238 doc.name = "<script>"239 for format in ExchangeFormat.allCases {240 let back = try ExchangeCodec.decode(ExchangeCodec.encode(doc, format: format), format: format)241 #expect(back.waypoints[0].name?.hasSuffix("b]]><x>&") == true, "\(format)")242 #expect(back.waypoints[0].note?.count == ExchangeLimits.maxTextLength, "\(format)")243 #expect(back.name == "<script>", "\(format)")244 }245 }246247 @Test func boundsAndEmptiness() {248 #expect(ExchangeDocument().isEmpty && ExchangeDocument().bounds == nil)249 let b = sample.bounds!250 #expect(b.minLat == 45.498 && b.maxLat == 45.5048 && b.minLon == -73.6)251 }252}253