SPB Git

Repository Public

DecodageTests.swift 12.4 KB 256 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : Groupe Ka — app iOS native7// File             : GroupeKaTests/DecodageTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/groupe-ka-ios10// Project Website  : Not specified11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041@testable import GroupeKa42import XCTest4344/// Réponses réelles de l'API de préproduction, capturées le 2026-12-03 (GroupeKaTests/Fixtures).45enum Echantillon {46    static func donnees(_ nom: String) throws -> Data {47        let b = Bundle(for: DecodageTests.self)48        guard let u = b.url(forResource: nom, withExtension: "json") ?? b.url(forResource: nom, withExtension: "json", subdirectory: "Fixtures") else {49            throw XCTSkip("échantillon absent : \(nom)")50        }51        return try Data(contentsOf: u)52    }5354    static func lire<T: Decodable & Sendable>(_ type: T.Type, _ nom: String) throws -> (T, Meta?) {55        let e = try JSONDecoder().decode(Enveloppe<T>.self, from: donnees(nom))56        return (e.donnees, e.meta)57    }58}5960final class DecodageTests: XCTestCase {61    func testObservatoire() throws {62        let (o, meta) = try Echantillon.lire(Observatoire.self, "observatoire-30j")63        XCTAssertEqual(o.sites.compactMap(\.siteID), [.louka, .immoka, .autoka, .foodka])64        XCTAssertEqual(o.periode?.id, "30j")65        XCTAssertEqual(o.totaux?.sites, 4)66        XCTAssertNotNil(o.totaux?.annonces)67        XCTAssertEqual(meta?.perime, false)68        XCTAssertEqual(meta?.version, "1.0.0")69        let louka = try XCTUnwrap(o.sites.first)70        XCTAssertEqual(louka.nom, "Lou-Ka")71        XCTAssertNotNil(louka.chiffre?.valeur)72        XCTAssertEqual(louka.pouls?.points.count, 30)73        XCTAssertNotNil(louka.pouls?.points.first?.date)74        XCTAssertEqual(louka.kpis.count, 8)75        XCTAssertNotNil(louka.marche?.pct_sous)76        XCTAssertEqual(louka.etat?.en_ligne, true)77        // la collecte de Lou-Ka ne publie pas ses sources en bon état : la valeur reste absente78        XCTAssertNotNil(louka.collecte?.sources)79        XCTAssertNil(louka.collecte?.ok)80        // Food-Ka n'a pas de flux d'entrées et de retraits81        XCTAssertNil(o.sites.last?.flux)82        XCTAssertEqual(o.sites.last?.pouls?.pas, "semaine")83        XCTAssertFalse(o.collectes.isEmpty)84    }8586    func testTableauxDesQuatreSites() throws {87        for id in SiteID.mesures {88            let (t, _) = try Echantillon.lire(Tableau.self, "tableau-\(id.rawValue)-30j")89            XCTAssertFalse(t.kpis.isEmpty, id.rawValue)90            XCTAssertFalse(t.series.isEmpty, id.rawValue)91            XCTAssertNotNil(t.period?.from, id.rawValue)92            XCTAssertFalse(t.series[0].points.isEmpty, id.rawValue)93            XCTAssertFalse(t.breakdowns.isEmpty, id.rawValue)94            XCTAssertFalse(t.tables.isEmpty, id.rawValue)95            for tb in t.tables { XCTAssertFalse(tb.rows.isEmpty, "\(id.rawValue) \(tb.id ?? "")") }96        }97    }9899    func testTableauLouKa() throws {100        let (t, _) = try Echantillon.lire(Tableau.self, "tableau-louka-30j")101        XCTAssertEqual(t.kpis.first?.id, "actives")102        XCTAssertEqual(t.kpis.first?.direction, "down")103        XCTAssertEqual(t.kpis.first?.spark.count, 30)104        XCTAssertEqual(t.series.first?.kind, "line")105        XCTAssertEqual(t.series.first?.compare.count, 30)106        XCTAssertEqual(t.multiseries.count, 1)107        XCTAssertFalse(t.multiseries[0].series.isEmpty)108        XCTAssertEqual(t.stacked.first?.keys.count, t.stacked.first?.points.first?.values.count)109        XCTAssertEqual(t.gauges.count, 5)110        XCTAssertEqual(t.gauges.first?.max, 100)111        XCTAssertFalse(t.heatmap?.cells.isEmpty ?? true)112        // sept jours sur vingt-quatre heures ; une case sans activité peut manquer113        XCTAssertEqual(t.hourly?.cells.count, 167)114        XCTAssertTrue(t.hourly?.cells.allSatisfy { (0..<7).contains($0.dow ?? -1) && (0..<24).contains($0.hour ?? -1) } ?? false)115        XCTAssertEqual(t.panels.count, 9)116        XCTAssertEqual(t.panels.first?.kpis.count, 4)117        XCTAssertEqual(t.records.count, 10)118        // les cellules d'un tableau mêlent texte et nombres119        let ligne = try XCTUnwrap(t.tables.first?.rows.first)120        XCTAssertEqual(ligne.first?.chaine, "Montréal")121        XCTAssertNotNil(ligne[1].nombre)122        XCTAssertNil(t.method)123    }124125    func testTableauFoodKaCompose() throws {126        let (t, _) = try Echantillon.lire(Tableau.self, "tableau-foodka-30j")127        XCTAssertEqual(t.period?.composed, true)128        XCTAssertNotNil(t.period?.note)129        XCTAssertNil(t.heatmap)130        XCTAssertNil(t.hourly)131        XCTAssertTrue(t.panels.isEmpty)132        XCTAssertEqual(t.method?["nom"]?.chaine, "Indice du panier d'épicerie Food-Ka")133        // un indicateur sans variation ni courbe reste sans variation ni courbe134        XCTAssertNil(t.kpis.first?.delta_pct)135        XCTAssertTrue(t.kpis.first?.spark.isEmpty ?? false)136    }137138    func testSeries() throws {139        let (catalogue, _) = try Echantillon.lire([SerieCatalogue].self, "series")140        XCTAssertEqual(catalogue.count, 78)141        XCTAssertTrue(catalogue.contains { $0.id == "louka.annonces" && $0.origine == "observatoire" })142        XCTAssertEqual(Set(catalogue.compactMap(\.site)), ["louka", "immoka", "autoka", "foodka"])143        let (s, _) = try Echantillon.lire(Serie.self, "serie-louka-annonces")144        XCTAssertEqual(s.id, "louka.annonces")145        XCTAssertEqual(s.points.count, 120)146        XCTAssertEqual(s.points.first?.t, "2026-08-06")147    }148149    func testEtatEtCollectes() throws {150        let (e, _) = try Echantillon.lire([EtatSite].self, "etat")151        XCTAssertEqual(e.count, 4)152        XCTAssertEqual(e.first?.en_ligne, true)153        XCTAssertEqual(e.first?.sondes_24h.first?.count, 3)154        XCTAssertNotNil(Dates.instant(e.first?.donnees_lues_a))155        let (c, _) = try Echantillon.lire([Collecte].self, "collectes")156        XCTAssertEqual(c.count, 20)157        XCTAssertNotNil(c.first?.source)158        XCTAssertNotNil(Dates.instant(c.first?.a))159    }160161    func testRechercheFederee() throws {162        let (r, meta) = try Echantillon.lire(RechercheFederee.self, "recherche-sherbrooke")163        XCTAssertEqual(r.q, "sherbrooke")164        XCTAssertEqual(r.sites.count, 4)165        XCTAssertEqual(meta?.perime, false)166        let immo = try XCTUnwrap(r.sites.first { $0.site == "immoka" }?.annonces.first)167        XCTAssertEqual(immo.verdict?.position, "dessus")168        XCTAssertNotNil(immo.verdict?.ecart_pct)169        XCTAssertEqual(LigneAnnonce.verdict(immo.verdict)?.hasPrefix("au-dessus du marché, +"), true)170        XCTAssertNotNil(immo.attributs?["chambres"]?.nombre)171        // Lou-Ka ne juge pas cette annonce : pas de verdict, et l'app n'en fabrique pas172        let louka = try XCTUnwrap(r.sites.first { $0.site == "louka" }?.annonces.first)173        XCTAssertNil(louka.verdict)174        XCTAssertNil(LigneAnnonce.verdict(louka.verdict))175        XCTAssertEqual(louka.prix_unite, "$/mois")176        // Food-Ka a répondu sans résultat : un total de zéro, pas une erreur177        let food = try XCTUnwrap(r.sites.first { $0.site == "foodka" })178        XCTAssertEqual(food.total, 0)179        XCTAssertNil(food.erreur)180    }181182    func testVersionEtChiffres() throws {183        let v = try JSONDecoder().decode(VersionSite.self, from: Echantillon.donnees("version"))184        let c = try XCTUnwrap(v.chiffres)185        XCTAssertEqual(c["valoplex"]?.libelle, "immeubles évalués")186        XCTAssertNotNil(c["louka"]?.n)187        // les six portes ont leur chiffre ; Fabri-Ka n'est plus une porte188        for id in SiteID.allCases { XCTAssertNotNil(c[id.rawValue], id.rawValue) }189        XCTAssertNil(SiteID(rawValue: "fabrika"))190    }191192    func testOpenAPIEtRoutes() throws {193        let spec = try JSONDecoder().decode(OpenAPI.self, from: Echantillon.donnees("openapi"))194        let (index, _) = try Echantillon.lire(IndexAPI.self, "index")195        let groupes = RouteAPI.lire(spec, index: index)196        XCTAssertEqual(groupes.map(\.groupe), ["Sites", "Annonces", "Observatoire", "Séries", "Service"])197        let routes = groupes.flatMap(\.routes)198        XCTAssertEqual(routes.count, 15)199        let tableau = try XCTUnwrap(routes.first { $0.id == "tableau" })200        XCTAssertEqual(tableau.chemin, "/api/v1/sites/{site}/tableau")201        XCTAssertEqual(tableau.params.map(\.nom), ["site", "periode"])202        XCTAssertEqual(tableau.params[0].dans, "path")203        XCTAssertTrue(tableau.params[0].requis)204        XCTAssertEqual(tableau.params[1].valeurs, ["7j", "30j", "3m", "6m", "12m", "tout"])205        XCTAssertEqual(tableau.params[1].defaut, "30j")206        XCTAssertEqual(tableau.exemple, "/api/v1/sites/louka/tableau?periode=30j")207        XCTAssertEqual(routes.first { $0.id == "recherche" }?.params.first?.exemple, "sherbrooke")208        XCTAssertEqual(index.limite?.jetons_par_minute, 120)209    }210211    func testProbleme() throws {212        let p = try JSONDecoder().decode(Probleme.self, from: Echantillon.donnees("erreur-400"))213        XCTAssertEqual(p.status, 400)214        XCTAssertEqual(p.title, "Paramètre invalide")215        XCTAssertEqual(APIErreur.http(400, p).errorDescription?.hasPrefix("400 — « periode »"), true)216    }217218    /// Un champ absent, nul ou mal typé ne fait jamais échouer la réponse, et rien n'est mis à sa place.219    func testTolerance() throws {220        let json = #"""221        {"donnees": {"sites": [222            {"id": "louka", "chiffre": {"valeur": "beaucoup"}, "variation_pct": null, "pouls": {"points": [{"t": "2026-12-01", "v": 5}, {"t": 3}, "x"]}, "kpis": "aucun"},223            42,224            {"id": "inconnu", "marche": null}225        ], "collectes": null}, "meta": {"version": 3}}226        """#227        let e = try JSONDecoder().decode(Enveloppe<Observatoire>.self, from: Data(json.utf8))228        XCTAssertEqual(e.donnees.sites.count, 2)229        let s = e.donnees.sites[0]230        XCTAssertNil(s.chiffre?.valeur)231        XCTAssertNil(s.variation_pct)232        XCTAssertEqual(s.pouls?.points.count, 1)233        XCTAssertTrue(s.kpis.isEmpty)234        XCTAssertNil(e.donnees.sites[1].siteID)235        XCTAssertTrue(e.donnees.collectes.isEmpty)236        XCTAssertNil(e.meta?.version)237        XCTAssertNil(e.donnees.totaux)238    }239240    func testContenuDesPieces() throws {241        for s in KaSite.tous {242            let c = try XCTUnwrap(ContenuPiece.charger(s.slug), s.slug)243            XCTAssertNotNil(c.accroche, s.slug)244            XCTAssertFalse(c.apercu.isEmpty, s.slug)245            XCTAssertFalse(c.fonctions.isEmpty, s.slug)246            XCTAssertFalse(c.faq.isEmpty, s.slug)247            // chaque capture citée a ses dimensions : rien ne saute au chargement248            let origine = try XCTUnwrap(URL(string: "https://www.groupe-ka.com"))249            for cap in c.captures { XCTAssertNotNil(VuePiece.de(cap, slug: s.slug, origine: origine), "\(s.slug) \(cap.fichier ?? "")") }250        }251        let v = try XCTUnwrap(ContenuPiece.charger("lou-ka")?.captures.first.flatMap { VuePiece.de($0, slug: "lou-ka", origine: API.production) })252        XCTAssertEqual(v.grande?.absoluteString, "https://www.groupe-ka.com/captures/lou-ka/01-web-home-1440.webp")253        XCTAssertEqual(v.proportion, 1.6, accuracy: 0.001)254    }255}256
Files main
Menu

Theme