SPB Git

Repository Public BSD-3-Clause

TestSupport.swift 10.9 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXMapPackage/Tests/ORIXMapPackageTests/TestSupport.swift10// Module           : ORIXMapPackageTests11// 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 CryptoKit89import Foundation90import ORIXGeoCore91@testable import ORIXMapPackage9293/// A temporary directory removed when the value is released.94final class TempDir: @unchecked Sendable {95    let url: URL9697    init(_ label: String = "orixmap") {98        url = FileManager.default.temporaryDirectory.appendingPathComponent("\(label)-\(UUID().uuidString)")99        try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)100    }101102    deinit { try? FileManager.default.removeItem(at: url) }103104    func file(_ name: String) -> URL { url.appendingPathComponent(name) }105}106107/// Deterministic generator, so that a failing fuzz run can be replayed from its seed.108struct SeededGenerator: RandomNumberGenerator {109    var state: UInt64110    init(seed: UInt64) { state = seed == 0 ? 0x9E37_79B9_7F4A_7C15 : seed }111    mutating func next() -> UInt64 {112        state ^= state << 13; state ^= state >> 7; state ^= state << 17113        return state114    }115}116117func pseudoRandomData(_ count: Int, seed: UInt64) -> Data {118    var g = SeededGenerator(seed: seed)119    var data = Data(count: count)120    data.withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) in121        var i = 0122        while i + 8 <= count { buffer.storeBytes(of: g.next(), toByteOffset: i, as: UInt64.self); i += 8 }123        while i < count { buffer[i] = UInt8(truncatingIfNeeded: g.next()); i += 1 }124    }125    return data126}127128func sha256Hex(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }129130enum Fixture {131    static let montrealBox = BoundingBox(minLat: 45.15, minLon: -74.35, maxLat: 45.95, maxLon: -73.15)132    static let licences = [133        Licence(source: "OpenStreetMap", licence: "ODbL-1.0", attribution: "© OpenStreetMap contributors", url: "https://www.openstreetmap.org/copyright"),134        Licence(source: "Natural Earth", licence: "Public domain", attribution: "Made with Natural Earth", url: "https://www.naturalearthdata.com/"),135    ]136137    static func description(regionId: String = "ca-qc-montreal", version: String = "2026.11.24", minApp: String? = nil,138                            buildDate: Date = Timestamp.parse("2026-11-25T08:00:00Z")!) -> PackageWriter.Description {139        PackageWriter.Description(140            regionId: regionId, names: ["en": "Greater Montréal", "fr": "Grand Montréal"], bbox: montrealBox,141            dataVersion: DataVersion(version)!, dataTimestamp: Timestamp.parse("2026-11-24T00:00:00Z")!, buildDate: buildDate,142            mapZoom: ZoomRange(minZoom: 0, maxZoom: 14), languages: ["en", "fr"], licences: licences,143            builder: ["orix-package": "test"], minAppVersion: minApp.flatMap(AppVersion.init))144    }145146    /// Writes component files of the given sizes and assembles a signed package. Returns the package and the component bytes.147    @discardableResult148    static func makePackage(in dir: URL, name: String? = nil, regionId: String = "ca-qc-montreal", version: String = "2026.11.24",149                            sizes: [(ComponentID, Int)] = [(.map, 9000), (.search, 5000), (.routing, 3000)],150                            formatVersions: [ComponentID: Int] = [:], minApp: String? = nil, seed: UInt64 = 1,151                            buildDate: Date = Timestamp.parse("2026-11-25T08:00:00Z")!,152                            key: Curve25519.Signing.PrivateKey) throws -> (url: URL, components: [ComponentID: Data], manifest: PackageManifest) {153        var sources: [PackageWriter.ComponentSource] = []154        var contents: [ComponentID: Data] = [:]155        for (i, (id, size)) in sizes.enumerated() {156            let data = pseudoRandomData(size, seed: seed &* 1000 &+ UInt64(i) &+ 7)157            let url = dir.appendingPathComponent("src-\(UUID().uuidString.prefix(8))-\(id.rawValue).bin")158            try data.write(to: url)159            contents[id] = data160            sources.append(.init(id: id, url: url, formatVersion: formatVersions[id] ?? (id == .map || id == .terrain ? 3 : 1)))161        }162        let out = dir.appendingPathComponent(name ?? "\(regionId)-\(version)-\(UUID().uuidString.prefix(6)).orixmap")163        let manifest = try PackageWriter.write(description: description(regionId: regionId, version: version, minApp: minApp, buildDate: buildDate),164                                               components: sources, signingKey: key, to: out)165        for s in sources { try? FileManager.default.removeItem(at: s.url) }166        return (out, contents, manifest)167    }168169    /// Rebuilds a package around a modified manifest, signed again with `key`: what a hostile or buggy *signer* could170    /// produce. `mutate` edits the manifest as a JSON dictionary; the payload bytes after the first aligned offset are kept.171    static func resigned(_ package: Data, key: Curve25519.Signing.PrivateKey, fixTotal: Bool = false,172                         mutate: (inout [String: Any]) -> Void) throws -> Data {173        let header = try PackageHeader.parse(package)174        let manifestBytes = package.subdata(in: Int(header.manifestOffset)..<Int(header.signatureOffset))175        var object = try JSONSerialization.jsonObject(with: manifestBytes) as! [String: Any]176        mutate(&object)177        let newManifest = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])178        return try assemble(manifest: newManifest, key: key, payloadFrom: package, originalHeader: header,179                            total: fixTotal ? nil : header.totalLength)180    }181182    static func assemble(manifest: Data, key: Curve25519.Signing.PrivateKey, payloadFrom package: Data, originalHeader: PackageHeader,183                         total: UInt64?, headerKeyId: String? = nil) throws -> Data {184        let firstOffset = Int(PackageLayout.alignUp(originalHeader.preambleLength)!)185        let payload = package.count > firstOffset ? package.subdata(in: firstOffset..<package.count) : Data()186        var header = PackageHeader(manifestLength: UInt32(manifest.count), keyId: headerKeyId ?? TrustedKey(key.publicKey).keyId, totalLength: 0)187        let newFirst = Int(PackageLayout.alignUp(header.preambleLength)!)188        header.totalLength = total ?? UInt64(newFirst + payload.count)189        var out = header.encoded()190        out.append(manifest)191        out.append(try key.signature(for: manifest))192        out.append(Data(count: newFirst - out.count))193        out.append(payload)194        return out195    }196197    static func trust(_ keys: Curve25519.Signing.PrivateKey...) -> TrustStore {198        TrustStore(keys: keys.map { TrustedKey($0.publicKey) })199    }200}201202/// Runs a throwing body and returns the `PackageError` it threw, nil when it succeeded or threw something else.203func packageError(_ body: () throws -> Void) -> PackageError? {204    do { try body(); return nil } catch let e as PackageError { return e } catch { return nil }205}206207func listTree(_ root: URL) -> [String] {208    guard let e = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) else { return [] }209    let base = root.resolvingSymlinksInPath().path210    return e.allObjects.compactMap { ($0 as? URL)?.resolvingSymlinksInPath().path }211        .map { String($0.dropFirst(base.count + 1)) }.sorted()212}213214extension RegionStore {215    static func open(_ root: URL, trust: TrustStore, configure: (inout Configuration) -> Void = { _ in }) throws -> RegionStore {216        var c = Configuration(trustStore: trust)217        configure(&c)218        return try RegionStore(root: root, configuration: c)219    }220221    func setFault(_ point: FaultPoint?) { faultPoint = point }222}223
Files main
Menu

Theme