Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<View>,
root: Matcher<Root>? = 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Application>())
}

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 = "<div>Signature</div>"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,16 @@

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
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
Expand Down Expand Up @@ -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
Expand All @@ -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

/**
Expand Down Expand Up @@ -83,6 +84,12 @@ class AttachmentDownloadingWithRestrictionFlowTest : BaseMessageDetailsFlowTest(
useAPI = true
)

private val notificationManager: NotificationManager
get() = requireNotNull(getTargetContext().getSystemService<NotificationManager>())

//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,
Expand Down Expand Up @@ -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()
Expand All @@ -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
}
}
Loading
Loading