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 09863d53ea..049dfd2235 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") 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 b6fbe2371a..beb7883886 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() } } 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 71a31435a4..cb6b85ed5c 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 @@ -367,7 +375,6 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { } @Test - @Ignore("Need to fix. Flaky") fun testSelectImportPublicKeyFromPopUp() { activeActivityRule?.launch(intent) intending(hasComponent(ComponentName(getTargetContext(), MainActivity::class.java))) @@ -376,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 @@ -451,6 +432,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 +446,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 +503,7 @@ class ComposeScreenFlowTest : BaseComposeScreenTest() { ) ) - Thread.sleep(2000) + waitUntilRecipientWithoutPubKeyIsSettled() onView(withId(R.id.menuActionSend)) .check(matches(isDisplayed())) @@ -934,6 +920,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/PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/PrivateKeyDetailsFragmentPassInRamFlexibleTimeFlowTest.kt index 94f5bd4787..1057a8b04b 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))) 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 91eb97ef8d..065a5e8b96 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/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/fragment/isolation/incontainer/CreateMessageFragmentDisallowAttesterSearchForDomainInIsolationTest.kt index c81858a824..55efa58019 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 { 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 bdc21f97c4..5b42f722ad 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 + ) } } 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 99be1e2743..3e8fdcb47f 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 0000000000..90ec3eaebd --- /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() + } +} 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 d718791954..8123c1e422 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") } } diff --git a/docs/testing-like-ci.md b/docs/testing-like-ci.md index 6097d1fa17..1254e4a085 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. diff --git a/script/ci-wait-for-emulator.sh b/script/ci-wait-for-emulator.sh index 3c3b51f199..23e19e581a 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.