SPB Git

Repository Public

DecodingTests.swift 12.0 KB 274 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka iOS9// File             : LouKaTests/DecodingTests.swift10// Description      : décodage tolérant des réponses de l'API, sur des11//                    échantillons réels et des formes dégradées.12// Module           : LouKaTests13// Repository       : https://git.spboucher.ai/lou-ka-ios-v314// Project Website  : https://www.lou-ka.com15// Created          : 2026-11-2516// Last Modified    : 2026-11-2817//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing92@testable import LouKa9394private final class BundleToken {}9596private func fixture(_ name: String) throws -> Data {97    let url = try #require(Bundle(for: BundleToken.self).url(forResource: name, withExtension: "json"), "échantillon \(name).json absent du lot de tests")98    return try Data(contentsOf: url)99}100101private func decode<T: Decodable>(_ type: T.Type, _ json: String) throws -> T {102    try JSONDecoder().decode(T.self, from: Data(json.utf8))103}104105@Suite("Décodage des réponses de l'API")106struct DecodingTests {107    @Test("fiche complète (échantillon réel)")108    func listingDetail() throws {109        let l = try JSONDecoder().decode(Listing.self, from: fixture("listing"))110        #expect(l.uid == "mountbridge:bosco-1050-2-45")111        #expect(l.city == "Montréal")112        #expect(l.unitType == "4½")113        #expect(l.bedrooms == 2)114        #expect(l.details.inclusions["hot_water"] == true)115        #expect(l.details.parking?.available == true)116        #expect(l.details.priceFrom)117        #expect(l.digest?.enBref == "Eau chaude et wifi inclus.")118        #expect(l.coordinate != nil)119        #expect(l.active)120        // 329 $ est un loyer « à partir de » : plausible selon les bornes du serveur121        #expect(l.plausiblePrice == 329)122    }123124    @Test("recherche : annonces et points compacts")125    func search() throws {126        let r = try JSONDecoder().decode(SearchResponse.self, from: fixture("search"))127        #expect(r.total > 0)128        #expect(r.listings.count == 3)129        let pts = try #require(r.points)130        #expect(pts.count == 400)131        #expect(pts.allSatisfy { abs($0.lat) <= 90 && abs($0.lng) <= 180 })132        // dans une liste, digest et détails arrivent parfois encodés en chaîne : jamais d'échec133        #expect(r.listings.allSatisfy { !$0.uid.isEmpty })134    }135136    @Test("analyses de la fiche")137    func analyses() throws {138        let fv = try JSONDecoder().decode(FairValueDetail.self, from: fixture("fairvalue"))139        #expect(fv.fv == 2411)140        #expect(fv.low < fv.fv && fv.fv < fv.high)141        #expect(fv.histogram.count == 24)142        #expect(fv.verdict == nil)143144        let c = try JSONDecoder().decode(CoutReel.self, from: fixture("coutreel"))145        #expect(c.lignes.first?.poste == "Loyer affiché")146        #expect(c.postesInconnus.contains("Électricité"))147148        let h = try JSONDecoder().decode(Historique.self, from: fixture("historique"))149        #expect(h.joursEnLigne == 48)150        #expect(h.timeline.first?.prixAvant == 2578)151    }152153    @Test("gestionnaires : annuaire et fiche")154    func managers() throws {155        let d = try JSONDecoder().decode(ManagersDirectory.self, from: fixture("managers"))156        #expect(d.total > 300)157        #expect(d.managers.count == 3)158        #expect(d.managers.allSatisfy { !$0.name.isEmpty })159160        let p = try JSONDecoder().decode(ManagerProfile.self, from: fixture("manager"))161        #expect(p.nom == "Cogir Immobilier")162        #expect(p.distribution[1] == 32)163        #expect(p.themes.first?.name == "service client")164        #expect(p.recents.count > 1)165    }166167    @Test("stationnement : objet, nombre ou booléen")168    func parkingShapes() throws {169        let a = try decode(ListingDetails.self, #"{"parking": {"available": true, "price": 120, "included": false}}"#)170        #expect(a.parking?.price == 120)171        let b = try decode(ListingDetails.self, #"{"parking": 2}"#)172        #expect(b.parking?.available == true)173        let c = try decode(ListingDetails.self, #"{"parking": false}"#)174        #expect(c.parking == nil)175        let d = try decode(ListingDetails.self, #"{"parking": true, "inclusions": {"heating": 1, "internet": "non"}}"#)176        #expect(d.parking?.available == true)177        #expect(d.inclusions == ["heating": true, "internet": false])178    }179180    @Test("annonce minimale et champs mal typés")181    func degradedListing() throws {182        let l = try decode(Listing.self, #"""183        {"uid": "x:1", "price": "1 250", "area_sqft": "800", "active": 0, "furnished": "oui",184         "images": "[\"https://a/b.jpg\", 3, \"data:zzz\"]", "amenities": null, "city": "Gatineau )",185         "details": "{\"ac\": 1}", "digest": "{\"en_bref\": \"Calme\", \"sections\": []}",186         "fv_verdict": "inconnu", "lat": "45.4", "lng": -75.7, "bedrooms": null}187        """#)188        #expect(l.price == nil)            // « 1 250 » avec espace : illisible, donc prix sur demande189        #expect(l.areaSqft == 800)190        #expect(!l.active)191        #expect(l.furnished == true)192        #expect(l.images == ["https://a/b.jpg"])193        #expect(l.cleanCity == "Gatineau")194        #expect(l.details.ac == true)195        #expect(l.digest?.enBref == "Calme")196        #expect(l.fvVerdict == nil)197        #expect(l.coordinate != nil)198        #expect(l.displayTitle == "Logement à louer")199    }200201    @Test("une annonce sans uid est écartée sans faire échouer la liste")202    func lossyList() throws {203        let r = try decode(SearchResponse.self, #"{"total": 2, "page": 1, "page_size": 20, "listings": [{"title": "sans uid"}, {"uid": "ok:1"}], "points": [["a", -73.5, 45.5, null, "s"], ["b", -73.6, 45.6, 1500, null], ["cassé"]], "unpositioned": 0}"#)204        #expect(r.listings.map(\.uid) == ["ok:1"])205        #expect(r.points?.count == 2)206        #expect(r.points?.first?.verdict == .sous)207        #expect(r.points?.first?.price == nil)208        #expect(r.points?.last?.price == 1500)209    }210211    @Test("lumières et version")212    func lights() throws {213        let l = try decode(LightsResponse.self, #"{"cells": [[-73.5, 45.5, 12, 1800], [-71.2, 46.8, 3, null]], "total": 15, "cities": [{"city": "Montréal", "n": 12, "lng": -73.5, "lat": 45.5, "median": 1800}]}"#)214        #expect(l.cells.count == 2)215        #expect(l.cells[0].n == 12)216        #expect(l.cities.first?.city == "Montréal")217        #expect(try decode(APIVersion.self, #"{"api": 2, "version": "2.0.0"}"#).api == 2)218    }219}220221@Suite("Formats")222struct FormatTests {223    @Test func prices() {224        #expect(Fmt.shortPrice(950) == "950")225        #expect(Fmt.shortPrice(1695) == "1,7 k")226        #expect(Fmt.shortPrice(2000) == "2 k")227        #expect(Fmt.shortPrice(0) == "•")228        #expect(Fmt.shortPrice(nil) == "•")229        #expect(Fmt.pct(-0.167) == "−17 %")230        #expect(Fmt.pct(0.08) == "+8 %")231        #expect(Fmt.pct(nil) == "—")232    }233234    @Test func slugsMatchServer() {235        #expect(Fmt.slug("Trois-Rivières") == "trois-rivieres")236        #expect(Fmt.slug("3½") == "3-1-2")237        #expect(Fmt.slug("6½+") == "6-1-2-plus")238        #expect(Fmt.slug("Saint-Jean-sur-Richelieu") == "saint-jean-sur-richelieu")239        #expect(Fmt.slug("  L'Ancienne-Lorette ") == "l-ancienne-lorette")240    }241242    @Test func distancesAndAvailability() {243        #expect(Fmt.distance(250) == "250 m")244        #expect(Fmt.distance(1240) == "1,2 km")245        #expect(Fmt.availability("now") == "Maintenant")246        #expect(Fmt.availability("2020-01-01") == "Maintenant")247        #expect(Fmt.availability(nil) == nil)248        #expect(Fmt.availability("n'importe quoi") == nil)249    }250251    @Test("formats du Québec ajoutés pour la v3")252    func v3Formats() {253        #expect(Fmt.points(-21.18).filter { !$0.isWhitespace } == "−21,2%" && Fmt.points(0.02).filter { !$0.isWhitespace } == "0%")254        #expect(Fmt.perSqft(2.763).filter { !$0.isWhitespace } == "2,76$/pi²")255        #expect(Fmt.isoMonth("2026-10-01") == "octobre 2026" && Fmt.isoDay("2026-11-01") == "1ᵉʳ novembre")256        #expect(Fmt.dec(101.36, 1) == "101,4")257        #expect(Fmt.daysUntil(iso: Fmt.isoInDays(30)) == 30)258        var f = SearchFilters()259        #expect(f.isEmpty && f.activeCount == 0 && !f.hasPlace)260        f.city = "Québec"; f.unitType = "4½"; f.priceMax = 1500; f.deal = .sous; f.pets = true261        // le séparateur de milliers est une espace insécable fine : on compare sans les espaces262        #expect(f.summary.filter { !$0.isWhitespace } == "Québec·4½·≤1500$·sousl'estimation·animaux")263    }264265    @Test func scoreWeights() {266        let s = ScoreSet(walk: 80, transit: 60, bike: nil, calme: 40, services: 100, global: 70)267        // (24 + 12 + 8 + 15) / 0,85 : l'axe sans donnée est retiré du dénominateur268        #expect(s.weighted(ScoreSet.defaultWeights) == 69.4)269        #expect(ScoreSet(walk: 90, transit: nil, bike: nil, calme: nil, services: nil, global: nil).weighted(ScoreSet.defaultWeights) == nil)270        #expect(ScoreSet.label(86) == "Exceptionnel")271        #expect(ScoreSet.label(20) == "Faible")272    }273}274
Files main
Menu

Theme