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/ORIXTileStore/Tests/ORIXTileStoreTests/TileStoreTests.swift10// Module : ORIXTileStoreTests11// 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 ORIXTileStore9293/// The world base map bundled with the application (12.7 MB, zoom 0–6) is the real-data fixture.94private let baseMapURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()95 .appending(path: "Apps/ORIXMaps/Resources/BaseMap/world-base.pmtiles")9697@Suite struct PMTilesTests {98 @Test func hilbertTileIDsMatchTheSpecification() {99 // Reference values from the PMTiles v3 specification and reference implementation.100 #expect(PMTilesArchive.tileID(TileID(z: 0, x: 0, y: 0)) == 0)101 #expect(PMTilesArchive.tileID(TileID(z: 1, x: 0, y: 0)) == 1)102 #expect(PMTilesArchive.tileID(TileID(z: 1, x: 0, y: 1)) == 2)103 #expect(PMTilesArchive.tileID(TileID(z: 1, x: 1, y: 1)) == 3)104 #expect(PMTilesArchive.tileID(TileID(z: 1, x: 1, y: 0)) == 4)105 #expect(PMTilesArchive.tileID(TileID(z: 2, x: 0, y: 0)) == 5)106 #expect(PMTilesArchive.tileID(TileID(z: 12, x: 3423, y: 1763)) == 19_078_479)107 // Every tile of a zoom level has a distinct identifier inside the level's range.108 var seen = Set<UInt64>()109 for x in 0..<16 { for y in 0..<16 { seen.insert(PMTilesArchive.tileID(TileID(z: 4, x: UInt32(x), y: UInt32(y)))) } }110 #expect(seen.count == 256 && seen.min() == 85 && seen.max() == 340)111 }112113 @Test func readsTheBundledWorldMap() throws {114 let archive = try PMTilesArchive(url: baseMapURL)115 let h = archive.header116 #expect(h.minZoom == 0 && h.maxZoom == 6 && h.tileType == 1 && h.tileCompression == 2)117 #expect(h.bounds.minLon == -180 && h.bounds.maxLon == 180 && h.addressedTiles == 5461)118 let meta = try archive.metadata()119 let layers = (meta["vector_layers"] as? [[String: Any]])?.compactMap { $0["id"] as? String } ?? []120 #expect(layers.contains("earth") && layers.contains("water"))121 // Every tile of zooms 0–3 exists and decodes.122 var decoded = 0123 for z in 0...3 {124 for x in 0..<(1 << z) { for y in 0..<(1 << z) {125 let data = try #require(try archive.tile(TileID(z: UInt8(z), x: UInt32(x), y: UInt32(y))))126 let tile = try VectorTile(data: data)127 #expect(!tile.layers.isEmpty)128 decoded += 1129 } }130 }131 #expect(decoded == 85)132 #expect(try archive.tile(TileID(z: 7, x: 0, y: 0)) == nil)133 #expect(try archive.tile(TileID(z: 2, x: 9, y: 0)) == nil)134 }135136 @Test func vectorTileContentIsPlausible() throws {137 let archive = try PMTilesArchive(url: baseMapURL)138 // z3 tile over eastern North America.139 let tile = try VectorTile(data: try #require(try archive.tile(WebMercator.tile(for: Coordinate(latitude: 45.5, longitude: -73.6), zoom: 3))))140 let earth = try #require(tile.layer("earth"))141 #expect(earth.extent == 4096)142 let land = try #require(earth.features.first { $0.type == .polygon })143 #expect(land.attributes["kind"]?.string == "earth")144 #expect(land.parts.allSatisfy { $0.count >= 4 && $0.first == $0.last })145 #expect(land.parts.contains { VectorTile.signedArea($0) > 0 })146 let boundaries = try #require(tile.layer("boundaries"))147 #expect(boundaries.features.contains { $0.type == .line && $0.attributes["kind"]?.string == "country" && $0.attributes["kind_detail"]?.number == 2 })148 let water = try #require(tile.layer("water"))149 #expect(water.features.contains { $0.attributes["kind"]?.string == "ocean" })150 // Coordinates stay within the tile plus a reasonable buffer.151 for layer in tile.layers { for f in layer.features { for p in f.parts.joined() { #expect(p.x > -2048 && p.x < 6144 && p.y > -2048 && p.y < 6144) } } }152 }153154 @Test func rejectsForeignTruncatedAndCorruptedArchives() throws {155 #expect(throws: TileStoreError.truncated("header")) { _ = try PMTilesArchive(data: Data(count: 50)) }156 #expect(throws: TileStoreError.notPMTiles) { _ = try PMTilesArchive(data: Data(count: 200)) }157 let good = try Data(contentsOf: baseMapURL)158 var v2 = good; v2[7] = 2159 #expect(throws: TileStoreError.unsupportedVersion(2)) { _ = try PMTilesArchive(data: v2) }160 #expect(throws: TileStoreError.self) { _ = try PMTilesArchive(data: good.prefix(100_000)) }161 // Hostile offsets: a root directory placed beyond the end of the file.162 var far = good163 for i in 8..<16 { far[i] = 0xff }164 #expect(throws: TileStoreError.self) { _ = try PMTilesArchive(data: far) }165 // Random corruption of the first megabyte (header, directories) must never crash.166 var rng = SystemRandomNumberGenerator()167 let head = good.prefix(1_000_000)168 for _ in 0..<60 {169 var bad = Data(head)170 for _ in 0..<40 { bad[Int.random(in: 0..<min(bad.count, 20_000), using: &rng)] = UInt8.random(in: 0...255, using: &rng) }171 if let a = try? PMTilesArchive(data: bad) {172 for z in 0...4 { _ = try? a.tile(TileID(z: UInt8(z), x: 0, y: 0)).map { try? VectorTile(data: $0) } }173 _ = try? a.metadata()174 }175 }176 }177178 @Test func corruptedTilesNeverCrashTheDecoder() throws {179 let archive = try PMTilesArchive(url: baseMapURL)180 let good = try #require(try archive.tile(TileID(z: 2, x: 1, y: 1)))181 var rng = SystemRandomNumberGenerator()182 for _ in 0..<400 {183 var bad = good184 for _ in 0..<Int.random(in: 1...10, using: &rng) { bad[Int.random(in: 0..<bad.count, using: &rng)] = UInt8.random(in: 0...255, using: &rng) }185 if Bool.random(using: &rng) { bad = bad.prefix(Int.random(in: 0..<bad.count, using: &rng)) }186 _ = try? VectorTile(data: bad)187 }188 #expect(throws: TileStoreError.self) { _ = try VectorTile(data: Data([0x1a, 0xff, 0xff, 0xff, 0xff, 0x0f])) }189 #expect(try VectorTile(data: Data()).layers.isEmpty)190 }191}192193@Suite struct CacheTests {194 @Test func lruEvictsByCostAndCount() {195 var c = LRUCache<String, Int>(costLimit: 100, countLimit: 3)196 #expect(c.insert(1, for: "a", cost: 40).isEmpty && c.insert(2, for: "b", cost: 40).isEmpty)197 #expect(c.value(for: "a") == 1) // "a" is now the most recent198 #expect(c.insert(3, for: "c", cost: 40) == ["b"]) // over the cost budget: least recent goes199 #expect(c.totalCost == 80 && c.count == 2 && !c.contains("b"))200 #expect(c.insert(9, for: "huge", cost: 500) == ["huge"] && !c.contains("huge"))201 c.insert(4, for: "d", cost: 1); c.insert(5, for: "e", cost: 1)202 #expect(c.count == 3 && !c.contains("a"))203 c.insert(7, for: "c", cost: 10) // replacing updates the cost204 #expect(c.totalCost == 12 && c.value(for: "c") == 7)205 #expect(c.remove("c") == 7 && c.remove("zzz") == nil)206 c.removeAll()207 #expect(c.count == 0 && c.totalCost == 0)208 }209210 @Test func tileStoreCachesSharesLoadsAndFallsBackToAncestors() async throws {211 let store = TileStore(archive: try PMTilesArchive(url: baseMapURL), memoryLimit: 8 * 1024 * 1024)212 let id = TileID(z: 3, x: 2, y: 2)213 async let a = store.tile(id), b = store.tile(id), c = store.tile(id)214 let tiles = try await [a, b, c]215 #expect(tiles[0] != nil && tiles[0] == tiles[1] && tiles[1] == tiles[2])216 #expect(await store.misses == 1)217 _ = try await store.tile(id)218 #expect(await store.hits >= 1)219 // Zoom 9 does not exist in the archive: the best tile is the zoom 6 ancestor.220 let deep = WebMercator.tile(for: Coordinate(latitude: 45.5, longitude: -73.6), zoom: 9)221 let best = try #require(try await store.bestTile(for: deep))222 #expect(best.0 == deep.ancestor(atZoom: 6))223 #expect(await store.cachedCost > 0)224 await store.purge()225 #expect(await store.cachedCost == 0)226 }227}228