SPB Git

Repository Public BSD-3-Clause

OSMPBFReaderTests.swift 8.2 KB 188 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Infrastructure/ingestion/ORIXOSM/Tests/ORIXOSMTests/OSMPBFReaderTests.swift10// Module           : ORIXOSMTests11// 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 Testing90@testable import ORIXOSM9192private func fixture() throws -> URL {93    try #require(Bundle.module.url(forResource: "monaco.osm", withExtension: "pbf", subdirectory: "Fixtures"))94}9596@Suite struct OSMPBFReaderTests {97    @Test func readsMonaco() throws {98        let reader = try OSMPBFReader(url: fixture())99        let header = try reader.header()100        #expect(header.requiredFeatures.contains("OsmSchema-V0.6"))101        let bbox = try #require(header.bbox)102        #expect(bbox.minLon > 7.3 && bbox.maxLon < 7.6 && bbox.minLat > 43.4 && bbox.maxLat < 43.8)103104        var nodes = 0, ways = 0, relations = 0, taggedNodes = 0105        var lastNodeID: Int64 = .min, sorted = true106        var names = Set<String>()107        var highwayWays = 0, refsTotal = 0, restrictionRelations = 0, outside = 0108        try reader.read { block in109            for n in block.nodes {110                nodes += 1111                if n.id <= lastNodeID { sorted = false }112                lastNodeID = n.id113                if n.latitude < 43.3 || n.latitude > 44.0 || n.longitude < 7.0 || n.longitude > 7.9 { outside += 1 }114                if !n.tags.isEmpty { taggedNodes += 1 }115                if let name = n.tags["name"] { names.insert(name) }116            }117            for w in block.ways {118                ways += 1119                refsTotal += w.nodeRefs.count120                #expect(w.nodeRefs.count >= 1)121                if w.tags["highway"] != nil { highwayWays += 1 }122                if let name = w.tags["name"] { names.insert(name) }123            }124            for r in block.relations {125                relations += 1126                if r.tags["type"] == "restriction" { restrictionRelations += 1 }127            }128        }129        // Monaco has tens of thousands of nodes and thousands of ways; exact numbers move with every extract.130        #expect(nodes > 20_000 && ways > 3_000 && relations > 100)131        #expect(sorted)132        // The extract keeps a few nodes of ways that leave the country; nearly all nodes are in or around Monaco.133        #expect(outside < nodes / 20, "\(outside) of \(nodes) nodes far from Monaco")134        #expect(taggedNodes > 1_000 && taggedNodes < nodes)135        #expect(highwayWays > 500)136        #expect(refsTotal > ways * 2)137        #expect(restrictionRelations > 0)138        #expect(names.contains { $0.contains("Monte-Carlo") })139        #expect(names.contains { $0.contains("Grimaldi") })140        #expect(names.contains("Avenue de Monte-Carlo"))141    }142143    @Test func kindFilterAndSerialOrder() throws {144        let reader = try OSMPBFReader(url: fixture())145        var sawNodeAfterWay = false, sawWay = false, nodes = 0, ways = 0, relations = 0146        try reader.read([.ways, .relations], parallelism: 4) { block in147            nodes += block.nodes.count; ways += block.ways.count; relations += block.relations.count148        }149        #expect(nodes == 0 && ways > 0 && relations > 0)150        var all = 0151        try reader.read(.all, parallelism: 1) { block in152            if !block.ways.isEmpty { sawWay = true }153            if sawWay, !block.nodes.isEmpty, block.ways.isEmpty { sawNodeAfterWay = true }154            all += block.nodes.count + block.ways.count + block.relations.count155        }156        #expect(!sawNodeAfterWay)157        #expect(all > ways + relations)158    }159160    @Test func handlerErrorsPropagate() throws {161        struct Stop: Error {}162        let reader = try OSMPBFReader(url: fixture())163        #expect(throws: Stop.self) { try reader.read { _ in throw Stop() } }164    }165166    @Test func rejectsGarbage() throws {167        #expect(throws: OSMPBFError.self) { _ = try OSMPBFReader(data: Data([0, 0, 0])) }168        #expect(throws: OSMPBFError.self) { _ = try OSMPBFReader(data: Data([0xff, 0xff, 0xff, 0xff, 1, 2, 3])) }169        #expect(throws: OSMPBFError.self) { _ = try OSMPBFReader(data: Data(repeating: 0, count: 64)) }170        // A valid file cut in the middle, and the same file with flipped bytes, must fail cleanly and never crash.171        let good = try Data(contentsOf: fixture())172        #expect(throws: OSMPBFError.self) { _ = try OSMPBFReader(data: good.prefix(good.count / 2)) }173        var rng = SystemRandomNumberGenerator()174        for _ in 0..<40 {175            var bad = good176            for _ in 0..<64 { bad[Int.random(in: 0..<bad.count, using: &rng)] = UInt8.random(in: 0...255, using: &rng) }177            if let r = try? OSMPBFReader(data: bad) { try? r.read { _ in } }178        }179    }180181    @Test func zigzag() {182        #expect(ProtoReader.zigzag(0) == 0)183        #expect(ProtoReader.zigzag(1) == -1)184        #expect(ProtoReader.zigzag(2) == 1)185        #expect(ProtoReader.zigzag(UInt64.max) == Int64.min)186    }187}188
Files main
Menu

Theme