SPB Git

Repository Public

V3Tests.swift 31.2 KB 528 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Immo-Ka iOS9// File             : ImmoKaTests/V3Tests.swift10// Description      : API v3 sur des réponses réelles de la production du11//                    2026-11-28 — recherche à curseur, carte par emprise,12//                    phrase libre, fiche, prix de vente attendu, comparables,13//                    coût de possession, marché, quartier ; contrat HTTP (ETag,14//                    304, 410, 429, erreurs structurées) ; regroupements ;15//                    liens universels.16// Module           : ImmoKaTests17// Repository       : https://git.spboucher.ai/immo-ka-ios-v318// Project Website  : https://www.immo-ka.com19// Created          : 2026-11-2820// Last Modified    : 2026-11-3021//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import Testing96@testable import ImmoKa9798private final class V3BundleToken {}99100private func fixture(_ name: String) throws -> Data {101    let url = try #require(Bundle(for: V3BundleToken.self).url(forResource: name, withExtension: "json"), "échantillon \(name).json absent du lot de tests")102    return try Data(contentsOf: url)103}104105private func decode<T: Decodable>(_ type: T.Type, _ name: String) throws -> T {106    try JSONDecoder().decode(T.self, from: fixture(name))107}108109@Suite("API v3 : décodage des réponses réelles")110struct V3DecodingTests {111    @Test("version : api 3, index daté")112    func version() throws {113        let v = try decode(V3Version.self, "v3-version")114        #expect(v.api == 3 && v.version == "3.0.0" && (v.listings ?? 0) > 10_000 && v.builtAt != nil)115        // aller-retour par les réglages (hors ligne)116        let back = try JSONDecoder().decode(V3Version.self, from: JSONEncoder().encode(v))117        #expect(back == v)118    }119120    @Test("recherche : résultats v3, curseur, critères appliqués")121    func search() throws {122        let r = try decode(V3SearchResponse.self, "v3-search")123        #expect(r.total > 1000 && r.items.count == 3 && r.nextCursor != nil)124        #expect(r.interpreted["city"] == "Gatineau")125        let l = try #require(r.items.first)126        #expect(l.isV3 && l.uid == "sutton:23170275" && l.propertyType == "Maison" && l.family == "unifamiliale")127        #expect(l.plausiblePrice == 400_000 && l.bedrooms == 4 && l.yearBuilt == 1974 && l.images.count == 1)128        // attributs à trois états : oui, non, et l'absence qui veut dire inconnu129        #expect(l.flags["parking"] == true && l.flags["basement"] == false && l.flags["pool"] == nil)130        // prix de vente attendu et position : ceux du modèle v3, jamais l'ancien verdict131        let e = try #require(l.estimate)132        #expect(e.value == 523_300 && e.low == 391_500 && e.high == 595_400 && e.level == 0.8 && e.position == .marche)133        #expect(e.levelLabel == "8 ventes sur 10")134        #expect(l.verdict == .marche && abs((l.deviation ?? 0) + 0.236) < 1e-9)135        #expect(l.expected?.value == 523_300 && l.vraiprix == nil)136        #expect(l.daysObserved == 0 && !l.marketCensored && l.taxTotal == 4007 && l.dupSources.count == 2)137        #expect(l.statusLabel == nil, "« a-vendre » n'est pas un statut à signaler")138    }139140    @Test("fiche v3 : description, photos, historique, statut")141    func listing() throws {142        let l = try decode(Listing.self, "v3-listing")143        #expect(l.isV3 && l.uid == "remax_quebec:9985160" && l.images.count == 4 && !l.description.isEmpty)144        #expect(l.status == "a-vendre" && l.priceHistory.count == 1 && l.garageSpaces == 1 && l.parkingSpaces == 5)145        #expect(l.estimate?.position == .marche && l.estimate?.confidence == "moyenne")146        #expect(l.details.rows.contains { $0.label == "Mode de chauffage" })147        #expect(l.coordinate != nil)148    }149150    @Test("la fiche v2 est complétée par la v3, qui fait foi pour l'estimation")151    func merge() throws {152        ServiceGeneration.pin(2)153        defer { ServiceGeneration.pin(nil) }154        let v2 = try decode(Listing.self, "v2-listing")155        let v3 = try decode(Listing.self, "v3-listing")156        let m = v2.merging(v3: v3)157        #expect(m.uid == v2.uid && m.isV3)158        #expect(m.estimate == v3.estimate && m.verdict == v3.verdict)159        #expect(m.expected?.value == v3.estimate?.value)160        // ce que seule la v2 sert reste : quartier, points d'intérêt, données du rôle161        #expect(m.quartier == v2.quartier && m.poi.count == v2.poi.count && m.vraiprix?.valeurRole == v2.vraiprix?.valeurRole)162        // une fiche v3 sans estimation n'en montre aucune, même si la v2 en portait une163        var bare = v3; bare.estimate = nil164        let n = v2.merging(v3: bare)165        #expect(n.expected == nil && n.verdict == nil)166    }167168    @Test("service v3 : une inscription lue par une route v2 ne montre pas l'ancien verdict")169    func legacyVerdictHidden() throws {170        ServiceGeneration.pin(3)171        defer { ServiceGeneration.pin(nil) }172        let v2 = try decode(Listing.self, "v2-listing")173        #expect(!v2.isV3 && v2.verdict == nil && v2.expected == nil)174    }175176    @Test("carte : points sous le seuil, regroupements du serveur au-delà")177    func map() throws {178        let p = try decode(V3MapResponse.self, "v3-map-points")179        #expect(!p.isClustered && p.points.count == 40 && p.clusters.isEmpty && p.total > 40)180        #expect(p.points.allSatisfy { !$0.uid.isEmpty && abs($0.lat) <= 90 })181        let c = try decode(V3MapResponse.self, "v3-map-clusters")182        #expect(c.isClustered && c.points.isEmpty && c.clusters.count > 50)183        #expect(c.clusters.reduce(0) { $0 + $1.count } == c.total, "les regroupements portent toutes les inscriptions")184    }185186    @Test("phrase libre : critères compris, fragments d'origine")187    func parse() throws {188        let p = try decode(V3Parse.self, "v3-parse")189        #expect(p.params["city"] == "Gatineau" && p.params["price_max"] == "500000" && p.params["bedrooms_min"] == "3")190        #expect(p.params["with"] == "garage" && p.params["family"] == "unifamiliale")191        #expect(p.interpreted.count == 5 && p.interpreted.contains { $0.label == "Au plus 500 000 $" } && p.rest.isEmpty)192        let s = try decode(ItemsEnvelope<PlaceSuggestion>.self, "v3-suggest")193        #expect(s.items.first?.name == "Gatineau" && s.items.first?.kind == "municipalite" && s.items.first?.kindLabel == "Ville")194    }195196    @Test("prix de vente attendu : trois grandeurs, facteurs, limites")197    func valuation() throws {198        let v = try decode(Valuation.self, "v3-valuation")199        let e = try #require(v.expected)200        #expect(e.value == 334_700 && e.low == 230_600 && e.high == 395_000 && e.level == 0.8)201        let p = try #require(v.probable)202        #expect(p.value == 254_400 && v.saleToAskRatio == 0.979 && v.pairs == 9513)203        #expect(v.position == .marche && v.gapPct == -22.3 && v.positionText != nil && v.positionAbsentReasons.isEmpty)204        #expect(v.confidence == "moyenne" && v.salesWithin1km == 53 && v.rollValue == 297_600)205        // la référence plus la somme des effets donne le prix de vente attendu (à l'arrondi du service près)206        #expect(v.effects.count == 5)207        let sum = (v.reference ?? 0) + v.effects.reduce(0) { $0 + $1.effect }208        #expect(abs(sum - e.value) <= 200)209        #expect(v.limits.count >= 5 && v.modelVersion?.hasPrefix("v3-") == true && v.salesUntil == "2026-07-27")210    }211212    @Test("comparables : ventes réelles et inscriptions actives, jamais mélangées")213    func comparables() throws {214        let c = try decode(Comparables.self, "v3-comparables")215        #expect(c.sold.count == 8 && c.active.count == 8)216        let s = try #require(c.sold.first)217        #expect(s.address == "384, rue Charles" && s.salePrice == 220_000 && s.adjustedPrice == 229_100 && s.saleDate == "2026-01-12")218        #expect(s.comparability == "élevée" && !s.sameProperty)219        #expect(c.active.allSatisfy { !$0.uid.isEmpty } && c.active.first?.askPrice == 259_900)220        #expect(c.soldNature?.contains("VENTE") == true && c.activeNature?.contains("DEMANDÉS") == true)221    }222223    @Test("coût de possession : postes, provenance, inconnu jamais additionné")224    func ownership() throws {225        let o = try decode(Ownership.self, "v3-ownership")226        #expect(o.applicable && o.rate == 5.14 && o.downPct == 20 && o.amortization == 25 && o.insured == false)227        let m = try #require(o.monthly)228        #expect(m.amount == 1732.98 && m.atLeast && m.notCounted == ["Entretien"])229        #expect(o.monthlyLines.map(\.key) == ["mortgage", "municipal_tax", "school_tax", "insurance", "energy", "maintenance"])230        #expect(o.monthlyLines.map(\.status) == [.estime, .observe, .observe, .hypothese, .estime, .hypothese])231        // l'entretien est inconnu : nul, et le total est la somme des seuls postes connus232        let known = o.monthlyLines.compactMap(\.amount).reduce(0, +)233        #expect(o.monthlyLines.last?.amount == nil && abs(known - m.amount) < 0.01)234        let c = try #require(o.cash)235        #expect(c.amount == 56_764.5 && o.purchaseLines.count == 5 && o.purchaseLines.first?.key == "down_payment")236        #expect(o.stressRate == 7.14 && o.ratesObserved == 23)237        #expect(Provenance(code: "n'importe quoi") == .inconnu)238    }239240    @Test("marché : prix demandés, flux, ventes réelles, indice ou sa raison d'absence")241    func market() throws {242        let m = try decode(MarketPortrait.self, "v3-market")243        #expect(m.place.name == "Gatineau" && m.place.kind == "municipalite" && m.place.parentName == "Outaouais")244        #expect(m.inventory == 1912 && m.askMedian == 469_250 && m.new30d == 469 && m.askP25 == 349_900 && m.askP75 == 609_900)245        #expect(m.flowNew.current == 111 && m.flowNew.previous == 145 && m.flowWithdrawn.current == 218)246        #expect(m.lastSale == "2026-07-27" && m.sales.first?.median == 485_000 && m.sales.first?.n == 3696)247        #expect(m.bands.count == 6 && m.bands.first?.label.hasPrefix("moins de") == true)248        // l'indice est publié pour l'unifamiliale, refusé pour le condo avec sa raison249        let uni = try #require(m.index.first { $0.family == "unifamiliale" })250        let condo = try #require(m.index.first { $0.family == "condo" })251        #expect(uni.value == 159.04 && uni.yoyPct == 3.12 && condo.value == nil && condo.reason?.contains("effectif insuffisant") == true)252        #expect(m.definitions["n_withdrawn"]?.contains("PAS une vente") == true)253        let idx = try decode(MarketSeries.self, "v3-indices")254        #expect(idx.published && idx.points.count == 23 && idx.points.first?.value == 100 && idx.points.last?.low != nil)255        let sales = try decode(MarketSeries.self, "v3-sales")256        #expect(sales.points.count == 23 && sales.points.first?.value == 320_000 && sales.lastSale == "2026-07-27")257    }258259    @Test("quartier : marché, parc, services, transport ; ni score ni classement")260    func neighborhood() throws {261        let p = try decode(NeighborhoodPortrait.self, "v3-neighborhood")262        #expect(p.place.name == "Gatineau" && p.bbox.count == 4 && p.lat != nil)263        #expect(p.ask?.n == 1912 && p.ask?.p50 == 469_500 && p.askGapMedianPct == 1.7)264        #expect(p.medianYear == 1989 && p.ageBands.count == 7 && abs(p.ageBands.reduce(0) { $0 + $1.share } - 1) < 0.01)265        #expect(p.taxPer100k == 792 && p.taxStatus == "estimé" && p.services.count >= 8)266        #expect(p.services.allSatisfy { $0.percentile >= 0 && $0.percentile <= 100 })267        // limite connue : les stations de l'O-Train sont à Ottawa ; l'app porte la précision du service268        let otrain = try #require(p.transit.first { $0.key == "otrain" })269        #expect(otrain.count == 21 && otrain.many == "stations de l'O-Train" && p.transitNote?.contains("Ottawa") == true)270        #expect(p.transit.first?.key == "bus" && p.transit.first?.text.hasSuffix("arrêts d'autobus") == true)271        #expect(p.floodChecked == 1930 && !p.neighbors.isEmpty && p.sales.count == 4)272        let list = try decode(ItemsEnvelope<NeighborhoodEntry>.self, "v3-neighborhoods")273        #expect(list.items.first?.name == "Aylmer" && list.items.first?.parentSlug == "gatineau" && list.items.first?.kind == "secteur")274    }275276    @Test("même propriété ailleurs et courtiers")277    func linksAndBrokers() throws {278        let l = try decode(ListingLinks.self, "v3-links")279        #expect(l.same.count == 1 && l.same.first?.merged == true && l.same.first?.explanation.first?.contains("Centris") == true)280        #expect(l.agencyName == "Re/Max Vision" && l.banner == "RE/MAX" && l.agencyID != nil)281        let b = try decode(ItemsEnvelope<BrokerEntry>.self, "v3-brokers")282        #expect(b.items.count == 2 && b.total == 52 && b.nextOffset == 2)283        #expect(b.items.first?.name == "Tremblay Carl" && b.items.first?.agencyName == "Via Capitale Elite" && b.items.first?.regions.isEmpty == false)284    }285}286287@Suite("API v3 : contrat HTTP")288struct V3ContractTests {289    @Test("200 : le corps ; 304 : la copie locale ; 304 sans copie : erreur")290    func cache() throws {291        let body = Data("{\"a\":1}".utf8), cached = Data("{\"a\":0}".utf8)292        #expect(try APIClient.interpretV3(status: 200, data: body, headers: [:], cached: cached) == body)293        #expect(try APIClient.interpretV3(status: 304, data: Data(), headers: [:], cached: cached) == cached)294        #expect(throws: APIError.self) { try APIClient.interpretV3(status: 304, data: Data(), headers: [:], cached: nil) }295    }296297    @Test("inscription regroupée : 404 duplicate et en-tête Location nomment la fiche gardée")298    func regrouped() throws {299        let dup = Data(#"{"error":{"code":"duplicate","message":"Inscription regroupée avec une autre","request_id":"r"}}"#.utf8)300        #expect { try APIClient.interpretV3(status: 404, data: dup, headers: ["location": "/api/v3/listings/remax_quebec:20045919"], cached: nil) } throws: { e in301            if case APIError.regrouped(let uid) = e { return uid == "remax_quebec:20045919" }302            return false303        }304        // sans en-tête Location : une fiche introuvable comme une autre305        #expect { try APIClient.interpretV3(status: 404, data: dup, headers: [:], cached: nil) } throws: { e in306            if case APIError.notFound = e { return true }307            return false308        }309        #expect(APIClient.regroupedUID(headers: ["Location": "/api/v3/listings/a%3Ab%2Fc"]) == "a:b/c" && APIClient.regroupedUID(headers: ["Location": "/ailleurs"]) == nil)310    }311312    @Test("erreurs structurées : 404, 422 avec paramètre, 429 avec délai, 410 avec ce qui reste de l'inscription")313    func errors() throws {314        let nf = try fixture("v3-not-found")315        #expect { try APIClient.interpretV3(status: 404, data: nf, headers: [:], cached: nil) } throws: { e in316            if case APIError.notFound = e { return true }; return false317        }318        let bad = Data(#"{"error":{"code":"invalid_parameter","message":"Zoom hors bornes","param":"zoom","request_id":"abc"}}"#.utf8)319        #expect { try APIClient.interpretV3(status: 422, data: bad, headers: [:], cached: nil) } throws: { e in320            guard case APIError.server(let b, let status) = e else { return false }321            return status == 422 && b.code == "invalid_parameter" && b.param == "zoom" && b.requestID == "abc"322                && (e as? LocalizedError)?.errorDescription == "Zoom hors bornes"323        }324        #expect { try APIClient.interpretV3(status: 429, data: Data(), headers: ["Retry-After": "12"], cached: nil) } throws: { e in325            if case APIError.rateLimited(let s) = e { return s == 12 }; return false326        }327        // forme du 410 servie par `immoka/v3/api.py` (_gone)328        let gone = Data(#"{"error":{"code":"gone","message":"Cette inscription n'est plus affichée par sa source.","request_id":"r1"},"listing":{"uid":"x:1","title":"12 Rue des Pins","city":"Gatineau","type":"Maison","last_seen":1795000000,"status":"vendu","status_observed_at":1794990000}}"#.utf8)329        #expect { try APIClient.interpretV3(status: 410, data: gone, headers: [:], cached: nil) } throws: { e in330            guard case APIError.goneListing(let g) = e else { return false }331            return g.uid == "x:1" && g.city == "Gatineau" && g.status == "vendu" && g.sentence.contains("vendue")332        }333        // disparue sans statut : ce n'est pas une vente, et l'app le dit334        let g = GoneListing(uid: "x:2", title: "8 Rue A")335        #expect(g.sentence.contains("ne veut pas dire qu'elle est vendue"))336        // 500 sans corps structuré337        #expect { try APIClient.interpretV3(status: 500, data: Data("oups".utf8), headers: [:], cached: nil) } throws: { e in338            if case APIError.http(500) = e { return true }; return false339        }340    }341342    @Test("ETag gardé à côté de la réponse, effacé avec elle")343    func etagStore() {344        let u = URL(string: "https://exemple.test/api/v3/essai?x=\(UUID().uuidString)")!345        #expect(ResponseCache.etag(u) == nil)346        ResponseCache.write(u, Data("{}".utf8), etag: "W/\"abc\"")347        #expect(ResponseCache.etag(u) == "W/\"abc\"" && ResponseCache.read(u) == Data("{}".utf8))348        // la clé ne dépend pas de l'hôte : production et repli partagent leurs copies349        let other = URL(string: "https://autre.test" + u.path + "?" + (u.query ?? ""))!350        #expect(ResponseCache.etag(other) == "W/\"abc\"")351        ResponseCache.write(u, Data("{}".utf8), etag: nil)352        #expect(ResponseCache.etag(u) == nil)353    }354355    @Test("filtres → paramètres de la v3")356    func filters() {357        var f = SearchFilters()358        f.city = "Gatineau"; f.sector = "Aylmer"; f.propertyType = "Maison"; f.priceMax = 500_000; f.bedroomsMin = 3359        f.deal = .marche; f.with = ["pool", "garage"]; f.priceDrop = true; f.newDays = 7; f.taxMax = 5000; f.broker = "Tremblay"360        let q = f.queryV3.compactMapValues { $0 }361        #expect(q == ["city": "Gatineau", "area": "Aylmer", "type": "Maison", "price_max": "500000", "bedrooms_min": "3",362                      "position": "dans", "with": "garage,pool", "price_drop": "1", "new_days": "7", "tax_max": "5000", "broker": "Tremblay"])363        #expect(f.activeCount == 10, "type, prix, chambres, position, quartier, baisse, nouveautés, taxes, et deux attributs")364        var nl = SearchFilters(); nl.nl = "maison au bord de l'eau"365        #expect(nl.queryV3.compactMapValues { $0 } == ["nl": "maison au bord de l'eau"] && nl.hasPlace && nl.summary == "« maison au bord de l'eau »")366        // tris : dix en v3, ramenés aux cinq de la v2 en repli367        #expect(SearchSort.deal.v3 == "ecart" && SearchSort.baisse.v3 == "baisse" && SearchSort.pertinence.v2 == "recent" && SearchSort.pi2.v1 == "price_asc")368        // une recherche enregistrée par la 2.0.0 se relit (les champs de la v3 sont absents)369        let old = Data(#"{"city":"Laval","priceMax":400000,"deal":"sous"}"#.utf8)370        let back = try? JSONDecoder().decode(SearchFilters.self, from: old)371        #expect(back?.city == "Laval" && back?.deal == .sous && back?.with == nil && back?.nl == nil)372    }373374    @Test("zoom de la carte déduit de l'emprise")375    @MainActor376    func zoom() {377        let world = ExploreModel.zoom(for: MapBounds(west: -180, south: -80, east: 180, north: 80), width: 256)378        #expect(abs(world - 2) < 1e-9, "borne basse")379        let city = ExploreModel.zoom(for: MapBounds(west: -75.9, south: 45.35, east: -75.5, north: 45.6), width: 402)380        #expect(city > 10 && city < 11)381        #expect(ExploreModel.zoom(for: MapBounds(west: 0, south: 0, east: 0, north: 0), width: 400) == 20)382    }383}384385@Suite("Regroupements du serveur")386struct ServerClusterTests {387    @Test("fusion : aucune inscription perdue ni inventée, borne d'éléments, prix minimal gardé")388    func merge() throws {389        let r = try decode(V3MapResponse.self, "v3-map-clusters")390        let all = MapBounds(west: -81, south: 44, east: -56, north: 63)391        let items = Clusterer.merge(r.clusters, in: all, columns: 5, aspect: 1.8)392        #expect(!items.isEmpty && items.count <= 160 && items.count < r.clusters.count)393        #expect(items.reduce(0) { $0 + $1.count } == r.total)394        #expect(Set(items.map(\.id)).count == items.count)395        let mins = r.clusters.compactMap(\.minPrice).filter { Listing.priceIsPlausible($0) }396        let kept = items.compactMap { i -> Double? in if case .cluster(_, _, let m) = i.kind { return m }; return nil }397        #expect(kept.min() == mins.min())398        // hors de la zone visible : rien399        #expect(Clusterer.merge(r.clusters, in: MapBounds(west: 0, south: 0, east: 1, north: 1)).isEmpty)400    }401402    @Test("zone à cadrer : pondérée par les effectifs, sans les marges")403    func bounds() throws {404        let r = try decode(V3MapResponse.self, "v3-map-clusters")405        let b = try #require(Clusterer.robustBounds(points: [], clusters: r.clusters))406        #expect(b.west < b.east && b.south < b.north && b.west > -80.5 && b.north < 52)407        #expect(Clusterer.robustBounds(points: [], clusters: []) == nil)408        let one = [ServerCluster(lng: -73.5, lat: 45.5, count: 10)]409        let single = try #require(Clusterer.robustBounds(points: [], clusters: one))410        #expect(single.west == -73.5 && single.east == -73.5)411    }412}413414@Suite("Liens universels et liens profonds")415struct LinkTests {416    @MainActor417    private func route(_ url: String) -> (AppTab, Int) {418        UserDefaults.standard.removeObject(forKey: "IKTab")419        let m = AppModel()420        m.tab = .discover421        m.handle(url: URL(string: url)!)422        return (m.tab, m.paths[m.tab]?.count ?? 0)423    }424425    @Test("adresses du site v3 : fiche, ville, quartier, marché, taux, comparateur")426    @MainActor427    func universal() {428        #expect(route("https://www.immo-ka.com/propriete/remax_quebec:9985160/147-rue-jean-xxiii-gatineau") == (.discover, 1))429        #expect(route("https://www.immo-ka.com/propriete/remax_quebec%3A9985160") == (.discover, 1))430        #expect(route("https://www.immo-ka.com/a-vendre/gatineau") == (.discover, 1))431        #expect(route("https://www.immo-ka.com/a-vendre/trois-rivieres/condo") == (.discover, 1))432        #expect(route("https://www.immo-ka.com/quartier/gatineau/aylmer") == (.market, 1))433        #expect(route("https://www.immo-ka.com/quartier/gatineau") == (.market, 1))434        #expect(route("https://www.immo-ka.com/marche") == (.market, 0))435        #expect(route("https://www.immo-ka.com/taux") == (.market, 1))436        #expect(route("https://www.immo-ka.com/comparer") == (.favorites, 1))437        #expect(route("https://www.immo-ka.com/recherche?city=Laval") == (.explore, 0))438        #expect(route("https://www.immo-ka.com/agences") == (.pros, 0))439        #expect(route("https://www.immo-ka.com/vrai-prix") == (.market, 1))440        // adresse inconnue : rien ne bouge441        #expect(route("https://www.immo-ka.com/ops") == (.discover, 0))442    }443444    @Test("schéma immoka:// de la 2.0.0, toujours compris")445    @MainActor446    func scheme() {447        #expect(route("immoka://propriete/remax_quebec:9985160") == (.discover, 1))448        #expect(route("immoka://ville/Gatineau") == (.discover, 1))449        #expect(route("immoka://taux") == (.market, 1))450    }451452    @Test("l'identifiant du lien universel est le premier segment, la suite est décorative")453    @MainActor454    func uidSegment() {455        let m = AppModel()456        m.handle(url: URL(string: "https://www.immo-ka.com/propriete/duproprio:1234/belle-maison-a-vendre")!)457        #expect(m.paths[m.tab]?.count == 1)458        #expect(AppModel.listingUID(from: URL(string: "https://www.immo-ka.com/propriete/duproprio:1234/belle-maison")!) == "duproprio:1234")459        #expect(AppModel.listingUID(from: URL(string: "immoka://propriete/x:9")!) == "x:9")460        #expect(AppModel.listingUID(from: URL(string: "https://www.immo-ka.com/marche")!) == nil)461    }462}463464@Suite("Fonctions système : Spotlight, raccourcis, widgets")465struct SystemTests {466    @Test("Spotlight : identifiants et contenu d'une propriété")467    func spotlight() {468        let id = Spotlight.identifier("remax_quebec:9985160", domain: Spotlight.favoritesDomain)469        #expect(id == "favoris|remax_quebec:9985160" && Spotlight.uid(from: id) == "remax_quebec:9985160")470        #expect(Spotlight.uid(from: "sans-séparateur") == nil && Spotlight.uid(from: "favoris|") == nil)471        let a = Spotlight.attributes(title: "147 Rue Jean-XXIII", city: "Gatineau", sector: "Buckingham", kind: "Maison", price: 259_900, facts: "Maison · 5 ch.")472        #expect(a.title == "147 Rue Jean-XXIII" && a.city == "Gatineau")473        #expect(a.contentDescription?.contains("demandés") == true && a.contentDescription?.contains("Buckingham, Gatineau") == true)474        // prix inconnu : pas de zéro, pas de montant475        let b = Spotlight.attributes(title: "Terrain", city: "", sector: "", kind: "", price: nil, facts: "")476        #expect(b.contentDescription == "" && b.city == nil)477    }478479    @Test("raccourci Siri : la réponse parle de prix demandés, et s'abstient sans données")480    func askingPrice() throws {481        let m = try decode(MarketPortrait.self, "v3-market")482        // les nombres portent des espaces insécables : on les ramène à des espaces pour comparer483        let s = AskingPriceIntent.sentence(m, asked: "gatineau").replacingOccurrences(of: "\u{00A0}", with: " ").replacingOccurrences(of: "\u{202F}", with: " ")484        #expect(s.hasPrefix("À Gatineau, le prix demandé médian est de 469 250 $"))485        #expect(s.contains("1 912 propriétés à vendre") && s.contains("ventes réelles") && s.contains("485 000 $"))486        let empty = try JSONDecoder().decode(MarketPortrait.self, from: Data(#"{"place":{"name":"Petite-Ville","kind":"municipalite","slug":"petite-ville"},"listings":{}}"#.utf8))487        #expect(AskingPriceIntent.sentence(empty, asked: "Petite-Ville").contains("pas assez de propriétés"))488    }489490    @Test("lien de recherche des raccourcis et des widgets")491    @MainActor492    func searchLink() {493        let u = DeepLinkInbox.searchURL(city: "Trois-Rivières", type: "Condo", priceMax: 400_000)494        #expect(u.scheme == "immoka" && u.host() == "recherche")495        let m = AppModel()496        m.tab = .discover497        m.handle(url: u)498        #expect(m.tab == .explore)499        #expect(m.pendingSearch?.filters.city == "Trois-Rivières" && m.pendingSearch?.filters.propertyType == "Condo" && m.pendingSearch?.filters.priceMax == 400_000)500        // sans critère : la carte, sans recherche imposée501        let n = AppModel(); n.handle(url: DeepLinkInbox.searchURL(city: nil, type: nil, priceMax: nil))502        #expect(n.tab == .explore && n.pendingSearch == nil)503        // widget « Marché local » : marché d'une ville504        let w = AppModel(); w.handle(url: URL(string: "immoka://marche/trois-rivieres")!)505        #expect(w.tab == .market && w.paths[.market]?.count == 1)506    }507508    @Test("widgets : décodage des réponses réelles, formats, identifiants de ville")509    func widgets() throws {510        let page = try WidgetAPI.decodeSearch(try fixture("v3-search"))511        #expect(page.total ?? 0 > 1000 && page.items.count == 3)512        let l = try #require(page.items.first)513        #expect(l.uid == "sutton:23170275" && l.price == 400_000 && l.type == "Maison" && l.city == "Gatineau")514        #expect(l.url.absoluteString == "immoka://propriete/sutton:23170275")515        #expect(AppModel.listingUID(from: l.url) == "sutton:23170275")516        let m = try WidgetAPI.decodeMarket(try fixture("v3-market"), slug: "gatineau")517        #expect(m.place == "Gatineau" && m.askMedian == 469_250 && m.inventory == 1912 && m.new30d == 469 && m.indexYoY == 3.12 && m.asOf == "2026-11-28")518        #expect(WidgetFormat.slug("Trois-Rivières") == "trois-rivieres" && WidgetFormat.slug("L'Ange-Gardien (Outaouais)") == "l-ange-gardien-outaouais")519        #expect(WidgetFormat.slug("Trois-Rivières") == Fmt.slug("Trois-Rivières"), "le widget et l'app nomment une ville de la même façon")520        #expect(WidgetFormat.money(469_250).replacingOccurrences(of: "\u{00A0}", with: " ").replacingOccurrences(of: "\u{202F}", with: " ") == "469 250 $")521        #expect(WidgetFormat.compact(1_250_000).hasSuffix("M$") && WidgetFormat.compact(425_000).hasPrefix("425"))522        #expect(WidgetFormat.shortDay("2026-11-28")?.hasPrefix("28") == true && WidgetFormat.shortDay("n'importe") == nil)523        // prix non plausible (loyer publié par erreur) : « sur demande », jamais un faux prix524        let odd = try JSONDecoder().decode(WidgetListing.self, from: Data(#"{"uid":"x:1","title":"Loft","price":1500}"#.utf8))525        #expect(odd.price == nil && odd.address == "Loft")526    }527}528
Files main
Menu

Theme