diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt index b088a1a081..5b04eb74ac 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt @@ -25,6 +25,7 @@ import androidx.lifecycle.Lifecycle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.IdlingResource +import androidx.test.espresso.Root import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.idling.CountingIdlingResource @@ -62,6 +63,7 @@ import com.google.android.material.snackbar.Snackbar import jakarta.mail.Session import jakarta.mail.internet.MimeMessage import kotlinx.coroutines.runBlocking +import org.hamcrest.Matcher import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.allOf import org.hamcrest.Matchers.hasToString @@ -409,6 +411,32 @@ abstract class BaseTest : BaseActivityTestImplementation { } } + /** + * Wait until the view with [viewId] matches [matcher], e.g. a list that is shown after + * asynchronous loading. Fails with a regular Espresso error if it doesn't happen in [timeoutMs]. + * Use [root] when the same id is used on the screen and in a dialog. + */ + protected fun waitUntilViewMatches( + viewId: Int, + matcher: Matcher, + root: Matcher? = null, + timeoutMs: Long = TimeUnit.SECONDS.toMillis(10) + ) { + val findView = { + val interaction = onView(withId(viewId)) + if (root != null) interaction.inRoot(root) else interaction + } + waitUntil(timeoutMs) { + runCatching { + //the default failure handler takes a screenshot on every failed check + findView() + .withFailureHandler { error, _ -> throw error } + .check(matches(matcher)) + }.isSuccess + } + findView().check(matches(matcher)) + } + /** * Wait until the recipient chip keeps its final color during [stableForMs]. * The chip is white while the recipient lookup is in progress, and the compose screen diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModelTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModelTest.kt new file mode 100644 index 0000000000..a0776ee91e --- /dev/null +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModelTest.kt @@ -0,0 +1,115 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + */ + +package com.flowcrypt.email.jetpack.viewmodel + +import android.app.Application +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.MediumTest +import com.flowcrypt.email.TestConstants +import com.flowcrypt.email.api.retrofit.response.base.Result +import com.flowcrypt.email.database.FlowCryptRoomDatabase +import com.flowcrypt.email.rules.AddAccountToDatabaseRule +import com.flowcrypt.email.rules.ClearAppSettingsRule +import com.flowcrypt.email.rules.FlowCryptMockWebServerRule +import com.flowcrypt.email.ui.base.BaseGmailApiTest +import com.google.api.client.json.gson.GsonFactory +import com.google.api.services.gmail.model.ListSendAsResponse +import com.google.api.services.gmail.model.SendAs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.RecordedRequest +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.rules.TestRule +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.util.concurrent.TimeUnit + +@MediumTest +@RunWith(AndroidJUnit4::class) +class AccountAliasesViewModelTest { + private val accountEntity = BaseGmailApiTest.BASE_ACCOUNT_ENTITY + private val addAccountToDatabaseRule = AddAccountToDatabaseRule(accountEntity) + private val mockWebServerRule = FlowCryptMockWebServerRule( + TestConstants.MOCK_WEB_SERVER_PORT, + object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + return if (request.path == "/gmail/v1/users/me/settings/sendAs") { + MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody( + ListSendAsResponse().apply { + factory = GsonFactory.getDefaultInstance() + sendAs = listOf( + SendAs().apply { + sendAsEmail = accountEntity.email + signature = SIGNATURE + isPrimary = true + isDefault = true + }, + SendAs().apply { + sendAsEmail = ALIAS_EMAIL + signature = SIGNATURE + treatAsAlias = true + verificationStatus = "accepted" + }, + ) + }.toString() + ) + } else { + MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND) + } + } + }) + + @get:Rule + var ruleChain: TestRule = RuleChain + .outerRule(ClearAppSettingsRule()) + .around(mockWebServerRule) + .around(addAccountToDatabaseRule) + + @Test + fun testFetchUpdatesSavesAliasesBeforeActiveAccountIsLoaded() { + /* + Nobody observes activeAccountLiveData here, so it has no value. It's the same situation as + on a slow device, where the 'sendAs' response comes before the active account is loaded + and decrypted for the LiveData. + */ + val viewModel = runBlocking(Dispatchers.Main) { + AccountAliasesViewModel(ApplicationProvider.getApplicationContext()) + } + + val result = runBlocking { + withContext(Dispatchers.Main) { viewModel.fetchUpdates(monitorProgress = true) } + withTimeout(TimeUnit.SECONDS.toMillis(30)) { + viewModel.fetchFreshestAliasesStateFlow.first { + it.status == Result.Status.SUCCESS || it.status == Result.Status.EXCEPTION + } + } + } + assertEquals(Result.Status.SUCCESS, result.status) + + val savedAliases = runBlocking { + FlowCryptRoomDatabase.getDatabase(ApplicationProvider.getApplicationContext()) + .accountAliasesDao() + .getAliases(account = accountEntity.email, accountType = accountEntity.accountType) + } + assertEquals( + setOf(accountEntity.email.lowercase(), ALIAS_EMAIL), + savedAliases.mapNotNull { it.sendAsEmail?.lowercase() }.toSet() + ) + } + + companion object { + private const val ALIAS_EMAIL = "alias@flowcrypt.test" + private const val SIGNATURE = "
Signature
" + } +} diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/AttachmentDownloadingWithRestrictionFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/AttachmentDownloadingWithRestrictionFlowTest.kt index 00ef9fcbd8..d6d48a5ba3 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/AttachmentDownloadingWithRestrictionFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/AttachmentDownloadingWithRestrictionFlowTest.kt @@ -5,6 +5,9 @@ package com.flowcrypt.email.ui +import android.app.NotificationManager +import androidx.core.app.NotificationCompat +import androidx.core.content.getSystemService import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches @@ -12,10 +15,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.uiautomator.By -import androidx.test.uiautomator.UiDevice -import androidx.test.uiautomator.Until import com.flowcrypt.email.R import com.flowcrypt.email.TestConstants import com.flowcrypt.email.api.email.model.AttachmentInfo @@ -44,7 +43,7 @@ import com.google.api.services.gmail.model.MessagePartHeader import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest -import org.junit.Ignore +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -53,7 +52,9 @@ import org.junit.runner.RunWith import java.math.BigInteger import java.net.HttpURLConnection import java.util.UUID +import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference import kotlin.random.Random /** @@ -83,6 +84,12 @@ class AttachmentDownloadingWithRestrictionFlowTest : BaseMessageDetailsFlowTest( useAPI = true ) + private val notificationManager: NotificationManager + get() = requireNotNull(getTargetContext().getSystemService()) + + //the mock web server waits for it on its own thread + private val attachmentResponseReleased = AtomicReference(CountDownLatch(1)) + override val addAccountToDatabaseRule = AddAccountToDatabaseRule(userWithClientConfiguration) private val addPrivateKeyToDatabaseRule = AddPrivateKeyToDatabaseRule( accountEntity = addAccountToDatabaseRule.account, @@ -137,9 +144,13 @@ class AttachmentDownloadingWithRestrictionFlowTest : BaseMessageDetailsFlowTest( } "/gmail/v1/users/me/messages/${simpleAttInfo?.uid?.toHex()}/attachments/$ATTACHMENT_ID?fields=data&prettyPrint=false" -> { + //keep the download in progress until the test checks the 'downloading' dialog + attachmentResponseReleased.get().await( + RELEASE_ATTACHMENT_RESPONSE_TIMEOUT_IN_SECONDS, + TimeUnit.SECONDS + ) return MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) - .setBodyDelay(DELAY_FOR_DOWNLOADING_IN_SECONDS, TimeUnit.SECONDS) .setBody( MessagePartBody().apply { factory = GsonFactory.getDefaultInstance() @@ -165,70 +176,84 @@ class AttachmentDownloadingWithRestrictionFlowTest : BaseMessageDetailsFlowTest( .around(ScreenshotTestRule()) @Test - @Ignore("tests crash randomly too many times on this test. Temporary disabled") fun testDownloadingAttachment() { - val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) + val incomingMessageInfo = getMsgInfo( + path = "messages/info/standard_msg_info_plaintext_with_one_att.json", + mimeMsgPath = "messages/mime/standard_msg_info_plaintext_with_one_att.txt", + atts = arrayOf(simpleAttInfo), + accountEntity = addAccountToDatabaseRule.accountEntityWithDecryptedInfo + ) { + it?.copy(msgEntity = it.msgEntity.copy(accountType = AccountEntity.ACCOUNT_TYPE_GOOGLE)) + } - try { - val incomingMessageInfo = getMsgInfo( - path = "messages/info/standard_msg_info_plaintext_with_one_att.json", - mimeMsgPath = "messages/mime/standard_msg_info_plaintext_with_one_att.txt", - atts = arrayOf(simpleAttInfo), - accountEntity = addAccountToDatabaseRule.accountEntityWithDecryptedInfo - ) { - it?.copy(msgEntity = it.msgEntity.copy(accountType = AccountEntity.ACCOUNT_TYPE_GOOGLE)) - } + baseCheckWithAtt(incomingMsgInfo = incomingMessageInfo, att = simpleAttInfo) { + waitForObjectWithText( + requireNotNull(incomingMessageInfo?.text), + TimeUnit.SECONDS.toMillis(10) + ) - //close the notification bar if needed - if (device.hasObject(By.res(NOTIFICATION_RESOURCES_NAME))) { - device.pressBack() - } + waitForObjectWithText( + requireNotNull(simpleAttInfo?.name), + TimeUnit.SECONDS.toMillis(10) + ) + } - baseCheckWithAtt(incomingMsgInfo = incomingMessageInfo, att = simpleAttInfo) { - waitForObjectWithText( - requireNotNull(incomingMessageInfo?.text), - TimeUnit.SECONDS.toMillis(10) - ) + onView(withId(R.id.imageViewAttIcon)) + .check(matches(withDrawable(R.drawable.ic_attachment))) - waitForObjectWithText( - requireNotNull(simpleAttInfo?.name), - TimeUnit.SECONDS.toMillis(10) - ) - } - - onView(withId(R.id.imageViewAttIcon)) - .check(matches(withDrawable(R.drawable.ic_attachment))) + //RetryRule reruns the test in the same process, so remove a notification of a previous run + notificationManager.cancelAll() + val attachmentResponseLatch = CountDownLatch(1) + attachmentResponseReleased.set(attachmentResponseLatch) + /* + The dialog closes itself right after the download. The mock web server doesn't return + the attachment until the dialog is checked, so a slow test thread can't miss it. + Release the response in any case: otherwise a failed check leaves the request waiting, + and stopping the mock web server hides the original failure. + */ + try { onView(withId(R.id.imageButtonDownloadAtt)) .check(matches(isDisplayed())) .perform(click()) isDialogWithTextDisplayed(decorView, getResString(R.string.downloading)) isDialogWithTextDisplayed(decorView, requireNotNull(simpleAttInfo?.name)) + } finally { + attachmentResponseLatch.countDown() + } - Thread.sleep(TimeUnit.SECONDS.toMillis(DELAY_FOR_DOWNLOADING_IN_SECONDS * 2)) + //the download can take a while on a slow CI emulator. Wait for the result + waitUntil(TimeUnit.SECONDS.toMillis(30)) { + isDownloadCompletedNotificationShown() + } + assertTrue( + "The 'download complete' notification is missing", + isDownloadCompletedNotificationShown() + ) - //at this stage icon should be as by default - onView(withId(R.id.imageViewAttIcon)) - .check(matches(withDrawable(R.drawable.ic_attachment))) + /* + At this stage the icon should be as by default. The screen updates the attachment item + after the download, and ListAdapter calculates the diff on a background thread that + Espresso doesn't track. Until it's done, the list can contain the old and the new item views. + */ + waitUntilViewMatches( + viewId = R.id.imageViewAttIcon, + matcher = withDrawable(R.drawable.ic_attachment) + ) + } - //open notification and check we have "End Pass Phrase Session" button - device.openNotification() - device.wait( - Until.hasObject(By.text(requireNotNull(simpleAttInfo.name))), - TimeUnit.SECONDS.toMillis(1) - ) - device.pressBack() - } finally { - //close the notification bar if needed - if (device.hasObject(By.res(NOTIFICATION_RESOURCES_NAME))) { - device.pressBack() - } + private fun isDownloadCompletedNotificationShown(): Boolean { + val expectedText = getResString(R.string.download_complete) + return notificationManager.activeNotifications.any { statusBarNotification -> + statusBarNotification.tag == simpleAttInfo?.id && + statusBarNotification.notification.extras + .getCharSequence(NotificationCompat.EXTRA_TEXT)?.toString() == expectedText } } companion object { val ATTACHMENT_ID = UUID.randomUUID().toString() - const val DELAY_FOR_DOWNLOADING_IN_SECONDS = 4L + private const val RELEASE_ATTACHMENT_RESPONSE_TIMEOUT_IN_SECONDS = 60L } } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest.kt index 3d6223c0ac..600f31b03d 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest.kt @@ -8,7 +8,7 @@ package com.flowcrypt.email.ui import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.clearText import androidx.test.espresso.action.ViewActions.pressImeActionButton -import androidx.test.espresso.action.ViewActions.typeText +import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId @@ -33,19 +33,22 @@ import com.flowcrypt.email.util.TestGeneralUtil import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest +import org.junit.Assert.assertEquals +import org.junit.Before import org.junit.ClassRule -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.RunWith import java.net.HttpURLConnection +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.TimeUnit /** * @author Denys Bondarenko */ -@FlowCryptTestSettings(useIntents = true) +@FlowCryptTestSettings(useCommonIdling = false, useIntents = true) @MediumTest @RunWith(AndroidJUnit4::class) class ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest : BaseTest() { @@ -81,31 +84,40 @@ class ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest : BaseTest() { .around(activityScenarioRule) .around(ScreenshotTestRule()) + @Before + fun clearRequestedLookups() { + attesterLookups.clear() + } + @Test fun testDisallowLookupOnAttester() { - onView(withId(R.id.eTKeyIdOrEmail)) - .perform( - clearText(), - typeText("user@$SOME_DOMAIN"), - pressImeActionButton() - ) + searchKey("user@$SOME_DOMAIN") - onView(withText(R.string.supported_public_key_not_found)) - .check(matches((isDisplayed()))) + val expectedText = getResString(R.string.supported_public_key_not_found) + waitForObjectWithText(expectedText, TimeUnit.SECONDS.toMillis(10)) + onView(withText(expectedText)).check(matches(isDisplayed())) + //the same text is shown when a lookup is sent and nothing is found + assertEquals(emptyList(), attesterLookups.toList()) } @Test - @Ignore("Need to fix. Flaky") fun testAllowAttesterSearchOnlyForDomains() { + searchKey(ALLOWED_USER) + + val expectedText = getResString(R.string.template_message_part_public_key_owner, ALLOWED_USER) + waitForObjectWithText(expectedText, TimeUnit.SECONDS.toMillis(10)) + onView(withText(expectedText)).check(matches(isDisplayed())) + assertEquals(listOf(ALLOWED_USER), attesterLookups.toList()) + } + + private fun searchKey(keyIdOrEmail: String) { + //typeText() can lose characters on a slow emulator when the IME session restarts onView(withId(R.id.eTKeyIdOrEmail)) .perform( clearText(), - typeText(ALLOWED_USER), + replaceText(keyIdOrEmail), pressImeActionButton() ) - - onView(withText(getResString(R.string.template_message_part_public_key_owner, ALLOWED_USER))) - .check(matches(isDisplayed())) } companion object { @@ -127,6 +139,9 @@ class ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest : BaseTest() { "=MoFp\n" + "-----END PGP PUBLIC KEY BLOCK-----" + //the mock web server adds them on its own thread + private val attesterLookups = ConcurrentLinkedQueue() + @get:ClassRule @JvmStatic val mockWebServerRule = FlowCryptMockWebServerRule( @@ -135,6 +150,7 @@ class ImportRecipientAllowAttesterSearchOnlyForDomainsFlowTest : BaseTest() { override fun dispatch(request: RecordedRequest): MockResponse { if (request.path?.startsWith("/attester/pub", ignoreCase = true) == true) { val lastSegment = request.requestUrl?.pathSegments?.lastOrNull() + lastSegment?.let { attesterLookups.add(it.lowercase()) } when { ALLOWED_USER.equals(lastSegment, true) -> { diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsChangeGmailLabelsFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsChangeGmailLabelsFlowTest.kt index 6387c66065..13c1de9d79 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsChangeGmailLabelsFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsChangeGmailLabelsFlowTest.kt @@ -13,6 +13,7 @@ import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.RootMatchers.isDialog +import androidx.test.espresso.matcher.ViewMatchers.hasMinimumChildCount import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText @@ -33,14 +34,16 @@ import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import okio.GzipSource import okio.buffer +import org.hamcrest.Matchers.allOf import org.junit.Assert.assertEquals -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.RunWith import java.net.HttpURLConnection +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicReference /** * @author Denys Bondarenko @@ -48,7 +51,9 @@ import java.net.HttpURLConnection @MediumTest @RunWith(AndroidJUnit4::class) class MessageDetailsChangeGmailLabelsFlowTest : BaseGmailLabelsFlowTest() { - private var lastLabelIds = mutableListOf() + //the mock web server changes them on its own thread + private val lastLabelIds = CopyOnWriteArrayList() + private val lastBatchModifyRequest = AtomicReference() private val mockWebServerRule = FlowCryptMockWebServerRule( TestConstants.MOCK_WEB_SERVER_PORT, @@ -68,15 +73,9 @@ class MessageDetailsChangeGmailLabelsFlowTest : BaseGmailLabelsFlowTest() { batchModifyMessagesRequest.removeLabelIds?.let { lastLabelIds.removeAll(it) } + //check it in the test thread. A failed assertion here doesn't fail the test + lastBatchModifyRequest.set(batchModifyMessagesRequest) - assertEquals( - LABELS.take(3).map { it.name }, - batchModifyMessagesRequest.removeLabelIds - ) - assertEquals( - LABELS.filter { it.name == "Test9" }.map { it.name }, - batchModifyMessagesRequest.addLabelIds - ) return MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) } @@ -99,19 +98,26 @@ class MessageDetailsChangeGmailLabelsFlowTest : BaseGmailLabelsFlowTest() { .around(ScreenshotTestRule()) @Test - @Ignore("flaky. Temporary disabled") fun testLabelsManagement() { val allLabels = initLabelIds() - lastLabelIds = (allLabels.take(4) + allLabels.takeLast(1)).toMutableList() + lastLabelIds.clear() + lastLabelIds.addAll(allLabels.take(4) + allLabels.takeLast(1)) + lastBatchModifyRequest.set(null) val details = genIncomingMessageInfo(labelsIds = lastLabelIds)?.msgEntity requireNotNull(details) launchActivity(details) - Thread.sleep(1000) + //the screen shows the message labels after loading the message + waitUntilViewMatches( + viewId = R.id.recyclerViewLabels, + matcher = allOf(isDisplayed(), hasMinimumChildCount(1)) + ) //open dialog by clicking on one of the labels onView(withId(R.id.recyclerViewLabels)) .perform(RecyclerViewActions.actionOnItemAtPosition(0, click())) + //'back' closes the screen if the dialog isn't shown yet + waitUntilLabelsDialogIsLoaded() //close dialog pressBack() @@ -120,6 +126,7 @@ class MessageDetailsChangeGmailLabelsFlowTest : BaseGmailLabelsFlowTest() { onView(withText(R.string.change_labels)) .check(matches(isDisplayed())) .perform(click()) + waitUntilLabelsDialogIsLoaded() //deselect the first 3 labels onView(withId(R.id.recyclerViewLabels)) @@ -156,13 +163,29 @@ class MessageDetailsChangeGmailLabelsFlowTest : BaseGmailLabelsFlowTest() { .inRoot(isDialog()) .perform(click()) - Thread.sleep(3000) - + waitUntil { lastBatchModifyRequest.get() != null } + val batchModifyRequest = requireNotNull(lastBatchModifyRequest.get()) { + "The app didn't send the 'batchModify' request" + } + assertEquals(LABELS.take(3).map { it.name }, batchModifyRequest.removeLabelIds) + assertEquals( + LABELS.filter { it.name == "Test9" }.map { it.name }, + batchModifyRequest.addLabelIds + ) assertEquals( allLabels.take(1) + allLabels.takeLast(1) + allLabels.filter { it == "Test9" }, - lastLabelIds + lastLabelIds.toList() + ) + } + + private fun waitUntilLabelsDialogIsLoaded() { + //the dialog shows the list after the labels are loaded asynchronously + waitUntilViewMatches( + viewId = R.id.recyclerViewLabels, + matcher = allOf(isDisplayed(), hasMinimumChildCount(3)), + root = isDialog() ) } } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsFlowTest.kt index f4e9fdd3d8..020a4c934b 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessageDetailsFlowTest.kt @@ -85,7 +85,6 @@ import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -151,7 +150,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testFwdButton() { testStandardMsgPlaintextInternal() onView(withId(R.id.forwardButton)) @@ -682,7 +680,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testSignedMsgClearSign() { val msgInfo = getMsgInfo( path = "messages/info/signed_msg_clearsign.json", @@ -806,7 +803,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testSignatureVerificationInbandOnlySignedPartially() { PrivateKeysManager.savePubKeyToDatabase("pgp/denbond7@flowcrypt.test_pub_primary.asc") @@ -825,7 +821,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testSignatureVerificationInbandEncryptedSignedPartially() { PrivateKeysManager.savePubKeyToDatabase("pgp/denbond7@flowcrypt.test_pub_primary.asc") @@ -880,7 +875,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testSignatureVerificationInbandOnlyEncrypted() { val msgInfo = getMsgInfo( path = "messages/info/signature_verification_inband_only_encrypted.json", @@ -916,7 +910,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testSignatureVerificationDetachedSignatureContentAndPublicKey() { PrivateKeysManager.savePubKeyToDatabase("pgp/denbond7@flowcrypt.test_pub_primary.asc") @@ -1039,7 +1032,6 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testSignatureVerificationCleartextOnlySignedPartially() { PrivateKeysManager.savePubKeyToDatabase("pgp/denbond7@flowcrypt.test_pub_primary.asc") diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessagesListChangeGmailLabelsFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessagesListChangeGmailLabelsFlowTest.kt index 4f35b67082..6339b53ac6 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessagesListChangeGmailLabelsFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/MessagesListChangeGmailLabelsFlowTest.kt @@ -12,6 +12,7 @@ import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition import androidx.test.espresso.matcher.RootMatchers.isDialog +import androidx.test.espresso.matcher.ViewMatchers.hasMinimumChildCount import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText @@ -24,6 +25,7 @@ import com.flowcrypt.email.api.email.JavaEmailConstants import com.flowcrypt.email.api.email.model.LocalFolder import com.flowcrypt.email.database.FlowCryptRoomDatabase import com.flowcrypt.email.database.entity.MessageEntity +import com.flowcrypt.email.junit.annotations.FlowCryptTestSettings import com.flowcrypt.email.rules.AddLabelsToDatabaseRule import com.flowcrypt.email.rules.ClearAppSettingsRule import com.flowcrypt.email.rules.FlowCryptMockWebServerRule @@ -42,12 +44,14 @@ import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import okio.GzipSource import okio.buffer +import org.hamcrest.Matchers.allOf import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.RunWith import java.net.HttpURLConnection +import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit /** @@ -55,8 +59,10 @@ import java.util.concurrent.TimeUnit */ @MediumTest @RunWith(AndroidJUnit4::class) +@FlowCryptTestSettings(useCommonIdling = false, useIntents = true) class MessagesListChangeGmailLabelsFlowTest : BaseGmailApiTest() { - private var lastLabelIds = mutableListOf() + //the mock web server changes it on its own thread + private val lastLabelIds = CopyOnWriteArrayList() override val mockWebServerRule = FlowCryptMockWebServerRule(TestConstants.MOCK_WEB_SERVER_PORT, object : Dispatcher() { @@ -149,6 +155,12 @@ class MessagesListChangeGmailLabelsFlowTest : BaseGmailApiTest() { .check(matches(isDisplayed())) .perform(click()) + //the dialog shows the list after the labels are loaded asynchronously + waitUntilViewMatches( + viewId = R.id.recyclerViewLabels, + matcher = allOf(isDisplayed(), hasMinimumChildCount(2)) + ) + //select the second and third labels onView(withId(R.id.recyclerViewLabels)) .perform(actionOnItemAtPosition(0, click())) @@ -161,42 +173,39 @@ class MessagesListChangeGmailLabelsFlowTest : BaseGmailApiTest() { waitForObjectWithText(CUSTOM_LABELS.first().name, TimeUnit.SECONDS.toMillis(10)) - //check API call results - assertEquals( - CUSTOM_LABELS.take(2).map { it.name }, - lastLabelIds - ) + /* + The screen can show the new labels before the API call and the database update are done. + Wait for both instead of checking them once. + */ + val expectedApiLabelIds = CUSTOM_LABELS.take(2).map { it.name } + waitUntil { lastLabelIds == expectedApiLabelIds } + assertEquals(expectedApiLabelIds, lastLabelIds.toList()) //check local changes for modified messages - val expectedLabelIds = - listOf(JavaEmailConstants.FOLDER_INBOX) + CUSTOM_LABELS.take(2).map { it.name } - assertEquals( - expectedLabelIds, - runBlocking { - FlowCryptRoomDatabase.getDatabase(getTargetContext()).msgDao().getMsgById( - requireNotNull(existingMessageEntities.first { it.subject == SUBJECT_EXISTING_ENCRYPTED }.id) - ) - }?.labelIds.orEmpty().split(MessageEntity.LABEL_IDS_SEPARATOR) - ) - assertEquals( - expectedLabelIds, - runBlocking { - FlowCryptRoomDatabase.getDatabase(getTargetContext()).msgDao().getMsgById( - requireNotNull(existingMessageEntities.first { it.subject == SUBJECT_EXISTING_STANDARD }.id) - ) - }?.labelIds.orEmpty().split(MessageEntity.LABEL_IDS_SEPARATOR) - ) + val expectedLabelIds = listOf(JavaEmailConstants.FOLDER_INBOX) + expectedApiLabelIds + val encryptedMsgId = existingMessageEntities.getId(SUBJECT_EXISTING_ENCRYPTED) + val standardMsgId = existingMessageEntities.getId(SUBJECT_EXISTING_STANDARD) + waitUntil { + getLabelIds(encryptedMsgId) == expectedLabelIds && + getLabelIds(standardMsgId) == expectedLabelIds + } + assertEquals(expectedLabelIds, getLabelIds(encryptedMsgId)) + assertEquals(expectedLabelIds, getLabelIds(standardMsgId)) + //as we didn't change the third message it should have only INBOX label assertEquals( listOf(JavaEmailConstants.FOLDER_INBOX), - runBlocking { - FlowCryptRoomDatabase.getDatabase(getTargetContext()).msgDao().getMsgById( - requireNotNull(existingMessageEntities.first { it.subject == SUBJECT_EXISTING_PGP_MIME }.id) - ) - }?.labelIds.orEmpty().split(MessageEntity.LABEL_IDS_SEPARATOR) + getLabelIds(existingMessageEntities.getId(SUBJECT_EXISTING_PGP_MIME)) ) } + private fun List.getId(subject: String): Long = + requireNotNull(first { it.subject == subject }.id) + + private fun getLabelIds(messageId: Long): List = runBlocking { + FlowCryptRoomDatabase.getDatabase(getTargetContext()).msgDao().getMsgById(messageId) + }?.labelIds.orEmpty().split(MessageEntity.LABEL_IDS_SEPARATOR) + companion object { private val CUSTOM_LABELS = listOf( GmailApiLabelsListAdapter.Label("LABEL_1", "#ff2323ff", "#FFFFFF"), diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/SignInScreenFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/SignInScreenFlowTest.kt index c3a5fbbb67..1a94b508eb 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/SignInScreenFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/SignInScreenFlowTest.kt @@ -33,6 +33,7 @@ import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.RunWith +import java.util.concurrent.TimeUnit /** * A test for [MainActivity] @@ -67,9 +68,16 @@ class SignInScreenFlowTest : BaseTest() { onView(withId(R.id.buttonSignInWithGmail)) .check(matches(isDisplayed())) .perform(click()) - //check that the Google Sign-in screen displayed + /* + Check that the Google Sign-in screen is displayed. On a slow emulator it can take a few + seconds: the Google Play services UI process can be frozen, and UiAutomator sees a new + window later. + */ val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) - assertTrue(device.wait(Until.hasObject(By.pkg("com.google.android.gms")), 5000)) + assertTrue( + "The Google Sign-in screen isn't displayed", + device.wait(Until.hasObject(By.pkg("com.google.android.gms")), TimeUnit.SECONDS.toMillis(30)) + ) device.pressBack() } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailApiSignatureFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailApiSignatureFlowTest.kt index 49fc16c3e7..04e452b28d 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailApiSignatureFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailApiSignatureFlowTest.kt @@ -21,6 +21,8 @@ import com.google.api.services.gmail.model.ListSendAsResponse import com.google.api.services.gmail.model.SendAs import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest +import org.hamcrest.Matcher +import org.hamcrest.Matchers.equalTo import java.net.HttpURLConnection /** @@ -64,10 +66,8 @@ abstract class BaseComposeGmailApiSignatureFlowTest : } } - protected fun doBaseChecking(){ - onView(withId(R.id.editTextEmailMessage)) - .perform(scrollTo()) - .check(matches(withText("\n\n$SIGNATURE_FOR_MAIN"))) + protected fun doBaseChecking() { + waitUntilMessageText(equalTo("\n\n$SIGNATURE_FOR_MAIN")) //switch to standard mode openActionBarOverflowOrOptionsMenu(getTargetContext()) @@ -75,9 +75,7 @@ abstract class BaseComposeGmailApiSignatureFlowTest : .check(matches(isDisplayed())) .perform(click()) - onView(withId(R.id.editTextEmailMessage)) - .perform(scrollTo()) - .check(matches(withText("\n\n$SIGNATURE_FOR_MAIN"))) + waitUntilMessageText(equalTo("\n\n$SIGNATURE_FOR_MAIN")) Espresso.closeSoftKeyboard() @@ -88,9 +86,15 @@ abstract class BaseComposeGmailApiSignatureFlowTest : .check(matches(isDisplayed())) .perform(click()) - onView(withId(R.id.editTextEmailMessage)) - .perform(scrollTo()) - .check(matches(withText("\n\n$SIGNATURE_FOR_ALIS"))) + waitUntilMessageText(equalTo("\n\n$SIGNATURE_FOR_ALIS")) + } + + /** + * The compose screen adds the signature asynchronously: after it loads the aliases + * (the 'sendAs' API call) and after the 'from' address is changed. + */ + protected fun waitUntilMessageText(matcher: Matcher) { + waitUntilViewMatches(viewId = R.id.editTextEmailMessage, matcher = withText(matcher)) } companion object { diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseMessageDetailsFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseMessageDetailsFlowTest.kt index 8481175a59..aa81064245 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseMessageDetailsFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseMessageDetailsFlowTest.kt @@ -6,6 +6,7 @@ package com.flowcrypt.email.ui.base import android.text.format.Formatter +import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ActivityScenario import androidx.test.espresso.Espresso.onView import androidx.test.espresso.IdlingRegistry @@ -54,6 +55,7 @@ import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.not import org.hamcrest.Matchers.notNullValue import org.junit.After +import java.util.concurrent.TimeUnit /** * @author Denys Bondarenko @@ -297,10 +299,30 @@ abstract class BaseMessageDetailsFlowTest : BaseTest() { badgeCount: Int, vararg badgeTypes: PgpBadgeListAdapter.PgpBadge.Type ) { + /* + The badges are shown after the message is processed asynchronously. Wait for the expected + types, not for the count only: while the app looks up the sender's key, the list already has + the final count with VERIFYING_SIGNATURE that is replaced later. + */ + val expectedTypes = badgeTypes.toSet() + waitUntil(TimeUnit.SECONDS.toMillis(10)) { + runCatching { + //the default failure handler takes a screenshot on every failed check + onView(withId(R.id.rVPgpBadges)) + .withFailureHandler { error, _ -> throw error } + .check { view, noViewFoundException -> + if (noViewFoundException != null) throw noViewFoundException + val adapter = (view as RecyclerView).adapter as PgpBadgeListAdapter + val actualTypes = adapter.currentList.map { it.type } + if (actualTypes.size != badgeCount || !actualTypes.containsAll(expectedTypes)) { + throw AssertionError("Unexpected PGP badges: $actualTypes") + } + } + }.isSuccess + } onView(withId(R.id.rVPgpBadges)) .check(matches(withRecyclerViewItemCount(badgeCount))) - for (badgeType in badgeTypes) { onView(withId(R.id.rVPgpBadges)) .perform( diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CheckCredentialsFragmentInIsolationTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CheckCredentialsFragmentInIsolationTest.kt index 813c83cb24..54afd178a3 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CheckCredentialsFragmentInIsolationTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CheckCredentialsFragmentInIsolationTest.kt @@ -14,6 +14,7 @@ import androidx.test.filters.MediumTest import com.flowcrypt.email.R import com.flowcrypt.email.api.retrofit.response.base.Result import com.flowcrypt.email.base.BaseTest +import com.flowcrypt.email.database.entity.AccountEntity import com.flowcrypt.email.extensions.android.os.getSerializableViaExt import com.flowcrypt.email.junit.annotations.DependsOnMailServer import com.flowcrypt.email.rules.AddAccountToDatabaseRule @@ -23,14 +24,17 @@ import com.flowcrypt.email.rules.RetryRule import com.flowcrypt.email.rules.ScreenshotTestRule import com.flowcrypt.email.ui.activity.fragment.CheckCredentialsFragment import com.flowcrypt.email.ui.activity.fragment.CheckCredentialsFragmentArgs +import jakarta.mail.AuthenticationFailedException import org.junit.Assert.assertEquals -import org.junit.Ignore +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.RunWith import java.util.UUID +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference /** * @author Denys Bondarenko @@ -50,63 +54,61 @@ class CheckCredentialsFragmentInIsolationTest : BaseTest() { .around(ScreenshotTestRule()) @Test - @Ignore("flaky. Temporary disabled") fun testReturnExceptionForFailedAuthorization() { - val requestKey = UUID.randomUUID().toString() - val scenario = launchFragmentInContainer( - fragmentArgs = CheckCredentialsFragmentArgs( - accountEntity = addAccountToDatabaseRule.account.copy( - email = "unknown@flowcrypt.test", - username = "unknown@flowcrypt.test" - ), - requestKey = requestKey - ).toBundle() + val actualResult = checkCredentials( + addAccountToDatabaseRule.account.copy( + email = "unknown@flowcrypt.test", + username = "unknown@flowcrypt.test" + ) ) - - lateinit var actualResult: Result<*> - scenario.onFragment { fragment -> - fragment.parentFragmentManager - .setFragmentResultListener( - requestKey, - fragment - ) { _, bundle -> - actualResult = requireNotNull( - bundle.getSerializableViaExt(CheckCredentialsFragment.KEY_CHECK_ACCOUNT_SETTINGS_RESULT) as? Result<*> - ) - } - } - - onView(withId(R.id.progress)) - .check(matches(isDisplayed())) assertEquals(Result.Status.EXCEPTION, actualResult.status) + //a network error or a timeout gives the same status, so check the cause as well + val causes = generateSequence(actualResult.exception) { it.cause }.toList() + assertTrue( + "Expected AuthenticationFailedException in the causes: $causes", + causes.any { it is AuthenticationFailedException } + ) } @Test fun testAuthorizationSuccess() { + val actualResult = checkCredentials(addAccountToDatabaseRule.account) + assertEquals(Result.Status.SUCCESS, actualResult.status) + assertEquals(true, actualResult.data as Boolean) + } + + private fun checkCredentials(accountEntity: AccountEntity): Result<*> { val requestKey = UUID.randomUUID().toString() val scenario = launchFragmentInContainer( fragmentArgs = CheckCredentialsFragmentArgs( - accountEntity = addAccountToDatabaseRule.account, + accountEntity = accountEntity, requestKey = requestKey ).toBundle() ) - lateinit var actualResult: Result<*> + //the listener runs on the main thread, the test reads the result on its own thread + val actualResult = AtomicReference?>() scenario.onFragment { fragment -> fragment.parentFragmentManager .setFragmentResultListener( requestKey, fragment ) { _, bundle -> - actualResult = requireNotNull( - bundle.getSerializableViaExt(CheckCredentialsFragment.KEY_CHECK_ACCOUNT_SETTINGS_RESULT) as? Result<*> + actualResult.set( + requireNotNull( + bundle.getSerializableViaExt( + CheckCredentialsFragment.KEY_CHECK_ACCOUNT_SETTINGS_RESULT + ) as? Result<*> + ) ) } } onView(withId(R.id.progress)) .check(matches(isDisplayed())) - assertEquals(Result.Status.SUCCESS, actualResult.status) - assertEquals(true, actualResult.data as Boolean) + + //the fragment returns the result after it connects to the mail server + waitUntil(TimeUnit.SECONDS.toMillis(60)) { actualResult.get() != null } + return requireNotNull(actualResult.get()) { "CheckCredentialsFragment didn't return a result" } } } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenForwardWithGmailApiSignatureFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenForwardWithGmailApiSignatureFlowTest.kt index 8dd6a17bc8..5d90fe7b4c 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenForwardWithGmailApiSignatureFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenForwardWithGmailApiSignatureFlowTest.kt @@ -32,7 +32,6 @@ import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import org.hamcrest.Matchers.startsWith -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -73,10 +72,9 @@ class ComposeScreenForwardWithGmailApiSignatureFlowTest : .around(ScreenshotTestRule()) @Test - @Ignore("flaky. It looks like adding signature after start has unexpected result for forwarding case") fun testAddingSignatureAfterStart() { //need to wait while the app loads the messages list - Thread.sleep(2000) + waitForObjectWithText(SUBJECT_EXISTING_ENCRYPTED, TimeUnit.SECONDS.toMillis(10)) //click on a message onView(withId(R.id.recyclerViewMsgs)) @@ -92,12 +90,7 @@ class ComposeScreenForwardWithGmailApiSignatureFlowTest : //click on forward button openReplyScreen(R.id.forwardButton, SUBJECT_EXISTING_ENCRYPTED) - //need to wait while all action for reply case will be applied - Thread.sleep(1000) - - onView(withId(R.id.editTextEmailMessage)) - .perform(scrollTo()) - .check(matches(withText(startsWith("\n\n$SIGNATURE_FOR_MAIN")))) + waitUntilMessageText(startsWith("\n\n$SIGNATURE_FOR_MAIN")) //switch to standard mode openActionBarOverflowOrOptionsMenu(getTargetContext()) @@ -107,9 +100,7 @@ class ComposeScreenForwardWithGmailApiSignatureFlowTest : closeSoftKeyboard() - onView(withId(R.id.editTextEmailMessage)) - .perform(scrollTo()) - .check(matches(withText(startsWith("\n\n$SIGNATURE_FOR_MAIN")))) + waitUntilMessageText(startsWith("\n\n$SIGNATURE_FOR_MAIN")) onView(withId(R.id.imageButtonAliases)) .perform(scrollTo()) @@ -119,8 +110,6 @@ class ComposeScreenForwardWithGmailApiSignatureFlowTest : .check(matches(isDisplayed())) .perform(click()) - onView(withId(R.id.editTextEmailMessage)) - .perform(scrollTo()) - .check(matches(withText(startsWith("\n\n$SIGNATURE_FOR_ALIS")))) + waitUntilMessageText(startsWith("\n\n$SIGNATURE_FOR_ALIS")) } } \ No newline at end of file diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenNewMessageWithGmailApiSignatureFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenNewMessageWithGmailApiSignatureFlowTest.kt index d5e4f94696..7bebf12a21 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenNewMessageWithGmailApiSignatureFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenNewMessageWithGmailApiSignatureFlowTest.kt @@ -19,7 +19,6 @@ import com.flowcrypt.email.ui.base.BaseComposeGmailApiSignatureFlowTest import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -58,10 +57,7 @@ class ComposeScreenNewMessageWithGmailApiSignatureFlowTest : .around(ScreenshotTestRule()) @Test - @Ignore("Temporary disabled as flaky") fun testAddingSignatureAfterStart() { - Thread.sleep(1000) - doBaseChecking() } } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenReplyWithGmailApiSignatureFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenReplyWithGmailApiSignatureFlowTest.kt index 8da6494dc5..2a04eb13b5 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenReplyWithGmailApiSignatureFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/ComposeScreenReplyWithGmailApiSignatureFlowTest.kt @@ -26,7 +26,6 @@ import com.flowcrypt.email.ui.base.BaseComposeGmailApiSignatureFlowTest import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -68,7 +67,6 @@ class ComposeScreenReplyWithGmailApiSignatureFlowTest : @Test @FlakyTest - @Ignore("Temporary disabled as flaky") fun testAddingSignatureAfterStart() { //need to wait while the app loads the messages list waitForObjectWithText(SUBJECT_EXISTING_STANDARD, TimeUnit.SECONDS.toMillis(10)) @@ -87,9 +85,6 @@ class ComposeScreenReplyWithGmailApiSignatureFlowTest : //click on replyAll openReplyScreen(R.id.replyButton, SUBJECT_EXISTING_ENCRYPTED) - //need to wait while all action for reply case will be applied - Thread.sleep(1000) - doBaseChecking() } } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModel.kt index a23281ac27..310240b319 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModel.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/AccountAliasesViewModel.kt @@ -47,7 +47,8 @@ class AccountAliasesViewModel(application: Application) : AccountViewModel(appli fetchFreshestAliasesMutableStateFlow.value = Result.loading() } val freshestAliases = fetchAliases(getApplication(), accountEntity.account) - roomDatabase.accountAliasesDao().updateAliases(activeAccountLiveData.value, freshestAliases) + //activeAccountLiveData can still be empty here, e.g. on a slow device + roomDatabase.accountAliasesDao().updateAliases(accountEntity, freshestAliases) val hasAliasesSignature = roomDatabase.accountAliasesDao().getAliases( account = accountEntity.email, diff --git a/docs/testing-like-ci.md b/docs/testing-like-ci.md index ca93173ecd..314e5c93ec 100644 --- a/docs/testing-like-ci.md +++ b/docs/testing-like-ci.md @@ -69,6 +69,7 @@ ANDROID_SERIAL=emulator-5560 ./script/ci-wait-for-emulator.sh This is the script CI runs. It waits for boot and then: - disables animations and sets `long_press_timeout` to 1500 ms; +- hides system crash/ANR dialogs (`hide_error_dialogs`), so they don't take the window focus; - disables the keyboard (IME), so `typeText()` doesn't lose characters, and fails if any IME is still enabled. Set `DISABLE_IME=0` to keep it; - runs `adb root` and redirects `127.0.0.1:443` to the mock web server port `1212` (`iptables`); @@ -135,7 +136,8 @@ Look at logcat (`adb logcat -d`) and at the view hierarchy dumps in | What you see | What it means | |---|---| | `Overslept and turned a tap into a long press` | The tap took longer than `long_press_timeout`, the view got a long click (e.g. a menu item shows its tooltip). | -| `RootViewWithoutFocusException`, `mCurrentFocus=... Application Not Responding: com.android.systemui` in `adb shell dumpsys window` | "System UI isn't responding" right after boot. `BaseTest.dismissANRSystemDialogIfExists()` taps `android:id/aerr_wait`. | +| `RootViewWithoutFocusException`, `mCurrentFocus=... Application Not Responding: com.android.systemui` in `adb shell dumpsys window` | "System UI isn't responding" right after boot. `ci-wait-for-emulator.sh` sets `hide_error_dialogs`, so the system doesn't show such dialogs. `BaseTest.dismissANRSystemDialogIfExists()` also taps `android:id/aerr_wait`. | +| Many unrelated tests of one shard fail with `RootViewWithoutFocusException`, logcat shows `ANR in system` and `Application Not Responding: system` windows again and again | `system_server` reported an ANR right after boot, and the system shows "Process system isn't responding" for the rest of the job. A dialog dismissed in `@Before` comes back during the test. Check that `adb shell settings get global hide_error_dialogs` returns `1`. | | `commitText on inactive InputConnection`, `Session id mismatch` during `typeText()` | The IME reconnects and key events are lost (`"message"` → `"essage"`). Use `replaceText()` or insert text without key events. | | A toast instead of the expected dialog after clicking Send | The compose screen is still looking up a recipient's key (`please_wait_while_information_about_recipients_will_be_updated`). | | A click opens another screen | The layout moved between computing the click coordinates and the click (a button appeared or the keyboard opened). | diff --git a/script/ci-wait-for-emulator.sh b/script/ci-wait-for-emulator.sh index 2d406ce0ac..688e3abc32 100755 --- a/script/ci-wait-for-emulator.sh +++ b/script/ci-wait-for-emulator.sh @@ -167,6 +167,13 @@ adb shell settings put global animator_duration_scale 0 # a long click instead of a click (e.g. a toolbar menu item shows its tooltip). adb shell settings put secure long_press_timeout 1500 +# Right after boot a slow emulator can report an ANR even for system_server. Then the system shows +# "Process system isn't responding" again and again for the whole job. The dialog takes the window +# focus, and every test that is running at that moment fails with RootViewWithoutFocusException. +# Don't show crash/ANR dialogs at all. Crashes and ANRs are still logged ("FATAL EXCEPTION", +# "ANR in"), and a test fails anyway if the app crashes or stops responding. +adb shell settings put global hide_error_dialogs 1 + # On slow emulators the IME (Gboard) restarts its input session after focus changes, and the app # drops text committed to the old session ("Session id mismatch ... commitText" in logcat). # typeText() then loses characters, e.g. "message" -> "essage". Without an IME, Espresso key events