SPB Git

Repository Public

DecodingTests.swift 12.8 KB 261 lines swift

1//2//  Food-Ka iOS v23//  File: FoodKaTests/DecodingTests.swift4//  Description: décodage des réponses réelles de l'API v2 (échantillons du 2026-11-26) et des formes dégradées.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import XCTest11@testable import FoodKa1213final class DecodingTests: XCTestCase {14    static func fixture(_ name: String) throws -> Data {15        let url = try XCTUnwrap(Bundle(for: DecodingTests.self).url(forResource: name, withExtension: "json"), "fixture \(name)")16        return try Data(contentsOf: url)17    }1819    private func decode<T: Decodable>(_ name: String, as: T.Type = T.self) throws -> T {20        try JSONDecoder().decode(T.self, from: DecodingTests.fixture(name))21    }2223    func testVersionPublishesRules() throws {24        let v: ServiceInfo = try decode("version")25        XCTAssertEqual(v.api, 2)26        XCTAssertNotNil(APIClient.isV2(try DecodingTests.fixture("version")))27        XCTAssertEqual(v.rules?.verdict?.codes?["bon"], "Sous son prix habituel")28        XCTAssertNotNil(v.rules?.verdict?.regle)29        XCTAssertNotNil(v.rules?.verdict?.raisons_sans_verdict?["prix_hors_quebec"])30        XCTAssertEqual(v.rules?.comparaison?.exclues, ["adonis", "walmart"])31        XCTAssertNotNil(v.rules?.solde?["clearance"])32        XCTAssertEqual(v.rules?.verdict?.bon_max_pct, -8)33        XCTAssertNotNil(v.rules?.solde?["verifiee"])34        XCTAssertNotNil(v.rules?.appariement?["equivalent"])35        ServiceInfo.store(v)36        // les libellés viennent du service : neutres, jamais « bon » ni « élevé »37        XCTAssertEqual(ServiceInfo.positionLabel(.sous), "Sous son prix habituel")38        XCTAssertEqual(ServiceInfo.positionLabel(.nettementDessus), "Nettement au-dessus de son prix habituel")39        XCTAssertEqual(ServiceInfo.noVerdictLabel("prix_hors_quebec"), "Prix relevé hors Québec : non comparé")40        XCTAssertEqual(ServiceInfo.scopeLabel("hors_quebec"), "Prix relevé hors Québec")41    }4243    func testV1IsNotAccepted() {44        XCTAssertNil(APIClient.isV2(Data(#"{"api": 1}"#.utf8)))45        XCTAssertNil(APIClient.isV2(Data("<!doctype html>".utf8)))46    }4748    func testSearchWithFacets() throws {49        let r: SearchResponse = try decode("search")50        XCTAssertGreaterThan(r.total, 0)51        XCTAssertFalse(r.products.isEmpty)52        let p = try XCTUnwrap(r.products.first)53        XCTAssertFalse(p.id.isEmpty)54        XCTAssertFalse(p.storeName.isEmpty)55        let f = try XCTUnwrap(r.facets)56        XCTAssertFalse(f.stores.isEmpty)57        XCTAssertFalse(f.categories.isEmpty)58        XCTAssertFalse(f.tagLabels.isEmpty)59    }6061    func testProductDetail() throws {62        let d: ProductDetail = try decode("product")63        XCTAssertEqual(d.card.id, "maxi:20894117004_EA")64        XCTAssertEqual(d.card.price, 2.19)65        XCTAssertEqual(d.card.unitPrice?.label, "2,30\u{00A0}$ / L")66        XCTAssertEqual(d.card.verdict, .bon, "la carte porte le code du verdict de la fiche")67        XCTAssertEqual(d.card.verdictPosition, .sous)68        XCTAssertEqual(d.verdict?.code, .bon)69        XCTAssertEqual(d.verdict?.position, .sous)70        XCTAssertEqual(d.verdict?.label, "Sous le prix des autres enseignes", "le libellé nomme la comparaison qui donne la position")71        XCTAssertEqual(d.verdict?.historyLabel, "À son prix habituel")72        XCTAssertEqual(d.card.compare?.bestStoreName, "Maxi")73        XCTAssertEqual(d.card.compare?.prices.count, 6)74        XCTAssertEqual(d.card.compare?.prices.first?.current, true)75        XCTAssertTrue(d.card.comparable)76        XCTAssertEqual(d.verdict?.storesCompared, 5)77        XCTAssertEqual(d.offers.count, 5)78        XCTAssertEqual(d.offersSummary?.stores, 6)79        XCTAssertTrue(d.offers.allSatisfy { $0.match != nil })80        // la moins chère d'abord, la fiche comprise81        XCTAssertEqual(d.allOffers.count, 6)82        XCTAssertEqual(d.cheapest.id, "maxi:20894117004_EA")83        XCTAssertEqual(d.allOffers.map { $0.price ?? 0 }, d.allOffers.map { $0.price ?? 0 }.sorted())84        let h = try XCTUnwrap(d.history)85        XCTAssertTrue(h.isSteps)86        XCTAssertEqual(h.median90d, 2.19)87        XCTAssertFalse(h.points.isEmpty)88        XCTAssertNil(d.nutrition)89        XCTAssertEqual(d.priceScope?.needsWarning, false)90    }9192    func testFlyerProduct() throws {93        let d: ProductDetail = try decode("product-circulaire")94        XCTAssertTrue(d.card.isFlyer)95        XCTAssertEqual(d.card.deal?.status, .verifiee)96        XCTAssertEqual(d.card.deal?.reference, "catalogue")97        XCTAssertEqual(d.history?.isSteps, false)98        XCTAssertNotNil(d.validity?.to)99        XCTAssertNotNil(d.validity?.finePrint)100        XCTAssertTrue(d.offers.isEmpty)101        XCTAssertNil(d.verdict)102        XCTAssertNotNil(d.verdictReason?.label, "sans verdict, le service dit pourquoi")103        XCTAssertNil(d.card.verdictPosition)104    }105106    func testNutritionKeysOfOpenFoodFacts() throws {107        let d: ProductDetail = try decode("product-nutrition")108        let n = try XCTUnwrap(d.nutrition)109        XCTAssertTrue(n.hasContent)110        XCTAssertEqual(n.rows.first?.label, "Calories")111        XCTAssertEqual(n.rows.first?.value, "526\u{00A0}kcal")112        XCTAssertTrue(n.rows.contains { $0.label == "Protéines" })113    }114115    func testWithdrawnProductIsReduced() throws {116        let json = #"{"id": "metro:1", "public": false, "active": false, "reason": "inactif", "reason_label": "n'est plus affiché par l'enseigne", "name": "Lait", "brand": null, "store": "metro", "store_name": "Metro", "last_price": 4.5, "last_seen": 1795000000}"#117        let d = try JSONDecoder().decode(ProductDetail.self, from: Data(json.utf8))118        XCTAssertFalse(d.isPublic)119        XCTAssertFalse(d.active)120        XCTAssertEqual(d.card.price, 4.5, "le dernier prix connu tient lieu de prix")121        XCTAssertEqual(d.reasonLabel, "n'est plus affiché par l'enseigne")122    }123124    func testSuggest() throws {125        let s: Suggestions = try decode("suggest")126        XCTAssertFalse(s.products.isEmpty)127        XCTAssertFalse(s.categories.isEmpty)128        XCTAssertEqual(s.categories.first?.parent, "Produits laitiers et œufs")129    }130131    func testDeals() throws {132        let d: DealsResponse = try decode("deals")133        XCTAssertEqual(d.byStatus["verifiee"], d.total)134        XCTAssertTrue(d.products.allSatisfy { $0.deal?.status == .verifiee })135        XCTAssertEqual(d.products.first?.deal?.clearance, true, "une baisse de 60 % et plus est une liquidation")136        XCTAssertTrue(DealBadge.text(d.products[0].deal!, long: false).hasPrefix("Liquidation"))137        XCTAssertNotNil(d.products.first?.deal?.dropPct)138    }139140    func testFlyersAndStoreFlyer() throws {141        let f: FlyersResponse = try decode("circulaires")142        XCTAssertEqual(f.flyers.count, f.total)143        XCTAssertNotNil(f.flyers.first?.validTo)144        XCTAssertNotNil(f.note)145    }146147    func testStores() throws {148        let r: StoresResponse = try decode("enseignes")149        XCTAssertEqual(r.stores.count, r.total)150        XCTAssertFalse(r.ranked.isEmpty)151        XCTAssertEqual(r.ranked.first?.id, "giant_tiger")152        XCTAssertTrue(r.stores.contains { !$0.connected })153        let maxi: Store = try decode("enseigne-maxi")154        XCTAssertEqual(maxi.priceLevel?.rank, 2)155        XCTAssertFalse(maxi.categories.isEmpty)156        XCTAssertFalse(maxi.topDeals.isEmpty)157        XCTAssertNotNil(maxi.freshness?.status)158        XCTAssertEqual(maxi.coverage, "echantillon")159        XCTAssertFalse(maxi.priceLevelByCategory.isEmpty)160        XCTAssertEqual(ServiceInfo.coverageLabel("echantillon") != nil || ServiceInfo.current == nil, true)161    }162163    func testMarket() throws {164        let m: MarketStats = try decode("marche")165        XCTAssertEqual(m.matching?.linkedSharePct, 5.3)166        XCTAssertNotNil(m.deals["verifiee"])167        let i: MarketIndex = try decode("marche-indice")168        XCTAssertEqual(i.summary?.index, 100.14)169        XCTAssertEqual(i.series.count, (i.summary?.weeks ?? 0) + 1, "la semaine de base, puis une par semaine")170        XCTAssertFalse(i.byCategory.isEmpty)171        XCTAssertFalse(i.byStore.isEmpty)172        XCTAssertEqual(i.method?.limites.count, 3)173        XCTAssertEqual(i.oneLine?.hasPrefix("Indice du panier : 100,14 · "), true)174        let mv: MarketMovements = try decode("marche-mouvements")175        XCTAssertEqual(mv.up + mv.down + mv.stable, mv.compared)176        XCTAssertNotNil(mv.topDown.first?.priceBefore)177        XCTAssertNotNil(mv.topDown.first?.moveKind, "chaque mouvement dit sa nature")178        XCTAssertEqual(mv.topDown.first?.kind, "catalogue")179        XCTAssertEqual(mv.kindLabels.count, 4)180    }181182    func testLightBatchRefreshesPricesWithoutLosingTheCard() throws {183        let b: ProductBatch = try decode("lot")184        XCTAssertEqual(b.missing, ["metro:zzz"])185        let e = try XCTUnwrap(b.products.first)186        XCTAssertTrue(e.live)187        XCTAssertNotNil(e.product.price)188        // la carte gardée porte le rayon et la comparaison ; le lot n'apporte que le prix et ses signaux189        var kept = Product(id: e.product.id, name: "Nectar de mangue", store: "maxi", storeName: "Maxi", category: "Boissons", size: "960 ml",190                           price: 9.99, compare: CompareInfo(stores: 6, bestPrice: 2.19, isBest: true, bestStore: "maxi"))191        kept = kept.refreshed(with: e.product)192        XCTAssertEqual(kept.price, e.product.price)193        XCTAssertEqual(kept.category, "Boissons")194        XCTAssertEqual(kept.compare?.stores, 6)195        XCTAssertEqual(kept.verdictLabel, e.product.verdictLabel)196    }197198    func testUpcomingFlyerItemsAreListedApart() throws {199        let f: Flyer = try decode("circulaire-iga")200        XCTAssertFalse(f.products.isEmpty)201        XCTAssertEqual(f.upcomingProducts.count, f.nUpcoming)202        XCTAssertTrue(f.upcomingProducts.allSatisfy { $0.flyerStatus == "a_venir" && $0.validFrom != nil })203        XCTAssertNotNil(f.validToMax)204    }205206    func testBarcodeSearch() throws {207        let r: SearchResponse = try decode("barcode")208        XCTAssertEqual(r.total, 2)209        XCTAssertEqual(r.coverageSharePct, 5.2, "la couverture est dite : peu de produits portent un code")210        XCTAssertNotNil(r.coverageNote)211    }212213    func testOutsideQuebecCardIsNotCompared() throws {214        let json = #"{"id": "walmart:1", "name": "Milk", "store": "walmart", "store_name": "Walmart Canada", "price": 4.5, "verdict": null, "verdict_label": null, "verdict_reason": "prix_hors_quebec", "price_scope": "hors_quebec", "comparable": false, "compare": null}"#215        let p = try JSONDecoder().decode(Product.self, from: Data(json.utf8))216        XCTAssertFalse(p.comparable)217        XCTAssertNil(p.verdictPosition)218        XCTAssertEqual(p.verdictReason, "prix_hors_quebec")219        XCTAssertEqual(p.priceScopeCode, "hors_quebec")220        XCTAssertEqual(ShelfTagContent.make(for: p).eyebrow, "Prix hors Québec")221        // une carte d'avant la révision 2 (cache) garde une position, déduite de son code222        let old = try JSONDecoder().decode(Product.self, from: Data(#"{"id": "maxi:1", "name": "Lait", "price": 4, "verdict": "eleve"}"#.utf8))223        XCTAssertEqual(old.verdictPosition, .dessus)224    }225226    func testCategoriesAndIcons() throws {227        let c: CategoriesResponse = try decode("categories")228        XCTAssertEqual(c.categories.count, 18)229        XCTAssertEqual(Category.icon(slug: "boissons"), "ic-boissons")230        XCTAssertEqual(Category.icon(name: "Produits laitiers et œufs"), "ic-laitiers")231        XCTAssertEqual(Category.icon(name: "Fruits et légumes"), "ic-fruits-legumes")232        XCTAssertEqual(Category.icon(name: nil), "ic-tablette")233    }234235    func testSearchFiltersQuery() {236        var f = SearchFilters()237        f.q = " yogourt grec "; f.stores = ["metro", "maxi"]; f.tags = ["bio", "local"]; f.sort = .unitPrice; f.dealOnly = true; f.priceMax = 5238        let q = f.query(page: 2, facets: true)239        XCTAssertEqual(q["q"], "yogourt grec")240        XCTAssertEqual(q["store"], "maxi,metro")241        XCTAssertEqual(q["tags"], "bio,local")242        XCTAssertEqual(q["sort"], "unit_price")243        XCTAssertEqual(q["deal"], "1")244        XCTAssertNil(q["apparie"] ?? nil)245        f.matchedOnly = true; f.inStockOnly = true246        XCTAssertEqual(f.query(page: 1)["apparie"], "1", "filtre « dans plusieurs enseignes »")247        XCTAssertEqual(f.query(page: 1)["in_stock"], "1")248        f.matchedOnly = false; f.inStockOnly = false249        XCTAssertEqual(q["price_max"], "5")250        XCTAssertEqual(q["page"], "2")251        XCTAssertEqual(q["facets"], "1")252        XCTAssertEqual(f.activeCount, 6)253    }254255    func testProductPathKeepsColon() {256        let u = APIClient.compose(base: APIClient.fallback, path: "api/products/" + APIClient.segment("maxi:20894117004_EA"), query: [:])257        XCTAssertEqual(u?.absoluteString, "https://foodka-v2.51-161-112-61.sslip.io/api/products/maxi:20894117004_EA")258        XCTAssertEqual(APIClient.segment("a/b c"), "a%2Fb%20c")259    }260}261
Files main
Menu

Theme