From c875d4c4f06a208890197510778545022296f741 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Fri, 13 Nov 2026 21:58:16 +0200 Subject: [PATCH 01/18] ci: raise emulator long press timeout --- script/ci-wait-for-emulator.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/script/ci-wait-for-emulator.sh b/script/ci-wait-for-emulator.sh index 2cf0c8594..3c3b51f19 100755 --- a/script/ci-wait-for-emulator.sh +++ b/script/ci-wait-for-emulator.sh @@ -162,6 +162,11 @@ adb shell settings put global window_animation_scale 0 adb shell settings put global transition_animation_scale 0 adb shell settings put global animator_duration_scale 0 +# CI emulators are slow. When injecting a tap takes longer than long_press_timeout (400 ms by +# default), Espresso logs "Overslept and turned a tap into a long press" and the view gets +# 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 + ################################################################################################### # To test WKD we need to route all traffic for localhost:443 to localhost:1212 # as we can't use 443 directly for a mock web server. From 8086071cbdb447073997cfae7b69d3562ee245fd Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Fri, 13 Nov 2026 21:58:25 +0200 Subject: [PATCH 02/18] test: fix flaky password-protected tests --- ...eenPasswordProtectedDisallowedTermsTest.kt | 52 +++++++++++++++++++ ...llowedTermsReFetchConfigurationFlowTest.kt | 33 +++++++++--- 2 files changed, 78 insertions(+), 7 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt index d532e4191..e2a34e4f5 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt @@ -5,6 +5,7 @@ package com.flowcrypt.email.ui.gmailapi.passwordprotected +import android.os.SystemClock import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard @@ -19,14 +20,18 @@ import androidx.test.espresso.matcher.ViewMatchers.withText import com.flowcrypt.email.R import com.flowcrypt.email.TestConstants import com.flowcrypt.email.database.entity.AccountEntity +import com.flowcrypt.email.matchers.CustomMatchers.Companion.withChipsBackgroundColor import com.flowcrypt.email.matchers.CustomMatchers.Companion.withTextViewDrawable import com.flowcrypt.email.matchers.TextViewDrawableMatcher import com.flowcrypt.email.rules.FlowCryptMockWebServerRule +import com.flowcrypt.email.ui.adapter.RecipientChipRecyclerViewAdapter import com.flowcrypt.email.ui.base.BaseComposeGmailFlow import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest +import org.hamcrest.Matchers.allOf import org.junit.Before +import java.util.concurrent.TimeUnit /** * @author Denys Bondarenko @@ -70,6 +75,53 @@ open class BaseComposeScreenPasswordProtectedDisallowedTermsTest( onView(withId(R.id.btSetPassword)) .perform(click()) + + //returning to the compose screen starts a new lookup for the recipient. + //Sending is blocked while it is in progress + waitUntilRecipientChipIsSettled( + email = TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY + ) + } + + /** + * The lookup starts asynchronously, so a single check can pass before it begins. + * Wait until the chip keeps its final color (it is white while the lookup is in progress) + * during [stableForMs]. + */ + private fun waitUntilRecipientChipIsSettled( + email: String, + colorResId: Int, + stableForMs: Long = TimeUnit.SECONDS.toMillis(1), + timeoutMs: Long = TimeUnit.SECONDS.toMillis(30) + ) { + val chipMatcher = allOf( + withText(email), + withChipsBackgroundColor(getTargetContext(), colorResId) + ) + val startTime = SystemClock.uptimeMillis() + var settledSince: Long? = null + while (true) { + val now = SystemClock.uptimeMillis() + val isSettled = runCatching { + onView(chipMatcher).check(matches(isDisplayed())) + }.isSuccess + + if (isSettled) { + val since = settledSince ?: now.also { settledSince = it } + if (now - since >= stableForMs) return + } else { + settledSince = null + } + + if (now - startTime >= timeoutMs) { + //fail with a clear Espresso error + onView(chipMatcher).check(matches(isDisplayed())) + return + } + + SystemClock.sleep(100) + } } companion object { diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest.kt index df6d76464..8f3191a55 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest.kt @@ -40,12 +40,12 @@ import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import org.hamcrest.Matchers.allOf -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 org.junit.runners.model.Statement import java.net.HttpURLConnection import java.util.concurrent.TimeUnit @@ -64,20 +64,25 @@ import java.util.concurrent.TimeUnit subject = "", isNew = true ) -@Ignore("temporary disabled") class ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest : BaseComposeScreenPasswordProtectedDisallowedTermsTest( ACCOUNT_ENTITY_WITH_EXISTING_OPTIONAL_PARAMETERS ) { - private var attemptsToUseDefaultBehavior = 2 + /** + * The app fetches the client configuration a few times before the test triggers the re-fetch + * (activity start, setting a web portal password). The exact count depends on timing, + * so the updated configuration is returned only after the test explicitly asks for it. + */ + @Volatile + private var isUpdatedClientConfigurationEnabled = false override val mockWebServerRule = FlowCryptMockWebServerRule(TestConstants.MOCK_WEB_SERVER_PORT, object : Dispatcher() { override fun dispatch(request: RecordedRequest): MockResponse { return when { request.path.equals("/api/v1/client-configuration?domain=flowcrypt.test") -> { - if (attemptsToUseDefaultBehavior == 0) { + if (isUpdatedClientConfigurationEnabled) { MockResponse() .setResponseCode(HttpURLConnection.HTTP_OK) .setBody( @@ -91,7 +96,6 @@ class ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest ) ) } else { - attemptsToUseDefaultBehavior-- handleCommonAPICalls(request) } } @@ -104,6 +108,15 @@ class ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest @get:Rule var ruleChain: TestRule = RuleChain.outerRule(RetryRule.DEFAULT) + //RetryRule reuses this instance, so every attempt must start with the default configuration + .around(TestRule { base, _ -> + object : Statement() { + override fun evaluate() { + isUpdatedClientConfigurationEnabled = false + base.evaluate() + } + } + }) .around(ClearAppSettingsRule()) .around(GrantPermissionRuleChooser.grant(Manifest.permission.POST_NOTIFICATIONS)) .around(mockWebServerRule) @@ -151,12 +164,18 @@ class ComposeScreenPasswordProtectedDisallowedTermsReFetchConfigurationFlowTest .perform(click()) } + isUpdatedClientConfigurationEnabled = true + //go to ProvidePasswordToProtectMsgFragment and go back to trigger updating onView(withId(R.id.btnSetWebPortalPassword)) .perform(click()) Espresso.pressBack() - //need to wait while threads will be synced - Thread.sleep(2000) + + //wait until RefreshClientConfigurationWorker saves the updated client configuration + waitUntil(TimeUnit.SECONDS.toMillis(30)) { + roomDatabase.accountDao().getActiveAccount() + ?.clientConfiguration?.disallowPasswordMessagesErrorText == UPDATED_ERROR_TEXT + } //check that client configuration was updated MATCHING_SUBJECTS.first().let { subject -> From e6d2d5c79ee02397ecd9f680678095af322cc96c Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Sat, 14 Nov 2026 19:33:03 +0200 Subject: [PATCH 03/18] test: fix ANR dialog dismissal --- .../java/com/flowcrypt/email/base/BaseTest.kt | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 df81ac88f..4ff1e1f42 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt @@ -40,7 +40,6 @@ import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiT import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice -import androidx.test.uiautomator.UiSelector import androidx.test.uiautomator.Until import com.flowcrypt.email.BuildConfig import com.flowcrypt.email.Constants @@ -104,9 +103,13 @@ abstract class BaseTest : BaseActivityTestImplementation { @Before fun dismissANRSystemDialogIfExists() { val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) - val waitButton = device.findObject(UiSelector().textContains("wait")) - if (waitButton.exists()) { + //a slow emulator can show "System UI isn't responding" for a few minutes after boot. + //The dialog can appear again right after we dismiss it, so we repeat it a few times + val deadline = SystemClock.uptimeMillis() + TimeUnit.SECONDS.toMillis(60) + while (SystemClock.uptimeMillis() < deadline) { + val waitButton = device.findObject(By.res("android", "aerr_wait")) ?: break waitButton.click() + device.wait(Until.gone(By.res("android", "aerr_wait")), TimeUnit.SECONDS.toMillis(5)) } //close the notification bar if needed From 355eee744dfee4545c7b7dde1280d420acba0441 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Sat, 14 Nov 2026 19:33:22 +0200 Subject: [PATCH 04/18] test: share recipient chip wait --- .../java/com/flowcrypt/email/base/BaseTest.kt | 42 ++++++++++++++++++ ...eenPasswordProtectedDisallowedTermsTest.kt | 44 ------------------- 2 files changed, 42 insertions(+), 44 deletions(-) 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 4ff1e1f42..c3a6be347 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/base/BaseTest.kt @@ -52,6 +52,7 @@ import com.flowcrypt.email.database.entity.AccountEntity import com.flowcrypt.email.database.entity.AttachmentEntity import com.flowcrypt.email.extensions.kotlin.toInputStream import com.flowcrypt.email.extensions.shutdown +import com.flowcrypt.email.matchers.CustomMatchers.Companion.withChipsBackgroundColor import com.flowcrypt.email.rules.FlowCryptTestSettingsRule import com.flowcrypt.email.util.FlavorSettings import com.flowcrypt.email.util.TestGeneralUtil @@ -406,6 +407,47 @@ abstract class BaseTest : BaseActivityTestImplementation { } } + /** + * 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 + * blocks sending during that time. The lookup can start asynchronously, + * so a single check can pass before it begins. + */ + protected fun waitUntilRecipientChipIsSettled( + email: String, + colorResId: Int, + stableForMs: Long = TimeUnit.SECONDS.toMillis(1), + timeoutMs: Long = TimeUnit.SECONDS.toMillis(30) + ) { + val chipMatcher = allOf( + withText(email), + withChipsBackgroundColor(getTargetContext(), colorResId) + ) + val startTime = SystemClock.uptimeMillis() + var settledSince: Long? = null + while (true) { + val now = SystemClock.uptimeMillis() + val isSettled = runCatching { + onView(chipMatcher).check(matches(isDisplayed())) + }.isSuccess + + if (isSettled) { + val since = settledSince ?: now.also { settledSince = it } + if (now - since >= stableForMs) return + } else { + settledSince = null + } + + if (now - startTime >= timeoutMs) { + //fail with a clear Espresso error + onView(chipMatcher).check(matches(isDisplayed())) + return + } + + SystemClock.sleep(100) + } + } + protected fun getIdentifierByName(name: String): Int { return getTargetContext() .resources diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt index e2a34e4f5..3a289429c 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/passwordprotected/BaseComposeScreenPasswordProtectedDisallowedTermsTest.kt @@ -5,7 +5,6 @@ package com.flowcrypt.email.ui.gmailapi.passwordprotected -import android.os.SystemClock import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard @@ -20,7 +19,6 @@ import androidx.test.espresso.matcher.ViewMatchers.withText import com.flowcrypt.email.R import com.flowcrypt.email.TestConstants import com.flowcrypt.email.database.entity.AccountEntity -import com.flowcrypt.email.matchers.CustomMatchers.Companion.withChipsBackgroundColor import com.flowcrypt.email.matchers.CustomMatchers.Companion.withTextViewDrawable import com.flowcrypt.email.matchers.TextViewDrawableMatcher import com.flowcrypt.email.rules.FlowCryptMockWebServerRule @@ -29,9 +27,7 @@ import com.flowcrypt.email.ui.base.BaseComposeGmailFlow import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest -import org.hamcrest.Matchers.allOf import org.junit.Before -import java.util.concurrent.TimeUnit /** * @author Denys Bondarenko @@ -84,46 +80,6 @@ open class BaseComposeScreenPasswordProtectedDisallowedTermsTest( ) } - /** - * The lookup starts asynchronously, so a single check can pass before it begins. - * Wait until the chip keeps its final color (it is white while the lookup is in progress) - * during [stableForMs]. - */ - private fun waitUntilRecipientChipIsSettled( - email: String, - colorResId: Int, - stableForMs: Long = TimeUnit.SECONDS.toMillis(1), - timeoutMs: Long = TimeUnit.SECONDS.toMillis(30) - ) { - val chipMatcher = allOf( - withText(email), - withChipsBackgroundColor(getTargetContext(), colorResId) - ) - val startTime = SystemClock.uptimeMillis() - var settledSince: Long? = null - while (true) { - val now = SystemClock.uptimeMillis() - val isSettled = runCatching { - onView(chipMatcher).check(matches(isDisplayed())) - }.isSuccess - - if (isSettled) { - val since = settledSince ?: now.also { settledSince = it } - if (now - since >= stableForMs) return - } else { - settledSince = null - } - - if (now - startTime >= timeoutMs) { - //fail with a clear Espresso error - onView(chipMatcher).check(matches(isDisplayed())) - return - } - - SystemClock.sleep(100) - } - } - companion object { private const val PASSWORD = "Qwerty1234@" const val URL = "https://flowcrypt.com" From a93e6243497d2f398558eecbef1b07f79cecf0bb Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Sat, 14 Nov 2026 19:33:28 +0200 Subject: [PATCH 05/18] test: fix flaky ComposeScreenFlowTest --- .../com/flowcrypt/email/ui/ComposeScreenFlowTest.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt index f05ddb81e..71a31435a 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt @@ -175,6 +175,12 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { replaceText(TestConstants.RECIPIENT_WITH_PUBLIC_KEY_ON_ATTESTER), pressImeActionButton() ) + //while the lookup is in progress the screen shows the web portal password button, + //and the layout shifts when it is hidden. Also sending is blocked until the lookup is done + waitUntilRecipientChipIsSettled( + email = TestConstants.RECIPIENT_WITH_PUBLIC_KEY_ON_ATTESTER, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_HAS_USABLE_PUB_KEY + ) onView(withId(R.id.editTextEmailSubject)) .check(matches(isDisplayed())) .perform(scrollTo(), click(), replaceText(EMAIL_SUBJECT)) @@ -591,12 +597,19 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { EmailUtil.genAttInfoFromPubKey(secondKeyDetails, addAccountToDatabaseRule.account.email) activeActivityRule?.launch(intent) + waitForObjectWithText( + getResString(R.string.prompt_compose_security_email), + TimeUnit.SECONDS.toMillis(10) + ) openActionBarOverflowOrOptionsMenu(getTargetContext()) onView(withText(R.string.include_public_key)) .check(matches(isDisplayed())) .perform(click()) + //keys are loaded asynchronously, the list is hidden until they are ready + waitForObjectWithResourceName("listViewKeys", TimeUnit.SECONDS.toMillis(10)) + onData(withPubKeyName(att?.name)) .inAdapterView(withId(R.id.listViewKeys)) .perform(click()) From f514ea5e162236d1d03f13c12638cebcd49cef11 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Sat, 14 Nov 2026 19:33:40 +0200 Subject: [PATCH 06/18] test: wait for public key dialog --- .../email/ui/base/BaseComposeGmailFlow.kt | 20 +++++++++++++++++++ ...mentsAndOwnPublicKeyComposeGmailApiFlow.kt | 7 +------ ...rdProtectedEncryptedComposeGmailApiFlow.kt | 7 +------ ...tandardWithPublicKeyComposeGmailApiFlow.kt | 5 +---- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt index 656e7e2aa..480da234b 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt @@ -6,6 +6,7 @@ package com.flowcrypt.email.ui.base import androidx.test.espresso.Espresso.onView +import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.scrollTo import androidx.test.espresso.assertion.ViewAssertions.matches @@ -186,6 +187,25 @@ abstract class BaseComposeGmailFlow(accountEntity: AccountEntity = BASE_ACCOUNT_ ) } + /** + * Attach the sender's own public key. [com.flowcrypt.email.ui.activity.fragment.dialog.ChoosePublicKeyDialogFragment] + * loads keys asynchronously and closes itself when there is a single key. + * Until then the dialog has the window focus, so we wait until the compose screen + * is in focus again (its Send action can be found). + */ + protected fun includeOwnPublicKey() { + openActionBarOverflowOrOptionsMenu(getTargetContext()) + onView(ViewMatchers.withText(R.string.include_public_key)) + .check(matches(isDisplayed())) + .perform(click()) + + waitUntil(TimeUnit.SECONDS.toMillis(10)) { + runCatching { + onView(withId(R.id.menuActionSend)).check(matches(isDisplayed())) + }.isSuccess + } + } + protected fun extractKeyId(pgpKeyRingDetails: PgpKeyRingDetails): Long { return PgpKey.parseKeys(pgpKeyRingDetails.publicKey) .pgpKeyRingCollection diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/EncryptedWithAttachmentsAndOwnPublicKeyComposeGmailApiFlow.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/EncryptedWithAttachmentsAndOwnPublicKeyComposeGmailApiFlow.kt index 5fdd0ece5..45f36a727 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/EncryptedWithAttachmentsAndOwnPublicKeyComposeGmailApiFlow.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/EncryptedWithAttachmentsAndOwnPublicKeyComposeGmailApiFlow.kt @@ -9,12 +9,10 @@ package com.flowcrypt.email.ui.gmailapi * @author Denys Bondarenko */ import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.FlakyTest import androidx.test.filters.MediumTest @@ -82,10 +80,7 @@ class EncryptedWithAttachmentsAndOwnPublicKeyComposeGmailApiFlow : BaseComposeGm } //attach a public key - openActionBarOverflowOrOptionsMenu(getTargetContext()) - onView(withText(R.string.include_public_key)) - .check(matches(isDisplayed())) - .perform(click()) + includeOwnPublicKey() //enqueue outgoing message onView(withId(R.id.menuActionSend)) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/PasswordProtectedEncryptedComposeGmailApiFlow.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/PasswordProtectedEncryptedComposeGmailApiFlow.kt index 62d52b0a3..41d3695c4 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/PasswordProtectedEncryptedComposeGmailApiFlow.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/PasswordProtectedEncryptedComposeGmailApiFlow.kt @@ -6,13 +6,11 @@ package com.flowcrypt.email.ui.gmailapi import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu import androidx.test.espresso.action.ViewActions.click 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 -import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.FlakyTest import androidx.test.filters.LargeTest @@ -168,10 +166,7 @@ class PasswordProtectedEncryptedComposeGmailApiFlow : BaseComposeGmailFlow() { } //attach a public key - openActionBarOverflowOrOptionsMenu(getTargetContext()) - onView(withText(R.string.include_public_key)) - .check(matches(isDisplayed())) - .perform(click()) + includeOwnPublicKey() //add password-protected logic onView(withId(R.id.btnSetWebPortalPassword)) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/StandardWithPublicKeyComposeGmailApiFlow.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/StandardWithPublicKeyComposeGmailApiFlow.kt index dc477b801..f104f3f99 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/StandardWithPublicKeyComposeGmailApiFlow.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/gmailapi/StandardWithPublicKeyComposeGmailApiFlow.kt @@ -81,10 +81,7 @@ class StandardWithPublicKeyComposeGmailApiFlow : BaseComposeGmailFlow() { .perform(click()) //attach a public key - openActionBarOverflowOrOptionsMenu(getTargetContext()) - onView(withText(R.string.include_public_key)) - .check(matches(isDisplayed())) - .perform(click()) + includeOwnPublicKey() //enqueue outgoing message onView(withId(R.id.menuActionSend)) From 818d6aa8f292586d12765d746bd72b642e075352 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Sat, 14 Nov 2026 19:33:40 +0200 Subject: [PATCH 07/18] test: fix sending checks race --- ...raftsGmailAPITestCorrectSendingFlowTest.kt | 18 ++++++++--- .../email/ui/base/BaseComposeGmailFlow.kt | 32 +++++++++++-------- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/DraftsGmailAPITestCorrectSendingFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/DraftsGmailAPITestCorrectSendingFlowTest.kt index 1f06aca03..f8eef0fd8 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/DraftsGmailAPITestCorrectSendingFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/DraftsGmailAPITestCorrectSendingFlowTest.kt @@ -30,6 +30,7 @@ import com.flowcrypt.email.rules.FlowCryptMockWebServerRule import com.flowcrypt.email.rules.GrantPermissionRuleChooser import com.flowcrypt.email.rules.RetryRule import com.flowcrypt.email.rules.ScreenshotTestRule +import com.flowcrypt.email.ui.adapter.RecipientChipRecyclerViewAdapter import com.flowcrypt.email.ui.base.BaseDraftsGmailAPIFlowTest import com.flowcrypt.email.util.TestGeneralUtil import com.flowcrypt.email.viewaction.ClickOnViewInRecyclerViewItem @@ -50,6 +51,7 @@ import org.junit.rules.TestRule import org.junit.runner.RunWith import java.io.InputStreamReader import java.net.HttpURLConnection +import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream @@ -61,7 +63,8 @@ import java.util.zip.GZIPInputStream @RunWith(AndroidJUnit4::class) @FlowCryptTestSettings(useCommonIdling = false) class DraftsGmailAPITestCorrectSendingFlowTest : BaseDraftsGmailAPIFlowTest() { - private val sentCache = mutableListOf() + //it's filled by the mock web server thread and read by the test thread + private val sentCache = CopyOnWriteArrayList() override val mockWebServerRule: FlowCryptMockWebServerRule = FlowCryptMockWebServerRule( TestConstants.MOCK_WEB_SERVER_PORT, object : Dispatcher() { @@ -186,16 +189,23 @@ class DraftsGmailAPITestCorrectSendingFlowTest : BaseDraftsGmailAPIFlowTest() { pressImeActionButton() ) + //sending is blocked while the recipient lookup is in progress + waitUntilRecipientChipIsSettled( + email = TestConstants.RECIPIENT_WITH_PUBLIC_KEY_ON_ATTESTER, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_HAS_USABLE_PUB_KEY + ) + onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) .perform(click()) - //need to wait while a message will be sent - waitUntil { + //need to wait while a message will be sent. Right after clicking 'Send' the message may not + //be added to the outbox yet, so an empty outbox alone doesn't mean the message was sent + waitUntil(TimeUnit.SECONDS.toMillis(30)) { val countOfOutgoingMessages = runBlocking { roomDatabase.msgDao().getOutboxMsgsSuspend(addAccountToDatabaseRule.account.email).size } - countOfOutgoingMessages == 0 + countOfOutgoingMessages == 0 && sentCache.isNotEmpty() } assertEquals(0, runBlocking { diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt index 480da234b..8fb1dba76 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeGmailFlow.kt @@ -61,6 +61,7 @@ import java.io.ByteArrayOutputStream import java.io.InputStream import java.net.HttpURLConnection import java.util.Properties +import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit /** @@ -68,7 +69,8 @@ import java.util.concurrent.TimeUnit */ abstract class BaseComposeGmailFlow(accountEntity: AccountEntity = BASE_ACCOUNT_ENTITY) : BaseGmailApiTest(accountEntity) { - protected val sentCache = mutableListOf() + //it's filled by the mock web server thread and read by the test thread + protected val sentCache = CopyOnWriteArrayList() @get:Rule val outgoingMessageConfigurationRule = OutgoingMessageConfigurationRule() @@ -301,7 +303,9 @@ abstract class BaseComposeGmailFlow(accountEntity: AccountEntity = BASE_ACCOUNT_ val countOfOutgoingMessages = runBlocking { roomDatabase.msgDao().getOutboxMsgsSuspend(addAccountToDatabaseRule.account.email).size } - if (countOfOutgoingMessages == 0) { + //right after clicking 'Send' the message may not be added to the outbox yet, + //so an empty outbox alone doesn't mean the message was sent + if (countOfOutgoingMessages == 0 && sentCache.isNotEmpty()) { Thread.sleep(TimeUnit.SECONDS.toMillis(1)) break } else { @@ -319,21 +323,23 @@ abstract class BaseComposeGmailFlow(accountEntity: AccountEntity = BASE_ACCOUNT_ //check that we have one message in the server cache and outbox label is not displayed assertEquals(1, sentCache.size) - onView(withId(R.id.toolbar)) - .check( - matches( - not( - hasDescendant( - withText( - getQuantityString( - R.plurals.outbox_msgs_count, - 1 - ) - ) + val toolbarWithoutOutboxLabel = matches( + not( + hasDescendant( + withText( + getQuantityString( + R.plurals.outbox_msgs_count, + 1 ) ) ) ) + ) + //the toolbar is updated a bit later than the outbox in the database + waitUntil(TimeUnit.SECONDS.toMillis(10)) { + runCatching { onView(withId(R.id.toolbar)).check(toolbarWithoutOutboxLabel) }.isSuccess + } + onView(withId(R.id.toolbar)).check(toolbarWithoutOutboxLabel) //check sent MIME message val rawMime = requireNotNull(sentCache.first().raw) From 413dd6e9e2cca6ec2864083a83ba26a077dfa227 Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 00:28:54 +0200 Subject: [PATCH 08/18] fix: ignore files removed during directory cleanup Glide's disk cache renames its journal while it rebuilds it. When the file disappears between exists() and delete(), delete() returns false and cleanDir() threw IOException. This broke ClearAppSettingsRule (e.g. WkdClientTest on CI). Treat it as an error only when the file still exists. --- .../java/com/flowcrypt/email/util/FileAndDirectoryUtils.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/util/FileAndDirectoryUtils.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/util/FileAndDirectoryUtils.kt index d71879195..8123c1e42 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/util/FileAndDirectoryUtils.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/util/FileAndDirectoryUtils.kt @@ -79,7 +79,9 @@ class FileAndDirectoryUtils { if (childFile != null && childFile.exists()) { if (childFile.isDirectory) { deleteFile(childFile) - } else if (!childFile.delete()) { + } else if (!childFile.delete() && childFile.exists()) { + //another component (e.g. Glide's disk cache) may remove or rename the file + //between exists() and delete(). It is an error only if the file is still there. throw IOException("An error occurred while delete $childFile") } } @@ -87,7 +89,7 @@ class FileAndDirectoryUtils { } } - if (!file.delete()) { + if (!file.delete() && file.exists()) { throw IOException("An error occurred while delete $file") } } From 442cd657e993d32673d929e3ce9c71e4dc939116 Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 00:29:36 +0200 Subject: [PATCH 09/18] test: take failure screenshots via UiAutomation androidx.test takeScreenshot() redraws the app windows on the main thread. When a window is being destroyed after a failure, it crashes the app process with NPE in ViewCapture.forceRedraw. The crash hides the original failure and stops RetryRule. UiAutomation takes the screenshot on the system side, and any screenshot error is now only logged. --- .../flowcrypt/email/rules/ScreenshotTestRule.kt | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/ScreenshotTestRule.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/ScreenshotTestRule.kt index b6fbe2371..beb788388 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/ScreenshotTestRule.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/ScreenshotTestRule.kt @@ -10,15 +10,12 @@ import android.graphics.Bitmap import android.os.Environment import android.provider.MediaStore import android.webkit.MimeTypeMap -import androidx.test.core.app.canTakeScreenshot -import androidx.test.core.app.takeScreenshot import androidx.test.platform.app.InstrumentationRegistry import com.flowcrypt.email.extensions.kotlin.getPossibleAndroidMimeType import org.apache.commons.io.FilenameUtils import org.junit.rules.TestWatcher import org.junit.runner.Description import java.io.BufferedOutputStream -import java.io.IOException import java.util.UUID @@ -35,7 +32,12 @@ class ScreenshotTestRule : TestWatcher() { private fun makeScreenshot(description: Description?) { try { - if (canTakeScreenshot()) { + //UiAutomation takes a screenshot on the system side. androidx.test takeScreenshot() + //force-redraws the app windows on the main thread. If a window is being destroyed + //(e.g. after a failure), it crashes the app process with NPE in ViewCapture.forceRedraw, + //hides the original failure and stops RetryRule. + val screenshot = InstrumentationRegistry.getInstrumentation().uiAutomation.takeScreenshot() + if (screenshot != null) { val filename = description?.testClass?.simpleName + "-" + description?.methodName + @@ -68,11 +70,12 @@ class ScreenshotTestRule : TestWatcher() { val outputStream = contentResolver.openOutputStream(imageUri) ?: throw IllegalStateException("ContentResolver issue") BufferedOutputStream(outputStream).use { out -> - takeScreenshot().compress(Bitmap.CompressFormat.PNG, 100, out) + screenshot.compress(Bitmap.CompressFormat.PNG, 100, out) out.flush() } } - } catch (e: IOException) { + } catch (e: Exception) { + //a screenshot is only a debug helper. It must not replace the original failure e.printStackTrace() } } From 35856c0f2b4ff4569e75b1e7d8c7321221a6deb0 Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 00:29:37 +0200 Subject: [PATCH 10/18] test: log failures fixed by RetryRule RetryRule printed only "run N failed". Print the stack trace too, so a failure hidden by a successful retry can be found in logcat. --- .../src/androidTest/java/com/flowcrypt/email/rules/RetryRule.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/RetryRule.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/RetryRule.kt index 09863d53e..049dfd223 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/RetryRule.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/rules/RetryRule.kt @@ -49,6 +49,8 @@ class RetryRule(private val retryCount: Int = 0) : BaseRule() { Thread.sleep(1000 * (times + 1).toLong()) caughtThrowable = it System.err.println(description.displayName.toString() + ": run ${times + 1} failed") + //without it a failure fixed by a retry is not visible in logcat + it.printStackTrace() } } System.err.println(description.displayName.toString() + ": giving up after " + attempts + " failures") From 959d511dd2a12c1c887081662a83be79d8f81386 Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 00:29:37 +0200 Subject: [PATCH 11/18] test: insert compose message text without key events On a slow emulator the IME session restarts after the focus change and typed characters are lost ("message" became "essage" in EncryptedReplyComposeGmailApiFlow). fillInAllFields() now inserts the message at the cursor directly and keeps existing text, e.g. a signature. --- .../email/ui/base/BaseComposeScreenTest.kt | 6 ++- .../email/viewaction/CustomViewActions.kt | 7 ++++ .../InsertTextAtCursorViewAction.kt | 41 +++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/InsertTextAtCursorViewAction.kt diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeScreenTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeScreenTest.kt index 91eb97ef8..065a5e8b9 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeScreenTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/base/BaseComposeScreenTest.kt @@ -16,7 +16,6 @@ import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.action.ViewActions.pressImeActionButton import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.action.ViewActions.scrollTo -import androidx.test.espresso.action.ViewActions.typeTextIntoFocusedView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.intent.Intents.intending import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction @@ -34,6 +33,7 @@ import com.flowcrypt.email.rules.lazyActivityScenarioRule import com.flowcrypt.email.ui.activity.CreateMessageActivity import com.flowcrypt.email.ui.activity.fragment.CreateMessageFragmentArgs import com.flowcrypt.email.util.TestGeneralUtil +import com.flowcrypt.email.viewaction.CustomViewActions.insertTextAtCursor import jakarta.mail.internet.InternetAddress import org.hamcrest.Matchers.allOf import java.io.File @@ -124,10 +124,12 @@ abstract class BaseComposeScreenTest : BaseTest() { closeSoftKeyboard() ) + //typing with key events can lose the first characters on a slow emulator while the IME + //reconnects after the focus change (e.g. "message" -> "essage") onView(withId(R.id.editTextEmailMessage)) .perform( scrollTo(), - typeTextIntoFocusedView(message), + insertTextAtCursor(message), closeSoftKeyboard() ) } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/CustomViewActions.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/CustomViewActions.kt index 99be1e274..3e8fdcb47 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/CustomViewActions.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/CustomViewActions.kt @@ -76,4 +76,11 @@ object CustomViewActions { fun waitUntilGone(text: String, timeout: Long): ViewAction { return WaitUntilTextGoneAction(text, timeout) } + + /** + * @return a [InsertTextAtCursorViewAction] instance created with the given [text] parameter. + */ + fun insertTextAtCursor(text: String): ViewAction { + return InsertTextAtCursorViewAction(text) + } } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/InsertTextAtCursorViewAction.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/InsertTextAtCursorViewAction.kt new file mode 100644 index 000000000..90ec3eaeb --- /dev/null +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/viewaction/InsertTextAtCursorViewAction.kt @@ -0,0 +1,41 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: denbond7 + */ + +package com.flowcrypt.email.viewaction + +import android.view.View +import android.widget.EditText +import androidx.test.espresso.UiController +import androidx.test.espresso.ViewAction +import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import org.hamcrest.Matcher +import org.hamcrest.Matchers.allOf + +/** + * Inserts [text] at the cursor position of an [EditText] and keeps the existing text. + * + * Typing with key events can lose the first characters on a slow emulator while the IME + * connection is restarted after a focus change. This action changes the text directly, like + * replaceText(), but does not remove the text that is already there (e.g. a signature). + */ +class InsertTextAtCursorViewAction(private val text: String) : ViewAction { + override fun getConstraints(): Matcher { + return allOf(isDisplayed(), isAssignableFrom(EditText::class.java)) + } + + override fun getDescription(): String { + return "insert text \"$text\" at the cursor position" + } + + override fun perform(uiController: UiController, view: View) { + val editText = view as EditText + val editable = editText.text + val position = editText.selectionStart.takeIf { it in 0..editable.length } ?: 0 + editable.insert(position, text) + editText.setSelection(position + text.length) + uiController.loopMainThreadUntilIdle() + } +} From 54ea57339e7a159a3ed1cf8311a2c8fc9cb52dfb Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 00:29:37 +0200 Subject: [PATCH 12/18] test: wait for passphrase expiry instead of fixed sleep PassPhrasesInRAMService clears expired pass phrases once per DELAY_TIMEOUT, counted from the service start, and the screen is updated asynchronously. Wait for the result instead of one check after a fixed sleep. --- ...eyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt index 94f5bd478..1057a8b04 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt @@ -42,6 +42,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 /** * @author Denys Bondarenko @@ -117,8 +118,15 @@ class PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest : BaseTest() { .check(matches(withText(getResString(R.string.stored_pass_phrase_matched)))) .check(matches(hasTextColor(R.color.colorPrimaryLight))) - //we need to wait around 1 minute to check that [PassPhrasesInRAMService] works well - Thread.sleep(PassPhrasesInRAMService.DELAY_TIMEOUT) + //[PassPhrasesInRAMService] clears expired pass phrases once per DELAY_TIMEOUT, counted from + //the service start, and the screen is updated after that asynchronously. On a slow emulator + //the service can start late, so wait for the result instead of a fixed sleep + waitUntil(PassPhrasesInRAMService.DELAY_TIMEOUT + TimeUnit.SECONDS.toMillis(30)) { + runCatching { + onView(withId(R.id.tVPassPhraseVerification)) + .check(matches(withText(getResString(R.string.pass_phrase_not_provided)))) + }.isSuccess + } onView(withId(R.id.tVPassPhraseVerification)) .check(matches(withText(getResString(R.string.pass_phrase_not_provided)))) .check(matches(hasTextColor(R.color.red))) From 3837556241307409d8c7fd1e13f972c2361e02ed Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 00:29:38 +0200 Subject: [PATCH 13/18] test: fix recipient lookup races in compose tests - Clicking Send during the recipient lookup shows a "please wait" toast instead of the dialog. The popup tests now wait until the recipient chip is settled. - The chip color check in CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest now waits for the lookup result. - typeText() lost characters when the IME session restarted (the recipient became "...@flowcrypt.te"), so these tests use replaceText(). --- .../email/ui/ComposeScreenFlowTest.kt | 22 +++++++++++-- ...wAttesterSearchForDomainInIsolationTest.kt | 32 +++++++------------ 2 files changed, 30 insertions(+), 24 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt index 71a31435a..3dd938aea 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt @@ -451,6 +451,7 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { requireNotNull(TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER.asInternetAddress()) ) ) + waitUntilRecipientWithoutPubKeyIsSettled() onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) .perform(click()) @@ -464,17 +465,21 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { fun testSelectedRemoveRecipientFromPopUp() { activeActivityRule?.launch(intent) + //typeText() can lose characters on a slow emulator when the IME session restarts + //("Session id mismatch" in logcat), e.g. the recipient became "...@flowcrypt.te" onView(withId(R.id.editTextEmailAddress)) .perform( - typeText(TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER), + replaceText(TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER), pressImeActionButton() ) //move the focus to the next view onView(withId(R.id.editTextEmailMessage)) .perform( scrollTo(), click(), - typeText(TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER), closeSoftKeyboard() + replaceText(TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER), closeSoftKeyboard() ) + //sending is blocked with a "please wait" toast until the recipient lookup is done + waitUntilRecipientWithoutPubKeyIsSettled() onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) .perform(click()) @@ -517,7 +522,7 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { ) ) - Thread.sleep(2000) + waitUntilRecipientWithoutPubKeyIsSettled() onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) @@ -934,6 +939,17 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { } } + /** + * Clicking 'Send' while the recipient lookup is in progress shows a "please wait" toast + * instead of the dialog for a recipient without a public key. + */ + private fun waitUntilRecipientWithoutPubKeyIsSettled() { + waitUntilRecipientChipIsSettled( + email = TestConstants.RECIPIENT_WITHOUT_PUBLIC_KEY_ON_ATTESTER, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY + ) + } + companion object { private const val ATTACHMENTS_COUNT = 3 diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest.kt index c81858a82..55efa5801 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest.kt @@ -5,15 +5,12 @@ package com.flowcrypt.email.ui.fragment.isolation.incontainer -import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.action.ViewActions.pressImeActionButton -import androidx.test.espresso.action.ViewActions.typeText -import androidx.test.espresso.contrib.RecyclerViewActions.scrollTo +import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.flowcrypt.email.R @@ -21,7 +18,6 @@ import com.flowcrypt.email.TestConstants import com.flowcrypt.email.api.retrofit.response.model.ClientConfiguration import com.flowcrypt.email.base.BaseTest import com.flowcrypt.email.database.entity.KeyEntity -import com.flowcrypt.email.matchers.CustomMatchers.Companion.withChipsBackgroundColor import com.flowcrypt.email.model.KeyImportDetails import com.flowcrypt.email.rules.AddAccountToDatabaseRule import com.flowcrypt.email.rules.AddPrivateKeyToDatabaseRule @@ -33,7 +29,6 @@ import com.flowcrypt.email.ui.activity.fragment.CreateMessageFragment import com.flowcrypt.email.ui.activity.fragment.CreateMessageFragmentArgs import com.flowcrypt.email.ui.adapter.RecipientChipRecyclerViewAdapter import com.flowcrypt.email.util.AccountDaoManager -import org.hamcrest.Matchers.allOf import org.junit.Ignore import org.junit.Rule import org.junit.Test @@ -90,7 +85,8 @@ class CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest : Base val recipient = "user@$DISALLOWED_DOMAIN" onView(withId(R.id.editTextEmailAddress)) .perform( - typeText(recipient), + //typeText() can lose characters on a slow emulator when the IME session restarts + replaceText(recipient), pressImeActionButton(), closeSoftKeyboard() ) @@ -99,27 +95,21 @@ class CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest : Base onView(withId(R.id.editTextEmailSubject)) .perform( click(), - typeText("subject"), + replaceText("subject"), closeSoftKeyboard() ) onView(withId(R.id.editTextEmailMessage)) .perform( - typeText("message"), + replaceText("message"), closeSoftKeyboard() ) - onView(withId(R.id.recyclerViewChipsTo)) - .perform( - scrollTo( - allOf( - withText(recipient), - withChipsBackgroundColor( - getTargetContext(), - RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY - ) - ) - ) - ) + //the chip has the 'updating' color while the lookup is in progress. A single check can run + //before the lookup finishes on a slow emulator + waitUntilRecipientChipIsSettled( + email = recipient, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY + ) } companion object { From ccac3e8d185dbc804b135c6c651f50ad04cbe9c9 Mon Sep 17 00:00:00 2001 From: denbond7 Date: Mon, 16 Nov 2026 02:49:42 +0200 Subject: [PATCH 14/18] ci: disable the keyboard on test emulators On slow emulators 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" became "essage" and "...@flowcrypt.test" became "...@flowcrypt.te". ci-wait-for-emulator.sh now disables Gboard and the Google TTS voice IME (the system falls back to it without Gboard), so Espresso key events go to the view directly. On a CI-like emulator 44 typeText-heavy tests ran in ~622s without an IME vs 680-813s with Gboard, with no new failures. Set DISABLE_IME=0 to keep the keyboard. --- script/ci-wait-for-emulator.sh | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/script/ci-wait-for-emulator.sh b/script/ci-wait-for-emulator.sh index 3c3b51f19..23e19e581 100755 --- a/script/ci-wait-for-emulator.sh +++ b/script/ci-wait-for-emulator.sh @@ -167,6 +167,26 @@ 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 +# 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 +# go to the view directly. Both packages must be disabled: without Gboard the system switches to +# the Google TTS voice IME. Set DISABLE_IME=0 to keep the keyboard. +if [[ "${DISABLE_IME:-1}" == "1" ]]; then + for ime_package in com.google.android.inputmethod.latin com.google.android.tts; do + adb shell pm disable-user --user 0 "$ime_package" || true + done + + # The system applies the change asynchronously. + enabled_imes="" + for _ in {1..15}; do + enabled_imes=$(adb shell ime list -s | tr -d '\r' | tr '\n' ' ' || true) + [[ -z "${enabled_imes// /}" ]] && break + sleep 1 + done + echo "Enabled input methods after disabling: [${enabled_imes}]" +fi + ################################################################################################### # To test WKD we need to route all traffic for localhost:443 to localhost:1212 # as we can't use 443 directly for a mock web server. From e49cfac112621fc11b65659955d10993a97f7bd4 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Thu, 19 Nov 2026 13:07:19 +0200 Subject: [PATCH 15/18] test: fix and re-enable testEmptyEmailSubject --- .../email/ui/ComposeScreenFlowTest.kt | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt index 3dd938aea..d602401e0 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt @@ -140,7 +140,6 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { } @Test - @Ignore("flaky. Temporary disabled") fun testEmptyEmailSubject() { activeActivityRule?.launch(intent) waitForObjectWithText( @@ -148,20 +147,29 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { TimeUnit.SECONDS.toMillis(10) ) + //typeText() can lose characters on a slow emulator when the IME session restarts onView(withId(R.id.editTextEmailAddress)) .perform( - typeText(TestConstants.RECIPIENT_WITH_PUBLIC_KEY_ON_ATTESTER), + replaceText(TestConstants.RECIPIENT_WITH_PUBLIC_KEY_ON_ATTESTER), pressImeActionButton() ) + //sending is blocked with a "please wait" toast until the recipient lookup is done + waitUntilRecipientChipIsSettled( + email = TestConstants.RECIPIENT_WITH_PUBLIC_KEY_ON_ATTESTER, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_HAS_USABLE_PUB_KEY + ) onView(withId(R.id.editTextEmailSubject)) - .perform(scrollTo(), click(), typeText("subject"), clearText()) + .perform(scrollTo(), click(), replaceText("")) .check(matches(withText(""))) + Espresso.closeSoftKeyboard() onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) .perform(click()) - onView( - withText(getResString(R.string.text_must_not_be_empty, getResString(R.string.prompt_subject))) - ).check(matches(isDisplayed())) + + val errorText = + getResString(R.string.text_must_not_be_empty, getResString(R.string.prompt_subject)) + waitForObjectWithText(errorText, TimeUnit.SECONDS.toMillis(10)) + onView(withText(errorText)).check(matches(isDisplayed())) } @Test From 85e04d64d725cc534d960fdbb83a22bd8b35fb79 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Thu, 19 Nov 2026 13:07:42 +0200 Subject: [PATCH 16/18] docs: repeat tests with a class rule --- docs/testing-like-ci.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/testing-like-ci.md b/docs/testing-like-ci.md index 6097d1fa1..1254e4a08 100644 --- a/docs/testing-like-ci.md +++ b/docs/testing-like-ci.md @@ -108,6 +108,20 @@ run can hide failures. To see them: `@RunWith(RepeatableAndroidJUnit4ClassRunner::class)` plus `@RepeatableAndroidJUnit4ClassRunner.RepeatTest(5)`, and `RetryRule.DEFAULT` with `RetryRule(1)`. + It doesn't work for a class with a `@ClassRule` mock web server (e.g. `ComposeScreenFlowTest`): + the rule starts twice and every test fails with `BindException: EADDRINUSE`. Also, the tests get + names like `testEmptyEmailSubject_1`, so `class=Class#method` matches nothing. For such a class + keep `@RunWith(AndroidJUnit4::class)`, set only `RetryRule(1)` and start the test in a loop: + + ```bash + ANDROID_SERIAL=emulator-5560 ./gradlew :FlowCrypt:installConsumerUiTests \ + :FlowCrypt:installConsumerUiTestsAndroidTest + for i in {1..10}; do + adb -s emulator-5560 shell am instrument -w -r \ + -e class com.flowcrypt.email.ui.ComposeScreenFlowTest#testEmptyEmailSubject \ + com.flowcrypt.email.debug.test/androidx.test.runner.AndroidJUnitRunner | grep -E '^OK|^Tests run' + done + ``` - **Run a few times.** Some races show up once in 5–10 runs. Compare the code before and after the fix under the same conditions. From c3730def4b8df2a041ab6d3b63a373a6af4dfb2d Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Thu, 19 Nov 2026 14:07:24 +0200 Subject: [PATCH 17/18] test: fix and re-enable import key popup test --- .../email/ui/ComposeScreenFlowTest.kt | 61 ++++++------------- 1 file changed, 17 insertions(+), 44 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt index d602401e0..cb6b85ed5 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/ComposeScreenFlowTest.kt @@ -375,7 +375,6 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { } @Test - @Ignore("Need to fix. Flaky") fun testSelectImportPublicKeyFromPopUp() { activeActivityRule?.launch(intent) intending(hasComponent(ComponentName(getTargetContext(), MainActivity::class.java))) @@ -384,70 +383,44 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { val email = primaryInternetAddress.address fillInAllFields(to = setOf(primaryInternetAddress)) - onView(withId(R.id.recyclerViewChipsTo)) - .perform( - RecyclerViewActions.scrollTo( - allOf( - withText(email), - withChipsBackgroundColor( - getTargetContext(), - RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY - ) - ) - ) - ) + //sending is blocked with a "please wait" toast until the recipient lookup is done + waitUntilRecipientChipIsSettled( + email = email, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY + ) onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) .perform(click()) + waitForObjectWithText( + getResString(R.string.import_their_public_key), + TimeUnit.SECONDS.toMillis(10) + ) onView(withText(R.string.import_their_public_key)) .check(matches(isDisplayed())) .perform(click()) - var clipboardOk = false val clipboard = getTargetContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - repeat(5) { _ -> - + waitUntil(TimeUnit.SECONDS.toMillis(10)) { addTextToClipboard("public key", pgpKeyRingDetails.publicKey) - Thread.sleep(1000) - - val clip = clipboard.primaryClip - val actualText = clip + clipboard.primaryClip ?.takeIf { it.itemCount > 0 } ?.getItemAt(0) ?.coerceToText(getTargetContext()) - ?.toString() - - if (actualText == pgpKeyRingDetails.publicKey) { - clipboardOk = true - return@repeat - } - } - - if (!clipboardOk) { - throw AssertionError("Clipboard did not contain expected public key after 5 attempts") + ?.toString() == pgpKeyRingDetails.publicKey } onView(withId(R.id.buttonLoadFromClipboard)) .check(matches(isDisplayed())) .perform(click()) - waitForObjectWithText(email, TimeUnit.SECONDS.toMillis(10)) - - onView(withId(R.id.recyclerViewChipsTo)) - .perform( - RecyclerViewActions.scrollTo( - allOf( - withText(email), - withChipsBackgroundColor( - getTargetContext(), - RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_HAS_USABLE_PUB_KEY - ) - ) - ) - ) + //returning to the compose screen starts a new lookup for the recipient + waitUntilRecipientChipIsSettled( + email = email, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_HAS_USABLE_PUB_KEY + ) } @Test From a458b27a62e12b1cb71c99e792f87b61f82e5377 Mon Sep 17 00:00:00 2001 From: Denys Bondarenko Date: Thu, 19 Nov 2026 14:37:37 +0200 Subject: [PATCH 18/18] test: fix and re-enable attester lookup test --- ...ntDisallowAttesterSearchInIsolationTest.kt | 34 ++++++------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchInIsolationTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchInIsolationTest.kt index bdc21f97c..5b42f722a 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchInIsolationTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchInIsolationTest.kt @@ -5,15 +5,12 @@ package com.flowcrypt.email.ui.fragment.isolation.incontainer -import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.action.ViewActions.pressImeActionButton -import androidx.test.espresso.action.ViewActions.typeText -import androidx.test.espresso.contrib.RecyclerViewActions.scrollTo +import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.matcher.ViewMatchers.withId -import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.flowcrypt.email.R @@ -21,7 +18,6 @@ import com.flowcrypt.email.TestConstants import com.flowcrypt.email.api.retrofit.response.model.ClientConfiguration import com.flowcrypt.email.base.BaseTest import com.flowcrypt.email.database.entity.KeyEntity -import com.flowcrypt.email.matchers.CustomMatchers.Companion.withChipsBackgroundColor import com.flowcrypt.email.model.KeyImportDetails import com.flowcrypt.email.rules.AddAccountToDatabaseRule import com.flowcrypt.email.rules.AddPrivateKeyToDatabaseRule @@ -33,8 +29,6 @@ import com.flowcrypt.email.ui.activity.fragment.CreateMessageFragment import com.flowcrypt.email.ui.activity.fragment.CreateMessageFragmentArgs import com.flowcrypt.email.ui.adapter.RecipientChipRecyclerViewAdapter import com.flowcrypt.email.util.AccountDaoManager -import org.hamcrest.Matchers.allOf -import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -80,7 +74,6 @@ class CreateMessageFragmentDisallowAttesterSearchInIsolationTest : BaseTest() { .around(ScreenshotTestRule()) @Test - @Ignore("Temporary disabled as flaky") fun testDisallowLookupOnAttester() { launchFragmentInContainer( fragmentArgs = CreateMessageFragmentArgs().toBundle() @@ -89,7 +82,8 @@ class CreateMessageFragmentDisallowAttesterSearchInIsolationTest : BaseTest() { val recipient = "recipient@example.test" onView(withId(R.id.editTextEmailAddress)) .perform( - typeText(recipient), + //typeText() can lose characters on a slow emulator when the IME session restarts + replaceText(recipient), pressImeActionButton(), closeSoftKeyboard() ) @@ -98,26 +92,20 @@ class CreateMessageFragmentDisallowAttesterSearchInIsolationTest : BaseTest() { onView(withId(R.id.editTextEmailSubject)) .perform( click(), - typeText("subject"), + replaceText("subject"), closeSoftKeyboard() ) onView(withId(R.id.editTextEmailMessage)) .perform( - typeText("message"), + replaceText("message"), closeSoftKeyboard() ) - onView(withId(R.id.recyclerViewChipsTo)) - .perform( - scrollTo( - allOf( - withText(recipient), - withChipsBackgroundColor( - getTargetContext(), - RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY - ) - ) - ) - ) + //the chip has the 'updating' color while the lookup is in progress. A single check can run + //before the lookup finishes on a slow emulator + waitUntilRecipientChipIsSettled( + email = recipient, + colorResId = RecipientChipRecyclerViewAdapter.CHIP_COLOR_RES_ID_NO_PUB_KEY + ) } }