SPB Git

Repository Public

ApiClientTest.kt 16.6 KB 347 lines kotlin

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project          : Vrai-Prix Android10 * File             : app/src/test/kotlin/com/spboucher/vraiprix/ApiClientTest.kt11 * Description      : client réseau contre un serveur simulé : sonde du niveau12 *                    (API v3, page HTML, moteur illisible, 5xx, hors ligne),13 *                    ETag et 304, copie servie hors ligne, erreurs structurées14 *                    (404, 410, 429, 503), requêtes.15 * Module           : test16 * Repository       : https://git.spboucher.ai/vrai-prix-android17 * Project Website  : https://www.vrai-prix.com18 * Created          : 2026-11-2919 * Last Modified    : 2026-11-2920 *21 * =============================================================================22 * AUTHOR & PROFESSIONAL AFFILIATION23 * =============================================================================24 *25 * Author           : Simon-Pierre Boucher26 * Position         : Professor of Finance27 * Institution      : Université du Québec en Outaouais (UQO)28 * Department       : Département des sciences administratives29 * Organization     : SP Boucher30 *31 * Website          : https://spboucher.ai32 * Git              : https://git.spboucher.ai33 *34 * =============================================================================35 * OFFICIAL CONTACT DIRECTORY36 * =============================================================================37 *38 * General          : info@spboucher.ai39 * Professional     : contact@spboucher.ai40 * Direct           : simon@spboucher.ai41 * Research         : research@spboucher.ai42 * Development      : dev@spboucher.ai43 * Support          : support@spboucher.ai44 * Security/Admin   : admin@spboucher.ai45 * Notifications    : notifications@spboucher.ai46 *47 * Preferred Contact: dev@spboucher.ai48 *49 * =============================================================================50 * COPYRIGHT & INTELLECTUAL PROPERTY51 * =============================================================================52 *53 * Copyright (c) 202654 * Simon-Pierre Boucher55 *56 * All rights reserved where applicable.57 *58 * This file is governed by the applicable project license,59 * copyright notices, institutional agreements and relevant law.60 *61 * Unless expressly authorized by the applicable license or62 * rights holder, copying, redistribution, sublicensing,63 * publication and commercial exploitation are not permitted.64 *65 * Existing third-party rights and notices remain unaffected.66 *67 * =============================================================================68 * CONFIDENTIALITY & SECURITY69 * =============================================================================70 *71 * Classification   : Public72 * Distribution     : Public repository; use is governed by the project license73 * Security Contact : admin@spboucher.ai74 *75 * Access to this source does not independently grant permission76 * to redistribute or disclose confidential materials.77 *78 * Do not embed credentials, private keys, access tokens,79 * certificates or confidential personal information.80 *81 * =============================================================================82 * LICENSE & MAINTENANCE83 * =============================================================================84 *85 * License          : None specified (no license file in this repository)86 * Maintainer       : Simon-Pierre Boucher87 * Technical Contact: dev@spboucher.ai88 *89 * =============================================================================90 * END OF SP BOUCHER SOURCE HEADER91 * =============================================================================92 */9394package com.spboucher.vraiprix9596import com.spboucher.vraiprix.core.model.Property97import com.spboucher.vraiprix.core.model.ValueStatus98import com.spboucher.vraiprix.core.net.ApiClient99import com.spboucher.vraiprix.core.net.ApiError100import com.spboucher.vraiprix.core.net.MapBounds101import com.spboucher.vraiprix.core.net.MemoryKeyValue102import com.spboucher.vraiprix.core.net.ResponseCache103import com.spboucher.vraiprix.core.net.ServerError104import com.spboucher.vraiprix.core.net.ServiceLevel105import com.spboucher.vraiprix.core.net.VpApi106import kotlinx.coroutines.runBlocking107import mockwebserver3.MockResponse108import mockwebserver3.MockWebServer109import okhttp3.HttpUrl.Companion.toHttpUrl110import okhttp3.OkHttpClient111import org.junit.After112import org.junit.Assert.assertEquals113import org.junit.Assert.assertFalse114import org.junit.Assert.assertNotNull115import org.junit.Assert.assertNull116import org.junit.Assert.assertTrue117import org.junit.Assert.fail118import org.junit.Before119import org.junit.Rule120import org.junit.Test121import org.junit.rules.TemporaryFolder122import java.util.concurrent.TimeUnit123124class ApiClientTest {125    @get:Rule val tmp = TemporaryFolder()126    private lateinit var server: MockWebServer127    private val prefs = MemoryKeyValue()128    private val id = "23027379018778110000000"129130    @Before fun start() { server = MockWebServer(); server.start() }131    @After fun stop() { try { server.close() } catch (_: Exception) { } }132133    private fun client(level: ServiceLevel? = ServiceLevel.V3) = ApiClient(134        OkHttpClient.Builder().connectTimeout(2, TimeUnit.SECONDS).readTimeout(2, TimeUnit.SECONDS).build(),135        ResponseCache(tmp.root), prefs, server.url("/").toString(), level,136    )137138    private fun json(body: String, code: Int = 200, etag: String? = null): MockResponse {139        val b = MockResponse.Builder().code(code).body(body).addHeader("Content-Type", "application/json")140        if (etag != null) b.addHeader("ETag", etag)141        return b.build()142    }143144    private inline fun <reified E : ApiError> expect(block: () -> Unit): E {145        try { block() } catch (e: ApiError) { assertTrue("attendu ${E::class.simpleName}, reçu $e", e is E); return e as E }146        fail("aucune erreur levée"); throw IllegalStateException()147    }148149    // --- Sonde du niveau ---150151    @Test fun levelReadingRule() {152        assertEquals(ServiceLevel.V3, ServiceLevel.read(Fixtures.text("prod/v3-version")).first)153        assertEquals("v3-20261128-191255", ServiceLevel.read(Fixtures.text("prod/v3-version")).second!!.model)154        assertEquals(ServiceLevel.V3, ServiceLevel.read(Fixtures.text("v3-version")).first)155        // la page HTML du site quand la route n'existe pas156        assertEquals(ServiceLevel.V2, ServiceLevel.read("<!DOCTYPE html><html><body>404</body></html>").first)157        // la réponse de l'API 2158        assertEquals(ServiceLevel.V2, ServiceLevel.read(Fixtures.text("prod/version")).first)159        // moteur en migration : jamais des écrans vides160        val migrating = ServiceLevel.read("""{"api":3,"engine":{"routes_available":false}}""")161        assertEquals(ServiceLevel.V2, migrating.first)162        assertNotNull(migrating.second)163        assertEquals(ServiceLevel.V2, ServiceLevel.read("""{"api":3}""").first)164        assertEquals(ServiceLevel.V2, ServiceLevel.read("").first)165    }166167    @Test fun probeSwitchesToV3AndRemembers() = runBlocking {168        val c = client(level = null)169        assertFalse("aucun niveau connu au tout premier lancement", c.hasKnownLevel)170        assertEquals("API 2 avant la première sonde", ServiceLevel.V2, c.level)171        assertFalse("lire le niveau par défaut ne le rend pas connu", c.hasKnownLevel)172        server.enqueue(json(Fixtures.text("prod/v3-version")))173        assertEquals(ServiceLevel.V3, c.probeLevel())174        assertEquals("/api/v3/version", server.takeRequest().url.encodedPath)175        assertEquals(ServiceLevel.V3, c.level)176        assertEquals("2026-11-29", c.info!!.valueDate)177        // un nouveau client (prochain lancement) s'ouvre aussitôt au dernier niveau connu178        assertEquals(ServiceLevel.V3, client(level = null).level)179        assertTrue(client(level = null).hasKnownLevel)180    }181182    @Test fun probeFallsBackToV2OnHtmlOrUnreadableEngine() = runBlocking {183        val c = client(level = null)184        server.enqueue(json(Fixtures.text("prod/v3-version")))185        assertEquals(ServiceLevel.V3, c.probeLevel())186        server.enqueue(MockResponse.Builder().code(404).body("<html>introuvable</html>").build())187        assertEquals(ServiceLevel.V2, c.probeLevel())188        server.enqueue(json("""{"api":3,"engine":{"routes_available":false}}"""))189        assertEquals(ServiceLevel.V2, c.probeLevel())190        server.enqueue(MockResponse.Builder().code(200).body("<html>page du site</html>").build())191        assertEquals(ServiceLevel.V2, c.probeLevel())192    }193194    @Test fun probeKeepsTheLastKnownLevelOn5xxAndOffline() = runBlocking {195        val c = client(level = null)196        server.enqueue(json(Fixtures.text("prod/v3-version")))197        assertEquals(ServiceLevel.V3, c.probeLevel())198        server.enqueue(MockResponse.Builder().code(503).body("panne").build())199        assertEquals(ServiceLevel.V3, c.probeLevel())200        server.close()201        assertEquals(ServiceLevel.V3, c.probeLevel())202        // un niveau imposé (tests, captures) ne sonde pas203        assertEquals(ServiceLevel.V2, client(level = ServiceLevel.V2).probeLevel())204    }205206    // --- ETag, 304, hors ligne ---207208    @Test fun etagThenNotModifiedServesTheStoredCopy() = runBlocking {209        val api = VpApi(client())210        server.enqueue(json(Fixtures.text("prod/v3-fiche-valeur"), etag = "W/\"abc\""))211        val first = api.property(id)212        assertFalse(first.stale)213        val r1 = server.takeRequest()214        assertEquals("/api/v3/proprietes/$id", r1.url.encodedPath)215        assertNull(r1.headers["If-None-Match"])216        assertEquals("fr-CA", r1.headers["Accept-Language"])217218        server.enqueue(MockResponse.Builder().code(304).build())219        val second = api.property(id)220        assertEquals("W/\"abc\"", server.takeRequest().headers["If-None-Match"])221        assertFalse("une copie validée par 304 n'est pas périmée", second.stale)222        assertEquals(first.value, second.value)223        assertEquals(1, api.client.notModified.get())224    }225226    @Test fun offlineServesTheLastAnswerAndSaysSo() = runBlocking {227        val api = VpApi(client())228        server.enqueue(json(Fixtures.text("prod/v3-fiche-valeur"), etag = "\"v1\""))229        val live = api.property(id)230        server.close()231        val cached = api.property(id)232        assertTrue(cached.stale)233        assertEquals(live.value.id, cached.value.id)234        assertEquals(ValueStatus.VALEUR, cached.value.valeur.status)235        // une fiche jamais consultée : hors ligne, dit comme tel236        expect<ApiError.Offline> { runBlocking { api.property("11111111111111111111111") } }237        Unit238    }239240    @Test fun cacheKeyIgnoresTheHostAndPruneDropsOldEntries() {241        val a = "https://www.vrai-prix.com/api/v3/proprietes/$id?k=8".toHttpUrl()242        val b = "http://127.0.0.1:9999/api/v3/proprietes/$id?k=8".toHttpUrl()243        assertEquals(ResponseCache.key(a), ResponseCache.key(b))244        assertFalse(ResponseCache.key(a) == ResponseCache.key("https://www.vrai-prix.com/api/v3/proprietes/$id?k=9".toHttpUrl()))245        val cache = ResponseCache(tmp.newFolder("c"))246        cache.write(a, "{}"); cache.setEtag(a, "\"x\"")247        assertEquals("{}", cache.read(a)); assertEquals("\"x\"", cache.etag(a))248        assertEquals(1, cache.usage().second)249        cache.prune(System.currentTimeMillis() + 29L * 86_400_000L)250        assertNotNull(cache.read(a))251        cache.prune(System.currentTimeMillis() + 31L * 86_400_000L)252        assertNull(cache.read(a)); assertNull(cache.etag(a))253        cache.write(a, "{}"); cache.clear()254        assertEquals(0, cache.usage().second)255    }256257    @Test fun anUnreadableAnswerIsNeverStored() = runBlocking {258        val c = client()259        server.enqueue(MockResponse.Builder().code(200).body("<html>maintenance</html>").addHeader("ETag", "\"h\"").build())260        expect<ApiError.Decoding> { runBlocking { VpApi(c).property(id) } }261        assertNull(c.cache.read(c.url("api/v3/proprietes/$id")!!))262        assertNull(c.cache.etag(c.url("api/v3/proprietes/$id")!!))263    }264265    // --- Erreurs ---266267    @Test fun bothErrorEnvelopes() {268        assertEquals(ServerError("not_found", "Propriété introuvable au rôle d'évaluation."), ServerError.read(Fixtures.text("prod/v3-erreur")))269        assertEquals(ServerError(null, "Paramètre invalide"), ServerError.read("""{"error":"Paramètre invalide"}"""))270        assertNull(ServerError.read("""{"error":null}"""))271        assertNull(ServerError.read("<html>"))272    }273274    @Test fun structuredErrors() {275        val api = VpApi(client())276        server.enqueue(json(Fixtures.text("prod/v3-erreur"), 404))277        expect<ApiError.NotFound> { runBlocking { api.property("000") } }278        server.enqueue(json("""{"error":{"code":"gone","message":"Inscription retirée."}}""", 410))279        expect<ApiError.Gone> { runBlocking { api.listing("duproprio:1") } }280        server.enqueue(json("""{"error":{"code":"rate_limited","message":"Trop de requêtes."}}""", 429))281        expect<ApiError.RateLimited> { runBlocking { api.market() } }282        // moteur illisible : « valeurs en cours de mise à jour », jamais un chiffre de remplacement283        server.enqueue(json("""{"error":{"code":"engine_unavailable","message":"Le moteur de valeur est en cours de mise à jour."}}""", 503))284        expect<ApiError.Unavailable> { runBlocking { api.property(id) } }285        server.enqueue(json(Fixtures.text("prod/v3-erreur-parametre"), 400))286        val bad = expect<ApiError.Server> { runBlocking { api.rankings("prix_median", null, null) } }287        assertEquals("bad_parameter", bad.code)288        assertTrue(bad.text.startsWith("critere"))289        server.enqueue(MockResponse.Builder().code(502).body("Bad Gateway").build())290        assertEquals(502, expect<ApiError.Http> { runBlocking { api.model() } }.code)291    }292293    @Test fun a503DoesNotFallBackToTheStoredCopy() = runBlocking {294        val api = VpApi(client())295        server.enqueue(json(Fixtures.text("prod/v3-fiche-valeur")))296        api.property(id)297        server.enqueue(json("""{"error":{"code":"engine_unavailable","message":"…"}}""", 503))298        expect<ApiError.Unavailable> { runBlocking { api.property(id) } }299        Unit300    }301302    // --- Requêtes ---303304    @Test fun queriesAreSortedEncodedAndSkipEmptyValues() = runBlocking {305        val api = VpApi(client())306        server.enqueue(json(Fixtures.text("prod/v3-ventes")))307        api.sales(mapOf("q" to "Lévis", "type" to null, "marche" to "1", "prix_min" to ""), cursor = null, limit = 10)308        val u = server.takeRequest().url309        assertEquals("/api/v3/ventes", u.encodedPath)310        assertEquals("limit=10&marche=1&q=L%C3%A9vis", u.encodedQuery)311312        server.enqueue(json(Fixtures.text("v3-inscription")))313        api.listing("duproprio:1000921")314        assertEquals("/api/v3/inscriptions/duproprio%3A1000921", server.takeRequest().url.encodedPath)315316        server.enqueue(json(Fixtures.text("prod/v3-position")))317        api.position(id, 449_999.6, asked = true)318        assertEquals("id=$id&nature=demande&prix=450000", server.takeRequest().url.encodedQuery)319320        server.enqueue(json(Fixtures.text("prod/v3-proprietes-bbox")))321        api.properties(MapBounds(-71.25, 46.8, -71.24, 46.805), 20)322        assertEquals("-71.25000,46.80000,-71.24000,46.80500", server.takeRequest().url.queryParameter("bbox"))323    }324325    @Test fun linksAndImages() {326        val api = VpApi(ApiClient(OkHttpClient(), ResponseCache(tmp.root), prefs))327        assertEquals("https://www.vrai-prix.com/api/report?id=$id", api.reportUrl(id))328        assertEquals("https://www.vrai-prix.com/estimation/$id", api.pageUrl("/estimation/$id"))329        val l = Property.from(Fixtures.json("prod/v3-fiche-inscrite")).listing!!330        assertTrue(api.imageUrl(l)!!.startsWith("https://www.vrai-prix.com/api/img?u=https%3A%2F%2Fphotos.duproprio.com"))331        assertTrue(api.imageUrl(l, 360)!!.endsWith("w=360"))332        assertEquals("https://www.vrai-prix.com/api/img?u=https%3A%2F%2Fx.test%2Fa%20b.jpg&w=640", api.imageUrl("https://x.test/a b.jpg"))333        assertNull(api.imageUrl(null as String?))334        val b = MapBounds(-72.0, 46.0, -71.0, 46.5)335        assertTrue(b.contains(46.2, -71.5)); assertFalse(b.contains(47.0, -71.5))336        assertEquals(2.0, b.expanded(1.0).lngSpan, 1e-9)337    }338339    @Test fun underApi2WhatOnlyV3KnowsIsNotServed() {340        val api = VpApi(client(level = ServiceLevel.V2))341        expect<ApiError.NotServed> { runBlocking { api.sale("abc") } }342        expect<ApiError.NotServed> { runBlocking { api.position(id, 1.0, true) } }343        expect<ApiError.NotServed> { runBlocking { api.model() } }344        assertEquals(0, server.requestCount)345    }346}347
Files main
Menu

Theme