SPB Git

Repository Public

MapScreensTest.kt 44.0 KB 744 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/androidTest/kotlin/com/spboucher/vraiprix/MapScreensTest.kt11 * Description      : essais sur appareil des écrans de carte (KA Maps), contre12 *                    l'API de production en lecture seule (et la préproduction13 *                    du site pour les routes d'agrégats, qui ne sont pas encore14 *                    en production) : chaque nature à sa forme, rien sous15 *                    l'interface, groupe touché, sélection et plomb, analyses16 *                    et légendes, 2D / 3D, rotation, arrière-plan, sombre,17 *                    comparables, OpenGL ES, police agrandie, zone gardée puis18 *                    mode avion.19 * Module           : androidTest20 * Repository       : https://git.spboucher.ai/vrai-prix-android21 * Project Website  : https://www.vrai-prix.com22 * Created          : 2026-12-0123 * Last Modified    : 2026-12-0124 *25 * =============================================================================26 * AUTHOR & PROFESSIONAL AFFILIATION27 * =============================================================================28 *29 * Author           : Simon-Pierre Boucher30 * Position         : Professor of Finance31 * Institution      : Université du Québec en Outaouais (UQO)32 * Department       : Département des sciences administratives33 * Organization     : SP Boucher34 *35 * Website          : https://spboucher.ai36 * Git              : https://git.spboucher.ai37 *38 * =============================================================================39 * OFFICIAL CONTACT DIRECTORY40 * =============================================================================41 *42 * General          : info@spboucher.ai43 * Professional     : contact@spboucher.ai44 * Direct           : simon@spboucher.ai45 * Research         : research@spboucher.ai46 * Development      : dev@spboucher.ai47 * Support          : support@spboucher.ai48 * Security/Admin   : admin@spboucher.ai49 * Notifications    : notifications@spboucher.ai50 *51 * Preferred Contact: dev@spboucher.ai52 *53 * =============================================================================54 * COPYRIGHT & INTELLECTUAL PROPERTY55 * =============================================================================56 *57 * Copyright (c) 202658 * Simon-Pierre Boucher59 *60 * All rights reserved where applicable.61 *62 * This file is governed by the applicable project license,63 * copyright notices, institutional agreements and relevant law.64 *65 * Unless expressly authorized by the applicable license or66 * rights holder, copying, redistribution, sublicensing,67 * publication and commercial exploitation are not permitted.68 *69 * Existing third-party rights and notices remain unaffected.70 *71 * =============================================================================72 * CONFIDENTIALITY & SECURITY73 * =============================================================================74 *75 * Classification   : Public76 * Distribution     : Public repository; use is governed by the project license77 * Security Contact : admin@spboucher.ai78 *79 * Access to this source does not independently grant permission80 * to redistribute or disclose confidential materials.81 *82 * Do not embed credentials, private keys, access tokens,83 * certificates or confidential personal information.84 *85 * =============================================================================86 * LICENSE & MAINTENANCE87 * =============================================================================88 *89 * License          : None specified (no license file in this repository)90 * Maintainer       : Simon-Pierre Boucher91 * Technical Contact: dev@spboucher.ai92 *93 * =============================================================================94 * END OF SP BOUCHER SOURCE HEADER95 * =============================================================================96 */9798package com.spboucher.vraiprix99100import ai.spboucher.kamaps.KaFeature101import ai.spboucher.kamaps.KaLayer102import ai.spboucher.kamaps.KaLayerData103import ai.spboucher.kamaps.KaMapController104import ai.spboucher.kamaps.KaMode105import ai.spboucher.kamaps.KaRegionState106import ai.spboucher.kamaps.KaThemes107import ai.spboucher.kamaps.LngLat108import android.content.Intent109import android.util.Log110import androidx.lifecycle.Lifecycle111import androidx.test.core.app.ActivityScenario112import androidx.test.ext.junit.runners.AndroidJUnit4113import androidx.test.platform.app.InstrumentationRegistry114import androidx.test.uiautomator.By115import androidx.test.uiautomator.UiDevice116import androidx.test.uiautomator.Until117import com.spboucher.vraiprix.core.net.MapBounds118import com.spboucher.vraiprix.design.MapStyle119import com.spboucher.vraiprix.features.map.Analysis120import com.spboucher.vraiprix.features.map.MapLayer121import com.spboucher.vraiprix.features.map.MapModel122import com.spboucher.vraiprix.features.map.MapOffline123import com.spboucher.vraiprix.features.map.MapPoint124import com.spboucher.vraiprix.features.map.MapProbe125import kotlinx.coroutines.runBlocking126import kotlinx.serialization.json.JsonArray127import kotlinx.serialization.json.JsonObject128import kotlinx.serialization.json.JsonPrimitive129import kotlinx.serialization.json.jsonArray130import kotlinx.serialization.json.jsonObject131import org.junit.After132import org.junit.Assert.assertEquals133import org.junit.Assert.assertFalse134import org.junit.Assert.assertNotNull135import org.junit.Assert.assertNull136import org.junit.Assert.assertTrue137import org.junit.FixMethodOrder138import org.junit.Test139import org.junit.runner.RunWith140import org.junit.runners.MethodSorters141142@RunWith(AndroidJUnit4::class)143@FixMethodOrder(MethodSorters.NAME_ASCENDING)144class MapScreensTest {145    private val inst = InstrumentationRegistry.getInstrumentation()146    private val device: UiDevice = UiDevice.getInstance(inst)147    private val context get() = inst.targetContext148    private val density get() = context.resources.displayMetrics.density149    private var scenario: ActivityScenario<MainActivity>? = null150151    /** Plateau-Mont-Royal : des ventes, des valeurs aux trois régimes et des inscriptions dans la même vue. */152    private val plateau = "45.5231,-73.5817"153    /**154     * Zoom des épreuves de la couche des valeurs : sur un grand écran la même échelle montre plus de propriétés que le155     * service n'en rend d'un coup, et la carte passe alors aux secteurs (c'est voulu) ; on regarde donc de plus près.156     */157    private val unitsZoom: String get() = if (context.resources.displayMetrics.let { it.widthPixels / it.density } > 600) "17.5" else "16.4"158    /** Préproduction du site : seule à servir `/api/v3/carte/territoires` et `/api/v3/carte/ventes-grille` pour l'instant. */159    private val staging = "https://vraiprix-kamaps.51-161-112-61.sslip.io"160161    @After fun close() {162        shell("cmd connectivity airplane-mode disable")163        shell("settings put system font_scale 1.0")164        runCatching { device.setOrientationNatural() }165        scenario?.close(); scenario = null166    }167168    private fun shell(cmd: String): String = inst.uiAutomation.executeShellCommand(cmd).use { fd -> android.os.ParcelFileDescriptor.AutoCloseInputStream(fd).bufferedReader().readText() }169170    /** Lance l'app sur l'onglet Carte (production, sauf `base_url`). */171    private fun launch(vararg extras: Pair<String, String>) {172        scenario?.close()173        MapProbe.loaded = false; MapProbe.controller = null; MapProbe.preview = null; MapProbe.model = null; MapProbe.engine = null174        val i = Intent(context, MainActivity::class.java).putExtra("tab", "map").putExtra("appearance", "light")175        for ((k, v) in extras) i.putExtra(k, v)176        scenario = ActivityScenario.launch(i)177    }178179    private fun <T> main(block: () -> T): T {180        var out: Result<T>? = null181        inst.runOnMainSync { out = runCatching(block) }182        return out!!.getOrThrow()183    }184185    private fun waitFor(what: String, timeoutMs: Long = 30_000, cond: () -> Boolean) {186        val end = System.currentTimeMillis() + timeoutMs187        while (System.currentTimeMillis() < end) { if (runCatching(cond).getOrDefault(false)) return; Thread.sleep(200) }188        throw AssertionError("délai dépassé : $what")189    }190191    private fun map(): KaMapController = MapProbe.controller ?: throw AssertionError("carte absente")192    private fun model(): MapModel = MapProbe.model ?: throw AssertionError("modèle absent")193    private fun layer(id: String): KaLayer? = main { MapProbe.controller?.layer(id) }194    private fun layerIds(): List<String> = main { MapProbe.controller?.layerIds() ?: emptyList() }195    private fun items(id: String): List<JsonObject> = ((layer(id)?.data as? KaLayerData.Json)?.element as? JsonArray)?.map { it.jsonObject } ?: emptyList()196    private fun features(id: String): List<JsonObject> = ((layer(id)?.data as? KaLayerData.Json)?.element as? JsonObject)?.get("features")?.jsonArray?.map { it.jsonObject } ?: emptyList()197    private fun str(o: JsonObject?, k: String): String? = (o?.get(k) as? JsonPrimitive)?.content198    private fun points(): List<MapPoint> = main { model().points }199    private fun camera() = main { map().getCamera() }200201    private fun waitForEngine() {202        waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null && MapProbe.model != null }203    }204205    /** Attend la carte, son premier chargement complet et des points venus du service. */206    private fun waitForPoints(min: Int = 1) {207        waitForEngine()208        waitFor("points de l'API", 60_000) { points().size >= min && !main { model().loading } }209        waitFor("carte chargée", 60_000) { MapProbe.loaded }210        waitFor("couches posées") { layerIds().isNotEmpty() }211        Thread.sleep(900)212    }213214    /** Position à l'écran (dp, repère de la carte) d'un lieu, s'il est dans la partie dégagée. */215    private fun screen(lat: Double, lng: Double): Pair<Double, Double>? = main {216        val p = map().project(LngLat(lng, lat)) ?: return@main null217        val w = MapProbe.width / density; val h = MapProbe.height / density218        if (p.x < 30 || p.x > w - 90 || p.y < 70 || p.y > h - 60) null else p.x to p.y219    }220221    /** Cherche une entité rendue dans la partie dégagée de la carte (dp). */222    private fun find(layers: List<String>, pred: (KaFeature) -> Boolean): Pair<Pair<Double, Double>, KaFeature>? = main {223        val w = MapProbe.width / density; val h = MapProbe.height / density224        var y = 80.0225        while (y < h - 70) {226            var x = 24.0227            while (x < w - 84) {228                val f = map().queryRendered(x, y, layers).firstOrNull()229                if (f != null && pred(f)) return@main (x to y) to f230                x += 14231            }232            y += 14233        }234        null235    }236237    private fun tap(dp: Pair<Double, Double>) { device.click((MapProbe.originX + dp.first * density).toInt(), (MapProbe.originY + dp.second * density).toInt()) }238239    /** Un point seul à l'écran (aucun autre à moins de 26 dp, pas à la même adresse), loin des bords et de l'interface. */240    private fun lonely(pred: (MapPoint) -> Boolean): Pair<MapPoint, Pair<Double, Double>> {241        val all = points().mapNotNull { p -> screen(p.lat, p.lng)?.let { p to it } }242        // toute l'interface posée sur la carte (un toucher sur un bouton ne choisirait pas le point)243        val obstacles = MapProbe.obstacles.map { doubleArrayOf(it.left, it.top, it.right, it.bottom) }244        return all.firstOrNull { (p, at) ->245            pred(p) && all.none { (q, o) -> q.id != p.id && Math.hypot(o.first - at.first, o.second - at.second) < 26 } &&246                obstacles.none { r -> at.first > r[0] - 12 && at.first < r[2] + 12 && at.second > r[1] - 12 && at.second < r[3] + 12 } &&247                // le repère est bien ce que le doigt touche (pas l'étiquette d'un voisin posée au-dessus)248                main { map().queryRendered(at.first, at.second).firstOrNull()?.id } == p.id249        } ?: throw AssertionError("aucun point isolé à l'écran")250    }251252    /** L'interface posée sur la carte, en dp dans le repère de la carte : `[gauche, haut, droite, bas]`. */253    private fun obstacles(): List<DoubleArray> {254        val out = ArrayList<DoubleArray>()255        for (desc in listOf(context.getString(R.string.map_mode_to_3d), context.getString(R.string.map_mode_to_2d))) {256            device.findObject(By.desc(desc))?.visibleBounds?.let { b ->257                out += doubleArrayOf((b.left - MapProbe.originX) / density.toDouble(), (b.top - MapProbe.originY) / density.toDouble(), (b.right - MapProbe.originX) / density.toDouble(), (b.bottom - MapProbe.originY) / density.toDouble())258            }259        }260        device.findObject(By.descStartsWith(context.getString(R.string.map_analysis_a11y, "").trim()))?.visibleBounds?.let { b ->261            out += doubleArrayOf((b.left - MapProbe.originX) / density.toDouble(), (b.top - MapProbe.originY) / density.toDouble(), (b.right - MapProbe.originX) / density.toDouble(), (b.bottom - MapProbe.originY) / density.toDouble())262        }263        return out264    }265266    private fun log(s: String) = Log.i("VraiPrixMapTest", s)267268    // -----------------------------------------------------------------------------------------------------269270    @Test fun t01_ventes_reelles_en_carres_et_backend() {271        launch("layer" to "sales", "map" to "$plateau,15.2")272        waitForPoints(10)273        val info = MapProbe.engine!!274        log("backend=${info.backend} adapter=${info.adapter} driver=${info.driver} software=${info.software}")275        assertTrue(info.backend in setOf("vulkan", "gles"))276        assertEquals(MapStyle.BRAND, main { map().currentBrand })277        // une vente de marché est un carré plein, une vente hors marché un anneau barré : jamais un rond ni un losange278        assertEquals("square", str(layer(MapStyle.Layers.DOTS_SALES)!!.options, "shape"))279        layer(MapStyle.Layers.DOTS_OFF_MARKET)?.let { assertEquals("ring-struck", str(it.options, "shape")) }280        assertTrue(layerIds().none { it in listOf(MapStyle.Layers.DOTS_FIRM, MapStyle.Layers.DOTS_ORDER, MapStyle.Layers.DOTS_NONE, MapStyle.Layers.DOTS_LISTINGS) })281        val pts = points()282        assertTrue(pts.all { it.layer == MapLayer.SALES && it.sale != null })283        assertEquals(pts.count { it.sale?.deMarche == true }, items(MapStyle.Layers.DOTS_SALES).size)284        // les étiquettes : des prix payés (nature observée, genre `sale`)285        val labels = items(MapStyle.Layers.LABELS)286        assertTrue(labels.isNotEmpty())287        assertTrue(labels.all { str(it, "kind") == "sale" && str(it, "nature") == "observe" })288        assertNotNull("un repère est dessiné", find(MapStyle.Layers.DOTS + MapStyle.Layers.LABELS) { true })289        val perf = main { map().getPerf() }!!290        log("perf ventes tiles=${perf.tiles} drawCalls=${perf.drawCalls} triangles=${perf.triangles} labels=${perf.labels} gpuMemory=${perf.gpuMemoryBytes} frameMs=${perf.frameMs} cpuMs=${perf.cpuMs}")291        assertTrue(perf.tiles > 0)292        assertEquals(0, MapProbe.errors)293    }294295    @Test fun t02_rien_sous_l_interface_ni_sur_la_mention_des_sources() {296        launch("layer" to "sales", "map" to "$plateau,15.2")297        waitForPoints(10)298        val w = MapProbe.width / density; val h = MapProbe.height / density299        val obstacles = obstacles()300        assertTrue("boutons trouvés à l'écran", obstacles.size >= 2)301        val drawn = main { map().queryLayer(MapStyle.Layers.LABELS) }302        assertTrue("des étiquettes dessinées", drawn.isNotEmpty())303        for (d in drawn) {304            val r = d.rect305            for (o in obstacles) assertFalse("étiquette ${d.label} sous l'interface", r.left < o[2] && r.right > o[0] && r.top < o[3] && r.bottom > o[1])306            // la mention des sources : bande du bas, à gauche307            assertFalse("étiquette ${d.label} sur la mention des sources", r.bottom > h - 30 && r.left < 320)308            assertTrue("étiquette ${d.label} entière dans la carte", r.left >= -1 && r.right <= w + 1 && r.top >= -1 && r.bottom <= h + 1)309        }310        // aucune étiquette n'en recouvre une autre311        for (i in drawn.indices) for (j in i + 1 until drawn.size) {312            val a = drawn[i].rect; val b = drawn[j].rect313            assertFalse("${drawn[i].label} recouvre ${drawn[j].label}", a.left < b.right - 1 && a.right > b.left + 1 && a.top < b.bottom - 1 && a.bottom > b.top + 1)314        }315        // la mention des sources est à l'écran, lisible316        assertTrue(main { map().attribution.value }.contains("OpenStreetMap"))317        // aux petites échelles : les plaques de groupes non plus318        launch("layer" to "sales", "map" to "$plateau,12.4")319        waitForPoints(10)320        val plates = main { map().queryLayer(MapStyle.Layers.GROUPS) }.filter { it.isCluster }321        assertTrue("des groupes dessinés", plates.isNotEmpty())322        // aucune plaque sous l'interface (boutons repérés par UiAutomator), aucune coupée par un bord de la carte323        val w2 = MapProbe.width / density; val h2 = MapProbe.height / density324        val ui = obstacles()325        assertTrue(ui.size >= 2)326        for (p in plates.filter { it.isPill }) {327            for (o in ui) assertFalse("plaque ${p.label} sous l'interface", p.rect.left < o[2] && p.rect.right > o[0] && p.rect.top < o[3] && p.rect.bottom > o[1])328            assertTrue("plaque ${p.label} coupée par un bord (${p.rect})", p.rect.left >= -0.5 && p.rect.right <= w2 + 0.5 && p.rect.top >= -0.5 && p.rect.bottom <= h2 + 0.5)329            assertFalse("plaque ${p.label} sur la mention des sources", p.rect.bottom > h2 - 26 && p.rect.left < 300)330        }331    }332333    @Test fun t03_toucher_un_groupe_rapproche() {334        launch("layer" to "sales", "map" to "$plateau,12.4")335        waitForPoints(10)336        // la plaque d'un groupe de ventes est au charbon, jamais à l'outremer des valeurs estimées337        val c = layer(MapStyle.Layers.GROUPS)!!.options["cluster"]!!.jsonObject338        assertEquals("#15171c", str(c, "color")); assertEquals("median", str(c, "aggregate"))339        val hit = find(listOf(MapStyle.Layers.GROUPS)) { it.isCluster } ?: throw AssertionError("aucun groupe à l'écran")340        val plates = main { map().queryLayer(MapStyle.Layers.GROUPS) }.filter { it.isCluster }341        log("groupes dessinés : ${plates.size} ; premier : ${plates.first().label} (${plates.first().count} ventes, médiane ${plates.first().value})")342        // chaque plaque compte au moins deux ventes, porte la médiane de leurs prix payés et dit ce qu'elle compte343        assertTrue(plates.all { it.count >= 2 && it.value != null })344        assertTrue("texte dessiné des plaques : ${plates.filter { it.isPill }.map { it.label }}", plates.filter { it.isPill }.all { it.label.orEmpty().contains("ventes · ") })345        assertEquals("{count} ventes · {value}", str(c, "labelTemplate"))346        val before = camera().zoom347        tap(hit.first)348        waitFor("zoom sur le groupe") { camera().zoom > before + 0.4 }349    }350351    @Test fun t04_selection_apercu_et_plomb() {352        launch("layer" to "sales", "map" to "$plateau,15.6")353        waitForPoints(5)354        val (p, at) = lonely { it.amount != null }355        tap(at)356        waitFor("aperçu de la vente", 10_000) { MapProbe.preview == p.id }357        assertEquals(p.id, main { model().selection?.id })358        // l'étiquette du point choisi est la vue ancrée de l'app : le moteur n'en dessine pas une seconde359        waitFor("couche d'étiquettes sans le point choisi") { items(MapStyle.Layers.LABELS).none { str(it, "id") == p.id } }360        assertNull(main { map().selected.value })361        // l'aperçu est déclaré au moteur : aucune étiquette dessous362        waitFor("aperçu déclaré au moteur") { MapProbe.obstacles.any { it.right - it.left > MapProbe.width / density * 0.6 && it.bottom - it.top > 80 } }363        Thread.sleep(900)364        val card = MapProbe.obstacles.first { it.right - it.left > MapProbe.width / density * 0.6 && it.bottom - it.top > 80 }365        for (d in main { map().queryLayer(MapStyle.Layers.LABELS) }) {366            assertFalse("étiquette ${d.label} sous l'aperçu", d.rect.left < card.right && d.rect.right > card.left && d.rect.top < card.bottom && d.rect.bottom > card.top)367        }368        // le point choisi et son plomb restent à l'écran, au-dessus de l'aperçu (la carte glisse s'il le faut)369        waitFor("point choisi au-dessus de l'aperçu") { main { map().project(LngLat(p.lng, p.lat)) }!!.let { it.y < card.top - 20 && it.y > 60 } }370        Thread.sleep(600)371        // le retoucher ferme l'aperçu372        val now = main { map().project(LngLat(p.lng, p.lat)) }!!373        tap(now.x to now.y)374        waitFor("aperçu fermé") { MapProbe.preview == null }375    }376377    @Test fun t05_valeurs_estimees_en_ronds_jamais_en_prix_observes() {378        launch("layer" to "units", "map" to "$plateau,$unitsZoom")379        waitForPoints(10)380        val pts = points()381        assertTrue(pts.all { it.layer == MapLayer.UNITS })382        assertEquals("dot", str(layer(MapStyle.Layers.DOTS_FIRM)!!.options, "shape"))383        layer(MapStyle.Layers.DOTS_ORDER)?.let { assertEquals("ring", str(it.options, "shape")) }384        layer(MapStyle.Layers.DOTS_NONE)?.let { assertEquals("ring", str(it.options, "shape")) }385        assertTrue(layerIds().none { it in listOf(MapStyle.Layers.DOTS_SALES, MapStyle.Layers.DOTS_OFF_MARKET, MapStyle.Layers.DOTS_LISTINGS) })386        assertEquals(pts.count { it.value?.isFirm == true }, items(MapStyle.Layers.DOTS_FIRM).size)387        // une valeur du modèle n'est jamais dite observée ; un ordre de grandeur s'écrit « ≈ » ; sans valeur : aucune étiquette388        val labels = items(MapStyle.Layers.LABELS)389        assertTrue(labels.isNotEmpty())390        assertTrue(labels.none { str(it, "nature") == "observe" || it.containsKey("kind") })391        for (l in labels) {392            val p = pts.first { it.id == str(l, "id") }393            assertNotNull(p.amount)394            if (p.value?.isFirm == true) assertEquals("estime", str(l, "nature")) else { assertEquals("hypothese", str(l, "nature")); assertTrue(str(l, "label")!!.startsWith("≈")) }395        }396        // une propriété sans valeur choisie : l'interface le dit, sans montant397        val none = pts.firstOrNull { it.amount == null && screen(it.lat, it.lng) != null }398        if (none != null) {399            main { model().select(none) }400            waitFor("aperçu sans valeur") { MapProbe.preview == none.id }401            val none_ = context.getString(R.string.value_none)402            waitFor("« $none_ » à l'écran", 6_000) { device.hasObject(By.textContains(none_)) || device.hasObject(By.descContains(none_)) }403            assertTrue(items(MapStyle.Layers.LABELS).none { str(it, "id") == none.id })404            main { model().select(null) }405        } else log("aucune propriété sans valeur dans la vue")406    }407408    @Test fun t06_prix_demandes_en_losanges_etiquette_claire_a_filet_ocre() {409        launch("layer" to "listings", "map" to "$plateau,14.4")410        waitForPoints(5)411        assertEquals("diamond-ring", str(layer(MapStyle.Layers.DOTS_LISTINGS)!!.options, "shape"))412        assertTrue(layerIds().none { it in listOf(MapStyle.Layers.DOTS_SALES, MapStyle.Layers.DOTS_FIRM, MapStyle.Layers.DOTS_ORDER) })413        val labels = items(MapStyle.Layers.LABELS)414        assertTrue(labels.isNotEmpty())415        for (l in labels) {416            assertEquals("listing", str(l, "kind")); assertEquals("observe", str(l, "nature"))417            assertEquals("#ffffff", str(l, "color")); assertEquals("#8c5800", str(l, "strokeColor"))418        }419        // couche « écart » : le prix demandé face à l'intervalle de valeur, dit par une flèche et par la forme420        main { model().chooseAnalysis(Analysis.GAP) }421        waitFor("écart posé") { items(MapStyle.Layers.LABELS).any { str(it, "label")!!.take(1) in listOf("↓", "↑", "=") } || points().none { it.listing?.position?.position != null } }422        val placed = points().count { it.listing?.position?.position != null }423        log("inscriptions situées face à l'intervalle : $placed sur ${points().size}")424        if (placed > 0) assertTrue(items(MapStyle.Layers.DOTS_LISTINGS).any { str(it, "shape") == "diamond" } || str(layer(MapStyle.Layers.DOTS_LISTINGS)!!.options, "shape") == "diamond")425    }426427    @Test fun t07_analyses_de_la_production_et_sonde_des_agregats() {428        launch("layer" to "units", "map" to "$plateau,$unitsZoom")429        waitForPoints(10)430        waitFor("sonde des routes d'agrégats") { main { model().capabilities } != null }431        val caps = main { model().capabilities }!!432        log("production : territoires=${caps.territories} grille des ventes=${caps.salesGrid}")433        // ce que la production ne sert pas ne s'offre pas (aucun repli fabriqué)434        val offered = Analysis.entries.filter { it.offered(caps) }435        if (!caps.territories) assertTrue(offered.none { it.isTerritories })436        if (!caps.salesGrid) assertTrue(Analysis.HEAT !in offered && Analysis.PRICE_CELLS !in offered)437        // incertitude : les valeurs fermes teintées par la largeur de leur intervalle (rampe grège → ocre, pas l'outremer)438        main { model().chooseAnalysis(Analysis.UNCERTAINTY) }439        waitFor("incertitude posée") { items(MapStyle.Layers.DOTS_FIRM).isNotEmpty() && items(MapStyle.Layers.DOTS_FIRM).all { str(it, "color") in listOf("#efe9d8", "#e0cf9c", "#cdab58", "#a97a1d", "#6e4800") } }440        // surface de valeur (route de production) : cases publiées seulement, sous le seuil rien441        main { model().chooseAnalysis(Analysis.VALUE_CELLS) }442        waitFor("grille de valeurs", 45_000) { main { model().valueGrid } != null }443        val g = main { model().valueGrid }!!444        log("grille de valeurs : disponible=${g.disponible} cases publiées=${g.grid.published} motif=${g.motif}")445        if (g.disponible && g.grid.published > 0) {446            waitFor("cases posées") { features(MapStyle.Layers.CELLS).size == g.grid.published }447            assertTrue(layerIds().none { it in MapStyle.Layers.DOTS })448        } else {449            assertNull(layer(MapStyle.Layers.CELLS)); assertNotNull(main { model().analysisNote })450        }451    }452453    @Test fun t08_territoires_grille_et_chaleur_sur_la_preproduction() {454        launch("layer" to "units", "analysis" to "territoires-valeurs", "map" to "45.55,-73.65,9.6", "base_url" to staging, "legend" to "true")455        waitForEngine()456        waitFor("territoires", 60_000) { main { model().territories } != null && !main { model().analysisLoading } }457        waitFor("carte chargée", 60_000) { MapProbe.loaded }458        val t = main { model().territories }!!459        val published = t.map.items.count { it.publie && it.valeur != null && it.limite != null && it.limite in t.shapes }460        log("territoires : ${t.map.items.size} reçus, $published publiés avec limite, ${t.missing} sans limite")461        assertTrue(published > 0)462        waitFor("choroplèthe posée") { features(MapStyle.Layers.TERRITORIES).size == published }463        // sous l'eau du fond : le fleuve reste de l'eau464        assertEquals("below-water", str(layer(MapStyle.Layers.TERRITORIES)!!.options, "slot"))465        // un territoire sous le seuil n'a pas de teinte466        assertTrue(features(MapStyle.Layers.TERRITORIES_NA).none { it["properties"]!!.jsonObject.containsKey("color") })467        assertTrue(layerIds().none { it in MapStyle.Layers.DOTS })468        // la légende dépliée dit la nature469        assertTrue(device.wait(Until.hasObject(By.textContains("ESTIMATION")), 5_000) || device.hasObject(By.textContains("Estimation")))470        // un territoire touché : son panneau471        val hit = find(listOf(MapStyle.Layers.TERRITORIES)) { it.id != null }472        if (hit != null) {473            main { model().legendOpen = false }474            Thread.sleep(500)475            val at = find(listOf(MapStyle.Layers.TERRITORIES)) { it.id != null }!!476            tap(at.first)477            waitFor("territoire choisi") { main { model().pickedTerritory } != null }478        }479        // prix payé médian au pied carré par case : seuils du service480        main { model().chooseAnalysis(Analysis.PRICE_CELLS); model().pendingCamera = com.spboucher.vraiprix.features.map.CameraOrder.Center(45.5231, -73.5817, 12.2, animate = false) }481        waitFor("grille des ventes", 60_000) { main { model().salesGrid } != null && camera().zoom > 12 && !main { model().analysisLoading } }482        val g = main { model().salesGrid }!!483        log("grille des ventes : disponible=${g.disponible} publiées=${g.grid.published} seuil case=${g.seuilCase}")484        if (g.disponible) {485            waitFor("cases posées") { features(MapStyle.Layers.CELLS).size == g.grid.published }486            for (i in g.grid.values.indices) if (g.grid.counts[i] < g.seuilCase) assertNull(g.grid.values[i])487        }488        // chaleur : densité des ventes, aucun prix489        main { model().chooseAnalysis(Analysis.HEAT) }490        waitFor("chaleur posée", 45_000) { layer(MapStyle.Layers.HEAT) != null }491        assertNull(layer(MapStyle.Layers.CELLS))492    }493494    @Test fun t09_bascule_2d_3d_batiments_teintes_et_provenance_des_hauteurs() {495        launch("layer" to "units", "map" to "$plateau,$unitsZoom")496        waitForPoints(10)497        assertEquals(0.0, camera().pitch, 0.5)498        assertNull(layer(MapStyle.Layers.BUILDINGS))499        device.findObject(By.desc(context.getString(R.string.map_mode_to_3d))).click()500        waitFor("inclinaison 3D") { camera().pitch > 30 }501        assertEquals(KaMode.THREE_D, main { map().mode.value })502        // la vue inclinée montre plus de terrain : la zone est relue (en quarts s'il le faut), sans passer aux secteurs503        Thread.sleep(1200)504        waitFor("relecture de la vue inclinée", 60_000) { !main { model().loading } && points().isNotEmpty() }505        assertFalse("la vue inclinée garde les propriétés une à une", main { model().sectorMode })506        // les vrais bâtiments teintés par la valeur ferme ; jamais une hauteur tirée d'une valeur507        waitFor("bâtiments teintés", 30_000) { layer(MapStyle.Layers.BUILDINGS) != null }508        assertEquals(points().count { it.value?.isFirm == true }, items(MapStyle.Layers.BUILDINGS).size)509        // vue inclinée : les étiquettes sont posées par le moteur, sans recouvrement510        assertEquals("true", str(layer(MapStyle.Layers.LABELS)!!.options, "declutter"))511        val b = layer(MapStyle.Layers.BUILDINGS)!!512        assertEquals("false", str(b.options, "heights"))513        val data = items(MapStyle.Layers.BUILDINGS)514        assertTrue(data.isNotEmpty() && data.all { str(it, "nature") == "estime" && !it.containsKey("height") })515        Thread.sleep(2500)516        // un bâtiment touché : sa hauteur et, toujours, sa provenance517        val w = MapProbe.width / density; val h = MapProbe.height / density518        val base = main {519            var out: Pair<Double, Double>? = null520            var y = h * 0.35521            while (out == null && y < h * 0.8) {522                var x = 40.0523                while (out == null && x < w - 100) {524                    if (map().queryRendered(x, y).let { fs -> fs.firstOrNull()?.let { it.source == "base" && it.isBuilding } == true }) out = x to y525                    x += 22526                }527                y += 22528            }529            out530        }531        if (base != null) {532            tap(base)533            waitFor("bâtiment choisi ou point choisi", 8_000) { main { model().pickedBuilding != null || model().selection != null } }534            main { model().pickedBuilding }?.let { log("bâtiment : hauteur=${it.heightM} provenance=${it.source} levé=${it.year}"); assertTrue(it.source in listOf("mesuree", "bloc", "etages", "estimee", "inconnue")) }535        } else log("aucun bâtiment nu trouvé sous la grille de recherche")536        val perf = main { map().getPerf() }!!537        log("perf 3D tiles=${perf.tiles} drawCalls=${perf.drawCalls} triangles=${perf.triangles} gpuMemory=${perf.gpuMemoryBytes} frameMs=${perf.frameMs} cpuMs=${perf.cpuMs}")538        main { model().pickedBuilding = null; model().select(null) }539        device.findObject(By.desc(context.getString(R.string.map_mode_to_2d))).click()540        waitFor("retour à plat") { camera().pitch < 1 }541        waitFor("teinte des bâtiments retirée") { layer(MapStyle.Layers.BUILDINGS) == null }542    }543544    @Test fun t10_rotation_de_l_ecran() {545        launch("layer" to "sales", "map" to "$plateau,15.2")546        waitForPoints(10)547        val before = camera(); val engine = MapProbe.engine!!.generation; val w = MapProbe.width548        device.setOrientationLeft()549        waitFor("carte redimensionnée") { MapProbe.width != w && MapProbe.controller != null }550        waitFor("points de retour", 45_000) { points().isNotEmpty() && layer(MapStyle.Layers.DOTS_SALES) != null }551        assertEquals("le moteur n'est pas recréé", engine, MapProbe.engine!!.generation)552        assertEquals(before.center.lat, camera().center.lat, 2e-3); assertEquals(before.zoom, camera().zoom, 0.05)553        device.setOrientationNatural()554        waitFor("retour à l'orientation d'origine") { MapProbe.width == w }555    }556557    @Test fun t11_arriere_plan_puis_retour() {558        launch("layer" to "sales", "map" to "$plateau,15.2")559        waitForPoints(10)560        val before = camera(); val engine = MapProbe.engine!!.generation; val n = points().size561        scenario!!.moveToState(Lifecycle.State.CREATED)562        Thread.sleep(1500)563        scenario!!.moveToState(Lifecycle.State.RESUMED)564        waitFor("carte de retour") { MapProbe.controller != null && main { map().getPerf() } != null }565        assertEquals(engine, MapProbe.engine!!.generation)566        assertEquals(before.zoom, camera().zoom, 0.01)567        assertEquals(n, points().size)568        assertNotNull(find(MapStyle.Layers.DOTS + MapStyle.Layers.LABELS) { true })569        assertEquals(0, MapProbe.errors)570    }571572    @Test fun t12_theme_sombre() {573        launch("layer" to "units", "map" to "$plateau,$unitsZoom", "appearance" to "dark")574        waitForPoints(10)575        assertEquals(KaThemes.MIDNIGHT, main { map().currentTheme })576        // les teintes de la nuit : classes de valeur claires sur fond sombre577        assertTrue(items(MapStyle.Layers.DOTS_FIRM).all { str(it, "color") in listOf("#293a57", "#305088", "#3666bf", "#4e80e4", "#6c98f8") })578        launch("layer" to "units", "map" to "$plateau,$unitsZoom", "appearance" to "light")579        waitForPoints(10)580        assertEquals(KaThemes.SIGNATURE, main { map().currentTheme })581    }582583    @Test fun t13_comparables_sur_la_carte_et_sur_la_fiche() {584        launch("layer" to "units", "map" to "$plateau,$unitsZoom")585        waitForPoints(10)586        val firm = points().first { it.value?.isFirm == true && screen(it.lat, it.lng) != null }587        main { model().select(firm) }588        waitFor("aperçu de la propriété") { MapProbe.preview == firm.id }589        main { model().showComparables(firm) }590        waitFor("comparables lus", 45_000) { main { model().comparables != null || model().comparablesFailed } }591        val c = main { model().comparables } ?: throw AssertionError("comparables non servis")592        val located = c.comps.items.count { it.hasCoordinate && !it.memeUnite }593        log("comparables : ${c.comps.items.size} ventes, $located situées")594        if (located > 0) {595            waitFor("ventes comparables posées") { items(MapStyle.Layers.COMPARABLES).size == located }596            // ce sont des ventes réelles : genre `sale`, nature observée, reliées au sujet597            assertTrue(items(MapStyle.Layers.COMPARABLES).all { str(it, "kind") == "sale" && str(it, "nature") == "observe" })598            assertEquals(located, features(MapStyle.Layers.LINKS).size)599            // la carte s'éloigne pour les cadrer : la propriété reste choisie, ses comparables restent tracés, même si600            // la zone contient alors trop de propriétés pour les montrer une à une601            Thread.sleep(2500)602            waitFor("lecture de la vue cadrée") { !main { model().loading } }603            Thread.sleep(800)604            assertEquals(firm.id, main { model().selection?.id })605            assertEquals(located, items(MapStyle.Layers.COMPARABLES).size)606            assertNull("les secteurs se taisent pendant les comparables", layer(MapStyle.Layers.SECTORS))607        }608        // la fiche : sa carte de comparables, sans geste609        launch("open" to "propriete/" + firm.property!!.id)610        val desc = context.getString(R.string.property_comps_map_a11y, 0).substringBefore(" :")611        var seen = false612        for (i in 0 until 14) {613            if (device.hasObject(By.descStartsWith(desc))) { seen = true; break }614            device.swipe(device.displayWidth / 2, (device.displayHeight * 0.72).toInt(), device.displayWidth / 2, (device.displayHeight * 0.30).toInt(), 24)615            Thread.sleep(700)616        }617        if (located > 0) assertTrue("carte des comparables de la fiche", seen) else log("fiche sans comparable situé : pas de carte attendue (vue=$seen)")618        if (seen) {619            // la carte n'a pas de geste : un glisser parti d'elle fait défiler la fiche620            device.swipe(device.displayWidth / 2, (device.displayHeight * 0.72).toInt(), device.displayWidth / 2, (device.displayHeight * 0.52).toInt(), 20)621            Thread.sleep(900)622            val before = device.findObject(By.descStartsWith(desc))?.visibleBounds623            if (before != null && before.height() > 80) {624                device.swipe(before.centerX(), before.centerY(), before.centerX(), before.centerY() - (120 * density).toInt(), 30)625                Thread.sleep(900)626                val after = device.findObject(By.descStartsWith(desc))?.visibleBounds627                assertTrue("la fiche défile quand le doigt part de la carte ($before → $after)", after == null || after.top < before.top - 20 || after.height() < before.height() - 20)628            }629        }630    }631632    @Test fun t14_opengl_es_impose() {633        launch("layer" to "sales", "map" to "$plateau,15.2", "backend" to "gles")634        waitForPoints(10)635        val info = MapProbe.engine!!636        log("backend imposé=${info.backend} adapter=${info.adapter} driver=${info.driver}")637        assertEquals("gles", info.backend)638        assertNotNull(find(MapStyle.Layers.DOTS + MapStyle.Layers.LABELS) { true })639        val perf = main { map().getPerf() }!!640        log("perf GLES tiles=${perf.tiles} drawCalls=${perf.drawCalls} triangles=${perf.triangles} gpuMemory=${perf.gpuMemoryBytes} frameMs=${perf.frameMs} cpuMs=${perf.cpuMs}")641        assertTrue(perf.tiles > 0)642        assertEquals(0, MapProbe.errors)643    }644645    @Test fun t15_les_etiquettes_suivent_la_police_du_systeme() {646        launch("layer" to "sales", "map" to "$plateau,15.2")647        waitForPoints(10)648        val normal = main { map().queryLayer(MapStyle.Layers.LABELS) }.filter { !it.isCluster }649        assertTrue(normal.isNotEmpty())650        val h1 = normal.map { it.rect.bottom - it.rect.top }.average()651        shell("settings put system font_scale 1.3")652        Thread.sleep(1500)653        launch("layer" to "sales", "map" to "$plateau,15.2")654        waitForPoints(10)655        Thread.sleep(1500)656        val large = main { map().queryLayer(MapStyle.Layers.LABELS) }.filter { !it.isCluster }657        assertTrue(large.isNotEmpty())658        val h2 = large.map { it.rect.bottom - it.rect.top }.average()659        log("hauteur moyenne d'une étiquette : $h1 dp à 1,0 ; $h2 dp à 1,3 ; ${normal.size} puis ${large.size} étiquettes")660        assertTrue("les étiquettes grossissent ($h1 → $h2)", h2 > h1 * 1.12)661        assertTrue("moins d'étiquettes, ou autant", large.size <= normal.size)662        for (i in large.indices) for (j in i + 1 until large.size) {663            val a = large[i].rect; val b = large[j].rect664            assertFalse("${large[i].label} recouvre ${large[j].label}", a.left < b.right - 1 && a.right > b.left + 1 && a.top < b.bottom - 1 && a.bottom > b.top + 1)665        }666    }667668    @Test fun t17_filtres_qui_changent_pendant_qu_un_doigt_glisse() {669        launch("layer" to "sales", "map" to "$plateau,15.2")670        waitForPoints(10)671        val cx = (MapProbe.originX + MapProbe.width / 2f).toInt(); val cy = (MapProbe.originY + MapProbe.height / 2f).toInt()672        val errors = MapProbe.errors; val engine = MapProbe.engine!!.generation673        // un doigt glisse sur la carte (fil d'essai) pendant que la couche, la période, le type et l'analyse changent674        val drag = Thread {675            repeat(6) { i ->676                val pts = Array(30) { k -> android.graphics.Point(cx + (if (i % 2 == 0) 1 else -1) * (k * 9 - 130), cy + (k * 5 - 70)) }677                device.swipe(pts, 4)678            }679        }680        drag.start()681        val months = listOf(6, 12, 60, 24)682        var n = 0683        while (drag.isAlive) {684            main {685                val m = model()686                when (n % 5) {687                    0 -> m.applyFilters(m.filters.copy(months = months[(n / 5) % months.size]))688                    1 -> m.chooseLayer(MapLayer.LISTINGS)689                    2 -> m.chooseAnalysis(Analysis.GAP)690                    3 -> m.chooseLayer(MapLayer.UNITS)691                    else -> { m.chooseLayer(MapLayer.SALES); m.applyFilters(m.filters.copy(type = if (m.filters.type.isEmpty()) "condo" else "")) }692                }693            }694            n++695            Thread.sleep(90)696        }697        drag.join()698        log("filtres changés $n fois pendant six glissers")699        assertTrue(n >= 10)700        // la carte vit toujours : même moteur, aucune erreur, elle répond et se redessine701        main { model().chooseLayer(MapLayer.SALES); model().applyFilters(model().filters.copy(type = "", months = 24)) }702        waitFor("ventes relues après la rafale", 60_000) { points().isNotEmpty() && !main { model().loading } && layer(MapStyle.Layers.DOTS_SALES) != null }703        assertEquals(engine, MapProbe.engine!!.generation)704        assertEquals(errors, MapProbe.errors)705        assertNotNull(main { map().getPerf() })706        assertNotNull(find(MapStyle.Layers.DOTS + MapStyle.Layers.LABELS) { true })707    }708709    @Test fun t16_zone_gardee_puis_mode_avion() {710        // une petite zone de Sherbrooke, gardée du zoom 0 au zoom 14711        val zone = MapBounds(-71.900, 45.398, -71.884, 45.408)712        val off = MapOffline.get(context)713        launch("layer" to "sales", "map" to "45.403,-71.892,14.2")714        waitForEngine()715        waitFor("lecture des ventes de la zone", 60_000) { !main { model().loading } && !main { model().zoomedOut } && MapProbe.loaded }716        Thread.sleep(1500)717        val online = points().size718        runBlocking { off.regions().forEach { off.remove(it.region.id) } }719        val tiles = MapOffline.keep(context, "Sherbrooke (essai)", zone)!!720        waitFor("zone téléchargée ($tiles tuiles)", 180_000) { runBlocking { off.regions().any { it.region.id == MapOffline.regionId(zone) && (it.region.state == KaRegionState.COMPLETE || it.completedAt != null) } } }721        val region = runBlocking { off.regions().first { it.region.id == MapOffline.regionId(zone) } }722        log("zone gardée : $tiles tuiles demandées, ${region.region.bytes} octets, état ${region.region.state}")723        shell("cmd connectivity airplane-mode enable")724        Thread.sleep(2500)725        try {726            launch("layer" to "sales", "map" to "45.403,-71.892,14.2")727            waitForEngine()728            waitFor("carte dessinée sans réseau", 45_000) { MapProbe.loaded && main { map().getPerf() }?.let { it.tiles > 0 } == true }729            waitFor("lecture finie") { !main { model().loading } }730            Thread.sleep(1200)731            val m = main { model() }732            log("hors connexion : ${points().size} ventes (en ligne : $online), copie du ${main { m.staleSince }}, erreur=${main { m.error }}")733            // les ventes viennent de la copie de l'appareil et l'écran le dit avec sa date ; à défaut, l'écran dit la panne734            if (online > 0 && main { m.staleSince } != null) {735                assertEquals(online, points().size)736                assertTrue(device.wait(Until.hasObject(By.textStartsWith(context.getString(R.string.map_stale, "").trim().substringBefore("données") + "données")), 5_000))737            } else if (online > 0) assertNotNull("sans copie : la panne est dite", main { m.error })738        } finally {739            shell("cmd connectivity airplane-mode disable")740            runBlocking { off.remove(MapOffline.regionId(zone)) }741        }742    }743}744
Files main
Menu

Theme