Skip to content
Draft
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 @@ -39,6 +39,8 @@ import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.espresso.web.sugar.Web
import androidx.test.espresso.web.sugar.Web.onWebView
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
Expand Down Expand Up @@ -393,6 +395,23 @@ abstract class BaseTest : BaseActivityTestImplementation {
}
}

/**
* Enable JavaScript in the WebView that matches [webViewMatcher] and run [check] on it.
* The app keeps JavaScript disabled, and the new setting reaches the WebView renderer
* asynchronously, so on a slow emulator the first checks can fail with
* "Could not parse: null" or time out. Retry [check] until it passes or [timeoutMs]
* expires, then run it once more to fail with the real error.
*/
protected fun checkWebViewWithJavascript(
webViewMatcher: Matcher<View>,
timeoutMs: Long = TimeUnit.SECONDS.toMillis(30),
check: (Web.WebInteraction<Void>) -> Unit
) {
onWebView(webViewMatcher).forceJavascriptEnabled()
waitUntil(timeoutMs) { runCatching { check(onWebView(webViewMatcher)) }.isSuccess }
check(onWebView(webViewMatcher))
}

protected fun waitUntil(
timeoutInMilliseconds: Long = TimeUnit.SECONDS.toMillis(10),
predicate: () -> Boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@
package com.flowcrypt.email.ui

import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.clearText
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.closeSoftKeyboard
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
Expand All @@ -21,6 +20,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.flowcrypt.email.R
import com.flowcrypt.email.TestConstants
import com.flowcrypt.email.junit.annotations.FlowCryptTestSettings
import com.flowcrypt.email.rules.ClearAppSettingsRule
import com.flowcrypt.email.rules.GrantPermissionRuleChooser
import com.flowcrypt.email.rules.RetryRule
Expand All @@ -31,18 +31,19 @@ import com.flowcrypt.email.util.AuthCredentialsManager
import com.flowcrypt.email.util.TestGeneralUtil
import org.hamcrest.Matchers.anyOf
import org.hamcrest.Matchers.startsWith
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit

/**
* @author Denys Bondarenko
*/
@MediumTest
@RunWith(AndroidJUnit4::class)
@FlowCryptTestSettings(useCommonIdling = false)
class AddOtherAccountFlowTest : AddOtherAccountBaseTest() {

override val activeActivityRule = activityScenarioRule<MainActivity>(
Expand All @@ -60,84 +61,61 @@ class AddOtherAccountFlowTest : AddOtherAccountBaseTest() {
.around(ScreenshotTestRule())

@Test
//@Ignore("flaky 8")
//RepeatableAndroidJUnit4ClassRunner 50 attempts passed
@Ignore("flaky. Temporary disabled")
fun testShowWarningIfAuthFail() {
enableAdvancedMode()
val credentials = AuthCredentialsManager.getAuthCredentials("user_with_not_existed_server.json")
fillAllFields(credentials)
val someFailTextToChangeRightValue = "123"

val fieldIdentifiersWithIncorrectData = intArrayOf(
R.id.editTextEmail,
R.id.editTextUserName,
R.id.editTextImapServer,
R.id.editTextImapPort,
R.id.editTextSmtpServer,
R.id.editTextSmtpPort,
R.id.editTextSmtpUsername,
R.id.editTextSmtpPassword
// Nothing listens on the IMAP and SMTP ports of *.flowcrypt.test (127.0.0.1), so every
// attempt fails fast with a connection error, whichever field has an incorrect value.
// The email goes last: changing it also overwrites the servers and the username.
val checks = listOf(
FieldCheck(R.id.editTextUserName, credentials.username, "wrong_user"),
FieldCheck(R.id.editTextImapServer, credentials.imapServer, "wrong.imap.flowcrypt.test"),
FieldCheck(R.id.editTextImapPort, credentials.imapPort.toString(), CLOSED_PORT),
FieldCheck(R.id.editTextSmtpServer, credentials.smtpServer, "wrong.smtp.flowcrypt.test"),
FieldCheck(R.id.editTextSmtpPort, credentials.smtpPort.toString(), CLOSED_PORT),
FieldCheck(R.id.editTextEmail, credentials.email, "wrong_user@flowcrypt.test")
)

val correctData = arrayOf(
credentials.email,
credentials.username,
credentials.password,
credentials.imapServer,
credentials.imapPort.toString(),
credentials.smtpServer,
credentials.smtpPort.toString(),
credentials.smtpSigInUsername,
credentials.smtpSignInPassword
)

val numberOfChecks = if (credentials.hasCustomSignInForSmtp) {
fieldIdentifiersWithIncorrectData.size
} else {
fieldIdentifiersWithIncorrectData.size - 2
}

for (i in 0 until numberOfChecks) {
onView(withId(fieldIdentifiersWithIncorrectData[i]))
.perform(
scrollTo(),
typeText(someFailTextToChangeRightValue),
closeSoftKeyboard()
)
for (check in checks) {
replaceFieldText(check.viewId, check.incorrectValue)
onView(withId(R.id.buttonTryToConnect))
.perform(scrollTo(), click())

onView(
anyOf(
withText(startsWith(TestConstants.IMAP)),
withText(startsWith(TestConstants.SMTP))
)
).check(matches(isDisplayed()))

if (i in intArrayOf(
R.id.editTextImapServer,
R.id.editTextImapPort,
R.id.editTextSmtpServer,
R.id.editTextSmtpPort
)
) {
onView(withText(getResString(R.string.network_error)))
.check(matches(isDisplayed()))
}
// The settings are checked in the background, so wait for the result dialog
waitUntilViewMatches(
viewId = android.R.id.message,
matcher = withText(anyOf(startsWith(TestConstants.IMAP), startsWith(TestConstants.SMTP))),
root = isDialog(),
timeoutMs = TimeUnit.SECONDS.toMillis(30)
)
onView(withText(getResString(R.string.network_error)))
.inRoot(isDialog())
.check(matches(isDisplayed()))

onView(withText(getResString(R.string.cancel)))
.inRoot(isDialog())
.check(matches(isDisplayed()))
.perform(click())
waitUntilViewMatches(viewId = R.id.buttonTryToConnect, matcher = isDisplayed())

onView(withId(fieldIdentifiersWithIncorrectData[i]))
.perform(
scrollTo(),
clearText(),
typeText(correctData[i]),
closeSoftKeyboard()
)
replaceFieldText(check.viewId, check.correctValue)
}
}

private fun replaceFieldText(viewId: Int, text: String) {
onView(withId(viewId))
.perform(scrollTo(), replaceText(text), closeSoftKeyboard())
}

private data class FieldCheck(
val viewId: Int,
val correctValue: String,
val incorrectValue: String
)

companion object {
private const val CLOSED_PORT = "1"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1008,9 +1008,8 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() {
)
baseCheck(msgInfo, checkWebContent = false)

onWebView(withId(R.id.emailWebView)).forceJavascriptEnabled()
onWebView(withId(R.id.emailWebView))
.check(
checkWebViewWithJavascript(withId(R.id.emailWebView)) { webView ->
webView.check(
webContent(
elementByXPath(
"/html/body",
Expand All @@ -1023,6 +1022,7 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() {
)
)
)
}

testPgpBadges(
2,
Expand Down Expand Up @@ -1197,10 +1197,11 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() {
Atoms.castOrDie(String::class.java)
)

onWebView(withId(R.id.emailWebView)).forceJavascriptEnabled()
onWebView(withId(R.id.emailWebView))
.withElement(findElement(Locator.XPATH, xpath))
.check(webMatches(imgSrcViaJavaScript, equalTo(imgSrc)))
checkWebViewWithJavascript(withId(R.id.emailWebView)) { webView ->
webView
.withElement(findElement(Locator.XPATH, xpath))
.check(webMatches(imgSrcViaJavaScript, equalTo(imgSrc)))
}
}

@Test
Expand All @@ -1221,16 +1222,16 @@ class MessageDetailsFlowTest : BaseMessageDetailsFlowTest() {

baseCheck(msgInfo)

onWebView(withId(R.id.emailWebView)).forceJavascriptEnabled()
onWebView(withId(R.id.emailWebView))
.check(
checkWebViewWithJavascript(withId(R.id.emailWebView)) { webView ->
webView.check(
webContent(
elementByXPath(
"/html/body",
withTextContent(not(containsString("Version: 1")))
)
)
)
}

Thread.sleep(1000)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import androidx.test.espresso.action.ViewActions.typeText
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.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
Expand All @@ -37,8 +38,8 @@ import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.RecordedRequest
import org.eclipse.angus.mail.imap.IMAPFolder
import org.hamcrest.Matchers.containsString
import org.junit.Assert.assertTrue
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
Expand All @@ -57,11 +58,11 @@ import java.util.concurrent.TimeUnit
@MediumTest
@RunWith(AndroidJUnit4::class)
@FlowCryptTestSettings(useIntents = true, useCommonIdling = false)
@Ignore("temporary disabled")
class SubmitPublicKeyAfterCreationNonGoogleAccountFlowTest : BaseSignTest() {
override val activityScenarioRule = activityScenarioRule<MainActivity>()

private val userWithoutBackups = AccountDaoManager.getUserWithoutBackup()
@Volatile
private var isSubmitPubKeyCalled = false

val mockWebServerRule = FlowCryptMockWebServerRule(
Expand Down Expand Up @@ -109,20 +110,24 @@ class SubmitPublicKeyAfterCreationNonGoogleAccountFlowTest : BaseSignTest() {
.check(matches(isDisplayed()))
.perform(click())

waitForObjectWithText(
getResString(R.string.create_a_new_key).uppercase(),
TimeUnit.SECONDS.toMillis(5)
//the app checks the settings and searches for backups on the mail server first
waitUntilViewMatches(
viewId = R.id.buttonCreateNewKey,
matcher = isDisplayed(),
timeoutMs = TimeUnit.SECONDS.toMillis(30)
)

onView(withId(R.id.buttonCreateNewKey))
.check(matches(isDisplayed()))
.perform(click())

val passphrase = UUID.randomUUID().toString() + UUID.randomUUID().toString()
onView(withId(R.id.editTextKeyPassword))
.check(matches(isDisplayed()))
.perform(replaceText(passphrase))
Thread.sleep(TimeUnit.SECONDS.toMillis(1))
//the button does nothing until the passphrase strength is evaluated in the background
waitUntilViewMatches(
viewId = R.id.textViewPasswordQualityInfo,
matcher = withText(containsString(getResString(R.string.password_quality_subtext)))
)
onView(withId(R.id.buttonSetPassPhrase))
.check(matches(isDisplayed()))
.perform(click())
Expand All @@ -133,26 +138,43 @@ class SubmitPublicKeyAfterCreationNonGoogleAccountFlowTest : BaseSignTest() {
.check(matches(isDisplayed()))
.perform(click())

//need to wait while a key is creating
waitForObjectWithText(JavaEmailConstants.FOLDER_INBOX, TimeUnit.SECONDS.toMillis(10))

//the app sends a backup of the key to the inbox first, then submits the public key
waitUntil(TimeUnit.SECONDS.toMillis(30)) { isSubmitPubKeyCalled }
assertTrue(isSubmitPubKeyCalled)
} finally {
runBlocking {
val imapStoreConnection = IMAPStoreConnection(getTargetContext(), userWithoutBackups)
imapStoreConnection.connect()
imapStoreConnection.store.use { store ->
store.getFolder("INBOX").use { folder ->
val imapFolder = (folder as IMAPFolder).apply { open(Folder.READ_WRITE) }
val msgs =
imapFolder.messages.filter { it.subject == "Your FlowCrypt Backup" }.toTypedArray()
if (msgs.isNotEmpty()) {
imapFolder.setFlags(msgs, Flags(Flags.Flag.DELETED), true)
}
folder.expunge()
deleteBackupEmails()
}
}

/**
* Other tests expect that [userWithoutBackups] has no backups in the inbox. The mail server
* delivers the backup email asynchronously, so if the key was created, wait for the email
* before deleting it.
*/
private fun deleteBackupEmails() {
runBlocking {
val imapStoreConnection = IMAPStoreConnection(getTargetContext(), userWithoutBackups)
imapStoreConnection.connect()
imapStoreConnection.store.use { store ->
store.getFolder(JavaEmailConstants.FOLDER_INBOX).use { folder ->
val imapFolder = (folder as IMAPFolder).apply { open(Folder.READ_WRITE) }
val findBackups = {
imapFolder.messages.filter { it.subject == BACKUP_EMAIL_SUBJECT }.toTypedArray()
}
if (isSubmitPubKeyCalled) {
waitUntil(TimeUnit.SECONDS.toMillis(30)) { findBackups().isNotEmpty() }
}
val backups = findBackups()
if (backups.isNotEmpty()) {
imapFolder.setFlags(backups, Flags(Flags.Flag.DELETED), true)
}
folder.expunge()
}
}
}
}

companion object {
private const val BACKUP_EMAIL_SUBJECT = "Your FlowCrypt Backup"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.espresso.web.assertion.TagSoupDocumentParser
import androidx.test.espresso.web.assertion.WebViewAssertions.webContent
import androidx.test.espresso.web.matcher.DomMatchers.elementByXPath
import androidx.test.espresso.web.sugar.Web.onWebView
import com.flowcrypt.email.R
import com.flowcrypt.email.api.email.EmailUtil
import com.flowcrypt.email.api.email.model.AttachmentInfo
Expand Down Expand Up @@ -212,10 +211,9 @@ abstract class BaseMessageDetailsFlowTest : BaseTest() {
.joinToString(separator = "\n") { it.textContent }
.trim()

onWebView(withId(R.id.emailWebView)).forceJavascriptEnabled()
onWebView(withId(R.id.emailWebView))
.check(webContent(elementByXPath("/html/body", withTextContentMatcher(`is`(content)))))
//.check(webContent(withBody(withTextContentMatcher(`is`(content)))))
checkWebViewWithJavascript(withId(R.id.emailWebView)) { webView ->
webView.check(webContent(elementByXPath("/html/body", withTextContentMatcher(`is`(content)))))
}
}

protected fun testMissingKey(incomingMsgInfo: IncomingMessageInfo?) {
Expand Down
Loading
Loading