SPB Git

Repository Public

MapScreensTest.kt 34.1 KB 594 lines kotlin

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project          : Immo-Ka Android10 * File             : app/src/androidTest/kotlin/com/spboucher/immoka/MapScreensTest.kt11 * Description      : essais sur appareil des écrans de carte (KA Maps) contre12 *                    l'API de production en lecture seule — pastilles et13 *                    backend graphique, zones sans pastille, groupe touché,14 *                    sélection (marqueur à la porte, aperçu, lot tracé sur une15 *                    propriété de Montréal, fiche ouverte par le marqueur), 2D16 *                    / 3D, immeuble visé et provenance de sa hauteur, rotation,17 *                    arrière-plan, thèmes, zones de marché, cartes de la fiche,18 *                    OpenGL ES imposé, taille de police du système, zone gardée19 *                    puis mode avion.20 * Module           : androidTest21 * Repository       : https://git.spboucher.ai/immo-ka-android22 * Project Website  : https://www.immo-ka.com23 * Created          : 2026-12-0124 * Last Modified    : 2026-12-0125 *26 * =============================================================================27 * AUTHOR & PROFESSIONAL AFFILIATION28 * =============================================================================29 *30 * Author           : Simon-Pierre Boucher31 * Position         : Professor of Finance32 * Institution      : Université du Québec en Outaouais (UQO)33 * Department       : Département des sciences administratives34 * Organization     : SP Boucher35 *36 * Website          : https://spboucher.ai37 * Git              : https://git.spboucher.ai38 *39 * =============================================================================40 * OFFICIAL CONTACT DIRECTORY41 * =============================================================================42 *43 * General          : info@spboucher.ai44 * Professional     : contact@spboucher.ai45 * Direct           : simon@spboucher.ai46 * Research         : research@spboucher.ai47 * Development      : dev@spboucher.ai48 * Support          : support@spboucher.ai49 * Security/Admin   : admin@spboucher.ai50 * Notifications    : notifications@spboucher.ai51 *52 * Preferred Contact: contact@spboucher.ai53 *54 * =============================================================================55 * COPYRIGHT & INTELLECTUAL PROPERTY56 * =============================================================================57 *58 * Copyright (c) 202659 * Simon-Pierre Boucher60 *61 * All rights reserved where applicable.62 *63 * This file is governed by the applicable project license,64 * copyright notices, institutional agreements and relevant law.65 *66 * Unless expressly authorized by the applicable license or67 * rights holder, copying, redistribution, sublicensing,68 * publication and commercial exploitation are not permitted.69 *70 * Existing third-party rights and notices remain unaffected.71 *72 * =============================================================================73 * CONFIDENTIALITY & SECURITY74 * =============================================================================75 *76 * Classification   : Public77 * Distribution     : Public repository; use is governed by the project license78 * Security Contact : admin@spboucher.ai79 *80 * Access to this source does not independently grant permission81 * to redistribute or disclose confidential materials.82 *83 * Do not embed credentials, private keys, access tokens,84 * certificates or confidential personal information.85 *86 * =============================================================================87 * LICENSE & MAINTENANCE88 * =============================================================================89 *90 * License          : None specified (no license file in this repository)91 * Maintainer       : Simon-Pierre Boucher92 * Technical Contact: dev@spboucher.ai93 *94 * =============================================================================95 * END OF SP BOUCHER SOURCE HEADER96 * =============================================================================97 */9899package com.spboucher.immoka100101import ai.spboucher.kamaps.KaDrawnItem102import ai.spboucher.kamaps.KaFeature103import ai.spboucher.kamaps.KaLayerData104import ai.spboucher.kamaps.KaMapController105import ai.spboucher.kamaps.KaRegionState106import android.content.Intent107import android.util.Log108import androidx.lifecycle.Lifecycle109import androidx.test.core.app.ActivityScenario110import androidx.test.ext.junit.runners.AndroidJUnit4111import androidx.test.platform.app.InstrumentationRegistry112import androidx.test.uiautomator.By113import androidx.test.uiautomator.UiDevice114import androidx.test.uiautomator.Until115import com.spboucher.immoka.app.MainActivity116import com.spboucher.immoka.core.map.MapBounds117import com.spboucher.immoka.core.map.MapOffline118import com.spboucher.immoka.features.explore.MapProbe119import com.spboucher.immoka.features.explore.MapStyle120import com.spboucher.immoka.features.listing.ListingMapProbe121import kotlinx.coroutines.runBlocking122import kotlinx.serialization.json.jsonArray123import kotlinx.serialization.json.jsonObject124import kotlinx.serialization.json.jsonPrimitive125import org.junit.After126import org.junit.Assert.assertEquals127import org.junit.Assert.assertNotNull128import org.junit.Assert.assertTrue129import org.junit.FixMethodOrder130import org.junit.Test131import org.junit.runner.RunWith132import org.junit.runners.MethodSorters133import kotlin.math.abs134135@RunWith(AndroidJUnit4::class)136@FixMethodOrder(MethodSorters.NAME_ASCENDING)137class MapScreensTest {138    private val inst = InstrumentationRegistry.getInstrumentation()139    private val device: UiDevice = UiDevice.getInstance(inst)140    private val context get() = inst.targetContext141    private val density get() = context.resources.displayMetrics.density142    private var scenario: ActivityScenario<MainActivity>? = null143    private val tag = "ImmoKaMapTest"144145    /** Plateau-Mont-Royal : assez de propriétés pour des groupes et des pastilles seules ; dans l'agglomération de Montréal (lots). */146    private val plateau = "45.5245,-73.577"147148    @After fun close() {149        shell("cmd connectivity airplane-mode disable")150        shell("settings put system font_scale 1.0")151        runCatching { device.setOrientationNatural() }152        scenario?.close(); scenario = null153    }154155    private fun shell(cmd: String): String = inst.uiAutomation.executeShellCommand(cmd).use { fd -> android.os.ParcelFileDescriptor.AutoCloseInputStream(fd).bufferedReader().readText() }156157    /** Lance l'app sur l'API de production, base locale jetable. */158    private fun launch(vararg extras: Pair<String, String>, tab: String? = "explore") {159        scenario?.close()160        MapProbe.loaded = false; MapProbe.controller = null; MapProbe.preview = null; MapProbe.lot = null; MapProbe.building = null; MapProbe.pin = null161        ListingMapProbe.locationLoaded = false; ListingMapProbe.lot = null; ListingMapProbe.comparablesLoaded = false; ListingMapProbe.comparables = 0162        val i = Intent(context, MainActivity::class.java).putExtra("in_memory", true).putExtra("base_url", "https://www.immo-ka.com")163        if (tab != null) i.putExtra("tab", tab)164        for ((k, v) in extras) i.putExtra(k, v)165        scenario = ActivityScenario.launch(i)166    }167168    private fun <T> main(block: () -> T): T {169        var out: Result<T>? = null170        inst.runOnMainSync { out = runCatching(block) }171        return out!!.getOrThrow()172    }173174    private fun waitFor(what: String, timeoutMs: Long = 30_000, cond: () -> Boolean) {175        val end = System.currentTimeMillis() + timeoutMs176        while (System.currentTimeMillis() < end) { if (runCatching(cond).getOrDefault(false)) return; Thread.sleep(200) }177        throw AssertionError("délai dépassé : $what")178    }179180    private fun map(): KaMapController = MapProbe.controller ?: throw AssertionError("carte absente")181182    private fun count(layer: String): Int = main { (MapProbe.controller?.layer(layer)?.data as? KaLayerData.Json)?.element?.jsonArray?.size ?: 0 }183    private fun markerCount(): Int = count(MapStyle.Layers.LISTINGS)184185    /** Attend la carte, son premier chargement complet et des pastilles venues du serveur. */186    private fun waitForListings() {187        waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null }188        // l'API de production met parfois plus de 45 s à répondre quand la machine d'essai est chargée189        waitFor("pastilles de l'API", 90_000) { markerCount() > 0 }190        waitFor("carte chargée", 45_000) { MapProbe.loaded }191        Thread.sleep(1200)192    }193194    /** Pastilles et groupes dessinés (rectangles en dp, repère de la carte). */195    private fun drawn(): List<KaDrawnItem> = main { map().queryLayer(MapStyle.Layers.LISTINGS) + map().queryLayer(MapStyle.Layers.GROUPS) }196197    /** Vrai si le centre de l'élément est dans la partie dégagée de la carte : ni sous une zone d'interface, ni sous le tiroir. */198    private fun free(i: KaDrawnItem): Boolean {199        val x = i.rect.centerX; val y = i.rect.centerY200        val w = MapProbe.width / density; val h = MapProbe.height / density201        if (x < 12 || x > w - 12 || y < 12 + MapProbe.topInset || y > h - 12 - MapProbe.bottomInset) return false202        return MapProbe.obstacles.none { o -> x > o.left - 2 && x < o.right + 2 && y > o.top - 2 && y < o.bottom + 2 }203    }204205    /** Une vraie pastille (pas un marqueur réduit à son point). */206    private fun KaDrawnItem.isListingPill() = !isCluster && isPill207208    private fun tap(i: KaDrawnItem) { device.click((MapProbe.originX + i.rect.centerX * density).toInt(), (MapProbe.originY + i.rect.centerY * density).toInt()) }209210    private fun camera() = main { map().getCamera() }211212    /** Sélectionne une propriété seule dessinée dans la partie dégagée ; rend son identifiant. */213    private fun selectOne(): String {214        var hit: KaDrawnItem? = null215        val cx = MapProbe.width / density / 2.0; val cy = MapProbe.height / density / 2.0216        // la plus proche du centre de la carte : le choix ne dépend pas de l'ordre de dessin217        waitFor("une pastille seule à l'écran", 20_000) {218            hit = drawn().filter { it.isListingPill() && it.id != null && free(it) && it.layer == MapStyle.Layers.LISTINGS }219                .minByOrNull { (it.rect.centerX - cx) * (it.rect.centerX - cx) + (it.rect.centerY - cy) * (it.rect.centerY - cy) }220            hit != null221        }222        Log.i(tag, "propriété choisie : ${hit!!.id} « ${hit!!.label} » en ${hit!!.rect.centerX.toInt()},${hit!!.rect.centerY.toInt()} dp")223        tap(hit!!)224        waitFor("aperçu de la propriété", 12_000) { MapProbe.preview == hit!!.id }225        return hit!!.id!!226    }227228    // -----------------------------------------------------------------------------------------------------229230    @Test fun t01_pastilles_de_la_production_et_backend() {231        launch("camera" to "$plateau,14.6")232        waitForListings()233        val info = MapProbe.engine!!234        Log.i(tag, "backend=${info.backend} adapter=${info.adapter} driver=${info.driver} software=${info.software}")235        assertTrue(info.backend in setOf("vulkan", "gles"))236        assertTrue("des pastilles de l'API", markerCount() > 10)237        // les identifiants sont ceux du serveur (« source:id »), les étiquettes des prix demandés238        val first = main { (map().layer(MapStyle.Layers.LISTINGS)!!.data as KaLayerData.Json).element.jsonArray.first().jsonObject }239        assertTrue(first["id"]!!.jsonPrimitive.content.contains(":"))240        assertEquals("observe", first["nature"]!!.jsonPrimitive.content)241        assertTrue("une pastille ou un groupe est dessiné", drawn().isNotEmpty())242        assertEquals("immoka", main { map().currentBrand?.id })243        val perf = main { map().getPerf() }!!244        Log.i(tag, "perf tiles=${perf.tiles} drawCalls=${perf.drawCalls} triangles=${perf.triangles} labels=${perf.labels} frameMs=${perf.frameMs} cpuMs=${perf.cpuMs} taille=${MapProbe.width}x${MapProbe.height} densite=$density")245        assertTrue(perf.tiles > 0)246        assertEquals(0, MapProbe.errors)247    }248249    /**250     * Zones de l'interface dans le repère de la carte (dp) : les éléments déclarés par l'app (boutons, légende, aperçu),251     * la mention des sources (lue dans l'arbre d'accessibilité) et les marges permanentes (haut recouvert, tiroir).252     */253    private fun zones(): List<ai.spboucher.kamaps.KaScreenRect> {254        val w = MapProbe.width / density.toDouble(); val h = MapProbe.height / density.toDouble()255        val out = ArrayList(MapProbe.obstacles)256        device.findObject(By.textContains("OpenStreetMap"))?.visibleBounds?.let { b ->257            out += ai.spboucher.kamaps.KaScreenRect((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        if (MapProbe.bottomInset > 0) out += ai.spboucher.kamaps.KaScreenRect(0.0, h - MapProbe.bottomInset, w, h)260        if (MapProbe.topInset > 0) out += ai.spboucher.kamaps.KaScreenRect(0.0, 0.0, w, MapProbe.topInset.toDouble())261        return out262    }263264    /** Compte, pour une vue, les pastilles et les plaques sous une zone de l'interface ou coupées par le cadre. */265    private fun underOrCut(view: String): Int {266        val w = MapProbe.width / density.toDouble(); val h = MapProbe.height / density.toDouble()267        val z = zones()268        fun over(i: KaDrawnItem, o: ai.spboucher.kamaps.KaScreenRect) = i.rect.right > o.left + 1 && i.rect.left < o.right - 1 && i.rect.bottom > o.top + 1 && i.rect.top < o.bottom - 1269        fun cut(i: KaDrawnItem) = i.rect.left < -0.5 || i.rect.top < -0.5 || i.rect.right > w + 0.5 || i.rect.bottom > h + 0.5270        // une plaque est une grappe ou un regroupement du serveur ; une pastille réduite à son point n'est pas comptée271        val plates = drawn().filter { it.isCluster || it.isPill }272        val under = plates.filter { i -> z.any { over(i, it) } }273        val clipped = plates.filter { cut(it) }274        Log.i(tag, "$view : zones=${z.size} plaques et pastilles=${plates.size} (groupes ${plates.count { it.isCluster }}) sous l'interface=${under.size} coupées par le cadre=${clipped.size}" +275            (under + clipped).take(3).joinToString("") { " [« ${it.label} » ${it.rect.left.toInt()},${it.rect.top.toInt()}–${it.rect.right.toInt()},${it.rect.bottom.toInt()}]" })276        assertTrue("$view : des plaques ou des pastilles sont dessinées", plates.isNotEmpty())277        return under.size + clipped.size278    }279280    @Test fun t02_aucune_plaque_ni_pastille_sous_l_interface_ni_coupee() {281        var bad = 0282        // quatre vues : pastilles seules, mélange, grappes du moteur, regroupements du serveur283        for ((view, cam) in listOf("z15,6" to "$plateau,15.6", "z14,6" to "$plateau,14.6", "z13,6" to "$plateau,13.6", "z11,3" to "45.53,-73.62,11.3")) {284            launch("camera" to cam)285            waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null }286            waitFor("pastilles ou regroupements de l'API", 45_000) { markerCount() > 0 || count(MapStyle.Layers.GROUPS) > 0 }287            waitFor("carte chargée", 45_000) { MapProbe.loaded }288            waitFor("zones déclarées") { MapProbe.obstacles.isNotEmpty() }289            assertTrue("la mention des sources est dans l'arbre d'accessibilité", device.wait(Until.hasObject(By.textContains("OpenStreetMap")), 8_000))290            Thread.sleep(2500)291            bad += underOrCut(view)292        }293        assertEquals("aucune plaque ni pastille sous l'interface ni coupée par le cadre, sur les quatre vues", 0, bad)294    }295296    @Test fun t02b_selection_rien_sous_le_panneau_ni_coupe() {297        launch("camera" to "$plateau,15.6")298        waitForListings()299        selectOne()300        waitFor("marqueur de la sélection posé") { MapProbe.pin != null && MapProbe.pin!!.width > 0 }301        Thread.sleep(2500)302        assertEquals("aucune plaque sous le panneau de la sélection, les boutons, la mention des sources, ni coupée", 0, underOrCut("sélection"))303        // la pastille sélectionnée du moteur n'est pas dessinée sous le marqueur maison, mais reste connue304        assertEquals("true", main { map().layer(MapStyle.Layers.LISTINGS)!!.options["hideSelected"]!!.jsonPrimitive.content })305    }306307    @Test fun t03_toucher_un_groupe_zoome() {308        launch("camera" to "$plateau,13.6")309        waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null }310        // plus de 4 000 propriétés dans l'emprise : le serveur regroupe ; sinon le moteur regroupe311        waitFor("pastilles ou regroupements de l'API", 45_000) { markerCount() > 0 || count(MapStyle.Layers.GROUPS) > 0 }312        waitFor("carte chargée", 45_000) { MapProbe.loaded }313        var hit: KaDrawnItem? = null314        waitFor("un groupe à l'écran", 20_000) { hit = drawn().firstOrNull { (it.isCluster || it.layer == MapStyle.Layers.GROUPS) && free(it) }; hit != null }315        Log.i(tag, "groupe : ${if (hit!!.isCluster) "moteur (médiane ${hit!!.value}, ${hit!!.count} propriétés, « ${hit!!.label} »)" else "serveur (${hit!!.label})"}")316        val before = camera().zoom317        tap(hit!!)318        waitFor("zoom sur le groupe") { camera().zoom > before + 0.4 }319    }320321    /** Nombre de pixels au rouge de la porte dans la carte, hors d'un cadre donné (px de la fenêtre). */322    private fun doorRedPixels(except: com.spboucher.immoka.design.brand.Box?): Int {323        val bmp = inst.uiAutomation.takeScreenshot() ?: throw AssertionError("capture impossible")324        var n = 0325        val x0 = MapProbe.originX.toInt(); val y0 = MapProbe.originY.toInt()326        val x1 = minOf(bmp.width, x0 + MapProbe.width); val y1 = minOf(bmp.height, y0 + MapProbe.height)327        var y = y0328        while (y < y1) {329            var x = x0330            while (x < x1) {331                if (except == null || x < except.left - 6 || x > except.right + 6 || y < except.top - 6 || y > except.bottom + 6) {332                    val c = bmp.getPixel(x, y)333                    val r = (c shr 16) and 0xff; val g = (c shr 8) and 0xff; val bl = c and 0xff334                    if (r > 170 && g < 95 && bl < 105 && r - g > 90) n++335                }336                x += 2337            }338            y += 2339        }340        bmp.recycle()341        return n342    }343344    @Test fun t04_selection_marqueur_a_la_porte_apercu_et_lot() {345        launch("camera" to "$plateau,16.3")346        waitForListings()347        val redBefore = doorRedPixels(null)348        val uid = selectOne()349        waitFor("sélection connue du moteur") { main { map().selected.value?.id } == uid }350        // le marqueur de la sélection (vue ancrée) est posé dans la carte, sur la coordonnée de la propriété351        waitFor("marqueur de la sélection posé") { MapProbe.pin != null && MapProbe.pin!!.width > 0 }352        val pin = MapProbe.pin!!353        assertTrue("marqueur dans la carte", pin.left >= MapProbe.originX - 1 && pin.right <= MapProbe.originX + MapProbe.width + 1 && pin.top >= MapProbe.originY - 1)354        // propriété de l'agglomération de Montréal : son lot est lu dans le fond (superficie de la Ville)355        waitFor("lot de la Ville de Montréal trouvé sous la propriété", 20_000) { (MapProbe.lot?.areaM2 ?: 0.0) > 0 }356        Log.i(tag, "lot : superficie ${MapProbe.lot?.areaM2} m² (Ville de Montréal), contour rendu par la requête : ${MapProbe.lot?.geometry != null}")357        // l'immeuble et le lot sont tracés au rouge de la porte : compté sur l'image, hors du marqueur (sur un petit358        // écran une partie du lot passe sous le panneau de la sélection : le seuil est bas)359        Thread.sleep(1500)360        var redAfter = 0361        waitFor("immeuble et lot tracés en rouge sur la carte", 10_000) { redAfter = doorRedPixels(MapProbe.pin); redAfter > redBefore + 40 }362        Log.i(tag, "pixels au rouge de la porte dans la carte (un sur quatre compté) : $redBefore avant la sélection, $redAfter après")363        // toucher le marqueur ouvre la fiche364        val p = MapProbe.pin!!365        device.click((p.left + p.width / 2).toInt(), (p.top + p.height * 0.4f).toInt())366        assertTrue("fiche ouverte par le marqueur", device.wait(Until.hasObject(By.text(context.getString(R.string.view_listing))), 20_000))367    }368369    @Test fun t05_bascule_2d_3d() {370        launch("camera" to "$plateau,15.2", "map" to "2d")371        waitForListings()372        assertEquals(0.0, camera().pitch, 0.5)373        device.findObject(By.desc(context.getString(R.string.map_3d_on))).click()374        waitFor("inclinaison 3D") { camera().pitch > 30 }375        assertTrue(device.wait(Until.hasObject(By.desc(context.getString(R.string.map_3d_off))), 5_000))376        // survol du quartier : la caméra tourne autour du centre, puis s'arrête à la demande377        Thread.sleep(900)378        val bearing = camera().bearing379        device.findObject(By.desc(context.getString(R.string.map_orbit))).click()380        waitFor("la caméra tourne autour du quartier", 12_000) { abs(camera().bearing - bearing) > 4 }381        device.wait(Until.hasObject(By.desc(context.getString(R.string.map_orbit_stop))), 3_000)382        device.findObject(By.desc(context.getString(R.string.map_orbit_stop))).click()383        Thread.sleep(700)384        val stopped = camera().bearing385        Thread.sleep(900)386        assertEquals("le survol s'arrête", stopped, camera().bearing, 0.5)387        device.findObject(By.desc(context.getString(R.string.map_3d_off))).click()388        waitFor("retour à plat, au nord") { camera().pitch < 1 && abs(camera().bearing) < 1 }389    }390391    @Test fun t06_immeuble_vise_en_3d_et_provenance_de_sa_hauteur() {392        launch("camera" to "45.5017,-73.5673,16.2", "map" to "3d")393        waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null }394        waitFor("carte chargée", 45_000) { MapProbe.loaded }395        waitFor("inclinaison 3D") { camera().pitch > 30 }396        Thread.sleep(1500)397        val w = MapProbe.width / density; val h = MapProbe.height / density398        // un immeuble du fond sous un point dégagé de la carte399        var at: Pair<Double, Double>? = null400        waitFor("un immeuble sous un point dégagé", 20_000) {401            at = main {402                var found: Pair<Double, Double>? = null403                var y = h * 0.35404                while (found == null && y < h * 0.7) {405                    var x = w * 0.15406                    while (found == null && x < w * 0.7) {407                        val f: List<KaFeature> = map().queryRendered(x, y, listOf("base:building", MapStyle.Layers.LISTINGS, MapStyle.Layers.GROUPS))408                        if (f.isNotEmpty() && f.first().isBuilding && f.none { it.layer == MapStyle.Layers.LISTINGS || it.layer == MapStyle.Layers.GROUPS }) found = x to y409                        x += 22410                    }411                    y += 22412                }413                found414            }415            at != null416        }417        device.click((MapProbe.originX + at!!.first * density).toInt(), (MapProbe.originY + at!!.second * density).toInt())418        waitFor("immeuble visé", 10_000) { MapProbe.building != null }419        val b = MapProbe.building!!420        Log.i(tag, "immeuble : hauteur=${b.height} provenance=${b.heightSource} mesurée=${b.measured} année=${b.year}")421        assertTrue(b.heightSource in setOf("mesuree", "etages", "estimee", "bloc", "inconnue"))422        assertTrue("la fiche de l'immeuble dit sa hauteur", device.wait(Until.hasObject(By.text(context.getString(R.string.bld_title))), 5_000))423    }424425    @Test fun t07_rotation_de_l_ecran() {426        launch("camera" to "$plateau,14.6")427        waitForListings()428        val before = camera(); val engine = MapProbe.engine!!.generation; val w = MapProbe.width429        device.setOrientationLeft()430        waitFor("carte redimensionnée") { MapProbe.width != w }431        Thread.sleep(1800)432        assertEquals("le moteur n'est pas recréé : même génération", engine, MapProbe.engine!!.generation)433        assertEquals(before.center.lat, camera().center.lat, 0.02); assertEquals(before.zoom, camera().zoom, 0.6)434        waitFor("pastilles redessinées") { markerCount() > 0 && main { map().getPerf() }!!.tiles > 0 }435        device.setOrientationNatural()436        waitFor("retour à l'orientation de départ") { MapProbe.width == w }437    }438439    @Test fun t08_arriere_plan_puis_retour() {440        launch("camera" to "$plateau,14.6")441        waitForListings()442        val before = camera()443        scenario!!.moveToState(Lifecycle.State.CREATED)444        Thread.sleep(1500)445        scenario!!.moveToState(Lifecycle.State.RESUMED)446        waitFor("carte de retour") { MapProbe.controller != null && main { map().isReady.value } }447        Thread.sleep(1500)448        assertEquals(before.center.lon, camera().center.lon, 1e-3); assertEquals(before.zoom, camera().zoom, 0.05)449        assertTrue(markerCount() > 0)450        waitFor("pastilles encore dessinées") { drawn().isNotEmpty() }451    }452453    @Test fun t09_theme_sombre_et_clair() {454        launch("camera" to "$plateau,14.6", "appearance" to "dark")455        waitForListings()456        assertEquals("midnight", main { map().currentTheme })457        launch("camera" to "$plateau,14.6", "appearance" to "light")458        waitForListings()459        assertEquals("signature", main { map().currentTheme })460    }461462    @Test fun t10_zones_de_marche_sous_l_eau() {463        launch("camera" to "45.53,-73.62,11.3", "layers" to "zones")464        waitFor("moteur prêt") { MapProbe.controller != null }465        waitFor("zones teintées (statistiques + contours)", 60_000) { main { map().layer(MapStyle.Layers.ZONES) } != null }466        val layer = main { map().layer(MapStyle.Layers.ZONES)!! }467        val n = (layer.data as KaLayerData.Json).element.jsonObject["features"]!!.jsonArray.size468        Log.i(tag, "zones publiées : $n")469        assertTrue("plusieurs zones publiées", n >= 3)470        // la teinte est rangée sous l'eau : un fleuve n'est jamais teinté471        assertEquals("below-water", layer.options["slot"]!!.jsonPrimitive.content)472    }473474    @Test fun t11_cartes_de_la_fiche_emplacement_et_comparables() {475        launch("camera" to "$plateau,16.3")476        waitForListings()477        val uid = selectOne()478        launch("open" to "propriete/$uid", tab = null)479        assertTrue("fiche ouverte", device.wait(Until.hasObject(By.text(context.getString(R.string.view_listing))), 30_000))480        val h = device.displayHeight; val x = device.displayWidth / 2481        fun scrollTo(what: String, desc: String) {482            repeat(70) {483                if (device.hasObject(By.descStartsWith(desc))) return484                device.swipe(x, (h * 0.62).toInt(), x, (h * 0.34).toInt(), 12); Thread.sleep(350)485            }486            throw AssertionError("introuvable en faisant défiler la fiche : $what")487        }488        scrollTo("carte d'emplacement", context.getString(R.string.loc_map_a11y, "").trim().trimEnd(','))489        waitFor("carte d'emplacement chargée, lot cherché", 30_000) { ListingMapProbe.locationLoaded }490        // la carte incrustée n'a pas de gestes : un glisser parti d'elle fait défiler la page (sans voile par-dessus)491        val locDesc = context.getString(R.string.loc_map_a11y, "").trim().trimEnd(',')492        val before = device.findObject(By.descStartsWith(locDesc)).visibleBounds493        device.swipe(before.centerX(), before.centerY(), before.centerX(), before.centerY() - (120 * density).toInt(), 30)494        Thread.sleep(900)495        val after = device.findObject(By.descStartsWith(locDesc))?.visibleBounds496        Log.i(tag, "glisser parti de la carte d'emplacement : haut de la carte ${before.top} → ${after?.top} px")497        assertTrue("la page a défilé", after == null || after.top < before.top - 40)498        Log.i(tag, "fiche $uid : lot ${ListingMapProbe.lot?.areaM2} m²")499        scrollTo("carte des comparables", context.getString(R.string.comp_map_a11y, 0, 0).substringBefore(":"))500        waitFor("comparables posés", 30_000) { ListingMapProbe.comparables > 0 }501        waitFor("carte des comparables chargée", 30_000) { ListingMapProbe.comparablesLoaded }502        Log.i(tag, "comparables sur la carte : ${ListingMapProbe.comparables}")503    }504505    @Test fun t12_opengl_es_impose() {506        launch("camera" to "$plateau,14.6", "backend" to "gles")507        waitForListings()508        val info = MapProbe.engine!!509        Log.i(tag, "backend imposé=${info.backend} adapter=${info.adapter} driver=${info.driver} software=${info.software}")510        assertEquals("gles", info.backend)511        waitFor("pastilles dessinées en OpenGL ES") { drawn().isNotEmpty() }512        assertTrue(main { map().getPerf() }!!.tiles > 0)513    }514515    @Test fun t13_les_pastilles_suivent_la_police_du_systeme() {516        fun pillHeight(): Double {517            launch("camera" to "$plateau,16.3")518            waitForListings()519            var hs: List<Double> = emptyList()520            // une carte basse (petit téléphone) ne montre parfois qu'une pastille seule à ce zoom521            waitFor("pastilles seules", 20_000) { hs = drawn().filter { it.isListingPill() }.map { it.rect.bottom - it.rect.top }.sorted(); hs.isNotEmpty() }522            return hs[hs.size / 2]523        }524        shell("settings put system font_scale 1.0"); Thread.sleep(800)525        val normal = pillHeight()526        shell("settings put system font_scale 1.3"); Thread.sleep(1200)527        val large = pillHeight()528        Log.i(tag, "hauteur médiane d'une pastille : $normal dp à 1,0 ; $large dp à 1,3")529        assertTrue("les pastilles grossissent avec la police du système ($normal → $large)", large > normal * 1.12)530    }531532    @Test fun t14_zone_gardee_puis_mode_avion() {533        // Sherbrooke : aucune autre épreuve n'y passe, les tuiles ne peuvent venir que de la zone gardée534        val zone = MapBounds(-71.905, 45.395, -71.885, 45.408)535        val off = MapOffline.get(context)536        runBlocking { off.regions().forEach { off.remove(it.region.id) } }537        val tiles = MapOffline.keep(context, "Sherbrooke (essai)", zone)!!538        waitFor("zone téléchargée ($tiles tuiles)", 120_000) { runBlocking { off.regions().any { it.region.id == MapOffline.regionId(zone) && (it.region.state == KaRegionState.COMPLETE || it.completedAt != null) } } }539        val region = runBlocking { off.regions().first() }540        Log.i(tag, "zone gardée : tuiles=${region.region.tilesDone}/${region.region.tilesTotal} octets=${region.region.bytes} version=${region.dataVersion}")541        assertTrue(region.region.bytes > 0)542543        shell("cmd connectivity airplane-mode enable")544        Thread.sleep(2500)545        launch("camera" to "45.4015,-71.895,13.6")546        waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null }547        waitFor("carte chargée sans réseau", 40_000) { MapProbe.loaded && main { map().getPerf() }!!.tiles > 0 }548        // les propriétés, elles, ne viennent pas : l'app le dit549        val offline = context.getString(R.string.map_counter_offline_none).substringBefore("·").trim()550        // une connexion déjà ouverte peut mettre son délai entier à échouer : attente longue551        val said = device.wait(Until.hasObject(By.textStartsWith(offline)), 75_000)552        if (!said) Log.i(tag, "compteur hors connexion absent ; textes à l'écran : ${device.findObjects(By.textContains(" ")).mapNotNull { runCatching { it.text }.getOrNull() }.take(12)}")553        assertTrue("le compteur dit « $offline »", said)554        shell("cmd connectivity airplane-mode disable")555        runBlocking { off.remove(MapOffline.regionId(zone)) }556        // le réseau revient avant l'épreuve suivante557        waitFor("réseau de retour", 30_000) { shell("ping -c 1 -W 2 8.8.8.8").contains("1 received") || shell("cmd connectivity airplane-mode").contains("disabled").also { Thread.sleep(6000) } }558    }559560    @Test fun t15_filtres_qui_changent_pendant_un_glisser() {561        launch("camera" to "$plateau,13.6")562        waitFor("moteur prêt") { MapProbe.controller != null && MapProbe.engine != null }563        // grand écran : plus de 4 000 propriétés dans l'emprise, le serveur regroupe564        waitFor("pastilles ou regroupements de l'API", 90_000) { markerCount() > 0 || count(MapStyle.Layers.GROUPS) > 0 }565        waitFor("carte chargée", 45_000) { MapProbe.loaded }566        val generation = MapProbe.engine!!.generation; val failures = MapProbe.engineFailures; val errors = MapProbe.errors567        val x0 = (MapProbe.originX + MapProbe.width * 0.3f).toInt(); val x1 = (MapProbe.originX + MapProbe.width * 0.6f).toInt()568        val y0 = (MapProbe.originY + MapProbe.height * 0.35f).toInt(); val y1 = (MapProbe.originY + MapProbe.height * 0.6f).toInt()569        // UiAutomator est un service d'accessibilité à l'écoute pendant toute l'épreuve570        repeat(3) { round ->571            val drag = Thread { device.swipe(x0, y0, x1, y1, 420) }   // un doigt glisse sur la carte pendant environ 2 s572            drag.start()573            // pendant le glisser : la recherche change (ville, puis type), les couches de la carte sont remplacées574            for (city in listOf("Laval", "Montréal", "Longueuil")) {575                Thread.sleep(350)576                context.startActivity(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)577                    .putExtra("tab", "explore").putExtra("city", city))578            }579            drag.join()580            Log.i(tag, "glisser ${round + 1} : filtres changés trois fois pendant le geste")581            Thread.sleep(700)582        }583        waitFor("la carte répond encore", 30_000) { MapProbe.controller != null && main { map().isReady.value } && main { map().getPerf() }!!.tiles > 0 }584        // la carte obéit encore au doigt : un glisser de plus la déplace585        Thread.sleep(1500)586        val before = camera()587        device.swipe(x1, y1, x0, y0, 40)588        waitFor("la carte suit encore le doigt", 10_000) { abs(camera().center.lon - before.center.lon) > 1e-5 || abs(camera().center.lat - before.center.lat) > 1e-5 }589        assertEquals("le moteur n'a pas été recréé", generation, MapProbe.engine!!.generation)590        assertEquals("aucune perte ni panne du moteur", failures, MapProbe.engineFailures)591        Log.i(tag, "après les glissers : génération ${MapProbe.engine!!.generation}, pannes ${MapProbe.engineFailures - failures}, erreurs signalées ${MapProbe.errors - errors}")592    }593}594
Files main
Menu

Theme