SPB Git

Repository Public BSD-3-Clause

IndexTests.swift 28.3 KB 479 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXSearch/Tests/ORIXSearchTests/IndexTests.swift10// Module           : ORIXSearchTests11// 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 ORIXSearch9293@Suite struct EndToEndTests {94    @Test func writerSummaryAndMetadata() async throws {95        let url = Fixture.temporaryURL()96        let summary = try Fixture.buildMontreal(at: url)97        #expect(summary.places == 6)98        #expect(summary.streets == 8)99        #expect(summary.pois == 15)100        #expect(summary.addresses == 7) // the duplicate "1000" on the building is merged101        #expect(summary.interpolations == 1)102        #expect(summary.fileSize > 0)103        let info = try SearchEngine.inspect(at: url)104        #expect(info.regionID == "test-montreal")105        #expect(info.schemaMajor == SearchSchema.majorVersion)106        #expect(info.dataDate == Fixture.dataDate)107        #expect(info.buildDate != nil)108        #expect(info.attribution == "© OpenStreetMap contributors (ODbL)")109        #expect(info.builderVersion == "tests")110        #expect(info.placeCount == 6 && info.poiCount == 15 && info.streetCount == 8 && info.addressCount == 7 && info.interpolationCount == 1)111        #expect(info.boundingBox == BoundingBox(minLat: 45.40, minLon: -73.98, maxLat: 45.71, maxLon: -73.47))112    }113114    @Test func nameSearchIgnoresAccentsAndCase() async throws {115        let engine = try await Fixture.montrealEngine()116        for text in ["Montréal", "montreal", "MONTREAL", "mtl"] {117            let r = try await engine.search(SearchQuery(text: text))118            #expect(r.results.first?.name == "Montréal", "query \(text)")119            #expect(r.results.first?.kind == .place)120            #expect(r.results.first?.placeType == .city)121        }122        let r = try await engine.search(SearchQuery(text: "stade olympique"))123        let stadium = try #require(r.results.first)124        #expect(stadium.name == "Stade olympique")125        #expect(stadium.kind == .poi)126        #expect(stadium.category == .sports)127        #expect(stadium.osm == OSMElementRef(type: .way, id: 200))128        #expect(stadium.regionID == "test-montreal")129        #expect(stadium.dataDate == Fixture.dataDate)130        #expect(stadium.boundingBox != nil)131        #expect(stadium.secondaryLine == "4545 Avenue Pierre-De Coubertin, Montréal")132        #expect(stadium.id == "test-montreal/w200")133        // English variant.134        #expect(try await engine.search(SearchQuery(text: "Olympic Stadium")).results.first?.name == "Stade olympique")135    }136137    @Test func abbreviationsFindStreets() async throws {138        let engine = try await Fixture.montrealEngine()139        for text in ["av du Parc", "ave du parc", "avenue du parc", "Park Avenue"] {140            #expect(try await engine.search(SearchQuery(text: text)).results.first?.name == "Avenue du Parc", "query \(text)")141        }142        for text in ["boul René-Lévesque O", "blvd rene levesque ouest", "boulevard René-Lévesque West"] {143            #expect(try await engine.search(SearchQuery(text: text)).results.first?.name == "Boulevard René-Lévesque Ouest", "query \(text)")144        }145        for text in ["rue St-Denis", "rue saint denis", "st denis"] {146            let first = try await engine.search(SearchQuery(text: text)).results.first147            #expect(first?.name == "Rue Saint-Denis", "query \(text)")148            #expect(first?.kind == .street)149            #expect(first?.streetClass == .secondary)150            #expect(first?.boundingBox != nil)151            #expect(first?.city == "Montréal")152        }153    }154155    @Test func roadReferences() async throws {156        let engine = try await Fixture.montrealEngine()157        for text in ["A-40", "a40", "A 40", "Autoroute 40", "aut 40"] {158            let first = try await engine.search(SearchQuery(text: text)).results.first159            #expect(first?.name == "Autoroute Métropolitaine", "query \(text)")160            #expect(first?.roadRef == "40")161            #expect(first?.streetClass == .motorway)162        }163        #expect(try await engine.search(SearchQuery(text: "route 138")).results.first?.name == "Rue Sherbrooke Ouest")164    }165166    @Test func addressWithTaggedNumber() async throws {167        let engine = try await Fixture.montrealEngine()168        for text in ["1000 rue Sherbrooke Ouest", "1000 Sherbrooke O", "1000, rue Sherbrooke Ouest, Montréal", "1000 sherbrooke street west", "1000 sherbrooke ouest montreal"] {169            let r = try await engine.search(SearchQuery(text: text))170            let first = try #require(r.results.first, "query \(text)")171            #expect(first.kind == .address, "query \(text)")172            #expect(first.addressMatch == .exact)173            #expect(first.houseNumber == "1000")174            #expect(first.street == "Rue Sherbrooke Ouest")175            #expect(first.name == "1000 Rue Sherbrooke Ouest")176            #expect(first.city == "Montréal")177            #expect(first.osm == OSMElementRef(type: .node, id: 1000))178            #expect(abs(first.coordinate.latitude - 45.5031) < 1e-6 && abs(first.coordinate.longitude + 73.5760) < 1e-6)179            #expect(first.requestedHouseNumber == "1000")180            // The node and the building carrying the same number 2 m apart are one address.181            #expect(r.results.filter { $0.kind == .address }.count == 1)182        }183    }184185    @Test func addressSuffixRangeAndInterpolation() async throws {186        let engine = try await Fixture.montrealEngine()187        let suffix = try #require(try await engine.search(SearchQuery(text: "1002 rue Sherbrooke Ouest")).results.first)188        #expect(suffix.addressMatch == .sameNumberOtherSuffix)189        #expect(suffix.houseNumber == "1002A")190        let exactSuffix = try #require(try await engine.search(SearchQuery(text: "1002a rue Sherbrooke Ouest")).results.first)191        #expect(exactSuffix.addressMatch == .exact)192        let range = try #require(try await engine.search(SearchQuery(text: "1012 rue Sherbrooke Ouest")).results.first)193        #expect(range.addressMatch == .withinTaggedRange)194        #expect(range.houseNumber == "1010-1014")195        #expect(range.osm == OSMElementRef(type: .way, id: 1010))196        let unit = try #require(try await engine.search(SearchQuery(text: "301-845 rue Sherbrooke Ouest")).results.first)197        #expect(unit.addressMatch == .exact)198        #expect(unit.houseNumber == "845")199200        // 1150 is half-way along the even interpolation 1100…1200.201        let estimated = try #require(try await engine.search(SearchQuery(text: "1150 rue Sherbrooke Ouest")).results.first)202        #expect(estimated.kind == .address)203        #expect(estimated.addressMatch == .interpolated)204        #expect(estimated.houseNumber == "1150")205        #expect(abs(estimated.coordinate.longitude - (-73.5790)) < 1e-5)206        #expect(estimated.osm == OSMElementRef(type: .way, id: 7000))207        // 1151 is odd: not part of an even range.208        let odd = try #require(try await engine.search(SearchQuery(text: "1151 rue Sherbrooke Ouest")).results.first)209        #expect(odd.addressMatch == .streetOnly)210    }211212    @Test func unknownNumberReturnsTheStreetFlagged() async throws {213        let engine = try await Fixture.montrealEngine()214        let r = try await engine.search(SearchQuery(text: "99999 rue Sherbrooke Ouest", focus: Fixture.downtown))215        #expect(!r.results.isEmpty)216        #expect(!r.results.contains { $0.kind == .address })217        let first = try #require(r.results.first)218        #expect(first.kind == .street)219        #expect(first.addressMatch == .streetOnly)220        #expect(first.requestedHouseNumber == "99999")221        #expect(first.name == "Rue Sherbrooke Ouest")222        #expect(first.houseNumber == nil)223        #expect(first.city == "Montréal")224        // Both municipalities' pieces of the street are listed, each flagged.225        #expect(r.results.filter { $0.addressMatch == .streetOnly }.map(\.city).contains("Westmount"))226    }227228    @Test func localityRestrictsAndFallsBack() async throws {229        let engine = try await Fixture.montrealEngine()230        // Westmount has no number 1000: the street of Westmount is reported as street-only, and the number found in Montréal is still offered.231        let r = try await engine.search(SearchQuery(text: "1000 rue Sherbrooke Ouest, Westmount"))232        #expect(r.results.contains { $0.addressMatch == .streetOnly && $0.city == "Westmount" })233        #expect(r.results.contains { $0.addressMatch == .exact && $0.city == "Montréal" })234        // A locality at the end, with and without a comma.235        for text in ["pharmacie jean coutu laval", "Pharmacie Jean Coutu, Laval"] {236            let first = try #require(try await engine.search(SearchQuery(text: text)).results.first, "query \(text)")237            #expect(first.city == "Laval", "query \(text)")238            #expect(first.osm == OSMElementRef(type: .node, id: 211))239        }240        #expect(try await engine.search(SearchQuery(text: "café, Laval")).results.first?.name == "Café du Nord")241        // An unknown locality does not hide the results.242        #expect(try await engine.search(SearchQuery(text: "Café Olimpico, Atlantide")).results.first?.name == "Café Olimpico")243        // A borough works as a locality.244        #expect(try await engine.search(SearchQuery(text: "café, Plateau-Mont-Royal")).results.first?.name == "Café Névé")245    }246247    @Test func categoryNearAPoint() async throws {248        let engine = try await Fixture.montrealEngine()249        let r = try await engine.search(SearchQuery(text: "café", focus: Fixture.downtown))250        #expect(r.matchedCategory == .cafe)251        let cafes = r.results.filter { $0.category == .cafe }252        #expect(cafes.map(\.name) == ["Café Olimpico", "Dispatch Coffee", "Café Névé", "Café du Nord"])253        #expect(cafes.allSatisfy { $0.distance != nil })254        #expect(cafes[0].distance! < cafes[1].distance! && cafes[1].distance! < cafes[2].distance!)255        #expect(cafes[1].matchedBy == .category) // "Dispatch Coffee" has no "café" in its name256        // French and English synonyms, unnamed features included.257        for text in ["essence", "gas station", "station-service"] {258            let fuel = try await engine.search(SearchQuery(text: text, focus: Fixture.downtown))259            #expect(fuel.matchedCategory == .fuel, "query \(text)")260            #expect(fuel.results.first?.name == "", "the unnamed station is the nearest")261            #expect(fuel.results.first?.category == .fuel)262            #expect(fuel.results.count == 2)263        }264        // Explicit category filter without text (map filters, Explorer).265        let filtered = try await engine.pointsOfInterest(categories: [.pharmacy], focus: Fixture.downtown, limit: 10)266        #expect(filtered.map(\.name) == ["Pharmaprix", "Pharmacie Jean Coutu", "Pharmacie Jean Coutu"])267        // A brand is not a category: it is found by name.268        let saq = try await engine.search(SearchQuery(text: "SAQ", focus: Fixture.downtown))269        #expect(saq.matchedCategory == nil)270        #expect(saq.results.first?.category == .liquorStore)271        #expect(saq.results.first?.matchedBy == .name)272        // A category word next to a name that does not contain it.273        #expect(try await engine.search(SearchQuery(text: "métro Berri-UQAM")).results.first?.name == "Berri-UQAM")274    }275276    @Test func rankingByRelevanceImportanceAndDistance() async throws {277        let engine = try await Fixture.montrealEngine()278        // Without a focus the exact, important match comes first.279        let plain = try await engine.search(SearchQuery(text: "sherbrooke"))280        #expect(plain.results.first?.name == "Sherbrooke")281        #expect(plain.results.first?.placeType == .city)282        #expect(plain.results.contains { $0.name == "Rue Sherbrooke Ouest" })283        #expect(plain.results.contains { $0.name == "Lac-Sherbrooke" })284        #expect(plain.results.first { $0.name == "Lac-Sherbrooke" }?.cityIsApproximate == true)285        // Two identical names: the nearer one first, wherever the focus is.286        let nearDowntown = try await engine.search(SearchQuery(text: "pharmacie jean coutu", focus: Fixture.downtown))287        #expect(nearDowntown.results.first?.osm?.id == 212)288        let nearLaval = try await engine.search(SearchQuery(text: "pharmacie jean coutu", focus: Coordinate(latitude: 45.5705, longitude: -73.7405)))289        #expect(nearLaval.results.first?.osm?.id == 211)290        // Viewport bias without a focus.291        let inLaval = try await engine.search(SearchQuery(text: "pharmacie jean coutu", viewport: BoundingBox(minLat: 45.55, minLon: -73.78, maxLat: 45.60, maxLon: -73.70)))292        #expect(inLaval.results.first?.osm?.id == 211)293        // The street is measured to its geometry, not to its middle: 30 m north of its west end.294        let onStreet = try await engine.search(SearchQuery(text: "rue sherbrooke ouest", focus: Coordinate(latitude: 45.5033, longitude: -73.5895)))295        let street = try #require(onStreet.results.first)296        #expect(street.city == "Montréal")297        #expect(street.distance! < 50)298        // The same street in another municipality stays a separate line.299        #expect(onStreet.results.filter { $0.kind == .street && $0.name == "Rue Sherbrooke Ouest" }.count == 2)300    }301302    @Test func typoCorrectionOnlyWhenNeeded() async throws {303        let engine = try await Fixture.montrealEngine()304        let r = try await engine.search(SearchQuery(text: "sherbroke"))305        #expect(r.corrections == [TermCorrection(original: "sherbroke", replacements: ["sherbrooke"])])306        #expect(r.results.first?.name == "Sherbrooke")307        #expect(r.results.allSatisfy { $0.isTypoCorrected })308        let m = try await engine.search(SearchQuery(text: "montreel"))309        #expect(m.results.first?.name == "Montréal")310        #expect(m.corrections.first?.replacements == ["montreal"])311        let two = try await engine.search(SearchQuery(text: "stade olimpiqe"))312        #expect(two.results.first?.name == "Stade olympique")313        let address = try await engine.search(SearchQuery(text: "1000 rue sherbroke ouest"))314        #expect(address.results.first?.addressMatch == .exact)315        #expect(address.results.first?.isTypoCorrected == true)316        // A correct query is never "corrected".317        let ok = try await engine.search(SearchQuery(text: "sherbrooke"))318        #expect(ok.corrections.isEmpty)319        #expect(ok.results.allSatisfy { !$0.isTypoCorrected })320        // Nothing close in the vocabulary: no result rather than a wild guess.321        let none = try await engine.search(SearchQuery(text: "xyzzyqwerty"))322        #expect(none.results.isEmpty)323        #expect(none.corrections.isEmpty)324        // Type-ahead corrects only when nothing matches the prefix.325        let typing = try await engine.suggest("sherbor")326        #expect(typing.results.contains { $0.name == "Sherbrooke" })327    }328329    @Test func suggestionsArePrefixQueries() async throws {330        let engine = try await Fixture.montrealEngine()331        #expect(try await engine.suggest("mon").results.first?.name == "Montréal")332        #expect(try await engine.suggest("sta").results.contains { $0.name == "Stade olympique" })333        #expect(try await engine.suggest("stade ol").results.first?.name == "Stade olympique")334        #expect(try await engine.suggest("rue sain").results.first?.name == "Rue Saint-Denis")335        #expect(try await engine.suggest("1000 rue sher").results.first?.addressMatch == .exact)336        let pharm = try await engine.suggest("pharm", focus: Fixture.downtown)337        #expect(pharm.matchedCategory == .pharmacy)338        #expect(pharm.results.first?.name == "Pharmaprix")339        // A submitted query still accepts an unfinished last word only as a whole word.340        #expect(try await engine.search(SearchQuery(text: "sta", mode: .full)).results.isEmpty)341        #expect(try await engine.suggest("", focus: Fixture.downtown).results.isEmpty)342        #expect(try await engine.suggest("la fontaine").results.first?.name == "Parc La Fontaine")343        #expect(try await engine.suggest("parc lafontaine").results.first?.name == "Parc La Fontaine")344        #expect(try await engine.suggest("café", limit: 2).results.count == 2)345    }346347    @Test func coordinatesNeedNoIndex() async throws {348        let empty = SearchEngine()349        let r = try await empty.search(SearchQuery(text: "45.5017, -73.5673"))350        #expect(r.results.count == 1)351        #expect(r.results[0].kind == .coordinate)352        #expect(r.results[0].coordinate == Coordinate(latitude: 45.5017, longitude: -73.5673))353        #expect(r.regionIDs.isEmpty)354        #expect(try await empty.search(SearchQuery(text: "Montréal")).results.isEmpty)355        #expect(try await empty.reverseGeocode(Fixture.downtown) == .nothingWithin(meters: 150))356        // With an index, the coordinate still comes first.357        let engine = try await Fixture.montrealEngine()358        let first = try await engine.search(SearchQuery(text: "45°30'06\"N 73°34'02\"W", focus: Fixture.downtown)).results.first359        #expect(first?.kind == .coordinate)360        #expect(first?.distance != nil)361    }362363    @Test func reverseGeocoding() async throws {364        let engine = try await Fixture.montrealEngine()365        // 11 m north of the address node "1000", 33 m from the street line.366        let c = Coordinate(latitude: 45.5032, longitude: -73.5760)367        guard case .found(let r) = try await engine.reverseGeocode(c, maxDistance: 150) else { Issue.record("expected a result"); return }368        let address = try #require(r.address)369        #expect(address.kind == .address)370        #expect(address.result.name == "1000 Rue Sherbrooke Ouest")371        #expect(address.result.kind == .address)372        #expect(address.result.osm == OSMElementRef(type: .node, id: 1000))373        #expect(abs(address.distance - 11.1) < 1)374        let street = try #require(r.street)375        #expect(street.result.name == "Rue Sherbrooke Ouest")376        #expect(street.result.city == "Montréal")377        #expect(abs(street.distance - 22.2) < 1.5)378        let place = try #require(r.place)379        #expect(place.result.name == "Café Olimpico")380        #expect(place.distance < 70)381        #expect(r.nearest?.kind == .address)382        #expect(r.maxDistance == 150)383384        // In the middle of the motorway: a street, no address within 150 m.385        guard case .found(let m) = try await engine.reverseGeocode(Coordinate(latitude: 45.5401, longitude: -73.6500)) else { Issue.record("expected a result"); return }386        #expect(m.street?.result.name == "Autoroute Métropolitaine")387        #expect(m.street?.result.roadRef == "40")388        #expect(m.address == nil)389        #expect(m.place == nil)390        // A street known only from addresses is found through its address.391        guard case .found(let f) = try await engine.reverseGeocode(Coordinate(latitude: 45.53005, longitude: -73.6200), maxDistance: 50) else { Issue.record("expected a result"); return }392        #expect(f.address?.result.name == "12 Rue Fictive-du-Test")393        #expect(f.street == nil)394        // Nowhere: an explicit "nothing", not the nearest thing 40 km away.395        #expect(try await engine.reverseGeocode(Coordinate(latitude: 45.90, longitude: -73.00), maxDistance: 300) == .nothingWithin(meters: 300))396        #expect(try await engine.reverseGeocode(Coordinate(latitude: .nan, longitude: 0)) == .nothingWithin(meters: 150))397        // The radius is honoured: 33 m from the street line, asking for 10 m.398        #expect(try await engine.reverseGeocode(Coordinate(latitude: 45.5033, longitude: -73.5840), maxDistance: 10) == .nothingWithin(meters: 10))399    }400401    @Test func extentCoversStreetsNotOnlyTheirMiddle() async throws {402        // No bounding box given: the recorded extent must contain the ends of the streets, or reverse geocoding near an403        // edge of the region would skip the index.404        let url = Fixture.temporaryURL()405        let w = try SearchIndexWriter(url: url, regionID: "edge")406        let line = [Coordinate(latitude: 45.0, longitude: -73.10), Coordinate(latitude: 45.0, longitude: -73.00)]407        w.add(StreetRecord(osm: Fixture.way(1), names: NameSet(primary: "Rue Longue"), streetClass: .residential, geometry: [line],408                           coordinate: Coordinate(latitude: 45.0, longitude: -73.05)))409        _ = try w.finish(dataTimestamp: nil)410        let engine = SearchEngine()411        let info = try await engine.openIndex(at: url)412        #expect(info.boundingBox?.minLon == -73.10 && info.boundingBox?.maxLon == -73.00)413        guard case .found(let r) = try await engine.reverseGeocode(Coordinate(latitude: 45.0001, longitude: -73.0995)) else { Issue.record("expected the street"); return }414        #expect(r.street?.result.name == "Rue Longue")415    }416417    @Test func pointsOfInterestInABox() async throws {418        let engine = try await Fixture.montrealEngine()419        let small = BoundingBox(minLat: 45.500, minLon: -73.580, maxLat: 45.508, maxLon: -73.565)420        let all = try await engine.pointsOfInterest(in: small)421        #expect(Set(all.map(\.name)) == ["Café Olimpico", "Dispatch Coffee", "SAQ", "", "Pharmaprix", "Pharmacie Jean Coutu", "Les 3 Brasseurs", "Université McGill"])422        #expect(all.first?.name == "Université McGill") // most important first423        #expect(try await engine.pointsOfInterest(in: small, categories: [.cafe]).map(\.name).sorted() == ["Café Olimpico", "Dispatch Coffee"])424        #expect(try await engine.pointsOfInterest(in: small, limit: 3).count == 3)425        // A box too large for the grid goes through the full-text index and gives the same kind of answer.426        let large = BoundingBox(minLat: 45.40, minLon: -73.98, maxLat: 45.71, maxLon: -73.47)427        #expect(try await engine.pointsOfInterest(in: large, categories: [.cafe]).count == 4)428    }429430    @Test func multipleRegionsMergeAndClose() async throws {431        let (engine, urls) = try await Fixture.engine({ try Fixture.buildMontreal(at: $0) }, { try Fixture.buildQuebec(at: $0) })432        #expect(await engine.openIndexes.map(\.regionID) == ["test-montreal", "test-quebec"])433        let frontenac = try #require(try await engine.search(SearchQuery(text: "Château Frontenac")).results.first)434        #expect(frontenac.regionID == "test-quebec")435        #expect(frontenac.category == .lodging)436        #expect(frontenac.dataDate == Fixture.dataDate.addingTimeInterval(86_400))437        #expect(frontenac.secondaryLine == "1 Rue des Carrières, Québec")438        // The city present in both regions appears once, from the most recent data.439        let montreal = try await engine.search(SearchQuery(text: "Montréal")).results.filter { $0.kind == .place && $0.name == "Montréal" }440        #expect(montreal.count == 1)441        #expect(montreal.first?.regionID == "test-quebec")442        // Category near Québec comes from the Québec index, nearest first.443        let pharmacies = try await engine.search(SearchQuery(text: "pharmacie", focus: Fixture.oldQuebec, limit: 3))444        #expect(pharmacies.results.first?.name == "Pharmacie Brunet")445        #expect(pharmacies.regionIDs == ["test-montreal", "test-quebec"])446        guard case .found(let r) = try await engine.reverseGeocode(Coordinate(latitude: 46.8119, longitude: -71.2053)) else { Issue.record("expected a result"); return }447        #expect(r.address?.result.name == "1 Rue des Carrières")448        #expect(r.address?.result.regionID == "test-quebec")449        #expect(r.place?.result.name == "Fairmont Le Château Frontenac")450        // Opening the same region twice is refused; closing removes its results.451        await #expect(throws: SearchIndexError.regionAlreadyOpen("test-quebec")) { try await engine.openIndex(at: urls[1]) }452        #expect(await engine.closeIndex(regionID: "test-quebec"))453        #expect(await engine.closeIndex(regionID: "test-quebec") == false)454        #expect(try await engine.search(SearchQuery(text: "Château Frontenac")).results.isEmpty)455        #expect(try await engine.search(SearchQuery(text: "Montréal")).results.first?.regionID == "test-montreal")456        // The file of a closed region can be replaced and reopened.457        try Fixture.buildQuebec(at: urls[1], dataDate: nil)458        let info = try await engine.openIndex(at: urls[1])459        #expect(info.dataDate == nil)460        #expect(try await engine.search(SearchQuery(text: "Château Frontenac")).results.first?.dataDate == nil)461        await engine.closeAll()462        #expect(await engine.openIndexes.isEmpty)463    }464465    @Test func resultsAreCodable() async throws {466        let engine = try await Fixture.montrealEngine()467        let response = try await engine.search(SearchQuery(text: "1000 rue Sherbrooke Ouest", focus: Fixture.downtown))468        let data = try JSONEncoder().encode(response)469        let decoded = try JSONDecoder().decode(SearchResponse.self, from: data)470        #expect(decoded.results == response.results)471        #expect(decoded.parsed == response.parsed)472        let query = SearchQuery(text: "café", mode: .suggest, focus: Fixture.downtown, limit: 5, categories: [.cafe])473        #expect(try JSONDecoder().decode(SearchQuery.self, from: JSONEncoder().encode(query)) == query)474        if case .found(let r) = try await engine.reverseGeocode(Fixture.downtown) {475            #expect(try JSONDecoder().decode(ReverseGeocodeResult.self, from: JSONEncoder().encode(r)) == r)476        }477    }478}479
Files main
Menu

Theme