Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project : Immo-Ka Android10 * File : app/src/test/kotlin/com/spboucher/immoka/LibrarySyncTest.kt11 * Description : synchronisation des favoris, des notes et des recherches —12 * règles pures (aperçu, fusion, chaîne de requête) et moteur13 * contre un serveur local : envoi complet à la connexion,14 * ajout et retrait immédiats, retraits gardés hors ligne15 * puis rejoués, déconnexion, session refusée.16 * Module : test17 * Repository : https://git.spboucher.ai/immo-ka-android18 * Project Website : https://www.immo-ka.com19 * Created : 2026-11-3020 * Last Modified : 2026-11-3021 *22 * =============================================================================23 * AUTHOR & PROFESSIONAL AFFILIATION24 * =============================================================================25 *26 * Author : Simon-Pierre Boucher27 * Position : Professor of Finance28 * Institution : Université du Québec en Outaouais (UQO)29 * Department : Département des sciences administratives30 * Organization : SP Boucher31 *32 * Website : https://spboucher.ai33 * Git : https://git.spboucher.ai34 *35 * =============================================================================36 * OFFICIAL CONTACT DIRECTORY37 * =============================================================================38 *39 * General : info@spboucher.ai40 * Professional : contact@spboucher.ai41 * Direct : simon@spboucher.ai42 * Research : research@spboucher.ai43 * Development : dev@spboucher.ai44 * Support : support@spboucher.ai45 * Security/Admin : admin@spboucher.ai46 * Notifications : notifications@spboucher.ai47 *48 * Preferred Contact: contact@spboucher.ai49 *50 * =============================================================================51 * COPYRIGHT & INTELLECTUAL PROPERTY52 * =============================================================================53 *54 * Copyright (c) 202655 * Simon-Pierre Boucher56 *57 * All rights reserved where applicable.58 *59 * This file is governed by the applicable project license,60 * copyright notices, institutional agreements and relevant law.61 *62 * Unless expressly authorized by the applicable license or63 * rights holder, copying, redistribution, sublicensing,64 * publication and commercial exploitation are not permitted.65 *66 * Existing third-party rights and notices remain unaffected.67 *68 * =============================================================================69 * CONFIDENTIALITY & SECURITY70 * =============================================================================71 *72 * Classification : Public73 * Distribution : Public repository; use is governed by the project license74 * Security Contact : admin@spboucher.ai75 *76 * Access to this source does not independently grant permission77 * to redistribute or disclose confidential materials.78 *79 * Do not embed credentials, private keys, access tokens,80 * certificates or confidential personal information.81 *82 * =============================================================================83 * LICENSE & MAINTENANCE84 * =============================================================================85 *86 * License : None specified (no license file in this repository)87 * Maintainer : Simon-Pierre Boucher88 * Technical Contact: dev@spboucher.ai89 *90 * =============================================================================91 * END OF SP BOUCHER SOURCE HEADER92 * =============================================================================93 */9495package com.spboucher.immoka9697import com.spboucher.immoka.core.account.Account98import com.spboucher.immoka.core.account.AccountUser99import com.spboucher.immoka.core.account.LibrarySync100import com.spboucher.immoka.core.account.MemorySessionVault101import com.spboucher.immoka.core.account.RemoteFavorite102import com.spboucher.immoka.core.account.RemoteSearch103import com.spboucher.immoka.core.account.StoredSession104import com.spboucher.immoka.core.account.SyncRules105import com.spboucher.immoka.core.account.SyncStatus106import com.spboucher.immoka.core.model.Listing107import com.spboucher.immoka.core.model.SearchFilters108import com.spboucher.immoka.core.model.SearchSort109import com.spboucher.immoka.core.store.Favorite110import com.spboucher.immoka.core.store.Snapshot111import com.spboucher.immoka.core.store.Library112import com.spboucher.immoka.core.store.LibraryEvent113import com.spboucher.immoka.core.store.Removal114import com.spboucher.immoka.core.store.SavedSearch115import com.spboucher.immoka.core.util.arr116import com.spboucher.immoka.core.util.dbl117import com.spboucher.immoka.core.util.obj118import com.spboucher.immoka.core.util.str119import kotlinx.coroutines.CoroutineScope120import kotlinx.coroutines.job121import kotlinx.coroutines.runBlocking122import kotlinx.coroutines.yield123import kotlinx.serialization.json.JsonObject124import kotlinx.serialization.json.jsonObject125import okhttp3.mockwebserver.MockResponse126import okhttp3.mockwebserver.MockWebServer127import okhttp3.mockwebserver.RecordedRequest128import org.junit.After129import org.junit.Assert.assertEquals130import org.junit.Assert.assertFalse131import org.junit.Assert.assertNull132import org.junit.Assert.assertTrue133import org.junit.Before134import org.junit.Rule135import org.junit.Test136import org.junit.rules.TemporaryFolder137import java.io.File138import java.util.concurrent.TimeUnit139140private fun jsonObj(text: String) = com.spboucher.immoka.core.util.parseObject(text)!!141142class LibrarySyncTest {143 @get:Rule val tmp = TemporaryFolder()144 private lateinit var server: MockWebServer145 private var clock = 1_796_000_000_000L146 private fun base() = server.url("/").toString().trimEnd('/')147 private fun json(body: String, code: Int = 200) = MockResponse().setResponseCode(code).setHeader("Content-Type", "application/json").setBody(body)148 private fun l(uid: String, price: Int = 300_000) = Listing(uid = uid, address = "12 rue $uid", city = "Laval", sector = "Chomedey", propertyType = "Maison", price = price.toDouble(),149 images = listOf("https://x.test/i.jpg"), source = "centris", areaSqft = 1850.0, lat = 45.55, lng = -73.75)150 private fun fav(uid: String, at: Long, note: String = "", price: Double = 300_000.0) = Favorite(Snapshot.of(l(uid, price.toInt())), at, note, savedPrice = price, updatedAt = at)151 private fun favList(vararg items: String, skipped: Int = 0) = json("""{"items":[${items.joinToString(",")}],"limit":2000,"server_time":1,"skipped":$skipped}""")152 private fun remoteFav(uid: String, savedAt: Long, note: String = "", title: String = "D'ailleurs") =153 """{"uid":"$uid","saved_at":$savedAt,"note":"$note","snapshot":{"title":"$title","city":"Québec","price":415000,"image":"https://x.test/r.jpg","ptype":"Condo","inconnu":true},"updated_at":${savedAt + 5}}"""154 private val emptySearches get() = json("""{"items":[],"limit":100,"server_time":1,"skipped":0}""")155156 @Before fun start() { server = MockWebServer(); server.start() }157 @After fun stop() { runCatching { server.shutdown() } }158159 private fun vault() = MemorySessionVault(StoredSession("JETON", base(), AccountUser("u1", "lea@example.org", "Léa", true, role = "acheteur")))160 private fun take(): RecordedRequest = server.takeRequest(5, TimeUnit.SECONDS) ?: error("aucune requête reçue")161 private suspend fun CoroutineScope.settle() { while (true) { val c = coroutineContext.job.children.filter { it.isActive }.toList(); if (c.isEmpty()) break; c.forEach { it.join() } } }162163 // --- Règles pures ------------------------------------------------------------------------------------164165 @Test fun `apercu - les champs partages par les trois clients, rien d'inutile`() {166 val f = fav("centris:1", 1000)167 val s = SyncRules.snapshot(f.item)168 assertEquals(setOf("title", "address", "city", "sector", "ptype", "price", "image", "source", "area_sqft", "lat", "lng"), s.keys)169 assertEquals("12 rue centris:1", s.str("title")); assertEquals("Maison", s.str("ptype")); assertEquals(300_000.0, s.dbl("price")); assertEquals(1850.0, s.dbl("area_sqft")); assertEquals(-73.75, s.dbl("lng"))170 assertEquals(setOf("title"), SyncRules.snapshot(Snapshot(uid = "a:1", title = "Seul")).keys)171 // le prix de l'aperçu est celui de l'enregistrement, pas le prix du jour172 val up = SyncRules.upload(f.copy(note = "près du parc", item = f.item.copy(price = 289_000.0)))173 assertEquals("centris:1", up.uid); assertEquals(1000L, up.savedAt); assertEquals("près du parc", up.note); assertEquals(1000L, up.updatedAt); assertEquals(300_000.0, up.snapshot!!.dbl("price"))174 assertNull(SyncRules.upload(f.copy(updatedAt = 0)).updatedAt) // favori d'avant la 3.1.0 : le serveur se rabat sur saved_at175 }176177 @Test fun `favori venu d'un autre appareil - affiche avec son apercu, un favori connu garde son etat local`() {178 val remote = RemoteFavorite("centris:9/a", 5000, "à visiter", jsonObj("""{"title":"3 av. Y","address":"3 av. Y","city":"Québec","sector":"Limoilou","ptype":"Duplex","price":"545000","image":"https://x.test/9.jpg","source":"centris","area_sqft":2100,"lat":46.8,"lng":-71.2}"""), 6000)179 val f = SyncRules.favorite(remote, null)180 assertEquals("3 av. Y", f.item.title); assertEquals("Limoilou · Québec", f.item.place); assertEquals("Duplex", f.item.propertyType); assertEquals(545_000.0, f.item.price); assertEquals(545_000.0, f.savedPrice)181 assertEquals("à visiter", f.note); assertEquals(5000L, f.savedAt); assertEquals(6000L, f.updatedAt); assertEquals(2100.0, f.item.areaSqft); assertEquals(46.8, f.item.lat)182 // connu ici : le prix du jour, les chambres et la photo locale restent ; la note et les dates viennent du serveur183 val local = Favorite(Snapshot(uid = "centris:9/a", title = "Ancien titre", price = 529_000.0, image = "https://x.test/local.jpg", bedrooms = 4, bathrooms = 2), 1, "ancienne", savedPrice = 560_000.0)184 val g = SyncRules.favorite(remote.copy(snapshot = JsonObject(emptyMap())), local)185 assertEquals("Ancien titre", g.item.title); assertEquals(529_000.0, g.item.price); assertEquals(560_000.0, g.savedPrice); assertEquals(4, g.item.bedrooms); assertEquals("https://x.test/local.jpg", g.item.image); assertEquals("à visiter", g.note)186 assertEquals(529_000.0, SyncRules.favorite(remote, local).item.price); assertEquals(545_000.0, SyncRules.favorite(remote, local).savedPrice)187 }188189 @Test fun `fusion - la liste du serveur devient la liste de l'appareil, sauf ce qui a change pendant l'echange`() {190 val a = fav("a:1", 100); val b = fav("b:2", 200, "locale"); val c = fav("c:3", 300)191 fun r(uid: String, at: Long, note: String = "") = RemoteFavorite(uid, at, note, jsonObj("""{"title":"R $uid"}"""), at)192 // le serveur ne rend pas a:1 (retiré sur un autre appareil) et ajoute d:4193 val merged = SyncRules.mergeFavorites(listOf(c, b, a), listOf(r("b:2", 200, "du serveur"), r("d:4", 400), r("c:3", 300)))194 assertEquals(listOf("d:4", "c:3", "b:2"), merged.map { it.item.uid }); assertEquals("du serveur", merged[2].note); assertEquals("R d:4", merged[0].item.title)195 // pendant l'échange : c:3 retiré sur l'appareil, e:5 ajouté, b:2 annoté → leur état local l'emporte196 val e = fav("e:5", 500)197 val during = SyncRules.mergeFavorites(listOf(e, b.copy(note = "plus récente"), a), listOf(r("b:2", 200, "du serveur"), r("c:3", 300), r("a:1", 100)), touched = setOf("c:3", "e:5", "b:2"))198 assertEquals(listOf("e:5", "b:2", "a:1"), during.map { it.item.uid }); assertEquals("plus récente", during[1].note)199 // le serveur a écarté des éléments (limite du compte) : rien de local n'est perdu200 assertEquals(listOf("c:3", "b:2", "a:1"), SyncRules.mergeFavorites(listOf(c, b, a), listOf(r("b:2", 200)), keepMissing = true).map { it.item.uid })201 assertTrue(SyncRules.mergeFavorites(listOf(a), emptyList()).isEmpty())202 }203204 @Test fun `recherche - chaine de requete du site, relue telle quelle, parametre inconnu = recherche non montree`() {205 val filters = SearchFilters(city = "Trois-Rivières", propertyType = "Maison", priceMax = 450_000, bedroomsMin = 3, with = listOf("garage", "pool"), text = "près du parc & école")206 val q = SyncRules.query(filters, SearchSort.PRIX)207 assertEquals("bedrooms_min=3&city=Trois-Rivi%C3%A8res&price_max=450000&q=pr%C3%A8s%20du%20parc%20%26%20%C3%A9cole&sort=prix&type=Maison&with=garage%2Cpool", q)208 val (back, sort) = SyncRules.parseQuery(q)!!209 assertEquals(filters, back); assertEquals(SearchSort.PRIX, sort)210 assertEquals("sort=recent", SyncRules.query(SearchFilters(), SearchSort.RECENT))211 // forme du site : « ? » en tête, « + » pour l'espace, ordre libre212 val (web, webSort) = SyncRules.parseQuery("?sort=ecart&city=Laval&q=bord+de+l%27eau&position=sous")!!213 assertEquals(SearchFilters(city = "Laval", text = "bord de l'eau", deal = com.spboucher.immoka.core.model.PositionFilter.SOUS), web); assertEquals(SearchSort.ECART, webSort)214 assertEquals(SearchSort.RECENT, SyncRules.parseQuery("city=Laval")!!.second)215 assertNull(SyncRules.parseQuery("city=Laval&polygon=1,2,3")) // zone tracée : inconnue de l'app216 assertNull(SyncRules.parseQuery("city=Laval&sort=mystere"))217 assertNull(SyncRules.parseQuery("bbox=-74,45,-73,46"))218 assertNull(SyncRules.parseQuery("city=Laval&with=garage,piste_de_bowling")); assertNull(SyncRules.parseQuery("city=Laval&position=ailleurs"))219 val up = SyncRules.upload(SavedSearch("id-1", SearchFilters(city = "Laval", propertyType = "Condo", priceMax = 400_000), SearchSort.RECENT, 1000, 12))220 assertEquals("android", up.origin); assertEquals("city=Laval&price_max=400000&sort=recent&type=Condo", up.query); assertEquals(12, up.lastTotal); assertEquals("Laval · Condo · ≤ 400000 $", up.label)221 assertEquals("Recherche", SyncRules.label(SearchFilters()))222 }223224 @Test fun `fusion des recherches - connue gardee, lisible ajoutee, illisible laissee au serveur`() {225 val mine = SavedSearch("m1", SearchFilters(city = "Laval"), SearchSort.PRIX, 100, 7)226 val remote = listOf(227 RemoteSearch("m1", "Laval (renommée)", "city=Laval&sort=prix", "android", 100, 9, null, 150),228 RemoteSearch("w1", "Québec, condos", "city=Qu%C3%A9bec&type=Condo", "web", 300, 41, null, 300),229 RemoteSearch("w2", "Zone tracée", "polygon=abc", "web", 400, 3, null, 400),230 RemoteSearch("i1", "", "price_max=350000", "ios", 200, null, null, 200),231 )232 val merged = SyncRules.mergeSearches(listOf(mine), remote)233 assertEquals(listOf("w1", "i1", "m1"), merged.map { it.id })234 assertEquals(mine.filters, merged[2].filters); assertNull(merged[2].label); assertEquals(7, merged[2].lastTotal)235 assertEquals(SearchFilters(city = "Québec", propertyType = "Condo"), merged[0].filters); assertEquals(41, merged[0].lastTotal); assertEquals("Québec, condos", merged[0].label)236 assertNull(merged[1].label); assertEquals(350_000, merged[1].filters.priceMax)237 assertEquals(listOf("m1"), SyncRules.mergeSearches(listOf(mine), emptyList(), touched = setOf("m1")).map { it.id })238 assertTrue(SyncRules.mergeSearches(listOf(mine), emptyList()).isEmpty())239 }240241 // --- Données locales ---------------------------------------------------------------------------------242243 @Test fun `retraits en attente - gardes seulement avec un compte, oublies a la deconnexion ou pour un autre compte`() {244 val f = File(tmp.root, "library.json")245 val lib = Library(f, now = { clock })246 lib.toggleFavorite(l("a:1")); lib.removeFavorite("a:1")247 assertTrue(lib.state.value.removedFavorites.isEmpty()) // sans compte : comme avant, rien n'est gardé248 lib.beginSync("u1")249 lib.toggleFavorite(l("a:1")); lib.toggleFavorite(l("b:2")); clock += 10; lib.removeFavorite("a:1"); lib.removeFavorite("absent:0")250 lib.saveSearch(SearchFilters(city = "Laval"), SearchSort.RECENT, 3)251 val id = lib.state.value.searches.single().id252 lib.deleteSearch(id)253 assertEquals(listOf(Removal("a:1", clock)), lib.state.value.removedFavorites); assertEquals(listOf(Removal(id, clock)), lib.state.value.removedSearches)254 lib.toggleFavorite(l("a:1")); assertTrue(lib.state.value.removedFavorites.isEmpty()) // remis en favori : plus rien à retirer255 assertFalse(lib.toggleFavorite(l("a:1"))); lib.flush() // basculé de nouveau : retiré256 val back = Library(f)257 assertEquals("u1", back.state.value.syncUser); assertEquals(listOf("a:1"), back.state.value.removedFavorites.map { it.id }) // survit à l'arrêt de l'app258 back.beginSync("u1"); assertEquals(1, back.state.value.removedFavorites.size)259 back.favoriteRemovalsSent(listOf(Removal("a:1", 1))); assertEquals(1, back.state.value.removedFavorites.size) // retiré de nouveau depuis : reste en attente260 back.beginSync("u2"); assertTrue(back.state.value.removedFavorites.isEmpty() && back.state.value.removedSearches.isEmpty()); assertEquals(listOf("b:2"), back.state.value.favorites.map { it.item.uid })261 back.removeFavorite("b:2"); back.endSync()262 assertNull(back.state.value.syncUser); assertTrue(back.state.value.removedFavorites.isEmpty())263 }264265 @Test fun `la meme recherche enregistree de nouveau remplace l'ancienne, qui est retiree du compte`() {266 val lib = Library(null, now = { clock })267 val events = ArrayList<LibraryEvent>()268 lib.listener = { events += it }269 lib.beginSync("u1")270 lib.saveSearch(SearchFilters(city = "Laval"), SearchSort.RECENT, 3)271 val first = lib.state.value.searches.single().id272 clock += 5273 lib.saveSearch(SearchFilters(city = "Laval"), SearchSort.RECENT, 4)274 val second = lib.state.value.searches.single().id275 assertTrue(first != second); assertEquals(listOf(Removal(first, clock)), lib.state.value.removedSearches)276 assertEquals(listOf("SearchSaved", "SearchDeleted", "SearchSaved"), events.map { it::class.simpleName })277 // une note inchangée, un favori absent : aucun événement278 events.clear(); lib.setNote("absent:0", "x"); lib.removeFavorite("absent:0"); lib.deleteSearch("absent"); assertTrue(events.isEmpty())279 }280281 // --- Moteur ------------------------------------------------------------------------------------------282283 @Test fun `sans session rien n'est envoye`() = runBlocking {284 val lib = Library(null, now = { clock })285 val account = Account(MemorySessionVault(), base())286 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }287 sync.start(); sync.onForeground(); sync.onNetworkAvailable()288 lib.toggleFavorite(l("a:1")); lib.setNote("a:1", "n"); lib.removeFavorite("a:1"); lib.saveSearch(SearchFilters(), SearchSort.RECENT, 1)289 settle()290 assertEquals(0, server.requestCount); assertEquals(SyncStatus.OFF, sync.status); assertTrue(lib.state.value.removedFavorites.isEmpty())291 }292293 @Test fun `connexion - toutes les donnees locales partent, la liste fusionnee les remplace`() = runBlocking {294 val lib = Library(null, now = { clock })295 lib.toggleFavorite(l("centris:1")); clock += 1000; lib.toggleFavorite(l("duproprio:2/b", 250_000)); lib.setNote("centris:1", "près du parc")296 lib.saveSearch(SearchFilters(city = "Laval"), SearchSort.PRIX, 12)297 val searchId = lib.state.value.searches.single().id298 val account = Account(MemorySessionVault(), base())299 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }300 server.enqueue(json("""{"user":{"id":"u1","email":"lea@example.org","name":"Léa","verified":true,"role":"acheteur"},"session":{"expires_at":1,"token":"JETON"}}"""))301 // le serveur garde les deux favoris locaux et en rend un troisième, venu d'un autre appareil302 server.enqueue(favList(remoteFav("web:7", 1_796_000_500_000, "du site"), remoteFav("duproprio:2/b", 1_796_000_001_000, title = "12 rue duproprio:2/b"), remoteFav("centris:1", 1_796_000_000_000, "près du parc", "12 rue centris:1")))303 server.enqueue(json("""{"items":[{"id":"w1","label":"Québec","query":"city=Qu%C3%A9bec","origin":"web","saved_at":5,"updated_at":5},{"id":"$searchId","label":"Laval","query":"city=Laval&sort=prix","origin":"android","saved_at":$clock,"updated_at":1}],"limit":100,"server_time":1,"skipped":0}"""))304 account.signIn("lea@example.org", "Porte-Verte-2026")305 settle()306 assertEquals("/api/v3/compte/connexion", take().path)307 val favReq = take()308 assertEquals("POST", favReq.method); assertEquals("/api/v3/compte/favoris/synchronisation", favReq.path); assertEquals("Bearer JETON", favReq.getHeader("Authorization")); assertEquals("android", favReq.getHeader("X-ImmoKa-Client"))309 val body = jsonObj(favReq.body.readUtf8())310 val items = body.arr("items")!!.map { it.jsonObject }311 assertEquals(listOf("duproprio:2/b", "centris:1"), items.map { it.str("uid") }); assertEquals(0, body.arr("removed")!!.size)312 val k = items[1]313 assertEquals("près du parc", k.str("note")); assertEquals(1_796_000_000_000.0, k.dbl("saved_at")); assertEquals(1_796_000_001_000.0, k.dbl("updated_at"))314 assertEquals("12 rue centris:1", k.obj("snapshot")!!.str("title")); assertEquals("Maison", k.obj("snapshot")!!.str("ptype"))315 val se = take()316 assertEquals("/api/v3/compte/recherches/synchronisation", se.path)317 val sItem = jsonObj(se.body.readUtf8()).arr("items")!![0].jsonObject318 assertEquals("android", sItem.str("origin")); assertEquals("city=Laval&sort=prix", sItem.str("query")); assertEquals("Laval", sItem.str("label"))319 // données locales = liste du serveur320 assertEquals(listOf("web:7", "duproprio:2/b", "centris:1"), lib.state.value.favorites.map { it.item.uid })321 val web = lib.state.value.favorites[0]322 assertEquals("D'ailleurs", web.item.title); assertEquals("du site", web.note); assertEquals(415_000.0, web.item.price); assertEquals("Québec", web.item.city); assertEquals("Condo", web.item.propertyType); assertEquals("https://x.test/r.jpg", web.item.image)323 assertEquals(300_000.0, lib.state.value.favorites[2].item.price) // ce que l'appareil sait d'un favori connu est gardé324 assertEquals(listOf(searchId, "w1"), lib.state.value.searches.map { it.id }); assertEquals(SearchFilters(city = "Québec"), lib.state.value.searches[1].filters); assertEquals("Québec", lib.state.value.searches[1].label)325 assertEquals("u1", lib.state.value.syncUser); assertEquals(SyncStatus.DONE, sync.status); assertEquals(clock, sync.lastSync)326 }327328 @Test fun `connecte - ajout, note et retrait partent aussitot, uid tel quel dans le chemin`() = runBlocking {329 val lib = Library(null, now = { clock })330 val account = Account(vault(), base())331 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }332 lib.beginSync("u1")333 repeat(3) { server.enqueue(json("{}")) }; server.enqueue(MockResponse().setResponseCode(204))334 lib.toggleFavorite(l("centris:12/34-b")); lib.setNote("centris:12/34-b", "à visiter samedi"); lib.setNote("centris:12/34-b", "à visiter samedi")335 lib.saveSearch(SearchFilters(city = "Laval", propertyType = "Condo"), SearchSort.RECENT, 12)336 val searchId = lib.state.value.searches.single().id337 clock += 500; lib.removeFavorite("centris:12/34-b")338 settle()339 val put = take()340 assertEquals("PUT", put.method); assertEquals("/api/v3/compte/favoris/centris:12/34-b", put.path); assertEquals("Bearer JETON", put.getHeader("Authorization"))341 val pb = jsonObj(put.body.readUtf8())342 assertEquals(setOf("saved_at", "note", "snapshot"), pb.keys); assertEquals("", pb.str("note")); assertEquals("Chomedey", pb.obj("snapshot")!!.str("sector"))343 val note = take()344 assertEquals("/api/v3/compte/favoris/centris:12/34-b", note.path); assertEquals("""{"note":"à visiter samedi"}""", note.body.readUtf8())345 val search = take()346 assertEquals("PUT", search.method); assertEquals("/api/v3/compte/recherches/$searchId", search.path)347 val sb = jsonObj(search.body.readUtf8())348 assertEquals("android", sb.str("origin")); assertEquals("city=Laval&sort=recent&type=Condo", sb.str("query")); assertFalse("id" in sb)349 val del = take()350 assertEquals("DELETE", del.method); assertEquals("/api/v3/compte/favoris/centris:12/34-b", del.path)351 assertEquals(4, server.requestCount) // la note inchangée n'a rien envoyé352 assertTrue(lib.state.value.removedFavorites.isEmpty()); assertEquals(SyncStatus.DONE, sync.status)353 // un favori que le serveur ne connaît pas (404) est tenu pour retiré : rien ne reste en attente354 server.enqueue(json("{}")); server.enqueue(json("""{"error":{"code":"not_found","message":"Introuvable."}}""", 404))355 lib.toggleFavorite(l("a:1")); lib.removeFavorite("a:1"); settle()356 assertTrue(lib.state.value.removedFavorites.isEmpty()); assertEquals(SyncStatus.DONE, sync.status)357 }358359 @Test fun `hors ligne - le retrait attend avec sa date, puis il est rejoue et la file se vide`() = runBlocking {360 val lib = Library(null, now = { clock })361 val account = Account(vault(), base())362 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }363 lib.beginSync("u1")364 lib.replaceFavorites(listOf(fav("a:1", clock), fav("b:2", clock)))365 val port = server.port366 server.shutdown()367 clock += 60_000368 val removedAt = clock369 lib.removeFavorite("a:1"); lib.toggleFavorite(l("c:3"))370 settle()371 assertEquals(listOf(Removal("a:1", removedAt)), lib.state.value.removedFavorites); assertEquals(SyncStatus.PENDING, sync.status)372 assertTrue(account.signedIn); assertEquals(listOf("c:3", "b:2"), lib.state.value.favorites.map { it.item.uid })373 // le réseau revient374 server = MockWebServer(); server.start(port)375 server.enqueue(favList(remoteFav("c:3", clock, title = "12 rue c:3"), remoteFav("b:2", clock - 60_000, title = "12 rue b:2")))376 server.enqueue(emptySearches)377 clock += 5_000378 sync.onNetworkAvailable()379 settle()380 val body = jsonObj(take().body.readUtf8())381 assertEquals(listOf("c:3", "b:2"), body.arr("items")!!.map { it.jsonObject.str("uid") })382 val removed = body.arr("removed")!!.map { it.jsonObject }383 assertEquals(1, removed.size); assertEquals("a:1", removed[0].str("uid")); assertEquals(removedAt.toDouble(), removed[0].dbl("at"))384 assertTrue(lib.state.value.removedFavorites.isEmpty()); assertEquals(SyncStatus.DONE, sync.status); assertEquals(listOf("c:3", "b:2"), lib.state.value.favorites.map { it.item.uid })385 // plus rien n'attend : le retour du réseau ne renvoie rien386 take(); sync.onNetworkAvailable(); settle(); assertEquals(2, server.requestCount)387 }388389 @Test fun `premier plan - nouvelle synchronisation, pas plus d'une par demi-minute`() = runBlocking {390 val lib = Library(null, now = { clock })391 val account = Account(vault(), base())392 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }393 repeat(2) { server.enqueue(favList(remoteFav("web:7", 10))); server.enqueue(emptySearches) }394 sync.start(); sync.onForeground(); settle()395 assertEquals(2, server.requestCount); assertEquals(listOf("web:7"), lib.state.value.favorites.map { it.item.uid })396 clock += 5_000; sync.onForeground(); settle(); assertEquals(2, server.requestCount)397 clock += 30_000; sync.onForeground(); settle(); assertEquals(4, server.requestCount)398 }399400 @Test fun `deconnexion - les donnees locales restent, plus rien n'est envoye`() = runBlocking {401 val lib = Library(null, now = { clock })402 val account = Account(vault(), base())403 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }404 lib.beginSync("u1")405 lib.replaceFavorites(listOf(fav("a:1", clock), fav("b:2", clock + 1)))406 server.enqueue(MockResponse().setResponseCode(204))407 account.signOut(this)408 settle()409 assertEquals("/api/v3/compte/deconnexion", take().path)410 assertEquals(2, lib.state.value.favorites.size); assertNull(lib.state.value.syncUser); assertEquals(SyncStatus.OFF, sync.status)411 clock += 100; lib.removeFavorite("a:1"); lib.toggleFavorite(l("c:3")); lib.setNote("b:2", "n"); sync.onForeground(); sync.syncNow().join()412 settle()413 assertEquals(1, server.requestCount); assertTrue(lib.state.value.removedFavorites.isEmpty()); assertEquals(listOf("c:3", "b:2"), lib.state.value.favorites.map { it.item.uid })414 }415416 @Test fun `session refusee (401) pendant la synchronisation - etat deconnecte, rien d'autre n'est efface`() = runBlocking {417 val lib = Library(null, now = { clock })418 val vault = vault()419 val account = Account(vault, base())420 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }421 lib.beginSync("u1")422 lib.replaceFavorites(listOf(fav("a:1", clock), fav("b:2", clock)))423 server.enqueue(json("{}"))424 lib.saveSearch(SearchFilters(city = "Laval"), SearchSort.RECENT, 3); settle(); take()425 server.enqueue(json("""{"error":{"code":"non_authentifie","message":"Connectez-vous pour continuer."}}""", 401))426 sync.syncNow().join()427 assertFalse(account.signedIn); assertTrue(account.expired); assertNull(vault.load())428 assertEquals(2, lib.state.value.favorites.size); assertEquals(1, lib.state.value.searches.size); assertEquals(SyncStatus.OFF, sync.status)429 // les retraits faits ensuite attendent le retour du même compte430 clock += 10; lib.removeFavorite("a:1"); settle()431 assertEquals(listOf("a:1"), lib.state.value.removedFavorites.map { it.id }); assertEquals("u1", lib.state.value.syncUser)432 }433434 @Test fun `changement fait pendant l'echange - il n'est pas ecrase par la reponse`() = runBlocking {435 val lib = Library(null, now = { clock })436 val account = Account(vault(), base())437 val sync = LibrarySync(account, lib, this, now = { clock }).also { it.attach() }438 lib.beginSync("u1")439 lib.replaceFavorites(listOf(fav("a:1", clock)))440 // la réponse (qui contient encore a:1 et pas encore n:9) arrive après les gestes441 server.enqueue(favList(remoteFav("a:1", clock, title = "12 rue a:1")).setBodyDelay(400, TimeUnit.MILLISECONDS))442 server.enqueue(emptySearches); server.enqueue(MockResponse().setResponseCode(204)); server.enqueue(json("{}"))443 val job = sync.syncNow()444 yield(); take() // l'envoi est parti445 clock += 100; lib.removeFavorite("a:1"); lib.toggleFavorite(l("n:9"))446 job.join(); settle()447 assertEquals(listOf("n:9"), lib.state.value.favorites.map { it.item.uid })448 take()449 assertEquals("DELETE /api/v3/compte/favoris/a:1", take().let { it.method + " " + it.path }); assertEquals("PUT /api/v3/compte/favoris/n:9", take().let { it.method + " " + it.path })450 assertTrue(lib.state.value.removedFavorites.isEmpty())451 }452}453