From bb381cae5d1b879c5764f50dbb1f26202e19ab8c Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 16 Sep 2022 19:10:52 +0100 Subject: [PATCH 01/56] adding test helpers when using coroutines with live data --- .../android/sdk/common/TestExtensions.kt | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt new file mode 100644 index 00000000000..918abdc54f0 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.matrix.android.sdk.common + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.withContext +import org.matrix.android.sdk.api.session.room.RoomService +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine + +suspend fun RoomService.onMain(block: RoomService.() -> T): T { + return withContext(Dispatchers.Main) { + block() + } +} + +suspend fun LiveData.first(predicate: (T) -> Boolean): T { + return withContext(Dispatchers.Main) { + suspendCoroutine { continuation -> + val observer = object : Observer { + override fun onChanged(data: T) { + if (predicate(data)) { + removeObserver(this) + continuation.resume(data) + } + } + } + observeForever(observer) + } + } +} + +suspend fun waitFor(continueWhen: suspend () -> T, action: suspend () -> Unit) { + coroutineScope { + val deferred = async { continueWhen() } + action() + deferred.await() + } +} From b4dde4443d054755ccd12bd48e36024ff35a3381 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 16 Sep 2022 19:11:12 +0100 Subject: [PATCH 02/56] replacing latched live data waiting with coroutines --- .../android/sdk/common/CommonTestHelper.kt | 6 +++ .../android/sdk/common/CryptoTestHelper.kt | 48 +++++++++---------- 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index b179c6027e2..043ca1ef3d9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -497,6 +497,12 @@ class CommonTestHelper internal constructor(context: Context) { } } + fun launch(block: suspend () -> Unit) { + runBlocking { + block() + } + } + fun waitWithLatch(timeout: Long? = TestConstants.timeOutMillis, dispatcher: CoroutineDispatcher = Dispatchers.Main, block: suspend (CountDownLatch) -> Unit) { val latch = CountDownLatch(1) val job = coroutineScope.launch(dispatcher) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index f36bfb6210e..aa57f4b9983 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -18,7 +18,12 @@ package org.matrix.android.sdk.common import android.os.SystemClock import android.util.Log +import androidx.lifecycle.LiveData import androidx.lifecycle.Observer +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.withContext import org.amshove.kluent.fail import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -52,6 +57,7 @@ import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.Room +import org.matrix.android.sdk.api.session.room.RoomService import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.RoomSummary @@ -66,6 +72,7 @@ import org.matrix.android.sdk.api.util.toBase64NoPadding import java.util.UUID import kotlin.coroutines.Continuation import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine class CryptoTestHelper(val testHelper: CommonTestHelper) { @@ -117,36 +124,25 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { val bobSession = testHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) - testHelper.waitWithLatch { latch -> - val bobRoomSummariesLive = bobSession.roomService().getRoomSummariesLive(roomSummaryQueryParams { }) - val newRoomObserver = object : Observer> { - override fun onChanged(t: List?) { - if (t?.isNotEmpty() == true) { - bobRoomSummariesLive.removeObserver(this) - latch.countDown() - } - } - } - bobRoomSummariesLive.observeForever(newRoomObserver) - aliceRoom.membershipService().invite(bobSession.myUserId) - } + testHelper.launch { + waitFor( + continueWhen = { bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { it.isNotEmpty() } }, + action = { aliceRoom.membershipService().invite(bobSession.myUserId) } + ) - testHelper.waitWithLatch { latch -> - val bobRoomSummariesLive = bobSession.roomService().getRoomSummariesLive(roomSummaryQueryParams { }) - val roomJoinedObserver = object : Observer> { - override fun onChanged(t: List?) { - if (bobSession.getRoom(aliceRoomId) + waitFor( + continueWhen = { + bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { + bobSession.getRoom(aliceRoomId) ?.membershipService() ?.getRoomMember(bobSession.myUserId) - ?.membership == Membership.JOIN) { - bobRoomSummariesLive.removeObserver(this) - latch.countDown() - } - } - } - bobRoomSummariesLive.observeForever(roomJoinedObserver) - bobSession.roomService().joinRoom(aliceRoomId) + ?.membership == Membership.JOIN + } + }, + action = { bobSession.roomService().joinRoom(aliceRoomId) } + ) } + // Ensure bob can send messages to the room // val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! // assertNotNull(roomFromBobPOV.powerLevels) From 4552f430ee67042f18550bbc1450e6f7029746ea Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 16 Sep 2022 19:28:42 +0100 Subject: [PATCH 03/56] adding suspending test account creation --- .../android/sdk/common/CommonTestHelper.kt | 65 ++++++++++++++++++- .../android/sdk/common/CryptoTestHelper.kt | 10 +-- .../android/sdk/common/TestExtensions.kt | 21 +++--- 3 files changed, 80 insertions(+), 16 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 043ca1ef3d9..cdc04639d92 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -116,6 +116,10 @@ class CommonTestHelper internal constructor(context: Context) { return createAccount(userNamePrefix, TestConstants.PASSWORD, testParams) } + suspend fun createAccountSuspending(userNamePrefix: String, testParams: SessionTestParams): Session { + return createAccountSuspending(userNamePrefix, TestConstants.PASSWORD, testParams) + } + fun logIntoAccount(userId: String, testParams: SessionTestParams): Session { return logIntoAccount(userId, TestConstants.PASSWORD, testParams) } @@ -161,6 +165,12 @@ class CommonTestHelper internal constructor(context: Context) { await(lock, timeout) } + suspend fun syncSessionSuspending(session: Session, timeout: Long = TestConstants.timeOutMillis * 10) { + session.syncService().startSync(true) + val syncLiveData = session.syncService().getSyncStateLive() + syncLiveData.first(timeout) { session.syncService().hasAlreadySynced() } + } + /** * This methods clear the cache and waits for initialSync * @@ -331,6 +341,24 @@ class CommonTestHelper internal constructor(context: Context) { } } + private suspend fun createAccountSuspending( + userNamePrefix: String, + password: String, + testParams: SessionTestParams + ): Session { + val session = createAccountAndSyncSuspending( + userNamePrefix + "_" + accountNumber++ + "_" + UUID.randomUUID(), + password, + testParams + ) + assertNotNull(session) + return session.also { + // most of the test was created pre-MSC3061 so ensure compatibility + it.cryptoService().enableShareKeyOnInvite(false) + trackedSessions.add(session) + } + } + /** * Logs into an existing account * @@ -391,6 +419,39 @@ class CommonTestHelper internal constructor(context: Context) { return session } + private suspend fun createAccountAndSyncSuspending( + userName: String, + password: String, + sessionTestParams: SessionTestParams + ): Session { + val hs = createHomeServerConfig() + + withTimeout(TestConstants.timeOutMillis) { + matrix.authenticationService.getLoginFlow(hs) + } + + withTimeout(timeMillis = 60_000L) { + matrix.authenticationService + .getRegistrationWizard() + .createAccount(userName, password, null) + } + + // Perform dummy step + val registrationResult = runBlockingTest(timeout = 60_000) { + matrix.authenticationService + .getRegistrationWizard() + .dummy() + } + + assertTrue(registrationResult is RegistrationResult.Success) + val session = (registrationResult as RegistrationResult.Success).session + session.open() + if (sessionTestParams.withInitialSync) { + syncSessionSuspending(session, 120_000) + } + return session + } + /** * Start an account login * @@ -497,8 +558,8 @@ class CommonTestHelper internal constructor(context: Context) { } } - fun launch(block: suspend () -> Unit) { - runBlocking { + fun launch(block: suspend () -> T): T { + return runBlocking { block() } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index aa57f4b9983..d92c77685c4 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -122,9 +122,9 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { val aliceRoom = aliceSession.getRoom(aliceRoomId)!! - val bobSession = testHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) + return testHelper.launch { + val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, defaultSessionParams) - testHelper.launch { waitFor( continueWhen = { bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { it.isNotEmpty() } }, action = { aliceRoom.membershipService().invite(bobSession.myUserId) } @@ -141,14 +141,14 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { }, action = { bobSession.roomService().joinRoom(aliceRoomId) } ) - } - // Ensure bob can send messages to the room + // Ensure bob can send messages to the room // val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! // assertNotNull(roomFromBobPOV.powerLevels) // assertTrue(roomFromBobPOV.powerLevels.maySendMessage(bobSession.myUserId)) - return CryptoTestData(aliceRoomId, listOf(aliceSession, bobSession)) + CryptoTestData(aliceRoomId, listOf(aliceSession, bobSession)) + } } /** diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt index 918abdc54f0..9f9ee5ba74d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout import org.matrix.android.sdk.api.session.room.RoomService import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine @@ -32,18 +33,20 @@ suspend fun RoomService.onMain(block: RoomService.() -> T): T { } } -suspend fun LiveData.first(predicate: (T) -> Boolean): T { - return withContext(Dispatchers.Main) { - suspendCoroutine { continuation -> - val observer = object : Observer { - override fun onChanged(data: T) { - if (predicate(data)) { - removeObserver(this) - continuation.resume(data) +suspend fun LiveData.first(timeout: Long = TestConstants.timeOutMillis, predicate: (T) -> Boolean): T { + return withTimeout(timeout) { + withContext(Dispatchers.Main) { + suspendCoroutine { continuation -> + val observer = object : Observer { + override fun onChanged(data: T) { + if (predicate(data)) { + removeObserver(this) + continuation.resume(data) + } } } + observeForever(observer) } - observeForever(observer) } } } From 6b9e5a2fa27d688a7172dd9fad4edde5d320e875 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 10:25:41 +0100 Subject: [PATCH 04/56] removing unused helpers --- .../android/sdk/common/CryptoTestHelper.kt | 74 +------------------ 1 file changed, 1 insertion(+), 73 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index d92c77685c4..0a12b5522c7 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -16,14 +16,8 @@ package org.matrix.android.sdk.common -import android.os.SystemClock import android.util.Log -import androidx.lifecycle.LiveData import androidx.lifecycle.Observer -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.async -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.withContext import org.amshove.kluent.fail import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -56,8 +50,6 @@ import org.matrix.android.sdk.api.session.events.model.EventType import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom -import org.matrix.android.sdk.api.session.room.Room -import org.matrix.android.sdk.api.session.room.RoomService import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.RoomSummary @@ -72,7 +64,6 @@ import org.matrix.android.sdk.api.util.toBase64NoPadding import java.util.UUID import kotlin.coroutines.Continuation import kotlin.coroutines.resume -import kotlin.coroutines.suspendCoroutine class CryptoTestHelper(val testHelper: CommonTestHelper) { @@ -151,42 +142,6 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } } - /** - * @return Alice, Bob and Sam session - */ - fun doE2ETestWithAliceAndBobAndSamInARoom(): CryptoTestData { - val cryptoTestData = doE2ETestWithAliceAndBobInARoom() - val aliceSession = cryptoTestData.firstSession - val aliceRoomId = cryptoTestData.roomId - - val room = aliceSession.getRoom(aliceRoomId)!! - - val samSession = createSamAccountAndInviteToTheRoom(room) - - // wait the initial sync - SystemClock.sleep(1000) - - return CryptoTestData(aliceRoomId, listOf(aliceSession, cryptoTestData.secondSession!!, samSession)) - } - - /** - * Create Sam account and invite him in the room. He will accept the invitation - * @Return Sam session - */ - fun createSamAccountAndInviteToTheRoom(room: Room): Session { - val samSession = testHelper.createAccount(TestConstants.USER_SAM, defaultSessionParams) - - testHelper.runBlockingTest { - room.membershipService().invite(samSession.myUserId, null) - } - - testHelper.runBlockingTest { - samSession.roomService().joinRoom(room.roomId, null, emptyList()) - } - - return samSession - } - /** * @return Alice and Bob sessions */ @@ -246,34 +201,7 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } } - fun checkEncryptedEvent(event: Event, roomId: String, clearMessage: String, senderSession: Session) { - assertEquals(EventType.ENCRYPTED, event.type) - assertNotNull(event.content) - - val eventWireContent = event.content.toContent() - assertNotNull(eventWireContent) - - assertNull(eventWireContent["body"]) - assertEquals(MXCRYPTO_ALGORITHM_MEGOLM, eventWireContent["algorithm"]) - - assertNotNull(eventWireContent["ciphertext"]) - assertNotNull(eventWireContent["session_id"]) - assertNotNull(eventWireContent["sender_key"]) - - assertEquals(senderSession.sessionParams.deviceId, eventWireContent["device_id"]) - - assertNotNull(event.eventId) - assertEquals(roomId, event.roomId) - assertEquals(EventType.MESSAGE, event.getClearType()) - // TODO assertTrue(event.getAge() < 10000) - - val eventContent = event.toContent() - assertNotNull(eventContent) - assertEquals(clearMessage, eventContent["body"]) - assertEquals(senderSession.myUserId, event.senderId) - } - - fun createFakeMegolmBackupAuthData(): MegolmBackupAuthData { + private fun createFakeMegolmBackupAuthData(): MegolmBackupAuthData { return MegolmBackupAuthData( publicKey = "abcdefg", signatures = mapOf("something" to mapOf("ed25519:something" to "hijklmnop")) From 743667bc12b193175b0b60a55233c7c82927f498 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 10:42:35 +0100 Subject: [PATCH 05/56] converting test helper to use coroutine based waits --- .../android/sdk/common/CryptoTestHelper.kt | 40 +++++++------------ .../android/sdk/common/TestExtensions.kt | 4 +- 2 files changed, 16 insertions(+), 28 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 0a12b5522c7..9ed8b248957 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -21,13 +21,11 @@ import androidx.lifecycle.Observer import org.amshove.kluent.fail import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.matrix.android.sdk.api.auth.UIABaseAuth import org.matrix.android.sdk.api.auth.UserInteractiveAuthInterceptor import org.matrix.android.sdk.api.auth.UserPasswordAuth import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse -import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM import org.matrix.android.sdk.api.crypto.MXCRYPTO_ALGORITHM_MEGOLM_BACKUP import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.Session @@ -45,9 +43,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.IncomingSasVerific import org.matrix.android.sdk.api.session.crypto.verification.OutgoingSasVerificationTransaction import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState -import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.EventType -import org.matrix.android.sdk.api.session.events.model.toContent import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.Membership @@ -58,7 +54,6 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import org.matrix.android.sdk.api.session.securestorage.EmptyKeySigner import org.matrix.android.sdk.api.session.securestorage.KeyRef -import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.awaitCallback import org.matrix.android.sdk.api.util.toBase64NoPadding import java.util.UUID @@ -76,31 +71,24 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { * @return alice session */ fun doE2ETestWithAliceInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { - val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) + return testHelper.launch { + val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, defaultSessionParams) - val roomId = testHelper.runBlockingTest { - aliceSession.roomService().createRoom(CreateRoomParams().apply { - historyVisibility = roomHistoryVisibility - name = "MyRoom" - }) - } - if (encryptedRoom) { - testHelper.waitWithLatch { latch -> + val roomId = testHelper.runBlockingTest { + aliceSession.roomService().createRoom(CreateRoomParams().apply { + historyVisibility = roomHistoryVisibility + name = "MyRoom" + }) + } + if (encryptedRoom) { val room = aliceSession.getRoom(roomId)!! - room.roomCryptoService().enableEncryption() - val roomSummaryLive = room.getRoomSummaryLive() - val roomSummaryObserver = object : Observer> { - override fun onChanged(roomSummary: Optional) { - if (roomSummary.getOrNull()?.isEncrypted.orFalse()) { - roomSummaryLive.removeObserver(this) - latch.countDown() - } - } - } - roomSummaryLive.observeForever(roomSummaryObserver) + waitFor( + continueWhen = { room.onMain { getRoomSummaryLive() }.first { it.getOrNull()?.isEncrypted.orFalse() } }, + action = { room.roomCryptoService().enableEncryption() } + ) } + CryptoTestData(roomId, listOf(aliceSession)) } - return CryptoTestData(roomId, listOf(aliceSession)) } /** diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt index 9f9ee5ba74d..13f6177d72a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -27,9 +27,9 @@ import org.matrix.android.sdk.api.session.room.RoomService import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine -suspend fun RoomService.onMain(block: RoomService.() -> T): T { +suspend fun T.onMain(block: T.() -> R): R { return withContext(Dispatchers.Main) { - block() + block(this@onMain) } } From 79fd5bf23111c516629540dbc7e2bf2f030bad85 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 11:26:13 +0100 Subject: [PATCH 06/56] adding suspending message sending and top level suspending runTest helper --- matrix-sdk-android/build.gradle | 2 + .../android/sdk/common/CommonTestHelper.kt | 118 +++++++++++++----- .../android/sdk/common/CryptoTestHelper.kt | 60 ++++----- .../sdk/internal/crypto/E2eeSanityTests.kt | 21 ++-- .../crypto/keysbackup/KeysBackupTest.kt | 2 +- 5 files changed, 128 insertions(+), 75 deletions(-) diff --git a/matrix-sdk-android/build.gradle b/matrix-sdk-android/build.gradle index 5c800f720e7..1ed3aff0572 100644 --- a/matrix-sdk-android/build.gradle +++ b/matrix-sdk-android/build.gradle @@ -221,6 +221,8 @@ dependencies { androidTestImplementation libs.mockk.mockkAndroid androidTestImplementation libs.androidx.coreTesting androidTestImplementation libs.jetbrains.coroutinesAndroid + androidTestImplementation libs.jetbrains.coroutinesTest + // Plant Timber tree for test androidTestImplementation libs.tests.timberJunitRule diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index cdc04639d92..a5e1d37d869 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -24,12 +24,16 @@ import androidx.test.internal.runner.junit4.statement.UiThreadStatement import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.cancel +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -57,6 +61,8 @@ import java.util.UUID import java.util.concurrent.CancellationException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine /** * This class exposes methods to be used in common cases @@ -87,6 +93,21 @@ class CommonTestHelper internal constructor(context: Context) { } } } + + @OptIn(ExperimentalCoroutinesApi::class) + internal fun runSuspendingCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend (CryptoTestHelper, CommonTestHelper) -> Unit) { + val testHelper = CommonTestHelper(context) + val cryptoTestHelper = CryptoTestHelper(testHelper) + return runTest { + try { + block(cryptoTestHelper, testHelper) + } finally { + if (autoSignoutOnClose) { + testHelper.cleanUpOpenedSessions() + } + } + } + } } internal val matrix: TestMatrix @@ -202,6 +223,10 @@ class CommonTestHelper internal constructor(context: Context) { * @param nbOfMessages the number of time the message will be sent */ fun sendTextMessage(room: Room, message: String, nbOfMessages: Int, timeout: Long = TestConstants.timeOutMillis): List { + return runBlocking { sendTextMessageSuspending(room, message, nbOfMessages, timeout) } + } + + suspend fun sendTextMessageSuspending(room: Room, message: String, nbOfMessages: Int, timeout: Long = TestConstants.timeOutMillis): List { val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) timeline.start() val sentEvents = sendTextMessagesBatched(timeline, room, message, nbOfMessages, timeout) @@ -214,48 +239,57 @@ class CommonTestHelper internal constructor(context: Context) { /** * Will send nb of messages provided by count parameter but waits every 10 messages to avoid gap in sync */ - private fun sendTextMessagesBatched(timeline: Timeline, room: Room, message: String, count: Int, timeout: Long, rootThreadEventId: String? = null): List { + private suspend fun sendTextMessagesBatched(timeline: Timeline, room: Room, message: String, count: Int, timeout: Long, rootThreadEventId: String? = null): List { val sentEvents = ArrayList(count) (1 until count + 1) .map { "$message #$it" } .chunked(10) .forEach { batchedMessages -> - batchedMessages.forEach { formattedMessage -> - if (rootThreadEventId != null) { - room.relationService().replyInThread( - rootThreadEventId = rootThreadEventId, - replyInThreadText = formattedMessage - ) - } else { - room.sendService().sendTextMessage(formattedMessage) - } - } - waitWithLatch(timeout) { latch -> - val timelineListener = object : Timeline.Listener { - - override fun onTimelineUpdated(snapshot: List) { - val allSentMessages = snapshot - .filter { it.root.sendState == SendState.SYNCED } - .filter { it.root.getClearType() == EventType.MESSAGE } - .filter { it.root.getClearContent().toModel()?.body?.startsWith(message) == true } - - val hasSyncedAllBatchedMessages = allSentMessages - .map { - it.root.getClearContent().toModel()?.body + waitFor( + continueWhen = { + withTimeout(timeout) { + suspendCoroutine { continuation -> + val timelineListener = object : Timeline.Listener { + + override fun onTimelineUpdated(snapshot: List) { + val allSentMessages = snapshot + .filter { it.root.sendState == SendState.SYNCED } + .filter { it.root.getClearType() == EventType.MESSAGE } + .filter { it.root.getClearContent().toModel()?.body?.startsWith(message) == true } + + val hasSyncedAllBatchedMessages = allSentMessages + .map { + it.root.getClearContent().toModel()?.body + } + .containsAll(batchedMessages) + + if (allSentMessages.size == count) { + sentEvents.addAll(allSentMessages) + } + if (hasSyncedAllBatchedMessages) { + timeline.removeListener(this) + continuation.resume(Unit) + } + } } - .containsAll(batchedMessages) - - if (allSentMessages.size == count) { - sentEvents.addAll(allSentMessages) + timeline.addListener(timelineListener) + } } - if (hasSyncedAllBatchedMessages) { - timeline.removeListener(this) - latch.countDown() + }, + action = { + batchedMessages.forEach { formattedMessage -> + if (rootThreadEventId != null) { + room.relationService().replyInThread( + rootThreadEventId = rootThreadEventId, + replyInThreadText = formattedMessage + ) + } else { + room.sendService().sendTextMessage(formattedMessage) + } } + } - } - timeline.addListener(timelineListener) - } + ) } return sentEvents } @@ -306,7 +340,7 @@ class CommonTestHelper internal constructor(context: Context) { ): List { val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) timeline.start() - val sentEvents = sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId) + val sentEvents = runBlocking { sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId) } timeline.dispose() // Check that all events has been created assertEquals("Message number do not match $sentEvents", numberOfMessages.toLong(), sentEvents.size.toLong()) @@ -600,6 +634,22 @@ class CommonTestHelper internal constructor(context: Context) { return result!! } + suspend fun doSyncSuspending(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { + val deferred = coroutineScope { + async { + suspendCoroutine { continuation -> + val callback = object : MatrixCallback { + override fun onSuccess(data: T) { + continuation.resume(data) + } + } + block(callback) + } + } + } + return withTimeout(timeout) { deferred.await() } + } + /** * Clear all provided sessions */ diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 9ed8b248957..3f8132dd6fa 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -99,9 +99,9 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId - val aliceRoom = aliceSession.getRoom(aliceRoomId)!! - return testHelper.launch { + val aliceRoom = aliceSession.getRoom(aliceRoomId)!! + val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, defaultSessionParams) waitFor( @@ -139,39 +139,41 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { val aliceRoomId = cryptoTestData.roomId val bobSession = cryptoTestData.secondSession!! - bobSession.cryptoService().setWarnOnUnknownDevices(false) - aliceSession.cryptoService().setWarnOnUnknownDevices(false) + return testHelper.launch { + bobSession.cryptoService().setWarnOnUnknownDevices(false) + aliceSession.cryptoService().setWarnOnUnknownDevices(false) - val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! - val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! + val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! + val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! - // Alice sends a message - testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId -> - // ensure bob got it - ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) - } + // Alice sends a message + testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId -> + // ensure bob got it + ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) + } - // Bob send 3 messages - testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> - // ensure alice got it - ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) - } + // Bob send 3 messages + testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> + // ensure alice got it + ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) + } - testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId -> - // ensure alice got it - ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) - } - testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId -> - // ensure alice got it - ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) - } + testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId -> + // ensure alice got it + ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) + } + testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId -> + // ensure alice got it + ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) + } - // Alice sends a message - testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId -> - // ensure bob got it - ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) + // Alice sends a message + testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId -> + // ensure bob got it + ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) + } + cryptoTestData } - return cryptoTestData } private fun ensureEventReceived(roomId: String, eventId: String, session: Session, andCanDecrypt: Boolean) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index f8832954950..945abb84b30 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -57,6 +57,7 @@ import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -219,7 +220,7 @@ class E2eeSanityTests : InstrumentedTest { * 9. Check that new session can decrypt */ @Test - fun testBasicBackupImport() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBasicBackupImport() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -229,10 +230,10 @@ class E2eeSanityTests : InstrumentedTest { Log.v("#E2E TEST", "Create and start key backup for bob ...") val bobKeysBackupService = bobSession.cryptoService().keysBackupService() val keyBackupPassword = "FooBarBaz" - val megolmBackupCreationInfo = testHelper.doSync { + val megolmBackupCreationInfo = testHelper.doSyncSuspending { bobKeysBackupService.prepareKeysBackupVersion(keyBackupPassword, null, it) } - val version = testHelper.doSync { + val version = testHelper.doSyncSuspending { bobKeysBackupService.createKeysBackupVersion(megolmBackupCreationInfo, it) } Log.v("#E2E TEST", "... Key backup started and enabled for bob") @@ -259,9 +260,7 @@ class E2eeSanityTests : InstrumentedTest { // we want more so let's discard the session aliceSession.cryptoService().discardOutboundSession(e2eRoomID) - testHelper.runBlockingTest { - delay(1_000) - } + delay(1_000) } Log.v("#E2E TEST", "Bob received all and can decrypt") @@ -284,9 +283,7 @@ class E2eeSanityTests : InstrumentedTest { testHelper.signOutAndClose(bobSession) Log.v("#E2E TEST", "..Logout alice and bob...") - testHelper.runBlockingTest { - delay(1_000) - } + delay(1_000) // Create a new session for bob Log.v("#E2E TEST", "Create a new session for Bob") @@ -676,8 +673,10 @@ class E2eeSanityTests : InstrumentedTest { assertEquals("Decimal code should have matched", oldCode, newCode) // Assert that devices are verified - val newDeviceFromOldPov: CryptoDeviceInfo? = aliceSession.cryptoService().getCryptoDeviceInfo(aliceSession.myUserId, aliceNewSession.sessionParams.deviceId) - val oldDeviceFromNewPov: CryptoDeviceInfo? = aliceSession.cryptoService().getCryptoDeviceInfo(aliceSession.myUserId, aliceSession.sessionParams.deviceId) + val newDeviceFromOldPov: CryptoDeviceInfo? = + aliceSession.cryptoService().getCryptoDeviceInfo(aliceSession.myUserId, aliceNewSession.sessionParams.deviceId) + val oldDeviceFromNewPov: CryptoDeviceInfo? = + aliceSession.cryptoService().getCryptoDeviceInfo(aliceSession.myUserId, aliceSession.sessionParams.deviceId) Assert.assertTrue("new device should be verified from old point of view", newDeviceFromOldPov!!.isVerified) Assert.assertTrue("old device should be verified from new point of view", oldDeviceFromNewPov!!.isVerified) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index 2439119f01c..cd6e4738961 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -1007,7 +1007,7 @@ class KeysBackupTest : InstrumentedTest { val room2 = aliceSession2.getRoom(cryptoTestData.roomId)!! - testHelper.sendTextMessage(room2, "New key", 1) + testHelper.launch { testHelper.sendTextMessageSuspending(room2, "New key", 1) } // - Try to backup all in aliceSession2, it must fail val keysBackup2 = aliceSession2.cryptoService().keysBackupService() From f90667ad3cba957939beeba42e257ce3a513b6c4 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 11:32:45 +0100 Subject: [PATCH 07/56] creating wrapper function for testing coroutine timeouts --- .../android/sdk/common/CommonTestHelper.kt | 17 ++++++----------- .../matrix/android/sdk/common/TestExtensions.kt | 8 +++++++- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index a5e1d37d869..a307fd694f9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -27,9 +27,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.async import kotlinx.coroutines.cancel -import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking @@ -635,19 +633,16 @@ class CommonTestHelper internal constructor(context: Context) { } suspend fun doSyncSuspending(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { - val deferred = coroutineScope { - async { - suspendCoroutine { continuation -> - val callback = object : MatrixCallback { - override fun onSuccess(data: T) { - continuation.resume(data) - } + return wrapWithTimeout(timeout) { + suspendCoroutine { continuation -> + val callback = object : MatrixCallback { + override fun onSuccess(data: T) { + continuation.resume(data) } - block(callback) } + block(callback) } } - return withTimeout(timeout) { deferred.await() } } /** diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt index 13f6177d72a..c98dad7c346 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -23,7 +23,6 @@ import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout -import org.matrix.android.sdk.api.session.room.RoomService import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine @@ -58,3 +57,10 @@ suspend fun waitFor(continueWhen: suspend () -> T, action: suspend () -> Uni deferred.await() } } + +suspend fun wrapWithTimeout(timeout: Long = TestConstants.timeOutMillis, block: suspend () -> T): T { + val deferred = coroutineScope { + async { block() } + } + return withTimeout(timeout) { deferred.await() } +} From e3fb36289a048596c115021e71294b96f598913f Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 12:09:51 +0100 Subject: [PATCH 08/56] using suspending periodic retries for the E2E share history tests --- .../android/sdk/common/CommonTestHelper.kt | 10 +- .../crypto/E2eeShareKeysHistoryTest.kt | 203 ++++++++---------- 2 files changed, 97 insertions(+), 116 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index a307fd694f9..fdde2af495d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -245,7 +245,7 @@ class CommonTestHelper internal constructor(context: Context) { .forEach { batchedMessages -> waitFor( continueWhen = { - withTimeout(timeout) { + wrapWithTimeout(timeout) { suspendCoroutine { continuation -> val timelineListener = object : Timeline.Listener { @@ -575,6 +575,14 @@ class CommonTestHelper internal constructor(context: Context) { ) } + suspend fun retryPeriodically(timeout: Long = TestConstants.timeOutMillis, predicate: () -> Boolean) { + wrapWithTimeout(timeout) { + while (!predicate()) { + delay(1000) + } + } + } + suspend fun retryPeriodicallyWithLatch(latch: CountDownLatch, condition: (() -> Boolean)) { while (true) { try { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt index 32a95008b1a..6b61c93a1c3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt @@ -40,9 +40,9 @@ import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibilityContent import org.matrix.android.sdk.api.session.room.model.shouldShareHistory import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest -import org.matrix.android.sdk.common.CryptoTestHelper +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.SessionTestParams +import org.matrix.android.sdk.common.wrapWithTimeout @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @@ -76,7 +76,7 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { * We should not be able to view messages/decrypt otherwise */ private fun testShareHistoryWithRoomVisibility(roomHistoryVisibility: RoomHistoryVisibility? = null) = - runCryptoTest(context()) { cryptoTestHelper, testHelper -> + runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true, roomHistoryVisibility) val e2eRoomID = cryptoTestData.roomId @@ -101,15 +101,13 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { Log.v("#E2E TEST", "Alice sent message to roomId: $e2eRoomID") // Bob should be able to decrypt the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = bobSession.roomService().getRoom(e2eRoomID)?.timelineService()?.getTimelineEvent(aliceMessageId!!) - (timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE).also { - if (it) { - Log.v("#E2E TEST", "Bob can decrypt the message: ${timelineEvent?.root?.getDecryptedTextSummary()}") - } + testHelper.retryPeriodically { + val timelineEvent = bobSession.roomService().getRoom(e2eRoomID)?.timelineService()?.getTimelineEvent(aliceMessageId!!) + (timelineEvent != null && + timelineEvent.isEncrypted() && + timelineEvent.root.getClearType() == EventType.MESSAGE).also { + if (it) { + Log.v("#E2E TEST", "Bob can decrypt the message: ${timelineEvent?.root?.getDecryptedTextSummary()}") } } } @@ -121,10 +119,8 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { Log.v("#E2E TEST", "Aris user created") // Alice invites new user to the room - testHelper.runBlockingTest { - Log.v("#E2E TEST", "Alice invites ${arisSession.myUserId}") - aliceRoomPOV.membershipService().invite(arisSession.myUserId) - } + Log.v("#E2E TEST", "Alice invites ${arisSession.myUserId}") + aliceRoomPOV.membershipService().invite(arisSession.myUserId) waitForAndAcceptInviteInRoom(arisSession, e2eRoomID, testHelper) @@ -137,30 +133,26 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { null -> { // Aris should be able to decrypt the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = arisSession.roomService().getRoom(e2eRoomID)?.timelineService()?.getTimelineEvent(aliceMessageId!!) - (timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE - ).also { - if (it) { - Log.v("#E2E TEST", "Aris can decrypt the message: ${timelineEvent?.root?.getDecryptedTextSummary()}") - } + testHelper.retryPeriodically { + val timelineEvent = arisSession.roomService().getRoom(e2eRoomID)?.timelineService()?.getTimelineEvent(aliceMessageId!!) + (timelineEvent != null && + timelineEvent.isEncrypted() && + timelineEvent.root.getClearType() == EventType.MESSAGE + ).also { + if (it) { + Log.v("#E2E TEST", "Aris can decrypt the message: ${timelineEvent?.root?.getDecryptedTextSummary()}") } - } + } } } RoomHistoryVisibility.INVITED, RoomHistoryVisibility.JOINED -> { // Aris should not even be able to get the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = arisSession.roomService().getRoom(e2eRoomID) - ?.timelineService() - ?.getTimelineEvent(aliceMessageId!!) - timelineEvent == null - } + testHelper.retryPeriodically { + val timelineEvent = arisSession.roomService().getRoom(e2eRoomID) + ?.timelineService() + ?.getTimelineEvent(aliceMessageId!!) + timelineEvent == null } } } @@ -238,10 +230,7 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { private fun testRotationDueToVisibilityChange( initRoomHistoryVisibility: RoomHistoryVisibility, nextRoomHistoryVisibility: RoomHistoryVisibilityContent - ) { - val testHelper = CommonTestHelper(context()) - val cryptoTestHelper = CryptoTestHelper(testHelper) - + ) = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true, initRoomHistoryVisibility) val e2eRoomID = cryptoTestData.roomId @@ -267,21 +256,19 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { // Bob should be able to decrypt the message var firstAliceMessageMegolmSessionId: String? = null val bobRoomPov = bobSession.roomService().getRoom(e2eRoomID) - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = bobRoomPov - ?.timelineService() - ?.getTimelineEvent(aliceMessageId!!) - (timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE).also { - if (it) { - firstAliceMessageMegolmSessionId = timelineEvent?.root?.content?.get("session_id") as? String - Log.v( - "#E2E TEST", - "Bob can decrypt the message (sid:$firstAliceMessageMegolmSessionId): ${timelineEvent?.root?.getDecryptedTextSummary()}" - ) - } + testHelper.retryPeriodically { + val timelineEvent = bobRoomPov + ?.timelineService() + ?.getTimelineEvent(aliceMessageId!!) + (timelineEvent != null && + timelineEvent.isEncrypted() && + timelineEvent.root.getClearType() == EventType.MESSAGE).also { + if (it) { + firstAliceMessageMegolmSessionId = timelineEvent?.root?.content?.get("session_id") as? String + Log.v( + "#E2E TEST", + "Bob can decrypt the message (sid:$firstAliceMessageMegolmSessionId): ${timelineEvent?.root?.getDecryptedTextSummary()}" + ) } } } @@ -290,8 +277,8 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { var secondAliceMessageSessionId: String? = null sendMessageInRoom(aliceRoomPOV, "Other msg", testHelper)?.let { secondMessage -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { + testHelper.launch { + testHelper.retryPeriodically { val timelineEvent = bobRoomPov ?.timelineService() ?.getTimelineEvent(secondMessage) @@ -313,50 +300,42 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { Log.v("#E2E TEST ROTATION", "No rotation needed yet") // Let's change the room history visibility - testHelper.runBlockingTest { - aliceRoomPOV.stateService() - .sendStateEvent( - eventType = EventType.STATE_ROOM_HISTORY_VISIBILITY, - stateKey = "", - body = RoomHistoryVisibilityContent( - historyVisibilityStr = nextRoomHistoryVisibility.historyVisibilityStr - ).toContent() - ) - } + aliceRoomPOV.stateService() + .sendStateEvent( + eventType = EventType.STATE_ROOM_HISTORY_VISIBILITY, + stateKey = "", + body = RoomHistoryVisibilityContent( + historyVisibilityStr = nextRoomHistoryVisibility.historyVisibilityStr + ).toContent() + ) // ensure that the state did synced down - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - aliceRoomPOV.stateService().getStateEvent(EventType.STATE_ROOM_HISTORY_VISIBILITY, QueryStringValue.IsEmpty)?.content - ?.toModel()?.historyVisibility == nextRoomHistoryVisibility.historyVisibility - } + testHelper.retryPeriodically { + aliceRoomPOV.stateService().getStateEvent(EventType.STATE_ROOM_HISTORY_VISIBILITY, QueryStringValue.IsEmpty)?.content + ?.toModel()?.historyVisibility == nextRoomHistoryVisibility.historyVisibility } - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val roomVisibility = aliceSession.getRoom(e2eRoomID)!! - .stateService() - .getStateEvent(EventType.STATE_ROOM_HISTORY_VISIBILITY, QueryStringValue.IsEmpty) - ?.content - ?.toModel() - Log.v("#E2E TEST ROTATION", "Room visibility changed from: ${initRoomHistoryVisibility.name} to: ${roomVisibility?.historyVisibility?.name}") - roomVisibility?.historyVisibility == nextRoomHistoryVisibility.historyVisibility - } + testHelper.retryPeriodically { + val roomVisibility = aliceSession.getRoom(e2eRoomID)!! + .stateService() + .getStateEvent(EventType.STATE_ROOM_HISTORY_VISIBILITY, QueryStringValue.IsEmpty) + ?.content + ?.toModel() + Log.v("#E2E TEST ROTATION", "Room visibility changed from: ${initRoomHistoryVisibility.name} to: ${roomVisibility?.historyVisibility?.name}") + roomVisibility?.historyVisibility == nextRoomHistoryVisibility.historyVisibility } var aliceThirdMessageSessionId: String? = null sendMessageInRoom(aliceRoomPOV, "Message after visibility change", testHelper)?.let { thirdMessage -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = bobRoomPov - ?.timelineService() - ?.getTimelineEvent(thirdMessage) - (timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE).also { - if (it) { - aliceThirdMessageSessionId = timelineEvent?.root?.content?.get("session_id") as? String - } + testHelper.retryPeriodically { + val timelineEvent = bobRoomPov + ?.timelineService() + ?.getTimelineEvent(thirdMessage) + (timelineEvent != null && + timelineEvent.isEncrypted() && + timelineEvent.root.getClearType() == EventType.MESSAGE).also { + if (it) { + aliceThirdMessageSessionId = timelineEvent?.root?.content?.get("session_id") as? String } } } @@ -376,35 +355,31 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { cryptoTestData.cleanUp(testHelper) } - private fun sendMessageInRoom(aliceRoomPOV: Room, text: String, testHelper: CommonTestHelper): String? { - return testHelper.sendTextMessage(aliceRoomPOV, text, 1).firstOrNull()?.eventId + private suspend fun sendMessageInRoom(aliceRoomPOV: Room, text: String, testHelper: CommonTestHelper): String? { + return testHelper.sendTextMessageSuspending(aliceRoomPOV, text, 1).firstOrNull()?.eventId } - private fun ensureMembersHaveJoined(aliceSession: Session, otherAccounts: List, e2eRoomID: String, testHelper: CommonTestHelper) { - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - otherAccounts.map { - aliceSession.roomService().getRoomMember(it.myUserId, e2eRoomID)?.membership - }.all { - it == Membership.JOIN - } + private suspend fun ensureMembersHaveJoined(aliceSession: Session, otherAccounts: List, e2eRoomID: String, testHelper: CommonTestHelper) { + testHelper.retryPeriodically { + otherAccounts.map { + aliceSession.roomService().getRoomMember(it.myUserId, e2eRoomID)?.membership + }.all { + it == Membership.JOIN } } } - private fun waitForAndAcceptInviteInRoom(otherSession: Session, e2eRoomID: String, testHelper: CommonTestHelper) { - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val roomSummary = otherSession.roomService().getRoomSummary(e2eRoomID) - (roomSummary != null && roomSummary.membership == Membership.INVITE).also { - if (it) { - Log.v("#E2E TEST", "${otherSession.myUserId} can see the invite from alice") - } + private suspend fun waitForAndAcceptInviteInRoom(otherSession: Session, e2eRoomID: String, testHelper: CommonTestHelper) { + testHelper.retryPeriodically { + val roomSummary = otherSession.roomService().getRoomSummary(e2eRoomID) + (roomSummary != null && roomSummary.membership == Membership.INVITE).also { + if (it) { + Log.v("#E2E TEST", "${otherSession.myUserId} can see the invite from alice") } } } - testHelper.runBlockingTest(60_000) { + wrapWithTimeout(60_000) { Log.v("#E2E TEST", "${otherSession.myUserId} tries to join room $e2eRoomID") try { otherSession.roomService().joinRoom(e2eRoomID) @@ -414,11 +389,9 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { } Log.v("#E2E TEST", "${otherSession.myUserId} waiting for join echo ...") - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - val roomSummary = otherSession.roomService().getRoomSummary(e2eRoomID) - roomSummary != null && roomSummary.membership == Membership.JOIN - } + testHelper.retryPeriodically { + val roomSummary = otherSession.roomService().getRoomSummary(e2eRoomID) + roomSummary != null && roomSummary.membership == Membership.JOIN } } } From e59cadce549fe3d6430688cdd9788a902dc0b28c Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 12:56:20 +0100 Subject: [PATCH 09/56] replacing direct usages of withTimeout with the deferred result reading version --- .../java/org/matrix/android/sdk/common/CommonTestHelper.kt | 7 +++---- .../java/org/matrix/android/sdk/common/TestExtensions.kt | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index fdde2af495d..7a50b0f019c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -32,7 +32,6 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest -import kotlinx.coroutines.withTimeout import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue @@ -458,11 +457,11 @@ class CommonTestHelper internal constructor(context: Context) { ): Session { val hs = createHomeServerConfig() - withTimeout(TestConstants.timeOutMillis) { + wrapWithTimeout(TestConstants.timeOutMillis) { matrix.authenticationService.getLoginFlow(hs) } - withTimeout(timeMillis = 60_000L) { + wrapWithTimeout(60_000L) { matrix.authenticationService .getRegistrationWizard() .createAccount(userName, password, null) @@ -614,7 +613,7 @@ class CommonTestHelper internal constructor(context: Context) { fun runBlockingTest(timeout: Long = TestConstants.timeOutMillis, block: suspend () -> T): T { return runBlocking { - withTimeout(timeout) { + wrapWithTimeout(timeout) { block() } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt index c98dad7c346..8392dc6a519 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -33,7 +33,7 @@ suspend fun T.onMain(block: T.() -> R): R { } suspend fun LiveData.first(timeout: Long = TestConstants.timeOutMillis, predicate: (T) -> Boolean): T { - return withTimeout(timeout) { + return wrapWithTimeout(timeout) { withContext(Dispatchers.Main) { suspendCoroutine { continuation -> val observer = object : Observer { From 7f0955b6ca6c5e09b25afa3910a7d2df16355c56 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 12:58:28 +0100 Subject: [PATCH 10/56] allowing the live data suspending wrapper to clean up on cancellation --- .../java/org/matrix/android/sdk/common/TestExtensions.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt index 8392dc6a519..786038ba72a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -21,10 +21,10 @@ import androidx.lifecycle.Observer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlin.coroutines.resume -import kotlin.coroutines.suspendCoroutine suspend fun T.onMain(block: T.() -> R): R { return withContext(Dispatchers.Main) { @@ -35,7 +35,7 @@ suspend fun T.onMain(block: T.() -> R): R { suspend fun LiveData.first(timeout: Long = TestConstants.timeOutMillis, predicate: (T) -> Boolean): T { return wrapWithTimeout(timeout) { withContext(Dispatchers.Main) { - suspendCoroutine { continuation -> + suspendCancellableCoroutine { continuation -> val observer = object : Observer { override fun onChanged(data: T) { if (predicate(data)) { @@ -45,6 +45,7 @@ suspend fun LiveData.first(timeout: Long = TestConstants.timeOutMillis, p } } observeForever(observer) + continuation.invokeOnCancellation { removeObserver(observer) } } } } From 6ebda6b8b2a97ede15e6a726101d7aaf442e01d9 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 13:02:55 +0100 Subject: [PATCH 11/56] replacing send message test periodic retries with suspending versions --- .../android/sdk/common/CommonTestHelper.kt | 27 +++++++ .../sdk/internal/crypto/E2eeSanityTests.kt | 76 ++++++++----------- 2 files changed, 58 insertions(+), 45 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 7a50b0f019c..f1ffd52c5d7 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -322,6 +322,33 @@ class CommonTestHelper internal constructor(context: Context) { } } + suspend fun waitForAndAcceptInviteInRoomSuspending(otherSession: Session, roomID: String) { + retryPeriodically { + val roomSummary = otherSession.getRoomSummary(roomID) + (roomSummary != null && roomSummary.membership == Membership.INVITE).also { + if (it) { + Log.v("# TEST", "${otherSession.myUserId} can see the invite") + } + } + } + + // not sure why it's taking so long :/ + wrapWithTimeout(90_000) { + Log.v("#E2E TEST", "${otherSession.myUserId} tries to join room $roomID") + try { + otherSession.roomService().joinRoom(roomID) + } catch (ex: JoinRoomFailure.JoinedWithTimeout) { + // it's ok we will wait after + } + } + + Log.v("#E2E TEST", "${otherSession.myUserId} waiting for join echo ...") + retryPeriodically { + val roomSummary = otherSession.getRoomSummary(roomID) + roomSummary != null && roomSummary.membership == Membership.JOIN + } + } + /** * Reply in a thread * @param room the room where to send the messages diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index 945abb84b30..ea0645e9f83 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -83,7 +83,7 @@ class E2eeSanityTests : InstrumentedTest { * Alice sends a new message, then check that the new one can be decrypted */ @Test - fun testSendingE2EEMessages() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testSendingE2EEMessages() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -105,10 +105,8 @@ class E2eeSanityTests : InstrumentedTest { Log.v("#E2E TEST", "All accounts created") // we want to invite them in the room otherAccounts.forEach { - testHelper.runBlockingTest { - Log.v("#E2E TEST", "Alice invites ${it.myUserId}") - aliceRoomPOV.membershipService().invite(it.myUserId) - } + Log.v("#E2E TEST", "Alice invites ${it.myUserId}") + aliceRoomPOV.membershipService().invite(it.myUserId) } // All user should accept invite @@ -130,51 +128,43 @@ class E2eeSanityTests : InstrumentedTest { // All should be able to decrypt otherAccounts.forEach { otherSession -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId!!) - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + val timeLineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId!!) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } // Add a new user to the room, and check that he can't decrypt val newAccount = listOf("adam") // , "adam", "manu") .map { - testHelper.createAccount(it, SessionTestParams(true)) + testHelper.createAccountSuspending(it, SessionTestParams(true)) } newAccount.forEach { - testHelper.runBlockingTest { - Log.v("#E2E TEST", "Alice invites ${it.myUserId}") - aliceRoomPOV.membershipService().invite(it.myUserId) - } + Log.v("#E2E TEST", "Alice invites ${it.myUserId}") + aliceRoomPOV.membershipService().invite(it.myUserId) } newAccount.forEach { - testHelper.waitForAndAcceptInviteInRoom(it, e2eRoomID) + testHelper.waitForAndAcceptInviteInRoomSuspending(it, e2eRoomID) } ensureMembersHaveJoined(testHelper, aliceSession, newAccount, e2eRoomID) // wait a bit - testHelper.runBlockingTest { - delay(3_000) - } + delay(3_000) // check that messages are encrypted (uisi) newAccount.forEach { otherSession -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId!!).also { - Log.v("#E2E TEST", "Event seen by new user ${it?.root?.getClearType()}|${it?.root?.mCryptoError}") - } - timelineEvent != null && - timelineEvent.root.getClearType() == EventType.ENCRYPTED && - timelineEvent.root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID + testHelper.retryPeriodically { + val timelineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId!!).also { + Log.v("#E2E TEST", "Event seen by new user ${it?.root?.getClearType()}|${it?.root?.mCryptoError}") } + timelineEvent != null && + timelineEvent.root.getClearType() == EventType.ENCRYPTED && + timelineEvent.root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID } } @@ -186,15 +176,13 @@ class E2eeSanityTests : InstrumentedTest { // new members should be able to decrypt it newAccount.forEach { otherSession -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(secondSentEventId!!).also { - Log.v("#E2E TEST", "Second Event seen by new user ${it?.root?.getClearType()}|${it?.root?.mCryptoError}") - } - timelineEvent != null && - timelineEvent.root.getClearType() == EventType.MESSAGE && - secondMessage == timelineEvent.root.getClearContent().toModel()?.body + testHelper.retryPeriodically { + val timelineEvent = otherSession.getRoom(e2eRoomID)?.getTimelineEvent(secondSentEventId!!).also { + Log.v("#E2E TEST", "Second Event seen by new user ${it?.root?.getClearType()}|${it?.root?.mCryptoError}") } + timelineEvent != null && + timelineEvent.root.getClearType() == EventType.MESSAGE && + secondMessage == timelineEvent.root.getClearContent().toModel()?.body } } } @@ -724,14 +712,12 @@ class E2eeSanityTests : InstrumentedTest { ) } - private fun ensureMembersHaveJoined(testHelper: CommonTestHelper, aliceSession: Session, otherAccounts: List, e2eRoomID: String) { - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - otherAccounts.map { - aliceSession.roomService().getRoomMember(it.myUserId, e2eRoomID)?.membership - }.all { - it == Membership.JOIN - } + private suspend fun ensureMembersHaveJoined(testHelper: CommonTestHelper, aliceSession: Session, otherAccounts: List, e2eRoomID: String) { + testHelper.retryPeriodically { + otherAccounts.map { + aliceSession.roomService().getRoomMember(it.myUserId, e2eRoomID)?.membership + }.all { + it == Membership.JOIN } } } From 71d18bbe27efc3b12b02de7e6183de234be9111a Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 14:11:08 +0100 Subject: [PATCH 12/56] forcing periodic retries to block the test thread --- .../java/org/matrix/android/sdk/common/CommonTestHelper.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index f1ffd52c5d7..8c7445bfa35 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -495,7 +495,7 @@ class CommonTestHelper internal constructor(context: Context) { } // Perform dummy step - val registrationResult = runBlockingTest(timeout = 60_000) { + val registrationResult = wrapWithTimeout(timeout = 60_000) { matrix.authenticationService .getRegistrationWizard() .dummy() @@ -601,10 +601,10 @@ class CommonTestHelper internal constructor(context: Context) { ) } - suspend fun retryPeriodically(timeout: Long = TestConstants.timeOutMillis, predicate: () -> Boolean) { + suspend fun retryPeriodically(timeout: Long = TestConstants.timeOutMillis, predicate: suspend () -> Boolean) { wrapWithTimeout(timeout) { while (!predicate()) { - delay(1000) + runBlocking { delay(1000) } } } } From 24a7ea9d194dfce9929a2c4f0f264a2479b8b3b3 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 14:16:14 +0100 Subject: [PATCH 13/56] using suspending message sending and removing duplicated retry rule --- .../sdk/internal/crypto/E2eeSanityTests.kt | 41 ++++++++----------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index ea0645e9f83..df0f87f88e4 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -60,7 +60,6 @@ import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams -import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.common.TestMatrixCallback import org.matrix.android.sdk.mustFail import java.util.concurrent.CountDownLatch @@ -71,8 +70,6 @@ import java.util.concurrent.CountDownLatch @LargeTest class E2eeSanityTests : InstrumentedTest { - @get:Rule val rule = RetryTestRule(3) - /** * Simple test that create an e2ee room. * Some new members are added, and a message is sent. @@ -323,7 +320,7 @@ class E2eeSanityTests : InstrumentedTest { * get them from an older one. */ @Test - fun testSimpleGossip() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testSimpleGossip() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -423,7 +420,7 @@ class E2eeSanityTests : InstrumentedTest { * Test that if a better key is forwarded (lower index, it is then used) */ @Test - fun testForwardBetterKey() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testForwardBetterKey() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -541,27 +538,25 @@ class E2eeSanityTests : InstrumentedTest { } } - private fun sendMessageInRoom(testHelper: CommonTestHelper, aliceRoomPOV: Room, text: String): String? { - aliceRoomPOV.sendService().sendTextMessage(text) + private suspend fun sendMessageInRoom(testHelper: CommonTestHelper, aliceRoomPOV: Room, text: String): String? { var sentEventId: String? = null - testHelper.waitWithLatch(4 * TestConstants.timeOutMillis) { latch -> - val timeline = aliceRoomPOV.timelineService().createTimeline(null, TimelineSettings(60)) - timeline.start() - testHelper.retryPeriodicallyWithLatch(latch) { - val decryptedMsg = timeline.getSnapshot() - .filter { it.root.getClearType() == EventType.MESSAGE } - .also { list -> - val message = list.joinToString(",", "[", "]") { "${it.root.type}|${it.root.sendState}" } - Log.v("#E2E TEST", "Timeline snapshot is $message") - } - .filter { it.root.sendState == SendState.SYNCED } - .firstOrNull { it.root.getClearContent().toModel()?.body?.startsWith(text) == true } - sentEventId = decryptedMsg?.eventId - decryptedMsg != null - } + aliceRoomPOV.sendService().sendTextMessage(text) - timeline.dispose() + val timeline = aliceRoomPOV.timelineService().createTimeline(null, TimelineSettings(60)) + timeline.start() + testHelper.retryPeriodically { + val decryptedMsg = timeline.getSnapshot() + .filter { it.root.getClearType() == EventType.MESSAGE } + .also { list -> + val message = list.joinToString(",", "[", "]") { "${it.root.type}|${it.root.sendState}" } + Log.v("#E2E TEST", "Timeline snapshot is $message") + } + .filter { it.root.sendState == SendState.SYNCED } + .firstOrNull { it.root.getClearContent().toModel()?.body?.startsWith(text) == true } + sentEventId = decryptedMsg?.eventId + decryptedMsg != null } + timeline.dispose() return sentEventId } From 40042637f885e160acc602f04ae42c59df0696cb Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 14:46:11 +0100 Subject: [PATCH 14/56] using default context when running tests to allow delays to execute - replaces some more runBlocking/periodic lateches --- .../android/sdk/common/CommonTestHelper.kt | 5 +++- .../android/sdk/common/CryptoTestHelper.kt | 30 ++++++++----------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 8c7445bfa35..44a2da907b3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue @@ -97,7 +98,9 @@ class CommonTestHelper internal constructor(context: Context) { val cryptoTestHelper = CryptoTestHelper(testHelper) return runTest { try { - block(cryptoTestHelper, testHelper) + withContext(Dispatchers.Default) { + block(cryptoTestHelper, testHelper) + } } finally { if (autoSignoutOnClose) { testHelper.cleanUpOpenedSessions() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 3f8132dd6fa..67a2cee3da9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -74,12 +74,10 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { return testHelper.launch { val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, defaultSessionParams) - val roomId = testHelper.runBlockingTest { - aliceSession.roomService().createRoom(CreateRoomParams().apply { - historyVisibility = roomHistoryVisibility - name = "MyRoom" - }) - } + val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { + historyVisibility = roomHistoryVisibility + name = "MyRoom" + }) if (encryptedRoom) { val room = aliceSession.getRoom(roomId)!! waitFor( @@ -176,17 +174,15 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } } - private fun ensureEventReceived(roomId: String, eventId: String, session: Session, andCanDecrypt: Boolean) { - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = session.getRoom(roomId)?.timelineService()?.getTimelineEvent(eventId) - if (andCanDecrypt) { - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } else { - timeLineEvent != null - } + private suspend fun ensureEventReceived(roomId: String, eventId: String, session: Session, andCanDecrypt: Boolean) { + testHelper.retryPeriodically { + val timeLineEvent = session.getRoom(roomId)?.timelineService()?.getTimelineEvent(eventId) + if (andCanDecrypt) { + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE + } else { + timeLineEvent != null } } } From e39faa8e0083b0d4eb05d2556f0f6fe69633e0ab Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 14:50:28 +0100 Subject: [PATCH 15/56] replacing latches with suspending versions --- .../internal/crypto/E2EShareKeysConfigTest.kt | 114 ++++++++---------- 1 file changed, 47 insertions(+), 67 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt index 32d63a19342..e20ff35ae75 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt @@ -36,11 +36,10 @@ import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.CryptoTestData import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants -import org.matrix.android.sdk.common.TestMatrixCallback @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @@ -48,44 +47,38 @@ import org.matrix.android.sdk.common.TestMatrixCallback class E2EShareKeysConfigTest : InstrumentedTest { @Test - fun msc3061ShouldBeDisabledByDefault() = runCryptoTest(context()) { _, commonTestHelper -> - val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) + fun msc3061ShouldBeDisabledByDefault() = runSuspendingCryptoTest(context()) { _, commonTestHelper -> + val aliceSession = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) Assert.assertFalse("MSC3061 is lab and should be disabled by default", aliceSession.cryptoService().isShareKeysOnInviteEnabled()) } @Test - fun ensureKeysAreNotSharedIfOptionDisabled() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + fun ensureKeysAreNotSharedIfOptionDisabled() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + val aliceSession = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) aliceSession.cryptoService().enableShareKeyOnInvite(false) - val roomId = commonTestHelper.runBlockingTest { - aliceSession.roomService().createRoom(CreateRoomParams().apply { - historyVisibility = RoomHistoryVisibility.SHARED - name = "MyRoom" - enableEncryption() - }) - } - - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession.roomService().getRoomSummary(roomId)?.isEncrypted == true - } + val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { + historyVisibility = RoomHistoryVisibility.SHARED + name = "MyRoom" + enableEncryption() + }) + + commonTestHelper.retryPeriodically { + aliceSession.roomService().getRoomSummary(roomId)?.isEncrypted == true } val roomAlice = aliceSession.roomService().getRoom(roomId)!! // send some messages - val withSession1 = commonTestHelper.sendTextMessage(roomAlice, "Hello", 1) + val withSession1 = commonTestHelper.sendTextMessageSuspending(roomAlice, "Hello", 1) aliceSession.cryptoService().discardOutboundSession(roomId) - val withSession2 = commonTestHelper.sendTextMessage(roomAlice, "World", 1) + val withSession2 = commonTestHelper.sendTextMessageSuspending(roomAlice, "World", 1) // Create bob account - val bobSession = commonTestHelper.createAccount(TestConstants.USER_BOB, SessionTestParams(withInitialSync = true)) + val bobSession = commonTestHelper.createAccountSuspending(TestConstants.USER_BOB, SessionTestParams(withInitialSync = true)) // Let alice invite bob - commonTestHelper.runBlockingTest { - roomAlice.membershipService().invite(bobSession.myUserId) - } + roomAlice.membershipService().invite(bobSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoom(bobSession, roomId) + commonTestHelper.waitForAndAcceptInviteInRoomSuspending(bobSession, roomId) // Bob has join but should not be able to decrypt history cryptoTestHelper.ensureCannotDecrypt( @@ -101,7 +94,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { aliceSession.cryptoService().enableShareKeyOnInvite(true) // let's add a new message first - val afterFlagOn = commonTestHelper.sendTextMessage(roomAlice, "After", 1) + val afterFlagOn = commonTestHelper.sendTextMessageSuspending(roomAlice, "After", 1) // Worth nothing to check that the session was rotated Assert.assertNotEquals( @@ -111,14 +104,12 @@ class E2EShareKeysConfigTest : InstrumentedTest { ) // Invite a new user - val samSession = commonTestHelper.createAccount(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) + val samSession = commonTestHelper.createAccountSuspending(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) // Let alice invite sam - commonTestHelper.runBlockingTest { - roomAlice.membershipService().invite(samSession.myUserId) - } + roomAlice.membershipService().invite(samSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoom(samSession, roomId) + commonTestHelper.waitForAndAcceptInviteInRoomSuspending(samSession, roomId) // Sam shouldn't be able to decrypt messages with the first session, but should decrypt the one with 3rd session cryptoTestHelper.ensureCannotDecrypt( @@ -135,7 +126,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { } @Test - fun ifSharingDisabledOnAliceSideBobShouldNotShareAliceHistoty() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun ifSharingDisabledOnAliceSideBobShouldNotShareAliceHistory() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(roomHistoryVisibility = RoomHistoryVisibility.SHARED) val aliceSession = testData.firstSession.also { it.cryptoService().enableShareKeyOnInvite(false) @@ -162,7 +153,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { } @Test - fun ifSharingEnabledOnAliceSideBobShouldShareAliceHistoty() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun ifSharingEnabledOnAliceSideBobShouldShareAliceHistory() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(roomHistoryVisibility = RoomHistoryVisibility.SHARED) val aliceSession = testData.firstSession.also { it.cryptoService().enableShareKeyOnInvite(true) @@ -186,48 +177,42 @@ class E2EShareKeysConfigTest : InstrumentedTest { fromBobSharable.map { it.root.getClearContent()?.get("body") as String }) } - private fun commonAliceAndBobSendMessages(commonTestHelper: CommonTestHelper, aliceSession: Session, testData: CryptoTestData, bobSession: Session): Triple, List, Session> { - val fromAliceNotSharable = commonTestHelper.sendTextMessage(aliceSession.getRoom(testData.roomId)!!, "Hello from alice", 1) - val fromBobSharable = commonTestHelper.sendTextMessage(bobSession.getRoom(testData.roomId)!!, "Hello from bob", 1) + private suspend fun commonAliceAndBobSendMessages(commonTestHelper: CommonTestHelper, aliceSession: Session, testData: CryptoTestData, bobSession: Session): Triple, List, Session> { + val fromAliceNotSharable = commonTestHelper.sendTextMessageSuspending(aliceSession.getRoom(testData.roomId)!!, "Hello from alice", 1) + val fromBobSharable = commonTestHelper.sendTextMessageSuspending(bobSession.getRoom(testData.roomId)!!, "Hello from bob", 1) // Now let bob invite Sam // Invite a new user - val samSession = commonTestHelper.createAccount(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) + val samSession = commonTestHelper.createAccountSuspending(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) // Let bob invite sam - commonTestHelper.runBlockingTest { - bobSession.getRoom(testData.roomId)!!.membershipService().invite(samSession.myUserId) - } + bobSession.getRoom(testData.roomId)!!.membershipService().invite(samSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoom(samSession, testData.roomId) + commonTestHelper.waitForAndAcceptInviteInRoomSuspending(samSession, testData.roomId) return Triple(fromAliceNotSharable, fromBobSharable, samSession) } // test flag on backup is correct @Test - fun testBackupFlagIsCorrect() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + fun testBackupFlagIsCorrect() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + val aliceSession = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) aliceSession.cryptoService().enableShareKeyOnInvite(false) - val roomId = commonTestHelper.runBlockingTest { - aliceSession.roomService().createRoom(CreateRoomParams().apply { - historyVisibility = RoomHistoryVisibility.SHARED - name = "MyRoom" - enableEncryption() - }) - } - - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession.roomService().getRoomSummary(roomId)?.isEncrypted == true - } + val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { + historyVisibility = RoomHistoryVisibility.SHARED + name = "MyRoom" + enableEncryption() + }) + + commonTestHelper.retryPeriodically { + aliceSession.roomService().getRoomSummary(roomId)?.isEncrypted == true } val roomAlice = aliceSession.roomService().getRoom(roomId)!! // send some messages - val notSharableMessage = commonTestHelper.sendTextMessage(roomAlice, "Hello", 1) + val notSharableMessage = commonTestHelper.sendTextMessageSuspending(roomAlice, "Hello", 1) aliceSession.cryptoService().enableShareKeyOnInvite(true) - val sharableMessage = commonTestHelper.sendTextMessage(roomAlice, "World", 1) + val sharableMessage = commonTestHelper.sendTextMessageSuspending(roomAlice, "World", 1) Log.v("#E2E TEST", "Create and start key backup for bob ...") val keysBackupService = aliceSession.cryptoService().keysBackupService() @@ -239,11 +224,8 @@ class E2EShareKeysConfigTest : InstrumentedTest { keysBackupService.createKeysBackupVersion(megolmBackupCreationInfo, it) } - commonTestHelper.waitWithLatch { latch -> - keysBackupService.backupAllGroupSessions( - null, - TestMatrixCallback(latch, true) - ) + commonTestHelper.doSync { + keysBackupService.backupAllGroupSessions(null, it) } // signout @@ -273,14 +255,12 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Now let's invite sam // Invite a new user - val samSession = commonTestHelper.createAccount(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) + val samSession = commonTestHelper.createAccountSuspending(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) // Let alice invite sam - commonTestHelper.runBlockingTest { - newAliceSession.getRoom(roomId)!!.membershipService().invite(samSession.myUserId) - } + newAliceSession.getRoom(roomId)!!.membershipService().invite(samSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoom(samSession, roomId) + commonTestHelper.waitForAndAcceptInviteInRoomSuspending(samSession, roomId) // Sam shouldn't be able to decrypt messages with the first session, but should decrypt the one with 3rd session cryptoTestHelper.ensureCannotDecrypt( From ad5ec06e5cb19077a6db2bcad67831abeb286e8b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 15:41:16 +0100 Subject: [PATCH 16/56] adding suspending account login helpers --- .../android/sdk/common/CommonTestHelper.kt | 36 +++++++++ .../android/sdk/common/CryptoTestHelper.kt | 76 +++++++++---------- 2 files changed, 73 insertions(+), 39 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 44a2da907b3..96af7bd50c9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -145,6 +145,10 @@ class CommonTestHelper internal constructor(context: Context) { return logIntoAccount(userId, TestConstants.PASSWORD, testParams) } + suspend fun logIntoAccountSuspending(userId: String, testParams: SessionTestParams): Session { + return logIntoAccountSuspending(userId, TestConstants.PASSWORD, testParams) + } + fun cleanUpOpenedSessions() { trackedSessions.forEach { runBlockingTest { @@ -440,6 +444,18 @@ class CommonTestHelper internal constructor(context: Context) { } } + suspend fun logIntoAccountSuspending( + userId: String, + password: String, + testParams: SessionTestParams + ): Session { + val session = logAccountAndSyncSuspending(userId, password, testParams) + assertNotNull(session) + return session.also { + trackedSessions.add(session) + } + } + /** * Create an account and a dedicated session * @@ -544,6 +560,26 @@ class CommonTestHelper internal constructor(context: Context) { return session } + private suspend fun logAccountAndSyncSuspending( + userName: String, + password: String, + sessionTestParams: SessionTestParams + ): Session { + val hs = createHomeServerConfig() + + matrix.authenticationService.getLoginFlow(hs) + + val session = matrix.authenticationService + .getLoginWizard() + .login(userName, password, "myDevice") + session.open() + if (sessionTestParams.withInitialSync) { + syncSessionSuspending(session) + } + + return session + } + /** * Log into the account and expect an error * diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 67a2cee3da9..00e1fdb0a6f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -260,53 +260,51 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { /** * Initialize cross-signing, set up megolm backup and save all in 4S */ - fun bootstrapSecurity(session: Session) { + suspend fun bootstrapSecurity(session: Session) { initializeCrossSigning(session) val ssssService = session.sharedSecretStorageService() - testHelper.runBlockingTest { - val keyInfo = ssssService.generateKey( - UUID.randomUUID().toString(), - null, - "ssss_key", - EmptyKeySigner() - ) - ssssService.setDefaultKey(keyInfo.keyId) + val keyInfo = ssssService.generateKey( + UUID.randomUUID().toString(), + null, + "ssss_key", + EmptyKeySigner() + ) + ssssService.setDefaultKey(keyInfo.keyId) - ssssService.storeSecret( - MASTER_KEY_SSSS_NAME, - session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.master!!, - listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) - ) + ssssService.storeSecret( + MASTER_KEY_SSSS_NAME, + session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.master!!, + listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) - ssssService.storeSecret( - SELF_SIGNING_KEY_SSSS_NAME, - session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.selfSigned!!, - listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) - ) + ssssService.storeSecret( + SELF_SIGNING_KEY_SSSS_NAME, + session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.selfSigned!!, + listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) + ssssService.storeSecret( + USER_SIGNING_KEY_SSSS_NAME, + session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.user!!, + listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) + ) + + // set up megolm backup + val creationInfo = testHelper.doSync { + session.cryptoService().keysBackupService().prepareKeysBackupVersion(null, null, it) + } + val version = testHelper.doSync { + session.cryptoService().keysBackupService().createKeysBackupVersion(creationInfo, it) + } + // Save it for gossiping + session.cryptoService().keysBackupService().saveBackupRecoveryKey(creationInfo.recoveryKey, version = version.version) + + extractCurveKeyFromRecoveryKey(creationInfo.recoveryKey)?.toBase64NoPadding()?.let { secret -> ssssService.storeSecret( - USER_SIGNING_KEY_SSSS_NAME, - session.cryptoService().crossSigningService().getCrossSigningPrivateKeys()!!.user!!, + KEYBACKUP_SECRET_SSSS_NAME, + secret, listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) ) - - // set up megolm backup - val creationInfo = awaitCallback { - session.cryptoService().keysBackupService().prepareKeysBackupVersion(null, null, it) - } - val version = awaitCallback { - session.cryptoService().keysBackupService().createKeysBackupVersion(creationInfo, it) - } - // Save it for gossiping - session.cryptoService().keysBackupService().saveBackupRecoveryKey(creationInfo.recoveryKey, version = version.version) - - extractCurveKeyFromRecoveryKey(creationInfo.recoveryKey)?.toBase64NoPadding()?.let { secret -> - ssssService.storeSecret( - KEYBACKUP_SECRET_SSSS_NAME, - secret, - listOf(KeyRef(keyInfo.keyId, keyInfo.keySpec)) - ) - } } } From 2470796fde36229617b324062d466ba27ebc24a2 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 15:44:36 +0100 Subject: [PATCH 17/56] replace latches with suspending funcs --- .../sdk/internal/crypto/E2eeSanityTests.kt | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index df0f87f88e4..c444ad73bf3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -564,14 +564,14 @@ class E2eeSanityTests : InstrumentedTest { * Test that if a better key is forwared (lower index, it is then used) */ @Test - fun testASelfInteractiveVerificationAndGossip() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testASelfInteractiveVerificationAndGossip() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> - val aliceSession = testHelper.createAccount("alice", SessionTestParams(true)) + val aliceSession = testHelper.createAccountSuspending("alice", SessionTestParams(true)) cryptoTestHelper.bootstrapSecurity(aliceSession) // now let's create a new login from alice - val aliceNewSession = testHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) + val aliceNewSession = testHelper.logIntoAccountSuspending(aliceSession.myUserId, SessionTestParams(true)) val oldCompleteLatch = CountDownLatch(1) lateinit var oldCode: String @@ -665,16 +665,12 @@ class E2eeSanityTests : InstrumentedTest { Assert.assertTrue("old device should be verified from new point of view", oldDeviceFromNewPov!!.isVerified) // wait for secret gossiping to happen - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - aliceNewSession.cryptoService().crossSigningService().allPrivateKeysKnown() - } + testHelper.retryPeriodically { + aliceNewSession.cryptoService().crossSigningService().allPrivateKeysKnown() } - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - aliceNewSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo() != null - } + testHelper.retryPeriodically { + aliceNewSession.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo() != null } assertEquals( From c42d6f1ec08f7d1e23d2d4a9ec3c98846c0dcf92 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 16:07:41 +0100 Subject: [PATCH 18/56] converting auto verification test to coroutine suspends --- .../android/sdk/common/CommonTestHelper.kt | 2 +- .../sdk/internal/crypto/E2eeSanityTests.kt | 195 ++++++++++-------- 2 files changed, 109 insertions(+), 88 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 96af7bd50c9..243b4a07389 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -93,7 +93,7 @@ class CommonTestHelper internal constructor(context: Context) { } @OptIn(ExperimentalCoroutinesApi::class) - internal fun runSuspendingCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend (CryptoTestHelper, CommonTestHelper) -> Unit) { + internal fun runSuspendingCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CryptoTestHelper, CommonTestHelper) -> Unit) { val testHelper = CommonTestHelper(context) val cryptoTestHelper = CryptoTestHelper(testHelper) return runTest { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index c444ad73bf3..f319d9de15c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -18,12 +18,16 @@ package org.matrix.android.sdk.internal.crypto import android.util.Log import androidx.test.filters.LargeTest +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll import kotlinx.coroutines.delay +import kotlinx.coroutines.suspendCancellableCoroutine import org.amshove.kluent.fail import org.amshove.kluent.internal.assertEquals import org.junit.Assert import org.junit.FixMethodOrder -import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @@ -55,14 +59,12 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest -import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestMatrixCallback import org.matrix.android.sdk.mustFail -import java.util.concurrent.CountDownLatch +import kotlin.coroutines.resume // @Ignore("This test fails with an unhandled exception thrown from a coroutine which terminates the entire test run.") @RunWith(JUnit4::class) @@ -573,86 +575,18 @@ class E2eeSanityTests : InstrumentedTest { val aliceNewSession = testHelper.logIntoAccountSuspending(aliceSession.myUserId, SessionTestParams(true)) - val oldCompleteLatch = CountDownLatch(1) - lateinit var oldCode: String - aliceSession.cryptoService().verificationService().addListener(object : VerificationService.Listener { - - override fun verificationRequestUpdated(pr: PendingVerificationRequest) { - val readyInfo = pr.readyInfo - if (readyInfo != null) { - aliceSession.cryptoService().verificationService().beginKeyVerification( - VerificationMethod.SAS, - aliceSession.myUserId, - readyInfo.fromDevice, - readyInfo.transactionId - - ) - } - } - - override fun transactionUpdated(tx: VerificationTransaction) { - Log.d("##TEST", "exitsingPov: $tx") - val sasTx = tx as OutgoingSasVerificationTransaction - when (sasTx.uxState) { - OutgoingSasVerificationTransaction.UxState.SHOW_SAS -> { - // for the test we just accept? - oldCode = sasTx.getDecimalCodeRepresentation() - sasTx.userHasVerifiedShortCode() - } - OutgoingSasVerificationTransaction.UxState.VERIFIED -> { - // we can release this latch? - oldCompleteLatch.countDown() - } - else -> Unit - } - } - }) - - val newCompleteLatch = CountDownLatch(1) - lateinit var newCode: String - aliceNewSession.cryptoService().verificationService().addListener(object : VerificationService.Listener { - - override fun verificationRequestCreated(pr: PendingVerificationRequest) { - // let's ready - aliceNewSession.cryptoService().verificationService().readyPendingVerification( - listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW), - aliceSession.myUserId, - pr.transactionId!! - ) - } - - var matchOnce = true - override fun transactionUpdated(tx: VerificationTransaction) { - Log.d("##TEST", "newPov: $tx") - - val sasTx = tx as IncomingSasVerificationTransaction - when (sasTx.uxState) { - IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT -> { - // no need to accept as there was a request first it will auto accept - } - IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { - if (matchOnce) { - sasTx.userHasVerifiedShortCode() - newCode = sasTx.getDecimalCodeRepresentation() - matchOnce = false - } - } - IncomingSasVerificationTransaction.UxState.VERIFIED -> { - newCompleteLatch.countDown() - } - else -> Unit - } - } - }) - + val deferredOldCode = aliceSession.cryptoService().verificationService().readOldVerificationCodeAsync(this, aliceSession.myUserId) + val deferredNewCode = aliceNewSession.cryptoService().verificationService().readNewVerificationCodeAsync(this, aliceSession.myUserId) // initiate self verification aliceSession.cryptoService().verificationService().requestKeyVerification( listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW), aliceNewSession.myUserId, listOf(aliceNewSession.sessionParams.deviceId!!) ) - testHelper.await(oldCompleteLatch) - testHelper.await(newCompleteLatch) + + + val (oldCode, newCode) = awaitAll(deferredOldCode, deferredNewCode) + assertEquals("Decimal code should have matched", oldCode, newCode) // Assert that devices are verified @@ -703,6 +637,95 @@ class E2eeSanityTests : InstrumentedTest { ) } + private suspend fun VerificationService.readOldVerificationCodeAsync(scope: CoroutineScope, userId: String): Deferred { + return scope.async { + suspendCancellableCoroutine { continuation -> + var oldCode: String? = null + val listener = object : VerificationService.Listener { + + override fun verificationRequestUpdated(pr: PendingVerificationRequest) { + val readyInfo = pr.readyInfo + if (readyInfo != null) { + beginKeyVerification( + VerificationMethod.SAS, + userId, + readyInfo.fromDevice, + readyInfo.transactionId + + ) + } + } + + override fun transactionUpdated(tx: VerificationTransaction) { + Log.d("##TEST", "exitsingPov: $tx") + val sasTx = tx as OutgoingSasVerificationTransaction + when (sasTx.uxState) { + OutgoingSasVerificationTransaction.UxState.SHOW_SAS -> { + // for the test we just accept? + oldCode = sasTx.getDecimalCodeRepresentation() + sasTx.userHasVerifiedShortCode() + } + OutgoingSasVerificationTransaction.UxState.VERIFIED -> { + // we can release this latch? + continuation.resume(oldCode!!) + removeListener(this) + } + else -> Unit + } + } + } + addListener(listener) + continuation.invokeOnCancellation { removeListener(listener) } + } + } + } + + private suspend fun VerificationService.readNewVerificationCodeAsync(scope: CoroutineScope, userId: String): Deferred { + return scope.async { + suspendCancellableCoroutine { continuation -> + var newCode: String? = null + + val listener = object : VerificationService.Listener { + + override fun verificationRequestCreated(pr: PendingVerificationRequest) { + // let's ready + readyPendingVerification( + listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW), + userId, + pr.transactionId!! + ) + } + + var matchOnce = true + override fun transactionUpdated(tx: VerificationTransaction) { + Log.d("##TEST", "newPov: $tx") + + val sasTx = tx as IncomingSasVerificationTransaction + when (sasTx.uxState) { + IncomingSasVerificationTransaction.UxState.SHOW_ACCEPT -> { + // no need to accept as there was a request first it will auto accept + } + IncomingSasVerificationTransaction.UxState.SHOW_SAS -> { + if (matchOnce) { + sasTx.userHasVerifiedShortCode() + newCode = sasTx.getDecimalCodeRepresentation() + matchOnce = false + } + } + IncomingSasVerificationTransaction.UxState.VERIFIED -> { + continuation.resume(newCode!!) + removeListener(this) + } + else -> Unit + } + } + } + addListener(listener) + continuation.invokeOnCancellation { removeListener(listener) } + } + } + } + private suspend fun ensureMembersHaveJoined(testHelper: CommonTestHelper, aliceSession: Session, otherAccounts: List, e2eRoomID: String) { testHelper.retryPeriodically { otherAccounts.map { @@ -713,15 +736,13 @@ class E2eeSanityTests : InstrumentedTest { } } - private fun ensureIsDecrypted(testHelper: CommonTestHelper, sentEventIds: List, session: Session, e2eRoomID: String) { - testHelper.waitWithLatch { latch -> - sentEventIds.forEach { sentEventId -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = session.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } + private suspend fun ensureIsDecrypted(testHelper: CommonTestHelper, sentEventIds: List, session: Session, e2eRoomID: String) { + sentEventIds.forEach { sentEventId -> + testHelper.retryPeriodically { + val timeLineEvent = session.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } } From 62338ed8a590f25ebefe140f97ab3aa7a21350e1 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 16:37:31 +0100 Subject: [PATCH 19/56] removing unused non suspending wait for invite - replaces latches in basic import test - reduces the periodic delay, slightly improving test run time --- .../android/sdk/common/CommonTestHelper.kt | 35 +---------------- .../internal/crypto/E2EShareKeysConfigTest.kt | 8 ++-- .../sdk/internal/crypto/E2eeSanityTests.kt | 39 +++++++------------ 3 files changed, 19 insertions(+), 63 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 243b4a07389..ab02616c248 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -298,38 +298,7 @@ class CommonTestHelper internal constructor(context: Context) { return sentEvents } - fun waitForAndAcceptInviteInRoom(otherSession: Session, roomID: String) { - waitWithLatch { latch -> - retryPeriodicallyWithLatch(latch) { - val roomSummary = otherSession.getRoomSummary(roomID) - (roomSummary != null && roomSummary.membership == Membership.INVITE).also { - if (it) { - Log.v("# TEST", "${otherSession.myUserId} can see the invite") - } - } - } - } - - // not sure why it's taking so long :/ - runBlockingTest(90_000) { - Log.v("#E2E TEST", "${otherSession.myUserId} tries to join room $roomID") - try { - otherSession.roomService().joinRoom(roomID) - } catch (ex: JoinRoomFailure.JoinedWithTimeout) { - // it's ok we will wait after - } - } - - Log.v("#E2E TEST", "${otherSession.myUserId} waiting for join echo ...") - waitWithLatch { - retryPeriodicallyWithLatch(it) { - val roomSummary = otherSession.getRoomSummary(roomID) - roomSummary != null && roomSummary.membership == Membership.JOIN - } - } - } - - suspend fun waitForAndAcceptInviteInRoomSuspending(otherSession: Session, roomID: String) { + suspend fun waitForAndAcceptInviteInRoom(otherSession: Session, roomID: String) { retryPeriodically { val roomSummary = otherSession.getRoomSummary(roomID) (roomSummary != null && roomSummary.membership == Membership.INVITE).also { @@ -643,7 +612,7 @@ class CommonTestHelper internal constructor(context: Context) { suspend fun retryPeriodically(timeout: Long = TestConstants.timeOutMillis, predicate: suspend () -> Boolean) { wrapWithTimeout(timeout) { while (!predicate()) { - runBlocking { delay(1000) } + runBlocking { delay(500) } } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt index e20ff35ae75..5776f6e58e5 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt @@ -78,7 +78,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Let alice invite bob roomAlice.membershipService().invite(bobSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoomSuspending(bobSession, roomId) + commonTestHelper.waitForAndAcceptInviteInRoom(bobSession, roomId) // Bob has join but should not be able to decrypt history cryptoTestHelper.ensureCannotDecrypt( @@ -109,7 +109,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Let alice invite sam roomAlice.membershipService().invite(samSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoomSuspending(samSession, roomId) + commonTestHelper.waitForAndAcceptInviteInRoom(samSession, roomId) // Sam shouldn't be able to decrypt messages with the first session, but should decrypt the one with 3rd session cryptoTestHelper.ensureCannotDecrypt( @@ -188,7 +188,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Let bob invite sam bobSession.getRoom(testData.roomId)!!.membershipService().invite(samSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoomSuspending(samSession, testData.roomId) + commonTestHelper.waitForAndAcceptInviteInRoom(samSession, testData.roomId) return Triple(fromAliceNotSharable, fromBobSharable, samSession) } @@ -260,7 +260,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Let alice invite sam newAliceSession.getRoom(roomId)!!.membershipService().invite(samSession.myUserId) - commonTestHelper.waitForAndAcceptInviteInRoomSuspending(samSession, roomId) + commonTestHelper.waitForAndAcceptInviteInRoom(samSession, roomId) // Sam shouldn't be able to decrypt messages with the first session, but should decrypt the one with 3rd session cryptoTestHelper.ensureCannotDecrypt( diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index f319d9de15c..6ffc8cc9af9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -62,7 +62,6 @@ import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.SessionTestParams -import org.matrix.android.sdk.common.TestMatrixCallback import org.matrix.android.sdk.mustFail import kotlin.coroutines.resume @@ -96,7 +95,7 @@ class E2eeSanityTests : InstrumentedTest { // add some more users and invite them val otherAccounts = listOf("benoit", "valere", "ganfra") // , "adam", "manu") .map { - testHelper.createAccount(it, SessionTestParams(true)).also { + testHelper.createAccountSuspending(it, SessionTestParams(true)).also { it.cryptoService().enableKeyGossiping(false) } } @@ -147,7 +146,7 @@ class E2eeSanityTests : InstrumentedTest { } newAccount.forEach { - testHelper.waitForAndAcceptInviteInRoomSuspending(it, e2eRoomID) + testHelper.waitForAndAcceptInviteInRoom(it, e2eRoomID) } ensureMembersHaveJoined(testHelper, aliceSession, newAccount, e2eRoomID) @@ -236,30 +235,21 @@ class E2eeSanityTests : InstrumentedTest { sentEventIds.add(it) } - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + val timeLineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } // we want more so let's discard the session aliceSession.cryptoService().discardOutboundSession(e2eRoomID) - - delay(1_000) } Log.v("#E2E TEST", "Bob received all and can decrypt") // Let's wait a bit to be sure that bob has backed up the session Log.v("#E2E TEST", "Force key backup for Bob...") - testHelper.waitWithLatch { latch -> - bobKeysBackupService.backupAllGroupSessions( - null, - TestMatrixCallback(latch, true) - ) - } + testHelper.doSync { bobKeysBackupService.backupAllGroupSessions(null, it) } Log.v("#E2E TEST", "... Key backup done for Bob") // Now lets logout both alice and bob to ensure that we won't have any gossiping @@ -274,19 +264,16 @@ class E2eeSanityTests : InstrumentedTest { // Create a new session for bob Log.v("#E2E TEST", "Create a new session for Bob") - val newBobSession = testHelper.logIntoAccount(bobUserId, SessionTestParams(true)) + val newBobSession = testHelper.logIntoAccountSuspending(bobUserId, SessionTestParams(true)) // check that bob can't currently decrypt Log.v("#E2E TEST", "check that bob can't currently decrypt") sentEventIds.forEach { sentEventId -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timelineEvent = newBobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId)?.also { - Log.v("#E2E TEST", "Event seen by new user ${it.root.getClearType()}|${it.root.mCryptoError}") - } - timelineEvent != null && - timelineEvent.root.getClearType() == EventType.ENCRYPTED + testHelper.retryPeriodically { + val timelineEvent = newBobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId)?.also { + Log.v("#E2E TEST", "Event seen by new user ${it.root.getClearType()}|${it.root.mCryptoError}") } + timelineEvent != null && timelineEvent.root.getClearType() == EventType.ENCRYPTED } } // after initial sync events are not decrypted, so we have to try manually From 942e3bd50a33d6c77a35101ee5198f4cee9facdf Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 17:09:10 +0100 Subject: [PATCH 20/56] increasing the default runTest timeout --- .../java/org/matrix/android/sdk/common/CommonTestHelper.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index ab02616c248..d0cb58ff027 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -96,7 +96,7 @@ class CommonTestHelper internal constructor(context: Context) { internal fun runSuspendingCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CryptoTestHelper, CommonTestHelper) -> Unit) { val testHelper = CommonTestHelper(context) val cryptoTestHelper = CryptoTestHelper(testHelper) - return runTest { + return runTest(dispatchTimeoutMs = TestConstants.timeOutMillis) { try { withContext(Dispatchers.Default) { block(cryptoTestHelper, testHelper) From 46434c8fd07e2f25294a80504e2647e641d416c8 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 20 Sep 2022 17:09:28 +0100 Subject: [PATCH 21/56] replacing latches with suspending versions --- .../sdk/internal/crypto/E2eeSanityTests.kt | 74 ++++++++----------- 1 file changed, 30 insertions(+), 44 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index 6ffc8cc9af9..e4e109ec438 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -426,13 +426,11 @@ class E2eeSanityTests : InstrumentedTest { firstMessage.let { text -> firstEventId = sendMessageInRoom(testHelper, aliceRoomPOV, text)!! - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = bobSessionWithBetterKey.getRoom(e2eRoomID)?.getTimelineEvent(firstEventId) - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + val timeLineEvent = bobSessionWithBetterKey.getRoom(e2eRoomID)?.getTimelineEvent(firstEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } @@ -440,7 +438,7 @@ class E2eeSanityTests : InstrumentedTest { ensureIsDecrypted(testHelper, listOf(firstEventId), bobSessionWithBetterKey, e2eRoomID) // Let's add a new unverified session from bob - val newBobSession = testHelper.logIntoAccount(bobSessionWithBetterKey.myUserId, SessionTestParams(true)) + val newBobSession = testHelper.logIntoAccountSuspending(bobSessionWithBetterKey.myUserId, SessionTestParams(true)) // check that new bob can't currently decrypt Log.v("#E2E TEST", "check that new bob can't currently decrypt") @@ -454,13 +452,11 @@ class E2eeSanityTests : InstrumentedTest { secondMessage.let { text -> secondEventId = sendMessageInRoom(testHelper, aliceRoomPOV, text)!! - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = newBobSession.getRoom(e2eRoomID)?.getTimelineEvent(secondEventId) - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + val timeLineEvent = newBobSession.getRoom(e2eRoomID)?.getTimelineEvent(secondEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } @@ -474,18 +470,14 @@ class E2eeSanityTests : InstrumentedTest { Assert.assertTrue("Should be the same session id", firstSessionId == secondSessionId) // Confirm we can decrypt one but not the other - testHelper.runBlockingTest { - mustFail(message = "Should not be able to decrypt event") { - newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") - } + mustFail(message = "Should not be able to decrypt event") { + newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") } - testHelper.runBlockingTest { - try { - newBobSession.cryptoService().decryptEvent(secondEventNewBobPov.root, "") - } catch (error: MXCryptoError) { - fail("Should be able to decrypt event") - } + try { + newBobSession.cryptoService().decryptEvent(secondEventNewBobPov.root, "") + } catch (error: MXCryptoError) { + fail("Should be able to decrypt event") } // Now let's verify bobs session, and re-request keys @@ -504,26 +496,20 @@ class E2eeSanityTests : InstrumentedTest { // old session should have shared the key at earliest known index now // we should be able to decrypt both - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - val canDecryptFirst = try { - testHelper.runBlockingTest { - newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") - } - true - } catch (error: MXCryptoError) { - false - } - val canDecryptSecond = try { - testHelper.runBlockingTest { - newBobSession.cryptoService().decryptEvent(secondEventNewBobPov.root, "") - } - true - } catch (error: MXCryptoError) { - false - } - canDecryptFirst && canDecryptSecond + testHelper.retryPeriodically { + val canDecryptFirst = try { + newBobSession.cryptoService().decryptEvent(firstEventNewBobPov.root, "") + true + } catch (error: MXCryptoError) { + false + } + val canDecryptSecond = try { + newBobSession.cryptoService().decryptEvent(secondEventNewBobPov.root, "") + true + } catch (error: MXCryptoError) { + false } + canDecryptFirst && canDecryptSecond } } From 26db94dd0a6d24948bba63342e90dec7e16bf1ef Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 09:01:41 +0100 Subject: [PATCH 22/56] updating encryption test to use suspending functions --- .../crypto/encryption/EncryptionTest.kt | 77 +++++++++---------- 1 file changed, 37 insertions(+), 40 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt index 5f26fda9461..091f6a37e84 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.crypto.encryption import androidx.test.ext.junit.runners.AndroidJUnit4 -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.suspendCancellableCoroutine import org.amshove.kluent.shouldBe import org.junit.FixMethodOrder import org.junit.Test @@ -34,54 +34,59 @@ import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.CryptoTestHelper -import java.util.concurrent.CountDownLatch +import org.matrix.android.sdk.common.waitFor +import kotlin.coroutines.resume @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) class EncryptionTest : InstrumentedTest { @Test - fun test_EncryptionEvent() { - runCryptoTest(context()) { cryptoTestHelper, testHelper -> - performTest(cryptoTestHelper, testHelper, roomShouldBeEncrypted = false) { room -> - // Send an encryption Event as an Event (and not as a state event) - room.sendService().sendEvent( - eventType = EventType.STATE_ROOM_ENCRYPTION, - content = EncryptionEventContent(algorithm = MXCRYPTO_ALGORITHM_MEGOLM).toContent() - ) - } + fun test_EncryptionEvent() = runSuspendingCryptoTest(context()) { cryptoTestHelper, _ -> + performTest(cryptoTestHelper, roomShouldBeEncrypted = false) { room -> + // Send an encryption Event as an Event (and not as a state event) + room.sendService().sendEvent( + eventType = EventType.STATE_ROOM_ENCRYPTION, + content = EncryptionEventContent(algorithm = MXCRYPTO_ALGORITHM_MEGOLM).toContent() + ) } } @Test - fun test_EncryptionStateEvent() { - runCryptoTest(context()) { cryptoTestHelper, testHelper -> - performTest(cryptoTestHelper, testHelper, roomShouldBeEncrypted = true) { room -> - runBlocking { - // Send an encryption Event as a State Event - room.stateService().sendStateEvent( - eventType = EventType.STATE_ROOM_ENCRYPTION, - stateKey = "", - body = EncryptionEventContent(algorithm = MXCRYPTO_ALGORITHM_MEGOLM).toContent() - ) - } - } + fun test_EncryptionStateEvent() = runSuspendingCryptoTest(context()) { cryptoTestHelper, _ -> + performTest(cryptoTestHelper, roomShouldBeEncrypted = true) { room -> + // Send an encryption Event as a State Event + room.stateService().sendStateEvent( + eventType = EventType.STATE_ROOM_ENCRYPTION, + stateKey = "", + body = EncryptionEventContent(algorithm = MXCRYPTO_ALGORITHM_MEGOLM).toContent() + ) } } - private fun performTest(cryptoTestHelper: CryptoTestHelper, testHelper: CommonTestHelper, roomShouldBeEncrypted: Boolean, action: (Room) -> Unit) { + private suspend fun performTest(cryptoTestHelper: CryptoTestHelper, roomShouldBeEncrypted: Boolean, action: suspend (Room) -> Unit) { val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(encryptedRoom = false) - val aliceSession = cryptoTestData.firstSession val room = aliceSession.getRoom(cryptoTestData.roomId)!! room.roomCryptoService().isEncrypted() shouldBe false val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) - val latch = CountDownLatch(1) + timeline.start() + waitFor( + continueWhen = { timeline.waitForEncryptedMessages() }, + action = { action.invoke(room) } + ) + timeline.dispose() + + room.roomCryptoService().isEncrypted() shouldBe roomShouldBeEncrypted + } +} + +private suspend fun Timeline.waitForEncryptedMessages() { + suspendCancellableCoroutine { continuation -> val timelineListener = object : Timeline.Listener { override fun onTimelineFailure(throwable: Throwable) { } @@ -96,20 +101,12 @@ class EncryptionTest : InstrumentedTest { .filter { it.root.getClearType() == EventType.STATE_ROOM_ENCRYPTION } if (newMessages.isNotEmpty()) { - timeline.removeListener(this) - latch.countDown() + removeListener(this) + continuation.resume(Unit) } } } - timeline.start() - timeline.addListener(timelineListener) - - action.invoke(room) - testHelper.await(latch) - timeline.dispose() - testHelper.waitWithLatch { - room.roomCryptoService().isEncrypted() shouldBe roomShouldBeEncrypted - it.countDown() - } + addListener(timelineListener) + continuation.invokeOnCancellation { removeListener(timelineListener) } } } From 1f6dbbda0a2b714e07b997fa0d973afe63c2f0a8 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 09:10:19 +0100 Subject: [PATCH 23/56] using suspending versions of doSync --- .../android/sdk/common/CryptoTestHelper.kt | 4 ++-- .../internal/crypto/gossiping/WithHeldTests.kt | 5 +++-- .../internal/crypto/keysbackup/KeysBackupTest.kt | 16 ++++++++-------- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 00e1fdb0a6f..3afac327a6e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -238,8 +238,8 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { return roomId } - fun initializeCrossSigning(session: Session) { - testHelper.doSync { + suspend fun initializeCrossSigning(session: Session) { + testHelper.doSyncSuspending { session.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index 0aac4297e42..abd0ed59700 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -37,6 +37,7 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.MockOkHttpInterceptor import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams @@ -51,7 +52,7 @@ class WithHeldTests : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) @Test - fun test_WithHeldUnverifiedReason() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_WithHeldUnverifiedReason() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> // ============================= // ARRANGE @@ -233,7 +234,7 @@ class WithHeldTests : InstrumentedTest { } @Test - fun test_WithHeldKeyRequest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_WithHeldKeyRequest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = testData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index cd6e4738961..cbc6c59b1d3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -46,6 +46,7 @@ import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.common.TestMatrixCallback @@ -65,7 +66,7 @@ class KeysBackupTest : InstrumentedTest { * - Reset keys backup markers */ @Test - fun roomKeysTest_testBackupStore_ok() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun roomKeysTest_testBackupStore_ok() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -132,9 +133,8 @@ class KeysBackupTest : InstrumentedTest { * Test creating a keys backup version and check that createKeysBackupVersion() returns valid data */ @Test - fun createKeysBackupVersionTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - - val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) + fun createKeysBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) cryptoTestHelper.initializeCrossSigning(bobSession) val keysBackup = bobSession.cryptoService().keysBackupService() @@ -143,14 +143,14 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled()) - val megolmBackupCreationInfo = testHelper.doSync { + val megolmBackupCreationInfo = testHelper.doSyncSuspending { keysBackup.prepareKeysBackupVersion(null, null, it) } assertFalse(keysBackup.isEnabled()) // Create the version - val version = testHelper.doSync { + val version = testHelper.doSyncSuspending { keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) } @@ -158,10 +158,10 @@ class KeysBackupTest : InstrumentedTest { assertTrue(keysBackup.isEnabled()) // Check that it's signed with MSK - val versionResult = testHelper.doSync { + val versionResult = testHelper.doSyncSuspending { keysBackup.getVersion(version.version, it) } - val trust = testHelper.doSync { + val trust = testHelper.doSyncSuspending { keysBackup.getKeysBackupTrust(versionResult!!, it) } From 8e226bc14d651fbdc14fb0189594a978d75ec193 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 09:19:40 +0100 Subject: [PATCH 24/56] updating preshare tests to use suspending methods --- .../sdk/internal/crypto/PreShareKeysTest.kt | 22 +++++------- .../crypto/keysbackup/KeysBackupTest.kt | 36 +++++++++---------- 2 files changed, 27 insertions(+), 31 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt index e8e7b1d7084..c6e0c7b986b 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt @@ -30,14 +30,14 @@ import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventCon import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) class PreShareKeysTest : InstrumentedTest { @Test - fun ensure_outbound_session_happy_path() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun ensure_outbound_session_happy_path() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = testData.roomId val aliceSession = testData.firstSession @@ -52,15 +52,13 @@ class PreShareKeysTest : InstrumentedTest { Log.d("#Test", "Room Key Received from alice $preShareCount") // Force presharing of new outbound key - testHelper.doSync { + testHelper.doSyncSuspending { aliceSession.cryptoService().prepareToEncrypt(e2eRoomID, it) } - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val newKeysCount = bobSession.cryptoService().keysBackupService().getTotalNumbersOfKeys() - newKeysCount > preShareCount - } + testHelper.retryPeriodically { + val newKeysCount = bobSession.cryptoService().keysBackupService().getTotalNumbersOfKeys() + newKeysCount > preShareCount } val aliceCryptoStore = (aliceSession.cryptoService() as DefaultCryptoService).cryptoStoreForTesting @@ -82,13 +80,11 @@ class PreShareKeysTest : InstrumentedTest { assertEquals("The session received by bob should match what alice sent", 0, sharedIndex) // Just send a real message as test - val sentEvent = testHelper.sendTextMessage(aliceSession.getRoom(e2eRoomID)!!, "Allo", 1).first() + val sentEvent = testHelper.sendTextMessageSuspending(aliceSession.getRoom(e2eRoomID)!!, "Allo", 1).first() assertEquals("Unexpected megolm session", megolmSessionId, sentEvent.root.content.toModel()?.sessionId) - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEvent.eventId)?.root?.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEvent.eventId)?.root?.getClearType() == EventType.MESSAGE } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index cbc6c59b1d3..758b65d5e0e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -198,7 +198,7 @@ class KeysBackupTest : InstrumentedTest { * - Check the backup completes */ @Test - fun backupAfterCreateKeysBackupVersionTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun backupAfterCreateKeysBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -239,7 +239,7 @@ class KeysBackupTest : InstrumentedTest { * Check that backupAllGroupSessions() returns valid data */ @Test - fun backupAllGroupSessionsTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun backupAllGroupSessionsTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -284,7 +284,7 @@ class KeysBackupTest : InstrumentedTest { * - Compare the decrypted megolm key with the original one */ @Test - fun testEncryptAndDecryptKeysBackupData() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testEncryptAndDecryptKeysBackupData() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -328,7 +328,7 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - fun restoreKeysBackupTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun restoreKeysBackupTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -414,7 +414,7 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - fun trustKeyBackupVersionTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Do an e2e backup to the homeserver with a recovery key @@ -474,7 +474,7 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - fun trustKeyBackupVersionWithRecoveryKeyTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithRecoveryKeyTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Do an e2e backup to the homeserver with a recovery key @@ -532,7 +532,7 @@ class KeysBackupTest : InstrumentedTest { * - The backup must still be untrusted and disabled */ @Test - fun trustKeyBackupVersionWithWrongRecoveryKeyTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithWrongRecoveryKeyTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Do an e2e backup to the homeserver with a recovery key @@ -574,7 +574,7 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - fun trustKeyBackupVersionWithPasswordTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithPasswordTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "Password" @@ -634,7 +634,7 @@ class KeysBackupTest : InstrumentedTest { * - The backup must still be untrusted and disabled */ @Test - fun trustKeyBackupVersionWithWrongPasswordTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithWrongPasswordTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "Password" @@ -675,7 +675,7 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - fun restoreKeysBackupWithAWrongRecoveryKeyTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun restoreKeysBackupWithAWrongRecoveryKeyTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -708,7 +708,7 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - fun testBackupWithPassword() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBackupWithPassword() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "password" @@ -764,7 +764,7 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - fun restoreKeysBackupWithAWrongPasswordTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun restoreKeysBackupWithAWrongPasswordTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "password" @@ -800,7 +800,7 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "password" @@ -829,7 +829,7 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -860,7 +860,7 @@ class KeysBackupTest : InstrumentedTest { * - Check the returned KeysVersionResult is trusted */ @Test - fun testIsKeysBackupTrusted() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testIsKeysBackupTrusted() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version @@ -905,7 +905,7 @@ class KeysBackupTest : InstrumentedTest { * -> That must fail and her backup state must be WrongBackUpVersion */ @Test - fun testBackupWhenAnotherBackupWasCreated() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBackupWhenAnotherBackupWasCreated() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version @@ -977,7 +977,7 @@ class KeysBackupTest : InstrumentedTest { * -> It must success */ @Test - fun testBackupAfterVerifyingADevice() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBackupAfterVerifyingADevice() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version @@ -1075,7 +1075,7 @@ class KeysBackupTest : InstrumentedTest { * - Delete the backup */ @Test - fun deleteKeysBackupTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun deleteKeysBackupTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version From 1006e9e1e590b461a19ea57aa7943230896864a8 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 09:21:52 +0100 Subject: [PATCH 25/56] updating search message tests to use suspending functions --- .../android/sdk/session/search/SearchMessagesTest.kt | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt index 7c97426c391..b0ecb5f7726 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.search.SearchResult -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.CryptoTestData @RunWith(JUnit4::class) @@ -73,21 +73,19 @@ class SearchMessagesTest : InstrumentedTest { } } - private fun doTest(block: suspend (CryptoTestData) -> SearchResult) = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + private fun doTest(block: suspend (CryptoTestData) -> SearchResult) = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! - commonTestHelper.sendTextMessage( + commonTestHelper.sendTextMessageSuspending( roomFromAlicePOV, MESSAGE, 2 ) - val data = commonTestHelper.runBlockingTest { - block.invoke(cryptoTestData) - } + val data = block.invoke(cryptoTestData) assertTrue(data.results?.size == 2) assertTrue( From 969e98dfc182599a566a34c44349382c3bc5c600 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 16:42:57 +0100 Subject: [PATCH 26/56] marking doE2ETestWithAliceInARoom as suspending --- .../sdk/account/AccountCreationTest.kt | 4 +- .../android/sdk/common/CryptoTestHelper.kt | 38 +++++++++---------- .../crypto/gossiping/KeyShareTests.kt | 2 +- .../room/threads/ThreadMessagingTest.kt | 4 +- .../timeline/TimelineForwardPaginationTest.kt | 2 +- 5 files changed, 24 insertions(+), 26 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt index 7e4fc4768fb..d24a2a50ef3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt @@ -24,8 +24,8 @@ import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -49,7 +49,7 @@ class AccountCreationTest : InstrumentedTest { } @Test - fun simpleE2eTest() = runCryptoTest(context()) { cryptoTestHelper, _ -> + fun simpleE2eTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, _ -> cryptoTestHelper.doE2ETestWithAliceInARoom() } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 3afac327a6e..240ebec6b2c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -70,34 +70,32 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { /** * @return alice session */ - fun doE2ETestWithAliceInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { - return testHelper.launch { - val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, defaultSessionParams) - - val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { - historyVisibility = roomHistoryVisibility - name = "MyRoom" - }) - if (encryptedRoom) { - val room = aliceSession.getRoom(roomId)!! - waitFor( - continueWhen = { room.onMain { getRoomSummaryLive() }.first { it.getOrNull()?.isEncrypted.orFalse() } }, - action = { room.roomCryptoService().enableEncryption() } - ) - } - CryptoTestData(roomId, listOf(aliceSession)) + suspend fun doE2ETestWithAliceInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { + val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, defaultSessionParams) + + val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { + historyVisibility = roomHistoryVisibility + name = "MyRoom" + }) + if (encryptedRoom) { + val room = aliceSession.getRoom(roomId)!! + waitFor( + continueWhen = { room.onMain { getRoomSummaryLive() }.first { it.getOrNull()?.isEncrypted.orFalse() } }, + action = { room.roomCryptoService().enableEncryption() } + ) } + return CryptoTestData(roomId, listOf(aliceSession)) } /** * @return alice and bob sessions */ fun doE2ETestWithAliceAndBobInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { - val cryptoTestData = doE2ETestWithAliceInARoom(encryptedRoom, roomHistoryVisibility) - val aliceSession = cryptoTestData.firstSession - val aliceRoomId = cryptoTestData.roomId - return testHelper.launch { + val cryptoTestData = doE2ETestWithAliceInARoom(encryptedRoom, roomHistoryVisibility) + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId + val aliceRoom = aliceSession.getRoom(aliceRoomId)!! val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, defaultSessionParams) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index 7bb53e139c3..f2fdb76dd47 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -226,7 +226,7 @@ class KeyShareTests : InstrumentedTest { @Test fun test_reShareToUnverifiedIfWasIntendedToBeShared() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val testData = cryptoTestHelper.doE2ETestWithAliceInARoom(true) + val testData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(true) } val aliceSession = testData.firstSession val roomFromAlice = aliceSession.getRoom(testData.roomId)!! diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt index 45bd38870d3..8ece6d10c59 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt @@ -44,7 +44,7 @@ class ThreadMessagingTest : InstrumentedTest { @Test fun reply_in_thread_should_create_a_thread() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) + val cryptoTestData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(false) } val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId @@ -175,7 +175,7 @@ class ThreadMessagingTest : InstrumentedTest { @Test fun reply_in_thread_to_timeline_message_multiple_times() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) + val cryptoTestData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(false) } val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt index 2e5c69b0487..fac519ce2d1 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt @@ -56,7 +56,7 @@ class TimelineForwardPaginationTest : InstrumentedTest { @Ignore("Ignoring this test until it's fixed since it blocks the CI.") fun forwardPaginationTest() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val numberOfMessagesToSend = 90 - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) + val cryptoTestData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(false) } val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId From 800746b58ff78a90811685cda6c40608c4a2ae75 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 16:54:13 +0100 Subject: [PATCH 27/56] replacing some keysbackup latch usages --- .../android/sdk/common/CryptoTestHelper.kt | 59 +++++++++---------- .../crypto/keysbackup/KeysBackupTest.kt | 21 ++++--- .../crypto/keysbackup/KeysBackupTestHelper.kt | 34 ++++++----- 3 files changed, 56 insertions(+), 58 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 240ebec6b2c..803a06a3169 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -54,7 +54,6 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import org.matrix.android.sdk.api.session.securestorage.EmptyKeySigner import org.matrix.android.sdk.api.session.securestorage.KeyRef -import org.matrix.android.sdk.api.util.awaitCallback import org.matrix.android.sdk.api.util.toBase64NoPadding import java.util.UUID import kotlin.coroutines.Continuation @@ -129,47 +128,45 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { /** * @return Alice and Bob sessions */ - fun doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(): CryptoTestData { + suspend fun doE2ETestWithAliceAndBobInARoomWithEncryptedMessages(): CryptoTestData { val cryptoTestData = doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId val bobSession = cryptoTestData.secondSession!! - return testHelper.launch { - bobSession.cryptoService().setWarnOnUnknownDevices(false) - aliceSession.cryptoService().setWarnOnUnknownDevices(false) + bobSession.cryptoService().setWarnOnUnknownDevices(false) + aliceSession.cryptoService().setWarnOnUnknownDevices(false) - val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! - val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! + val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! + val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! - // Alice sends a message - testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId -> - // ensure bob got it - ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) - } + // Alice sends a message + testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId -> + // ensure bob got it + ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) + } - // Bob send 3 messages - testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> - // ensure alice got it - ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) - } + // Bob send 3 messages + testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> + // ensure alice got it + ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) + } - testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId -> - // ensure alice got it - ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) - } - testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId -> - // ensure alice got it - ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) - } + testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId -> + // ensure alice got it + ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) + } + testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId -> + // ensure alice got it + ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) + } - // Alice sends a message - testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId -> - // ensure bob got it - ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) - } - cryptoTestData + // Alice sends a message + testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId -> + // ensure bob got it + ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) } + return cryptoTestData } private suspend fun ensureEventReceived(roomId: String, eventId: String, session: Session, andCanDecrypt: Boolean) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index 758b65d5e0e..44a50934090 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -44,7 +44,6 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreation import org.matrix.android.sdk.api.session.crypto.keysbackup.toKeysVersionResult import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult import org.matrix.android.sdk.api.session.getRoom -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.RetryTestRule @@ -429,7 +428,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device - testHelper.doSync { + testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersion( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, true, @@ -445,14 +444,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -489,7 +488,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device with the recovery key - testHelper.doSync { + testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithRecoveryKey( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, testData.prepareKeysBackupDataResult.megolmBackupCreationInfo.recoveryKey, @@ -505,14 +504,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -591,7 +590,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device with the password - testHelper.doSync { + testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithPassphrase( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, password, @@ -607,14 +606,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -718,7 +717,7 @@ class KeysBackupTest : InstrumentedTest { // - Restore the e2e backup with the password val steps = ArrayList() - val importRoomKeysResult = testHelper.doSync { + val importRoomKeysResult = testHelper.doSyncSuspending { testData.aliceSession2.cryptoService().keysBackupService().restoreKeyBackupWithPassword( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, password, diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt index 2cc2b506b92..c4dabbf6f8f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -16,6 +16,7 @@ package org.matrix.android.sdk.internal.crypto.keysbackup +import kotlinx.coroutines.suspendCancellableCoroutine import org.junit.Assert import org.matrix.android.sdk.api.listeners.ProgressListener import org.matrix.android.sdk.api.session.Session @@ -29,7 +30,7 @@ import org.matrix.android.sdk.common.CryptoTestHelper import org.matrix.android.sdk.common.assertDictEquals import org.matrix.android.sdk.common.assertListEquals import org.matrix.android.sdk.internal.crypto.MegolmSessionData -import java.util.concurrent.CountDownLatch +import kotlin.coroutines.resume internal class KeysBackupTestHelper( private val testHelper: CommonTestHelper, @@ -47,7 +48,7 @@ internal class KeysBackupTestHelper( * * @param password optional password */ - fun createKeysBackupScenarioWithPassword(password: String?): KeysBackupScenarioData { + suspend fun createKeysBackupScenarioWithPassword(password: String?): KeysBackupScenarioData { val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() waitForKeybackUpBatching() @@ -64,7 +65,7 @@ internal class KeysBackupTestHelper( var lastProgress = 0 var lastTotal = 0 - testHelper.doSync { + testHelper.doSyncSuspending { keysBackup.backupAllGroupSessions(object : ProgressListener { override fun onProgress(progress: Int, total: Int) { lastProgress = progress @@ -79,7 +80,7 @@ internal class KeysBackupTestHelper( val aliceUserId = cryptoTestData.firstSession.myUserId // - Log Alice on a new device - val aliceSession2 = testHelper.logIntoAccount(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) + val aliceSession2 = testHelper.logIntoAccountSuspending(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) // Test check: aliceSession2 has no keys at login Assert.assertEquals(0, aliceSession2.cryptoService().inboundGroupSessionsCount(false)) @@ -129,25 +130,26 @@ internal class KeysBackupTestHelper( * As KeysBackup is doing asynchronous call to update its internal state, this method help to wait for the * KeysBackup object to be in the specified state */ - fun waitForKeysBackupToBeInState(session: Session, state: KeysBackupState) { + suspend fun waitForKeysBackupToBeInState(session: Session, state: KeysBackupState) { // If already in the wanted state, return - if (session.cryptoService().keysBackupService().getState() == state) { + val keysBackupService = session.cryptoService().keysBackupService() + if (keysBackupService.getState() == state) { return } // Else observe state changes - val latch = CountDownLatch(1) - - session.cryptoService().keysBackupService().addListener(object : KeysBackupStateListener { - override fun onStateChange(newState: KeysBackupState) { - if (newState == state) { - session.cryptoService().keysBackupService().removeListener(this) - latch.countDown() + suspendCancellableCoroutine { continuation -> + val listener = object : KeysBackupStateListener { + override fun onStateChange(newState: KeysBackupState) { + if (newState == state) { + keysBackupService.removeListener(this) + continuation.resume(Unit) + } } } - }) - - testHelper.await(latch) + keysBackupService.addListener(listener) + continuation.invokeOnCancellation { keysBackupService.removeListener(listener) } + } } fun assertKeysEquals(keys1: MegolmSessionData?, keys2: MegolmSessionData?) { From fff364f75ebd1adf66361c1e069146cb887c4850 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 16:59:12 +0100 Subject: [PATCH 28/56] replacing withheld test latch usages with suspends --- .../android/sdk/common/CryptoTestHelper.kt | 66 +++---- .../crypto/gossiping/WithHeldTests.kt | 161 ++++++++---------- 2 files changed, 97 insertions(+), 130 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 803a06a3169..9350ae2b867 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -303,7 +303,7 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } } - fun verifySASCrossSign(alice: Session, bob: Session, roomId: String) { + suspend fun verifySASCrossSign(alice: Session, bob: Session, roomId: String) { assertTrue(alice.cryptoService().crossSigningService().canCrossSign()) assertTrue(bob.cryptoService().crossSigningService().canCrossSign()) @@ -318,12 +318,10 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { roomId = roomId ).transactionId - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - bobVerificationService.getExistingVerificationRequests(alice.myUserId).firstOrNull { - it.requestInfo?.fromDevice == alice.sessionParams.deviceId - } != null - } + testHelper.retryPeriodically { + bobVerificationService.getExistingVerificationRequests(alice.myUserId).firstOrNull { + it.requestInfo?.fromDevice == alice.sessionParams.deviceId + } != null } val incomingRequest = bobVerificationService.getExistingVerificationRequests(alice.myUserId).first { it.requestInfo?.fromDevice == alice.sessionParams.deviceId @@ -332,16 +330,14 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { var requestID: String? = null // wait for it to be readied - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - val outgoingRequest = aliceVerificationService.getExistingVerificationRequests(bob.myUserId) - .firstOrNull { it.localId == localId } - if (outgoingRequest?.isReady == true) { - requestID = outgoingRequest.transactionId!! - true - } else { - false - } + testHelper.retryPeriodically { + val outgoingRequest = aliceVerificationService.getExistingVerificationRequests(bob.myUserId) + .firstOrNull { it.localId == localId } + if (outgoingRequest?.isReady == true) { + requestID = outgoingRequest.transactionId!! + true + } else { + false } } @@ -357,23 +353,19 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { var alicePovTx: OutgoingSasVerificationTransaction? = null var bobPovTx: IncomingSasVerificationTransaction? = null - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - alicePovTx = aliceVerificationService.getExistingTransaction(bob.myUserId, requestID!!) as? OutgoingSasVerificationTransaction - Log.v("TEST", "== alicePovTx is ${alicePovTx?.uxState}") - alicePovTx?.state == VerificationTxState.ShortCodeReady - } + testHelper.retryPeriodically { + alicePovTx = aliceVerificationService.getExistingTransaction(bob.myUserId, requestID!!) as? OutgoingSasVerificationTransaction + Log.v("TEST", "== alicePovTx is ${alicePovTx?.uxState}") + alicePovTx?.state == VerificationTxState.ShortCodeReady } // wait for alice to get the ready - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - bobPovTx = bobVerificationService.getExistingTransaction(alice.myUserId, requestID!!) as? IncomingSasVerificationTransaction - Log.v("TEST", "== bobPovTx is ${alicePovTx?.uxState}") - if (bobPovTx?.state == VerificationTxState.OnStarted) { - bobPovTx?.performAccept() - } - bobPovTx?.state == VerificationTxState.ShortCodeReady + testHelper.retryPeriodically { + bobPovTx = bobVerificationService.getExistingTransaction(alice.myUserId, requestID!!) as? IncomingSasVerificationTransaction + Log.v("TEST", "== bobPovTx is ${alicePovTx?.uxState}") + if (bobPovTx?.state == VerificationTxState.OnStarted) { + bobPovTx?.performAccept() } + bobPovTx?.state == VerificationTxState.ShortCodeReady } assertEquals("SAS code do not match", alicePovTx!!.getDecimalCodeRepresentation(), bobPovTx!!.getDecimalCodeRepresentation()) @@ -381,16 +373,12 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { bobPovTx!!.userHasVerifiedShortCode() alicePovTx!!.userHasVerifiedShortCode() - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - alice.cryptoService().crossSigningService().isUserTrusted(bob.myUserId) - } + testHelper.retryPeriodically { + alice.cryptoService().crossSigningService().isUserTrusted(bob.myUserId) } - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - alice.cryptoService().crossSigningService().isUserTrusted(bob.myUserId) - } + testHelper.retryPeriodically { + alice.cryptoService().crossSigningService().isUserTrusted(bob.myUserId) } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index abd0ed59700..48c9d5b3aa8 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -36,7 +36,6 @@ import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.MockOkHttpInterceptor import org.matrix.android.sdk.common.RetryTestRule @@ -58,8 +57,8 @@ class WithHeldTests : InstrumentedTest { // ARRANGE // ============================= - val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) - val bobSession = testHelper.createAccount(TestConstants.USER_BOB, SessionTestParams(true)) + val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(true)) + val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, SessionTestParams(true)) // Initialize cross signing on both cryptoTestHelper.initializeCrossSigning(aliceSession) @@ -70,7 +69,7 @@ class WithHeldTests : InstrumentedTest { val roomAlicePOV = aliceSession.getRoom(roomId)!! - val bobUnverifiedSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(true)) + val bobUnverifiedSession = testHelper.logIntoAccountSuspending(bobSession.myUserId, SessionTestParams(true)) // ============================= // ACT // ============================= @@ -78,13 +77,11 @@ class WithHeldTests : InstrumentedTest { // Alice decide to not send to unverified sessions aliceSession.cryptoService().setGlobalBlacklistUnverifiedDevices(true) - val timelineEvent = testHelper.sendTextMessage(roomAlicePOV, "Hello Bob", 1).first() + val timelineEvent = testHelper.sendTextMessageSuspending(roomAlicePOV, "Hello Bob", 1).first() // await for bob unverified session to get the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(timelineEvent.eventId) != null - } + testHelper.retryPeriodically { + bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(timelineEvent.eventId) != null } val eventBobPOV = bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(timelineEvent.eventId)!! @@ -96,65 +93,57 @@ class WithHeldTests : InstrumentedTest { // Bob should not be able to decrypt because the keys is withheld // .. might need to wait a bit for stability? - testHelper.runBlockingTest { - mustFail( - message = "This session should not be able to decrypt", - failureBlock = { failure -> - val type = (failure as MXCryptoError.Base).errorType - val technicalMessage = failure.technicalMessage - Assert.assertEquals("Error should be withheld", MXCryptoError.ErrorType.KEYS_WITHHELD, type) - Assert.assertEquals("Cause should be unverified", WithHeldCode.UNVERIFIED.value, technicalMessage) - } - ) { - bobUnverifiedSession.cryptoService().decryptEvent(eventBobPOV.root, "") - } + mustFail( + message = "This session should not be able to decrypt", + failureBlock = { failure -> + val type = (failure as MXCryptoError.Base).errorType + val technicalMessage = failure.technicalMessage + Assert.assertEquals("Error should be withheld", MXCryptoError.ErrorType.KEYS_WITHHELD, type) + Assert.assertEquals("Cause should be unverified", WithHeldCode.UNVERIFIED.value, technicalMessage) + } + ) { + bobUnverifiedSession.cryptoService().decryptEvent(eventBobPOV.root, "") } // Let's see if the reply we got from bob first session is unverified - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - bobUnverifiedSession.cryptoService().getOutgoingRoomKeyRequests() - .firstOrNull { it.sessionId == megolmSessionId } - ?.results - ?.firstOrNull { it.fromDevice == bobSession.sessionParams.deviceId } - ?.result - ?.let { - it as? RequestResult.Failure - } - ?.code == WithHeldCode.UNVERIFIED - } + testHelper.retryPeriodically { + bobUnverifiedSession.cryptoService().getOutgoingRoomKeyRequests() + .firstOrNull { it.sessionId == megolmSessionId } + ?.results + ?.firstOrNull { it.fromDevice == bobSession.sessionParams.deviceId } + ?.result + ?.let { + it as? RequestResult.Failure + } + ?.code == WithHeldCode.UNVERIFIED } // enable back sending to unverified aliceSession.cryptoService().setGlobalBlacklistUnverifiedDevices(false) - val secondEvent = testHelper.sendTextMessage(roomAlicePOV, "Verify your device!!", 1).first() + val secondEvent = testHelper.sendTextMessageSuspending(roomAlicePOV, "Verify your device!!", 1).first() - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val ev = bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(secondEvent.eventId) - // wait until it's decrypted - ev?.root?.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + val ev = bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(secondEvent.eventId) + // wait until it's decrypted + ev?.root?.getClearType() == EventType.MESSAGE } // Previous message should still be undecryptable (partially withheld session) // .. might need to wait a bit for stability? - testHelper.runBlockingTest { - mustFail( - message = "This session should not be able to decrypt", - failureBlock = { failure -> - val type = (failure as MXCryptoError.Base).errorType - val technicalMessage = failure.technicalMessage - Assert.assertEquals("Error should be withheld", MXCryptoError.ErrorType.KEYS_WITHHELD, type) - Assert.assertEquals("Cause should be unverified", WithHeldCode.UNVERIFIED.value, technicalMessage) - }) { - bobUnverifiedSession.cryptoService().decryptEvent(eventBobPOV.root, "") - } + mustFail( + message = "This session should not be able to decrypt", + failureBlock = { failure -> + val type = (failure as MXCryptoError.Base).errorType + val technicalMessage = failure.technicalMessage + Assert.assertEquals("Error should be withheld", MXCryptoError.ErrorType.KEYS_WITHHELD, type) + Assert.assertEquals("Cause should be unverified", WithHeldCode.UNVERIFIED.value, technicalMessage) + }) { + bobUnverifiedSession.cryptoService().decryptEvent(eventBobPOV.root, "") } } @Test - fun test_WithHeldNoOlm() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_WithHeldNoOlm() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = testData.firstSession @@ -175,29 +164,25 @@ class WithHeldTests : InstrumentedTest { val roomAlicePov = aliceSession.getRoom(testData.roomId)!! - val eventId = testHelper.sendTextMessage(roomAlicePov, "first message", 1).first().eventId + val eventId = testHelper.sendTextMessageSuspending(roomAlicePov, "first message", 1).first().eventId // await for bob session to get the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - bobSession.getRoom(testData.roomId)?.getTimelineEvent(eventId) != null - } + testHelper.retryPeriodically { + bobSession.getRoom(testData.roomId)?.getTimelineEvent(eventId) != null } // Previous message should still be undecryptable (partially withheld session) val eventBobPOV = bobSession.getRoom(testData.roomId)?.getTimelineEvent(eventId) // .. might need to wait a bit for stability? - testHelper.runBlockingTest { - mustFail( - message = "This session should not be able to decrypt", - failureBlock = { failure -> - val type = (failure as MXCryptoError.Base).errorType - val technicalMessage = failure.technicalMessage - Assert.assertEquals("Error should be withheld", MXCryptoError.ErrorType.KEYS_WITHHELD, type) - Assert.assertEquals("Cause should be unverified", WithHeldCode.NO_OLM.value, technicalMessage) - }) { - bobSession.cryptoService().decryptEvent(eventBobPOV!!.root, "") - } + mustFail( + message = "This session should not be able to decrypt", + failureBlock = { failure -> + val type = (failure as MXCryptoError.Base).errorType + val technicalMessage = failure.technicalMessage + Assert.assertEquals("Error should be withheld", MXCryptoError.ErrorType.KEYS_WITHHELD, type) + Assert.assertEquals("Cause should be unverified", WithHeldCode.NO_OLM.value, technicalMessage) + }) { + bobSession.cryptoService().decryptEvent(eventBobPOV!!.root, "") } // Ensure that alice has marked the session to be shared with bob @@ -211,16 +196,14 @@ class WithHeldTests : InstrumentedTest { // Add a new device for bob aliceInterceptor.clearRules() - val bobSecondSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(withInitialSync = true)) + val bobSecondSession = testHelper.logIntoAccountSuspending(bobSession.myUserId, SessionTestParams(withInitialSync = true)) // send a second message - val secondMessageId = testHelper.sendTextMessage(roomAlicePov, "second message", 1).first().eventId + val secondMessageId = testHelper.sendTextMessageSuspending(roomAlicePov, "second message", 1).first().eventId // Check that the // await for bob SecondSession session to get the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - bobSecondSession.getRoom(testData.roomId)?.getTimelineEvent(secondMessageId) != null - } + testHelper.retryPeriodically { + bobSecondSession.getRoom(testData.roomId)?.getTimelineEvent(secondMessageId) != null } val chainIndex2 = aliceSession.cryptoService().getSharedWithInfo(testData.roomId, sessionId).getObject( @@ -242,13 +225,13 @@ class WithHeldTests : InstrumentedTest { val roomAlicePov = aliceSession.getRoom(testData.roomId)!! - val eventId = testHelper.sendTextMessage(roomAlicePov, "first message", 1).first().eventId + val eventId = testHelper.sendTextMessageSuspending(roomAlicePov, "first message", 1).first().eventId testHelper.signOutAndClose(bobSession) // Create a new session for bob - val bobSecondSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(true)) + val bobSecondSession = testHelper.logIntoAccountSuspending(bobSession.myUserId, SessionTestParams(true)) // initialize to force request keys if missing cryptoTestHelper.initializeCrossSigning(bobSecondSession) @@ -259,27 +242,23 @@ class WithHeldTests : InstrumentedTest { var sessionId: String? = null // Check that the // await for bob SecondSession session to get the message - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = bobSecondSession.getRoom(testData.roomId)?.getTimelineEvent(eventId)?.also { - // try to decrypt and force key request - tryOrNull { - testHelper.runBlockingTest { - bobSecondSession.cryptoService().decryptEvent(it.root, "") - } + testHelper.retryPeriodically { + val timeLineEvent = bobSecondSession.getRoom(testData.roomId)?.getTimelineEvent(eventId)?.also { + // try to decrypt and force key request + tryOrNull { + testHelper.runBlockingTest { + bobSecondSession.cryptoService().decryptEvent(it.root, "") } } - sessionId = timeLineEvent?.root?.content?.toModel()?.sessionId - timeLineEvent != null } + sessionId = timeLineEvent?.root?.content?.toModel()?.sessionId + timeLineEvent != null } // Check that bob second session requested the key - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val wc = bobSecondSession.cryptoService().getWithHeldMegolmSession(roomAlicePov.roomId, sessionId!!) - wc?.code == WithHeldCode.UNAUTHORISED - } + testHelper.retryPeriodically { + val wc = bobSecondSession.cryptoService().getWithHeldMegolmSession(roomAlicePov.roomId, sessionId!!) + wc?.code == WithHeldCode.UNAUTHORISED } } } From 85eb46fe694b8385140012a08275b08e15358a10 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 17:02:51 +0100 Subject: [PATCH 29/56] replacing create dm latch with suspends --- .../android/sdk/common/CryptoTestHelper.kt | 57 ++++++++----------- 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 9350ae2b867..3307de30390 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -17,7 +17,6 @@ package org.matrix.android.sdk.common import android.util.Log -import androidx.lifecycle.Observer import org.amshove.kluent.fail import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -48,7 +47,6 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility -import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams @@ -197,39 +195,30 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { ) } - fun createDM(alice: Session, bob: Session): String { - var roomId: String = "" - testHelper.waitWithLatch { latch -> - roomId = alice.roomService().createDirectRoom(bob.myUserId) - val bobRoomSummariesLive = bob.roomService().getRoomSummariesLive(roomSummaryQueryParams { }) - val newRoomObserver = object : Observer> { - override fun onChanged(t: List?) { - if (t?.any { it.roomId == roomId }.orFalse()) { - bobRoomSummariesLive.removeObserver(this) - latch.countDown() - } - } - } - bobRoomSummariesLive.observeForever(newRoomObserver) - } - - testHelper.waitWithLatch { latch -> - val bobRoomSummariesLive = bob.roomService().getRoomSummariesLive(roomSummaryQueryParams { }) - val newRoomObserver = object : Observer> { - override fun onChanged(t: List?) { - if (bob.getRoom(roomId) - ?.membershipService() - ?.getRoomMember(bob.myUserId) - ?.membership == Membership.JOIN) { - bobRoomSummariesLive.removeObserver(this) - latch.countDown() - } - } - } - bobRoomSummariesLive.observeForever(newRoomObserver) - bob.roomService().joinRoom(roomId) - } + suspend fun createDM(alice: Session, bob: Session): String { + var roomId = "" + waitFor( + continueWhen = { + bob.roomService() + .onMain { getRoomSummariesLive(roomSummaryQueryParams { }) } + .first { it.any { it.roomId == roomId }.orFalse() } + }, + action = { roomId = alice.roomService().createDirectRoom(bob.myUserId) } + ) + waitFor( + continueWhen = { + bob.roomService() + .onMain { getRoomSummariesLive(roomSummaryQueryParams { }) } + .first { + bob.getRoom(roomId) + ?.membershipService() + ?.getRoomMember(bob.myUserId) + ?.membership == Membership.JOIN + } + }, + action = { bob.roomService().joinRoom(roomId) } + ) return roomId } From cff63e6ed94069bca2bc9c637629ee78aa9e96eb Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 17:07:03 +0100 Subject: [PATCH 30/56] making ensureCan/CannotDecrypt test functions suspending --- .../android/sdk/common/CryptoTestHelper.kt | 58 +++++++++---------- .../crypto/gossiping/KeyShareTests.kt | 11 ++-- 2 files changed, 32 insertions(+), 37 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 3307de30390..a007d06a53d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -397,47 +397,41 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { return CryptoTestData(roomId, sessions) } - fun ensureCanDecrypt(sentEventIds: List, session: Session, e2eRoomID: String, messagesText: List) { + suspend fun ensureCanDecrypt(sentEventIds: List, session: Session, e2eRoomID: String, messagesText: List) { sentEventIds.forEachIndexed { index, sentEventId -> - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val event = session.getRoom(e2eRoomID)!!.timelineService().getTimelineEvent(sentEventId)!!.root - testHelper.runBlockingTest { - try { - session.cryptoService().decryptEvent(event, "").let { result -> - event.mxDecryptionResult = OlmDecryptionResult( - payload = result.clearEvent, - senderKey = result.senderCurve25519Key, - keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) }, - forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain - ) - } - } catch (error: MXCryptoError) { - // nop - } + testHelper.retryPeriodically { + val event = session.getRoom(e2eRoomID)!!.timelineService().getTimelineEvent(sentEventId)!!.root + try { + session.cryptoService().decryptEvent(event, "").let { result -> + event.mxDecryptionResult = OlmDecryptionResult( + payload = result.clearEvent, + senderKey = result.senderCurve25519Key, + keysClaimed = result.claimedEd25519Key?.let { mapOf("ed25519" to it) }, + forwardingCurve25519KeyChain = result.forwardingCurve25519KeyChain + ) } - Log.v("TEST", "ensureCanDecrypt ${event.getClearType()} is ${event.getClearContent()}") - event.getClearType() == EventType.MESSAGE && - messagesText[index] == event.getClearContent()?.toModel()?.body + } catch (error: MXCryptoError) { + // nop } + Log.v("TEST", "ensureCanDecrypt ${event.getClearType()} is ${event.getClearContent()}") + event.getClearType() == EventType.MESSAGE && + messagesText[index] == event.getClearContent()?.toModel()?.body } } } - fun ensureCannotDecrypt(sentEventIds: List, session: Session, e2eRoomID: String, expectedError: MXCryptoError.ErrorType? = null) { + suspend fun ensureCannotDecrypt(sentEventIds: List, session: Session, e2eRoomID: String, expectedError: MXCryptoError.ErrorType? = null) { sentEventIds.forEach { sentEventId -> val event = session.getRoom(e2eRoomID)!!.timelineService().getTimelineEvent(sentEventId)!!.root - testHelper.runBlockingTest { - try { - session.cryptoService().decryptEvent(event, "") - fail("Should not be able to decrypt event") - } catch (error: MXCryptoError) { - val errorType = (error as? MXCryptoError.Base)?.errorType - if (expectedError == null) { - assertNotNull(errorType) - } else { - assertEquals("Unexpected reason", expectedError, errorType) - } + try { + session.cryptoService().decryptEvent(event, "") + fail("Should not be able to decrypt event") + } catch (error: MXCryptoError) { + val errorType = (error as? MXCryptoError.Base)?.errorType + if (expectedError == null) { + assertNotNull(errorType) + } else { + assertEquals("Unexpected reason", expectedError, errorType) } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index f2fdb76dd47..8cae668efb0 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -43,6 +43,7 @@ import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.timeline.getLastMessageContent import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -57,7 +58,7 @@ class KeyShareTests : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) @Test - fun test_DoNotSelfShareIfNotTrusted() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_DoNotSelfShareIfNotTrusted() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) Log.v("TEST", "=======> AliceSession 1 is ${aliceSession.sessionParams.deviceId}") @@ -193,7 +194,7 @@ class KeyShareTests : InstrumentedTest { * if the key was originally shared with him */ @Test - fun test_reShareIfWasIntendedToBeShared() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_reShareIfWasIntendedToBeShared() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = testData.firstSession @@ -224,7 +225,7 @@ class KeyShareTests : InstrumentedTest { * if the key was originally shared with him */ @Test - fun test_reShareToUnverifiedIfWasIntendedToBeShared() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_reShareToUnverifiedIfWasIntendedToBeShared() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(true) } val aliceSession = testData.firstSession @@ -261,7 +262,7 @@ class KeyShareTests : InstrumentedTest { * Tests that keys reshared with own verified session are done from the earliest known index */ @Test - fun test_reShareFromTheEarliestKnownIndexWithOwnVerifiedSession() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_reShareFromTheEarliestKnownIndexWithOwnVerifiedSession() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = testData.firstSession @@ -381,7 +382,7 @@ class KeyShareTests : InstrumentedTest { * Tests that we don't cancel a request to early on first forward if the index is not good enough */ @Test - fun test_dontCancelToEarly() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_dontCancelToEarly() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = testData.firstSession val bobSession = testData.secondSession!! From 080e5bbad8517b3f4ee6339920bf9af835a04a7c Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 17:10:14 +0100 Subject: [PATCH 31/56] replacing latches with suspending version --- .../sdk/internal/crypto/E2eeSanityTests.kt | 42 +++++++++---------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index e4e109ec438..7a8c1e8a03c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -328,13 +328,11 @@ class E2eeSanityTests : InstrumentedTest { sentEventIds.add(it) } - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val timeLineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) - timeLineEvent != null && - timeLineEvent.isEncrypted() && - timeLineEvent.root.getClearType() == EventType.MESSAGE - } + testHelper.retryPeriodically { + val timeLineEvent = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(sentEventId) + timeLineEvent != null && + timeLineEvent.isEncrypted() && + timeLineEvent.root.getClearType() == EventType.MESSAGE } } @@ -370,22 +368,20 @@ class E2eeSanityTests : InstrumentedTest { val megolmSessionId = newBobSession.getRoom(e2eRoomID)!! .getTimelineEvent(sentEventId)!! .root.content.toModel()!!.sessionId - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val aliceReply = newBobSession.cryptoService().getOutgoingRoomKeyRequests() - .first { - it.sessionId == megolmSessionId && - it.roomId == e2eRoomID - } - .results.also { - Log.w("##TEST", "result list is $it") - } - .firstOrNull { it.userId == aliceSession.myUserId } - ?.result - aliceReply != null && - aliceReply is RequestResult.Failure && - WithHeldCode.UNAUTHORISED == aliceReply.code - } + testHelper.retryPeriodically { + val aliceReply = newBobSession.cryptoService().getOutgoingRoomKeyRequests() + .first { + it.sessionId == megolmSessionId && + it.roomId == e2eRoomID + } + .results.also { + Log.w("##TEST", "result list is $it") + } + .firstOrNull { it.userId == aliceSession.myUserId } + ?.result + aliceReply != null && + aliceReply is RequestResult.Failure && + WithHeldCode.UNAUTHORISED == aliceReply.code } } From fec4bf17c71567993004634249b2a77772d9f823 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 17:30:53 +0100 Subject: [PATCH 32/56] making the test session clean up suspending --- .../sdk/api/network/ApiInterceptorTest.kt | 6 ++--- .../android/sdk/common/CommonTestHelper.kt | 22 +++++++++++++--- .../android/sdk/common/CryptoTestData.kt | 2 +- .../crypto/crosssigning/XSigningTest.kt | 3 ++- .../crypto/gossiping/KeyShareTests.kt | 1 - .../keysbackup/KeysBackupScenarioData.kt | 2 +- .../crypto/replayattack/ReplayAttackTest.kt | 25 +++++++++---------- .../sdk/internal/crypto/ssss/QuadSTests.kt | 3 ++- .../internal/crypto/verification/SASTest.kt | 3 ++- .../verification/qrcode/VerificationTest.kt | 3 ++- .../sdk/session/space/SpaceCreationTest.kt | 3 ++- .../sdk/session/space/SpaceHierarchyTest.kt | 3 ++- 12 files changed, 48 insertions(+), 28 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt index 8dbff820157..c5148a8078b 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt @@ -23,7 +23,7 @@ import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import timber.log.Timber @@ -33,7 +33,7 @@ import timber.log.Timber class ApiInterceptorTest : InstrumentedTest { @Test - fun apiInterceptorTest() = runSessionTest(context()) { commonTestHelper -> + fun apiInterceptorTest() = runSuspendingSessionTest(context()) { commonTestHelper -> val responses = mutableListOf() val listener = object : ApiInterceptorListener { @@ -45,7 +45,7 @@ class ApiInterceptorTest : InstrumentedTest { commonTestHelper.matrix.registerApiInterceptorListener(ApiPath.REGISTER, listener) - val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + val session = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) commonTestHelper.signOutAndClose(session) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index d0cb58ff027..4872abb7355 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -80,6 +80,22 @@ class CommonTestHelper internal constructor(context: Context) { } } + @OptIn(ExperimentalCoroutinesApi::class) + internal fun runSuspendingSessionTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CommonTestHelper) -> Unit) { + val testHelper = CommonTestHelper(context) + return runTest(dispatchTimeoutMs = TestConstants.timeOutMillis) { + try { + withContext(Dispatchers.Default) { + block(testHelper) + } + } finally { + if (autoSignoutOnClose) { + testHelper.cleanUpOpenedSessions() + } + } + } + } + internal fun runCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: (CryptoTestHelper, CommonTestHelper) -> Unit) { val testHelper = CommonTestHelper(context) val cryptoTestHelper = CryptoTestHelper(testHelper) @@ -690,11 +706,11 @@ class CommonTestHelper internal constructor(context: Context) { /** * Clear all provided sessions */ - fun Iterable.signOutAndClose() = forEach { signOutAndClose(it) } + suspend fun Iterable.signOutAndClose() = forEach { signOutAndClose(it) } - fun signOutAndClose(session: Session) { + suspend fun signOutAndClose(session: Session) { trackedSessions.remove(session) - runBlockingTest(timeout = 60_000) { + wrapWithTimeout(timeout = 60_000L) { session.signOutService().signOut(true) } // no need signout will close diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt index 41d0d3a7e86..8cd5bee5698 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestData.kt @@ -32,7 +32,7 @@ data class CryptoTestData( val thirdSession: Session? get() = sessions.getOrNull(2) - fun cleanUp(testHelper: CommonTestHelper) { + suspend fun cleanUp(testHelper: CommonTestHelper) { sessions.forEach { testHelper.signOutAndClose(it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index ef3fdfeeda3..462734ec6d8 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -40,6 +40,7 @@ import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import kotlin.coroutines.Continuation @@ -52,7 +53,7 @@ import kotlin.coroutines.resume class XSigningTest : InstrumentedTest { @Test - fun test_InitializeAndStoreKeys() = runSessionTest(context()) { testHelper -> + fun test_InitializeAndStoreKeys() = runSuspendingSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) testHelper.doSync { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index 8cae668efb0..dbd5d92664f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -42,7 +42,6 @@ import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.timeline.getLastMessageContent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupScenarioData.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupScenarioData.kt index cf201611a0c..8679cf3c998 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupScenarioData.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupScenarioData.kt @@ -30,7 +30,7 @@ internal data class KeysBackupScenarioData( val prepareKeysBackupDataResult: PrepareKeysBackupDataResult, val aliceSession2: Session ) { - fun cleanUp(testHelper: CommonTestHelper) { + suspend fun cleanUp(testHelper: CommonTestHelper) { cryptoTestData.cleanUp(testHelper) testHelper.signOutAndClose(aliceSession2) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt index 53cf802b91e..8b8fdedc924 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt @@ -29,6 +29,7 @@ import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.session.crypto.MXCryptoError import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @@ -36,7 +37,7 @@ import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest class ReplayAttackTest : InstrumentedTest { @Test - fun replayAttackAlreadyDecryptedEventTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun replayAttackAlreadyDecryptedEventTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = cryptoTestData.roomId @@ -51,25 +52,23 @@ class ReplayAttackTest : InstrumentedTest { assertEquals(bobRoomPOV.roomSummary()?.joinedMembersCount, 2) // Alice will send a message - val sentEvents = testHelper.sendTextMessage(aliceRoomPOV, "Hello I will be decrypted twice", 1) + val sentEvents = testHelper.sendTextMessageSuspending(aliceRoomPOV, "Hello I will be decrypted twice", 1) assertEquals(1, sentEvents.size) val fakeEventId = sentEvents[0].eventId + "_fake" val fakeEventWithTheSameIndex = sentEvents[0].copy(eventId = fakeEventId, root = sentEvents[0].root.copy(eventId = fakeEventId)) - testHelper.runBlockingTest { - // Lets assume we are from the main timelineId - val timelineId = "timelineId" - // Lets decrypt the original event - aliceSession.cryptoService().decryptEvent(sentEvents[0].root, timelineId) - // Lets decrypt the fake event that will have the same message index - val exception = assertFailsWith { - // An exception should be thrown while the same index would have been used for the previous decryption - aliceSession.cryptoService().decryptEvent(fakeEventWithTheSameIndex.root, timelineId) - } - assertEquals(MXCryptoError.ErrorType.DUPLICATED_MESSAGE_INDEX, exception.errorType) + // Lets assume we are from the main timelineId + val timelineId = "timelineId" + // Lets decrypt the original event + aliceSession.cryptoService().decryptEvent(sentEvents[0].root, timelineId) + // Lets decrypt the fake event that will have the same message index + val exception = assertFailsWith { + // An exception should be thrown while the same index would have been used for the previous decryption + aliceSession.cryptoService().decryptEvent(fakeEventWithTheSameIndex.root, timelineId) } + assertEquals(MXCryptoError.ErrorType.DUPLICATED_MESSAGE_INDEX, exception.errorType) cryptoTestData.cleanUp(testHelper) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt index c8be6aae74e..66afffd5628 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt @@ -41,6 +41,7 @@ import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.toBase64NoPadding import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.internal.crypto.secrets.DefaultSharedSecretStorageService @@ -56,7 +57,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_Generate4SKey() = runSessionTest(context()) { testHelper -> + fun test_Generate4SKey() = runSuspendingSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index 1bffbeeeaa9..bb9e1c54ebc 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -45,6 +45,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxStat import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationCancel import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationStart import org.matrix.android.sdk.internal.crypto.model.rest.toValue @@ -300,7 +301,7 @@ class SASTest : InstrumentedTest { // any two devices may only have at most one key verification in flight at a time. // If a device has two verifications in progress with the same device, then it should cancel both verifications. @Test - fun test_aliceStartTwoRequests() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceStartTwoRequests() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 3f229069653..1ed51b88a8a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -34,6 +34,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod import org.matrix.android.sdk.api.session.crypto.verification.VerificationService import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import java.util.concurrent.CountDownLatch @@ -256,7 +257,7 @@ class VerificationTest : InstrumentedTest { } @Test - fun test_selfVerificationAcceptedCancelsItForOtherSessions() = runSessionTest(context()) { testHelper -> + fun test_selfVerificationAcceptedCancelsItForOtherSessions() = runSuspendingSessionTest(context()) { testHelper -> val defaultSessionParams = SessionTestParams(true) val aliceSessionToVerify = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt index 2cd579df24d..c9e55a1e9c4 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt @@ -43,6 +43,7 @@ import org.matrix.android.sdk.api.session.room.model.create.CreateRoomPreset import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent import org.matrix.android.sdk.api.session.space.JoinSpaceResult import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams @RunWith(JUnit4::class) @@ -109,7 +110,7 @@ class SpaceCreationTest : InstrumentedTest { @Test @Ignore - fun testJoinSimplePublicSpace() = runSessionTest(context()) { commonTestHelper -> + fun testJoinSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt index 18645fd6d9c..81d47cfc60c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt @@ -48,6 +48,7 @@ import org.matrix.android.sdk.api.session.room.powerlevels.Role import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams @RunWith(JUnit4::class) @@ -296,7 +297,7 @@ class SpaceHierarchyTest : InstrumentedTest { } @Test - fun testLiveFlatChildren() = runSessionTest(context()) { commonTestHelper -> + fun testLiveFlatChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( From fa97699cd8452a8e7fb399547d2d51d99c80f4dd Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 21 Sep 2022 17:44:26 +0100 Subject: [PATCH 33/56] making test login and create account usages suspending --- .../sdk/account/AccountCreationTest.kt | 10 +-- .../android/sdk/account/ChangePasswordTest.kt | 10 ++- .../android/sdk/common/CommonTestHelper.kt | 65 +------------------ .../android/sdk/common/CryptoTestHelper.kt | 48 +++++++------- .../crypto/DecryptRedactedEventTest.kt | 41 ++++++------ .../sdk/internal/crypto/E2eeSanityTests.kt | 6 +- .../sdk/internal/crypto/UnwedgingTest.kt | 21 +++--- .../crypto/crosssigning/XSigningTest.kt | 25 ++++--- .../crypto/gossiping/WithHeldTests.kt | 6 +- .../crypto/keysbackup/KeysBackupTestHelper.kt | 2 +- .../crypto/replayattack/ReplayAttackTest.kt | 22 +++---- .../internal/crypto/verification/SASTest.kt | 18 ++--- .../verification/qrcode/VerificationTest.kt | 15 +++-- .../room/threads/ThreadMessagingTest.kt | 5 +- .../room/timeline/PollAggregationTest.kt | 3 +- .../TimelinePreviousLastForwardTest.kt | 2 +- .../TimelineSimpleBackPaginationTest.kt | 3 +- 17 files changed, 118 insertions(+), 184 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt index d24a2a50ef3..f61bc5aa1ae 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt @@ -24,8 +24,8 @@ import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -35,14 +35,14 @@ import org.matrix.android.sdk.common.TestConstants class AccountCreationTest : InstrumentedTest { @Test - fun createAccountTest() = runSessionTest(context()) { commonTestHelper -> - commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + fun createAccountTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) } @Test @Ignore("This test will be ignored until it is fixed") - fun createAccountAndLoginAgainTest() = runSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + fun createAccountAndLoginAgainTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + val session = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) // Log again to the same account commonTestHelper.logIntoAccount(session.myUserId, SessionTestParams(withInitialSync = true)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt index 260e8dbe058..053f67b4f69 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt @@ -25,7 +25,7 @@ import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.failure.isInvalidPassword -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -39,13 +39,11 @@ class ChangePasswordTest : InstrumentedTest { } @Test - fun changePasswordTest() = runSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) + fun changePasswordTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + val session = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) // Change password - commonTestHelper.runBlockingTest { - session.accountService().changePassword(TestConstants.PASSWORD, NEW_PASSWORD) - } + session.accountService().changePassword(TestConstants.PASSWORD, NEW_PASSWORD) // Try to login with the previous password, it will fail val throwable = commonTestHelper.logAccountWithError(session.myUserId, TestConstants.PASSWORD) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 4872abb7355..f30c367ee75 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -157,14 +157,10 @@ class CommonTestHelper internal constructor(context: Context) { return createAccountSuspending(userNamePrefix, TestConstants.PASSWORD, testParams) } - fun logIntoAccount(userId: String, testParams: SessionTestParams): Session { + suspend fun logIntoAccount(userId: String, testParams: SessionTestParams): Session { return logIntoAccount(userId, TestConstants.PASSWORD, testParams) } - suspend fun logIntoAccountSuspending(userId: String, testParams: SessionTestParams): Session { - return logIntoAccountSuspending(userId, TestConstants.PASSWORD, testParams) - } - fun cleanUpOpenedSessions() { trackedSessions.forEach { runBlockingTest { @@ -409,15 +405,7 @@ class CommonTestHelper internal constructor(context: Context) { } } - /** - * Logs into an existing account - * - * @param userId the userId to log in - * @param password the password to log in - * @param testParams test params about the session - * @return the session associated with the existing account - */ - fun logIntoAccount( + suspend fun logIntoAccount( userId: String, password: String, testParams: SessionTestParams @@ -429,18 +417,6 @@ class CommonTestHelper internal constructor(context: Context) { } } - suspend fun logIntoAccountSuspending( - userId: String, - password: String, - testParams: SessionTestParams - ): Session { - val session = logAccountAndSyncSuspending(userId, password, testParams) - assertNotNull(session) - return session.also { - trackedSessions.add(session) - } - } - /** * Create an account and a dedicated session * @@ -514,42 +490,7 @@ class CommonTestHelper internal constructor(context: Context) { return session } - /** - * Start an account login - * - * @param userName the account username - * @param password the password - * @param sessionTestParams session test params - */ - private fun logAccountAndSync( - userName: String, - password: String, - sessionTestParams: SessionTestParams - ): Session { - val hs = createHomeServerConfig() - - runBlockingTest { - matrix.authenticationService.getLoginFlow(hs) - } - - val session = runBlockingTest { - matrix.authenticationService - .getLoginWizard() - .login(userName, password, "myDevice") - } - session.open() - if (sessionTestParams.withInitialSync) { - syncSession(session) - } - - return session - } - - private suspend fun logAccountAndSyncSuspending( - userName: String, - password: String, - sessionTestParams: SessionTestParams - ): Session { + private suspend fun logAccountAndSync(userName: String, password: String, sessionTestParams: SessionTestParams): Session { val hs = createHomeServerConfig() matrix.authenticationService.getLoginFlow(hs) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index a007d06a53d..3e577b54eae 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -87,40 +87,38 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { /** * @return alice and bob sessions */ - fun doE2ETestWithAliceAndBobInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { - return testHelper.launch { - val cryptoTestData = doE2ETestWithAliceInARoom(encryptedRoom, roomHistoryVisibility) - val aliceSession = cryptoTestData.firstSession - val aliceRoomId = cryptoTestData.roomId + suspend fun doE2ETestWithAliceAndBobInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { + val cryptoTestData = doE2ETestWithAliceInARoom(encryptedRoom, roomHistoryVisibility) + val aliceSession = cryptoTestData.firstSession + val aliceRoomId = cryptoTestData.roomId - val aliceRoom = aliceSession.getRoom(aliceRoomId)!! + val aliceRoom = aliceSession.getRoom(aliceRoomId)!! - val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, defaultSessionParams) + val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, defaultSessionParams) - waitFor( - continueWhen = { bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { it.isNotEmpty() } }, - action = { aliceRoom.membershipService().invite(bobSession.myUserId) } - ) + waitFor( + continueWhen = { bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { it.isNotEmpty() } }, + action = { aliceRoom.membershipService().invite(bobSession.myUserId) } + ) - waitFor( - continueWhen = { - bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { - bobSession.getRoom(aliceRoomId) - ?.membershipService() - ?.getRoomMember(bobSession.myUserId) - ?.membership == Membership.JOIN - } - }, - action = { bobSession.roomService().joinRoom(aliceRoomId) } - ) + waitFor( + continueWhen = { + bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { + bobSession.getRoom(aliceRoomId) + ?.membershipService() + ?.getRoomMember(bobSession.myUserId) + ?.membership == Membership.JOIN + } + }, + action = { bobSession.roomService().joinRoom(aliceRoomId) } + ) - // Ensure bob can send messages to the room + // Ensure bob can send messages to the room // val roomFromBobPOV = bobSession.getRoom(aliceRoomId)!! // assertNotNull(roomFromBobPOV.powerLevels) // assertTrue(roomFromBobPOV.powerLevels.maySendMessage(bobSession.myUserId)) - CryptoTestData(aliceRoomId, listOf(aliceSession, bobSession)) - } + return CryptoTestData(aliceRoomId, listOf(aliceSession, bobSession)) } /** diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt index a48b45a1f53..48d9d6da77c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt @@ -28,48 +28,45 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) class DecryptRedactedEventTest : InstrumentedTest { @Test - fun doNotFailToDecryptRedactedEvent() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun doNotFailToDecryptRedactedEvent() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = testData.roomId val aliceSession = testData.firstSession val bobSession = testData.secondSession!! val roomALicePOV = aliceSession.getRoom(e2eRoomID)!! - val timelineEvent = testHelper.sendTextMessage(roomALicePOV, "Hello", 1).first() + val timelineEvent = testHelper.sendTextMessageSuspending(roomALicePOV, "Hello", 1).first() val redactionReason = "Wrong Room" roomALicePOV.sendService().redactEvent(timelineEvent.root, redactionReason) // get the event from bob - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - bobSession.getRoom(e2eRoomID)?.getTimelineEvent(timelineEvent.eventId)?.root?.isRedacted() == true - } + testHelper.retryPeriodically { + bobSession.getRoom(e2eRoomID)?.getTimelineEvent(timelineEvent.eventId)?.root?.isRedacted() == true } val eventBobPov = bobSession.getRoom(e2eRoomID)?.getTimelineEvent(timelineEvent.eventId)!! - testHelper.runBlockingTest { - try { - val result = bobSession.cryptoService().decryptEvent(eventBobPov.root, "") - Assert.assertEquals( - "Unexpected redacted reason", - redactionReason, - result.clearEvent.toModel()?.unsignedData?.redactedEvent?.content?.get("reason") - ) - Assert.assertEquals( - "Unexpected Redacted event id", - timelineEvent.eventId, - result.clearEvent.toModel()?.unsignedData?.redactedEvent?.redacts - ) - } catch (failure: Throwable) { - Assert.fail("Should not throw when decrypting a redacted event") - } + try { + val result = bobSession.cryptoService().decryptEvent(eventBobPov.root, "") + Assert.assertEquals( + "Unexpected redacted reason", + redactionReason, + result.clearEvent.toModel()?.unsignedData?.redactedEvent?.content?.get("reason") + ) + Assert.assertEquals( + "Unexpected Redacted event id", + timelineEvent.eventId, + result.clearEvent.toModel()?.unsignedData?.redactedEvent?.redacts + ) + } catch (failure: Throwable) { + Assert.fail("Should not throw when decrypting a redacted event") } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index 7a8c1e8a03c..d1d34faa562 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -264,7 +264,7 @@ class E2eeSanityTests : InstrumentedTest { // Create a new session for bob Log.v("#E2E TEST", "Create a new session for Bob") - val newBobSession = testHelper.logIntoAccountSuspending(bobUserId, SessionTestParams(true)) + val newBobSession = testHelper.logIntoAccount(bobUserId, SessionTestParams(true)) // check that bob can't currently decrypt Log.v("#E2E TEST", "check that bob can't currently decrypt") @@ -434,7 +434,7 @@ class E2eeSanityTests : InstrumentedTest { ensureIsDecrypted(testHelper, listOf(firstEventId), bobSessionWithBetterKey, e2eRoomID) // Let's add a new unverified session from bob - val newBobSession = testHelper.logIntoAccountSuspending(bobSessionWithBetterKey.myUserId, SessionTestParams(true)) + val newBobSession = testHelper.logIntoAccount(bobSessionWithBetterKey.myUserId, SessionTestParams(true)) // check that new bob can't currently decrypt Log.v("#E2E TEST", "check that new bob can't currently decrypt") @@ -542,7 +542,7 @@ class E2eeSanityTests : InstrumentedTest { // now let's create a new login from alice - val aliceNewSession = testHelper.logIntoAccountSuspending(aliceSession.myUserId, SessionTestParams(true)) + val aliceNewSession = testHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) val deferredOldCode = aliceSession.cryptoService().verificationService().readOldVerificationCodeAsync(this, aliceSession.myUserId) val deferredNewCode = aliceNewSession.cryptoService().verificationService().readNewVerificationCodeAsync(this, aliceSession.myUserId) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index 5fe73761841..fb05e608423 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -39,6 +39,7 @@ import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.internal.crypto.model.OlmSessionWrapper import org.matrix.android.sdk.internal.crypto.store.db.deserializeFromRealm @@ -82,7 +83,7 @@ class UnwedgingTest : InstrumentedTest { * -> This is automatically fixed after SDKs restarted the olm session */ @Test - fun testUnwedging() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testUnwedging() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession @@ -205,7 +206,7 @@ class UnwedgingTest : InstrumentedTest { bobTimeline.removeListener(bobHasThreeDecryptedEventsListener) // It's a trick to force key request on fail to decrypt - testHelper.doSync { + testHelper.doSyncSuspending { bobSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { @@ -223,17 +224,13 @@ class UnwedgingTest : InstrumentedTest { } // Wait until we received back the key - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - // we should get back the key and be able to decrypt - val result = testHelper.runBlockingTest { - tryOrNull { - bobSession.cryptoService().decryptEvent(messagesReceivedByBob[0].root, "") - } - } - Timber.i("## CRYPTO | testUnwedging: decrypt result ${result?.clearEvent}") - result != null + testHelper.retryPeriodically { + // we should get back the key and be able to decrypt + val result = tryOrNull { + bobSession.cryptoService().decryptEvent(messagesReceivedByBob[0].root, "") } + Timber.i("## CRYPTO | testUnwedging: decrypt result ${result?.clearEvent}") + result != null } bobTimeline.dispose() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index 462734ec6d8..6797db52699 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -38,8 +38,7 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.isCrossSignedVerif import org.matrix.android.sdk.api.session.crypto.crosssigning.isVerified import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -87,7 +86,7 @@ class XSigningTest : InstrumentedTest { } @Test - fun test_CrossSigningCheckBobSeesTheKeys() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_CrossSigningCheckBobSeesTheKeys() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession @@ -102,14 +101,14 @@ class XSigningTest : InstrumentedTest { password = TestConstants.PASSWORD ) - testHelper.doSync { + testHelper.doSyncSuspending { aliceSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(aliceAuthParams) } }, it) } - testHelper.doSync { + testHelper.doSyncSuspending { bobSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(bobAuthParams) @@ -140,7 +139,7 @@ class XSigningTest : InstrumentedTest { } @Test - fun test_CrossSigningTestAliceTrustBobNewDevice() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_CrossSigningTestAliceTrustBobNewDevice() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession @@ -155,14 +154,14 @@ class XSigningTest : InstrumentedTest { password = TestConstants.PASSWORD ) - testHelper.doSync { + testHelper.doSyncSuspending { aliceSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(aliceAuthParams) } }, it) } - testHelper.doSync { + testHelper.doSyncSuspending { bobSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(bobAuthParams) @@ -172,12 +171,12 @@ class XSigningTest : InstrumentedTest { // Check that alice can see bob keys val bobUserId = bobSession.myUserId - testHelper.doSync> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } + testHelper.doSyncSuspending> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } val bobKeysFromAlicePOV = aliceSession.cryptoService().crossSigningService().getUserCrossSigningKeys(bobUserId) assertTrue("Bob keys from alice pov should not be trusted", bobKeysFromAlicePOV?.isTrusted() == false) - testHelper.doSync { aliceSession.cryptoService().crossSigningService().trustUser(bobUserId, it) } + testHelper.doSyncSuspending { aliceSession.cryptoService().crossSigningService().trustUser(bobUserId, it) } // Now bobs logs in on a new device and verifies it // We will want to test that in alice POV, this new device would be trusted by cross signing @@ -186,7 +185,7 @@ class XSigningTest : InstrumentedTest { val bobSecondDeviceId = bobSession2.sessionParams.deviceId!! // Check that bob first session sees the new login - val data = testHelper.doSync> { + val data = testHelper.doSyncSuspending> { bobSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } @@ -198,12 +197,12 @@ class XSigningTest : InstrumentedTest { assertNotNull("Bob Second device should be known and persisted from first", bobSecondDevicePOVFirstDevice) // Manually mark it as trusted from first session - testHelper.doSync { + testHelper.doSyncSuspending { bobSession.cryptoService().crossSigningService().trustDevice(bobSecondDeviceId, it) } // Now alice should cross trust bob's second device - val data2 = testHelper.doSync> { + val data2 = testHelper.doSyncSuspending> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index 48c9d5b3aa8..a1fde267787 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -69,7 +69,7 @@ class WithHeldTests : InstrumentedTest { val roomAlicePOV = aliceSession.getRoom(roomId)!! - val bobUnverifiedSession = testHelper.logIntoAccountSuspending(bobSession.myUserId, SessionTestParams(true)) + val bobUnverifiedSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(true)) // ============================= // ACT // ============================= @@ -196,7 +196,7 @@ class WithHeldTests : InstrumentedTest { // Add a new device for bob aliceInterceptor.clearRules() - val bobSecondSession = testHelper.logIntoAccountSuspending(bobSession.myUserId, SessionTestParams(withInitialSync = true)) + val bobSecondSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(withInitialSync = true)) // send a second message val secondMessageId = testHelper.sendTextMessageSuspending(roomAlicePov, "second message", 1).first().eventId @@ -231,7 +231,7 @@ class WithHeldTests : InstrumentedTest { // Create a new session for bob - val bobSecondSession = testHelper.logIntoAccountSuspending(bobSession.myUserId, SessionTestParams(true)) + val bobSecondSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(true)) // initialize to force request keys if missing cryptoTestHelper.initializeCrossSigning(bobSecondSession) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt index c4dabbf6f8f..a5d20a7cd28 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -80,7 +80,7 @@ internal class KeysBackupTestHelper( val aliceUserId = cryptoTestData.firstSession.myUserId // - Log Alice on a new device - val aliceSession2 = testHelper.logIntoAccountSuspending(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) + val aliceSession2 = testHelper.logIntoAccount(aliceUserId, KeysBackupTestConstants.defaultSessionParamsWithInitialSync) // Test check: aliceSession2 has no keys at login Assert.assertEquals(0, aliceSession2.cryptoService().inboundGroupSessionsCount(false)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt index 8b8fdedc924..ee643281a1e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt @@ -73,7 +73,7 @@ class ReplayAttackTest : InstrumentedTest { } @Test - fun replayAttackSameEventTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun replayAttackSameEventTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = cryptoTestData.roomId @@ -88,21 +88,19 @@ class ReplayAttackTest : InstrumentedTest { assertEquals(bobRoomPOV.roomSummary()?.joinedMembersCount, 2) // Alice will send a message - val sentEvents = testHelper.sendTextMessage(aliceRoomPOV, "Hello I will be decrypted twice", 1) + val sentEvents = testHelper.sendTextMessageSuspending(aliceRoomPOV, "Hello I will be decrypted twice", 1) Assert.assertTrue("Message should be sent", sentEvents.size == 1) assertEquals(sentEvents.size, 1) - testHelper.runBlockingTest { - // Lets assume we are from the main timelineId - val timelineId = "timelineId" - // Lets decrypt the original event + // Lets assume we are from the main timelineId + val timelineId = "timelineId" + // Lets decrypt the original event + aliceSession.cryptoService().decryptEvent(sentEvents[0].root, timelineId) + try { + // Lets try to decrypt the same event aliceSession.cryptoService().decryptEvent(sentEvents[0].root, timelineId) - try { - // Lets try to decrypt the same event - aliceSession.cryptoService().decryptEvent(sentEvents[0].root, timelineId) - } catch (ex: Throwable) { - fail("Shouldn't throw a decryption error for same event") - } + } catch (ex: Throwable) { + fail("Shouldn't throw a decryption error for same event") } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index bb9e1c54ebc..df289e61882 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -58,7 +58,7 @@ class SASTest : InstrumentedTest { @Test fun test_aliceStartThenAliceCancel() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -140,7 +140,7 @@ class SASTest : InstrumentedTest { @Ignore("This test will be ignored until it is fixed") fun test_key_agreement_protocols_must_include_curve25519() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val bobSession = cryptoTestData.secondSession!! @@ -196,7 +196,7 @@ class SASTest : InstrumentedTest { @Ignore("This test will be ignored until it is fixed") fun test_key_agreement_macs_Must_include_hmac_sha256() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val bobSession = cryptoTestData.secondSession!! @@ -233,7 +233,7 @@ class SASTest : InstrumentedTest { @Ignore("This test will be ignored until it is fixed") fun test_key_agreement_short_code_include_decimal() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val bobSession = cryptoTestData.secondSession!! @@ -302,7 +302,7 @@ class SASTest : InstrumentedTest { // If a device has two verifications in progress with the same device, then it should cancel both verifications. @Test fun test_aliceStartTwoRequests() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -343,7 +343,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") fun test_aliceAndBobAgreement() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -400,7 +400,7 @@ class SASTest : InstrumentedTest { @Test fun test_aliceAndBobSASCode() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -456,7 +456,7 @@ class SASTest : InstrumentedTest { @Test fun test_happyPath() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -532,7 +532,7 @@ class SASTest : InstrumentedTest { @Test fun test_ConcurrentStart() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() + val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 1ed51b88a8a..e3c5bb8ac17 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -32,8 +32,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.CancelCode import org.matrix.android.sdk.api.session.crypto.verification.PendingVerificationRequest import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod import org.matrix.android.sdk.api.session.crypto.verification.VerificationService -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -159,13 +158,13 @@ class VerificationTest : InstrumentedTest { bobSupportedMethods: List, expectedResultForAlice: ExpectedResult, expectedResultForBob: ExpectedResult - ) = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + ) = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession!! - testHelper.doSync { callback -> + testHelper.doSyncSuspending { callback -> aliceSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { @@ -182,7 +181,7 @@ class VerificationTest : InstrumentedTest { ) } - testHelper.doSync { callback -> + testHelper.doSyncSuspending { callback -> bobSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { @@ -262,7 +261,11 @@ class VerificationTest : InstrumentedTest { val aliceSessionToVerify = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) val aliceSessionThatVerifies = testHelper.logIntoAccount(aliceSessionToVerify.myUserId, TestConstants.PASSWORD, defaultSessionParams) - val aliceSessionThatReceivesCanceledEvent = testHelper.logIntoAccount(aliceSessionToVerify.myUserId, TestConstants.PASSWORD, defaultSessionParams) + val aliceSessionThatReceivesCanceledEvent = testHelper.logIntoAccount( + aliceSessionToVerify.myUserId, + TestConstants.PASSWORD, + defaultSessionParams + ) val verificationMethods = listOf(VerificationMethod.SAS, VerificationMethod.QR_CODE_SCAN, VerificationMethod.QR_CODE_SHOW) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt index 8ece6d10c59..90de934cc45 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt @@ -35,6 +35,7 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import java.util.concurrent.CountDownLatch @RunWith(JUnit4::class) @@ -101,7 +102,7 @@ class ThreadMessagingTest : InstrumentedTest { } @Test - fun reply_in_thread_should_create_a_thread_from_other_user() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun reply_in_thread_should_create_a_thread_from_other_user() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession @@ -237,7 +238,7 @@ class ThreadMessagingTest : InstrumentedTest { } @Test - fun thread_summary_advanced_validation_after_multiple_messages_in_multiple_threads() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun thread_summary_advanced_validation_after_multiple_messages_in_multiple_threads() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt index a37d2ce015f..ffb6ff5663b 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt @@ -39,6 +39,7 @@ import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import java.util.concurrent.CountDownLatch @RunWith(JUnit4::class) @@ -46,7 +47,7 @@ import java.util.concurrent.CountDownLatch class PollAggregationTest : InstrumentedTest { @Test - fun testAllPollUseCases() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun testAllPollUseCases() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt index 7c1a097b241..2ad3eda9181 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt @@ -49,7 +49,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { */ @Test - fun previousLastForwardTest() = CommonTestHelper.runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun previousLastForwardTest() = CommonTestHelper.runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt index 59b3b145322..6e66e1bc47e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt @@ -34,6 +34,7 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageTextContent import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.TestConstants @RunWith(JUnit4::class) @@ -43,7 +44,7 @@ import org.matrix.android.sdk.common.TestConstants class TimelineSimpleBackPaginationTest : InstrumentedTest { @Test - fun timeline_backPaginate_shouldReachEndOfTimeline() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun timeline_backPaginate_shouldReachEndOfTimeline() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val numberOfMessagesToSent = 200 val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) From 801afddc4991de26116b889634849820776ae205 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 09:15:23 +0100 Subject: [PATCH 34/56] using shouldbeequalto as we're checking values rather than instances --- .../android/sdk/internal/crypto/UnwedgingTest.kt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index fb05e608423..62d55b1f360 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -17,7 +17,7 @@ package org.matrix.android.sdk.internal.crypto import androidx.test.ext.junit.runners.AndroidJUnit4 -import org.amshove.kluent.shouldBe +import org.amshove.kluent.shouldBeEqualTo import org.junit.Assert import org.junit.Before import org.junit.FixMethodOrder @@ -38,7 +38,6 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.internal.crypto.model.OlmSessionWrapper @@ -133,14 +132,14 @@ class UnwedgingTest : InstrumentedTest { testHelper.await(latch) bobTimeline.removeListener(bobEventsListener) - messagesReceivedByBob.size shouldBe 1 + messagesReceivedByBob.size shouldBeEqualTo 1 val firstMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! // - Store the olm session between A&B devices // Let us pickle our session with bob here so we can later unpickle it // and wedge our session. val sessionIdsForBob = aliceCryptoStore.getDeviceSessionIds(bobSession.cryptoService().getMyDevice().identityKey()!!) - sessionIdsForBob!!.size shouldBe 1 + sessionIdsForBob!!.size shouldBeEqualTo 1 val olmSession = aliceCryptoStore.getDeviceSession(sessionIdsForBob.first(), bobSession.cryptoService().getMyDevice().identityKey()!!)!! val oldSession = serializeForRealm(olmSession.olmSession) @@ -161,7 +160,7 @@ class UnwedgingTest : InstrumentedTest { testHelper.await(latch) bobTimeline.removeListener(bobEventsListener) - messagesReceivedByBob.size shouldBe 2 + messagesReceivedByBob.size shouldBeEqualTo 2 // Session should have changed val secondMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! Assert.assertNotEquals(firstMessageSession, secondMessageSession) @@ -192,7 +191,7 @@ class UnwedgingTest : InstrumentedTest { } bobTimeline.removeListener(bobEventsListener) - messagesReceivedByBob.size shouldBe 3 + messagesReceivedByBob.size shouldBeEqualTo 3 val thirdMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! Timber.i("## CRYPTO | testUnwedging: third message session ID $thirdMessageSession") From e3a9e4ed4a801f14b5d83ff32141ba8bea302e8b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 09:18:24 +0100 Subject: [PATCH 35/56] removing test sleeps, the test is passing without --- .../org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index 62d55b1f360..5e4513bf417 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -145,7 +145,6 @@ class UnwedgingTest : InstrumentedTest { val oldSession = serializeForRealm(olmSession.olmSession) aliceSession.cryptoService().discardOutboundSession(roomFromAlicePOV.roomId) - Thread.sleep(6_000) latch = CountDownLatch(1) bobEventsListener = createEventListener(latch, 2) @@ -173,7 +172,6 @@ class UnwedgingTest : InstrumentedTest { bobSession.cryptoService().getMyDevice().identityKey()!! ) olmDevice.clearOlmSessionCache() - Thread.sleep(6_000) // Force new session, and key share aliceSession.cryptoService().discardOutboundSession(roomFromAlicePOV.roomId) From f4da2d8053aff7340df989136c99a59c50c07cf5 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 09:46:11 +0100 Subject: [PATCH 36/56] converting unwedging test to use coroutines/suspends instead of latches --- .../sdk/internal/crypto/UnwedgingTest.kt | 73 ++++++------------- 1 file changed, 21 insertions(+), 52 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index 5e4513bf417..d9756bd2eda 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -17,6 +17,7 @@ package org.matrix.android.sdk.internal.crypto import androidx.test.ext.junit.runners.AndroidJUnit4 +import kotlinx.coroutines.suspendCancellableCoroutine import org.amshove.kluent.shouldBeEqualTo import org.junit.Assert import org.junit.Before @@ -45,7 +46,6 @@ import org.matrix.android.sdk.internal.crypto.store.db.deserializeFromRealm import org.matrix.android.sdk.internal.crypto.store.db.serializeForRealm import org.matrix.olm.OlmSession import timber.log.Timber -import java.util.concurrent.CountDownLatch import kotlin.coroutines.Continuation import kotlin.coroutines.resume @@ -98,39 +98,13 @@ class UnwedgingTest : InstrumentedTest { val bobTimeline = roomFromBobPOV.timelineService().createTimeline(null, TimelineSettings(20)) bobTimeline.start() - val bobFinalLatch = CountDownLatch(1) - val bobHasThreeDecryptedEventsListener = object : Timeline.Listener { - override fun onTimelineFailure(throwable: Throwable) { - // noop - } - - override fun onNewTimelineEvents(eventIds: List) { - // noop - } - - override fun onTimelineUpdated(snapshot: List) { - val decryptedEventReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } - Timber.d("Bob can now decrypt ${decryptedEventReceivedByBob.size} messages") - if (decryptedEventReceivedByBob.size == 3) { - if (decryptedEventReceivedByBob[0].root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) { - bobFinalLatch.countDown() - } - } - } - } - bobTimeline.addListener(bobHasThreeDecryptedEventsListener) - - var latch = CountDownLatch(1) - var bobEventsListener = createEventListener(latch, 1) - bobTimeline.addListener(bobEventsListener) messagesReceivedByBob = emptyList() // - Alice sends a 1st message with a 1st megolm session roomFromAlicePOV.sendService().sendTextMessage("First message") // Wait for the message to be received by Bob - testHelper.await(latch) - bobTimeline.removeListener(bobEventsListener) + messagesReceivedByBob = bobTimeline.waitForMessages(expectedCount = 1) messagesReceivedByBob.size shouldBeEqualTo 1 val firstMessageSession = messagesReceivedByBob[0].root.content.toModel()!!.sessionId!! @@ -146,18 +120,13 @@ class UnwedgingTest : InstrumentedTest { aliceSession.cryptoService().discardOutboundSession(roomFromAlicePOV.roomId) - latch = CountDownLatch(1) - bobEventsListener = createEventListener(latch, 2) - bobTimeline.addListener(bobEventsListener) messagesReceivedByBob = emptyList() - Timber.i("## CRYPTO | testUnwedging: Alice sends a 2nd message with a 2nd megolm session") // - Alice sends a 2nd message with a 2nd megolm session roomFromAlicePOV.sendService().sendTextMessage("Second message") // Wait for the message to be received by Bob - testHelper.await(latch) - bobTimeline.removeListener(bobEventsListener) + messagesReceivedByBob = bobTimeline.waitForMessages(expectedCount = 2) messagesReceivedByBob.size shouldBeEqualTo 2 // Session should have changed @@ -176,18 +145,12 @@ class UnwedgingTest : InstrumentedTest { // Force new session, and key share aliceSession.cryptoService().discardOutboundSession(roomFromAlicePOV.roomId) + Timber.i("## CRYPTO | testUnwedging: Alice sends a 3rd message with a 3rd megolm session but a wedged olm session") + // - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session + roomFromAlicePOV.sendService().sendTextMessage("Third message") + // Bob should not be able to decrypt, because the session key could not be sent // Wait for the message to be received by Bob - testHelper.waitWithLatch { - bobEventsListener = createEventListener(it, 3) - bobTimeline.addListener(bobEventsListener) - messagesReceivedByBob = emptyList() - - Timber.i("## CRYPTO | testUnwedging: Alice sends a 3rd message with a 3rd megolm session but a wedged olm session") - // - Alice sends a 3rd message with a 3rd megolm session but a wedged olm session - roomFromAlicePOV.sendService().sendTextMessage("Third message") - // Bob should not be able to decrypt, because the session key could not be sent - } - bobTimeline.removeListener(bobEventsListener) + messagesReceivedByBob = bobTimeline.waitForMessages(expectedCount = 3) messagesReceivedByBob.size shouldBeEqualTo 3 @@ -199,8 +162,8 @@ class UnwedgingTest : InstrumentedTest { Assert.assertEquals(EventType.MESSAGE, messagesReceivedByBob[1].root.getClearType()) Assert.assertEquals(EventType.MESSAGE, messagesReceivedByBob[2].root.getClearType()) // Bob Should not be able to decrypt last message, because session could not be sent as the olm channel was wedged - testHelper.await(bobFinalLatch) - bobTimeline.removeListener(bobHasThreeDecryptedEventsListener) + + Assert.assertTrue(messagesReceivedByBob[0].root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) // It's a trick to force key request on fail to decrypt testHelper.doSyncSuspending { @@ -232,9 +195,11 @@ class UnwedgingTest : InstrumentedTest { bobTimeline.dispose() } +} - private fun createEventListener(latch: CountDownLatch, expectedNumberOfMessages: Int): Timeline.Listener { - return object : Timeline.Listener { +private suspend fun Timeline.waitForMessages(expectedCount: Int): List { + return suspendCancellableCoroutine { continuation -> + val listener = object : Timeline.Listener { override fun onTimelineFailure(throwable: Throwable) { // noop } @@ -244,12 +209,16 @@ class UnwedgingTest : InstrumentedTest { } override fun onTimelineUpdated(snapshot: List) { - messagesReceivedByBob = snapshot.filter { it.root.type == EventType.ENCRYPTED } + val messagesReceived = snapshot.filter { it.root.type == EventType.ENCRYPTED } - if (messagesReceivedByBob.size == expectedNumberOfMessages) { - latch.countDown() + if (messagesReceived.size == expectedCount) { + removeListener(this) + continuation.resume(messagesReceived) } } } + + addListener(listener) + continuation.invokeOnCancellation { removeListener(listener) } } } From 0b844eaab455dfe82d21522c7f65de1a7a480ebd Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 09:55:36 +0100 Subject: [PATCH 37/56] converting space creation tests to suspends --- .../sdk/session/space/SpaceCreationTest.kt | 98 +++++++------------ 1 file changed, 33 insertions(+), 65 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt index c9e55a1e9c4..0b1fc91ce2e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt @@ -52,19 +52,14 @@ import org.matrix.android.sdk.common.SessionTestParams class SpaceCreationTest : InstrumentedTest { @Test - fun createSimplePublicSpace() = runSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount("Hubble", SessionTestParams(true)) + fun createSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> + val session = commonTestHelper.createAccountSuspending("Hubble", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" - var spaceId: String = "" - commonTestHelper.runBlockingTest { - spaceId = session.spaceService().createSpace(roomName, topic, null, true) - } + val spaceId = session.spaceService().createSpace(roomName, topic, null, true) - commonTestHelper.waitWithLatch { - commonTestHelper.retryPeriodicallyWithLatch(it) { - session.spaceService().getSpace(spaceId)?.asRoom()?.roomSummary()?.name != null - } + commonTestHelper.retryPeriodically { + session.spaceService().getSpace(spaceId)?.asRoom()?.roomSummary()?.name != null } val syncedSpace = session.spaceService().getSpace(spaceId) @@ -80,14 +75,12 @@ class SpaceCreationTest : InstrumentedTest { assertEquals("Room type should be space", RoomType.SPACE, createContent?.type) var powerLevelsContent: PowerLevelsContent? = null - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - powerLevelsContent = syncedSpace.asRoom() - .getStateEvent(EventType.STATE_ROOM_POWER_LEVELS, QueryStringValue.IsEmpty) - ?.content - ?.toModel() - powerLevelsContent != null - } + commonTestHelper.retryPeriodically { + powerLevelsContent = syncedSpace.asRoom() + .getStateEvent(EventType.STATE_ROOM_POWER_LEVELS, QueryStringValue.IsEmpty) + ?.content + ?.toModel() + powerLevelsContent != null } assertEquals("Space-rooms should be created with a power level for events_default of 100", 100, powerLevelsContent?.eventsDefault) @@ -112,24 +105,18 @@ class SpaceCreationTest : InstrumentedTest { @Ignore fun testJoinSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) - val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) + val aliceSession = commonTestHelper.createAccountSuspending("alice", SessionTestParams(true)) + val bobSession = commonTestHelper.createAccountSuspending("bob", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" - val spaceId: String - runBlocking { - spaceId = aliceSession.spaceService().createSpace(roomName, topic, null, true) - // wait a bit to let the summary update it self :/ - delay(400) - } + val spaceId = aliceSession.spaceService().createSpace(roomName, topic, null, true) + // wait a bit to let the summary update it self :/ + delay(400) // Try to join from bob, it's a public space no need to invite - val joinResult: JoinSpaceResult - runBlocking { - joinResult = bobSession.spaceService().joinSpace(spaceId) - } + val joinResult = bobSession.spaceService().joinSpace(spaceId) assertEquals(JoinSpaceResult.Success, joinResult) @@ -142,9 +129,9 @@ class SpaceCreationTest : InstrumentedTest { } @Test - fun testSimplePublicSpaceWithChildren() = runSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) - val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) + fun testSimplePublicSpaceWithChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> + val aliceSession = commonTestHelper.createAccountSuspending("alice", SessionTestParams(true)) + val bobSession = commonTestHelper.createAccountSuspending("bob", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" @@ -153,43 +140,24 @@ class SpaceCreationTest : InstrumentedTest { val syncedSpace = aliceSession.spaceService().getSpace(spaceId) // create a room - var firstChild: String? = null - commonTestHelper.waitWithLatch { - firstChild = aliceSession.roomService().createRoom(CreateRoomParams().apply { - this.name = "FirstRoom" - this.topic = "Description of first room" - this.preset = CreateRoomPreset.PRESET_PUBLIC_CHAT - }) - it.countDown() - } + val firstChild: String = aliceSession.roomService().createRoom(CreateRoomParams().apply { + this.name = "FirstRoom" + this.topic = "Description of first room" + this.preset = CreateRoomPreset.PRESET_PUBLIC_CHAT + }) - commonTestHelper.waitWithLatch { - syncedSpace?.addChildren(firstChild!!, listOf(aliceSession.sessionParams.homeServerHost ?: ""), "a", suggested = true) - it.countDown() - } + syncedSpace?.addChildren(firstChild, listOf(aliceSession.sessionParams.homeServerHost ?: ""), "a", suggested = true) - var secondChild: String? = null - commonTestHelper.waitWithLatch { - secondChild = aliceSession.roomService().createRoom(CreateRoomParams().apply { - this.name = "SecondRoom" - this.topic = "Description of second room" - this.preset = CreateRoomPreset.PRESET_PUBLIC_CHAT - }) - it.countDown() - } + val secondChild = aliceSession.roomService().createRoom(CreateRoomParams().apply { + this.name = "SecondRoom" + this.topic = "Description of second room" + this.preset = CreateRoomPreset.PRESET_PUBLIC_CHAT + }) - commonTestHelper.waitWithLatch { - syncedSpace?.addChildren(secondChild!!, listOf(aliceSession.sessionParams.homeServerHost ?: ""), "b", suggested = true) - it.countDown() - } + syncedSpace?.addChildren(secondChild, listOf(aliceSession.sessionParams.homeServerHost ?: ""), "b", suggested = true) // Try to join from bob, it's a public space no need to invite - var joinResult: JoinSpaceResult? = null - commonTestHelper.waitWithLatch { - joinResult = bobSession.spaceService().joinSpace(spaceId) - // wait a bit to let the summary update it self :/ - it.countDown() - } + val joinResult = bobSession.spaceService().joinSpace(spaceId) assertEquals(JoinSpaceResult.Success, joinResult) From aff82a611aa97f3629cd345653f16afce1308b6b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:14:04 +0100 Subject: [PATCH 38/56] converting space hierarchy tests to suspends --- .../sdk/session/space/SpaceHierarchyTest.kt | 449 +++++++----------- 1 file changed, 169 insertions(+), 280 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt index 81d47cfc60c..f88ab449884 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt @@ -17,8 +17,6 @@ package org.matrix.android.sdk.session.space import android.util.Log -import androidx.lifecycle.Observer -import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.FixMethodOrder @@ -39,62 +37,50 @@ import org.matrix.android.sdk.api.session.getRoomSummary import org.matrix.android.sdk.api.session.room.getStateEvent import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesAllowEntry -import org.matrix.android.sdk.api.session.room.model.RoomSummary import org.matrix.android.sdk.api.session.room.model.RoomType import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.model.create.RestrictedRoomPreset import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper import org.matrix.android.sdk.api.session.room.powerlevels.Role import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams -import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams +import org.matrix.android.sdk.common.first +import org.matrix.android.sdk.common.onMain +import org.matrix.android.sdk.common.waitFor @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) class SpaceHierarchyTest : InstrumentedTest { @Test - fun createCanonicalChildRelation() = runSessionTest(context()) { commonTestHelper -> + fun createCanonicalChildRelation() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount("John", SessionTestParams(true)) + val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) val spaceName = "My Space" val topic = "A public space for test" - var spaceId = "" - commonTestHelper.runBlockingTest { - spaceId = session.spaceService().createSpace(spaceName, topic, null, true) - } + val spaceId = session.spaceService().createSpace(spaceName, topic, null, true) val syncedSpace = session.spaceService().getSpace(spaceId) - var roomId = "" - commonTestHelper.runBlockingTest { - roomId = session.roomService().createRoom(CreateRoomParams().apply { name = "General" }) - } + val roomId = session.roomService().createRoom(CreateRoomParams().apply { name = "General" }) val viaServers = listOf(session.sessionParams.homeServerHost ?: "") - commonTestHelper.runBlockingTest { - syncedSpace!!.addChildren(roomId, viaServers, null, true) - } + syncedSpace!!.addChildren(roomId, viaServers, null, true) - commonTestHelper.runBlockingTest { - session.spaceService().setSpaceParent(roomId, spaceId, true, viaServers) - } + session.spaceService().setSpaceParent(roomId, spaceId, true, viaServers) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val parents = session.getRoom(roomId)?.roomSummary()?.spaceParents - val canonicalParents = session.getRoom(roomId)?.roomSummary()?.spaceParents?.filter { it.canonical == true } - parents?.forEach { - Log.d("## TEST", "parent : $it") - } - parents?.size == 1 && - parents.first().roomSummary?.name == spaceName && - canonicalParents?.size == 1 && - canonicalParents.first().roomSummary?.name == spaceName + commonTestHelper.retryPeriodically { + val parents = session.getRoom(roomId)?.roomSummary()?.spaceParents + val canonicalParents = session.getRoom(roomId)?.roomSummary()?.spaceParents?.filter { it.canonical == true } + parents?.forEach { + Log.d("## TEST", "parent : $it") } + parents?.size == 1 && + parents.first().roomSummary?.name == spaceName && + canonicalParents?.size == 1 && + canonicalParents.first().roomSummary?.name == spaceName } } @@ -166,11 +152,10 @@ class SpaceHierarchyTest : InstrumentedTest { // } @Test - fun testFilteringBySpace() = runSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount("John", SessionTestParams(true)) + fun testFilteringBySpace() = runSuspendingSessionTest(context()) { commonTestHelper -> + val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( - commonTestHelper, session, "SpaceA", listOf( Triple("A1", true /*auto-join*/, true/*canonical*/), @@ -179,7 +164,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) /* val spaceBInfo = */ createPublicSpace( - commonTestHelper, session, "SpaceB", listOf( Triple("B1", true /*auto-join*/, true/*canonical*/), @@ -189,7 +173,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) val spaceCInfo = createPublicSpace( - commonTestHelper, session, "SpaceC", listOf( Triple("C1", true /*auto-join*/, true/*canonical*/), @@ -200,22 +183,12 @@ class SpaceHierarchyTest : InstrumentedTest { // add C as a subspace of A val spaceA = session.spaceService().getSpace(spaceAInfo.spaceId) val viaServers = listOf(session.sessionParams.homeServerHost ?: "") - commonTestHelper.runBlockingTest { - spaceA!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) - session.spaceService().setSpaceParent(spaceCInfo.spaceId, spaceAInfo.spaceId, true, viaServers) - } + spaceA!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) + session.spaceService().setSpaceParent(spaceCInfo.spaceId, spaceAInfo.spaceId, true, viaServers) // Create orphan rooms - - var orphan1 = "" - commonTestHelper.runBlockingTest { - orphan1 = session.roomService().createRoom(CreateRoomParams().apply { name = "O1" }) - } - - var orphan2 = "" - commonTestHelper.runBlockingTest { - orphan2 = session.roomService().createRoom(CreateRoomParams().apply { name = "O2" }) - } + val orphan1 = session.roomService().createRoom(CreateRoomParams().apply { name = "O1" }) + val orphan2 = session.roomService().createRoom(CreateRoomParams().apply { name = "O2" }) val allRooms = session.roomService().getRoomSummaries(roomSummaryQueryParams { excludeType = listOf(RoomType.SPACE) }) @@ -236,25 +209,24 @@ class SpaceHierarchyTest : InstrumentedTest { assertTrue("A1 should be a grand child of A", aChildren.any { it.name == "C2" }) // Add a non canonical child and check that it does not appear as orphan - commonTestHelper.runBlockingTest { - val a3 = session.roomService().createRoom(CreateRoomParams().apply { name = "A3" }) - spaceA!!.addChildren(a3, viaServers, null, false) - } + val a3 = session.roomService().createRoom(CreateRoomParams().apply { name = "A3" }) + spaceA.addChildren(a3, viaServers, null, false) + + val orphansUpdate = session.roomService().onMain { + getRoomSummariesLive(roomSummaryQueryParams { + spaceFilter = SpaceFilter.OrphanRooms + }) + }.first { it.size == 2 } - Thread.sleep(6_000) - val orphansUpdate = session.roomService().getRoomSummaries(roomSummaryQueryParams { - spaceFilter = SpaceFilter.OrphanRooms - }) assertEquals("Unexpected number of orphan rooms ${orphansUpdate.map { it.name }}", 2, orphansUpdate.size) } @Test @Ignore("This test will be ignored until it is fixed") - fun testBreakCycle() = runSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount("John", SessionTestParams(true)) + fun testBreakCycle() = runSuspendingSessionTest(context()) { commonTestHelper -> + val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( - commonTestHelper, session, "SpaceA", listOf( Triple("A1", true /*auto-join*/, true/*canonical*/), @@ -263,7 +235,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) val spaceCInfo = createPublicSpace( - commonTestHelper, session, "SpaceC", listOf( Triple("C1", true /*auto-join*/, true/*canonical*/), @@ -274,16 +245,12 @@ class SpaceHierarchyTest : InstrumentedTest { // add C as a subspace of A val spaceA = session.spaceService().getSpace(spaceAInfo.spaceId) val viaServers = listOf(session.sessionParams.homeServerHost ?: "") - commonTestHelper.runBlockingTest { - spaceA!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) - session.spaceService().setSpaceParent(spaceCInfo.spaceId, spaceAInfo.spaceId, true, viaServers) - } + spaceA!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) + session.spaceService().setSpaceParent(spaceCInfo.spaceId, spaceAInfo.spaceId, true, viaServers) // add back A as subspace of C - commonTestHelper.runBlockingTest { - val spaceC = session.spaceService().getSpace(spaceCInfo.spaceId) - spaceC!!.addChildren(spaceAInfo.spaceId, viaServers, null, true) - } + val spaceC = session.spaceService().getSpace(spaceCInfo.spaceId) + spaceC!!.addChildren(spaceAInfo.spaceId, viaServers, null, true) // A -> C -> A @@ -298,10 +265,9 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun testLiveFlatChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount("John", SessionTestParams(true)) + val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( - commonTestHelper, session, "SpaceA", listOf( @@ -311,7 +277,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) val spaceBInfo = createPublicSpace( - commonTestHelper, session, "SpaceB", listOf( @@ -324,13 +289,10 @@ class SpaceHierarchyTest : InstrumentedTest { // add B as a subspace of A val spaceA = session.spaceService().getSpace(spaceAInfo.spaceId) val viaServers = listOf(session.sessionParams.homeServerHost ?: "") - commonTestHelper.runBlockingTest { - spaceA!!.addChildren(spaceBInfo.spaceId, viaServers, null, true) - session.spaceService().setSpaceParent(spaceBInfo.spaceId, spaceAInfo.spaceId, true, viaServers) - } + spaceA!!.addChildren(spaceBInfo.spaceId, viaServers, null, true) + session.spaceService().setSpaceParent(spaceBInfo.spaceId, spaceAInfo.spaceId, true, viaServers) val spaceCInfo = createPublicSpace( - commonTestHelper, session, "SpaceC", listOf( @@ -339,52 +301,39 @@ class SpaceHierarchyTest : InstrumentedTest { ) ) - commonTestHelper.waitWithLatch { latch -> - - val flatAChildren = session.roomService().getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId) - val childObserver = object : Observer> { - override fun onChanged(children: List?) { -// Log.d("## TEST", "Space A flat children update : ${children?.map { it.name }}") - System.out.println("## TEST | Space A flat children update : ${children?.map { it.name }}") - if (children?.any { it.name == "C1" } == true && children.any { it.name == "C2" }) { - // B1 has been added live! - latch.countDown() - flatAChildren.removeObserver(this) + val spaceB = session.spaceService().getSpace(spaceBInfo.spaceId) + waitFor( + continueWhen = { + session.roomService().onMain { getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId) }.first { children -> + println("## TEST | Space A flat children update : ${children.map { it.name }}") + children.any { it.name == "C1" } && children.any { it.name == "C2" } } + }, + action = { + // add C as subspace of B + spaceB!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) } - } - - flatAChildren.observeForever(childObserver) - - // add C as subspace of B - val spaceB = session.spaceService().getSpace(spaceBInfo.spaceId) - spaceB!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) - - // C1 and C2 should be in flatten child of A now - } + ) + // C1 and C2 should be in flatten child of A now // Test part one of the rooms val bRoomId = spaceBInfo.roomIds.first() - commonTestHelper.waitWithLatch { latch -> - val flatAChildren = session.roomService().getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId) - val childObserver = object : Observer> { - override fun onChanged(children: List?) { - System.out.println("## TEST | Space A flat children update : ${children?.map { it.name }}") - if (children?.any { it.roomId == bRoomId } == false) { - // B1 has been added live! - latch.countDown() - flatAChildren.removeObserver(this) + waitFor( + continueWhen = { + // The room should have disappear from flat children + session.roomService().onMain { getFlattenRoomSummaryChildrenOfLive(spaceAInfo.spaceId) }.first { children -> + println("## TEST | Space A flat children update : ${children.map { it.name }}") + !children.any { it.roomId == bRoomId } } + }, + action = { + // part from b room + session.roomService().leaveRoom(bRoomId) } - } + ) - // The room should have disapear from flat children - flatAChildren.observeForever(childObserver) - // part from b room - session.roomService().leaveRoom(bRoomId) - } commonTestHelper.signOutAndClose(session) } @@ -393,79 +342,67 @@ class SpaceHierarchyTest : InstrumentedTest { val roomIds: List ) - private fun createPublicSpace( - commonTestHelper: CommonTestHelper, + private suspend fun createPublicSpace( session: Session, spaceName: String, childInfo: List> /** Name, auto-join, canonical*/ ): TestSpaceCreationResult { - var spaceId = "" - var roomIds: List = emptyList() - commonTestHelper.runBlockingTest { - spaceId = session.spaceService().createSpace(spaceName, "Test Topic", null, true) - val syncedSpace = session.spaceService().getSpace(spaceId) - val viaServers = listOf(session.sessionParams.homeServerHost ?: "") - - roomIds = childInfo.map { entry -> - session.roomService().createRoom(CreateRoomParams().apply { name = entry.first }) - } - roomIds.forEachIndexed { index, roomId -> - syncedSpace!!.addChildren(roomId, viaServers, null, childInfo[index].second) - val canonical = childInfo[index].third - if (canonical != null) { - session.spaceService().setSpaceParent(roomId, spaceId, canonical, viaServers) - } + val spaceId = session.spaceService().createSpace(spaceName, "Test Topic", null, true) + val syncedSpace = session.spaceService().getSpace(spaceId) + val viaServers = listOf(session.sessionParams.homeServerHost ?: "") + + val roomIds = childInfo.map { entry -> + session.roomService().createRoom(CreateRoomParams().apply { name = entry.first }) + } + roomIds.forEachIndexed { index, roomId -> + syncedSpace!!.addChildren(roomId, viaServers, null, childInfo[index].second) + val canonical = childInfo[index].third + if (canonical != null) { + session.spaceService().setSpaceParent(roomId, spaceId, canonical, viaServers) } } return TestSpaceCreationResult(spaceId, roomIds) } - private fun createPrivateSpace( - commonTestHelper: CommonTestHelper, + private suspend fun createPrivateSpace( session: Session, spaceName: String, childInfo: List> /** Name, auto-join, canonical*/ ): TestSpaceCreationResult { - var spaceId = "" - var roomIds: List = emptyList() - commonTestHelper.runBlockingTest { - spaceId = session.spaceService().createSpace(spaceName, "My Private Space", null, false) - val syncedSpace = session.spaceService().getSpace(spaceId) - val viaServers = listOf(session.sessionParams.homeServerHost ?: "") - roomIds = - childInfo.map { entry -> - val homeServerCapabilities = session - .homeServerCapabilitiesService() - .getHomeServerCapabilities() - session.roomService().createRoom(CreateRoomParams().apply { - name = entry.first - this.featurePreset = RestrictedRoomPreset( - homeServerCapabilities, - listOf( - RoomJoinRulesAllowEntry.restrictedToRoom(spaceId) - ) - ) - }) - } - roomIds.forEachIndexed { index, roomId -> - syncedSpace!!.addChildren(roomId, viaServers, null, childInfo[index].second) - val canonical = childInfo[index].third - if (canonical != null) { - session.spaceService().setSpaceParent(roomId, spaceId, canonical, viaServers) - } + val spaceId = session.spaceService().createSpace(spaceName, "My Private Space", null, false) + val syncedSpace = session.spaceService().getSpace(spaceId) + val viaServers = listOf(session.sessionParams.homeServerHost ?: "") + val roomIds = childInfo.map { entry -> + val homeServerCapabilities = session + .homeServerCapabilitiesService() + .getHomeServerCapabilities() + session.roomService().createRoom(CreateRoomParams().apply { + name = entry.first + this.featurePreset = RestrictedRoomPreset( + homeServerCapabilities, + listOf( + RoomJoinRulesAllowEntry.restrictedToRoom(spaceId) + ) + ) + }) + } + roomIds.forEachIndexed { index, roomId -> + syncedSpace!!.addChildren(roomId, viaServers, null, childInfo[index].second) + val canonical = childInfo[index].third + if (canonical != null) { + session.spaceService().setSpaceParent(roomId, spaceId, canonical, viaServers) } } return TestSpaceCreationResult(spaceId, roomIds) } @Test - fun testRootSpaces() = runSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccount("John", SessionTestParams(true)) + fun testRootSpaces() = runSuspendingSessionTest(context()) { commonTestHelper -> + val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) /* val spaceAInfo = */ createPublicSpace( - commonTestHelper, session, "SpaceA", listOf( Triple("A1", true /*auto-join*/, true/*canonical*/), @@ -474,7 +411,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) val spaceBInfo = createPublicSpace( - commonTestHelper, session, "SpaceB", listOf( Triple("B1", true /*auto-join*/, true/*canonical*/), @@ -484,7 +420,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) val spaceCInfo = createPublicSpace( - commonTestHelper, session, "SpaceC", listOf( Triple("C1", true /*auto-join*/, true/*canonical*/), @@ -495,10 +430,8 @@ class SpaceHierarchyTest : InstrumentedTest { val viaServers = listOf(session.sessionParams.homeServerHost ?: "") // add C as subspace of B - runBlocking { - val spaceB = session.spaceService().getSpace(spaceBInfo.spaceId) - spaceB!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) - } + val spaceB = session.spaceService().getSpace(spaceBInfo.spaceId) + spaceB!!.addChildren(spaceCInfo.spaceId, viaServers, null, true) // Thread.sleep(4_000) // + A @@ -508,21 +441,18 @@ class SpaceHierarchyTest : InstrumentedTest { // + C // + c1, c2 - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val rootSpaces = commonTestHelper.runBlockingTest { session.spaceService().getRootSpaceSummaries() } - rootSpaces.size == 2 - } + commonTestHelper.retryPeriodically { + val rootSpaces = commonTestHelper.runBlockingTest { session.spaceService().getRootSpaceSummaries() } + rootSpaces.size == 2 } } @Test - fun testParentRelation() = runSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccount("Alice", SessionTestParams(true)) - val bobSession = commonTestHelper.createAccount("Bib", SessionTestParams(true)) + fun testParentRelation() = runSuspendingSessionTest(context()) { commonTestHelper -> + val aliceSession = commonTestHelper.createAccountSuspending("Alice", SessionTestParams(true)) + val bobSession = commonTestHelper.createAccountSuspending("Bib", SessionTestParams(true)) val spaceAInfo = createPrivateSpace( - commonTestHelper, aliceSession, "Private Space A", listOf( Triple("General", true /*suggested*/, true/*canonical*/), @@ -530,94 +460,66 @@ class SpaceHierarchyTest : InstrumentedTest { ) ) - commonTestHelper.runBlockingTest { - aliceSession.getRoom(spaceAInfo.spaceId)!!.membershipService().invite(bobSession.myUserId, null) - } + aliceSession.getRoom(spaceAInfo.spaceId)!!.membershipService().invite(bobSession.myUserId, null) - commonTestHelper.runBlockingTest { - bobSession.roomService().joinRoom(spaceAInfo.spaceId, null, emptyList()) - } + bobSession.roomService().joinRoom(spaceAInfo.spaceId, null, emptyList()) - var bobRoomId = "" - commonTestHelper.runBlockingTest { - bobRoomId = bobSession.roomService().createRoom(CreateRoomParams().apply { name = "A Bob Room" }) - bobSession.getRoom(bobRoomId)!!.membershipService().invite(aliceSession.myUserId) - } + val bobRoomId = bobSession.roomService().createRoom(CreateRoomParams().apply { name = "A Bob Room" }) + bobSession.getRoom(bobRoomId)!!.membershipService().invite(aliceSession.myUserId) - commonTestHelper.runBlockingTest { - aliceSession.roomService().joinRoom(bobRoomId) - } + aliceSession.roomService().joinRoom(bobRoomId) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession.getRoomSummary(bobRoomId)?.membership?.isActive() == true - } + commonTestHelper.retryPeriodically { + aliceSession.getRoomSummary(bobRoomId)?.membership?.isActive() == true } - commonTestHelper.runBlockingTest { - bobSession.spaceService().setSpaceParent(bobRoomId, spaceAInfo.spaceId, false, listOf(bobSession.sessionParams.homeServerHost ?: "")) - } + bobSession.spaceService().setSpaceParent(bobRoomId, spaceAInfo.spaceId, false, listOf(bobSession.sessionParams.homeServerHost ?: "")) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val stateEvent = aliceSession.getRoom(bobRoomId)!!.getStateEvent(EventType.STATE_SPACE_PARENT, QueryStringValue.Equals(spaceAInfo.spaceId)) - stateEvent != null - } + commonTestHelper.retryPeriodically { + val stateEvent = aliceSession.getRoom(bobRoomId)!!.getStateEvent(EventType.STATE_SPACE_PARENT, QueryStringValue.Equals(spaceAInfo.spaceId)) + stateEvent != null } // This should be an invalid space parent relation, because no opposite child and bob is not admin of the space - commonTestHelper.runBlockingTest { - // we can see the state event - // but it is not valid and room is not in hierarchy - assertTrue("Bob Room should not be listed as a child of the space", aliceSession.getRoomSummary(bobRoomId)?.flattenParentIds?.isEmpty() == true) - } + // we can see the state event + // but it is not valid and room is not in hierarchy + assertTrue("Bob Room should not be listed as a child of the space", aliceSession.getRoomSummary(bobRoomId)?.flattenParentIds?.isEmpty() == true) // Let's now try to make alice admin of the room - commonTestHelper.waitWithLatch { - val room = bobSession.getRoom(bobRoomId)!! - val currentPLContent = room - .getStateEvent(EventType.STATE_ROOM_POWER_LEVELS, QueryStringValue.IsEmpty) - ?.content - .toModel() + val room = bobSession.getRoom(bobRoomId)!! + val currentPLContent = room + .getStateEvent(EventType.STATE_ROOM_POWER_LEVELS, QueryStringValue.IsEmpty) + ?.content + .toModel() - val newPowerLevelsContent = currentPLContent - ?.setUserPowerLevel(aliceSession.myUserId, Role.Admin.value) - ?.toContent() + val newPowerLevelsContent = currentPLContent + ?.setUserPowerLevel(aliceSession.myUserId, Role.Admin.value) + ?.toContent() - room.stateService().sendStateEvent(EventType.STATE_ROOM_POWER_LEVELS, stateKey = "", newPowerLevelsContent!!) - it.countDown() - } + room.stateService().sendStateEvent(EventType.STATE_ROOM_POWER_LEVELS, stateKey = "", newPowerLevelsContent!!) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val powerLevelsHelper = aliceSession.getRoom(bobRoomId)!! - .getStateEvent(EventType.STATE_ROOM_POWER_LEVELS, QueryStringValue.IsEmpty) - ?.content - ?.toModel() - ?.let { PowerLevelsHelper(it) } - powerLevelsHelper!!.isUserAllowedToSend(aliceSession.myUserId, true, EventType.STATE_SPACE_PARENT) - } + commonTestHelper.retryPeriodically { + val powerLevelsHelper = aliceSession.getRoom(bobRoomId)!! + .getStateEvent(EventType.STATE_ROOM_POWER_LEVELS, QueryStringValue.IsEmpty) + ?.content + ?.toModel() + ?.let { PowerLevelsHelper(it) } + powerLevelsHelper!!.isUserAllowedToSend(aliceSession.myUserId, true, EventType.STATE_SPACE_PARENT) } - commonTestHelper.waitWithLatch { - aliceSession.spaceService().setSpaceParent(bobRoomId, spaceAInfo.spaceId, false, listOf(bobSession.sessionParams.homeServerHost ?: "")) - it.countDown() - } + aliceSession.spaceService().setSpaceParent(bobRoomId, spaceAInfo.spaceId, false, listOf(bobSession.sessionParams.homeServerHost ?: "")) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - bobSession.getRoomSummary(bobRoomId)?.flattenParentIds?.contains(spaceAInfo.spaceId) == true - } + commonTestHelper.retryPeriodically { + bobSession.getRoomSummary(bobRoomId)?.flattenParentIds?.contains(spaceAInfo.spaceId) == true } } @Test - fun testDirectParentNames() = runSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccount("Alice", SessionTestParams(true)) + fun testDirectParentNames() = runSuspendingSessionTest(context()) { commonTestHelper -> + val aliceSession = commonTestHelper.createAccountSuspending("Alice", SessionTestParams(true)) val spaceAInfo = createPublicSpace( - commonTestHelper, aliceSession, "SpaceA", listOf( Triple("A1", true /*auto-join*/, true/*canonical*/), @@ -626,7 +528,6 @@ class SpaceHierarchyTest : InstrumentedTest { ) val spaceBInfo = createPublicSpace( - commonTestHelper, aliceSession, "SpaceB", listOf( Triple("B1", true /*auto-join*/, true/*canonical*/), @@ -642,51 +543,39 @@ class SpaceHierarchyTest : InstrumentedTest { val spaceA = aliceSession.spaceService().getSpace(spaceAInfo.spaceId) val spaceB = aliceSession.spaceService().getSpace(spaceBInfo.spaceId) - commonTestHelper.runBlockingTest { - spaceA!!.addChildren(B1roomId, viaServers, null, true) - } + spaceA!!.addChildren(B1roomId, viaServers, null, true) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val roomSummary = aliceSession.getRoomSummary(B1roomId) - roomSummary != null && - roomSummary.directParentNames.size == 2 && - roomSummary.directParentNames.contains(spaceA!!.spaceSummary()!!.name) && - roomSummary.directParentNames.contains(spaceB!!.spaceSummary()!!.name) - } + commonTestHelper.retryPeriodically { + val roomSummary = aliceSession.getRoomSummary(B1roomId) + roomSummary != null && + roomSummary.directParentNames.size == 2 && + roomSummary.directParentNames.contains(spaceA.spaceSummary()!!.name) && + roomSummary.directParentNames.contains(spaceB!!.spaceSummary()!!.name) } - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val roomSummary = aliceSession.getRoomSummary(spaceAInfo.roomIds.first()) - roomSummary != null && - roomSummary.directParentNames.size == 1 && - roomSummary.directParentNames.contains(spaceA!!.spaceSummary()!!.name) - } + commonTestHelper.retryPeriodically { + val roomSummary = aliceSession.getRoomSummary(spaceAInfo.roomIds.first()) + roomSummary != null && + roomSummary.directParentNames.size == 1 && + roomSummary.directParentNames.contains(spaceA.spaceSummary()!!.name) } val newAName = "FooBar" - commonTestHelper.runBlockingTest { - spaceA!!.asRoom().stateService().updateName(newAName) - } + spaceA.asRoom().stateService().updateName(newAName) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val roomSummary = aliceSession.getRoomSummary(B1roomId) - roomSummary != null && - roomSummary.directParentNames.size == 2 && - roomSummary.directParentNames.contains(newAName) && - roomSummary.directParentNames.contains(spaceB!!.spaceSummary()!!.name) - } + commonTestHelper.retryPeriodically { + val roomSummary = aliceSession.getRoomSummary(B1roomId) + roomSummary != null && + roomSummary.directParentNames.size == 2 && + roomSummary.directParentNames.contains(newAName) && + roomSummary.directParentNames.contains(spaceB!!.spaceSummary()!!.name) } - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val roomSummary = aliceSession.getRoomSummary(spaceAInfo.roomIds.first()) - roomSummary != null && - roomSummary.directParentNames.size == 1 && - roomSummary.directParentNames.contains(newAName) - } + commonTestHelper.retryPeriodically { + val roomSummary = aliceSession.getRoomSummary(spaceAInfo.roomIds.first()) + roomSummary != null && + roomSummary.directParentNames.size == 1 && + roomSummary.directParentNames.contains(newAName) } } } From 75becaf632d1d9fae1049f005bd673185928df84 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:21:20 +0100 Subject: [PATCH 39/56] making all test createAccount usages suspending --- .../sdk/account/AccountCreationTest.kt | 4 +- .../android/sdk/account/ChangePasswordTest.kt | 2 +- .../sdk/account/DeactivateAccountTest.kt | 4 +- .../sdk/api/network/ApiInterceptorTest.kt | 2 +- .../android/sdk/common/CommonTestHelper.kt | 105 +----------------- .../android/sdk/common/CryptoTestHelper.kt | 18 ++- .../internal/crypto/E2EShareKeysConfigTest.kt | 14 +-- .../sdk/internal/crypto/E2eeSanityTests.kt | 10 +- .../crypto/gossiping/WithHeldTests.kt | 4 +- .../crypto/keysbackup/KeysBackupTest.kt | 6 +- .../sdk/internal/crypto/ssss/QuadSTests.kt | 9 +- .../timeline/TimelineWithManyMembersTest.kt | 3 +- .../sdk/session/space/SpaceCreationTest.kt | 11 +- .../sdk/session/space/SpaceHierarchyTest.kt | 16 +-- 14 files changed, 55 insertions(+), 153 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt index f61bc5aa1ae..d2b41530fd0 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt @@ -36,13 +36,13 @@ class AccountCreationTest : InstrumentedTest { @Test fun createAccountTest() = runSuspendingSessionTest(context()) { commonTestHelper -> - commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) } @Test @Ignore("This test will be ignored until it is fixed") fun createAccountAndLoginAgainTest() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) // Log again to the same account commonTestHelper.logIntoAccount(session.myUserId, SessionTestParams(withInitialSync = true)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt index 053f67b4f69..7d56d0c626f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt @@ -40,7 +40,7 @@ class ChangePasswordTest : InstrumentedTest { @Test fun changePasswordTest() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) + val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) // Change password session.accountService().changePassword(TestConstants.PASSWORD, NEW_PASSWORD) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt index 0b21f85742d..26dae039c43 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt @@ -29,7 +29,7 @@ import org.matrix.android.sdk.api.auth.UserPasswordAuth import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse import org.matrix.android.sdk.api.failure.Failure import org.matrix.android.sdk.api.failure.MatrixError -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import kotlin.coroutines.Continuation @@ -40,7 +40,7 @@ import kotlin.coroutines.resume class DeactivateAccountTest : InstrumentedTest { @Test - fun deactivateAccountTest() = runSessionTest(context(), false /* session will be deactivated */) { commonTestHelper -> + fun deactivateAccountTest() = runSuspendingSessionTest(context(), false /* session will be deactivated */) { commonTestHelper -> val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) // Deactivate the account diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt index c5148a8078b..d2c6b388be6 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt @@ -45,7 +45,7 @@ class ApiInterceptorTest : InstrumentedTest { commonTestHelper.matrix.registerApiInterceptorListener(ApiPath.REGISTER, listener) - val session = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) commonTestHelper.signOutAndClose(session) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index f30c367ee75..ef3ad75cb11 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -149,14 +149,10 @@ class CommonTestHelper internal constructor(context: Context) { matrix = _matrix!! } - fun createAccount(userNamePrefix: String, testParams: SessionTestParams): Session { + suspend fun createAccount(userNamePrefix: String, testParams: SessionTestParams): Session { return createAccount(userNamePrefix, TestConstants.PASSWORD, testParams) } - suspend fun createAccountSuspending(userNamePrefix: String, testParams: SessionTestParams): Session { - return createAccountSuspending(userNamePrefix, TestConstants.PASSWORD, testParams) - } - suspend fun logIntoAccount(userId: String, testParams: SessionTestParams): Session { return logIntoAccount(userId, TestConstants.PASSWORD, testParams) } @@ -179,30 +175,7 @@ class CommonTestHelper internal constructor(context: Context) { .build() } - /** - * This methods init the event stream and check for initial sync - * - * @param session the session to sync - */ - fun syncSession(session: Session, timeout: Long = TestConstants.timeOutMillis * 10) { - val lock = CountDownLatch(1) - coroutineScope.launch { - session.syncService().startSync(true) - val syncLiveData = session.syncService().getSyncStateLive() - val syncObserver = object : Observer { - override fun onChanged(t: SyncState?) { - if (session.syncService().hasAlreadySynced()) { - lock.countDown() - syncLiveData.removeObserver(this) - } - } - } - syncLiveData.observeForever(syncObserver) - } - await(lock, timeout) - } - - suspend fun syncSessionSuspending(session: Session, timeout: Long = TestConstants.timeOutMillis * 10) { + suspend fun syncSession(session: Session, timeout: Long = TestConstants.timeOutMillis * 10) { session.syncService().startSync(true) val syncLiveData = session.syncService().getSyncStateLive() syncLiveData.first(timeout) { session.syncService().hasAlreadySynced() } @@ -361,15 +334,7 @@ class CommonTestHelper internal constructor(context: Context) { // PRIVATE METHODS ***************************************************************************** - /** - * Creates a unique account - * - * @param userNamePrefix the user name prefix - * @param password the password - * @param testParams test params about the session - * @return the session associated with the newly created account - */ - private fun createAccount( + private suspend fun createAccount( userNamePrefix: String, password: String, testParams: SessionTestParams @@ -387,24 +352,6 @@ class CommonTestHelper internal constructor(context: Context) { } } - private suspend fun createAccountSuspending( - userNamePrefix: String, - password: String, - testParams: SessionTestParams - ): Session { - val session = createAccountAndSyncSuspending( - userNamePrefix + "_" + accountNumber++ + "_" + UUID.randomUUID(), - password, - testParams - ) - assertNotNull(session) - return session.also { - // most of the test was created pre-MSC3061 so ensure compatibility - it.cryptoService().enableShareKeyOnInvite(false) - trackedSessions.add(session) - } - } - suspend fun logIntoAccount( userId: String, password: String, @@ -417,47 +364,7 @@ class CommonTestHelper internal constructor(context: Context) { } } - /** - * Create an account and a dedicated session - * - * @param userName the account username - * @param password the password - * @param sessionTestParams parameters for the test - */ - private fun createAccountAndSync( - userName: String, - password: String, - sessionTestParams: SessionTestParams - ): Session { - val hs = createHomeServerConfig() - - runBlockingTest { - matrix.authenticationService.getLoginFlow(hs) - } - - runBlockingTest(timeout = 60_000) { - matrix.authenticationService - .getRegistrationWizard() - .createAccount(userName, password, null) - } - - // Perform dummy step - val registrationResult = runBlockingTest(timeout = 60_000) { - matrix.authenticationService - .getRegistrationWizard() - .dummy() - } - - assertTrue(registrationResult is RegistrationResult.Success) - val session = (registrationResult as RegistrationResult.Success).session - session.open() - if (sessionTestParams.withInitialSync) { - syncSession(session, 120_000) - } - return session - } - - private suspend fun createAccountAndSyncSuspending( + private suspend fun createAccountAndSync( userName: String, password: String, sessionTestParams: SessionTestParams @@ -485,7 +392,7 @@ class CommonTestHelper internal constructor(context: Context) { val session = (registrationResult as RegistrationResult.Success).session session.open() if (sessionTestParams.withInitialSync) { - syncSessionSuspending(session, 120_000) + syncSession(session, 120_000) } return session } @@ -500,7 +407,7 @@ class CommonTestHelper internal constructor(context: Context) { .login(userName, password, "myDevice") session.open() if (sessionTestParams.withInitialSync) { - syncSessionSuspending(session) + syncSession(session) } return session diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 3e577b54eae..7d472f6f32f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -68,7 +68,7 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { * @return alice session */ suspend fun doE2ETestWithAliceInARoom(encryptedRoom: Boolean = true, roomHistoryVisibility: RoomHistoryVisibility? = null): CryptoTestData { - val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, defaultSessionParams) + val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { historyVisibility = roomHistoryVisibility @@ -94,7 +94,7 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { val aliceRoom = aliceSession.getRoom(aliceRoomId)!! - val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, defaultSessionParams) + val bobSession = testHelper.createAccount(TestConstants.USER_BOB, defaultSessionParams) waitFor( continueWhen = { bobSession.roomService().onMain { getRoomSummariesLive(roomSummaryQueryParams { }) }.first { it.isNotEmpty() } }, @@ -369,25 +369,21 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } } - fun doE2ETestWithManyMembers(numberOfMembers: Int): CryptoTestData { + suspend fun doE2ETestWithManyMembers(numberOfMembers: Int): CryptoTestData { val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) aliceSession.cryptoService().setWarnOnUnknownDevices(false) - val roomId = testHelper.runBlockingTest { - aliceSession.roomService().createRoom(CreateRoomParams().apply { name = "MyRoom" }) - } + val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { name = "MyRoom" }) val room = aliceSession.getRoom(roomId)!! - testHelper.runBlockingTest { - room.roomCryptoService().enableEncryption() - } + room.roomCryptoService().enableEncryption() val sessions = mutableListOf(aliceSession) for (index in 1 until numberOfMembers) { val session = testHelper.createAccount("User_$index", defaultSessionParams) - testHelper.runBlockingTest(timeout = 600_000) { room.membershipService().invite(session.myUserId, null) } + room.membershipService().invite(session.myUserId, null) println("TEST -> " + session.myUserId + " invited") - testHelper.runBlockingTest { session.roomService().joinRoom(room.roomId, null, emptyList()) } + session.roomService().joinRoom(room.roomId, null, emptyList()) println("TEST -> " + session.myUserId + " joined") sessions.add(session) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt index 5776f6e58e5..e0fd1c283fb 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt @@ -48,13 +48,13 @@ class E2EShareKeysConfigTest : InstrumentedTest { @Test fun msc3061ShouldBeDisabledByDefault() = runSuspendingCryptoTest(context()) { _, commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) + val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) Assert.assertFalse("MSC3061 is lab and should be disabled by default", aliceSession.cryptoService().isShareKeysOnInviteEnabled()) } @Test fun ensureKeysAreNotSharedIfOptionDisabled() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) aliceSession.cryptoService().enableShareKeyOnInvite(false) val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { historyVisibility = RoomHistoryVisibility.SHARED @@ -73,7 +73,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { val withSession2 = commonTestHelper.sendTextMessageSuspending(roomAlice, "World", 1) // Create bob account - val bobSession = commonTestHelper.createAccountSuspending(TestConstants.USER_BOB, SessionTestParams(withInitialSync = true)) + val bobSession = commonTestHelper.createAccount(TestConstants.USER_BOB, SessionTestParams(withInitialSync = true)) // Let alice invite bob roomAlice.membershipService().invite(bobSession.myUserId) @@ -104,7 +104,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { ) // Invite a new user - val samSession = commonTestHelper.createAccountSuspending(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) + val samSession = commonTestHelper.createAccount(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) // Let alice invite sam roomAlice.membershipService().invite(samSession.myUserId) @@ -183,7 +183,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Now let bob invite Sam // Invite a new user - val samSession = commonTestHelper.createAccountSuspending(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) + val samSession = commonTestHelper.createAccount(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) // Let bob invite sam bobSession.getRoom(testData.roomId)!!.membershipService().invite(samSession.myUserId) @@ -196,7 +196,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { @Test fun testBackupFlagIsCorrect() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) + val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) aliceSession.cryptoService().enableShareKeyOnInvite(false) val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { historyVisibility = RoomHistoryVisibility.SHARED @@ -255,7 +255,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // Now let's invite sam // Invite a new user - val samSession = commonTestHelper.createAccountSuspending(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) + val samSession = commonTestHelper.createAccount(TestConstants.USER_SAM, SessionTestParams(withInitialSync = true)) // Let alice invite sam newAliceSession.getRoom(roomId)!!.membershipService().invite(samSession.myUserId) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index d1d34faa562..742c02c9f4a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -59,8 +59,8 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.mustFail import kotlin.coroutines.resume @@ -95,7 +95,7 @@ class E2eeSanityTests : InstrumentedTest { // add some more users and invite them val otherAccounts = listOf("benoit", "valere", "ganfra") // , "adam", "manu") .map { - testHelper.createAccountSuspending(it, SessionTestParams(true)).also { + testHelper.createAccount(it, SessionTestParams(true)).also { it.cryptoService().enableKeyGossiping(false) } } @@ -137,7 +137,7 @@ class E2eeSanityTests : InstrumentedTest { // Add a new user to the room, and check that he can't decrypt val newAccount = listOf("adam") // , "adam", "manu") .map { - testHelper.createAccountSuspending(it, SessionTestParams(true)) + testHelper.createAccount(it, SessionTestParams(true)) } newAccount.forEach { @@ -186,7 +186,7 @@ class E2eeSanityTests : InstrumentedTest { } @Test - fun testKeyGossipingIsEnabledByDefault() = runSessionTest(context()) { testHelper -> + fun testKeyGossipingIsEnabledByDefault() = runSuspendingSessionTest(context()) { testHelper -> val session = testHelper.createAccount("alice", SessionTestParams(true)) Assert.assertTrue("Key gossiping should be enabled by default", session.cryptoService().isKeyGossipingEnabled()) } @@ -537,7 +537,7 @@ class E2eeSanityTests : InstrumentedTest { @Test fun testASelfInteractiveVerificationAndGossip() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> - val aliceSession = testHelper.createAccountSuspending("alice", SessionTestParams(true)) + val aliceSession = testHelper.createAccount("alice", SessionTestParams(true)) cryptoTestHelper.bootstrapSecurity(aliceSession) // now let's create a new login from alice diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index a1fde267787..6ceb5bd898a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -57,8 +57,8 @@ class WithHeldTests : InstrumentedTest { // ARRANGE // ============================= - val aliceSession = testHelper.createAccountSuspending(TestConstants.USER_ALICE, SessionTestParams(true)) - val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, SessionTestParams(true)) + val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) + val bobSession = testHelper.createAccount(TestConstants.USER_BOB, SessionTestParams(true)) // Initialize cross signing on both cryptoTestHelper.initializeCrossSigning(aliceSession) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index 44a50934090..ee5450c0b6d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -44,8 +44,8 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreation import org.matrix.android.sdk.api.session.crypto.keysbackup.toKeysVersionResult import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult import org.matrix.android.sdk.api.session.getRoom -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.common.TestMatrixCallback @@ -104,7 +104,7 @@ class KeysBackupTest : InstrumentedTest { * Check that prepareKeysBackupVersionWithPassword returns valid data */ @Test - fun prepareKeysBackupVersionTest() = runSessionTest(context()) { testHelper -> + fun prepareKeysBackupVersionTest() = runSuspendingSessionTest(context()) { testHelper -> val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) @@ -133,7 +133,7 @@ class KeysBackupTest : InstrumentedTest { */ @Test fun createKeysBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> - val bobSession = testHelper.createAccountSuspending(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) + val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) cryptoTestHelper.initializeCrossSigning(bobSession) val keysBackup = bobSession.cryptoService().keysBackupService() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt index 66afffd5628..4bd022b35f9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt @@ -40,7 +40,6 @@ import org.matrix.android.sdk.api.session.securestorage.SsssKeyCreationInfo import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.toBase64NoPadding import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -109,7 +108,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_StoreSecret() = runSessionTest(context()) { testHelper -> + fun test_StoreSecret() = runSuspendingSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId = "My.Key" @@ -152,7 +151,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_SetDefaultLocalEcho() = runSessionTest(context()) { testHelper -> + fun test_SetDefaultLocalEcho() = runSuspendingSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) @@ -171,7 +170,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_StoreSecretWithMultipleKey() = runSessionTest(context()) { testHelper -> + fun test_StoreSecretWithMultipleKey() = runSuspendingSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId1 = "Key.1" @@ -220,7 +219,7 @@ class QuadSTests : InstrumentedTest { @Test @Ignore("Test is working locally, not in GitHub actions") - fun test_GetSecretWithBadPassphrase() = runSessionTest(context()) { testHelper -> + fun test_GetSecretWithBadPassphrase() = runSuspendingSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId1 = "Key.1" diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt index 27ea0e1c3c0..d2512ec559a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt @@ -31,6 +31,7 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import java.util.concurrent.CountDownLatch /** !! Not working with the new timeline @@ -51,7 +52,7 @@ class TimelineWithManyMembersTest : InstrumentedTest { */ @Test - fun everyone_should_decrypt_message_in_a_crowded_room() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun everyone_should_decrypt_message_in_a_crowded_room() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithManyMembers(NUMBER_OF_MEMBERS) val sessionForFirstMember = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt index 0b1fc91ce2e..553f1b73ab9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt @@ -42,7 +42,6 @@ import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.model.create.CreateRoomPreset import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent import org.matrix.android.sdk.api.session.space.JoinSpaceResult -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest import org.matrix.android.sdk.common.SessionTestParams @@ -53,7 +52,7 @@ class SpaceCreationTest : InstrumentedTest { @Test fun createSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending("Hubble", SessionTestParams(true)) + val session = commonTestHelper.createAccount("Hubble", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" val spaceId = session.spaceService().createSpace(roomName, topic, null, true) @@ -105,8 +104,8 @@ class SpaceCreationTest : InstrumentedTest { @Ignore fun testJoinSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending("alice", SessionTestParams(true)) - val bobSession = commonTestHelper.createAccountSuspending("bob", SessionTestParams(true)) + val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) + val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" @@ -130,8 +129,8 @@ class SpaceCreationTest : InstrumentedTest { @Test fun testSimplePublicSpaceWithChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending("alice", SessionTestParams(true)) - val bobSession = commonTestHelper.createAccountSuspending("bob", SessionTestParams(true)) + val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) + val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt index f88ab449884..f977793cabb 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt @@ -56,7 +56,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun createCanonicalChildRelation() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) + val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceName = "My Space" val topic = "A public space for test" val spaceId = session.spaceService().createSpace(spaceName, topic, null, true) @@ -153,7 +153,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun testFilteringBySpace() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) + val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( session, "SpaceA", @@ -224,7 +224,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") fun testBreakCycle() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) + val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( session, "SpaceA", @@ -265,7 +265,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun testLiveFlatChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) + val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( session, @@ -400,7 +400,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun testRootSpaces() = runSuspendingSessionTest(context()) { commonTestHelper -> - val session = commonTestHelper.createAccountSuspending("John", SessionTestParams(true)) + val session = commonTestHelper.createAccount("John", SessionTestParams(true)) /* val spaceAInfo = */ createPublicSpace( session, "SpaceA", @@ -449,8 +449,8 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun testParentRelation() = runSuspendingSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending("Alice", SessionTestParams(true)) - val bobSession = commonTestHelper.createAccountSuspending("Bib", SessionTestParams(true)) + val aliceSession = commonTestHelper.createAccount("Alice", SessionTestParams(true)) + val bobSession = commonTestHelper.createAccount("Bib", SessionTestParams(true)) val spaceAInfo = createPrivateSpace( aliceSession, "Private Space A", @@ -517,7 +517,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test fun testDirectParentNames() = runSuspendingSessionTest(context()) { commonTestHelper -> - val aliceSession = commonTestHelper.createAccountSuspending("Alice", SessionTestParams(true)) + val aliceSession = commonTestHelper.createAccount("Alice", SessionTestParams(true)) val spaceAInfo = createPublicSpace( aliceSession, "SpaceA", From 9d3fdda3da6db3439050b6f60c6116886219b3d4 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:27:32 +0100 Subject: [PATCH 40/56] making all runCryptoTest suspending --- .../android/sdk/common/CommonTestHelper.kt | 28 ++----------------- .../crypto/DecryptRedactedEventTest.kt | 1 - .../crypto/replayattack/ReplayAttackTest.kt | 1 - .../internal/crypto/verification/SASTest.kt | 21 +++++++------- .../room/threads/ThreadMessagingTest.kt | 9 +++--- .../room/timeline/PollAggregationTest.kt | 1 - .../timeline/TimelineForwardPaginationTest.kt | 6 ++-- .../TimelineSimpleBackPaginationTest.kt | 1 - .../timeline/TimelineWithManyMembersTest.kt | 1 - 9 files changed, 19 insertions(+), 50 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index ef3ad75cb11..ef3fdaa6c9d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -69,16 +69,6 @@ import kotlin.coroutines.suspendCoroutine class CommonTestHelper internal constructor(context: Context) { companion object { - internal fun runSessionTest(context: Context, autoSignoutOnClose: Boolean = true, block: (CommonTestHelper) -> Unit) { - val testHelper = CommonTestHelper(context) - return try { - block(testHelper) - } finally { - if (autoSignoutOnClose) { - testHelper.cleanUpOpenedSessions() - } - } - } @OptIn(ExperimentalCoroutinesApi::class) internal fun runSuspendingSessionTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CommonTestHelper) -> Unit) { @@ -96,18 +86,6 @@ class CommonTestHelper internal constructor(context: Context) { } } - internal fun runCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: (CryptoTestHelper, CommonTestHelper) -> Unit) { - val testHelper = CommonTestHelper(context) - val cryptoTestHelper = CryptoTestHelper(testHelper) - return try { - block(cryptoTestHelper, testHelper) - } finally { - if (autoSignoutOnClose) { - testHelper.cleanUpOpenedSessions() - } - } - } - @OptIn(ExperimentalCoroutinesApi::class) internal fun runSuspendingCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CryptoTestHelper, CommonTestHelper) -> Unit) { val testHelper = CommonTestHelper(context) @@ -157,11 +135,9 @@ class CommonTestHelper internal constructor(context: Context) { return logIntoAccount(userId, TestConstants.PASSWORD, testParams) } - fun cleanUpOpenedSessions() { + suspend fun cleanUpOpenedSessions() { trackedSessions.forEach { - runBlockingTest { - it.signOutService().signOut(true) - } + it.signOutService().signOut(true) } trackedSessions.clear() } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt index 48d9d6da77c..b0c30ea7800 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt @@ -27,7 +27,6 @@ import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest @RunWith(AndroidJUnit4::class) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt index ee643281a1e..17102c4921b 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt @@ -28,7 +28,6 @@ import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.session.crypto.MXCryptoError -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest @RunWith(JUnit4::class) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index df289e61882..513a44051df 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -44,7 +44,6 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransa import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationCancel import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationStart @@ -57,8 +56,8 @@ import java.util.concurrent.CountDownLatch class SASTest : InstrumentedTest { @Test - fun test_aliceStartThenAliceCancel() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + fun test_aliceStartThenAliceCancel() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -138,9 +137,9 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun test_key_agreement_protocols_must_include_curve25519() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_key_agreement_protocols_must_include_curve25519() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val bobSession = cryptoTestData.secondSession!! @@ -194,7 +193,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun test_key_agreement_macs_Must_include_hmac_sha256() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_key_agreement_macs_Must_include_hmac_sha256() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } @@ -231,7 +230,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun test_key_agreement_short_code_include_decimal() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_key_agreement_short_code_include_decimal() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } @@ -342,7 +341,7 @@ class SASTest : InstrumentedTest { */ @Test @Ignore("This test will be ignored until it is fixed") - fun test_aliceAndBobAgreement() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceAndBobAgreement() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -399,7 +398,7 @@ class SASTest : InstrumentedTest { } @Test - fun test_aliceAndBobSASCode() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceAndBobSASCode() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -455,7 +454,7 @@ class SASTest : InstrumentedTest { } @Test - fun test_happyPath() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_happyPath() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -531,7 +530,7 @@ class SASTest : InstrumentedTest { } @Test - fun test_ConcurrentStart() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_ConcurrentStart() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt index 90de934cc45..f48f77d26bc 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt @@ -34,7 +34,6 @@ import org.matrix.android.sdk.api.session.events.model.isThread import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import java.util.concurrent.CountDownLatch @@ -44,8 +43,8 @@ import java.util.concurrent.CountDownLatch class ThreadMessagingTest : InstrumentedTest { @Test - fun reply_in_thread_should_create_a_thread() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val cryptoTestData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(false) } + fun reply_in_thread_should_create_a_thread() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId @@ -175,8 +174,8 @@ class ThreadMessagingTest : InstrumentedTest { } @Test - fun reply_in_thread_to_timeline_message_multiple_times() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val cryptoTestData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(false) } + fun reply_in_thread_to_timeline_message_multiple_times() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt index ffb6ff5663b..994e9beffcc 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt @@ -38,7 +38,6 @@ import org.matrix.android.sdk.api.session.room.model.message.PollType import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import java.util.concurrent.CountDownLatch diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt index fac519ce2d1..54f984769db 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt @@ -35,7 +35,7 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.checkSendOrder import timber.log.Timber import java.util.concurrent.CountDownLatch @@ -54,9 +54,9 @@ class TimelineForwardPaginationTest : InstrumentedTest { */ @Test @Ignore("Ignoring this test until it's fixed since it blocks the CI.") - fun forwardPaginationTest() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun forwardPaginationTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val numberOfMessagesToSend = 90 - val cryptoTestData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(false) } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt index 6e66e1bc47e..906a3e46ac5 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt @@ -33,7 +33,6 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageTextContent import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import org.matrix.android.sdk.common.TestConstants diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt index d2512ec559a..16500df945a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt @@ -30,7 +30,6 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest import java.util.concurrent.CountDownLatch From 20f7fc07cb24827af5550462b28deb32f125bf7b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:28:06 +0100 Subject: [PATCH 41/56] renaming all suspending test runners back to their original names now there's only 1 variant --- .../sdk/account/AccountCreationTest.kt | 10 ++-- .../android/sdk/account/ChangePasswordTest.kt | 4 +- .../sdk/account/DeactivateAccountTest.kt | 4 +- .../sdk/api/network/ApiInterceptorTest.kt | 4 +- .../android/sdk/common/CommonTestHelper.kt | 4 +- .../crypto/DecryptRedactedEventTest.kt | 4 +- .../internal/crypto/E2EShareKeysConfigTest.kt | 12 ++--- .../sdk/internal/crypto/E2eeSanityTests.kt | 16 +++---- .../crypto/E2eeShareKeysHistoryTest.kt | 6 +-- .../sdk/internal/crypto/PreShareKeysTest.kt | 4 +- .../sdk/internal/crypto/UnwedgingTest.kt | 4 +- .../crypto/crosssigning/XSigningTest.kt | 10 ++-- .../crypto/encryption/EncryptionTest.kt | 6 +-- .../crypto/gossiping/KeyShareTests.kt | 12 ++--- .../crypto/gossiping/WithHeldTests.kt | 8 ++-- .../crypto/keysbackup/KeysBackupTest.kt | 46 +++++++++---------- .../crypto/replayattack/ReplayAttackTest.kt | 6 +-- .../sdk/internal/crypto/ssss/QuadSTests.kt | 12 ++--- .../internal/crypto/verification/SASTest.kt | 20 ++++---- .../verification/qrcode/VerificationTest.kt | 8 ++-- .../room/threads/ThreadMessagingTest.kt | 10 ++-- .../room/timeline/PollAggregationTest.kt | 4 +- .../timeline/TimelineForwardPaginationTest.kt | 4 +- .../TimelinePreviousLastForwardTest.kt | 2 +- .../TimelineSimpleBackPaginationTest.kt | 4 +- .../timeline/TimelineWithManyMembersTest.kt | 4 +- .../sdk/session/search/SearchMessagesTest.kt | 4 +- .../sdk/session/space/SpaceCreationTest.kt | 8 ++-- .../sdk/session/space/SpaceHierarchyTest.kt | 16 +++---- 29 files changed, 128 insertions(+), 128 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt index d2b41530fd0..7e4fc4768fb 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/AccountCreationTest.kt @@ -24,8 +24,8 @@ import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -35,13 +35,13 @@ import org.matrix.android.sdk.common.TestConstants class AccountCreationTest : InstrumentedTest { @Test - fun createAccountTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun createAccountTest() = runSessionTest(context()) { commonTestHelper -> commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) } @Test @Ignore("This test will be ignored until it is fixed") - fun createAccountAndLoginAgainTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun createAccountAndLoginAgainTest() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) // Log again to the same account @@ -49,7 +49,7 @@ class AccountCreationTest : InstrumentedTest { } @Test - fun simpleE2eTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, _ -> + fun simpleE2eTest() = runCryptoTest(context()) { cryptoTestHelper, _ -> cryptoTestHelper.doE2ETestWithAliceInARoom() } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt index 7d56d0c626f..403f697778e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/ChangePasswordTest.kt @@ -25,7 +25,7 @@ import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.failure.isInvalidPassword -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -39,7 +39,7 @@ class ChangePasswordTest : InstrumentedTest { } @Test - fun changePasswordTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun changePasswordTest() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) // Change password diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt index 26dae039c43..0b21f85742d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt @@ -29,7 +29,7 @@ import org.matrix.android.sdk.api.auth.UserPasswordAuth import org.matrix.android.sdk.api.auth.registration.RegistrationFlowResponse import org.matrix.android.sdk.api.failure.Failure import org.matrix.android.sdk.api.failure.MatrixError -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import kotlin.coroutines.Continuation @@ -40,7 +40,7 @@ import kotlin.coroutines.resume class DeactivateAccountTest : InstrumentedTest { @Test - fun deactivateAccountTest() = runSuspendingSessionTest(context(), false /* session will be deactivated */) { commonTestHelper -> + fun deactivateAccountTest() = runSessionTest(context(), false /* session will be deactivated */) { commonTestHelper -> val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) // Deactivate the account diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt index d2c6b388be6..8dbff820157 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/api/network/ApiInterceptorTest.kt @@ -23,7 +23,7 @@ import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import timber.log.Timber @@ -33,7 +33,7 @@ import timber.log.Timber class ApiInterceptorTest : InstrumentedTest { @Test - fun apiInterceptorTest() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun apiInterceptorTest() = runSessionTest(context()) { commonTestHelper -> val responses = mutableListOf() val listener = object : ApiInterceptorListener { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index ef3fdaa6c9d..e8601f0ac87 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -71,7 +71,7 @@ class CommonTestHelper internal constructor(context: Context) { companion object { @OptIn(ExperimentalCoroutinesApi::class) - internal fun runSuspendingSessionTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CommonTestHelper) -> Unit) { + internal fun runSessionTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CommonTestHelper) -> Unit) { val testHelper = CommonTestHelper(context) return runTest(dispatchTimeoutMs = TestConstants.timeOutMillis) { try { @@ -87,7 +87,7 @@ class CommonTestHelper internal constructor(context: Context) { } @OptIn(ExperimentalCoroutinesApi::class) - internal fun runSuspendingCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CryptoTestHelper, CommonTestHelper) -> Unit) { + internal fun runCryptoTest(context: Context, autoSignoutOnClose: Boolean = true, block: suspend CoroutineScope.(CryptoTestHelper, CommonTestHelper) -> Unit) { val testHelper = CommonTestHelper(context) val cryptoTestHelper = CryptoTestHelper(testHelper) return runTest(dispatchTimeoutMs = TestConstants.timeOutMillis) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt index b0c30ea7800..ffb75991528 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt @@ -27,14 +27,14 @@ import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) class DecryptRedactedEventTest : InstrumentedTest { @Test - fun doNotFailToDecryptRedactedEvent() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun doNotFailToDecryptRedactedEvent() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = testData.roomId val aliceSession = testData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt index e0fd1c283fb..60a01b32ca1 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt @@ -36,7 +36,7 @@ import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CryptoTestData import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -47,13 +47,13 @@ import org.matrix.android.sdk.common.TestConstants class E2EShareKeysConfigTest : InstrumentedTest { @Test - fun msc3061ShouldBeDisabledByDefault() = runSuspendingCryptoTest(context()) { _, commonTestHelper -> + fun msc3061ShouldBeDisabledByDefault() = runCryptoTest(context()) { _, commonTestHelper -> val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) Assert.assertFalse("MSC3061 is lab and should be disabled by default", aliceSession.cryptoService().isShareKeysOnInviteEnabled()) } @Test - fun ensureKeysAreNotSharedIfOptionDisabled() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun ensureKeysAreNotSharedIfOptionDisabled() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) aliceSession.cryptoService().enableShareKeyOnInvite(false) val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { @@ -126,7 +126,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { } @Test - fun ifSharingDisabledOnAliceSideBobShouldNotShareAliceHistory() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun ifSharingDisabledOnAliceSideBobShouldNotShareAliceHistory() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(roomHistoryVisibility = RoomHistoryVisibility.SHARED) val aliceSession = testData.firstSession.also { it.cryptoService().enableShareKeyOnInvite(false) @@ -153,7 +153,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { } @Test - fun ifSharingEnabledOnAliceSideBobShouldShareAliceHistory() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun ifSharingEnabledOnAliceSideBobShouldShareAliceHistory() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(roomHistoryVisibility = RoomHistoryVisibility.SHARED) val aliceSession = testData.firstSession.also { it.cryptoService().enableShareKeyOnInvite(true) @@ -195,7 +195,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { // test flag on backup is correct @Test - fun testBackupFlagIsCorrect() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun testBackupFlagIsCorrect() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) aliceSession.cryptoService().enableShareKeyOnInvite(false) val roomId = aliceSession.roomService().createRoom(CreateRoomParams().apply { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index 742c02c9f4a..cedb06480f7 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -59,8 +59,8 @@ import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.mustFail import kotlin.coroutines.resume @@ -81,7 +81,7 @@ class E2eeSanityTests : InstrumentedTest { * Alice sends a new message, then check that the new one can be decrypted */ @Test - fun testSendingE2EEMessages() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testSendingE2EEMessages() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -186,7 +186,7 @@ class E2eeSanityTests : InstrumentedTest { } @Test - fun testKeyGossipingIsEnabledByDefault() = runSuspendingSessionTest(context()) { testHelper -> + fun testKeyGossipingIsEnabledByDefault() = runSessionTest(context()) { testHelper -> val session = testHelper.createAccount("alice", SessionTestParams(true)) Assert.assertTrue("Key gossiping should be enabled by default", session.cryptoService().isKeyGossipingEnabled()) } @@ -206,7 +206,7 @@ class E2eeSanityTests : InstrumentedTest { * 9. Check that new session can decrypt */ @Test - fun testBasicBackupImport() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBasicBackupImport() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -309,7 +309,7 @@ class E2eeSanityTests : InstrumentedTest { * get them from an older one. */ @Test - fun testSimpleGossip() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testSimpleGossip() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -405,7 +405,7 @@ class E2eeSanityTests : InstrumentedTest { * Test that if a better key is forwarded (lower index, it is then used) */ @Test - fun testForwardBetterKey() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testForwardBetterKey() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = cryptoTestData.firstSession @@ -535,7 +535,7 @@ class E2eeSanityTests : InstrumentedTest { * Test that if a better key is forwared (lower index, it is then used) */ @Test - fun testASelfInteractiveVerificationAndGossip() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testASelfInteractiveVerificationAndGossip() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val aliceSession = testHelper.createAccount("alice", SessionTestParams(true)) cryptoTestHelper.bootstrapSecurity(aliceSession) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt index 6b61c93a1c3..623e4827ad3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt @@ -40,7 +40,7 @@ import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibility import org.matrix.android.sdk.api.session.room.model.RoomHistoryVisibilityContent import org.matrix.android.sdk.api.session.room.model.shouldShareHistory import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.wrapWithTimeout @@ -76,7 +76,7 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { * We should not be able to view messages/decrypt otherwise */ private fun testShareHistoryWithRoomVisibility(roomHistoryVisibility: RoomHistoryVisibility? = null) = - runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true, roomHistoryVisibility) val e2eRoomID = cryptoTestData.roomId @@ -230,7 +230,7 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { private fun testRotationDueToVisibilityChange( initRoomHistoryVisibility: RoomHistoryVisibility, nextRoomHistoryVisibility: RoomHistoryVisibilityContent - ) = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + ) = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true, initRoomHistoryVisibility) val e2eRoomID = cryptoTestData.roomId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt index c6e0c7b986b..c82a65e82ac 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt @@ -30,14 +30,14 @@ import org.matrix.android.sdk.api.session.events.model.content.EncryptedEventCon import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) class PreShareKeysTest : InstrumentedTest { @Test - fun ensure_outbound_session_happy_path() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun ensure_outbound_session_happy_path() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = testData.roomId val aliceSession = testData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index d9756bd2eda..baf3a088c5e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -39,7 +39,7 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.internal.crypto.model.OlmSessionWrapper import org.matrix.android.sdk.internal.crypto.store.db.deserializeFromRealm @@ -82,7 +82,7 @@ class UnwedgingTest : InstrumentedTest { * -> This is automatically fixed after SDKs restarted the olm session */ @Test - fun testUnwedging() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testUnwedging() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index 6797db52699..cbcdf97e83f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -38,8 +38,8 @@ import org.matrix.android.sdk.api.session.crypto.crosssigning.isCrossSignedVerif import org.matrix.android.sdk.api.session.crypto.crosssigning.isVerified import org.matrix.android.sdk.api.session.crypto.model.CryptoDeviceInfo import org.matrix.android.sdk.api.session.crypto.model.MXUsersDevicesMap -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import kotlin.coroutines.Continuation @@ -52,7 +52,7 @@ import kotlin.coroutines.resume class XSigningTest : InstrumentedTest { @Test - fun test_InitializeAndStoreKeys() = runSuspendingSessionTest(context()) { testHelper -> + fun test_InitializeAndStoreKeys() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) testHelper.doSync { @@ -86,7 +86,7 @@ class XSigningTest : InstrumentedTest { } @Test - fun test_CrossSigningCheckBobSeesTheKeys() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_CrossSigningCheckBobSeesTheKeys() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession @@ -139,7 +139,7 @@ class XSigningTest : InstrumentedTest { } @Test - fun test_CrossSigningTestAliceTrustBobNewDevice() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_CrossSigningTestAliceTrustBobNewDevice() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt index 091f6a37e84..42a04dbe3f9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/encryption/EncryptionTest.kt @@ -34,7 +34,7 @@ import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CryptoTestHelper import org.matrix.android.sdk.common.waitFor import kotlin.coroutines.resume @@ -44,7 +44,7 @@ import kotlin.coroutines.resume class EncryptionTest : InstrumentedTest { @Test - fun test_EncryptionEvent() = runSuspendingCryptoTest(context()) { cryptoTestHelper, _ -> + fun test_EncryptionEvent() = runCryptoTest(context()) { cryptoTestHelper, _ -> performTest(cryptoTestHelper, roomShouldBeEncrypted = false) { room -> // Send an encryption Event as an Event (and not as a state event) room.sendService().sendEvent( @@ -55,7 +55,7 @@ class EncryptionTest : InstrumentedTest { } @Test - fun test_EncryptionStateEvent() = runSuspendingCryptoTest(context()) { cryptoTestHelper, _ -> + fun test_EncryptionStateEvent() = runCryptoTest(context()) { cryptoTestHelper, _ -> performTest(cryptoTestHelper, roomShouldBeEncrypted = true) { room -> // Send an encryption Event as a State Event room.stateService().sendStateEvent( diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index dbd5d92664f..f2fdb76dd47 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -42,7 +42,7 @@ import org.matrix.android.sdk.api.session.room.getTimelineEvent import org.matrix.android.sdk.api.session.room.model.RoomDirectoryVisibility import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.timeline.getLastMessageContent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants @@ -57,7 +57,7 @@ class KeyShareTests : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) @Test - fun test_DoNotSelfShareIfNotTrusted() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_DoNotSelfShareIfNotTrusted() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val aliceSession = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) Log.v("TEST", "=======> AliceSession 1 is ${aliceSession.sessionParams.deviceId}") @@ -193,7 +193,7 @@ class KeyShareTests : InstrumentedTest { * if the key was originally shared with him */ @Test - fun test_reShareIfWasIntendedToBeShared() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_reShareIfWasIntendedToBeShared() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = testData.firstSession @@ -224,7 +224,7 @@ class KeyShareTests : InstrumentedTest { * if the key was originally shared with him */ @Test - fun test_reShareToUnverifiedIfWasIntendedToBeShared() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_reShareToUnverifiedIfWasIntendedToBeShared() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(true) } val aliceSession = testData.firstSession @@ -261,7 +261,7 @@ class KeyShareTests : InstrumentedTest { * Tests that keys reshared with own verified session are done from the earliest known index */ @Test - fun test_reShareFromTheEarliestKnownIndexWithOwnVerifiedSession() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_reShareFromTheEarliestKnownIndexWithOwnVerifiedSession() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = testData.firstSession @@ -381,7 +381,7 @@ class KeyShareTests : InstrumentedTest { * Tests that we don't cancel a request to early on first forward if the index is not good enough */ @Test - fun test_dontCancelToEarly() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun test_dontCancelToEarly() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val aliceSession = testData.firstSession val bobSession = testData.secondSession!! diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index 6ceb5bd898a..dd86084eb00 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -36,7 +36,7 @@ import org.matrix.android.sdk.api.session.events.model.content.WithHeldCode import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.getTimelineEvent -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.MockOkHttpInterceptor import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.SessionTestParams @@ -51,7 +51,7 @@ class WithHeldTests : InstrumentedTest { @get:Rule val rule = RetryTestRule(3) @Test - fun test_WithHeldUnverifiedReason() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_WithHeldUnverifiedReason() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> // ============================= // ARRANGE @@ -143,7 +143,7 @@ class WithHeldTests : InstrumentedTest { } @Test - fun test_WithHeldNoOlm() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_WithHeldNoOlm() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = testData.firstSession @@ -217,7 +217,7 @@ class WithHeldTests : InstrumentedTest { } @Test - fun test_WithHeldKeyRequest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_WithHeldKeyRequest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val testData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = testData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index ee5450c0b6d..dac31e479f2 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -44,8 +44,8 @@ import org.matrix.android.sdk.api.session.crypto.keysbackup.MegolmBackupCreation import org.matrix.android.sdk.api.session.crypto.keysbackup.toKeysVersionResult import org.matrix.android.sdk.api.session.crypto.model.ImportRoomKeysResult import org.matrix.android.sdk.api.session.getRoom -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.common.TestMatrixCallback @@ -65,7 +65,7 @@ class KeysBackupTest : InstrumentedTest { * - Reset keys backup markers */ @Test - fun roomKeysTest_testBackupStore_ok() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun roomKeysTest_testBackupStore_ok() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -104,7 +104,7 @@ class KeysBackupTest : InstrumentedTest { * Check that prepareKeysBackupVersionWithPassword returns valid data */ @Test - fun prepareKeysBackupVersionTest() = runSuspendingSessionTest(context()) { testHelper -> + fun prepareKeysBackupVersionTest() = runSessionTest(context()) { testHelper -> val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) @@ -132,7 +132,7 @@ class KeysBackupTest : InstrumentedTest { * Test creating a keys backup version and check that createKeysBackupVersion() returns valid data */ @Test - fun createKeysBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun createKeysBackupVersionTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val bobSession = testHelper.createAccount(TestConstants.USER_BOB, KeysBackupTestConstants.defaultSessionParams) cryptoTestHelper.initializeCrossSigning(bobSession) @@ -197,7 +197,7 @@ class KeysBackupTest : InstrumentedTest { * - Check the backup completes */ @Test - fun backupAfterCreateKeysBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun backupAfterCreateKeysBackupVersionTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -238,7 +238,7 @@ class KeysBackupTest : InstrumentedTest { * Check that backupAllGroupSessions() returns valid data */ @Test - fun backupAllGroupSessionsTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun backupAllGroupSessionsTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -283,7 +283,7 @@ class KeysBackupTest : InstrumentedTest { * - Compare the decrypted megolm key with the original one */ @Test - fun testEncryptAndDecryptKeysBackupData() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testEncryptAndDecryptKeysBackupData() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoomWithEncryptedMessages() @@ -327,7 +327,7 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - fun restoreKeysBackupTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun restoreKeysBackupTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -413,7 +413,7 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - fun trustKeyBackupVersionTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Do an e2e backup to the homeserver with a recovery key @@ -473,7 +473,7 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - fun trustKeyBackupVersionWithRecoveryKeyTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithRecoveryKeyTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Do an e2e backup to the homeserver with a recovery key @@ -531,7 +531,7 @@ class KeysBackupTest : InstrumentedTest { * - The backup must still be untrusted and disabled */ @Test - fun trustKeyBackupVersionWithWrongRecoveryKeyTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithWrongRecoveryKeyTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Do an e2e backup to the homeserver with a recovery key @@ -573,7 +573,7 @@ class KeysBackupTest : InstrumentedTest { * - It must be trusted and must have with 2 signatures now */ @Test - fun trustKeyBackupVersionWithPasswordTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithPasswordTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "Password" @@ -633,7 +633,7 @@ class KeysBackupTest : InstrumentedTest { * - The backup must still be untrusted and disabled */ @Test - fun trustKeyBackupVersionWithWrongPasswordTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun trustKeyBackupVersionWithWrongPasswordTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "Password" @@ -674,7 +674,7 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - fun restoreKeysBackupWithAWrongRecoveryKeyTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun restoreKeysBackupWithAWrongRecoveryKeyTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -707,7 +707,7 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - fun testBackupWithPassword() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBackupWithPassword() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "password" @@ -763,7 +763,7 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - fun restoreKeysBackupWithAWrongPasswordTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun restoreKeysBackupWithAWrongPasswordTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "password" @@ -799,7 +799,7 @@ class KeysBackupTest : InstrumentedTest { * - Restore must be successful */ @Test - fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testUseRecoveryKeyToRestoreAPasswordBasedKeysBackup() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val password = "password" @@ -828,7 +828,7 @@ class KeysBackupTest : InstrumentedTest { * - It must fail */ @Test - fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testUsePasswordToRestoreARecoveryKeyBasedKeysBackup() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) @@ -859,7 +859,7 @@ class KeysBackupTest : InstrumentedTest { * - Check the returned KeysVersionResult is trusted */ @Test - fun testIsKeysBackupTrusted() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testIsKeysBackupTrusted() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version @@ -904,7 +904,7 @@ class KeysBackupTest : InstrumentedTest { * -> That must fail and her backup state must be WrongBackUpVersion */ @Test - fun testBackupWhenAnotherBackupWasCreated() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBackupWhenAnotherBackupWasCreated() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version @@ -976,7 +976,7 @@ class KeysBackupTest : InstrumentedTest { * -> It must success */ @Test - fun testBackupAfterVerifyingADevice() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun testBackupAfterVerifyingADevice() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version @@ -1074,7 +1074,7 @@ class KeysBackupTest : InstrumentedTest { * - Delete the backup */ @Test - fun deleteKeysBackupTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun deleteKeysBackupTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) // - Create a backup version diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt index 17102c4921b..c3e795e8c74 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt @@ -28,7 +28,7 @@ import org.junit.runners.JUnit4 import org.junit.runners.MethodSorters import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.session.crypto.MXCryptoError -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @@ -36,7 +36,7 @@ import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCry class ReplayAttackTest : InstrumentedTest { @Test - fun replayAttackAlreadyDecryptedEventTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun replayAttackAlreadyDecryptedEventTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = cryptoTestData.roomId @@ -72,7 +72,7 @@ class ReplayAttackTest : InstrumentedTest { } @Test - fun replayAttackSameEventTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun replayAttackSameEventTest() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true) val e2eRoomID = cryptoTestData.roomId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt index 4bd022b35f9..c8be6aae74e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt @@ -40,7 +40,7 @@ import org.matrix.android.sdk.api.session.securestorage.SsssKeyCreationInfo import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.toBase64NoPadding import org.matrix.android.sdk.common.CommonTestHelper -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.internal.crypto.secrets.DefaultSharedSecretStorageService @@ -56,7 +56,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_Generate4SKey() = runSuspendingSessionTest(context()) { testHelper -> + fun test_Generate4SKey() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) @@ -108,7 +108,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_StoreSecret() = runSuspendingSessionTest(context()) { testHelper -> + fun test_StoreSecret() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId = "My.Key" @@ -151,7 +151,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_SetDefaultLocalEcho() = runSuspendingSessionTest(context()) { testHelper -> + fun test_SetDefaultLocalEcho() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) @@ -170,7 +170,7 @@ class QuadSTests : InstrumentedTest { } @Test - fun test_StoreSecretWithMultipleKey() = runSuspendingSessionTest(context()) { testHelper -> + fun test_StoreSecretWithMultipleKey() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId1 = "Key.1" @@ -219,7 +219,7 @@ class QuadSTests : InstrumentedTest { @Test @Ignore("Test is working locally, not in GitHub actions") - fun test_GetSecretWithBadPassphrase() = runSuspendingSessionTest(context()) { testHelper -> + fun test_GetSecretWithBadPassphrase() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId1 = "Key.1" diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index 513a44051df..4419cdde19a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -44,7 +44,7 @@ import org.matrix.android.sdk.api.session.crypto.verification.VerificationTransa import org.matrix.android.sdk.api.session.crypto.verification.VerificationTxState import org.matrix.android.sdk.api.session.events.model.Event import org.matrix.android.sdk.api.session.events.model.toModel -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationCancel import org.matrix.android.sdk.internal.crypto.model.rest.KeyVerificationStart import org.matrix.android.sdk.internal.crypto.model.rest.toValue @@ -56,7 +56,7 @@ import java.util.concurrent.CountDownLatch class SASTest : InstrumentedTest { @Test - fun test_aliceStartThenAliceCancel() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceStartThenAliceCancel() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession @@ -137,7 +137,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun test_key_agreement_protocols_must_include_curve25519() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_key_agreement_protocols_must_include_curve25519() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() @@ -193,7 +193,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun test_key_agreement_macs_Must_include_hmac_sha256() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_key_agreement_macs_Must_include_hmac_sha256() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } @@ -230,7 +230,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun test_key_agreement_short_code_include_decimal() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_key_agreement_short_code_include_decimal() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } @@ -300,7 +300,7 @@ class SASTest : InstrumentedTest { // any two devices may only have at most one key verification in flight at a time. // If a device has two verifications in progress with the same device, then it should cancel both verifications. @Test - fun test_aliceStartTwoRequests() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceStartTwoRequests() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -341,7 +341,7 @@ class SASTest : InstrumentedTest { */ @Test @Ignore("This test will be ignored until it is fixed") - fun test_aliceAndBobAgreement() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceAndBobAgreement() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -398,7 +398,7 @@ class SASTest : InstrumentedTest { } @Test - fun test_aliceAndBobSASCode() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_aliceAndBobSASCode() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -454,7 +454,7 @@ class SASTest : InstrumentedTest { } @Test - fun test_happyPath() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_happyPath() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession @@ -530,7 +530,7 @@ class SASTest : InstrumentedTest { } @Test - fun test_ConcurrentStart() = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + fun test_ConcurrentStart() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index e3c5bb8ac17..597c43b96a1 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -32,8 +32,8 @@ import org.matrix.android.sdk.api.session.crypto.verification.CancelCode import org.matrix.android.sdk.api.session.crypto.verification.PendingVerificationRequest import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod import org.matrix.android.sdk.api.session.crypto.verification.VerificationService -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants import java.util.concurrent.CountDownLatch @@ -158,7 +158,7 @@ class VerificationTest : InstrumentedTest { bobSupportedMethods: List, expectedResultForAlice: ExpectedResult, expectedResultForBob: ExpectedResult - ) = runSuspendingCryptoTest(context()) { cryptoTestHelper, testHelper -> + ) = runCryptoTest(context()) { cryptoTestHelper, testHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession @@ -256,7 +256,7 @@ class VerificationTest : InstrumentedTest { } @Test - fun test_selfVerificationAcceptedCancelsItForOtherSessions() = runSuspendingSessionTest(context()) { testHelper -> + fun test_selfVerificationAcceptedCancelsItForOtherSessions() = runSessionTest(context()) { testHelper -> val defaultSessionParams = SessionTestParams(true) val aliceSessionToVerify = testHelper.createAccount(TestConstants.USER_ALICE, defaultSessionParams) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt index f48f77d26bc..45bd38870d3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/threads/ThreadMessagingTest.kt @@ -34,7 +34,7 @@ import org.matrix.android.sdk.api.session.events.model.isThread import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import java.util.concurrent.CountDownLatch @RunWith(JUnit4::class) @@ -43,7 +43,7 @@ import java.util.concurrent.CountDownLatch class ThreadMessagingTest : InstrumentedTest { @Test - fun reply_in_thread_should_create_a_thread() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun reply_in_thread_should_create_a_thread() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession @@ -101,7 +101,7 @@ class ThreadMessagingTest : InstrumentedTest { } @Test - fun reply_in_thread_should_create_a_thread_from_other_user() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun reply_in_thread_should_create_a_thread_from_other_user() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession @@ -174,7 +174,7 @@ class ThreadMessagingTest : InstrumentedTest { } @Test - fun reply_in_thread_to_timeline_message_multiple_times() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun reply_in_thread_to_timeline_message_multiple_times() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession @@ -237,7 +237,7 @@ class ThreadMessagingTest : InstrumentedTest { } @Test - fun thread_summary_advanced_validation_after_multiple_messages_in_multiple_threads() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun thread_summary_advanced_validation_after_multiple_messages_in_multiple_threads() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt index 994e9beffcc..a37d2ce015f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/PollAggregationTest.kt @@ -38,7 +38,7 @@ import org.matrix.android.sdk.api.session.room.model.message.PollType import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import java.util.concurrent.CountDownLatch @RunWith(JUnit4::class) @@ -46,7 +46,7 @@ import java.util.concurrent.CountDownLatch class PollAggregationTest : InstrumentedTest { @Test - fun testAllPollUseCases() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun testAllPollUseCases() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt index 54f984769db..2e5c69b0487 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineForwardPaginationTest.kt @@ -35,7 +35,7 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.checkSendOrder import timber.log.Timber import java.util.concurrent.CountDownLatch @@ -54,7 +54,7 @@ class TimelineForwardPaginationTest : InstrumentedTest { */ @Test @Ignore("Ignoring this test until it's fixed since it blocks the CI.") - fun forwardPaginationTest() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun forwardPaginationTest() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val numberOfMessagesToSend = 90 val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt index 2ad3eda9181..7c1a097b241 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelinePreviousLastForwardTest.kt @@ -49,7 +49,7 @@ class TimelinePreviousLastForwardTest : InstrumentedTest { */ @Test - fun previousLastForwardTest() = CommonTestHelper.runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun previousLastForwardTest() = CommonTestHelper.runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) val aliceSession = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt index 906a3e46ac5..59b3b145322 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt @@ -33,7 +33,7 @@ import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageTextContent import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.TestConstants @RunWith(JUnit4::class) @@ -43,7 +43,7 @@ import org.matrix.android.sdk.common.TestConstants class TimelineSimpleBackPaginationTest : InstrumentedTest { @Test - fun timeline_backPaginate_shouldReachEndOfTimeline() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun timeline_backPaginate_shouldReachEndOfTimeline() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val numberOfMessagesToSent = 200 val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom(false) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt index 16500df945a..27ea0e1c3c0 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineWithManyMembersTest.kt @@ -30,7 +30,7 @@ import org.matrix.android.sdk.api.session.events.model.toModel import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.room.model.message.MessageContent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import java.util.concurrent.CountDownLatch /** !! Not working with the new timeline @@ -51,7 +51,7 @@ class TimelineWithManyMembersTest : InstrumentedTest { */ @Test - fun everyone_should_decrypt_message_in_a_crowded_room() = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + fun everyone_should_decrypt_message_in_a_crowded_room() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithManyMembers(NUMBER_OF_MEMBERS) val sessionForFirstMember = cryptoTestData.firstSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt index b0ecb5f7726..525c047ac4c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt @@ -26,7 +26,7 @@ import org.matrix.android.sdk.InstrumentedTest import org.matrix.android.sdk.api.extensions.orFalse import org.matrix.android.sdk.api.session.getRoom import org.matrix.android.sdk.api.session.search.SearchResult -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingCryptoTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CryptoTestData @RunWith(JUnit4::class) @@ -73,7 +73,7 @@ class SearchMessagesTest : InstrumentedTest { } } - private fun doTest(block: suspend (CryptoTestData) -> SearchResult) = runSuspendingCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> + private fun doTest(block: suspend (CryptoTestData) -> SearchResult) = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceInARoom(false) val aliceSession = cryptoTestData.firstSession val aliceRoomId = cryptoTestData.roomId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt index 553f1b73ab9..3eeca524881 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt @@ -42,7 +42,7 @@ import org.matrix.android.sdk.api.session.room.model.create.CreateRoomParams import org.matrix.android.sdk.api.session.room.model.create.CreateRoomPreset import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent import org.matrix.android.sdk.api.session.space.JoinSpaceResult -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams @RunWith(JUnit4::class) @@ -51,7 +51,7 @@ import org.matrix.android.sdk.common.SessionTestParams class SpaceCreationTest : InstrumentedTest { @Test - fun createSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun createSimplePublicSpace() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("Hubble", SessionTestParams(true)) val roomName = "My Space" val topic = "A public space for test" @@ -102,7 +102,7 @@ class SpaceCreationTest : InstrumentedTest { @Test @Ignore - fun testJoinSimplePublicSpace() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testJoinSimplePublicSpace() = runSessionTest(context()) { commonTestHelper -> val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) @@ -128,7 +128,7 @@ class SpaceCreationTest : InstrumentedTest { } @Test - fun testSimplePublicSpaceWithChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testSimplePublicSpaceWithChildren() = runSessionTest(context()) { commonTestHelper -> val aliceSession = commonTestHelper.createAccount("alice", SessionTestParams(true)) val bobSession = commonTestHelper.createAccount("bob", SessionTestParams(true)) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt index f977793cabb..ce2cde0b401 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt @@ -43,7 +43,7 @@ import org.matrix.android.sdk.api.session.room.model.create.RestrictedRoomPreset import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper import org.matrix.android.sdk.api.session.room.powerlevels.Role import org.matrix.android.sdk.api.session.room.roomSummaryQueryParams -import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSuspendingSessionTest +import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.first import org.matrix.android.sdk.common.onMain @@ -54,7 +54,7 @@ import org.matrix.android.sdk.common.waitFor class SpaceHierarchyTest : InstrumentedTest { @Test - fun createCanonicalChildRelation() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun createCanonicalChildRelation() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceName = "My Space" @@ -152,7 +152,7 @@ class SpaceHierarchyTest : InstrumentedTest { // } @Test - fun testFilteringBySpace() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testFilteringBySpace() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( @@ -223,7 +223,7 @@ class SpaceHierarchyTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") - fun testBreakCycle() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testBreakCycle() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( @@ -264,7 +264,7 @@ class SpaceHierarchyTest : InstrumentedTest { } @Test - fun testLiveFlatChildren() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testLiveFlatChildren() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("John", SessionTestParams(true)) val spaceAInfo = createPublicSpace( @@ -399,7 +399,7 @@ class SpaceHierarchyTest : InstrumentedTest { } @Test - fun testRootSpaces() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testRootSpaces() = runSessionTest(context()) { commonTestHelper -> val session = commonTestHelper.createAccount("John", SessionTestParams(true)) /* val spaceAInfo = */ createPublicSpace( @@ -448,7 +448,7 @@ class SpaceHierarchyTest : InstrumentedTest { } @Test - fun testParentRelation() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testParentRelation() = runSessionTest(context()) { commonTestHelper -> val aliceSession = commonTestHelper.createAccount("Alice", SessionTestParams(true)) val bobSession = commonTestHelper.createAccount("Bib", SessionTestParams(true)) @@ -516,7 +516,7 @@ class SpaceHierarchyTest : InstrumentedTest { } @Test - fun testDirectParentNames() = runSuspendingSessionTest(context()) { commonTestHelper -> + fun testDirectParentNames() = runSessionTest(context()) { commonTestHelper -> val aliceSession = commonTestHelper.createAccount("Alice", SessionTestParams(true)) val spaceAInfo = createPublicSpace( From 087be6300ef112c7ba6b3651fdc6059bf8bcf5da Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:37:31 +0100 Subject: [PATCH 42/56] using suspending text message sending for all instrumentation tests --- .../android/sdk/common/CommonTestHelper.kt | 29 ++++--------------- .../android/sdk/common/CryptoTestHelper.kt | 10 +++---- .../crypto/DecryptRedactedEventTest.kt | 2 +- .../internal/crypto/E2EShareKeysConfigTest.kt | 14 ++++----- .../crypto/E2eeShareKeysHistoryTest.kt | 2 +- .../sdk/internal/crypto/PreShareKeysTest.kt | 2 +- .../crypto/gossiping/WithHeldTests.kt | 10 +++---- .../crypto/keysbackup/KeysBackupTest.kt | 2 +- .../crypto/replayattack/ReplayAttackTest.kt | 4 +-- .../sdk/session/search/SearchMessagesTest.kt | 2 +- 10 files changed, 30 insertions(+), 47 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index e8601f0ac87..5d4f608b6f1 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -19,7 +19,6 @@ package org.matrix.android.sdk.common import android.content.Context import android.net.Uri import android.util.Log -import androidx.lifecycle.Observer import androidx.test.internal.runner.junit4.statement.UiThreadStatement import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope @@ -53,7 +52,6 @@ import org.matrix.android.sdk.api.session.room.send.SendState import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings -import org.matrix.android.sdk.api.session.sync.SyncState import timber.log.Timber import java.util.UUID import java.util.concurrent.CancellationException @@ -162,22 +160,11 @@ class CommonTestHelper internal constructor(context: Context) { * * @param session the session to sync */ - fun clearCacheAndSync(session: Session, timeout: Long = TestConstants.timeOutMillis) { - waitWithLatch(timeout) { latch -> - session.clearCache() - val syncLiveData = session.syncService().getSyncStateLive() - val syncObserver = object : Observer { - override fun onChanged(t: SyncState?) { - if (session.syncService().hasAlreadySynced()) { - Timber.v("Clear cache and synced") - syncLiveData.removeObserver(this) - latch.countDown() - } - } - } - syncLiveData.observeForever(syncObserver) - session.syncService().startSync(true) - } + suspend fun clearCacheAndSync(session: Session, timeout: Long = TestConstants.timeOutMillis) { + session.clearCache() + syncSession(session, timeout) + session.syncService().getSyncStateLive().first(timeout) { session.syncService().hasAlreadySynced() } + Timber.v("Clear cache and synced") } /** @@ -187,11 +174,7 @@ class CommonTestHelper internal constructor(context: Context) { * @param message the message to send * @param nbOfMessages the number of time the message will be sent */ - fun sendTextMessage(room: Room, message: String, nbOfMessages: Int, timeout: Long = TestConstants.timeOutMillis): List { - return runBlocking { sendTextMessageSuspending(room, message, nbOfMessages, timeout) } - } - - suspend fun sendTextMessageSuspending(room: Room, message: String, nbOfMessages: Int, timeout: Long = TestConstants.timeOutMillis): List { + suspend fun sendTextMessage(room: Room, message: String, nbOfMessages: Int, timeout: Long = TestConstants.timeOutMillis): List { val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) timeline.start() val sentEvents = sendTextMessagesBatched(timeline, room, message, nbOfMessages, timeout) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 7d472f6f32f..e98648fa350 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -137,28 +137,28 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! // Alice sends a message - testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId -> + testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[0], 1).first().eventId.let { sentEventId -> // ensure bob got it ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) } // Bob send 3 messages - testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> + testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[0], 1).first().eventId.let { sentEventId -> // ensure alice got it ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) } - testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId -> + testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[1], 1).first().eventId.let { sentEventId -> // ensure alice got it ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) } - testHelper.sendTextMessageSuspending(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId -> + testHelper.sendTextMessage(roomFromBobPOV, messagesFromBob[2], 1).first().eventId.let { sentEventId -> // ensure alice got it ensureEventReceived(aliceRoomId, sentEventId, aliceSession, true) } // Alice sends a message - testHelper.sendTextMessageSuspending(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId -> + testHelper.sendTextMessage(roomFromAlicePOV, messagesFromAlice[1], 1).first().eventId.let { sentEventId -> // ensure bob got it ensureEventReceived(aliceRoomId, sentEventId, bobSession, true) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt index ffb75991528..4e1efbb700b 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/DecryptRedactedEventTest.kt @@ -41,7 +41,7 @@ class DecryptRedactedEventTest : InstrumentedTest { val bobSession = testData.secondSession!! val roomALicePOV = aliceSession.getRoom(e2eRoomID)!! - val timelineEvent = testHelper.sendTextMessageSuspending(roomALicePOV, "Hello", 1).first() + val timelineEvent = testHelper.sendTextMessage(roomALicePOV, "Hello", 1).first() val redactionReason = "Wrong Room" roomALicePOV.sendService().redactEvent(timelineEvent.root, redactionReason) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt index 60a01b32ca1..9a4b6eca7a7 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt @@ -68,9 +68,9 @@ class E2EShareKeysConfigTest : InstrumentedTest { val roomAlice = aliceSession.roomService().getRoom(roomId)!! // send some messages - val withSession1 = commonTestHelper.sendTextMessageSuspending(roomAlice, "Hello", 1) + val withSession1 = commonTestHelper.sendTextMessage(roomAlice, "Hello", 1) aliceSession.cryptoService().discardOutboundSession(roomId) - val withSession2 = commonTestHelper.sendTextMessageSuspending(roomAlice, "World", 1) + val withSession2 = commonTestHelper.sendTextMessage(roomAlice, "World", 1) // Create bob account val bobSession = commonTestHelper.createAccount(TestConstants.USER_BOB, SessionTestParams(withInitialSync = true)) @@ -94,7 +94,7 @@ class E2EShareKeysConfigTest : InstrumentedTest { aliceSession.cryptoService().enableShareKeyOnInvite(true) // let's add a new message first - val afterFlagOn = commonTestHelper.sendTextMessageSuspending(roomAlice, "After", 1) + val afterFlagOn = commonTestHelper.sendTextMessage(roomAlice, "After", 1) // Worth nothing to check that the session was rotated Assert.assertNotEquals( @@ -178,8 +178,8 @@ class E2EShareKeysConfigTest : InstrumentedTest { } private suspend fun commonAliceAndBobSendMessages(commonTestHelper: CommonTestHelper, aliceSession: Session, testData: CryptoTestData, bobSession: Session): Triple, List, Session> { - val fromAliceNotSharable = commonTestHelper.sendTextMessageSuspending(aliceSession.getRoom(testData.roomId)!!, "Hello from alice", 1) - val fromBobSharable = commonTestHelper.sendTextMessageSuspending(bobSession.getRoom(testData.roomId)!!, "Hello from bob", 1) + val fromAliceNotSharable = commonTestHelper.sendTextMessage(aliceSession.getRoom(testData.roomId)!!, "Hello from alice", 1) + val fromBobSharable = commonTestHelper.sendTextMessage(bobSession.getRoom(testData.roomId)!!, "Hello from bob", 1) // Now let bob invite Sam // Invite a new user @@ -210,9 +210,9 @@ class E2EShareKeysConfigTest : InstrumentedTest { val roomAlice = aliceSession.roomService().getRoom(roomId)!! // send some messages - val notSharableMessage = commonTestHelper.sendTextMessageSuspending(roomAlice, "Hello", 1) + val notSharableMessage = commonTestHelper.sendTextMessage(roomAlice, "Hello", 1) aliceSession.cryptoService().enableShareKeyOnInvite(true) - val sharableMessage = commonTestHelper.sendTextMessageSuspending(roomAlice, "World", 1) + val sharableMessage = commonTestHelper.sendTextMessage(roomAlice, "World", 1) Log.v("#E2E TEST", "Create and start key backup for bob ...") val keysBackupService = aliceSession.cryptoService().keysBackupService() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt index 623e4827ad3..55524eada68 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt @@ -356,7 +356,7 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { } private suspend fun sendMessageInRoom(aliceRoomPOV: Room, text: String, testHelper: CommonTestHelper): String? { - return testHelper.sendTextMessageSuspending(aliceRoomPOV, text, 1).firstOrNull()?.eventId + return testHelper.sendTextMessage(aliceRoomPOV, text, 1).firstOrNull()?.eventId } private suspend fun ensureMembersHaveJoined(aliceSession: Session, otherAccounts: List, e2eRoomID: String, testHelper: CommonTestHelper) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt index c82a65e82ac..a4874528173 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt @@ -80,7 +80,7 @@ class PreShareKeysTest : InstrumentedTest { assertEquals("The session received by bob should match what alice sent", 0, sharedIndex) // Just send a real message as test - val sentEvent = testHelper.sendTextMessageSuspending(aliceSession.getRoom(e2eRoomID)!!, "Allo", 1).first() + val sentEvent = testHelper.sendTextMessage(aliceSession.getRoom(e2eRoomID)!!, "Allo", 1).first() assertEquals("Unexpected megolm session", megolmSessionId, sentEvent.root.content.toModel()?.sessionId) testHelper.retryPeriodically { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index dd86084eb00..9ce2403e3ba 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -77,7 +77,7 @@ class WithHeldTests : InstrumentedTest { // Alice decide to not send to unverified sessions aliceSession.cryptoService().setGlobalBlacklistUnverifiedDevices(true) - val timelineEvent = testHelper.sendTextMessageSuspending(roomAlicePOV, "Hello Bob", 1).first() + val timelineEvent = testHelper.sendTextMessage(roomAlicePOV, "Hello Bob", 1).first() // await for bob unverified session to get the message testHelper.retryPeriodically { @@ -120,7 +120,7 @@ class WithHeldTests : InstrumentedTest { // enable back sending to unverified aliceSession.cryptoService().setGlobalBlacklistUnverifiedDevices(false) - val secondEvent = testHelper.sendTextMessageSuspending(roomAlicePOV, "Verify your device!!", 1).first() + val secondEvent = testHelper.sendTextMessage(roomAlicePOV, "Verify your device!!", 1).first() testHelper.retryPeriodically { val ev = bobUnverifiedSession.getRoom(roomId)?.getTimelineEvent(secondEvent.eventId) @@ -164,7 +164,7 @@ class WithHeldTests : InstrumentedTest { val roomAlicePov = aliceSession.getRoom(testData.roomId)!! - val eventId = testHelper.sendTextMessageSuspending(roomAlicePov, "first message", 1).first().eventId + val eventId = testHelper.sendTextMessage(roomAlicePov, "first message", 1).first().eventId // await for bob session to get the message testHelper.retryPeriodically { @@ -198,7 +198,7 @@ class WithHeldTests : InstrumentedTest { aliceInterceptor.clearRules() val bobSecondSession = testHelper.logIntoAccount(bobSession.myUserId, SessionTestParams(withInitialSync = true)) // send a second message - val secondMessageId = testHelper.sendTextMessageSuspending(roomAlicePov, "second message", 1).first().eventId + val secondMessageId = testHelper.sendTextMessage(roomAlicePov, "second message", 1).first().eventId // Check that the // await for bob SecondSession session to get the message @@ -225,7 +225,7 @@ class WithHeldTests : InstrumentedTest { val roomAlicePov = aliceSession.getRoom(testData.roomId)!! - val eventId = testHelper.sendTextMessageSuspending(roomAlicePov, "first message", 1).first().eventId + val eventId = testHelper.sendTextMessage(roomAlicePov, "first message", 1).first().eventId testHelper.signOutAndClose(bobSession) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index dac31e479f2..de3eda79feb 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -1006,7 +1006,7 @@ class KeysBackupTest : InstrumentedTest { val room2 = aliceSession2.getRoom(cryptoTestData.roomId)!! - testHelper.launch { testHelper.sendTextMessageSuspending(room2, "New key", 1) } + testHelper.launch { testHelper.sendTextMessage(room2, "New key", 1) } // - Try to backup all in aliceSession2, it must fail val keysBackup2 = aliceSession2.cryptoService().keysBackupService() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt index c3e795e8c74..0dfecffbded 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/replayattack/ReplayAttackTest.kt @@ -51,7 +51,7 @@ class ReplayAttackTest : InstrumentedTest { assertEquals(bobRoomPOV.roomSummary()?.joinedMembersCount, 2) // Alice will send a message - val sentEvents = testHelper.sendTextMessageSuspending(aliceRoomPOV, "Hello I will be decrypted twice", 1) + val sentEvents = testHelper.sendTextMessage(aliceRoomPOV, "Hello I will be decrypted twice", 1) assertEquals(1, sentEvents.size) val fakeEventId = sentEvents[0].eventId + "_fake" @@ -87,7 +87,7 @@ class ReplayAttackTest : InstrumentedTest { assertEquals(bobRoomPOV.roomSummary()?.joinedMembersCount, 2) // Alice will send a message - val sentEvents = testHelper.sendTextMessageSuspending(aliceRoomPOV, "Hello I will be decrypted twice", 1) + val sentEvents = testHelper.sendTextMessage(aliceRoomPOV, "Hello I will be decrypted twice", 1) Assert.assertTrue("Message should be sent", sentEvents.size == 1) assertEquals(sentEvents.size, 1) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt index 525c047ac4c..6ef90193d80 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/search/SearchMessagesTest.kt @@ -79,7 +79,7 @@ class SearchMessagesTest : InstrumentedTest { val aliceRoomId = cryptoTestData.roomId val roomFromAlicePOV = aliceSession.getRoom(aliceRoomId)!! - commonTestHelper.sendTextMessageSuspending( + commonTestHelper.sendTextMessage( roomFromAlicePOV, MESSAGE, 2 From a9361c766559c92d8194e31d9fd91e151ecc15ba Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:42:23 +0100 Subject: [PATCH 43/56] making all test doSync calls suspending instead of latch --- .../android/sdk/common/CommonTestHelper.kt | 22 +------------- .../android/sdk/common/CryptoTestHelper.kt | 2 +- .../sdk/internal/crypto/E2eeSanityTests.kt | 4 +-- .../sdk/internal/crypto/PreShareKeysTest.kt | 2 +- .../sdk/internal/crypto/UnwedgingTest.kt | 2 +- .../crypto/crosssigning/XSigningTest.kt | 18 +++++------ .../crypto/keysbackup/KeysBackupTest.kt | 30 +++++++++---------- .../crypto/keysbackup/KeysBackupTestHelper.kt | 4 +-- .../verification/qrcode/VerificationTest.kt | 4 +-- 9 files changed, 34 insertions(+), 54 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 5d4f608b6f1..5654cc1c8bd 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -477,27 +477,7 @@ class CommonTestHelper internal constructor(context: Context) { } } - // Transform a method with a MatrixCallback to a synchronous method - inline fun doSync(timeout: Long? = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { - val lock = CountDownLatch(1) - var result: T? = null - - val callback = object : TestMatrixCallback(lock) { - override fun onSuccess(data: T) { - result = data - super.onSuccess(data) - } - } - - block.invoke(callback) - - await(lock, timeout) - - assertNotNull(result) - return result!! - } - - suspend fun doSyncSuspending(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { + suspend fun doSync(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { return wrapWithTimeout(timeout) { suspendCoroutine { continuation -> val callback = object : MatrixCallback { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index e98648fa350..06331839689 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -221,7 +221,7 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } suspend fun initializeCrossSigning(session: Session) { - testHelper.doSyncSuspending { + testHelper.doSync { session.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index cedb06480f7..9d11c4e3560 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -216,10 +216,10 @@ class E2eeSanityTests : InstrumentedTest { Log.v("#E2E TEST", "Create and start key backup for bob ...") val bobKeysBackupService = bobSession.cryptoService().keysBackupService() val keyBackupPassword = "FooBarBaz" - val megolmBackupCreationInfo = testHelper.doSyncSuspending { + val megolmBackupCreationInfo = testHelper.doSync { bobKeysBackupService.prepareKeysBackupVersion(keyBackupPassword, null, it) } - val version = testHelper.doSyncSuspending { + val version = testHelper.doSync { bobKeysBackupService.createKeysBackupVersion(megolmBackupCreationInfo, it) } Log.v("#E2E TEST", "... Key backup started and enabled for bob") diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt index a4874528173..dc11cc14d08 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt @@ -52,7 +52,7 @@ class PreShareKeysTest : InstrumentedTest { Log.d("#Test", "Room Key Received from alice $preShareCount") // Force presharing of new outbound key - testHelper.doSyncSuspending { + testHelper.doSync { aliceSession.cryptoService().prepareToEncrypt(e2eRoomID, it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index baf3a088c5e..5ce13ca06ba 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -166,7 +166,7 @@ class UnwedgingTest : InstrumentedTest { Assert.assertTrue(messagesReceivedByBob[0].root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) // It's a trick to force key request on fail to decrypt - testHelper.doSyncSuspending { + testHelper.doSync { bobSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index cbcdf97e83f..ef3fdfeeda3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -101,14 +101,14 @@ class XSigningTest : InstrumentedTest { password = TestConstants.PASSWORD ) - testHelper.doSyncSuspending { + testHelper.doSync { aliceSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(aliceAuthParams) } }, it) } - testHelper.doSyncSuspending { + testHelper.doSync { bobSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(bobAuthParams) @@ -154,14 +154,14 @@ class XSigningTest : InstrumentedTest { password = TestConstants.PASSWORD ) - testHelper.doSyncSuspending { + testHelper.doSync { aliceSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(aliceAuthParams) } }, it) } - testHelper.doSyncSuspending { + testHelper.doSync { bobSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(bobAuthParams) @@ -171,12 +171,12 @@ class XSigningTest : InstrumentedTest { // Check that alice can see bob keys val bobUserId = bobSession.myUserId - testHelper.doSyncSuspending> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } + testHelper.doSync> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } val bobKeysFromAlicePOV = aliceSession.cryptoService().crossSigningService().getUserCrossSigningKeys(bobUserId) assertTrue("Bob keys from alice pov should not be trusted", bobKeysFromAlicePOV?.isTrusted() == false) - testHelper.doSyncSuspending { aliceSession.cryptoService().crossSigningService().trustUser(bobUserId, it) } + testHelper.doSync { aliceSession.cryptoService().crossSigningService().trustUser(bobUserId, it) } // Now bobs logs in on a new device and verifies it // We will want to test that in alice POV, this new device would be trusted by cross signing @@ -185,7 +185,7 @@ class XSigningTest : InstrumentedTest { val bobSecondDeviceId = bobSession2.sessionParams.deviceId!! // Check that bob first session sees the new login - val data = testHelper.doSyncSuspending> { + val data = testHelper.doSync> { bobSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } @@ -197,12 +197,12 @@ class XSigningTest : InstrumentedTest { assertNotNull("Bob Second device should be known and persisted from first", bobSecondDevicePOVFirstDevice) // Manually mark it as trusted from first session - testHelper.doSyncSuspending { + testHelper.doSync { bobSession.cryptoService().crossSigningService().trustDevice(bobSecondDeviceId, it) } // Now alice should cross trust bob's second device - val data2 = testHelper.doSyncSuspending> { + val data2 = testHelper.doSync> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index de3eda79feb..350b49dab4c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -142,14 +142,14 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled()) - val megolmBackupCreationInfo = testHelper.doSyncSuspending { + val megolmBackupCreationInfo = testHelper.doSync { keysBackup.prepareKeysBackupVersion(null, null, it) } assertFalse(keysBackup.isEnabled()) // Create the version - val version = testHelper.doSyncSuspending { + val version = testHelper.doSync { keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) } @@ -157,10 +157,10 @@ class KeysBackupTest : InstrumentedTest { assertTrue(keysBackup.isEnabled()) // Check that it's signed with MSK - val versionResult = testHelper.doSyncSuspending { + val versionResult = testHelper.doSync { keysBackup.getVersion(version.version, it) } - val trust = testHelper.doSyncSuspending { + val trust = testHelper.doSync { keysBackup.getKeysBackupTrust(versionResult!!, it) } @@ -378,7 +378,7 @@ class KeysBackupTest : InstrumentedTest { // assertTrue(unsentRequest != null || sentRequest != null) // // // - Restore the e2e backup from the homeserver -// val importRoomKeysResult = mTestHelper.doSync { +// val importRoomKeysResult = mTestHelper.doSyncSuspending<> { } { // testData.aliceSession2.cryptoService().keysBackupService().restoreKeysWithRecoveryKey(testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, // testData.prepareKeysBackupDataResult.megolmBackupCreationInfo.recoveryKey, // null, @@ -428,7 +428,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device - testHelper.doSyncSuspending { + testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersion( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, true, @@ -444,14 +444,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSyncSuspending { + val keysVersionResult = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSyncSuspending { + val keysBackupVersionTrust = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -488,7 +488,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device with the recovery key - testHelper.doSyncSuspending { + testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithRecoveryKey( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, testData.prepareKeysBackupDataResult.megolmBackupCreationInfo.recoveryKey, @@ -504,14 +504,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSyncSuspending { + val keysVersionResult = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSyncSuspending { + val keysBackupVersionTrust = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -590,7 +590,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device with the password - testHelper.doSyncSuspending { + testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithPassphrase( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, password, @@ -606,14 +606,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSyncSuspending { + val keysVersionResult = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSyncSuspending { + val keysBackupVersionTrust = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -717,7 +717,7 @@ class KeysBackupTest : InstrumentedTest { // - Restore the e2e backup with the password val steps = ArrayList() - val importRoomKeysResult = testHelper.doSyncSuspending { + val importRoomKeysResult = testHelper.doSync { testData.aliceSession2.cryptoService().keysBackupService().restoreKeyBackupWithPassword( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, password, diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt index a5d20a7cd28..36a567cc237 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -65,7 +65,7 @@ internal class KeysBackupTestHelper( var lastProgress = 0 var lastTotal = 0 - testHelper.doSyncSuspending { + testHelper.doSync { keysBackup.backupAllGroupSessions(object : ProgressListener { override fun onProgress(progress: Int, total: Int) { lastProgress = progress @@ -98,7 +98,7 @@ internal class KeysBackupTestHelper( ) } - fun prepareAndCreateKeysBackupData( + suspend fun prepareAndCreateKeysBackupData( keysBackup: KeysBackupService, password: String? = null ): PrepareKeysBackupDataResult { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 597c43b96a1..7172d098070 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -164,7 +164,7 @@ class VerificationTest : InstrumentedTest { val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession!! - testHelper.doSyncSuspending { callback -> + testHelper.doSync { callback -> aliceSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { @@ -181,7 +181,7 @@ class VerificationTest : InstrumentedTest { ) } - testHelper.doSyncSuspending { callback -> + testHelper.doSync { callback -> bobSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { From ae51bfe72bd0085a77cc0791fcd0b8bb085a5957 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:47:37 +0100 Subject: [PATCH 44/56] removing no longer needed test runBlocking or launch --- .../sdk/account/DeactivateAccountTest.kt | 54 +++--- .../android/sdk/common/CommonTestHelper.kt | 22 +-- .../crypto/E2eeShareKeysHistoryTest.kt | 28 ++- .../crypto/gossiping/KeyShareTests.kt | 28 ++- .../crypto/gossiping/WithHeldTests.kt | 4 +- .../crypto/keysbackup/KeysBackupTest.kt | 4 +- .../sdk/internal/crypto/ssss/QuadSTests.kt | 160 +++++++----------- .../internal/crypto/verification/SASTest.kt | 14 +- .../sdk/session/space/SpaceHierarchyTest.kt | 2 +- 9 files changed, 126 insertions(+), 190 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt index 0b21f85742d..515b687ee87 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/account/DeactivateAccountTest.kt @@ -44,22 +44,20 @@ class DeactivateAccountTest : InstrumentedTest { val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = true)) // Deactivate the account - commonTestHelper.runBlockingTest { - session.accountService().deactivateAccount( - eraseAllData = false, - userInteractiveAuthInterceptor = object : UserInteractiveAuthInterceptor { - override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { - promise.resume( - UserPasswordAuth( - user = session.myUserId, - password = TestConstants.PASSWORD, - session = flowResponse.session - ) - ) - } + session.accountService().deactivateAccount( + eraseAllData = false, + userInteractiveAuthInterceptor = object : UserInteractiveAuthInterceptor { + override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { + promise.resume( + UserPasswordAuth( + user = session.myUserId, + password = TestConstants.PASSWORD, + session = flowResponse.session + ) + ) } - ) - } + } + ) // Try to login on the previous account, it will fail (M_USER_DEACTIVATED) val throwable = commonTestHelper.logAccountWithError(session.myUserId, TestConstants.PASSWORD) @@ -74,23 +72,19 @@ class DeactivateAccountTest : InstrumentedTest { // Try to create an account with the deactivate account user id, it will fail (M_USER_IN_USE) val hs = commonTestHelper.createHomeServerConfig() - commonTestHelper.runBlockingTest { - commonTestHelper.matrix.authenticationService.getLoginFlow(hs) - } + commonTestHelper.matrix.authenticationService.getLoginFlow(hs) var accountCreationError: Throwable? = null - commonTestHelper.runBlockingTest { - try { - commonTestHelper.matrix.authenticationService - .getRegistrationWizard() - .createAccount( - session.myUserId.substringAfter("@").substringBefore(":"), - TestConstants.PASSWORD, - null - ) - } catch (failure: Throwable) { - accountCreationError = failure - } + try { + commonTestHelper.matrix.authenticationService + .getRegistrationWizard() + .createAccount( + session.myUserId.substringAfter("@").substringBefore(":"), + TestConstants.PASSWORD, + null + ) + } catch (failure: Throwable) { + accountCreationError = failure } // Test the error diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 5654cc1c8bd..e9803426571 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -378,18 +378,15 @@ class CommonTestHelper internal constructor(context: Context) { * @param userName the account username * @param password the password */ - fun logAccountWithError( + suspend fun logAccountWithError( userName: String, password: String ): Throwable { val hs = createHomeServerConfig() - runBlockingTest { - matrix.authenticationService.getLoginFlow(hs) - } + matrix.authenticationService.getLoginFlow(hs) var requestFailure: Throwable? = null - runBlockingTest { try { matrix.authenticationService .getLoginWizard() @@ -397,7 +394,6 @@ class CommonTestHelper internal constructor(context: Context) { } catch (failure: Throwable) { requestFailure = failure } - } assertNotNull(requestFailure) return requestFailure!! @@ -455,12 +451,6 @@ class CommonTestHelper internal constructor(context: Context) { } } - fun launch(block: suspend () -> T): T { - return runBlocking { - block() - } - } - fun waitWithLatch(timeout: Long? = TestConstants.timeOutMillis, dispatcher: CoroutineDispatcher = Dispatchers.Main, block: suspend (CountDownLatch) -> Unit) { val latch = CountDownLatch(1) val job = coroutineScope.launch(dispatcher) { @@ -469,14 +459,6 @@ class CommonTestHelper internal constructor(context: Context) { await(latch, timeout, job) } - fun runBlockingTest(timeout: Long = TestConstants.timeOutMillis, block: suspend () -> T): T { - return runBlocking { - wrapWithTimeout(timeout) { - block() - } - } - } - suspend fun doSync(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { return wrapWithTimeout(timeout) { suspendCoroutine { continuation -> diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt index 55524eada68..c078bcf03be 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeShareKeysHistoryTest.kt @@ -277,21 +277,19 @@ class E2eeShareKeysHistoryTest : InstrumentedTest { var secondAliceMessageSessionId: String? = null sendMessageInRoom(aliceRoomPOV, "Other msg", testHelper)?.let { secondMessage -> - testHelper.launch { - testHelper.retryPeriodically { - val timelineEvent = bobRoomPov - ?.timelineService() - ?.getTimelineEvent(secondMessage) - (timelineEvent != null && - timelineEvent.isEncrypted() && - timelineEvent.root.getClearType() == EventType.MESSAGE).also { - if (it) { - secondAliceMessageSessionId = timelineEvent?.root?.content?.get("session_id") as? String - Log.v( - "#E2E TEST", - "Bob can decrypt the message (sid:$secondAliceMessageSessionId): ${timelineEvent?.root?.getDecryptedTextSummary()}" - ) - } + testHelper.retryPeriodically { + val timelineEvent = bobRoomPov + ?.timelineService() + ?.getTimelineEvent(secondMessage) + (timelineEvent != null && + timelineEvent.isEncrypted() && + timelineEvent.root.getClearType() == EventType.MESSAGE).also { + if (it) { + secondAliceMessageSessionId = timelineEvent?.root?.content?.get("session_id") as? String + Log.v( + "#E2E TEST", + "Bob can decrypt the message (sid:$secondAliceMessageSessionId): ${timelineEvent?.root?.getDecryptedTextSummary()}" + ) } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index f2fdb76dd47..4a26841dc26 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -63,14 +63,12 @@ class KeyShareTests : InstrumentedTest { Log.v("TEST", "=======> AliceSession 1 is ${aliceSession.sessionParams.deviceId}") // Create an encrypted room and add a message - val roomId = commonTestHelper.runBlockingTest { - aliceSession.roomService().createRoom( - CreateRoomParams().apply { - visibility = RoomDirectoryVisibility.PRIVATE - enableEncryption() - } - ) - } + val roomId = aliceSession.roomService().createRoom( + CreateRoomParams().apply { + visibility = RoomDirectoryVisibility.PRIVATE + enableEncryption() + } + ) val room = aliceSession.getRoom(roomId) assertNotNull(room) Thread.sleep(4_000) @@ -94,10 +92,8 @@ class KeyShareTests : InstrumentedTest { assertNotNull(receivedEvent) assert(receivedEvent!!.isEncrypted()) - commonTestHelper.runBlockingTest { - mustFail { - aliceSession2.cryptoService().decryptEvent(receivedEvent.root, "foo") - } + mustFail { + aliceSession2.cryptoService().decryptEvent(receivedEvent.root, "foo") } val outgoingRequestsBefore = aliceSession2.cryptoService().getOutgoingRoomKeyRequests() @@ -165,10 +161,8 @@ class KeyShareTests : InstrumentedTest { } } - commonTestHelper.runBlockingTest { - mustFail { - aliceSession2.cryptoService().decryptEvent(receivedEvent.root, "foo") - } + mustFail { + aliceSession2.cryptoService().decryptEvent(receivedEvent.root, "foo") } // Mark the device as trusted @@ -226,7 +220,7 @@ class KeyShareTests : InstrumentedTest { @Test fun test_reShareToUnverifiedIfWasIntendedToBeShared() = runCryptoTest(context()) { cryptoTestHelper, commonTestHelper -> - val testData = cryptoTestHelper.testHelper.launch { cryptoTestHelper.doE2ETestWithAliceInARoom(true) } + val testData = cryptoTestHelper.doE2ETestWithAliceInARoom(true) val aliceSession = testData.firstSession val roomFromAlice = aliceSession.getRoom(testData.roomId)!! diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt index 9ce2403e3ba..b4b430484e4 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/WithHeldTests.kt @@ -246,9 +246,7 @@ class WithHeldTests : InstrumentedTest { val timeLineEvent = bobSecondSession.getRoom(testData.roomId)?.getTimelineEvent(eventId)?.also { // try to decrypt and force key request tryOrNull { - testHelper.runBlockingTest { - bobSecondSession.cryptoService().decryptEvent(it.root, "") - } + bobSecondSession.cryptoService().decryptEvent(it.root, "") } } sessionId = timeLineEvent?.root?.content?.toModel()?.sessionId diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index 350b49dab4c..21d3784ce18 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -298,7 +298,7 @@ class KeysBackupTest : InstrumentedTest { val keyBackupCreationInfo = keysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup).megolmBackupCreationInfo // - Check encryptGroupSession() returns stg - val keyBackupData = testHelper.runBlockingTest { keysBackup.encryptGroupSession(session) } + val keyBackupData = keysBackup.encryptGroupSession(session) assertNotNull(keyBackupData) assertNotNull(keyBackupData!!.sessionData) @@ -1006,7 +1006,7 @@ class KeysBackupTest : InstrumentedTest { val room2 = aliceSession2.getRoom(cryptoTestData.roomId)!! - testHelper.launch { testHelper.sendTextMessage(room2, "New key", 1) } + testHelper.sendTextMessage(room2, "New key", 1) // - Try to backup all in aliceSession2, it must fail val keysBackup2 = aliceSession2.cryptoService().keysBackupService() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt index c8be6aae74e..9700ee0d916 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt @@ -64,9 +64,7 @@ class QuadSTests : InstrumentedTest { val TEST_KEY_ID = "my.test.Key" - testHelper.runBlockingTest { - quadS.generateKey(TEST_KEY_ID, null, "Test Key", emptyKeySigner) - } + quadS.generateKey(TEST_KEY_ID, null, "Test Key", emptyKeySigner) var accountData: UserAccountDataEvent? = null // Assert Account data is updated @@ -118,13 +116,11 @@ class QuadSTests : InstrumentedTest { // Store a secret val clearSecret = "42".toByteArray().toBase64NoPadding() - testHelper.runBlockingTest { - aliceSession.sharedSecretStorageService().storeSecret( - "secret.of.life", - clearSecret, - listOf(KeyRef(null, keySpec)) // default key - ) - } + aliceSession.sharedSecretStorageService().storeSecret( + "secret.of.life", + clearSecret, + listOf(KeyRef(null, keySpec)) // default key + ) val secretAccountData = assertAccountData(testHelper, aliceSession, "secret.of.life") @@ -139,13 +135,11 @@ class QuadSTests : InstrumentedTest { // Try to decrypt?? - val decryptedSecret = testHelper.runBlockingTest { - aliceSession.sharedSecretStorageService().getSecret( - "secret.of.life", - null, // default key - keySpec!! - ) - } + val decryptedSecret = aliceSession.sharedSecretStorageService().getSecret( + "secret.of.life", + null, // default key + keySpec!! + ) assertEquals("Secret mismatch", clearSecret, decryptedSecret) } @@ -159,14 +153,10 @@ class QuadSTests : InstrumentedTest { val TEST_KEY_ID = "my.test.Key" - testHelper.runBlockingTest { - quadS.generateKey(TEST_KEY_ID, null, "Test Key", emptyKeySigner) - } + quadS.generateKey(TEST_KEY_ID, null, "Test Key", emptyKeySigner) // Test that we don't need to wait for an account data sync to access directly the keyid from DB - testHelper.runBlockingTest { - quadS.setDefaultKey(TEST_KEY_ID) - } + quadS.setDefaultKey(TEST_KEY_ID) } @Test @@ -180,16 +170,14 @@ class QuadSTests : InstrumentedTest { val mySecretText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" - testHelper.runBlockingTest { - aliceSession.sharedSecretStorageService().storeSecret( - "my.secret", - mySecretText.toByteArray().toBase64NoPadding(), - listOf( - KeyRef(keyId1, RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey)), - KeyRef(keyId2, RawBytesKeySpec.fromRecoveryKey(key2Info.recoveryKey)) - ) - ) - } + aliceSession.sharedSecretStorageService().storeSecret( + "my.secret", + mySecretText.toByteArray().toBase64NoPadding(), + listOf( + KeyRef(keyId1, RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey)), + KeyRef(keyId2, RawBytesKeySpec.fromRecoveryKey(key2Info.recoveryKey)) + ) + ) val accountDataEvent = aliceSession.accountDataService().getUserAccountDataEvent("my.secret") val encryptedContent = accountDataEvent?.content?.get("encrypted") as? Map<*, *> @@ -200,21 +188,17 @@ class QuadSTests : InstrumentedTest { assertNotNull(encryptedContent?.get(keyId2)) // Assert that can decrypt with both keys - testHelper.runBlockingTest { - aliceSession.sharedSecretStorageService().getSecret( - "my.secret", - keyId1, - RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey)!! - ) - } - - testHelper.runBlockingTest { - aliceSession.sharedSecretStorageService().getSecret( - "my.secret", - keyId2, - RawBytesKeySpec.fromRecoveryKey(key2Info.recoveryKey)!! - ) - } + aliceSession.sharedSecretStorageService().getSecret( + "my.secret", + keyId1, + RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey)!! + ) + + aliceSession.sharedSecretStorageService().getSecret( + "my.secret", + keyId2, + RawBytesKeySpec.fromRecoveryKey(key2Info.recoveryKey)!! + ) } @Test @@ -228,44 +212,38 @@ class QuadSTests : InstrumentedTest { val mySecretText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" - testHelper.runBlockingTest { - aliceSession.sharedSecretStorageService().storeSecret( - "my.secret", - mySecretText.toByteArray().toBase64NoPadding(), - listOf(KeyRef(keyId1, RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey))) - ) - } - - testHelper.runBlockingTest { - try { - aliceSession.sharedSecretStorageService().getSecret( - "my.secret", - keyId1, - RawBytesKeySpec.fromPassphrase( - "A bad passphrase", - key1Info.content?.passphrase?.salt ?: "", - key1Info.content?.passphrase?.iterations ?: 0, - null - ) - ) - } catch (throwable: Throwable) { - assert(throwable is SharedSecretStorageError.BadMac) - } - } + aliceSession.sharedSecretStorageService().storeSecret( + "my.secret", + mySecretText.toByteArray().toBase64NoPadding(), + listOf(KeyRef(keyId1, RawBytesKeySpec.fromRecoveryKey(key1Info.recoveryKey))) + ) - // Now try with correct key - testHelper.runBlockingTest { + try { aliceSession.sharedSecretStorageService().getSecret( "my.secret", keyId1, RawBytesKeySpec.fromPassphrase( - passphrase, + "A bad passphrase", key1Info.content?.passphrase?.salt ?: "", key1Info.content?.passphrase?.iterations ?: 0, null ) ) + } catch (throwable: Throwable) { + assert(throwable is SharedSecretStorageError.BadMac) } + + // Now try with correct key + aliceSession.sharedSecretStorageService().getSecret( + "my.secret", + keyId1, + RawBytesKeySpec.fromPassphrase( + passphrase, + key1Info.content?.passphrase?.salt ?: "", + key1Info.content?.passphrase?.iterations ?: 0, + null + ) + ) } private fun assertAccountData(testHelper: CommonTestHelper, session: Session, type: String): UserAccountDataEvent { @@ -284,43 +262,35 @@ class QuadSTests : InstrumentedTest { return accountData!! } - private fun generatedSecret(testHelper: CommonTestHelper, session: Session, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { + private suspend fun generatedSecret(testHelper: CommonTestHelper, session: Session, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { val quadS = session.sharedSecretStorageService() - val creationInfo = testHelper.runBlockingTest { - quadS.generateKey(keyId, null, keyId, emptyKeySigner) - } + val creationInfo = quadS.generateKey(keyId, null, keyId, emptyKeySigner) assertAccountData(testHelper, session, "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$keyId") if (asDefault) { - testHelper.runBlockingTest { - quadS.setDefaultKey(keyId) - } + quadS.setDefaultKey(keyId) assertAccountData(testHelper, session, DefaultSharedSecretStorageService.DEFAULT_KEY_ID) } return creationInfo } - private fun generatedSecretFromPassphrase(testHelper: CommonTestHelper, session: Session, passphrase: String, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { + private suspend fun generatedSecretFromPassphrase(testHelper: CommonTestHelper, session: Session, passphrase: String, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { val quadS = session.sharedSecretStorageService() - val creationInfo = testHelper.runBlockingTest { - quadS.generateKeyWithPassphrase( - keyId, - keyId, - passphrase, - emptyKeySigner, - null - ) - } + val creationInfo = quadS.generateKeyWithPassphrase( + keyId, + keyId, + passphrase, + emptyKeySigner, + null + ) assertAccountData(testHelper, session, "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$keyId") if (asDefault) { - testHelper.runBlockingTest { - quadS.setDefaultKey(keyId) - } + quadS.setDefaultKey(keyId) assertAccountData(testHelper, session, DefaultSharedSecretStorageService.DEFAULT_KEY_ID) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index 4419cdde19a..1bffbeeeaa9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -195,7 +195,7 @@ class SASTest : InstrumentedTest { @Ignore("This test will be ignored until it is fixed") fun test_key_agreement_macs_Must_include_hmac_sha256() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val bobSession = cryptoTestData.secondSession!! @@ -232,7 +232,7 @@ class SASTest : InstrumentedTest { @Ignore("This test will be ignored until it is fixed") fun test_key_agreement_short_code_include_decimal() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> fail("Not passing for the moment") - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val bobSession = cryptoTestData.secondSession!! @@ -301,7 +301,7 @@ class SASTest : InstrumentedTest { // If a device has two verifications in progress with the same device, then it should cancel both verifications. @Test fun test_aliceStartTwoRequests() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -342,7 +342,7 @@ class SASTest : InstrumentedTest { @Test @Ignore("This test will be ignored until it is fixed") fun test_aliceAndBobAgreement() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -399,7 +399,7 @@ class SASTest : InstrumentedTest { @Test fun test_aliceAndBobSASCode() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -455,7 +455,7 @@ class SASTest : InstrumentedTest { @Test fun test_happyPath() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession @@ -531,7 +531,7 @@ class SASTest : InstrumentedTest { @Test fun test_ConcurrentStart() = runCryptoTest(context()) { cryptoTestHelper, testHelper -> - val cryptoTestData = testHelper.launch { cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() } + val cryptoTestData = cryptoTestHelper.doE2ETestWithAliceAndBobInARoom() val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt index ce2cde0b401..abe9af5e385 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceHierarchyTest.kt @@ -442,7 +442,7 @@ class SpaceHierarchyTest : InstrumentedTest { // + c1, c2 commonTestHelper.retryPeriodically { - val rootSpaces = commonTestHelper.runBlockingTest { session.spaceService().getRootSpaceSummaries() } + val rootSpaces = session.spaceService().getRootSpaceSummaries() rootSpaces.size == 2 } } From 5ed9e7583f3b3dbf9c38a6af8e6878a80c5aa82e Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 10:50:33 +0100 Subject: [PATCH 45/56] replacing remaining period wait with latch with suspending version --- .../android/sdk/common/CommonTestHelper.kt | 30 +-- .../crypto/gossiping/KeyShareTests.kt | 202 ++++++++---------- .../internal/crypto/verification/SASTest.kt | 52 ++--- .../verification/qrcode/VerificationTest.kt | 8 +- 4 files changed, 118 insertions(+), 174 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index e9803426571..f023be9830c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -54,7 +54,6 @@ import org.matrix.android.sdk.api.session.room.timeline.TimelineEvent import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import timber.log.Timber import java.util.UUID -import java.util.concurrent.CancellationException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.coroutines.resume @@ -387,13 +386,13 @@ class CommonTestHelper internal constructor(context: Context) { matrix.authenticationService.getLoginFlow(hs) var requestFailure: Throwable? = null - try { - matrix.authenticationService - .getLoginWizard() - .login(userName, password, "myDevice") - } catch (failure: Throwable) { - requestFailure = failure - } + try { + matrix.authenticationService + .getLoginWizard() + .login(userName, password, "myDevice") + } catch (failure: Throwable) { + requestFailure = failure + } assertNotNull(requestFailure) return requestFailure!! @@ -436,21 +435,6 @@ class CommonTestHelper internal constructor(context: Context) { } } - suspend fun retryPeriodicallyWithLatch(latch: CountDownLatch, condition: (() -> Boolean)) { - while (true) { - try { - delay(1000) - } catch (ex: CancellationException) { - // the job was canceled, just stop - return - } - if (condition()) { - latch.countDown() - return - } - } - } - fun waitWithLatch(timeout: Long? = TestConstants.timeOutMillis, dispatcher: CoroutineDispatcher = Dispatchers.Main, block: suspend (CountDownLatch) -> Unit) { val latch = CountDownLatch(1) val job = coroutineScope.launch(dispatcher) { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt index 4a26841dc26..60a89b43708 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/gossiping/KeyShareTests.kt @@ -107,15 +107,13 @@ class KeyShareTests : InstrumentedTest { var outGoingRequestId: String? = null - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - aliceSession2.cryptoService().getOutgoingRoomKeyRequests() - .let { - val outgoing = it.firstOrNull { it.sessionId == eventMegolmSessionId } - outGoingRequestId = outgoing?.requestId - outgoing != null - } - } + commonTestHelper.retryPeriodically { + aliceSession2.cryptoService().getOutgoingRoomKeyRequests() + .let { + val outgoing = it.firstOrNull { it.sessionId == eventMegolmSessionId } + outGoingRequestId = outgoing?.requestId + outgoing != null + } } Log.v("TEST", "=======> Outgoing requet Id is $outGoingRequestId") @@ -127,9 +125,8 @@ class KeyShareTests : InstrumentedTest { // The first session should see an incoming request // the request should be refused, because the device is not trusted - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - // DEBUG LOGS + commonTestHelper.retryPeriodically { + // DEBUG LOGS // aliceSession.cryptoService().getIncomingRoomKeyRequests().let { // Log.v("TEST", "Incoming request Session 1 (looking for $outGoingRequestId)") // Log.v("TEST", "=========================") @@ -139,26 +136,23 @@ class KeyShareTests : InstrumentedTest { // Log.v("TEST", "=========================") // } - val incoming = aliceSession.cryptoService().getIncomingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } - incoming != null - } + val incoming = aliceSession.cryptoService().getIncomingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } + incoming != null } - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - // DEBUG LOGS - aliceSession2.cryptoService().getOutgoingRoomKeyRequests().forEach { keyRequest -> - Log.v("TEST", "=========================") - Log.v("TEST", "requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") - Log.v("TEST", "replies -> ${keyRequest.results.joinToString { it.toString() }}") - Log.v("TEST", "=========================") - } - - val outgoing = aliceSession2.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } - val reply = outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } - val resultCode = (reply?.result as? RequestResult.Failure)?.code - resultCode == WithHeldCode.UNVERIFIED + commonTestHelper.retryPeriodically { + // DEBUG LOGS + aliceSession2.cryptoService().getOutgoingRoomKeyRequests().forEach { keyRequest -> + Log.v("TEST", "=========================") + Log.v("TEST", "requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") + Log.v("TEST", "replies -> ${keyRequest.results.joinToString { it.toString() }}") + Log.v("TEST", "=========================") } + + val outgoing = aliceSession2.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.requestId == outGoingRequestId } + val reply = outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val resultCode = (reply?.result as? RequestResult.Failure)?.code + resultCode == WithHeldCode.UNVERIFIED } mustFail { @@ -204,12 +198,10 @@ class KeyShareTests : InstrumentedTest { // As it was share previously alice should accept to reshare bobSession.cryptoService().reRequestRoomKeyForEvent(sentEvent.root) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val outgoing = bobSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val aliceReply = outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } - aliceReply != null && aliceReply.result is RequestResult.Success - } + commonTestHelper.retryPeriodically { + val outgoing = bobSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val aliceReply = outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + aliceReply != null && aliceReply.result is RequestResult.Success } } @@ -227,12 +219,10 @@ class KeyShareTests : InstrumentedTest { val aliceNewSession = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) // we wait for alice first session to be aware of that session? - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val newSession = aliceSession.cryptoService().getUserDevices(aliceSession.myUserId) - .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } - newSession != null - } + commonTestHelper.retryPeriodically { + val newSession = aliceSession.cryptoService().getUserDevices(aliceSession.myUserId) + .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } + newSession != null } val sentEvent = commonTestHelper.sendTextMessage(roomFromAlice, "Hello", 1).first() val sentEventMegolmSession = sentEvent.root.content.toModel()!!.sessionId!! @@ -241,13 +231,11 @@ class KeyShareTests : InstrumentedTest { // As it was share previously alice should accept to reshare aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvent.root) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val ownDeviceReply = - outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } - ownDeviceReply != null && ownDeviceReply.result is RequestResult.Success - } + commonTestHelper.retryPeriodically { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = + outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + ownDeviceReply != null && ownDeviceReply.result is RequestResult.Success } } @@ -271,12 +259,10 @@ class KeyShareTests : InstrumentedTest { commonTestHelper.syncSession(aliceNewSession) // we wait bob first session to be aware of that session? - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val newSession = bobSession.cryptoService().getUserDevices(aliceSession.myUserId) - .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } - newSession != null - } + commonTestHelper.retryPeriodically { + val newSession = bobSession.cryptoService().getUserDevices(aliceSession.myUserId) + .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } + newSession != null } val newEvent = commonTestHelper.sendTextMessage(roomFromBob, "The New", 1).first() @@ -298,26 +284,22 @@ class KeyShareTests : InstrumentedTest { aliceNewSession.cryptoService().enableKeyGossiping(true) aliceNewSession.cryptoService().reRequestRoomKeyForEvent(newEvent.root) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val ownDeviceReply = outgoing?.results - ?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } - val result = ownDeviceReply?.result - Log.v("TEST", "own device result is $result") - result != null && result is RequestResult.Failure && result.code == WithHeldCode.UNVERIFIED - } + commonTestHelper.retryPeriodically { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = outgoing?.results + ?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val result = ownDeviceReply?.result + Log.v("TEST", "own device result is $result") + result != null && result is RequestResult.Failure && result.code == WithHeldCode.UNVERIFIED } - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val bobDeviceReply = outgoing?.results - ?.firstOrNull { it.userId == bobSession.myUserId && it.fromDevice == bobSession.sessionParams.deviceId } - val result = bobDeviceReply?.result - Log.v("TEST", "bob device result is $result") - result != null && result is RequestResult.Success && result.chainIndex > 0 - } + commonTestHelper.retryPeriodically { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val bobDeviceReply = outgoing?.results + ?.firstOrNull { it.userId == bobSession.myUserId && it.fromDevice == bobSession.sessionParams.deviceId } + val result = bobDeviceReply?.result + Log.v("TEST", "bob device result is $result") + result != null && result is RequestResult.Success && result.chainIndex > 0 } // it's a success but still can't decrypt first message @@ -331,21 +313,19 @@ class KeyShareTests : InstrumentedTest { // Let's now try to request aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvents.first().root) - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - // DEBUG LOGS - aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().forEach { keyRequest -> - Log.v("TEST", "=========================") - Log.v("TEST", "requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") - Log.v("TEST", "replies -> ${keyRequest.results.joinToString { it.toString() }}") - Log.v("TEST", "=========================") - } - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val ownDeviceReply = - outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } - val result = ownDeviceReply?.result - result != null && result is RequestResult.Success && result.chainIndex == 0 + commonTestHelper.retryPeriodically { + // DEBUG LOGS + aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().forEach { keyRequest -> + Log.v("TEST", "=========================") + Log.v("TEST", "requestId ${keyRequest.requestId}, for sessionId ${keyRequest.requestBody?.sessionId}") + Log.v("TEST", "replies -> ${keyRequest.results.joinToString { it.toString() }}") + Log.v("TEST", "=========================") } + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = + outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val result = ownDeviceReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 0 } // now the new session should be able to decrypt all! @@ -357,13 +337,11 @@ class KeyShareTests : InstrumentedTest { ) // Additional test, can we check that bob replied successfully but with a ratcheted key - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId } - val result = bobReply?.result - result != null && result is RequestResult.Success && result.chainIndex == 3 - } + commonTestHelper.retryPeriodically { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId } + val result = bobReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 3 } commonTestHelper.signOutAndClose(aliceNewSession) @@ -388,12 +366,10 @@ class KeyShareTests : InstrumentedTest { val aliceNewSession = commonTestHelper.logIntoAccount(aliceSession.myUserId, SessionTestParams(true)) // we wait bob first session to be aware of that session? - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val newSession = bobSession.cryptoService().getUserDevices(aliceSession.myUserId) - .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } - newSession != null - } + commonTestHelper.retryPeriodically { + val newSession = bobSession.cryptoService().getUserDevices(aliceSession.myUserId) + .firstOrNull { it.deviceId == aliceNewSession.sessionParams.deviceId } + newSession != null } val newEvent = commonTestHelper.sendTextMessage(roomFromBob, "The New", 1).first() @@ -424,14 +400,12 @@ class KeyShareTests : InstrumentedTest { aliceNewSession.cryptoService().reRequestRoomKeyForEvent(sentEvents.first().root) // Should get a reply from bob and not from alice - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - // Log.d("#TEST", "outgoing key requests :${aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().joinToString { it.sessionId ?: "?" }}") - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId } - val result = bobReply?.result - result != null && result is RequestResult.Success && result.chainIndex == 3 - } + commonTestHelper.retryPeriodically { + // Log.d("#TEST", "outgoing key requests :${aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().joinToString { it.sessionId ?: "?" }}") + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val bobReply = outgoing?.results?.firstOrNull { it.userId == bobSession.myUserId } + val result = bobReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 3 } val outgoingReq = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } @@ -444,14 +418,12 @@ class KeyShareTests : InstrumentedTest { aliceSession.syncService().startSync(true) // We should now get a reply from first session - commonTestHelper.waitWithLatch { latch -> - commonTestHelper.retryPeriodicallyWithLatch(latch) { - val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } - val ownDeviceReply = - outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } - val result = ownDeviceReply?.result - result != null && result is RequestResult.Success && result.chainIndex == 0 - } + commonTestHelper.retryPeriodically { + val outgoing = aliceNewSession.cryptoService().getOutgoingRoomKeyRequests().firstOrNull { it.sessionId == sentEventMegolmSession } + val ownDeviceReply = + outgoing?.results?.firstOrNull { it.userId == aliceSession.myUserId && it.fromDevice == aliceSession.sessionParams.deviceId } + val result = ownDeviceReply?.result + result != null && result is RequestResult.Success && result.chainIndex == 0 } // It should be in sent then cancel diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt index 1bffbeeeaa9..fd2136edd5f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/SASTest.kt @@ -547,23 +547,19 @@ class SASTest : InstrumentedTest { var requestID: String? = null - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - val prAlicePOV = aliceVerificationService.getExistingVerificationRequests(bobSession.myUserId).firstOrNull() - requestID = prAlicePOV?.transactionId - Log.v("TEST", "== alicePOV is $prAlicePOV") - prAlicePOV?.transactionId != null && prAlicePOV.localId == req.localId - } + testHelper.retryPeriodically { + val prAlicePOV = aliceVerificationService.getExistingVerificationRequests(bobSession.myUserId).firstOrNull() + requestID = prAlicePOV?.transactionId + Log.v("TEST", "== alicePOV is $prAlicePOV") + prAlicePOV?.transactionId != null && prAlicePOV.localId == req.localId } Log.v("TEST", "== requestID is $requestID") - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - val prBobPOV = bobVerificationService.getExistingVerificationRequests(aliceSession.myUserId).firstOrNull() - Log.v("TEST", "== prBobPOV is $prBobPOV") - prBobPOV?.transactionId == requestID - } + testHelper.retryPeriodically { + val prBobPOV = bobVerificationService.getExistingVerificationRequests(aliceSession.myUserId).firstOrNull() + Log.v("TEST", "== prBobPOV is $prBobPOV") + prBobPOV?.transactionId == requestID } bobVerificationService.readyPendingVerification( @@ -573,12 +569,10 @@ class SASTest : InstrumentedTest { ) // wait for alice to get the ready - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - val prAlicePOV = aliceVerificationService.getExistingVerificationRequests(bobSession.myUserId).firstOrNull() - Log.v("TEST", "== prAlicePOV is $prAlicePOV") - prAlicePOV?.transactionId == requestID && prAlicePOV?.isReady != null - } + testHelper.retryPeriodically { + val prAlicePOV = aliceVerificationService.getExistingVerificationRequests(bobSession.myUserId).firstOrNull() + Log.v("TEST", "== prAlicePOV is $prAlicePOV") + prAlicePOV?.transactionId == requestID && prAlicePOV?.isReady != null } // Start concurrent! @@ -602,20 +596,16 @@ class SASTest : InstrumentedTest { var alicePovTx: SasVerificationTransaction? var bobPovTx: SasVerificationTransaction? - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - alicePovTx = aliceVerificationService.getExistingTransaction(bobSession.myUserId, requestID!!) as? SasVerificationTransaction - Log.v("TEST", "== alicePovTx is $alicePovTx") - alicePovTx?.state == VerificationTxState.ShortCodeReady - } + testHelper.retryPeriodically { + alicePovTx = aliceVerificationService.getExistingTransaction(bobSession.myUserId, requestID!!) as? SasVerificationTransaction + Log.v("TEST", "== alicePovTx is $alicePovTx") + alicePovTx?.state == VerificationTxState.ShortCodeReady } // wait for alice to get the ready - testHelper.waitWithLatch { - testHelper.retryPeriodicallyWithLatch(it) { - bobPovTx = bobVerificationService.getExistingTransaction(aliceSession.myUserId, requestID!!) as? SasVerificationTransaction - Log.v("TEST", "== bobPovTx is $bobPovTx") - bobPovTx?.state == VerificationTxState.ShortCodeReady - } + testHelper.retryPeriodically { + bobPovTx = bobVerificationService.getExistingTransaction(aliceSession.myUserId, requestID!!) as? SasVerificationTransaction + Log.v("TEST", "== bobPovTx is $bobPovTx") + bobPovTx?.state == VerificationTxState.ShortCodeReady } } } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 7172d098070..3c45706c37a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -290,11 +290,9 @@ class VerificationTest : InstrumentedTest { otherDevices = listOfNotNull(aliceSessionThatVerifies.sessionParams.deviceId, aliceSessionThatReceivesCanceledEvent.sessionParams.deviceId), ) - testHelper.waitWithLatch { latch -> - testHelper.retryPeriodicallyWithLatch(latch) { - val requests = serviceOfUserWhoReceivesCancellation.getExistingVerificationRequests(aliceSessionToVerify.myUserId) - requests.any { it.cancelConclusion == CancelCode.AcceptedByAnotherDevice } - } + testHelper.retryPeriodically { + val requests = serviceOfUserWhoReceivesCancellation.getExistingVerificationRequests(aliceSessionToVerify.myUserId) + requests.any { it.cancelConclusion == CancelCode.AcceptedByAnotherDevice } } testHelper.signOutAndClose(aliceSessionToVerify) From 707f3bfa8c4ec3ff7555818a2f7a0ffea60d01cd Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 11:12:12 +0100 Subject: [PATCH 46/56] replacing remaining latched wait usages with suspends --- .../android/sdk/common/CommonTestHelper.kt | 10 --- .../sdk/internal/crypto/ssss/QuadSTests.kt | 80 +++++++------------ .../TimelineSimpleBackPaginationTest.kt | 49 +++++++----- 3 files changed, 60 insertions(+), 79 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index f023be9830c..20cc7fe1175 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -20,7 +20,6 @@ import android.content.Context import android.net.Uri import android.util.Log import androidx.test.internal.runner.junit4.statement.UiThreadStatement -import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -28,7 +27,6 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay -import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext @@ -435,14 +433,6 @@ class CommonTestHelper internal constructor(context: Context) { } } - fun waitWithLatch(timeout: Long? = TestConstants.timeOutMillis, dispatcher: CoroutineDispatcher = Dispatchers.Main, block: suspend (CountDownLatch) -> Unit) { - val latch = CountDownLatch(1) - val job = coroutineScope.launch(dispatcher) { - block(latch) - } - await(latch, timeout, job) - } - suspend fun doSync(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { return wrapWithTimeout(timeout) { suspendCoroutine { continuation -> diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt index 9700ee0d916..0467d082a33 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/ssss/QuadSTests.kt @@ -16,7 +16,6 @@ package org.matrix.android.sdk.internal.crypto.ssss -import androidx.lifecycle.Observer import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -37,12 +36,12 @@ import org.matrix.android.sdk.api.session.securestorage.RawBytesKeySpec import org.matrix.android.sdk.api.session.securestorage.SecretStorageKeyContent import org.matrix.android.sdk.api.session.securestorage.SharedSecretStorageError import org.matrix.android.sdk.api.session.securestorage.SsssKeyCreationInfo -import org.matrix.android.sdk.api.util.Optional import org.matrix.android.sdk.api.util.toBase64NoPadding -import org.matrix.android.sdk.common.CommonTestHelper import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.SessionTestParams import org.matrix.android.sdk.common.TestConstants +import org.matrix.android.sdk.common.first +import org.matrix.android.sdk.common.onMain import org.matrix.android.sdk.internal.crypto.secrets.DefaultSharedSecretStorageService @RunWith(AndroidJUnit4::class) @@ -66,18 +65,12 @@ class QuadSTests : InstrumentedTest { quadS.generateKey(TEST_KEY_ID, null, "Test Key", emptyKeySigner) - var accountData: UserAccountDataEvent? = null // Assert Account data is updated - testHelper.waitWithLatch { - val liveAccountData = aliceSession.accountDataService().getLiveUserAccountDataEvent("${DefaultSharedSecretStorageService.KEY_ID_BASE}.$TEST_KEY_ID") - val accountDataObserver = Observer?> { t -> - if (t?.getOrNull()?.type == "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$TEST_KEY_ID") { - accountData = t.getOrNull() - } - it.countDown() - } - liveAccountData.observeForever(accountDataObserver) - } + val accountData = aliceSession.accountDataService() + .onMain { getLiveUserAccountDataEvent("${DefaultSharedSecretStorageService.KEY_ID_BASE}.$TEST_KEY_ID") } + .first { it.getOrNull()?.type == "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$TEST_KEY_ID" } + .getOrNull() + assertNotNull("Key should be stored in account data", accountData) val parsed = SecretStorageKeyContent.fromJson(accountData!!.content) assertNotNull("Key Content cannot be parsed", parsed) @@ -85,20 +78,13 @@ class QuadSTests : InstrumentedTest { assertEquals("Unexpected key name", "Test Key", parsed.name) assertNull("Key was not generated from passphrase", parsed.passphrase) - var defaultKeyAccountData: UserAccountDataEvent? = null + quadS.setDefaultKey(TEST_KEY_ID) + val defaultKeyAccountData = aliceSession.accountDataService() + .onMain { getLiveUserAccountDataEvent(DefaultSharedSecretStorageService.DEFAULT_KEY_ID) } + .first { it.getOrNull()?.type == DefaultSharedSecretStorageService.DEFAULT_KEY_ID } + .getOrNull() + // Set as default key - testHelper.waitWithLatch { latch -> - quadS.setDefaultKey(TEST_KEY_ID) - val liveDefAccountData = - aliceSession.accountDataService().getLiveUserAccountDataEvent(DefaultSharedSecretStorageService.DEFAULT_KEY_ID) - val accountDefDataObserver = Observer?> { t -> - if (t?.getOrNull()?.type == DefaultSharedSecretStorageService.DEFAULT_KEY_ID) { - defaultKeyAccountData = t.getOrNull()!! - latch.countDown() - } - } - liveDefAccountData.observeForever(accountDefDataObserver) - } assertNotNull(defaultKeyAccountData?.content) assertEquals("Unexpected default key ${defaultKeyAccountData?.content}", TEST_KEY_ID, defaultKeyAccountData?.content?.get("key")) @@ -110,7 +96,7 @@ class QuadSTests : InstrumentedTest { val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId = "My.Key" - val info = generatedSecret(testHelper, aliceSession, keyId, true) + val info = generatedSecret(aliceSession, keyId, true) val keySpec = RawBytesKeySpec.fromRecoveryKey(info.recoveryKey) @@ -122,7 +108,7 @@ class QuadSTests : InstrumentedTest { listOf(KeyRef(null, keySpec)) // default key ) - val secretAccountData = assertAccountData(testHelper, aliceSession, "secret.of.life") + val secretAccountData = assertAccountData(aliceSession, "secret.of.life") val encryptedContent = secretAccountData.content["encrypted"] as? Map<*, *> assertNotNull("Element should be encrypted", encryptedContent) @@ -164,9 +150,9 @@ class QuadSTests : InstrumentedTest { val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId1 = "Key.1" - val key1Info = generatedSecret(testHelper, aliceSession, keyId1, true) + val key1Info = generatedSecret(aliceSession, keyId1, true) val keyId2 = "Key2" - val key2Info = generatedSecret(testHelper, aliceSession, keyId2, true) + val key2Info = generatedSecret(aliceSession, keyId2, true) val mySecretText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" @@ -208,7 +194,7 @@ class QuadSTests : InstrumentedTest { val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) val keyId1 = "Key.1" val passphrase = "The good pass phrase" - val key1Info = generatedSecretFromPassphrase(testHelper, aliceSession, passphrase, keyId1, true) + val key1Info = generatedSecretFromPassphrase(aliceSession, passphrase, keyId1, true) val mySecretText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" @@ -246,38 +232,32 @@ class QuadSTests : InstrumentedTest { ) } - private fun assertAccountData(testHelper: CommonTestHelper, session: Session, type: String): UserAccountDataEvent { - var accountData: UserAccountDataEvent? = null - testHelper.waitWithLatch { - val liveAccountData = session.accountDataService().getLiveUserAccountDataEvent(type) - val accountDataObserver = Observer?> { t -> - if (t?.getOrNull()?.type == type) { - accountData = t.getOrNull() - it.countDown() - } - } - liveAccountData.observeForever(accountDataObserver) - } + private suspend fun assertAccountData(session: Session, type: String): UserAccountDataEvent { + val accountData = session.accountDataService() + .onMain { getLiveUserAccountDataEvent(type) } + .first { it.getOrNull()?.type == type } + .getOrNull() + assertNotNull("Account Data type:$type should be found", accountData) return accountData!! } - private suspend fun generatedSecret(testHelper: CommonTestHelper, session: Session, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { + private suspend fun generatedSecret(session: Session, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { val quadS = session.sharedSecretStorageService() val creationInfo = quadS.generateKey(keyId, null, keyId, emptyKeySigner) - assertAccountData(testHelper, session, "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$keyId") + assertAccountData(session, "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$keyId") if (asDefault) { quadS.setDefaultKey(keyId) - assertAccountData(testHelper, session, DefaultSharedSecretStorageService.DEFAULT_KEY_ID) + assertAccountData(session, DefaultSharedSecretStorageService.DEFAULT_KEY_ID) } return creationInfo } - private suspend fun generatedSecretFromPassphrase(testHelper: CommonTestHelper, session: Session, passphrase: String, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { + private suspend fun generatedSecretFromPassphrase(session: Session, passphrase: String, keyId: String, asDefault: Boolean = true): SsssKeyCreationInfo { val quadS = session.sharedSecretStorageService() val creationInfo = quadS.generateKeyWithPassphrase( @@ -288,10 +268,10 @@ class QuadSTests : InstrumentedTest { null ) - assertAccountData(testHelper, session, "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$keyId") + assertAccountData(session, "${DefaultSharedSecretStorageService.KEY_ID_BASE}.$keyId") if (asDefault) { quadS.setDefaultKey(keyId) - assertAccountData(testHelper, session, DefaultSharedSecretStorageService.DEFAULT_KEY_ID) + assertAccountData(session, DefaultSharedSecretStorageService.DEFAULT_KEY_ID) } return creationInfo diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt index 59b3b145322..160d6d1cf0c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt @@ -18,6 +18,7 @@ package org.matrix.android.sdk.session.room.timeline import androidx.test.filters.LargeTest import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.suspendCancellableCoroutine import org.amshove.kluent.internal.assertEquals import org.junit.FixMethodOrder import org.junit.Ignore @@ -35,6 +36,9 @@ import org.matrix.android.sdk.api.session.room.timeline.Timeline import org.matrix.android.sdk.api.session.room.timeline.TimelineSettings import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.TestConstants +import org.matrix.android.sdk.common.waitFor +import org.matrix.android.sdk.common.wrapWithTimeout +import kotlin.coroutines.resume @RunWith(JUnit4::class) @FixMethodOrder(MethodSorters.JVM) @@ -69,30 +73,37 @@ class TimelineSimpleBackPaginationTest : InstrumentedTest { val bobTimeline = roomFromBobPOV.timelineService().createTimeline(null, TimelineSettings(30)) bobTimeline.start() - commonTestHelper.waitWithLatch(timeout = TestConstants.timeOutMillis * 10) { - val listener = object : Timeline.Listener { - override fun onStateUpdated(direction: Timeline.Direction, state: Timeline.PaginationState) { - if (direction == Timeline.Direction.FORWARDS) { - return - } - if (state.hasMoreToLoad && !state.loading) { - bobTimeline.paginate(Timeline.Direction.BACKWARDS, 30) - } else if (!state.hasMoreToLoad) { - bobTimeline.removeListener(this) - it.countDown() + waitFor( + continueWhen = { + wrapWithTimeout(timeout = TestConstants.timeOutMillis * 10) { + suspendCancellableCoroutine { continuation -> + val listener = object : Timeline.Listener { + + override fun onStateUpdated(direction: Timeline.Direction, state: Timeline.PaginationState) { + if (direction == Timeline.Direction.FORWARDS) { + return + } + if (state.hasMoreToLoad && !state.loading) { + bobTimeline.paginate(Timeline.Direction.BACKWARDS, 30) + } else if (!state.hasMoreToLoad) { + bobTimeline.removeListener(this) + continuation.resume(Unit) + } + } + } + bobTimeline.addListener(listener) + continuation.invokeOnCancellation { bobTimeline.removeListener(listener) } + } } - } - } - bobTimeline.addListener(listener) - bobTimeline.paginate(Timeline.Direction.BACKWARDS, 30) - } + }, + action = { bobTimeline.paginate(Timeline.Direction.BACKWARDS, 30) } + ) + assertEquals(false, bobTimeline.hasMoreToLoad(Timeline.Direction.FORWARDS)) assertEquals(false, bobTimeline.hasMoreToLoad(Timeline.Direction.BACKWARDS)) - val onlySentEvents = runBlocking { - bobTimeline.getSnapshot() - } + val onlySentEvents = bobTimeline.getSnapshot() .filter { it.root.isTextMessage() }.filter { From 53e8e2585e19880c6f6dba83b8206e07653419c1 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 11:13:36 +0100 Subject: [PATCH 47/56] removing no longer need runBlocking --- .../java/org/matrix/android/sdk/common/CommonTestHelper.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 20cc7fe1175..78eb2513b2c 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -272,7 +272,7 @@ class CommonTestHelper internal constructor(context: Context) { * @param message the message to send * @param numberOfMessages the number of time the message will be sent */ - fun replyInThreadMessage( + suspend fun replyInThreadMessage( room: Room, message: String, numberOfMessages: Int, @@ -281,7 +281,7 @@ class CommonTestHelper internal constructor(context: Context) { ): List { val timeline = room.timelineService().createTimeline(null, TimelineSettings(10)) timeline.start() - val sentEvents = runBlocking { sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId) } + val sentEvents = sendTextMessagesBatched(timeline, room, message, numberOfMessages, timeout, rootThreadEventId) timeline.dispose() // Check that all events has been created assertEquals("Message number do not match $sentEvents", numberOfMessages.toLong(), sentEvents.size.toLong()) From 2c338bd6a481a021da795b12dea869fe99578c17 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 11:13:56 +0100 Subject: [PATCH 48/56] renaming function for better context --- .../android/sdk/common/CommonTestHelper.kt | 2 +- .../android/sdk/common/CryptoTestHelper.kt | 6 +-- .../internal/crypto/E2EShareKeysConfigTest.kt | 10 ++-- .../sdk/internal/crypto/E2eeSanityTests.kt | 10 ++-- .../sdk/internal/crypto/PreShareKeysTest.kt | 2 +- .../sdk/internal/crypto/UnwedgingTest.kt | 2 +- .../crypto/crosssigning/XSigningTest.kt | 22 ++++----- .../crypto/keysbackup/KeysBackupTest.kt | 48 +++++++++---------- .../crypto/keysbackup/KeysBackupTestHelper.kt | 6 +-- .../verification/qrcode/VerificationTest.kt | 4 +- 10 files changed, 56 insertions(+), 56 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 78eb2513b2c..0b9c053a34a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -433,7 +433,7 @@ class CommonTestHelper internal constructor(context: Context) { } } - suspend fun doSync(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { + suspend fun waitForCallback(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): T { return wrapWithTimeout(timeout) { suspendCoroutine { continuation -> val callback = object : MatrixCallback { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt index 06331839689..6c6bc7056c3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CryptoTestHelper.kt @@ -221,7 +221,7 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { } suspend fun initializeCrossSigning(session: Session) { - testHelper.doSync { + testHelper.waitForCallback { session.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { @@ -272,10 +272,10 @@ class CryptoTestHelper(val testHelper: CommonTestHelper) { ) // set up megolm backup - val creationInfo = testHelper.doSync { + val creationInfo = testHelper.waitForCallback { session.cryptoService().keysBackupService().prepareKeysBackupVersion(null, null, it) } - val version = testHelper.doSync { + val version = testHelper.waitForCallback { session.cryptoService().keysBackupService().createKeysBackupVersion(creationInfo, it) } // Save it for gossiping diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt index 9a4b6eca7a7..cbbc4dc74e9 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2EShareKeysConfigTest.kt @@ -217,14 +217,14 @@ class E2EShareKeysConfigTest : InstrumentedTest { Log.v("#E2E TEST", "Create and start key backup for bob ...") val keysBackupService = aliceSession.cryptoService().keysBackupService() val keyBackupPassword = "FooBarBaz" - val megolmBackupCreationInfo = commonTestHelper.doSync { + val megolmBackupCreationInfo = commonTestHelper.waitForCallback { keysBackupService.prepareKeysBackupVersion(keyBackupPassword, null, it) } - val version = commonTestHelper.doSync { + val version = commonTestHelper.waitForCallback { keysBackupService.createKeysBackupVersion(megolmBackupCreationInfo, it) } - commonTestHelper.doSync { + commonTestHelper.waitForCallback { keysBackupService.backupAllGroupSessions(null, it) } @@ -235,11 +235,11 @@ class E2EShareKeysConfigTest : InstrumentedTest { newAliceSession.cryptoService().enableShareKeyOnInvite(true) newAliceSession.cryptoService().keysBackupService().let { kbs -> - val keyVersionResult = commonTestHelper.doSync { + val keyVersionResult = commonTestHelper.waitForCallback { kbs.getVersion(version.version, it) } - val importedResult = commonTestHelper.doSync { + val importedResult = commonTestHelper.waitForCallback { kbs.restoreKeyBackupWithPassword( keyVersionResult!!, keyBackupPassword, diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index 9d11c4e3560..a8e99b124c2 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -216,10 +216,10 @@ class E2eeSanityTests : InstrumentedTest { Log.v("#E2E TEST", "Create and start key backup for bob ...") val bobKeysBackupService = bobSession.cryptoService().keysBackupService() val keyBackupPassword = "FooBarBaz" - val megolmBackupCreationInfo = testHelper.doSync { + val megolmBackupCreationInfo = testHelper.waitForCallback { bobKeysBackupService.prepareKeysBackupVersion(keyBackupPassword, null, it) } - val version = testHelper.doSync { + val version = testHelper.waitForCallback { bobKeysBackupService.createKeysBackupVersion(megolmBackupCreationInfo, it) } Log.v("#E2E TEST", "... Key backup started and enabled for bob") @@ -249,7 +249,7 @@ class E2eeSanityTests : InstrumentedTest { // Let's wait a bit to be sure that bob has backed up the session Log.v("#E2E TEST", "Force key backup for Bob...") - testHelper.doSync { bobKeysBackupService.backupAllGroupSessions(null, it) } + testHelper.waitForCallback { bobKeysBackupService.backupAllGroupSessions(null, it) } Log.v("#E2E TEST", "... Key backup done for Bob") // Now lets logout both alice and bob to ensure that we won't have any gossiping @@ -282,11 +282,11 @@ class E2eeSanityTests : InstrumentedTest { // Let's now import keys from backup newBobSession.cryptoService().keysBackupService().let { kbs -> - val keyVersionResult = testHelper.doSync { + val keyVersionResult = testHelper.waitForCallback { kbs.getVersion(version.version, it) } - val importedResult = testHelper.doSync { + val importedResult = testHelper.waitForCallback { kbs.restoreKeyBackupWithPassword( keyVersionResult!!, keyBackupPassword, diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt index dc11cc14d08..5c817443ce6 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/PreShareKeysTest.kt @@ -52,7 +52,7 @@ class PreShareKeysTest : InstrumentedTest { Log.d("#Test", "Room Key Received from alice $preShareCount") // Force presharing of new outbound key - testHelper.doSync { + testHelper.waitForCallback { aliceSession.cryptoService().prepareToEncrypt(e2eRoomID, it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt index 5ce13ca06ba..f3b3ccdd23a 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/UnwedgingTest.kt @@ -166,7 +166,7 @@ class UnwedgingTest : InstrumentedTest { Assert.assertTrue(messagesReceivedByBob[0].root.mCryptoError == MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID) // It's a trick to force key request on fail to decrypt - testHelper.doSync { + testHelper.waitForCallback { bobSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt index ef3fdfeeda3..2bb04a1faac 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/crosssigning/XSigningTest.kt @@ -55,7 +55,7 @@ class XSigningTest : InstrumentedTest { fun test_InitializeAndStoreKeys() = runSessionTest(context()) { testHelper -> val aliceSession = testHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(true)) - testHelper.doSync { + testHelper.waitForCallback { aliceSession.cryptoService().crossSigningService() .initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { @@ -101,14 +101,14 @@ class XSigningTest : InstrumentedTest { password = TestConstants.PASSWORD ) - testHelper.doSync { + testHelper.waitForCallback { aliceSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(aliceAuthParams) } }, it) } - testHelper.doSync { + testHelper.waitForCallback { bobSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(bobAuthParams) @@ -117,7 +117,7 @@ class XSigningTest : InstrumentedTest { } // Check that alice can see bob keys - testHelper.doSync> { aliceSession.cryptoService().downloadKeys(listOf(bobSession.myUserId), true, it) } + testHelper.waitForCallback> { aliceSession.cryptoService().downloadKeys(listOf(bobSession.myUserId), true, it) } val bobKeysFromAlicePOV = aliceSession.cryptoService().crossSigningService().getUserCrossSigningKeys(bobSession.myUserId) assertNotNull("Alice can see bob Master key", bobKeysFromAlicePOV!!.masterKey()) @@ -154,14 +154,14 @@ class XSigningTest : InstrumentedTest { password = TestConstants.PASSWORD ) - testHelper.doSync { + testHelper.waitForCallback { aliceSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(aliceAuthParams) } }, it) } - testHelper.doSync { + testHelper.waitForCallback { bobSession.cryptoService().crossSigningService().initializeCrossSigning(object : UserInteractiveAuthInterceptor { override fun performStage(flowResponse: RegistrationFlowResponse, errCode: String?, promise: Continuation) { promise.resume(bobAuthParams) @@ -171,12 +171,12 @@ class XSigningTest : InstrumentedTest { // Check that alice can see bob keys val bobUserId = bobSession.myUserId - testHelper.doSync> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } + testHelper.waitForCallback> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } val bobKeysFromAlicePOV = aliceSession.cryptoService().crossSigningService().getUserCrossSigningKeys(bobUserId) assertTrue("Bob keys from alice pov should not be trusted", bobKeysFromAlicePOV?.isTrusted() == false) - testHelper.doSync { aliceSession.cryptoService().crossSigningService().trustUser(bobUserId, it) } + testHelper.waitForCallback { aliceSession.cryptoService().crossSigningService().trustUser(bobUserId, it) } // Now bobs logs in on a new device and verifies it // We will want to test that in alice POV, this new device would be trusted by cross signing @@ -185,7 +185,7 @@ class XSigningTest : InstrumentedTest { val bobSecondDeviceId = bobSession2.sessionParams.deviceId!! // Check that bob first session sees the new login - val data = testHelper.doSync> { + val data = testHelper.waitForCallback> { bobSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } @@ -197,12 +197,12 @@ class XSigningTest : InstrumentedTest { assertNotNull("Bob Second device should be known and persisted from first", bobSecondDevicePOVFirstDevice) // Manually mark it as trusted from first session - testHelper.doSync { + testHelper.waitForCallback { bobSession.cryptoService().crossSigningService().trustDevice(bobSecondDeviceId, it) } // Now alice should cross trust bob's second device - val data2 = testHelper.doSync> { + val data2 = testHelper.waitForCallback> { aliceSession.cryptoService().downloadKeys(listOf(bobUserId), true, it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index 21d3784ce18..bcfa0d836f5 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -116,7 +116,7 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled()) - val megolmBackupCreationInfo = testHelper.doSync { + val megolmBackupCreationInfo = testHelper.waitForCallback { keysBackup.prepareKeysBackupVersion(null, null, it) } @@ -142,14 +142,14 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled()) - val megolmBackupCreationInfo = testHelper.doSync { + val megolmBackupCreationInfo = testHelper.waitForCallback { keysBackup.prepareKeysBackupVersion(null, null, it) } assertFalse(keysBackup.isEnabled()) // Create the version - val version = testHelper.doSync { + val version = testHelper.waitForCallback { keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) } @@ -157,10 +157,10 @@ class KeysBackupTest : InstrumentedTest { assertTrue(keysBackup.isEnabled()) // Check that it's signed with MSK - val versionResult = testHelper.doSync { + val versionResult = testHelper.waitForCallback { keysBackup.getVersion(version.version, it) } - val trust = testHelper.doSync { + val trust = testHelper.waitForCallback { keysBackup.getKeysBackupTrust(versionResult!!, it) } @@ -256,7 +256,7 @@ class KeysBackupTest : InstrumentedTest { var lastBackedUpKeysProgress = 0 - testHelper.doSync { + testHelper.waitForCallback { keysBackup.backupAllGroupSessions(object : ProgressListener { override fun onProgress(progress: Int, total: Int) { assertEquals(nbOfKeys, total) @@ -333,7 +333,7 @@ class KeysBackupTest : InstrumentedTest { val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) // - Restore the e2e backup from the homeserver - val importRoomKeysResult = testHelper.doSync { + val importRoomKeysResult = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().restoreKeysWithRecoveryKey( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, testData.prepareKeysBackupDataResult.megolmBackupCreationInfo.recoveryKey, @@ -428,7 +428,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device - testHelper.doSync { + testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersion( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, true, @@ -444,14 +444,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -488,7 +488,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device with the recovery key - testHelper.doSync { + testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithRecoveryKey( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, testData.prepareKeysBackupDataResult.megolmBackupCreationInfo.recoveryKey, @@ -504,14 +504,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -590,7 +590,7 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Trust the backup from the new device with the password - testHelper.doSync { + testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithPassphrase( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, password, @@ -606,14 +606,14 @@ class KeysBackupTest : InstrumentedTest { assertTrue(testData.aliceSession2.cryptoService().keysBackupService().isEnabled()) // - Retrieve the last version from the server - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().getCurrentVersion(it) }.toKeysVersionResult() // - It must be the same assertEquals(testData.prepareKeysBackupDataResult.version, keysVersionResult!!.version) - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().getKeysBackupTrust(keysVersionResult, it) } @@ -717,7 +717,7 @@ class KeysBackupTest : InstrumentedTest { // - Restore the e2e backup with the password val steps = ArrayList() - val importRoomKeysResult = testHelper.doSync { + val importRoomKeysResult = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().restoreKeyBackupWithPassword( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, password, @@ -807,7 +807,7 @@ class KeysBackupTest : InstrumentedTest { val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password) // - Restore the e2e backup with the recovery key. - val importRoomKeysResult = testHelper.doSync { + val importRoomKeysResult = testHelper.waitForCallback { testData.aliceSession2.cryptoService().keysBackupService().restoreKeysWithRecoveryKey( testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, testData.prepareKeysBackupDataResult.megolmBackupCreationInfo.recoveryKey, @@ -873,12 +873,12 @@ class KeysBackupTest : InstrumentedTest { keysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Get key backup version from the homeserver - val keysVersionResult = testHelper.doSync { + val keysVersionResult = testHelper.waitForCallback { keysBackup.getCurrentVersion(it) }.toKeysVersionResult() // - Check the returned KeyBackupVersion is trusted - val keysBackupVersionTrust = testHelper.doSync { + val keysBackupVersionTrust = testHelper.waitForCallback { keysBackup.getKeysBackupTrust(keysVersionResult!!, it) } @@ -944,7 +944,7 @@ class KeysBackupTest : InstrumentedTest { // - Create a new backup with fake data on the homeserver, directly using the rest client val megolmBackupCreationInfo = cryptoTestHelper.createFakeMegolmBackupCreationInfo() - testHelper.doSync { + testHelper.waitForCallback { (keysBackup as DefaultKeysBackupService).createFakeKeysBackupVersion(megolmBackupCreationInfo, it) } @@ -990,7 +990,7 @@ class KeysBackupTest : InstrumentedTest { keysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) // Wait for keys backup to finish by asking again to backup keys. - testHelper.doSync { + testHelper.waitForCallback { keysBackup.backupAllGroupSessions(null, it) } @@ -1058,7 +1058,7 @@ class KeysBackupTest : InstrumentedTest { // -> It must use the same backup version assertEquals(oldKeyBackupVersion, aliceSession2.cryptoService().keysBackupService().currentBackupVersion) - testHelper.doSync { + testHelper.waitForCallback { aliceSession2.cryptoService().keysBackupService().backupAllGroupSessions(null, it) } @@ -1091,7 +1091,7 @@ class KeysBackupTest : InstrumentedTest { assertTrue(keysBackup.isEnabled()) // Delete the backup - testHelper.doSync { keysBackup.deleteBackup(keyBackupCreationInfo.version, it) } + testHelper.waitForCallback { keysBackup.deleteBackup(keyBackupCreationInfo.version, it) } // Backup is now disabled assertFalse(keysBackup.isEnabled()) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt index 36a567cc237..10abf93bcb0 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTestHelper.kt @@ -65,7 +65,7 @@ internal class KeysBackupTestHelper( var lastProgress = 0 var lastTotal = 0 - testHelper.doSync { + testHelper.waitForCallback { keysBackup.backupAllGroupSessions(object : ProgressListener { override fun onProgress(progress: Int, total: Int) { lastProgress = progress @@ -104,7 +104,7 @@ internal class KeysBackupTestHelper( ): PrepareKeysBackupDataResult { val stateObserver = StateObserver(keysBackup) - val megolmBackupCreationInfo = testHelper.doSync { + val megolmBackupCreationInfo = testHelper.waitForCallback { keysBackup.prepareKeysBackupVersion(password, null, it) } @@ -113,7 +113,7 @@ internal class KeysBackupTestHelper( Assert.assertFalse("Key backup should not be enabled before creation", keysBackup.isEnabled()) // Create the version - val keysVersion = testHelper.doSync { + val keysVersion = testHelper.waitForCallback { keysBackup.createKeysBackupVersion(megolmBackupCreationInfo, it) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt index 3c45706c37a..4ecfe5be8f3 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/verification/qrcode/VerificationTest.kt @@ -164,7 +164,7 @@ class VerificationTest : InstrumentedTest { val aliceSession = cryptoTestData.firstSession val bobSession = cryptoTestData.secondSession!! - testHelper.doSync { callback -> + testHelper.waitForCallback { callback -> aliceSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { @@ -181,7 +181,7 @@ class VerificationTest : InstrumentedTest { ) } - testHelper.doSync { callback -> + testHelper.waitForCallback { callback -> bobSession.cryptoService().crossSigningService() .initializeCrossSigning( object : UserInteractiveAuthInterceptor { From 99d01b29aa95e3c94a2b7b910f6c4526a1ac33bd Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 11:14:50 +0100 Subject: [PATCH 49/56] removing unused scope --- .../java/org/matrix/android/sdk/common/CommonTestHelper.kt | 1 - 1 file changed, 1 deletion(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 0b9c053a34a..73583083bcf 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -100,7 +100,6 @@ class CommonTestHelper internal constructor(context: Context) { } internal val matrix: TestMatrix - private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) private var accountNumber = 0 private val trackedSessions = mutableListOf() From e09f9bcfe28e13fbdbdc129628fd7553d02f9c00 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 11:16:59 +0100 Subject: [PATCH 50/56] disabling test retries to help identify flaky tests --- .../java/org/matrix/android/sdk/InstrumentedTest.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt index f08f0a28ed1..713c9b3ebea 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt @@ -24,8 +24,8 @@ import org.matrix.android.sdk.test.shared.createTimberTestRule interface InstrumentedTest { - @Rule - fun retryTestRule() = RetryTestRule(3) +// @Rule +// fun retryTestRule() = RetryTestRule(3) @Rule fun timberTestRule() = createTimberTestRule() From 2c446ceba64773d0eba0b7bbbeb2add851e25f80 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 11:37:35 +0100 Subject: [PATCH 51/56] including waiting for the room topic to be updated --- .../org/matrix/android/sdk/session/space/SpaceCreationTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt index 3eeca524881..df131cc19aa 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/space/SpaceCreationTest.kt @@ -58,7 +58,8 @@ class SpaceCreationTest : InstrumentedTest { val spaceId = session.spaceService().createSpace(roomName, topic, null, true) commonTestHelper.retryPeriodically { - session.spaceService().getSpace(spaceId)?.asRoom()?.roomSummary()?.name != null + val roomSummary = session.spaceService().getSpace(spaceId)?.asRoom()?.roomSummary() + roomSummary?.name == roomName && roomSummary.topic == topic } val syncedSpace = session.spaceService().getSpace(spaceId) From ff012bd25999c5e5b0cdfdaf9e6289c004e63920 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 12:15:14 +0100 Subject: [PATCH 52/56] replacing latches in keysbackup tests --- .../android/sdk/common/CommonTestHelper.kt | 13 ++ .../crypto/keysbackup/KeysBackupTest.kt | 205 ++++++++---------- 2 files changed, 106 insertions(+), 112 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 73583083bcf..70d875b0a0f 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -445,6 +445,19 @@ class CommonTestHelper internal constructor(context: Context) { } } + suspend fun waitForCallbackError(timeout: Long = TestConstants.timeOutMillis, block: (MatrixCallback) -> Unit): Throwable { + return wrapWithTimeout(timeout) { + suspendCoroutine { continuation -> + val callback = object : MatrixCallback { + override fun onFailure(failure: Throwable) { + continuation.resume(failure) + } + } + block(callback) + } + } + } + /** * Clear all provided sessions */ diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index bcfa0d836f5..2de025fe80e 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -18,10 +18,10 @@ package org.matrix.android.sdk.internal.crypto.keysbackup import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest +import kotlinx.coroutines.suspendCancellableCoroutine import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.FixMethodOrder import org.junit.Rule @@ -49,8 +49,11 @@ import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.TestConstants import org.matrix.android.sdk.common.TestMatrixCallback +import org.matrix.android.sdk.common.waitFor +import java.security.InvalidParameterException import java.util.Collections import java.util.concurrent.CountDownLatch +import kotlin.coroutines.resume @RunWith(AndroidJUnit4::class) @FixMethodOrder(MethodSorters.JVM) @@ -546,13 +549,13 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Try to trust the backup from the new device with a wrong recovery key - val latch = CountDownLatch(1) - testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithRecoveryKey( - testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, - "Bad recovery key", - TestMatrixCallback(latch, false) - ) - testHelper.await(latch) + testHelper.waitForCallbackError { + testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithRecoveryKey( + testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, + "Bad recovery key", + it + ) + } // - The new device must still see the previous backup as not trusted assertNotNull(testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion) @@ -651,13 +654,13 @@ class KeysBackupTest : InstrumentedTest { assertEquals(KeysBackupState.NotTrusted, testData.aliceSession2.cryptoService().keysBackupService().getState()) // - Try to trust the backup from the new device with a wrong password - val latch = CountDownLatch(1) - testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithPassphrase( - testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, - badPassword, - TestMatrixCallback(latch, false) - ) - testHelper.await(latch) + testHelper.waitForCallbackError { + testData.aliceSession2.cryptoService().keysBackupService().trustKeysBackupVersionWithPassphrase( + testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, + badPassword, + it + ) + } // - The new device must still see the previous backup as not trusted assertNotNull(testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion) @@ -678,26 +681,21 @@ class KeysBackupTest : InstrumentedTest { val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) + val keysBackupService = testData.aliceSession2.cryptoService().keysBackupService() // - Try to restore the e2e backup with a wrong recovery key - val latch2 = CountDownLatch(1) - var importRoomKeysResult: ImportRoomKeysResult? = null - testData.aliceSession2.cryptoService().keysBackupService().restoreKeysWithRecoveryKey(testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, - "EsTc LW2K PGiF wKEA 3As5 g5c4 BXwk qeeJ ZJV8 Q9fu gUMN UE4d", - null, - null, - null, - object : TestMatrixCallback(latch2, false) { - override fun onSuccess(data: ImportRoomKeysResult) { - importRoomKeysResult = data - super.onSuccess(data) - } - } - ) - testHelper.await(latch2) + val importRoomKeysResult = testHelper.waitForCallbackError { + keysBackupService.restoreKeysWithRecoveryKey( + keysBackupService.keysBackupVersion!!, + "EsTc LW2K PGiF wKEA 3As5 g5c4 BXwk qeeJ ZJV8 Q9fu gUMN UE4d", + null, + null, + null, + it + ) + } - // onSuccess may not have been called - assertNull(importRoomKeysResult) + assertTrue(importRoomKeysResult is InvalidParameterException) } /** @@ -770,26 +768,21 @@ class KeysBackupTest : InstrumentedTest { val wrongPassword = "passw0rd" val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(password) + val keysBackupService = testData.aliceSession2.cryptoService().keysBackupService() // - Try to restore the e2e backup with a wrong password - val latch2 = CountDownLatch(1) - var importRoomKeysResult: ImportRoomKeysResult? = null - testData.aliceSession2.cryptoService().keysBackupService().restoreKeyBackupWithPassword(testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, - wrongPassword, - null, - null, - null, - object : TestMatrixCallback(latch2, false) { - override fun onSuccess(data: ImportRoomKeysResult) { - importRoomKeysResult = data - super.onSuccess(data) - } - } - ) - testHelper.await(latch2) + val importRoomKeysResult = testHelper.waitForCallbackError { + keysBackupService.restoreKeyBackupWithPassword( + keysBackupService.keysBackupVersion!!, + wrongPassword, + null, + null, + null, + it + ) + } - // onSuccess may not have been called - assertNull(importRoomKeysResult) + assertTrue(importRoomKeysResult is InvalidParameterException) } /** @@ -832,26 +825,21 @@ class KeysBackupTest : InstrumentedTest { val keysBackupTestHelper = KeysBackupTestHelper(testHelper, cryptoTestHelper) val testData = keysBackupTestHelper.createKeysBackupScenarioWithPassword(null) + val keysBackupService = testData.aliceSession2.cryptoService().keysBackupService() // - Try to restore the e2e backup with a password - val latch2 = CountDownLatch(1) - var importRoomKeysResult: ImportRoomKeysResult? = null - testData.aliceSession2.cryptoService().keysBackupService().restoreKeyBackupWithPassword(testData.aliceSession2.cryptoService().keysBackupService().keysBackupVersion!!, - "password", - null, - null, - null, - object : TestMatrixCallback(latch2, false) { - override fun onSuccess(data: ImportRoomKeysResult) { - importRoomKeysResult = data - super.onSuccess(data) - } - } - ) - testHelper.await(latch2) + val importRoomKeysResult = testHelper.waitForCallbackError { + keysBackupService.restoreKeyBackupWithPassword( + keysBackupService.keysBackupVersion!!, + "password", + null, + null, + null, + it + ) + } - // onSuccess may not have been called - assertNull(importRoomKeysResult) + assertTrue(importRoomKeysResult is IllegalStateException) } /** @@ -917,31 +905,37 @@ class KeysBackupTest : InstrumentedTest { assertFalse(keysBackup.isEnabled()) // Wait for keys backup to be finished - val latch0 = CountDownLatch(1) var count = 0 - keysBackup.addListener(object : KeysBackupStateListener { - override fun onStateChange(newState: KeysBackupState) { - // Check the backup completes - if (newState == KeysBackupState.ReadyToBackUp) { - count++ - - if (count == 2) { - // Remove itself from the list of listeners - keysBackup.removeListener(this) - - latch0.countDown() + waitFor( + continueWhen = { + suspendCancellableCoroutine { continuation -> + val listener = object : KeysBackupStateListener { + override fun onStateChange(newState: KeysBackupState) { + // Check the backup completes + if (newState == KeysBackupState.ReadyToBackUp) { + count++ + + if (count == 2) { + // Remove itself from the list of listeners + keysBackup.removeListener(this) + continuation.resume(Unit) + } + } + } + } + keysBackup.addListener(listener) + continuation.invokeOnCancellation { keysBackup.removeListener(listener) } } - } - } - }) - // - Make alice back up her keys to her homeserver - keysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) + }, + action = { + // - Make alice back up her keys to her homeserver + keysBackupTestHelper.prepareAndCreateKeysBackupData(keysBackup) + }, + ) assertTrue(keysBackup.isEnabled()) - testHelper.await(latch0) - // - Create a new backup with fake data on the homeserver, directly using the rest client val megolmBackupCreationInfo = cryptoTestHelper.createFakeMegolmBackupCreationInfo() testHelper.waitForCallback { @@ -952,9 +946,7 @@ class KeysBackupTest : InstrumentedTest { (cryptoTestData.firstSession.cryptoService().keysBackupService() as DefaultKeysBackupService).store.resetBackupMarkers() // - Make alice back up all her keys again - val latch2 = CountDownLatch(1) - keysBackup.backupAllGroupSessions(null, TestMatrixCallback(latch2, false)) - testHelper.await(latch2) + testHelper.waitForCallbackError { keysBackup.backupAllGroupSessions(null, it) } // -> That must fail and her backup state must be WrongBackUpVersion assertEquals(KeysBackupState.WrongBackUpVersion, keysBackup.getState()) @@ -1015,19 +1007,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver2 = StateObserver(keysBackup2) - var isSuccessful = false - val latch2 = CountDownLatch(1) - keysBackup2.backupAllGroupSessions( - null, - object : TestMatrixCallback(latch2, false) { - override fun onSuccess(data: Unit) { - isSuccessful = true - super.onSuccess(data) - } - }) - testHelper.await(latch2) - - assertFalse(isSuccessful) + testHelper.waitForCallbackError {keysBackup2.backupAllGroupSessions(null, it) } // Backup state must be NotTrusted assertEquals("Backup state must be NotTrusted", KeysBackupState.NotTrusted, keysBackup2.getState()) @@ -1041,19 +1021,20 @@ class KeysBackupTest : InstrumentedTest { ) // -> Backup should automatically enable on the new device - val latch4 = CountDownLatch(1) - keysBackup2.addListener(object : KeysBackupStateListener { - override fun onStateChange(newState: KeysBackupState) { - // Check the backup completes - if (keysBackup2.getState() == KeysBackupState.ReadyToBackUp) { - // Remove itself from the list of listeners - keysBackup2.removeListener(this) - - latch4.countDown() + suspendCancellableCoroutine { continuation -> + val listener = object : KeysBackupStateListener { + override fun onStateChange(newState: KeysBackupState) { + // Check the backup completes + if (keysBackup2.getState() == KeysBackupState.ReadyToBackUp) { + // Remove itself from the list of listeners + keysBackup2.removeListener(this) + continuation.resume(Unit) + } } } - }) - testHelper.await(latch4) + keysBackup2.addListener(listener) + continuation.invokeOnCancellation { keysBackup2.removeListener(listener) } + } // -> It must use the same backup version assertEquals(oldKeyBackupVersion, aliceSession2.cryptoService().keysBackupService().currentBackupVersion) From aef44a3aa77025c3fae545274abc7db56332b165 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 12:48:56 +0100 Subject: [PATCH 53/56] ensuring the verification listener is removed before resuming - fixes double trigger on the resume which error --- .../matrix/android/sdk/internal/crypto/E2eeSanityTests.kt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt index a8e99b124c2..6ba565777f2 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/E2eeSanityTests.kt @@ -553,7 +553,6 @@ class E2eeSanityTests : InstrumentedTest { listOf(aliceNewSession.sessionParams.deviceId!!) ) - val (oldCode, newCode) = awaitAll(deferredOldCode, deferredNewCode) assertEquals("Decimal code should have matched", oldCode, newCode) @@ -635,9 +634,9 @@ class E2eeSanityTests : InstrumentedTest { sasTx.userHasVerifiedShortCode() } OutgoingSasVerificationTransaction.UxState.VERIFIED -> { + removeListener(this) // we can release this latch? continuation.resume(oldCode!!) - removeListener(this) } else -> Unit } @@ -682,8 +681,8 @@ class E2eeSanityTests : InstrumentedTest { } } IncomingSasVerificationTransaction.UxState.VERIFIED -> { - continuation.resume(newCode!!) removeListener(this) + continuation.resume(newCode!!) } else -> Unit } From bf153e2e22ade03f08e96128ca46605d42c60345 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 12:54:03 +0100 Subject: [PATCH 54/56] removing unused imports and re-enabling retry test rule --- .../java/org/matrix/android/sdk/InstrumentedTest.kt | 4 ++-- .../java/org/matrix/android/sdk/common/CommonTestHelper.kt | 2 -- .../android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt | 4 +--- .../session/room/timeline/TimelineSimpleBackPaginationTest.kt | 2 -- 4 files changed, 3 insertions(+), 9 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt index 713c9b3ebea..f08f0a28ed1 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/InstrumentedTest.kt @@ -24,8 +24,8 @@ import org.matrix.android.sdk.test.shared.createTimberTestRule interface InstrumentedTest { -// @Rule -// fun retryTestRule() = RetryTestRule(3) + @Rule + fun retryTestRule() = RetryTestRule(3) @Rule fun timberTestRule() = createTimberTestRule() diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt index 70d875b0a0f..84a113e667d 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/CommonTestHelper.kt @@ -24,7 +24,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking @@ -231,7 +230,6 @@ class CommonTestHelper internal constructor(context: Context) { room.sendService().sendTextMessage(formattedMessage) } } - } ) } diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt index 2de025fe80e..01c03b80016 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/internal/crypto/keysbackup/KeysBackupTest.kt @@ -48,7 +48,6 @@ import org.matrix.android.sdk.common.CommonTestHelper.Companion.runCryptoTest import org.matrix.android.sdk.common.CommonTestHelper.Companion.runSessionTest import org.matrix.android.sdk.common.RetryTestRule import org.matrix.android.sdk.common.TestConstants -import org.matrix.android.sdk.common.TestMatrixCallback import org.matrix.android.sdk.common.waitFor import java.security.InvalidParameterException import java.util.Collections @@ -926,7 +925,6 @@ class KeysBackupTest : InstrumentedTest { keysBackup.addListener(listener) continuation.invokeOnCancellation { keysBackup.removeListener(listener) } } - }, action = { // - Make alice back up her keys to her homeserver @@ -1007,7 +1005,7 @@ class KeysBackupTest : InstrumentedTest { val stateObserver2 = StateObserver(keysBackup2) - testHelper.waitForCallbackError {keysBackup2.backupAllGroupSessions(null, it) } + testHelper.waitForCallbackError { keysBackup2.backupAllGroupSessions(null, it) } // Backup state must be NotTrusted assertEquals("Backup state must be NotTrusted", KeysBackupState.NotTrusted, keysBackup2.getState()) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt index 160d6d1cf0c..656e00bcbdf 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/session/room/timeline/TimelineSimpleBackPaginationTest.kt @@ -17,7 +17,6 @@ package org.matrix.android.sdk.session.room.timeline import androidx.test.filters.LargeTest -import kotlinx.coroutines.runBlocking import kotlinx.coroutines.suspendCancellableCoroutine import org.amshove.kluent.internal.assertEquals import org.junit.FixMethodOrder @@ -73,7 +72,6 @@ class TimelineSimpleBackPaginationTest : InstrumentedTest { val bobTimeline = roomFromBobPOV.timelineService().createTimeline(null, TimelineSettings(30)) bobTimeline.start() - waitFor( continueWhen = { wrapWithTimeout(timeout = TestConstants.timeOutMillis * 10) { From 3e46263bef7d480b441477ecf98589d79610e873 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 12:57:01 +0100 Subject: [PATCH 55/56] using correct license for matrix sdk class --- .../java/org/matrix/android/sdk/common/TestExtensions.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt index 786038ba72a..8f89d42ac07 100644 --- a/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt +++ b/matrix-sdk-android/src/androidTest/java/org/matrix/android/sdk/common/TestExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 New Vector Ltd + * Copyright 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From c595475995735e3e81d1f0df174ab52b6863b7f7 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Thu, 22 Sep 2022 14:11:28 +0100 Subject: [PATCH 56/56] adding changelog entry --- changelog.d/7207.sdk | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/7207.sdk diff --git a/changelog.d/7207.sdk b/changelog.d/7207.sdk new file mode 100644 index 00000000000..0bc221e9f7f --- /dev/null +++ b/changelog.d/7207.sdk @@ -0,0 +1 @@ +Ports SDK instrumentation tests to use suspending functions instead of countdown latches