Yokan / rebuild
Course 1 8624561

SyncAccountLeasesTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/SyncAccountLeasesTest.kt

test / fixture92 lines
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.app.profiles.ProfileRegistry5import eu.friedcutlet.yokan.app.profiles.ProfileRegistryPersistence6import eu.friedcutlet.yokan.database.DbSettings7import eu.friedcutlet.yokan.database.DbSyncPreference8import eu.friedcutlet.yokan.database.InMemoryYokanDatabase9import eu.friedcutlet.yokan.database.emptySnapshot10import eu.friedcutlet.yokan.services.http.HttpRequest11import eu.friedcutlet.yokan.services.http.HttpResponse12import eu.friedcutlet.yokan.services.http.HttpService13import kotlinx.coroutines.test.TestScope14import kotlinx.coroutines.test.runTest15import kotlin.test.Test16import kotlin.test.assertEquals17import kotlin.test.assertFalse18import kotlin.test.assertNull19import kotlin.test.assertTrue2021class SyncAccountLeasesTest {22    private class MemoryRegistry : ProfileRegistryPersistence {23        var raw: String? = null24        override suspend fun read() = raw25        override suspend fun compareAndSet(expected: String?, replacement: String) = (raw == expected).also { if (it) raw = replacement }26    }2728    /** Answers the version probe and login; everything else is an unexpected network call. */29    private class FakeHub : HttpService {30        val requests = mutableListOf<HttpRequest>()31        override suspend fun request(request: HttpRequest): HttpResponse {32            requests += request33            return when {34                request.url.endsWith("/api/version") -> HttpResponse(200, """{"supported":["1"]}""")35                request.url.endsWith("/api/v1/login") -> HttpResponse(200, """{"token":"tok"}""")36                else -> HttpResponse(500, "")37            }38        }39    }4041    private suspend fun registry() = ProfileRegistry(MemoryRegistry()).apply {42        refresh(); beginCreate("Reader", A); markReady(A); beginCreate("Other", B); markReady(B)43    }4445    private fun TestScope.hub(db: InMemoryYokanDatabase, http: HttpService, leases: SyncAccountLeases) =46        HubSyncService(db, http, webSocketEngine = null, autoSync = false, scope = backgroundScope, leases = leases)4748    @Test fun leasedAccountRejectsOtherProfilesLoginWithoutWritingCredentials() = runTest {49        val registry = registry()50        val dbA = InMemoryYokanDatabase(emptySnapshot()); val dbB = InMemoryYokanDatabase(emptySnapshot())51        assertTrue(hub(dbA, FakeHub(), registry.syncLeases(A)).login(1, "hub.test", "a@b", "pw").success)5253        // Server/account spelling differences still name the same remote library.54        val result = hub(dbB, FakeHub(), registry.syncLeases(B)).login(1, "https://HUB.test/", " A@B ", "pw")55        assertFalse(result.success)56        assertEquals("This sync account is already connected to profile ‘Reader’. Log out there first.", result.message)57        assertTrue(dbB.syncPreferences().isEmpty())5859        hub(dbA, FakeHub(), registry.syncLeases(A)).logout(1)60        assertTrue(hub(dbB, FakeHub(), registry.syncLeases(B)).login(1, "https://HUB.test/", " A@B ", "pw").success)61        assertEquals("tok", dbB.syncPreferences().single().authToken)62    }6364    @Test fun conflictingExistingLoginDoesNotSync() = runTest {65        val registry = registry()66        registry.claimSyncLease(A, "hub|https://hub.test|a@b")67        // e.g. a login restored into B from a backup of A.68        val dbB = InMemoryYokanDatabase(emptySnapshot())69        dbB.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", email = "a@b", authToken = "tok", syncOn = true))70        val http = FakeHub()71        val result = hub(dbB, http, registry.syncLeases(B)).sync(1, DbSettings())72        assertEquals(listOf("This sync account is already connected to profile ‘Reader’. Log out there first."), result.errors)73        assertTrue(http.requests.isEmpty())74        assertEquals("tok", dbB.syncPreferences().single().authToken, "the conflicting login is kept, not deleted")75    }7677    @Test fun rejectedCommitReturnsTheLeaseToThePreviousAccount() = runTest {78        val registry = registry()79        val previous = DbSyncPreference(server = "https://hub.test", email = "old", authToken = "tok")80        registry.claimSyncLease(A, syncLeaseKey(previous)!!)81        val failure = registry.syncLeases(A).commitClaimed(previous, previous.copy(email = "new")) { false }82        assertEquals("Sync configuration changed during login; try again.", failure)83        assertEquals(listOf("hub|https://hub.test|old"), registry.refresh().syncLeases.map { it.key })84        assertNull(registry.syncLeases(A).commitClaimed(null, previous.copy(email = "new")) { true })85        assertEquals(listOf("hub|https://hub.test|new"), registry.refresh().syncLeases.map { it.key })86    }8788    private companion object {89        val A = ProfileId("p_${"a".repeat(32)}")90        val B = ProfileId("p_${"b".repeat(32)}")91    }92}93

Search chapters, reference and source filenames.