SPB Git

Repository Public BSD-3-Clause

StyleTests.swift 17.4 KB 298 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXMapStyle/Tests/ORIXMapStyleTests/StyleTests.swift10// Module           : ORIXMapStyleTests11// 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 ORIXMapStyle9293private let options = StyleOptions(glyphsURL: "file:///glyphs/{fontstack}/{range}.pbf", language: "fr")94private let base = StyleSource(id: "base", url: "pmtiles://file:///base.pmtiles", role: .base, minZoom: 0, maxZoom: 6)95private let region = StyleSource(id: "r-montreal", url: "pmtiles://file:///m.pmtiles", role: .region, minZoom: 0, maxZoom: 15,96                                 bounds: BoundingBox(minLat: 45.15, minLon: -74.35, maxLat: 45.95, maxLon: -73.15))9798@Suite struct ThemeTests {99    @Test func eightBuiltInThemesWithCompletePalettes() {100        #expect(BuiltInThemes.all.count == 8)101        #expect(Set(BuiltInThemes.all.map(\.id)).count == 8)102        for role in ColorRole.allCases {103            #expect(BuiltInThemes.dayColors[role] != nil, "day lacks \(role)")104            #expect(BuiltInThemes.midnightColors[role] != nil, "midnight lacks \(role)")105        }106        #expect(Set(ColorRole.groups.flatMap(\.roles)) == Set(ColorRole.allCases))107        #expect(ColorRole.groups.flatMap(\.roles).count == ColorRole.allCases.count)108    }109110    @Test func labelContrastIsAccessible() {111        for t in BuiltInThemes.all {112            // Text is drawn with a halo, so the halo is the effective background.113            #expect(t[.placeLabel].contrast(with: t[.labelHalo]) >= 7, "\(t.id) place labels")114            #expect(t[.roadLabel].contrast(with: t[.labelHalo]) >= 4.5, "\(t.id) road labels")115            #expect(t[.waterLabel].contrast(with: t[.labelHalo]) >= 4.5, "\(t.id) water labels")116            #expect(t[.poiLabel].contrast(with: t[.labelHalo]) >= 4.5, "\(t.id) POI labels")117            #expect(t[.route].contrast(with: t[.land]) >= 3, "\(t.id) route on land")118            for g in POIGroup.all {119                let c = t.isDark ? g.nightColor : g.dayColor120                #expect(c.contrast(with: t[.labelHalo]) >= 3, "\(t.id) POI group \(g.id)")121            }122        }123        let hc = BuiltInThemes.highContrast124        #expect(hc[.placeLabel].contrast(with: hc[.land]) >= 15)125        #expect(hc[.majorRoadCasing].contrast(with: hc[.majorRoad]) >= 15)126    }127128    @Test func hexColor() {129        #expect(HexColor("#FFFFFF")?.luminance == 1)130        #expect(HexColor("#000000")!.contrast(with: HexColor("#FFFFFF")!) == 21)131        #expect(HexColor("#12abEF")?.description == "#12ABEF")132        #expect(HexColor("#11223380")?.css == "rgba(17,34,51,0.502)")133        for bad in ["", "FFFFFF", "#FFF", "#GGGGGG", "#12345", "#1234567", "red", "#-12345"] { #expect(HexColor(bad) == nil, "\(bad)") }134        #expect(HexColor("#000000")!.mixed(with: HexColor("#FFFFFF")!, 0.5) == HexColor(red: 128, green: 128, blue: 128))135    }136137    @Test func poiGroupsDoNotOverlap() {138        var seen: [String: String] = [:]139        for g in POIGroup.all {140            for k in g.kinds {141                #expect(seen[k] == nil, "\(k) in \(g.id) and \(seen[k] ?? "")")142                seen[k] = g.id143            }144        }145        #expect(POIGroup.group(forKind: "cafe")?.id == "food")146        #expect(POIGroup.group(forKind: "bench") == nil)147    }148149    @Test func themeDocumentRoundTripAndSanitizing() throws {150        var t = BuiltInThemes.explorer151        t.roadWidthScale = 99; t.labelDensity = -3; t.labelSizeScale = .infinity; t.hiddenPOIGroups = ["food", "nonsense"]; t.name = "  My theme  "152        let data = try ThemeDocument(theme: BuiltInThemes.explorer).exported()153        let back = try ThemeDocument.importing(data, newID: "user.test")154        var expected = BuiltInThemes.explorer; expected.id = "user.test"155        #expect(back == expected)156        let s = t.sanitized157        #expect(s.roadWidthScale == 2 && s.labelDensity == 0 && s.labelSizeScale == 1 && s.hiddenPOIGroups == ["food"] && s.name == "My theme")158    }159160    @Test func themeImportRejectsBadFiles() throws {161        #expect(throws: ThemeDocument.ImportError.notAThemeFile) { try ThemeDocument.importing(Data("{}".utf8)) }162        #expect(throws: ThemeDocument.ImportError.notAThemeFile) { try ThemeDocument.importing(Data("not json".utf8)) }163        #expect(throws: ThemeDocument.ImportError.notAThemeFile) { try ThemeDocument.importing(Data(#"{"format":"orix-map-theme","version":1,"theme":{"id":"x","name":"n","colors":{"land":"blue"}}}"#.utf8)) }164        #expect(throws: ThemeDocument.ImportError.unsupportedVersion(2)) { try ThemeDocument.importing(Data(#"{"format":"orix-map-theme","version":2,"theme":{}}"#.utf8)) }165        #expect(throws: ThemeDocument.ImportError.tooLarge(70_000)) { try ThemeDocument.importing(Data(repeating: 0x20, count: 70_000)) }166        // Minimal file: missing fields take defaults, unknown fields and roles are ignored, the id is always replaced.167        let minimal = ##"{"format":"orix-map-theme","version":1,"future":1,"theme":{"id":"orix.day","name":"Mine","colors":{"land":"#101010","unknownRole":"#FFFFFF"},"extra":true}}"##168        let t = try ThemeDocument.importing(Data(minimal.utf8))169        #expect(t.id.hasPrefix("user.") && t.name == "Mine" && t[.land] == HexColor("#101010") && t[.water] == BuiltInThemes.day[.water] && t.colors.count == 1)170    }171}172173@Suite struct StyleBuilderTests {174    private func layers(_ style: StyleBuilder.JSON) -> [StyleBuilder.JSON] { style["layers"] as! [StyleBuilder.JSON] }175176    @Test func everyThemeProducesAValidDocument() throws {177        for theme in BuiltInThemes.all {178            let style = StyleBuilder.style(theme: theme, sources: [region, base], options: options)179            let data = try StyleBuilder.styleData(theme: theme, sources: [region, base], options: options)180            #expect(data.count > 10_000 && data.count < 400_000)181            #expect(style["version"] as? Int == 8)182            let sources = style["sources"] as! StyleBuilder.JSON183            #expect(Set(sources.keys) == Set(["base", "r-montreal"] + OverlayID.allSources))184            let ls = layers(style)185            #expect(Set(ls.map { $0["id"] as! String }).count == ls.count, "\(theme.id): duplicate layer ids")186            for l in ls where l["type"] as? String != "background" {187                #expect(sources[l["source"] as! String] != nil)188                if let lo = l["minzoom"] as? Double, let hi = l["maxzoom"] as? Double { #expect(lo < hi, "\(l["id"]!)") }189            }190            // Every colour in the document is a CSS colour produced from the palette (no stray role names).191            let text = String(decoding: data, as: UTF8.self)192            #expect(!text.contains("nan,") && !text.contains(":inf") && !text.contains(":nan"))193        }194    }195196    @Test func layerOrderKeepsLabelsAboveFillsAndOverlays() {197        let ids = layers(StyleBuilder.style(theme: BuiltInThemes.day, sources: [base, region], options: options)).map { $0["id"] as! String }198        func idx(_ id: String) -> Int { ids.firstIndex(of: id) ?? -1 }199        #expect(idx("background") == 0)200        #expect(idx("base-earth") < idx("r-montreal-earth"))201        #expect(idx("r-montreal-earth") < idx("r-montreal-water"))202        #expect(idx("r-montreal-tunnel-highway") < idx("r-montreal-building"))203        #expect(idx("r-montreal-building") < idx("r-montreal-road-highway"))204        #expect(idx("r-montreal-road-minor-casing") < idx("r-montreal-road-minor"))205        #expect(idx("r-montreal-road-highway") < idx("r-montreal-bridge-highway"))206        #expect(idx("r-montreal-bridge-highway") < idx("orix-route-line"))207        #expect(idx("orix-route-casing") < idx("orix-route-line"))208        #expect(idx("orix-route-line") < idx("base-place-country"))209        #expect(idx("orix-route-line") < idx("r-montreal-place-locality"))210        #expect(idx("r-montreal-place-locality") < idx("orix-pins-symbols"))211        #expect(idx("orix-pins-symbols") < idx("orix-location-dot"))212        #expect(ids.last == "orix-location-dot")213    }214215    @Test func regionsLeaveLowZoomsToTheBaseMap() {216        let withBase = layers(StyleBuilder.style(theme: BuiltInThemes.day, sources: [base, region], options: options))217        func find(_ ls: [StyleBuilder.JSON], _ id: String) -> StyleBuilder.JSON? { ls.first { $0["id"] as? String == id } }218        #expect(find(withBase, "r-montreal-earth")?["minzoom"] as? Double == 7)219        #expect(find(withBase, "r-montreal-place-locality")?["minzoom"] as? Double == 7)220        #expect(find(withBase, "base-place-locality")?["maxzoom"] as? Double == 7)221        #expect(find(withBase, "base-earth")?["maxzoom"] == nil)222        // Road lines of a region are drawn at every zoom: the base map has no detailed network.223        #expect(find(withBase, "r-montreal-road-highway")?["minzoom"] as? Double == 3)224        // Layers that could never be visible are not emitted at all.225        #expect(find(withBase, "base-label-road-minor") == nil)226        #expect(find(withBase, "r-montreal-place-country") == nil)227        let alone = layers(StyleBuilder.style(theme: BuiltInThemes.day, sources: [region], options: options))228        #expect(find(alone, "r-montreal-earth")?["minzoom"] == nil)229        #expect(find(alone, "r-montreal-place-country") != nil)230    }231232    @Test func worldLabelsAreDrawnOnlyWhenProvidedAndYieldToRegions() {233        var o = options; o.worldLabelsURL = "file:///world-labels.geojson"234        let style = StyleBuilder.style(theme: BuiltInThemes.day, sources: [base, region], options: o)235        let ls = layers(style)236        let ids = ls.map { $0["id"] as! String }237        #expect((style["sources"] as! StyleBuilder.JSON)["orix-world-labels"] != nil)238        #expect(ids.contains("orix-world-labels-country") && ids.contains("orix-world-labels-locality-low"))239        let high = ls.first { $0["id"] as? String == "orix-world-labels-locality-high" }!240        #expect(high["minzoom"] as? Double == 7)241        #expect(String(describing: high["filter"]!).contains("inRegion"))242        #expect(ids.firstIndex(of: "r-montreal-place-locality")! < ids.firstIndex(of: "orix-world-labels-country")!)243        #expect(ids.firstIndex(of: "orix-world-labels-country")! < ids.firstIndex(of: "orix-pins-symbols")!)244        let none = layers(StyleBuilder.style(theme: BuiltInThemes.day, sources: [base], options: options)).map { $0["id"] as! String }245        #expect(!none.contains { $0.hasPrefix("orix-world-labels") })246    }247248    @Test func themeSwitchesChangeTheLayerSet() {249        func ids(_ t: MapTheme) -> Set<String> { Set(layers(StyleBuilder.style(theme: t, sources: [region], options: options)).map { $0["id"] as! String }) }250        let day = ids(BuiltInThemes.day), minimal = ids(BuiltInThemes.minimal), transit = ids(BuiltInThemes.transit)251        #expect(day.contains("r-montreal-building") && day.contains("r-montreal-building-3d") && day.contains("r-montreal-poi-food"))252        #expect(!minimal.contains("r-montreal-building") && !minimal.contains("r-montreal-poi-food") && !minimal.contains("r-montreal-label-housenumber"))253        #expect(transit.contains("r-montreal-poi-transit") && !transit.contains("r-montreal-poi-food") && !transit.contains("r-montreal-building-3d"))254        var custom = BuiltInThemes.day255        custom.showLandUse = false; custom.roadCasings = false256        let c = ids(custom)257        #expect(!c.contains("r-montreal-landuse-park") && !c.contains("r-montreal-road-major-casing") && c.contains("r-montreal-road-major"))258    }259260    @Test func languageAndWidthsFollowOptionsAndTheme() throws {261        var heavy = BuiltInThemes.day; heavy.roadWidthScale = 2262        let a = layers(StyleBuilder.style(theme: BuiltInThemes.day, sources: [region], options: options)).first { $0["id"] as? String == "r-montreal-road-highway" }!263        let b = layers(StyleBuilder.style(theme: heavy, sources: [region], options: options)).first { $0["id"] as? String == "r-montreal-road-highway" }!264        let wa = (a["paint"] as! StyleBuilder.JSON)["line-width"] as! [Any], wb = (b["paint"] as! StyleBuilder.JSON)["line-width"] as! [Any]265        #expect((wb.last as! Double) == 2 * (wa.last as! Double))266        let fr = String(decoding: try StyleBuilder.styleData(theme: BuiltInThemes.day, sources: [region], options: options), as: UTF8.self)267        #expect(fr.contains("name:fr") && !fr.contains("name:en"))268        let none = String(decoding: try StyleBuilder.styleData(theme: BuiltInThemes.day, sources: [region], options: StyleOptions(glyphsURL: "x", language: "")), as: UTF8.self)269        #expect(!none.contains("name:"))270    }271}272273@Suite struct RegionRenderPlannerTests {274    private let province = RegionRenderPlanner.Candidate(id: "quebec", bounds: BoundingBox(minLat: 44.9, minLon: -79.8, maxLat: 62.6, maxLon: -57.1), dataVersion: "2026.11.24", maxZoom: 15)275    private let city = RegionRenderPlanner.Candidate(id: "montreal", bounds: BoundingBox(minLat: 45.15, minLon: -74.35, maxLat: 45.95, maxLon: -73.15), dataVersion: "2026.11.24", maxZoom: 15)276277    @Test func containedRegionWithSameDataIsNotDrawnTwice() {278        #expect(RegionRenderPlanner.regionsToDraw([city, province]) == ["quebec"])279        #expect(RegionRenderPlanner.regionsToDraw([city]) == ["montreal"])280        #expect(RegionRenderPlanner.regionsToDraw([]) == [])281    }282283    @Test func newerOrDeeperContainedRegionIsKept() {284        var newer = city; newer.dataVersion = "2026.12.2"285        #expect(RegionRenderPlanner.regionsToDraw([newer, province]) == ["quebec", "montreal"])286        var deeper = city; deeper.maxZoom = 16287        #expect(RegionRenderPlanner.regionsToDraw([deeper, province]) == ["quebec", "montreal"])288        var older = city; older.dataVersion = "2026.9.30"289        #expect(RegionRenderPlanner.regionsToDraw([older, province]) == ["quebec"])290    }291292    @Test func overlappingButNotContainedRegionsAreBothDrawn() {293        let ottawa = RegionRenderPlanner.Candidate(id: "ottawa", bounds: BoundingBox(minLat: 45.0, minLon: -76.4, maxLat: 45.7, maxLon: -75.0), dataVersion: "2026.11.24", maxZoom: 15)294        let ontarioEdge = RegionRenderPlanner.Candidate(id: "east-ontario", bounds: BoundingBox(minLat: 44.0, minLon: -77.0, maxLat: 45.6, maxLon: -74.3), dataVersion: "2026.11.24", maxZoom: 15)295        #expect(Set(RegionRenderPlanner.regionsToDraw([ottawa, ontarioEdge])) == ["ottawa", "east-ontario"])296    }297}298
Files main
Menu

Theme