diff options
| author | test@dangofactory.cos <you@example.com> | 2026-08-20 16:57:18 +0000 |
|---|---|---|
| committer | test@dangofactory.cos <you@example.com> | 2026-08-20 16:57:18 +0000 |
| commit | 50ce5d5e6cd0d720ff437d35eace545816848428 (patch) | |
| tree | b59af206a36265cf081945e434900b32b0c43edd /app/ui/legacy/src/test/java/com | |
| download | monocles_mail-50ce5d5e6cd0d720ff437d35eace545816848428.tar.gz monocles_mail-50ce5d5e6cd0d720ff437d35eace545816848428.tar.bz2 monocles_mail-50ce5d5e6cd0d720ff437d35eace545816848428.zip | |
Inital
Diffstat (limited to 'app/ui/legacy/src/test/java/com')
24 files changed, 3925 insertions, 0 deletions
diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/K9RobolectricTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/K9RobolectricTest.kt new file mode 100644 index 0000000..4eb912f --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/K9RobolectricTest.kt @@ -0,0 +1,16 @@ +package com.fsck.k9 + +import android.app.Application +import org.junit.runner.RunWith +import org.koin.test.AutoCloseKoinTest +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * A Robolectric test that creates an instance of our [Application] test class [TestApp]. + * + * See also [RobolectricTest]. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = TestApp::class) +abstract class K9RobolectricTest : AutoCloseKoinTest() diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/RobolectricTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/RobolectricTest.kt new file mode 100644 index 0000000..8dde7f5 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/RobolectricTest.kt @@ -0,0 +1,17 @@ +package com.fsck.k9 + +import android.app.Application +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * A Robolectric test that does not create an instance of our [Application] class [K9]. + * + * See also [K9RobolectricTest]. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = EmptyApplication::class) +abstract class RobolectricTest + +class EmptyApplication : Application() diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/TestApp.kt b/app/ui/legacy/src/test/java/com/fsck/k9/TestApp.kt new file mode 100644 index 0000000..f120993 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/TestApp.kt @@ -0,0 +1,25 @@ +package com.fsck.k9 + +import android.app.Application +import com.fsck.k9.preferences.InMemoryStoragePersister +import com.fsck.k9.preferences.StoragePersister +import com.fsck.k9.storage.storageModule +import org.koin.dsl.module + +class TestApp : Application() { + override fun onCreate() { + Core.earlyInit() + + super.onCreate() + DI.start(this, coreModules + storageModule + testModule) + + K9.init(this) + Core.init(this) + } +} + +val testModule = module { + single { AppConfig(emptyList()) } + single<CoreResourceProvider> { TestCoreResourceProvider() } + single<StoragePersister> { InMemoryStoragePersister() } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/TestCoreResourceProvider.kt b/app/ui/legacy/src/test/java/com/fsck/k9/TestCoreResourceProvider.kt new file mode 100644 index 0000000..6669e65 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/TestCoreResourceProvider.kt @@ -0,0 +1,42 @@ +package com.fsck.k9 + +import com.fsck.k9.notification.PushNotificationState + +class TestCoreResourceProvider : CoreResourceProvider { + override fun defaultSignature() = throw UnsupportedOperationException("not implemented") + + override fun defaultIdentityDescription() = throw UnsupportedOperationException("not implemented") + + override fun contactDisplayNamePrefix() = throw UnsupportedOperationException("not implemented") + override fun contactUnknownSender() = throw UnsupportedOperationException("not implemented") + override fun contactUnknownRecipient() = throw UnsupportedOperationException("not implemented") + + override fun messageHeaderFrom() = throw UnsupportedOperationException("not implemented") + override fun messageHeaderTo() = throw UnsupportedOperationException("not implemented") + override fun messageHeaderCc() = throw UnsupportedOperationException("not implemented") + override fun messageHeaderDate() = throw UnsupportedOperationException("not implemented") + override fun messageHeaderSubject() = throw UnsupportedOperationException("not implemented") + override fun messageHeaderSeparator() = throw UnsupportedOperationException("not implemented") + + override fun noSubject() = throw UnsupportedOperationException("not implemented") + + override fun userAgent(): String = "K-9 Mail for Android" + override fun encryptedSubject(): String = "Encrypted message" + + override fun replyHeader(sender: String) = throw UnsupportedOperationException("not implemented") + override fun replyHeader(sender: String, sentDate: String) = throw UnsupportedOperationException("not implemented") + + override fun searchUnifiedInboxTitle() = throw UnsupportedOperationException("not implemented") + override fun searchUnifiedInboxDetail() = throw UnsupportedOperationException("not implemented") + + override fun outboxFolderName() = throw UnsupportedOperationException("not implemented") + + override val iconPushNotification: Int + get() = throw UnsupportedOperationException("not implemented") + + override fun pushNotificationText(notificationState: PushNotificationState): String { + throw UnsupportedOperationException("not implemented") + } + + override fun pushNotificationInfoText(): String = throw UnsupportedOperationException("not implemented") +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ViewTestExtensions.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ViewTestExtensions.kt new file mode 100644 index 0000000..0f1a3b9 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ViewTestExtensions.kt @@ -0,0 +1,6 @@ +package com.fsck.k9 + +import android.widget.TextView + +val TextView.textString: String + get() = text.toString() diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/account/AccountCreatorTest.java b/app/ui/legacy/src/test/java/com/fsck/k9/account/AccountCreatorTest.java new file mode 100644 index 0000000..cf4be31 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/account/AccountCreatorTest.java @@ -0,0 +1,75 @@ +package com.fsck.k9.account; + + +import android.content.res.Resources; + +import com.fsck.k9.Account.DeletePolicy; +import com.fsck.k9.Preferences; +import com.fsck.k9.RobolectricTest; +import com.fsck.k9.mail.ConnectionSecurity; +import com.fsck.k9.preferences.Protocols; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + + +public class AccountCreatorTest extends RobolectricTest { + private AccountCreator accountCreator; + + @Before + public void setUp() { + Preferences preferences = mock(Preferences.class); + Resources resources = mock(Resources.class); + accountCreator = new AccountCreator(preferences, resources); + } + + @Test + public void getDefaultDeletePolicy_withImap_shouldReturn_ON_DELETE() { + DeletePolicy result = accountCreator.getDefaultDeletePolicy(Protocols.IMAP); + + assertEquals(DeletePolicy.ON_DELETE, result); + } + + @Test + public void getDefaultDeletePolicy_withPop3_shouldReturn_NEVER() { + DeletePolicy result = accountCreator.getDefaultDeletePolicy(Protocols.POP3); + + assertEquals(DeletePolicy.NEVER, result); + } + + @Test + public void getDefaultDeletePolicy_withWebDav_shouldReturn_ON_DELETE() { + DeletePolicy result = accountCreator.getDefaultDeletePolicy(Protocols.WEBDAV); + + assertEquals(DeletePolicy.ON_DELETE, result); + } + + @Test(expected = AssertionError.class) + public void getDefaultDeletePolicy_withSmtp_shouldFail() { + accountCreator.getDefaultDeletePolicy(Protocols.SMTP); + } + + @Test + public void getDefaultPort_withNoConnectionSecurityAndImap_shouldReturnDefaultPort() { + int result = accountCreator.getDefaultPort(ConnectionSecurity.NONE, Protocols.IMAP); + + assertEquals(143, result); + } + + @Test + public void getDefaultPort_withStartTlsAndImap_shouldReturnDefaultPort() { + int result = accountCreator.getDefaultPort(ConnectionSecurity.STARTTLS_REQUIRED, Protocols.IMAP); + + assertEquals(143, result); + } + + @Test + public void getDefaultPort_withTlsAndImap_shouldReturnDefaultTlsPort() { + int result = accountCreator.getDefaultPort(ConnectionSecurity.SSL_TLS_REQUIRED, Protocols.IMAP); + + assertEquals(993, result); + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/AttachmentPresenterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/AttachmentPresenterTest.kt new file mode 100644 index 0000000..842a89a --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/AttachmentPresenterTest.kt @@ -0,0 +1,177 @@ +package com.fsck.k9.activity.compose + +import android.net.Uri +import androidx.loader.app.LoaderManager +import androidx.loader.app.LoaderManager.LoaderCallbacks +import androidx.test.core.app.ApplicationProvider +import assertk.assertThat +import assertk.assertions.hasSize +import assertk.assertions.isEmpty +import assertk.assertions.isEqualTo +import assertk.assertions.isFalse +import assertk.assertions.isTrue +import com.fsck.k9.K9RobolectricTest +import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentMvpView +import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentsChangedListener +import com.fsck.k9.activity.misc.Attachment +import com.fsck.k9.mail.internet.MimeHeader +import com.fsck.k9.mail.internet.MimeMessage +import com.fsck.k9.mail.internet.MimeMessageHelper +import com.fsck.k9.mail.internet.TextBody +import com.fsck.k9.mailstore.AttachmentResolver +import com.fsck.k9.mailstore.AttachmentViewInfo +import com.fsck.k9.mailstore.LocalBodyPart +import com.fsck.k9.mailstore.MessageViewInfo +import java.util.function.Supplier +import org.junit.Before +import org.junit.Test +import org.mockito.ArgumentMatchers.anyInt +import org.mockito.Mockito.doAnswer +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +private val attachmentMvpView = mock<AttachmentMvpView>() +private val loaderManager = mock<LoaderManager>() +private val listener = mock<AttachmentsChangedListener>() +private val attachmentResolver = mock<AttachmentResolver>() + +private const val ACCOUNT_UUID = "uuid" +private const val SUBJECT = "subject" +private const val TEXT = "text" +private const val EXTRA_TEXT = "extra text" +private const val ATTACHMENT_NAME = "1x1.png" +private const val MESSAGE_ID = 1L +private const val PATH_TO_FILE = "path/to/file.png" +private const val MIME_TYPE = "image/png" +private val URI = Uri.Builder().scheme("content://").build() + +class AttachmentPresenterTest : K9RobolectricTest() { + lateinit var attachmentPresenter: AttachmentPresenter + + @Before + fun setUp() { + attachmentPresenter = AttachmentPresenter( + ApplicationProvider.getApplicationContext(), + attachmentMvpView, + loaderManager, + listener + ) + } + + @Test + fun loadNonInlineAttachments_normalAttachment() { + val size = 42L + val message = MimeMessage() + MimeMessageHelper.setBody(message, TextBody(TEXT)) + val attachmentViewInfo = AttachmentViewInfo( + MIME_TYPE, + ATTACHMENT_NAME, + size, + URI, + false, + LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size), + true + ) + val messageViewInfo = MessageViewInfo( + message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, + EXTRA_TEXT, ArrayList(), null + ) + + mockLoaderManager({ attachmentPresenter.attachments.get(0) as Attachment }) + + val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) + + assertThat(result).isTrue() + assertThat(attachmentPresenter.attachments).hasSize(1) + assertThat(attachmentPresenter.inlineAttachments).isEmpty() + val attachment = attachmentPresenter.attachments.get(0) + assertThat(attachment?.name).isEqualTo(ATTACHMENT_NAME) + assertThat(attachment?.size).isEqualTo(size) + assertThat(attachment?.state).isEqualTo(com.fsck.k9.message.Attachment.LoadingState.COMPLETE) + assertThat(attachment?.fileName).isEqualTo(PATH_TO_FILE) + } + + @Test + fun loadNonInlineAttachments_normalAttachmentNotAvailable() { + val size = 42L + val message = MimeMessage() + MimeMessageHelper.setBody(message, TextBody(TEXT)) + val attachmentViewInfo = AttachmentViewInfo( + MIME_TYPE, + ATTACHMENT_NAME, + size, + URI, + false, + LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size), + false + ) + val messageViewInfo = MessageViewInfo( + message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, + EXTRA_TEXT, ArrayList(), null + ) + + val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) + + assertThat(result).isFalse() + assertThat(attachmentPresenter.attachments).isEmpty() + assertThat(attachmentPresenter.inlineAttachments).isEmpty() + } + + @Test + fun loadNonInlineAttachments_inlineAttachment() { + val size = 42L + val contentId = "xyz" + val message = MimeMessage() + MimeMessageHelper.setBody(message, TextBody(TEXT)) + val localBodyPart = LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size) + localBodyPart.addHeader(MimeHeader.HEADER_CONTENT_ID, contentId) + val attachmentViewInfo = AttachmentViewInfo(MIME_TYPE, ATTACHMENT_NAME, size, URI, true, localBodyPart, true) + val messageViewInfo = MessageViewInfo( + message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, + EXTRA_TEXT, ArrayList(), null + ) + + mockLoaderManager({ attachmentPresenter.inlineAttachments.get(contentId) as Attachment }) + + val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) + + assertThat(result).isTrue() + assertThat(attachmentPresenter.attachments).isEmpty() + assertThat(attachmentPresenter.inlineAttachments).hasSize(1) + val attachment = attachmentPresenter.inlineAttachments.get(contentId) + assertThat(attachment?.name).isEqualTo(ATTACHMENT_NAME) + assertThat(attachment?.size).isEqualTo(size) + assertThat(attachment?.state).isEqualTo(com.fsck.k9.message.Attachment.LoadingState.COMPLETE) + assertThat(attachment?.fileName).isEqualTo(PATH_TO_FILE) + } + + @Test + fun loadNonInlineAttachments_inlineAttachmentNotAvailable() { + val size = 42L + val contentId = "xyz" + val message = MimeMessage() + MimeMessageHelper.setBody(message, TextBody(TEXT)) + val localBodyPart = LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size) + localBodyPart.addHeader(MimeHeader.HEADER_CONTENT_ID, contentId) + val attachmentViewInfo = AttachmentViewInfo(MIME_TYPE, ATTACHMENT_NAME, size, URI, true, localBodyPart, false) + val messageViewInfo = MessageViewInfo( + message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, + EXTRA_TEXT, ArrayList(), null + ) + + val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) + + assertThat(result).isFalse() + assertThat(attachmentPresenter.attachments).isEmpty() + assertThat(attachmentPresenter.inlineAttachments).isEmpty() + } + + private fun mockLoaderManager(attachmentSupplier: Supplier<Attachment>) { + doAnswer { + val loaderCallbacks = it.getArgument<LoaderCallbacks<Attachment>>(2) + loaderCallbacks.onLoadFinished(mock(), attachmentSupplier.get().deriveWithLoadComplete(PATH_TO_FILE)) + null + }.whenever(loaderManager).initLoader(anyInt(), any(), any<LoaderCallbacks<Attachment>>()) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java new file mode 100644 index 0000000..6d98945 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientLoaderTest.java @@ -0,0 +1,330 @@ +package com.fsck.k9.activity.compose; + + +import java.util.List; + +import android.Manifest; +import android.app.Application; +import android.content.ContentResolver; +import android.content.Context; +import android.database.MatrixCursor; +import android.net.Uri; +import android.provider.ContactsContract; +import android.provider.ContactsContract.CommonDataKinds.Email; + +import com.fsck.k9.RobolectricTest; +import com.fsck.k9.mail.Address; +import com.fsck.k9.view.RecipientSelectView.Recipient; +import com.fsck.k9.view.RecipientSelectView.RecipientCryptoStatus; +import org.junit.Before; +import org.junit.Test; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.Shadows; +import org.robolectric.shadows.ShadowApplication; + +import static android.provider.ContactsContract.CommonDataKinds.Email.TYPE_HOME; +import static org.junit.Assert.assertEquals; +import static org.mockito.AdditionalMatchers.aryEq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + + +@SuppressWarnings("WeakerAccess") +public class RecipientLoaderTest extends RobolectricTest { + static final String CRYPTO_PROVIDER = "cryptoProvider"; + static final String[] PROJECTION = { + ContactsContract.CommonDataKinds.Email._ID, + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, + ContactsContract.Contacts.LOOKUP_KEY, + ContactsContract.CommonDataKinds.Email.ADDRESS, + ContactsContract.CommonDataKinds.Email.TYPE, + ContactsContract.CommonDataKinds.Email.LABEL, + ContactsContract.CommonDataKinds.Email.CONTACT_ID, + ContactsContract.Contacts.PHOTO_THUMBNAIL_URI, + ContactsContract.CommonDataKinds.Email.TIMES_CONTACTED, + ContactsContract.Contacts.SORT_KEY_PRIMARY, + ContactsContract.Contacts.STARRED + }; + static final String[] PROJECTION_NICKNAME = { + ContactsContract.Data.CONTACT_ID, + ContactsContract.CommonDataKinds.Nickname.NAME + }; + static final String[] PROJECTION_CRYPTO_ADDRESSES = { "address", "uid_address" }; + static final String[] PROJECTION_CRYPTO_STATUS = { "address", "uid_key_status", "autocrypt_key_status" }; + static final Address CONTACT_ADDRESS_1 = Address.parse("Contact Name <address@example.org>")[0]; + static final Address CONTACT_ADDRESS_2 = Address.parse("Other Contact Name <address_two@example.org>")[0]; + static final String TYPE = "" + TYPE_HOME; + static final String[] CONTACT_1 = + new String[] { "0", "Bob", "bob", "bob@host.com", TYPE, null, "1", null, "100", "Bob", "0" }; + static final String[] CONTACT_2 = + new String[] { "2", "Bob2", "bob2", "bob2@host.com", TYPE, null, "2", null, "99", "Bob2", "0" }; + static final String[] CONTACT_NO_EMAIL = + new String[] { "0", "Bob", "bob", null, TYPE, null, "1", null, "10", "Bob_noMail", "0" }; + static final String[] CONTACT_WITH_NICKNAME_NOT_CONTACTED = + new String[] { "0", "Eve_notContacted", "eve_notContacted", "eve_notContacted@host.com", TYPE, null, "2", + null, "0", "Eve", "0" }; + static final String[] NICKNAME_NOT_CONTACTED = new String[] { "2", "Eves_Nickname_Bob" }; + + static final String QUERYSTRING = "querystring"; + + ShadowApplication shadowApp; + Context context; + ContentResolver contentResolver; + + + @Before + public void setUp() throws Exception { + Application application = RuntimeEnvironment.getApplication(); + shadowApp = Shadows.shadowOf(application); + shadowApp.grantPermissions(Manifest.permission.READ_CONTACTS); + shadowApp.grantPermissions(Manifest.permission.WRITE_CONTACTS); + + context = mock(Context.class); + contentResolver = mock(ContentResolver.class); + + when(context.getApplicationContext()).thenReturn(application); + when(context.getContentResolver()).thenReturn(contentResolver); + } + + @Test + public void queryCryptoProvider() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, QUERYSTRING); + + setupQueryCryptoProvider("%" + QUERYSTRING + "%", CONTACT_ADDRESS_1, CONTACT_ADDRESS_2); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(2, recipients.size()); + assertEquals(CONTACT_ADDRESS_1, recipients.get(0).address); + assertEquals(CONTACT_ADDRESS_2, recipients.get(1).address); + assertEquals(RecipientCryptoStatus.UNAVAILABLE, recipients.get(0).getCryptoStatus()); + } + + @Test + public void queryCryptoStatus_unavailable() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, CONTACT_ADDRESS_1); + + setupCryptoProviderStatus(CONTACT_ADDRESS_1, "0", "0"); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(1, recipients.size()); + Recipient recipient = recipients.get(0); + assertEquals(CONTACT_ADDRESS_1, recipient.address); + assertEquals(RecipientCryptoStatus.UNAVAILABLE, recipient.getCryptoStatus()); + } + + @Test + public void queryCryptoStatus_autocrypt_untrusted() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, CONTACT_ADDRESS_1); + + setupCryptoProviderStatus(CONTACT_ADDRESS_1, "0", "1"); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(1, recipients.size()); + Recipient recipient = recipients.get(0); + assertEquals(CONTACT_ADDRESS_1, recipient.address); + assertEquals(RecipientCryptoStatus.AVAILABLE_UNTRUSTED, recipient.getCryptoStatus()); + } + + @Test + public void queryCryptoStatus_autocrypt_trusted() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, CONTACT_ADDRESS_1); + + setupCryptoProviderStatus(CONTACT_ADDRESS_1, "0", "2"); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(1, recipients.size()); + Recipient recipient = recipients.get(0); + assertEquals(CONTACT_ADDRESS_1, recipient.address); + assertEquals(RecipientCryptoStatus.AVAILABLE_TRUSTED, recipient.getCryptoStatus()); + } + + @Test + public void queryCryptoStatus_withHigherUidStatus() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, CONTACT_ADDRESS_1); + + setupCryptoProviderStatus(CONTACT_ADDRESS_1, "2", "1"); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(1, recipients.size()); + Recipient recipient = recipients.get(0); + assertEquals(CONTACT_ADDRESS_1, recipient.address); + assertEquals(RecipientCryptoStatus.AVAILABLE_TRUSTED, recipient.getCryptoStatus()); + } + + private void setupQueryCryptoProvider(String queriedAddress, Address... contactAddresses) { + MatrixCursor cursor = new MatrixCursor(PROJECTION_CRYPTO_ADDRESSES); + for (Address contactAddress : contactAddresses) { + cursor.addRow(new String[] { queriedAddress, contactAddress.toString() }); + } + + when(contentResolver + .query(eq(Uri.parse("content://" + CRYPTO_PROVIDER + ".provider.exported/autocrypt_status")), + aryEq(PROJECTION_CRYPTO_ADDRESSES), nullable(String.class), + aryEq(new String[] { queriedAddress }), + nullable(String.class))).thenReturn(cursor); + } + + private void setupCryptoProviderStatus(Address address, String uidStatus, String autocryptStatus) { + MatrixCursor cursorCryptoStatus = new MatrixCursor(PROJECTION_CRYPTO_STATUS); + cursorCryptoStatus.addRow(new String[] { address.getAddress(), uidStatus, autocryptStatus }); + + when(contentResolver + .query(eq(Uri.parse("content://" + CRYPTO_PROVIDER + ".provider.exported/autocrypt_status")), + aryEq(PROJECTION_CRYPTO_STATUS), nullable(String.class), + aryEq(new String[] { address.getAddress() }), + nullable(String.class))).thenReturn(cursorCryptoStatus); + } + + private void setupContactProvider(String queriedAddress, String[]... contacts) { + MatrixCursor cursor = new MatrixCursor(PROJECTION); + for (String[] contact : contacts) { + cursor.addRow(contact); + } + when(contentResolver + .query(eq(Email.CONTENT_URI), + aryEq(PROJECTION), + nullable(String.class), + aryEq(new String[] { queriedAddress, queriedAddress }), + nullable(String.class))).thenReturn(cursor); + } + + private void setupNicknameContactProvider(String[]... contactsWithNickname) { + MatrixCursor cursor = new MatrixCursor(PROJECTION_NICKNAME); + for (String[] contact : contactsWithNickname) { + cursor.addRow(contact); + } + when(contentResolver + .query(eq(ContactsContract.Data.CONTENT_URI), + aryEq(PROJECTION_NICKNAME), + nullable(String.class), + nullable(String[].class), + nullable(String.class))).thenReturn(cursor); + } + + private void setupContactProviderForId(String id, String[]... contacts) { + MatrixCursor cursor = new MatrixCursor(PROJECTION); + for (String[] contact : contacts) { + cursor.addRow(contact); + } + when(contentResolver + .query(eq(Email.CONTENT_URI), + aryEq(PROJECTION), + nullable(String.class), + aryEq(new String[] { id }), + nullable(String.class))).thenReturn(cursor); + } + + + @Test + public void queryContactProvider() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, QUERYSTRING); + setupContactProvider("%" + QUERYSTRING + "%", CONTACT_1); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(1, recipients.size()); + assertEquals("bob@host.com", recipients.get(0).address.getAddress()); + assertEquals(RecipientCryptoStatus.UNAVAILABLE, recipients.get(0).getCryptoStatus()); + } + + + @Test + public void queryContactProviderWithoutPermission() throws Exception { + shadowApp.denyPermissions(Manifest.permission.READ_CONTACTS); + shadowApp.denyPermissions(Manifest.permission.WRITE_CONTACTS); + + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, QUERYSTRING); + setupContactProvider("%" + QUERYSTRING + "%", CONTACT_1); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(0, recipients.size()); + } + + @Test + public void queryContactProvider_ignoresRecipientWithNoEmail() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, CRYPTO_PROVIDER, QUERYSTRING); + setupContactProvider("%" + QUERYSTRING + "%", CONTACT_NO_EMAIL); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(0, recipients.size()); + } + + @Test + public void queryContactProvider_sortByTimesContactedForNickname() throws Exception { + RecipientLoader recipientLoader = new RecipientLoader(context, null, QUERYSTRING); + setupContactProvider("%" + QUERYSTRING + "%", CONTACT_1); + setupNicknameContactProvider(NICKNAME_NOT_CONTACTED); + setupContactProviderForId(NICKNAME_NOT_CONTACTED[0], CONTACT_WITH_NICKNAME_NOT_CONTACTED); + + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(2, recipients.size()); + assertEquals("bob@host.com", recipients.get(0).address.getAddress()); + assertEquals("eve_notContacted@host.com", recipients.get(1).address.getAddress()); + } + + @Test + public void getMostContactedFoundMore() throws Exception { + int maxTargets = 1; + setupContactProvider(CONTACT_1, CONTACT_2); + + RecipientLoader recipientLoader = RecipientLoader.getMostContactedRecipientLoader(context, maxTargets); + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(maxTargets, recipients.size()); + assertEquals("bob@host.com", recipients.get(0).address.getAddress()); + assertEquals(RecipientCryptoStatus.UNDEFINED, recipients.get(0).getCryptoStatus()); + } + + @Test + public void getMostContactedFoundLess() throws Exception { + int maxTargets = 5; + setupContactProvider(CONTACT_1, CONTACT_2); + + RecipientLoader recipientLoader = RecipientLoader.getMostContactedRecipientLoader(context, maxTargets); + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(2, recipients.size()); + assertEquals("bob@host.com", recipients.get(0).address.getAddress()); + assertEquals(RecipientCryptoStatus.UNDEFINED, recipients.get(0).getCryptoStatus()); + assertEquals("bob2@host.com", recipients.get(1).address.getAddress()); + assertEquals(RecipientCryptoStatus.UNDEFINED, recipients.get(1).getCryptoStatus()); + } + + @Test + public void getMostContactedFoundNothing() throws Exception { + int maxTargets = 5; + setupContactProvider(); + + + RecipientLoader recipientLoader = RecipientLoader.getMostContactedRecipientLoader(context, maxTargets); + List<Recipient> recipients = recipientLoader.loadInBackground(); + + assertEquals(0, recipients.size()); + } + + + private void setupContactProvider(String[]... contacts) { + MatrixCursor cursor = new MatrixCursor(PROJECTION); + for (String[] contact : contacts) { + cursor.addRow(contact); + } + when(contentResolver + .query(eq(Email.CONTENT_URI), + aryEq(PROJECTION), + isNull(), + isNull(), + nullable(String.class))).thenReturn(cursor); + + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.kt new file mode 100644 index 0000000..03b9855 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/RecipientPresenterTest.kt @@ -0,0 +1,317 @@ +package com.fsck.k9.activity.compose + +import androidx.test.core.app.ApplicationProvider +import assertk.assertThat +import assertk.assertions.isEqualTo +import assertk.assertions.isFalse +import assertk.assertions.isNull +import assertk.assertions.isTrue +import com.fsck.k9.Account +import com.fsck.k9.K9RobolectricTest +import com.fsck.k9.activity.compose.RecipientMvpView.CryptoSpecialModeDisplayType +import com.fsck.k9.activity.compose.RecipientMvpView.CryptoStatusDisplayType +import com.fsck.k9.activity.compose.RecipientPresenter.CryptoMode +import com.fsck.k9.autocrypt.AutocryptDraftStateHeaderParser +import com.fsck.k9.helper.ReplyToParser +import com.fsck.k9.helper.ReplyToParser.ReplyToAddresses +import com.fsck.k9.mail.Address +import com.fsck.k9.mail.Message +import com.fsck.k9.mail.Message.RecipientType +import com.fsck.k9.message.AutocryptStatusInteractor +import com.fsck.k9.message.AutocryptStatusInteractor.RecipientAutocryptStatus +import com.fsck.k9.message.AutocryptStatusInteractor.RecipientAutocryptStatusType +import com.fsck.k9.message.ComposePgpEnableByDefaultDecider +import com.fsck.k9.message.ComposePgpInlineDecider +import com.fsck.k9.view.RecipientSelectView.Recipient +import kotlin.test.assertNotNull +import org.junit.Before +import org.junit.Ignore +import org.junit.Test +import org.koin.test.inject +import org.mockito.ArgumentMatchers.eq +import org.mockito.Mockito.verify +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.stubbing +import org.openintents.openpgp.OpenPgpApiManager +import org.openintents.openpgp.OpenPgpApiManager.OpenPgpApiManagerCallback +import org.openintents.openpgp.OpenPgpApiManager.OpenPgpProviderState +import org.openintents.openpgp.util.OpenPgpApi +import org.robolectric.Robolectric +import org.robolectric.annotation.LooperMode + +private val TO_ADDRESS = Address("to@domain.example") +private val CC_ADDRESS = Address("cc@domain.example") +private const val CRYPTO_PROVIDER = "crypto_provider" +private const val CRYPTO_KEY_ID = 123L + +@LooperMode(LooperMode.Mode.LEGACY) +class RecipientPresenterTest : K9RobolectricTest() { + private val openPgpApiManager = mock<OpenPgpApiManager> { + on { openPgpProviderState } doReturn OpenPgpProviderState.UNCONFIGURED + on { setOpenPgpProvider(any(), any()) } doAnswer { invocation -> + openPgpApiManagerCallback = invocation.getArgument(1) + } + } + private val recipientMvpView = mock<RecipientMvpView>() + private val account = mock<Account>() + private val composePgpInlineDecider = mock<ComposePgpInlineDecider>() + private val composePgpEnableByDefaultDecider = mock<ComposePgpEnableByDefaultDecider>() + private val autocryptStatusInteractor = mock<AutocryptStatusInteractor>() + private val replyToParser = mock<ReplyToParser>() + private val autocryptDraftStateHeaderParser: AutocryptDraftStateHeaderParser by inject() + private lateinit var recipientPresenter: RecipientPresenter + + private val noRecipientsAutocryptResult = RecipientAutocryptStatus(RecipientAutocryptStatusType.NO_RECIPIENTS, null) + private var openPgpApiManagerCallback: OpenPgpApiManagerCallback? = null + + @Before + fun setUp() { + Robolectric.getBackgroundThreadScheduler().pause() + + recipientPresenter = RecipientPresenter( + ApplicationProvider.getApplicationContext(), + mock(), + openPgpApiManager, + recipientMvpView, + account, + composePgpInlineDecider, + composePgpEnableByDefaultDecider, + autocryptStatusInteractor, + replyToParser, + autocryptDraftStateHeaderParser + ) + } + + @Test + @Ignore("It looks like the support version of AsyncTaskLoader handles background tasks differently") + fun testInitFromReplyToMessage() { + val message = mock<Message>() + stubbing(replyToParser) { + on { getRecipientsToReplyTo(message, account) } doReturn ReplyToAddresses(arrayOf(TO_ADDRESS)) + } + + recipientPresenter.initFromReplyToMessage(message, false) + runBackgroundTask() + + verify(recipientMvpView).addRecipients(eq(RecipientType.TO), eq(Recipient(TO_ADDRESS))) + } + + @Test + @Ignore("It looks like the support version of AsyncTaskLoader handles background tasks differently") + fun testInitFromReplyToAllMessage() { + val message = mock<Message>() + val replyToAddresses = ReplyToAddresses(listOf(TO_ADDRESS), listOf(CC_ADDRESS)) + stubbing(replyToParser) { + on { getRecipientsToReplyAllTo(message, account) } doReturn replyToAddresses + } + + recipientPresenter.initFromReplyToMessage(message, true) + runBackgroundTask() + runBackgroundTask() + + verify(recipientMvpView).addRecipients(eq(RecipientType.TO), eq(Recipient(TO_ADDRESS))) + verify(recipientMvpView).addRecipients(eq(RecipientType.CC), eq(Recipient(CC_ADDRESS))) + } + + @Test + fun initFromReplyToMessage_shouldCallComposePgpInlineDecider() { + val message = mock<Message>() + stubbing(replyToParser) { + on { getRecipientsToReplyTo(message, account) } doReturn ReplyToAddresses(arrayOf(TO_ADDRESS)) + } + + recipientPresenter.initFromReplyToMessage(message, false) + + verify(composePgpInlineDecider).shouldReplyInline(message) + } + + @Test + fun getCurrentCryptoStatus_withoutCryptoProvider() { + stubbing(openPgpApiManager) { + on { openPgpProviderState } doReturn OpenPgpProviderState.UNCONFIGURED + } + + recipientPresenter.asyncUpdateCryptoStatus() + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.UNCONFIGURED) + assertThat(status.specialModeDisplayType).isEqualTo(CryptoSpecialModeDisplayType.NONE) + assertThat(status.attachErrorStateOrNull).isNull() + assertThat(status.isProviderStateOk()).isFalse() + assertThat(status.isOpenPgpConfigured).isFalse() + } + } + + @Test + fun getCurrentCryptoStatus_withCryptoProvider() { + setupCryptoProvider(noRecipientsAutocryptResult) + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.UNAVAILABLE) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withOpportunistic() { + val recipientAutocryptStatus = RecipientAutocryptStatus( + RecipientAutocryptStatusType.AVAILABLE_UNCONFIRMED, + null + ) + + setupCryptoProvider(recipientAutocryptStatus) + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.AVAILABLE) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withOpportunistic__confirmed() { + val recipientAutocryptStatus = RecipientAutocryptStatus( + RecipientAutocryptStatusType.AVAILABLE_CONFIRMED, + null + ) + + setupCryptoProvider(recipientAutocryptStatus) + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.AVAILABLE) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withOpportunistic__missingKeys() { + val recipientAutocryptStatus = RecipientAutocryptStatus( + RecipientAutocryptStatusType.UNAVAILABLE, + null + ) + + setupCryptoProvider(recipientAutocryptStatus) + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.UNAVAILABLE) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withOpportunistic__privateMissingKeys() { + val recipientAutocryptStatus = RecipientAutocryptStatus( + RecipientAutocryptStatusType.UNAVAILABLE, + null + ) + + setupCryptoProvider(recipientAutocryptStatus) + recipientPresenter.onCryptoModeChanged(CryptoMode.CHOICE_ENABLED) + runBackgroundTask() + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.ENABLED_ERROR) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withModeDisabled() { + val recipientAutocryptStatus = RecipientAutocryptStatus( + RecipientAutocryptStatusType.AVAILABLE_UNCONFIRMED, + null + ) + + setupCryptoProvider(recipientAutocryptStatus) + recipientPresenter.onCryptoModeChanged(CryptoMode.CHOICE_DISABLED) + runBackgroundTask() + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.AVAILABLE) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withModePrivate() { + val recipientAutocryptStatus = RecipientAutocryptStatus( + RecipientAutocryptStatusType.AVAILABLE_UNCONFIRMED, + null + ) + + setupCryptoProvider(recipientAutocryptStatus) + recipientPresenter.onCryptoModeChanged(CryptoMode.CHOICE_ENABLED) + runBackgroundTask() + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.ENABLED) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withModeSignOnly() { + setupCryptoProvider(noRecipientsAutocryptResult) + + recipientPresenter.onMenuSetSignOnly(true) + runBackgroundTask() + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.SIGN_ONLY) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isOpenPgpConfigured).isTrue() + assertThat(status.isSignOnly).isTrue() + } + } + + @Test + fun getCurrentCryptoStatus_withModeInline() { + setupCryptoProvider(noRecipientsAutocryptResult) + + recipientPresenter.onMenuSetPgpInline(true) + runBackgroundTask() + + assertNotNull(recipientPresenter.currentCachedCryptoStatus) { status -> + assertThat(status.displayType).isEqualTo(CryptoStatusDisplayType.UNAVAILABLE) + assertThat(status.isProviderStateOk()).isTrue() + assertThat(status.isPgpInlineModeEnabled).isTrue() + } + } + + private fun runBackgroundTask() { + assertThat(Robolectric.getBackgroundThreadScheduler().runOneTask()).isTrue() + } + + private fun setupCryptoProvider(autocryptStatusResult: RecipientAutocryptStatus) { + stubbing(account) { + on { openPgpProvider } doReturn CRYPTO_PROVIDER + on { isOpenPgpProviderConfigured } doReturn true + on { openPgpKey } doReturn CRYPTO_KEY_ID + } + + recipientPresenter.onSwitchAccount(account) + + val openPgpApiMock = mock<OpenPgpApi>() + + stubbing(autocryptStatusInteractor) { + on { retrieveCryptoProviderRecipientStatus(eq(openPgpApiMock), any()) } doReturn autocryptStatusResult + } + + stubbing(openPgpApiManager) { + on { openPgpApi } doReturn openPgpApiMock + on { openPgpProviderState } doReturn OpenPgpProviderState.OK + } + + openPgpApiManagerCallback!!.onOpenPgpProviderStatusChanged() + runBackgroundTask() + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/ReplyToPresenterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/ReplyToPresenterTest.kt new file mode 100644 index 0000000..69c4202 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/ReplyToPresenterTest.kt @@ -0,0 +1,120 @@ +package com.fsck.k9.activity.compose + +import android.os.Bundle +import assertk.assertThat +import assertk.assertions.isFalse +import assertk.assertions.isSameAs +import assertk.assertions.isTrue +import com.fsck.k9.Identity +import com.fsck.k9.RobolectricTest +import com.fsck.k9.mail.Address +import org.junit.Test +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.stubbing +import org.mockito.kotlin.verify + +private const val REPLY_TO_ADDRESS = "reply-to@example.com" +private const val REPLY_TO_ADDRESS_2 = "reply-to2@example.com" +private const val REPLY_TO_ADDRESS_3 = "reply-to3@example.com" + +class ReplyToPresenterTest : RobolectricTest() { + private val view = mock<ReplyToView>() + private val replyToPresenter = ReplyToPresenter(view) + + @Test + fun testInstanceState_expectStoreVisibility() { + val initialView = mock<ReplyToView> { + on { isVisible } doReturn true + } + val initialPresenter = ReplyToPresenter(initialView) + val state = Bundle() + initialPresenter.onSaveInstanceState(state) + + replyToPresenter.onRestoreInstanceState(state) + + verify(view).isVisible = true + } + + @Test + fun testGetAddresses_expectAddressesFromView() { + val addresses = Address.parse(REPLY_TO_ADDRESS) + stubbing(view) { + on { getAddresses() } doReturn addresses + } + + val result = replyToPresenter.getAddresses() + + assertThat(result).isSameAs(addresses) + } + + @Test + fun testHasUncompletedRecipients_onlyCompleteAddresses_expectTrue() { + stubbing(view) { + on { hasUncompletedText() } doReturn false + } + + val result = replyToPresenter.isNotReadyForSending() + + assertThat(result).isFalse() + } + + @Test + fun testHasUncompletedRecipients_notCompleteAddresses_expectFalse() { + stubbing(view) { + on { hasUncompletedText() } doReturn true + } + + val result = replyToPresenter.isNotReadyForSending() + + assertThat(result).isTrue() + verify(view).showError() + verify(view).isVisible = true + } + + @Test + fun testSetIdentity_identityWithOneReplyTo_expectSetReplyTo() { + val identity = Identity("a", "b", "x@y.z", null, false, REPLY_TO_ADDRESS) + + replyToPresenter.setIdentity(identity) + + verify(view).silentlyAddAddresses(Address.parse(REPLY_TO_ADDRESS)) + } + + @Test + fun testSetIdentity_identityWithMultipleReplyTo_expectSetReplyTo() { + val replyTo = "$REPLY_TO_ADDRESS, $REPLY_TO_ADDRESS_2" + val identity = Identity("a", "b", "x@y.z", null, false, replyTo) + + replyToPresenter.setIdentity(identity) + + verify(view).silentlyAddAddresses(Address.parse(replyTo)) + } + + @Test + fun testOnSwitchIdentity_newIdentityWithoutReplyTo_expectRemoveReplyToOfOldIdentity() { + val replyToOne = "$REPLY_TO_ADDRESS, $REPLY_TO_ADDRESS_2" + val identityOne = Identity("a", "b", "x@y.z", null, false, replyToOne) + val identityTwo = Identity() + + replyToPresenter.setIdentity(identityOne) + replyToPresenter.setIdentity(identityTwo) + + verify(view).silentlyRemoveAddresses(Address.parse(replyToOne)) + } + + @Test + fun testOnSwitchIdentity_identityWithSubsetOfOldIdentity_expectRemoveThenAdd() { + val replyToOne = "$REPLY_TO_ADDRESS, $REPLY_TO_ADDRESS_2" + val identityOne = Identity("a", "b", "x@y.z", null, false, replyToOne) + val replyToTwo = "$REPLY_TO_ADDRESS, $REPLY_TO_ADDRESS_3" + val identityTwo = Identity("c", "d", "x@y.z", null, false, replyToTwo) + + replyToPresenter.setIdentity(identityOne) + replyToPresenter.setIdentity(identityTwo) + + verify(view).silentlyAddAddresses(Address.parse(replyToOne)) + verify(view).silentlyRemoveAddresses(Address.parse(replyToOne)) + verify(view).silentlyAddAddresses(Address.parse(replyToTwo)) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/autocrypt/AutocryptOperationsHelper.java b/app/ui/legacy/src/test/java/com/fsck/k9/autocrypt/AutocryptOperationsHelper.java new file mode 100644 index 0000000..a939ee8 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/autocrypt/AutocryptOperationsHelper.java @@ -0,0 +1,23 @@ +package com.fsck.k9.autocrypt; + + +import com.fsck.k9.mail.internet.MimeMessage; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static org.junit.Assert.assertArrayEquals; + + +public class AutocryptOperationsHelper { + private static AutocryptHeaderParser INSTANCE = AutocryptHeaderParser.getInstance(); + + public static void assertMessageHasAutocryptHeader( + MimeMessage message, String addr, boolean isPreferEncryptMutual, byte[] keyData) { + AutocryptHeader autocryptHeader = INSTANCE.getValidAutocryptHeader(message); + + assertNotNull(autocryptHeader); + assertEquals(addr, autocryptHeader.addr); + assertEquals(isPreferEncryptMutual, autocryptHeader.isPreferEncryptMutual); + assertArrayEquals(keyData, autocryptHeader.keyData); + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/contacts/ContactLetterExtractorTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/contacts/ContactLetterExtractorTest.kt new file mode 100644 index 0000000..cc793c4 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/contacts/ContactLetterExtractorTest.kt @@ -0,0 +1,59 @@ +package com.fsck.k9.contacts + +import com.fsck.k9.RobolectricTest +import com.fsck.k9.mail.Address +import org.junit.Assert.assertEquals +import org.junit.Test + +class ContactLetterExtractorTest : RobolectricTest() { + val letterExtractor = ContactLetterExtractor() + + @Test + fun extractContactLetter_withNoNameUsesAddress() { + assertExtractedLetterEquals("C", "<c@d.com>") + } + + @Test + fun extractContactLetter_withAsciiName() { + assertExtractedLetterEquals("A", "abcd <a@b.com>") + } + + @Test + fun extractContactLetter_withLstroke() { + assertExtractedLetterEquals("Ł", "Łatynka <a@b.com>") + } + + @Test + fun extractContactLetter_withChinese() { + assertExtractedLetterEquals("千", "千里之行﹐始于足下 <a@b.com>") + } + + @Test + fun extractContactLetter_withCombinedGlyphs() { + assertExtractedLetterEquals("\u0041\u0300", "\u0061\u0300 <a@b.com>") + } + + @Test + fun extractContactLetter_withSurrogatePair() { + assertExtractedLetterEquals("\uD800\uDFB5", "\uD800\uDFB5 <a@b.com>") + } + + @Test + fun extractContactLetter_ignoresSpace() { + assertExtractedLetterEquals("A", " abcd <a@b.com>") + } + + @Test + fun extractContactLetter_ignoresUsePunctuation() { + assertExtractedLetterEquals("A", "-a <a@b.com>") + } + + @Test + fun extractContactLetter_ignoresMatchEmoji() { + assertExtractedLetterEquals("?", "\uD83D\uDE00 <a@b.com>") + } + + private fun assertExtractedLetterEquals(expected: String, address: String) { + assertEquals(expected, letterExtractor.extractContactLetter(Address(address))) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/message/PgpMessageBuilderTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/message/PgpMessageBuilderTest.kt new file mode 100644 index 0000000..a37f1db --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/message/PgpMessageBuilderTest.kt @@ -0,0 +1,820 @@ +package com.fsck.k9.message + +import android.app.Activity +import android.app.PendingIntent +import android.content.Intent +import android.os.Parcelable +import com.fsck.k9.Account.QuoteStyle +import com.fsck.k9.CoreResourceProvider +import com.fsck.k9.Identity +import com.fsck.k9.K9RobolectricTest +import com.fsck.k9.activity.compose.ComposeCryptoStatus +import com.fsck.k9.activity.compose.RecipientPresenter.CryptoMode +import com.fsck.k9.activity.misc.Attachment +import com.fsck.k9.autocrypt.AutocryptOpenPgpApiInteractor +import com.fsck.k9.autocrypt.AutocryptOperations +import com.fsck.k9.autocrypt.AutocryptOperationsHelper.assertMessageHasAutocryptHeader +import com.fsck.k9.mail.Address +import com.fsck.k9.mail.BodyPart +import com.fsck.k9.mail.BoundaryGenerator +import com.fsck.k9.mail.MessagingException +import com.fsck.k9.mail.internet.BinaryTempFileBody +import com.fsck.k9.mail.internet.MessageIdGenerator +import com.fsck.k9.mail.internet.MimeMessage +import com.fsck.k9.mail.internet.MimeMultipart +import com.fsck.k9.mail.internet.MimeUtility +import com.fsck.k9.mail.internet.TextBody +import com.fsck.k9.message.MessageBuilder.Callback +import com.fsck.k9.message.quote.InsertableHtmlContent +import com.fsck.k9.view.RecipientSelectView +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.OutputStream +import java.util.Date +import org.apache.commons.io.Charsets +import org.apache.commons.io.IOUtils +import org.apache.james.mime4j.util.MimeUtil +import org.junit.Assert +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.koin.core.component.inject +import org.mockito.ArgumentCaptor +import org.mockito.ArgumentMatchers.any +import org.mockito.ArgumentMatchers.anyInt +import org.mockito.ArgumentMatchers.eq +import org.mockito.ArgumentMatchers.same +import org.mockito.Mockito.mock +import org.mockito.Mockito.spy +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoMoreInteractions +import org.mockito.Mockito.`when` +import org.mockito.kotlin.anyOrNull +import org.openintents.openpgp.OpenPgpApiManager.OpenPgpProviderState +import org.openintents.openpgp.OpenPgpError +import org.openintents.openpgp.util.OpenPgpApi +import org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.LooperMode + +@LooperMode(LooperMode.Mode.LEGACY) +class PgpMessageBuilderTest : K9RobolectricTest() { + + private val defaultCryptoStatus = ComposeCryptoStatus( + OpenPgpProviderState.OK, + TEST_KEY_ID, + emptyList<RecipientSelectView.Recipient>(), + false, + false, + false, + true, + true, + CryptoMode.NO_CHOICE + ) + private val resourceProvider: CoreResourceProvider by inject() + private val openPgpApi = mock(OpenPgpApi::class.java) + private val autocryptOpenPgpApiInteractor = mock(AutocryptOpenPgpApiInteractor::class.java) + private val pgpMessageBuilder = createDefaultPgpMessageBuilder(openPgpApi, autocryptOpenPgpApiInteractor, resourceProvider) + + @Before + @Throws(Exception::class) + fun setUp() { + BinaryTempFileBody.setTempDirectory(RuntimeEnvironment.getApplication().cacheDir) + `when`(autocryptOpenPgpApiInteractor.getKeyMaterialForKeyId(openPgpApi, TEST_KEY_ID, SENDER_EMAIL)) + .thenReturn(AUTOCRYPT_KEY_MATERIAL) + } + + @Test + @Throws(MessagingException::class) + fun build__withCryptoProviderUnconfigured__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(openPgpProviderState = OpenPgpProviderState.UNCONFIGURED) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + } + + @Test + @Throws(MessagingException::class) + fun build__withCryptoProviderUninitialized__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(openPgpProviderState = OpenPgpProviderState.UNINITIALIZED) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + } + + @Test + @Throws(MessagingException::class) + fun build__withCryptoProviderError__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(openPgpProviderState = OpenPgpProviderState.ERROR) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + } + + @Test + fun buildCleartext__withNoSigningKey__shouldBuildTrivialMessage() { + val cryptoStatus = defaultCryptoStatus.copy(openPgpKeyId = null) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + assertEquals("text/plain", message.mimeType) + } + + @Test + fun buildCleartext__shouldSucceed() { + pgpMessageBuilder.setCryptoStatus(defaultCryptoStatus) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) + assertEquals(0, message.getHeader("Autocrypt-Draft-State").size) + } + + @Test + @Throws(MessagingException::class) + fun buildSign__withNoDetachedSignatureInResult__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + `when`(openPgpApi.executeApi(any<Intent>(), any<OpenPgpDataSource>(), any<OutputStream>())).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + } + + @Test + @Throws(MessagingException::class) + fun buildSign__withDetachedSignatureInResult__shouldSucceed() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val capturedApiIntent = ArgumentCaptor.forClass(Intent::class.java) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + returnIntent.putExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE, byteArrayOf(1, 2, 3)) + `when`( + openPgpApi.executeApi( + capturedApiIntent.capture(), + any<OpenPgpDataSource>(), + anyOrNull() + ) + ).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val expectedIntent = Intent(OpenPgpApi.ACTION_DETACHED_SIGN) + expectedIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID) + expectedIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) + assertIntentEqualsActionAndExtras(expectedIntent, capturedApiIntent.value) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + Assert.assertEquals("message must be multipart/signed", "multipart/signed", message.mimeType) + + val multipart = message.body as MimeMultipart + Assert.assertEquals("multipart/signed must consist of two parts", 2, multipart.count.toLong()) + + val contentBodyPart = multipart.getBodyPart(0) + Assert.assertEquals( + "first part must have content type text/plain", + "text/plain", + MimeUtility.getHeaderParameter(contentBodyPart.contentType, null) + ) + assertTrue("signed message body must be TextBody", contentBodyPart.body is TextBody) + Assert.assertEquals(MimeUtil.ENC_QUOTED_PRINTABLE, (contentBodyPart.body as TextBody).encoding) + assertContentOfBodyPartEquals("content must match the message text", contentBodyPart, TEST_MESSAGE_TEXT) + + val signatureBodyPart = multipart.getBodyPart(1) + val contentType = signatureBodyPart.contentType + Assert.assertEquals( + "second part must be pgp signature", + "application/pgp-signature", + MimeUtility.getHeaderParameter(contentType, null) + ) + Assert.assertEquals( + "second part must be called signature.asc", + "signature.asc", + MimeUtility.getHeaderParameter(contentType, "name") + ) + assertContentOfBodyPartEquals( + "content must match the supplied detached signature", + signatureBodyPart, + byteArrayOf(1, 2, 3) + ) + + assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) + } + + @Test + @Throws(MessagingException::class) + fun buildSign__withUserInteractionResult__shouldReturnUserInteraction() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val returnIntent = mock(Intent::class.java) + `when`(returnIntent.getIntExtra(eq(OpenPgpApi.RESULT_CODE), anyInt())) + .thenReturn(OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED) + val mockPendingIntent = mock(PendingIntent::class.java) + `when`<Parcelable>(returnIntent.getParcelableExtra<Parcelable>(eq(OpenPgpApi.RESULT_INTENT))) + .thenReturn(mockPendingIntent) + + `when`(openPgpApi.executeApi(any<Intent>(), any<OpenPgpDataSource>(), any<OutputStream>())).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val captor = ArgumentCaptor.forClass(PendingIntent::class.java) + verify(mockCallback).onMessageBuildReturnPendingIntent(captor.capture(), anyInt()) + verifyNoMoreInteractions(mockCallback) + + val pendingIntent = captor.value + Assert.assertSame(pendingIntent, mockPendingIntent) + } + + @Test + @Throws(MessagingException::class) + fun buildSign__withReturnAfterUserInteraction__shouldSucceed() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + var returnedRequestCode = 0 + run { + val returnIntent = spy(Intent()) + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED) + + val mockPendingIntent = mock(PendingIntent::class.java) + `when`<Parcelable>(returnIntent.getParcelableExtra<Parcelable>(eq(OpenPgpApi.RESULT_INTENT))) + .thenReturn(mockPendingIntent) + + `when`(openPgpApi.executeApi(any<Intent>(), any<OpenPgpDataSource>(), any<OutputStream>())).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(returnIntent).getIntExtra(eq(OpenPgpApi.RESULT_CODE), anyInt()) + val piCaptor = ArgumentCaptor.forClass(PendingIntent::class.java) + val rcCaptor = ArgumentCaptor.forClass(Int::class.java) + verify(mockCallback).onMessageBuildReturnPendingIntent(piCaptor.capture(), rcCaptor.capture()) + verifyNoMoreInteractions(mockCallback) + + returnedRequestCode = rcCaptor.value + Assert.assertSame(mockPendingIntent, piCaptor.value) + } + + run { + val returnIntent = spy(Intent()) + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + + val mockReturnIntent = mock(Intent::class.java) + `when`(openPgpApi.executeApi(any<Intent>(), any<OpenPgpDataSource>(), any<OutputStream>())).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.onActivityResult(returnedRequestCode, Activity.RESULT_OK, mockReturnIntent, mockCallback) + verify(openPgpApi).executeApi(same(mockReturnIntent), any<OpenPgpDataSource>(), any<OutputStream>()) + verify(returnIntent).getIntExtra(eq(OpenPgpApi.RESULT_CODE), anyInt()) + } + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__withoutRecipients__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.CHOICE_ENABLED) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val returnIntent = spy(Intent()) + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + `when`(openPgpApi.executeApi(any(Intent::class.java), any(OpenPgpDataSource::class.java), any(OutputStream::class.java))) + .thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__draftWithoutRecipients() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.CHOICE_ENABLED) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.isDraft = true + + buildMessage() + } + + @Test + @Throws(MessagingException::class) + fun buildDraft() { + pgpMessageBuilder.setCryptoStatus(defaultCryptoStatus) + pgpMessageBuilder.isDraft = true + + val mimeMessage = buildMessage() + + assertEquals("encrypt=no; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) + } + + @Test + @Throws(MessagingException::class) + fun buildDraft_replyToEncrypted() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.NO_CHOICE, + isReplyToEncrypted = true + ) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.isDraft = true + + val mimeMessage = buildMessage() + + assertEquals("encrypt=yes; _is-reply-to-encrypted=yes; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) + } + + @Test + @Throws(MessagingException::class) + fun buildDraft_encrypt() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.CHOICE_ENABLED) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.isDraft = true + + val mimeMessage = buildMessage() + + assertEquals("encrypt=yes; _by-choice=yes; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) + } + + @Test + @Throws(MessagingException::class) + fun buildDraft_sign() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.isDraft = true + + val mimeMessage = buildMessage() + + assertEquals("encrypt=no; _sign-only=yes; _by-choice=yes; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) + } + + private fun buildMessage(): MimeMessage { + val returnIntent = spy(Intent()) + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + `when`(openPgpApi.executeApi(any(Intent::class.java), any(OpenPgpDataSource::class.java), any(OutputStream::class.java))) + .thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val mimeMessageCaptor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(mimeMessageCaptor.capture(), eq(true)) + verifyNoMoreInteractions(mockCallback) + + assertNotNull(mimeMessageCaptor.value) + return mimeMessageCaptor.value + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__checkGossip() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.CHOICE_ENABLED, + recipientAddresses = listOf("alice@example.org", "bob@example.org") + ) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + `when`(openPgpApi.executeApi(any(Intent::class.java), any(OpenPgpDataSource::class.java), any(OutputStream::class.java))) + .thenReturn(returnIntent) + pgpMessageBuilder.buildAsync(mock(Callback::class.java)) + + verify(autocryptOpenPgpApiInteractor).getKeyMaterialForUserId(same(openPgpApi), eq("alice@example.org")) + verify(autocryptOpenPgpApiInteractor).getKeyMaterialForUserId(same(openPgpApi), eq("bob@example.org")) + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__checkGossip__filterBcc() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.CHOICE_ENABLED, + recipientAddresses = listOf("alice@example.org", "bob@example.org", "carol@example.org") + ) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.setBcc(listOf(Address("carol@example.org"))) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + `when`(openPgpApi.executeApi(any(Intent::class.java), any(OpenPgpDataSource::class.java), any(OutputStream::class.java))) + .thenReturn(returnIntent) + pgpMessageBuilder.buildAsync(mock(Callback::class.java)) + + verify(autocryptOpenPgpApiInteractor).getKeyMaterialForKeyId(same(openPgpApi), eq(TEST_KEY_ID), eq(SENDER_EMAIL)) + verify(autocryptOpenPgpApiInteractor).getKeyMaterialForUserId(same(openPgpApi), eq("alice@example.org")) + verify(autocryptOpenPgpApiInteractor).getKeyMaterialForUserId(same(openPgpApi), eq("bob@example.org")) + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__checkGossip__filterBccSingleRecipient() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.CHOICE_ENABLED, + isPgpInlineModeEnabled = true, + recipientAddresses = listOf("alice@example.org", "carol@example.org") + ) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.setBcc(listOf(Address("carol@example.org"))) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + `when`(openPgpApi.executeApi(any(Intent::class.java), any(OpenPgpDataSource::class.java), any(OutputStream::class.java))) + .thenReturn(returnIntent) + pgpMessageBuilder.buildAsync(mock(Callback::class.java)) + + verify(autocryptOpenPgpApiInteractor).getKeyMaterialForKeyId(any(OpenPgpApi::class.java), any(Long::class.java), any(String::class.java)) + verifyNoMoreInteractions(autocryptOpenPgpApiInteractor) + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__shouldSucceed() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.CHOICE_ENABLED, + recipientAddresses = listOf("test@example.org") + ) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val capturedApiIntent = ArgumentCaptor.forClass(Intent::class.java) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + + `when`( + openPgpApi.executeApi( + capturedApiIntent.capture(), + any(OpenPgpDataSource::class.java), + any(OutputStream::class.java) + ) + ).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val expectedApiIntent = Intent(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longArrayOf(TEST_KEY_ID)) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.recipientAddressesAsArray) + assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.value) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + + Assert.assertEquals("message must be multipart/encrypted", "multipart/encrypted", message.mimeType) + + val multipart = message.body as MimeMultipart + Assert.assertEquals("multipart/encrypted must consist of two parts", 2, multipart.count.toLong()) + + val dummyBodyPart = multipart.getBodyPart(0) + Assert.assertEquals( + "first part must be pgp encrypted dummy part", + "application/pgp-encrypted", + dummyBodyPart.contentType + ) + assertContentOfBodyPartEquals( + "content must match the supplied detached signature", + dummyBodyPart, + "Version: 1" + ) + + val encryptedBodyPart = multipart.getBodyPart(1) + Assert.assertEquals( + "second part must be octet-stream of encrypted data", + "application/octet-stream; name=\"encrypted.asc\"", + encryptedBodyPart.contentType + ) + assertTrue( + "message body must be BinaryTempFileBody", + encryptedBodyPart.body is BinaryTempFileBody + ) + Assert.assertEquals(MimeUtil.ENC_7BIT, (encryptedBodyPart.body as BinaryTempFileBody).encoding) + + assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) + } + + @Test + @Throws(MessagingException::class) + fun buildEncrypt__withInlineEnabled__shouldSucceed() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.CHOICE_ENABLED, + isPgpInlineModeEnabled = true, + recipientAddresses = listOf("test@example.org") + ) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val capturedApiIntent = ArgumentCaptor.forClass(Intent::class.java) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + + `when`( + openPgpApi.executeApi( + capturedApiIntent.capture(), + any(OpenPgpDataSource::class.java), + any(OutputStream::class.java) + ) + ).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val expectedApiIntent = Intent(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longArrayOf(TEST_KEY_ID)) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.recipientAddressesAsArray) + assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.value) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + Assert.assertEquals("text/plain", message.mimeType) + assertTrue("message body must be BinaryTempFileBody", message.body is BinaryTempFileBody) + Assert.assertEquals(MimeUtil.ENC_7BIT, (message.body as BinaryTempFileBody).encoding) + + assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) + } + + @Test + @Throws(MessagingException::class) + fun buildSign__withInlineEnabled__shouldSucceed() { + val cryptoStatus = defaultCryptoStatus.copy( + cryptoMode = CryptoMode.SIGN_ONLY, + isPgpInlineModeEnabled = true, + recipientAddresses = listOf("test@example.org") + ) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val capturedApiIntent = ArgumentCaptor.forClass(Intent::class.java) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + + `when`( + openPgpApi.executeApi( + capturedApiIntent.capture(), + any(OpenPgpDataSource::class.java), + any(OutputStream::class.java) + ) + ).thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val expectedApiIntent = Intent(OpenPgpApi.ACTION_SIGN) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID) + expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) + assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.value) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + Assert.assertEquals("message must be text/plain", "text/plain", message.mimeType) + + assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) + } + + @Test + @Throws(MessagingException::class) + fun buildSignWithAttach__withInlineEnabled__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY, isPgpInlineModeEnabled = true) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.setAttachments(listOf(Attachment.createAttachment(null, 0, null, true, true))) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + verifyNoMoreInteractions(openPgpApi) + } + + @Test + @Throws(MessagingException::class) + fun buildEncryptWithAttach__withInlineEnabled__shouldThrow() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.CHOICE_ENABLED, isPgpInlineModeEnabled = true) + + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + pgpMessageBuilder.setAttachments(listOf(Attachment.createAttachment(null, 0, null, true, true))) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + verifyNoMoreInteractions(openPgpApi) + } + + @Test + @Throws(MessagingException::class) + fun buildOpportunisticEncrypt__withNoKeysAndNoSignOnly__shouldNotBeSigned() { + val cryptoStatus = defaultCryptoStatus.copy(recipientAddresses = listOf("test@example.org")) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val returnIntent = Intent() + returnIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR) + returnIntent.putExtra( + OpenPgpApi.RESULT_ERROR, + OpenPgpError(OpenPgpError.OPPORTUNISTIC_MISSING_KEYS, "Missing keys") + ) + + `when`(openPgpApi.executeApi(any(Intent::class.java), any(OpenPgpDataSource::class.java), any(OutputStream::class.java))) + .thenReturn(returnIntent) + + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + val captor = ArgumentCaptor.forClass(MimeMessage::class.java) + verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) + verifyNoMoreInteractions(mockCallback) + + val message = captor.value + Assert.assertEquals("text/plain", message.mimeType) + } + + @Test + @Throws(MessagingException::class) + fun buildSign__withNoDetachedSignatureExtra__shouldFail() { + val cryptoStatus = defaultCryptoStatus.copy(cryptoMode = CryptoMode.SIGN_ONLY) + pgpMessageBuilder.setCryptoStatus(cryptoStatus) + + val returnIntentSigned = Intent() + returnIntentSigned.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS) + // no OpenPgpApi.EXTRA_DETACHED_SIGNATURE! + + `when`(openPgpApi.executeApi(any<Intent>(), any<OpenPgpDataSource>(), any<OutputStream>())).thenReturn(returnIntentSigned) + val mockCallback = mock(Callback::class.java) + pgpMessageBuilder.buildAsync(mockCallback) + + verify(mockCallback).onMessageBuildException(any<MessagingException>()) + verifyNoMoreInteractions(mockCallback) + } + + companion object { + private const val TEST_KEY_ID = 123L + private const val TEST_MESSAGE_TEXT = "message text with a ☭ CCCP symbol" + private val AUTOCRYPT_KEY_MATERIAL = byteArrayOf(1, 2, 3) + private const val SENDER_EMAIL = "test@example.org" + + private fun createDefaultPgpMessageBuilder( + openPgpApi: OpenPgpApi, + autocryptOpenPgpApiInteractor: AutocryptOpenPgpApiInteractor, + resourceProvider: CoreResourceProvider + ): PgpMessageBuilder { + val builder = PgpMessageBuilder( + MessageIdGenerator.getInstance(), + BoundaryGenerator.getInstance(), + AutocryptOperations.getInstance(), + autocryptOpenPgpApiInteractor, + resourceProvider + ) + builder.setOpenPgpApi(openPgpApi) + + val identity = Identity( + name = "tester", + email = SENDER_EMAIL, + description = "test identity", + signatureUse = false + ) + + builder.setSubject("subject") + .setSentDate(Date()) + .setHideTimeZone(false) + .setTo(ArrayList()) + .setCc(ArrayList()) + .setBcc(ArrayList()) + .setInReplyTo("inreplyto") + .setReferences("references") + .setRequestReadReceipt(false) + .setIdentity(identity) + .setMessageFormat(SimpleMessageFormat.TEXT) + .setText(TEST_MESSAGE_TEXT) + .setAttachments(ArrayList()) + .setSignature("signature") + .setQuoteStyle(QuoteStyle.PREFIX) + .setQuotedTextMode(QuotedTextMode.NONE) + .setQuotedText("quoted text") + .setQuotedHtmlContent(InsertableHtmlContent()) + .setReplyAfterQuote(false) + .setSignatureBeforeQuotedText(false) + .setIdentityChanged(false) + .setSignatureChanged(false) + .setCursorPosition(0) + .setMessageReference(null).isDraft = false + + return builder + } + + private fun assertContentOfBodyPartEquals(reason: String, signatureBodyPart: BodyPart, expected: ByteArray) { + try { + val bos = ByteArrayOutputStream() + signatureBodyPart.body.writeTo(bos) + Assert.assertArrayEquals(reason, expected, bos.toByteArray()) + } catch (e: IOException) { + Assert.fail() + } catch (e: MessagingException) { + Assert.fail() + } + } + + private fun assertContentOfBodyPartEquals(reason: String, signatureBodyPart: BodyPart, expected: String) { + try { + val bos = ByteArrayOutputStream() + val inputStream = MimeUtility.decodeBody(signatureBodyPart.body) + IOUtils.copy(inputStream, bos) + Assert.assertEquals(reason, expected, String(bos.toByteArray(), Charsets.UTF_8)) + } catch (e: IOException) { + Assert.fail() + } catch (e: MessagingException) { + Assert.fail() + } + } + + private fun assertIntentEqualsActionAndExtras(expected: Intent, actual: Intent) { + Assert.assertEquals(expected.action, actual.action) + + val expectedExtras = expected.extras + val intentExtras = actual.extras + + if (expectedExtras!!.size() != intentExtras!!.size()) { + Assert.assertEquals(expectedExtras.size().toLong(), intentExtras.size().toLong()) + } + + for (key in expectedExtras.keySet()) { + val intentExtra = intentExtras.get(key) + val expectedExtra = expectedExtras.get(key) + if (intentExtra == null) { + if (expectedExtra == null) { + continue + } + Assert.fail("found null for an expected non-null extra: $key") + } + if (intentExtra is LongArray) { + Assert.assertArrayEquals("error in $key", expectedExtra as LongArray, intentExtra) + } else if (intentExtra is Array<*>) { + Assert.assertArrayEquals("error in $key", expectedExtra as Array<*>, intentExtra) + } else { + if (intentExtra != expectedExtra) { + Assert.assertEquals("error in $key", expectedExtra, intentExtra) + } + } + } + } + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/K9DrawerTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/K9DrawerTest.kt new file mode 100644 index 0000000..7db67cb --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/K9DrawerTest.kt @@ -0,0 +1,19 @@ +package com.fsck.k9.ui + +import com.fsck.k9.RobolectricTest +import com.fsck.k9.core.R +import org.junit.Assert.assertEquals +import org.junit.Test +import org.robolectric.RuntimeEnvironment + +class K9DrawerTest : RobolectricTest() { + @Test + fun testAccountColorLengthEqualsDrawerColorLength() { + val resources = RuntimeEnvironment.getApplication().resources + + val lightColors = resources.getIntArray(R.array.account_colors) + val darkColors = resources.getIntArray(R.array.drawer_account_accent_color_dark_theme) + + assertEquals(lightColors.size, darkColors.size) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/crypto/MessageCryptoHelperTest.java b/app/ui/legacy/src/test/java/com/fsck/k9/ui/crypto/MessageCryptoHelperTest.java new file mode 100644 index 0000000..42b3d36 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/crypto/MessageCryptoHelperTest.java @@ -0,0 +1,340 @@ +package com.fsck.k9.ui.crypto; + + +import java.io.InputStream; +import java.io.OutputStream; + +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; + +import com.fsck.k9.RobolectricTest; +import com.fsck.k9.autocrypt.AutocryptOperations; +import com.fsck.k9.mail.Address; +import com.fsck.k9.mail.Body; +import com.fsck.k9.mail.BodyPart; +import com.fsck.k9.mail.Message; +import com.fsck.k9.mail.internet.MimeBodyPart; +import com.fsck.k9.mail.internet.MimeMessage; +import com.fsck.k9.mail.internet.TextBody; +import com.fsck.k9.mailstore.CryptoResultAnnotation; +import com.fsck.k9.mailstore.CryptoResultAnnotation.CryptoError; +import com.fsck.k9.mailstore.MessageCryptoAnnotations; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.openintents.openpgp.IOpenPgpService2; +import org.openintents.openpgp.OpenPgpDecryptionResult; +import org.openintents.openpgp.OpenPgpSignatureResult; +import org.openintents.openpgp.util.OpenPgpApi; +import org.openintents.openpgp.util.OpenPgpApi.IOpenPgpCallback; +import org.openintents.openpgp.util.OpenPgpApi.IOpenPgpSinkResultCallback; +import org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSink; +import org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.annotation.LooperMode; + +import static com.fsck.k9.mail.TestMessageConstructionUtils.bodypart; +import static com.fsck.k9.mail.TestMessageConstructionUtils.messageFromBody; +import static com.fsck.k9.mail.TestMessageConstructionUtils.multipart; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertSame; +import static junit.framework.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + + +@SuppressWarnings("unchecked") +@LooperMode(LooperMode.Mode.LEGACY) +public class MessageCryptoHelperTest extends RobolectricTest { + private MessageCryptoHelper messageCryptoHelper; + private OpenPgpApi openPgpApi; + private Intent capturedApiIntent; + private IOpenPgpSinkResultCallback capturedCallback; + private MessageCryptoCallback messageCryptoCallback; + private AutocryptOperations autocryptOperations; + + + @Before + public void setUp() throws Exception { + openPgpApi = mock(OpenPgpApi.class); + autocryptOperations = mock(AutocryptOperations.class); + + OpenPgpApiFactory openPgpApiFactory = mock(OpenPgpApiFactory.class); + when(openPgpApiFactory.createOpenPgpApi(any(Context.class), nullable(IOpenPgpService2.class))) + .thenReturn(openPgpApi); + + messageCryptoHelper = new MessageCryptoHelper(RuntimeEnvironment.getApplication(), openPgpApiFactory, + autocryptOperations, "org.example.dummy"); + messageCryptoCallback = mock(MessageCryptoCallback.class); + } + + @Test + public void textPlain() throws Exception { + MimeMessage message = new MimeMessage(); + message.setUid("msguid"); + message.setHeader("Content-Type", "text/plain"); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); + verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); + MessageCryptoAnnotations annotations = captor.getValue(); + assertTrue(annotations.isEmpty()); + verifyNoMoreInteractions(messageCryptoCallback); + + verify(autocryptOperations).hasAutocryptHeader(message); + verifyNoMoreInteractions(autocryptOperations); + } + + @Test + public void textPlain_withAutocrypt() throws Exception { + MimeMessage message = new MimeMessage(); + message.setUid("msguid"); + message.setHeader("Content-Type", "text/plain"); + + when(autocryptOperations.hasAutocryptHeader(message)).thenReturn(true); + when(autocryptOperations.addAutocryptPeerUpdateToIntentIfPresent(same(message), any(Intent.class))).thenReturn(true); + + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + + ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); + verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); + MessageCryptoAnnotations annotations = captor.getValue(); + assertTrue(annotations.isEmpty()); + verifyNoMoreInteractions(messageCryptoCallback); + + ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); + verify(autocryptOperations).addAutocryptPeerUpdateToIntentIfPresent(same(message), intentCaptor.capture()); + verify(openPgpApi).executeApiAsync(same(intentCaptor.getValue()), same((InputStream) null), + same((OutputStream) null), any(IOpenPgpCallback.class)); + } + + @Test + public void multipartSigned__withNullBody__shouldReturnSignedIncomplete() throws Exception { + Message message = messageFromBody( + multipart("signed", "protocol=\"application/pgp-signature\"", + bodypart("text/plain"), + bodypart("application/pgp-signature") + ) + ); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, true); + + assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.OPENPGP_SIGNED_BUT_INCOMPLETE, null, + null, null, null); + } + + @Test + public void multipartEncrypted__withNullBody__shouldReturnEncryptedIncomplete() throws Exception { + Message message = messageFromBody( + multipart("encrypted", "protocol=\"application/pgp-encrypted\"", + bodypart("application/pgp-encrypted"), + bodypart("application/octet-stream") + ) + ); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + assertPartAnnotationHasState( + message, messageCryptoCallback, CryptoError.OPENPGP_ENCRYPTED_BUT_INCOMPLETE, null, null, null, null); + } + + @Test + public void multipartEncrypted__withUnknownProtocol__shouldReturnEncryptedUnsupported() throws Exception { + Message message = messageFromBody( + multipart("encrypted", "protocol=\"application/bad-protocol\"", + bodypart("application/bad-protocol", "content"), + bodypart("application/octet-stream", "content") + ) + ); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.ENCRYPTED_BUT_UNSUPPORTED, null, null, + null, null); + } + + @Test + public void multipartSigned__withUnknownProtocol__shouldReturnSignedUnsupported() throws Exception { + Message message = messageFromBody( + multipart("signed", "protocol=\"application/bad-protocol\"", + bodypart("text/plain", "content"), + bodypart("application/bad-protocol", "content") + ) + ); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, true); + + assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.SIGNED_BUT_UNSUPPORTED, null, null, + null, null); + } + + @Test + public void multipartSigned__shouldCallOpenPgpApiAsync() throws Exception { + BodyPart signedBodyPart = spy(bodypart("text/plain", "content")); + Message message = messageFromBody( + multipart("signed", "protocol=\"application/pgp-signature\"", + signedBodyPart, + bodypart("application/pgp-signature", "content") + ) + ); + message.setFrom(Address.parse("Test <test@example.org>")[0]); + + OutputStream outputStream = mock(OutputStream.class); + + + processSignedMessageAndCaptureMocks(message, signedBodyPart, outputStream); + + + assertEquals(OpenPgpApi.ACTION_DECRYPT_VERIFY, capturedApiIntent.getAction()); + assertEquals("test@example.org", capturedApiIntent.getStringExtra(OpenPgpApi.EXTRA_SENDER_ADDRESS)); + + verify(autocryptOperations).addAutocryptPeerUpdateToIntentIfPresent(message, capturedApiIntent); + verifyNoMoreInteractions(autocryptOperations); + } + + @Test + public void multipartSigned__withSignOnlyDisabled__shouldReturnNothing() throws Exception { + Message message = messageFromBody( + multipart("signed", "protocol=\"application/pgp-signature\"", + bodypart("text/plain", "content"), + bodypart("application/pgp-signature", "content") + ) + ); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); + } + + @Test + public void multipartSigned__withSignOnlyDisabledAndNullBody__shouldReturnNothing() throws Exception { + Message message = messageFromBody( + multipart("signed", "protocol=\"application/pgp-signature\"", + bodypart("text/plain"), + bodypart("application/pgp-signature") + ) + ); + + MessageCryptoCallback messageCryptoCallback = mock(MessageCryptoCallback.class); + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + assertReturnsWithNoCryptoAnnotations(messageCryptoCallback); + } + + @Test + public void multipartEncrypted__shouldCallOpenPgpApiAsync() throws Exception { + Body encryptedBody = spy(new TextBody("encrypted data")); + Message message = messageFromBody( + multipart("encrypted", "protocol=\"application/pgp-encrypted\"", + bodypart("application/pgp-encrypted", "content"), + bodypart("application/octet-stream", encryptedBody) + ) + ); + message.setFrom(Address.parse("Test <test@example.org>")[0]); + + OutputStream outputStream = mock(OutputStream.class); + + Intent resultIntent = new Intent(); + resultIntent.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS); + OpenPgpDecryptionResult decryptionResult = mock(OpenPgpDecryptionResult.class); + resultIntent.putExtra(OpenPgpApi.RESULT_DECRYPTION, decryptionResult); + OpenPgpSignatureResult signatureResult = mock(OpenPgpSignatureResult.class); + resultIntent.putExtra(OpenPgpApi.RESULT_SIGNATURE, signatureResult); + PendingIntent pendingIntent = mock(PendingIntent.class); + resultIntent.putExtra(OpenPgpApi.RESULT_INTENT, pendingIntent); + + + processEncryptedMessageAndCaptureMocks(message, encryptedBody, outputStream); + + MimeBodyPart decryptedPart = new MimeBodyPart(new TextBody("text")); + capturedCallback.onReturn(resultIntent, decryptedPart); + + + assertEquals(OpenPgpApi.ACTION_DECRYPT_VERIFY, capturedApiIntent.getAction()); + assertEquals("test@example.org", capturedApiIntent.getStringExtra(OpenPgpApi.EXTRA_SENDER_ADDRESS)); + assertPartAnnotationHasState(message, messageCryptoCallback, CryptoError.OPENPGP_OK, decryptedPart, + decryptionResult, signatureResult, pendingIntent); + verify(autocryptOperations).addAutocryptPeerUpdateToIntentIfPresent(message, capturedApiIntent); + verifyNoMoreInteractions(autocryptOperations); + } + + private void processEncryptedMessageAndCaptureMocks(Message message, Body encryptedBody, OutputStream outputStream) + throws Exception { + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, false); + + ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); + ArgumentCaptor<OpenPgpDataSource> dataSourceCaptor = ArgumentCaptor.forClass(OpenPgpDataSource.class); + ArgumentCaptor<IOpenPgpSinkResultCallback> callbackCaptor = ArgumentCaptor.forClass(IOpenPgpSinkResultCallback.class); + verify(openPgpApi).executeApiAsync(intentCaptor.capture(), dataSourceCaptor.capture(), + any(OpenPgpDataSink.class), callbackCaptor.capture()); + + capturedApiIntent = intentCaptor.getValue(); + capturedCallback = callbackCaptor.getValue(); + + OpenPgpDataSource dataSource = dataSourceCaptor.getValue(); + dataSource.writeTo(outputStream); + verify(encryptedBody).writeTo(outputStream); + } + + private void processSignedMessageAndCaptureMocks(Message message, BodyPart signedBodyPart, + OutputStream outputStream) throws Exception { + messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback, null, true); + + ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); + ArgumentCaptor<OpenPgpDataSource> dataSourceCaptor = ArgumentCaptor.forClass(OpenPgpDataSource.class); + ArgumentCaptor<IOpenPgpSinkResultCallback> callbackCaptor = ArgumentCaptor.forClass(IOpenPgpSinkResultCallback.class); + verify(openPgpApi).executeApiAsync(intentCaptor.capture(), dataSourceCaptor.capture(), + callbackCaptor.capture()); + + capturedApiIntent = intentCaptor.getValue(); + capturedCallback = callbackCaptor.getValue(); + + OpenPgpDataSource dataSource = dataSourceCaptor.getValue(); + dataSource.writeTo(outputStream); + verify(signedBodyPart).writeTo(outputStream); + } + + private void assertReturnsWithNoCryptoAnnotations(MessageCryptoCallback messageCryptoCallback) { + ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); + verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); + verifyNoMoreInteractions(messageCryptoCallback); + + MessageCryptoAnnotations annotations = captor.getValue(); + assertTrue(annotations.isEmpty()); + } + + private void assertPartAnnotationHasState(Message message, MessageCryptoCallback messageCryptoCallback, + CryptoError cryptoErrorState, MimeBodyPart replacementPart, OpenPgpDecryptionResult openPgpDecryptionResult, + OpenPgpSignatureResult openPgpSignatureResult, PendingIntent openPgpPendingIntent) { + ArgumentCaptor<MessageCryptoAnnotations> captor = ArgumentCaptor.forClass(MessageCryptoAnnotations.class); + verify(messageCryptoCallback).onCryptoOperationsFinished(captor.capture()); + MessageCryptoAnnotations annotations = captor.getValue(); + CryptoResultAnnotation cryptoResultAnnotation = annotations.get(message); + assertEquals(cryptoErrorState, cryptoResultAnnotation.getErrorType()); + if (replacementPart != null) { + assertSame(replacementPart, cryptoResultAnnotation.getReplacementData()); + } + assertSame(openPgpDecryptionResult, cryptoResultAnnotation.getOpenPgpDecryptionResult()); + assertSame(openPgpSignatureResult, cryptoResultAnnotation.getOpenPgpSignatureResult()); + assertSame(openPgpPendingIntent, cryptoResultAnnotation.getOpenPgpPendingIntent()); + verifyNoMoreInteractions(messageCryptoCallback); + } + +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/helper/RelativeDateTimeFormatterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/helper/RelativeDateTimeFormatterTest.kt new file mode 100644 index 0000000..a85b9d4 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/helper/RelativeDateTimeFormatterTest.kt @@ -0,0 +1,131 @@ +package com.fsck.k9.ui.helper + +import android.os.SystemClock +import app.k9mail.core.testing.TestClock +import com.fsck.k9.RobolectricTest +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import java.util.TimeZone +import kotlinx.datetime.Instant +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@Config(qualifiers = "en") +class RelativeDateTimeFormatterTest : RobolectricTest() { + + private val context = RuntimeEnvironment.getApplication().applicationContext + private val clock = TestClock() + private val dateTimeFormatter = RelativeDateTimeFormatter(context, clock) + + private val zoneId = "Europe/Berlin" + + @Before + fun setUp() { + TimeZone.setDefault(TimeZone.getTimeZone(zoneId)) + } + + @Test + fun inFiveMinutesOnNextDay_shouldReturnDay() { + setClockTo("2020-05-17T23:58") + val date = "2020-05-18T00:03".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("May 18", displayDate) + } + + @Test + fun oneMinuteAgo_shouldReturnTime() { + setClockTo("2020-05-17T15:42") + val date = "2020-05-17T15:41".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("3:41 PM", displayDate) + } + + @Test + fun sixHoursAgo_shouldReturnTime() { + setClockTo("2020-05-17T15:42") + val date = "2020-05-17T09:42".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("9:42 AM", displayDate) + } + + @Test + fun yesterday_shouldReturnWeekday() { + setClockTo("2020-05-17T15:42") + val date = "2020-05-16T15:42".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("Sat", displayDate) + } + + @Test + fun sixDaysAgo_shouldReturnWeekday() { + setClockTo("2020-05-17T15:42") + val date = "2020-05-11T09:42".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("Mon", displayDate) + } + + @Test + fun sixDaysAndTwentyHours_shouldReturnDay() { + setClockTo("2020-05-17T15:42") + val date = "2020-05-10T17:42".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("May 10", displayDate) + } + + @Test + fun sevenDaysAndTwoHours_shouldReturnDay() { + setClockTo("2020-05-17T15:42") + val date = "2020-05-10T13:42".toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("May 10", displayDate) + } + + @Test + fun startOfYear_shouldReturnDay() { + setClockTo("2020-05-17T15:42") + val date = LocalDate.parse("2020-01-01").atStartOfDay().toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("Jan 1", displayDate) + } + + @Test + fun endOfLastYear_shouldReturnDate() { + setClockTo("2020-05-17T15:42") + val date = LocalDateTime.parse("2019-12-31T23:59").toEpochMillis() + + val displayDate = dateTimeFormatter.formatDate(date) + + assertEquals("12/31/2019", displayDate) + } + + private fun setClockTo(time: String) { + val dateTime = LocalDateTime.parse(time) + val timeInMillis = dateTime.toEpochMillis() + SystemClock.setCurrentTimeMillis(timeInMillis) // Is handled by ShadowSystemClock + clock.changeTimeTo(Instant.fromEpochMilliseconds(timeInMillis)) + } + + private fun String.toEpochMillis() = LocalDateTime.parse(this).toEpochMillis() + + private fun LocalDateTime.toEpochMillis() = this.atZone(ZoneId.of(zoneId)).toInstant().toEpochMilli() +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/helper/SizeFormatterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/helper/SizeFormatterTest.kt new file mode 100644 index 0000000..9af9595 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/helper/SizeFormatterTest.kt @@ -0,0 +1,57 @@ +package com.fsck.k9.ui.helper + +import com.fsck.k9.RobolectricTest +import org.junit.Assert.assertEquals +import org.junit.Test +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@Config(qualifiers = "en") +class SizeFormatterTest : RobolectricTest() { + private val sizeFormatter = SizeFormatter(RuntimeEnvironment.getApplication().resources) + + @Test + fun bytes_lower_bound() { + assertEquals("0 B", sizeFormatter.formatSize(0)) + } + + @Test + fun bytes_upper_bound() { + assertEquals("999 B", sizeFormatter.formatSize(999)) + } + + @Test + fun kilobytes_lower_bound() { + assertEquals("1.0 kB", sizeFormatter.formatSize(1000)) + } + + @Test + fun kilobytes_upper_bound() { + assertEquals("999.9 kB", sizeFormatter.formatSize(999_949)) + } + + @Test + fun megabytes_lower_bound() { + assertEquals("1.0 MB", sizeFormatter.formatSize(999_950)) + } + + @Test + fun megabytes_upper_bound() { + assertEquals("999.9 MB", sizeFormatter.formatSize(999_949_999)) + } + + @Test + fun gigabytes_lower_bound() { + assertEquals("1.0 GB", sizeFormatter.formatSize(999_950_000)) + } + + @Test + fun gigabytes_2() { + assertEquals("2.0 GB", sizeFormatter.formatSize(2_000_000_000L)) + } + + @Test + fun gigabytes_2000() { + assertEquals("2000.0 GB", sizeFormatter.formatSize(2_000_000_000_000L)) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/identity/IdentityFormatterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/identity/IdentityFormatterTest.kt new file mode 100644 index 0000000..7d8d0d6 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/identity/IdentityFormatterTest.kt @@ -0,0 +1,68 @@ +package com.fsck.k9.ui.identity + +import assertk.assertThat +import assertk.assertions.isEqualTo +import com.fsck.k9.Identity +import org.junit.Test + +private const val IDENTITY_NAME = "Identity Name" +private const val SENDER_NAME = "Display Name" +private const val EMAIL = "test@domain.example" + +class IdentityFormatterTest { + private val identityFormatter = IdentityFormatter() + + @Test + fun `getDisplayName() with identity name`() { + val identity = Identity(description = IDENTITY_NAME, name = "irrelevant", email = EMAIL) + + val displayName = identityFormatter.getDisplayName(identity) + + assertThat(displayName).isEqualTo(IDENTITY_NAME) + } + + @Test + fun `getDisplayName() without identity name, but sender name`() { + val identity = Identity(description = null, name = SENDER_NAME, email = EMAIL) + + val displayName = identityFormatter.getDisplayName(identity) + + assertThat(displayName).isEqualTo("$SENDER_NAME <$EMAIL>") + } + + @Test + fun `getDisplayName() without identity name and sender name`() { + val identity = Identity(description = null, name = null, email = EMAIL) + + val displayName = identityFormatter.getDisplayName(identity) + + assertThat(displayName).isEqualTo(EMAIL) + } + + @Test + fun `getEmailDisplayName() with sender name`() { + val identity = Identity(name = SENDER_NAME, email = EMAIL) + + val displayName = identityFormatter.getEmailDisplayName(identity) + + assertThat(displayName).isEqualTo("$SENDER_NAME <$EMAIL>") + } + + @Test + fun `getEmailDisplayName() without sender name`() { + val identity = Identity(name = null, email = EMAIL) + + val displayName = identityFormatter.getEmailDisplayName(identity) + + assertThat(displayName).isEqualTo(EMAIL) + } + + @Test + fun `getEmailDisplayName() should ignore identity name`() { + val identity = Identity(description = IDENTITY_NAME, name = null, email = EMAIL) + + val displayName = identityFormatter.getEmailDisplayName(identity) + + assertThat(displayName).isEqualTo(EMAIL) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/messagedetails/MessageDetailsParticipantFormatterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messagedetails/MessageDetailsParticipantFormatterTest.kt new file mode 100644 index 0000000..e54b3bb --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messagedetails/MessageDetailsParticipantFormatterTest.kt @@ -0,0 +1,128 @@ +package com.fsck.k9.ui.messagedetails + +import android.graphics.Color +import android.text.Spannable +import android.text.style.ForegroundColorSpan +import androidx.core.text.getSpans +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEqualTo +import assertk.assertions.isInstanceOf +import assertk.assertions.isNotNull +import assertk.assertions.isNull +import com.fsck.k9.Account +import com.fsck.k9.Identity +import com.fsck.k9.RobolectricTest +import com.fsck.k9.helper.ContactNameProvider +import com.fsck.k9.mail.Address +import org.junit.Test + +private const val IDENTITY_NAME = "Alice" +private const val IDENTITY_ADDRESS = "me@domain.example" + +class MessageDetailsParticipantFormatterTest : RobolectricTest() { + private val contactNameProvider = object : ContactNameProvider { + override fun getNameForAddress(address: String): String? { + return when (address) { + "user1@domain.example" -> "Contact One" + "spoof@domain.example" -> "contact@important.example" + else -> null + } + } + } + + private val account = Account("uuid").apply { + identities += Identity(name = IDENTITY_NAME, email = IDENTITY_ADDRESS) + } + + private val participantFormatter = createParticipantFormatter() + + @Test + fun `identity address`() { + val displayName = participantFormatter.getDisplayName(Address(IDENTITY_ADDRESS, "irrelevant"), account) + + assertThat(displayName).isEqualTo(IDENTITY_NAME) + } + + @Test + fun `identity without a display name`() { + val account = Account("uuid").apply { + identities += Identity(name = null, email = IDENTITY_ADDRESS) + } + + val displayName = participantFormatter.getDisplayName(Address(IDENTITY_ADDRESS, "Bob"), account) + + assertThat(displayName).isEqualTo("Bob") + } + + @Test + fun `identity and address without a display name`() { + val account = Account("uuid").apply { + identities += Identity(name = null, email = IDENTITY_ADDRESS) + } + + val displayName = participantFormatter.getDisplayName(Address(IDENTITY_ADDRESS), account) + + assertThat(displayName).isNull() + } + + @Test + fun `email address without display name`() { + val displayName = participantFormatter.getDisplayName(Address("alice@domain.example"), account) + + assertThat(displayName).isNull() + } + + @Test + fun `email address with display name`() { + val displayName = participantFormatter.getDisplayName(Address("alice@domain.example", "Alice"), account) + + assertThat(displayName).isEqualTo("Alice") + } + + @Test + fun `don't look up contact when showContactNames = false`() { + val participantFormatter = createParticipantFormatter(showContactNames = false) + + val displayName = participantFormatter.getDisplayName(Address("user1@domain.example", "User 1"), account) + + assertThat(displayName).isEqualTo("User 1") + } + + @Test + fun `contact lookup`() { + val displayName = participantFormatter.getDisplayName(Address("user1@domain.example"), account) + + assertThat(displayName).isEqualTo("Contact One") + } + + @Test + fun `contact lookup despite display name`() { + val displayName = participantFormatter.getDisplayName(Address("user1@domain.example", "User 1"), account) + + assertThat(displayName).isEqualTo("Contact One") + } + + @Test + fun `colored contact name`() { + val participantFormatter = createParticipantFormatter(contactNameColor = Color.RED) + + val displayName = participantFormatter.getDisplayName(Address("user1@domain.example"), account) + + assertThat(displayName.toString()).isEqualTo("Contact One") + assertThat(displayName).isNotNull().isInstanceOf(Spannable::class.java) + val spans = (displayName as Spannable).getSpans<ForegroundColorSpan>(0, displayName.length) + assertThat(spans.map { it.foregroundColor }).containsExactly(Color.RED) + } + + private fun createParticipantFormatter( + showContactNames: Boolean = true, + contactNameColor: Int? = null + ): MessageDetailsParticipantFormatter { + return RealMessageDetailsParticipantFormatter( + contactNameProvider = contactNameProvider, + showContactNames = showContactNames, + contactNameColor = contactNameColor + ) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/messagelist/MessageListAdapterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messagelist/MessageListAdapterTest.kt new file mode 100644 index 0000000..3983807 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messagelist/MessageListAdapterTest.kt @@ -0,0 +1,495 @@ +package com.fsck.k9.ui.messagelist + +import android.content.Context +import android.text.Spannable +import android.text.style.AbsoluteSizeSpan +import android.view.ContextThemeWrapper +import android.view.LayoutInflater +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.isGone +import androidx.core.view.isVisible +import app.k9mail.core.testing.TestClock +import com.fsck.k9.Account +import com.fsck.k9.FontSizes +import com.fsck.k9.FontSizes.FONT_DEFAULT +import com.fsck.k9.FontSizes.LARGE +import com.fsck.k9.RobolectricTest +import com.fsck.k9.UiDensity +import com.fsck.k9.contacts.ContactPictureLoader +import com.fsck.k9.mail.Address +import com.fsck.k9.textString +import com.fsck.k9.ui.R +import com.fsck.k9.ui.helper.RelativeDateTimeFormatter +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.kotlin.mock +import org.robolectric.Robolectric + +private const val SOME_ACCOUNT_UUID = "6b84207b-25de-4dab-97c3-953bbf03fec6" +private const val FIRST_LINE_DEFAULT_FONT_SIZE = 16f +private const val SECOND_LINE_DEFAULT_FONT_SIZE = 14f +private const val DATE_DEFAULT_FONT_SIZE = 14f + +class MessageListAdapterTest : RobolectricTest() { + val activity = Robolectric.buildActivity(AppCompatActivity::class.java).create().get() + val context: Context = ContextThemeWrapper(activity, R.style.Theme_K9_Light) + + val contactsPictureLoader: ContactPictureLoader = mock() + val listItemListener: MessageListItemActionListener = mock() + + @Test + fun withShowAccountChip_shouldShowAccountChip() { + val adapter = createAdapter(showAccountChip = true) + + val view = adapter.createAndBindView() + + assertTrue(view.accountChipView.isVisible) + } + + @Test + fun withoutShowAccountChip_shouldHideAccountChip() { + val adapter = createAdapter(showAccountChip = false) + + val view = adapter.createAndBindView() + + assertTrue(view.accountChipView.isGone) + } + + @Test + fun withoutStars_shouldHideStarView() { + val adapter = createAdapter(stars = false) + + val view = adapter.createAndBindView() + + assertTrue(view.starView.isGone) + } + + @Test + fun withStars_shouldShowStarView() { + val adapter = createAdapter(stars = true) + + val view = adapter.createAndBindView() + + assertTrue(view.starView.isVisible) + } + + @Test + fun withStarsAndStarredMessage_shouldSetStarViewToSelected() { + val adapter = createAdapter(stars = true) + val messageListItem = createMessageListItem(isStarred = true) + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.starView.isSelected) + } + + @Test + fun withStarsAndUnstarredMessage_shouldNotSetStarViewToSelected() { + val adapter = createAdapter(stars = true) + val messageListItem = createMessageListItem(isStarred = false) + + val view = adapter.createAndBindView(messageListItem) + + assertFalse(view.starView.isSelected) + } + + @Test + fun withoutShowContactPicture_shouldHideContactPictureView() { + val adapter = createAdapter(showContactPicture = false) + + val view = adapter.createAndBindView() + + assertTrue(view.contactPictureContainerView.isGone) + } + + @Test + fun withShowContactPicture_shouldShowContactPictureView() { + val adapter = createAdapter(showContactPicture = true) + + val view = adapter.createAndBindView() + + assertTrue(view.contactPictureContainerView.isVisible) + } + + @Test + fun withThreadCountOne_shouldHideThreadCountView() { + val adapter = createAdapter() + val messageListItem = createMessageListItem(threadCount = 1) + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.threadCountView.isGone) + } + + @Test + fun withThreadCountGreaterOne_shouldShowThreadCountViewWithExpectedValue() { + val adapter = createAdapter() + val messageListItem = createMessageListItem(threadCount = 13) + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.threadCountView.isVisible) + assertEquals("13", view.threadCountView.textString) + } + + @Test + fun withoutSenderAboveSubject_shouldShowSubjectInFirstLine() { + val adapter = createAdapter(senderAboveSubject = false) + val messageListItem = createMessageListItem(subject = "Subject") + + val view = adapter.createAndBindView(messageListItem) + + assertEquals("Subject", view.firstLineView.textString) + } + + @Test + fun withSenderAboveSubject_shouldShowDisplayNameInFirstLine() { + val adapter = createAdapter(senderAboveSubject = true) + val messageListItem = createMessageListItem(displayName = "Display Name") + + val view = adapter.createAndBindView(messageListItem) + + assertEquals("Display Name", view.firstLineView.textString) + } + + @Test + fun withoutSenderAboveSubjectAndZeroPreviewLines_shouldShowDisplayNameInSecondLine() { + val adapter = createAdapter(senderAboveSubject = false, previewLines = 0) + val messageListItem = createMessageListItem(displayName = "Display Name") + + val view = adapter.createAndBindView(messageListItem) + + assertEquals("Display Name", view.secondLineView.textString) + } + + @Test + fun withoutSenderAboveSubjectAndPreviewLines_shouldShowDisplayNameAndPreviewInSecondLine() { + val adapter = createAdapter(senderAboveSubject = false, previewLines = 1) + val messageListItem = createMessageListItem(displayName = "Display Name", previewText = "Preview") + + val view = adapter.createAndBindView(messageListItem) + + assertEquals(secondLine("Display Name", "Preview"), view.secondLineView.textString) + } + + @Test + fun withSenderAboveSubjectAndZeroPreviewLines_shouldShowSubjectInSecondLine() { + val adapter = createAdapter(senderAboveSubject = true, previewLines = 0) + val messageListItem = createMessageListItem(subject = "Subject") + + val view = adapter.createAndBindView(messageListItem) + + assertEquals("Subject", view.secondLineView.textString) + } + + @Test + fun withSenderAboveSubjectAndPreviewLines_shouldShowSubjectAndPreviewInSecondLine() { + val adapter = createAdapter(senderAboveSubject = true, previewLines = 1) + val messageListItem = createMessageListItem(subject = "Subject", previewText = "Preview") + + val view = adapter.createAndBindView(messageListItem) + + assertEquals(secondLine("Subject", "Preview"), view.secondLineView.textString) + } + + @Test + fun withMissingSubject_shouldDisplayNoSubjectIndicator() { + val adapter = createAdapter(senderAboveSubject = false) + val messageListItem = createMessageListItem(subject = null) + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.firstLineView.containsNoSubjectIndicator()) + } + + @Test + fun withEmptySubject_shouldDisplayNoSubjectIndicator() { + val adapter = createAdapter(senderAboveSubject = false) + val messageListItem = createMessageListItem(subject = "") + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.firstLineView.containsNoSubjectIndicator()) + } + + @Test + fun withoutAttachments_shouldHideAttachmentCountView() { + val adapter = createAdapter() + val messageListItem = createMessageListItem(hasAttachments = false) + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.attachmentCountView.isGone) + } + + @Test + fun withAttachments_shouldShowAttachmentCountView() { + val adapter = createAdapter() + val messageListItem = createMessageListItem(hasAttachments = true) + + val view = adapter.createAndBindView(messageListItem) + + assertTrue(view.attachmentCountView.isVisible) + } + + @Test + fun withoutSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeOfFirstLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(subject = FONT_DEFAULT), + senderAboveSubject = false, + ) + + val view = adapter.createAndBindView() + + assertEquals(FIRST_LINE_DEFAULT_FONT_SIZE, view.firstLineView.textSize) + } + + @Test + fun withoutSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeOfFirstLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(subject = LARGE), + senderAboveSubject = false, + ) + + val view = adapter.createAndBindView() + + assertEquals(22f, view.firstLineView.textSize) + } + + @Test + fun withSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeOfFirstLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(sender = FONT_DEFAULT), + senderAboveSubject = true, + ) + + val view = adapter.createAndBindView() + + assertEquals(FIRST_LINE_DEFAULT_FONT_SIZE, view.firstLineView.textSize) + } + + @Test + fun withSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeOfFirstLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(sender = LARGE), + senderAboveSubject = true, + ) + + val view = adapter.createAndBindView() + + assertEquals(22f, view.firstLineView.textSize) + } + + @Test + fun withoutSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeSpanInSecondLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(sender = FONT_DEFAULT), + senderAboveSubject = false, + ) + + val view = adapter.createAndBindView() + + assertNull(view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) + } + + @Test + fun withoutSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeSpanInSecondLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(sender = LARGE), + senderAboveSubject = false, + ) + + val view = adapter.createAndBindView() + + assertEquals(22, view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) + } + + @Test + fun withSenderAboveSubjectAndDefaultFontSize_shouldNotSetTextSizeSpanInSecondLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(subject = FONT_DEFAULT), + senderAboveSubject = true, + ) + + val view = adapter.createAndBindView() + + assertNull(view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) + } + + @Test + fun withSenderAboveSubjectAndNonDefaultFontSize_shouldSetTextSizeSpanInSecondLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(subject = LARGE), + senderAboveSubject = true, + ) + + val view = adapter.createAndBindView() + + assertEquals(22, view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) + } + + @Test + fun dateWithDefaultFontSize_shouldNotSetTextSizeOfDateView() { + val adapter = createAdapter(fontSizes = createFontSizes(date = FONT_DEFAULT)) + + val view = adapter.createAndBindView() + + assertEquals(DATE_DEFAULT_FONT_SIZE, view.dateView.textSize) + } + + @Test + fun dateWithNonDefaultFontSize_shouldSetTextSizeOfDateView() { + val adapter = createAdapter(fontSizes = createFontSizes(date = LARGE)) + + val view = adapter.createAndBindView() + + assertEquals(22f, view.dateView.textSize) + } + + @Test + fun previewWithDefaultFontSize_shouldNotSetTextSizeOfSecondLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(preview = FONT_DEFAULT), + previewLines = 1, + ) + + val view = adapter.createAndBindView() + + assertEquals(SECOND_LINE_DEFAULT_FONT_SIZE, view.secondLineView.textSize) + } + + @Test + fun previewWithNonDefaultFontSize_shouldSetTextSizeOfSecondLineView() { + val adapter = createAdapter( + fontSizes = createFontSizes(preview = LARGE), + previewLines = 1, + ) + + val view = adapter.createAndBindView() + + assertEquals(22f, view.secondLineView.textSize) + } + + fun createFontSizes( + subject: Int = FONT_DEFAULT, + sender: Int = FONT_DEFAULT, + preview: Int = FONT_DEFAULT, + date: Int = FONT_DEFAULT, + ): FontSizes { + return FontSizes().apply { + messageListSubject = subject + messageListSender = sender + messageListPreview = preview + messageListDate = date + } + } + + fun createAdapter( + fontSizes: FontSizes = createFontSizes(), + previewLines: Int = 0, + stars: Boolean = true, + senderAboveSubject: Boolean = false, + showContactPicture: Boolean = true, + showingThreadedList: Boolean = true, + backGroundAsReadIndicator: Boolean = false, + showAccountChip: Boolean = false, + density: UiDensity = UiDensity.Default, + ): MessageListAdapter { + val appearance = MessageListAppearance( + fontSizes, + previewLines, + stars, + senderAboveSubject, + showContactPicture, + showingThreadedList, + backGroundAsReadIndicator, + showAccountChip, + density, + ) + + return MessageListAdapter( + theme = context.theme, + res = context.resources, + layoutInflater = LayoutInflater.from(context), + contactsPictureLoader = contactsPictureLoader, + listItemListener = listItemListener, + appearance = appearance, + relativeDateTimeFormatter = RelativeDateTimeFormatter(context, TestClock()), + ) + } + + fun createMessageListItem( + account: Account = Account(SOME_ACCOUNT_UUID), + subject: String? = "irrelevant", + threadCount: Int = 0, + messageDate: Long = 0L, + internalDate: Long = 0L, + displayName: CharSequence = "irrelevant", + displayAddress: Address? = Address.parse("irrelevant@domain.example").first(), + previewText: String = "irrelevant", + isMessageEncrypted: Boolean = false, + isRead: Boolean = false, + isStarred: Boolean = false, + isAnswered: Boolean = false, + isForwarded: Boolean = false, + hasAttachments: Boolean = false, + uniqueId: Long = 0L, + folderId: Long = 0L, + messageUid: String = "irrelevant", + databaseId: Long = 0L, + threadRoot: Long = 0L, + ): MessageListItem { + return MessageListItem( + account, + subject, + threadCount, + messageDate, + internalDate, + displayName, + displayAddress, + previewText, + isMessageEncrypted, + isRead, + isStarred, + isAnswered, + isForwarded, + hasAttachments, + uniqueId, + folderId, + messageUid, + databaseId, + threadRoot, + ) + } + + fun MessageListAdapter.createAndBindView(item: MessageListItem = createMessageListItem()): View { + messages = listOf(item) + val holder = onCreateViewHolder(LinearLayout(context), 0) + onBindViewHolder(holder, 0) + return holder.itemView + } + + fun secondLine(senderOrSubject: String, preview: String) = "$senderOrSubject – $preview" + + val View.accountChipView: View get() = findViewById(R.id.account_color_chip) + val View.starView: View get() = findViewById(R.id.star) + val View.contactPictureContainerView: View get() = findViewById(R.id.contact_picture_click_area) + val View.threadCountView: TextView get() = findViewById(R.id.thread_count) + val View.firstLineView: TextView get() = findViewById(R.id.subject) + val View.secondLineView: TextView get() = findViewById(R.id.preview) + val View.attachmentCountView: View get() = findViewById(R.id.attachment) + val View.dateView: TextView get() = findViewById(R.id.date) + + fun TextView.containsNoSubjectIndicator() = textString.contains(context.getString(R.string.general_no_subject)) + + fun TextView.getFirstAbsoluteSizeSpanValueOrNull(): Int? { + val spans = (text as Spannable).getSpans(0, text.length, AbsoluteSizeSpan::class.java) + return spans.firstOrNull()?.size + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/DisplayRecipientsExtractorTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/DisplayRecipientsExtractorTest.kt new file mode 100644 index 0000000..2297f7d --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/DisplayRecipientsExtractorTest.kt @@ -0,0 +1,148 @@ +package com.fsck.k9.ui.messageview + +import assertk.assertThat +import assertk.assertions.isEqualTo +import com.fsck.k9.Account +import com.fsck.k9.Identity +import com.fsck.k9.mail.Address +import com.fsck.k9.mail.buildMessage +import org.junit.Test + +private const val IDENTITY_ADDRESS = "me@domain.example" + +class DisplayRecipientsExtractorTest { + private val account = Account("uuid").apply { + identities += Identity( + email = IDENTITY_ADDRESS + ) + } + + private val recipientFormatter = object : MessageViewRecipientFormatter { + override fun getDisplayName(address: Address, account: Account): CharSequence { + return when (address.address) { + IDENTITY_ADDRESS -> "me" + "user1@domain.example" -> "Contact One" + "user2@domain.example" -> "Contact Two" + "user3@domain.example" -> "Contact Three" + "user4@domain.example" -> "Contact Four" + else -> address.personal ?: address.address + } + } + } + + private val displayRecipientsExtractor = DisplayRecipientsExtractor( + recipientFormatter, + maxNumberOfDisplayRecipients = 5 + ) + + @Test + fun `single recipient is identity address`() { + val message = buildMessage { + header("To", "Test User <$IDENTITY_ADDRESS>") + } + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients).isEqualTo( + DisplayRecipients(recipientNames = listOf("me"), numberOfRecipients = 1) + ) + } + + @Test + fun `single recipient is a contact`() { + val message = buildMessage { + header("To", "User 1 <user1@domain.example>") + } + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients).isEqualTo( + DisplayRecipients(recipientNames = listOf("Contact One"), numberOfRecipients = 1) + ) + } + + @Test + fun `single recipient is not a contact`() { + val message = buildMessage { + header("To", "Alice <alice@domain.example>") + } + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients).isEqualTo( + DisplayRecipients(recipientNames = listOf("Alice"), numberOfRecipients = 1) + ) + } + + @Test + fun `single recipient without name and not a contact`() { + val message = buildMessage { + header("To", "alice@domain.example") + } + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients).isEqualTo( + DisplayRecipients(recipientNames = listOf("alice@domain.example"), numberOfRecipients = 1) + ) + } + + @Test + fun `three unknown recipients`() { + val message = buildMessage { + header("To", "Unknown 1 <unknown1@domain.example>, Unknown 2 <unknown2@domain.example>") + header("Cc", "Unknown 3 <unknown3@domain.example>") + } + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients).isEqualTo( + DisplayRecipients( + recipientNames = listOf("Unknown 1", "Unknown 2", "Unknown 3"), + numberOfRecipients = 3 + ) + ) + } + + @Test + fun `recipients spread across To and Cc header`() { + val message = buildMessage { + header("To", "user1@domain.example, Alice <alice@domain.example>, $IDENTITY_ADDRESS") + header("Cc", "user2@domain.example, User 4 <user4@domain.example>, someone.else@domain.example") + header("Bcc", "hidden@domain.example") + } + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients).isEqualTo( + DisplayRecipients( + recipientNames = listOf("me", "Contact One", "Alice", "Contact Two", "Contact Four"), + numberOfRecipients = 7 + ) + ) + } + + @Test + fun `100 recipients, RecipientFormatter_getDisplayName should only be called maxNumberOfDisplayRecipients times`() { + val recipients = (1..100).joinToString(separator = ", ") { "unknown$it@domain.example" } + val message = buildMessage { + header("To", recipients) + } + var numberOfTimesCalled = 0 + val recipientFormatter = object : MessageViewRecipientFormatter { + override fun getDisplayName(address: Address, account: Account): CharSequence { + numberOfTimesCalled++ + return address.address + } + } + val displayRecipientsExtractor = DisplayRecipientsExtractor( + recipientFormatter, + maxNumberOfDisplayRecipients = 5 + ) + + val displayRecipients = displayRecipientsExtractor.extractDisplayRecipients(message, account) + + assertThat(displayRecipients.numberOfRecipients).isEqualTo(100) + assertThat(numberOfTimesCalled).isEqualTo(5) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/MessageViewRecipientFormatterTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/MessageViewRecipientFormatterTest.kt new file mode 100644 index 0000000..fee6648 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/MessageViewRecipientFormatterTest.kt @@ -0,0 +1,217 @@ +package com.fsck.k9.ui.messageview + +import android.graphics.Color +import android.text.Spannable +import android.text.style.ForegroundColorSpan +import androidx.core.text.getSpans +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEqualTo +import assertk.assertions.isInstanceOf +import com.fsck.k9.Account +import com.fsck.k9.Identity +import com.fsck.k9.RobolectricTest +import com.fsck.k9.helper.ContactNameProvider +import com.fsck.k9.mail.Address +import org.junit.Test + +private const val IDENTITY_ADDRESS = "me@domain.example" +private const val ME_TEXT = "me" + +class MessageViewRecipientFormatterTest : RobolectricTest() { + private val contactNameProvider = object : ContactNameProvider { + override fun getNameForAddress(address: String): String? { + return when (address) { + "user1@domain.example" -> "Contact One" + "spoof@domain.example" -> "contact@important.example" + else -> null + } + } + } + + private val account = Account("uuid").apply { + identities += Identity(email = IDENTITY_ADDRESS) + } + + @Test + fun `single identity`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address(IDENTITY_ADDRESS, "irrelevant"), account) + + assertThat(displayName).isEqualTo(ME_TEXT) + } + + @Test + fun `multiple identities`() { + val account = Account("uuid").apply { + identities += Identity(description = "My identity", email = IDENTITY_ADDRESS) + identities += Identity(email = "another.one@domain.example") + } + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address(IDENTITY_ADDRESS, "irrelevant"), account) + + assertThat(displayName).isEqualTo("My identity") + } + + @Test + fun `identity without a description`() { + val account = Account("uuid").apply { + identities += Identity(name = "My name", email = IDENTITY_ADDRESS) + identities += Identity(email = "another.one@domain.example") + } + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address(IDENTITY_ADDRESS, "irrelevant"), account) + + assertThat(displayName).isEqualTo("My name") + } + + @Test + fun `identity without a description and name`() { + val account = Account("uuid").apply { + identities += Identity(email = IDENTITY_ADDRESS) + identities += Identity(email = "another.one@domain.example") + } + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address(IDENTITY_ADDRESS, "irrelevant"), account) + + assertThat(displayName).isEqualTo(IDENTITY_ADDRESS) + } + + @Test + fun `email address without display name`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address("alice@domain.example"), account) + + assertThat(displayName).isEqualTo("alice@domain.example") + } + + @Test + fun `email address with display name`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address("alice@domain.example", "Alice"), account) + + assertThat(displayName).isEqualTo("Alice") + } + + @Test + fun `don't look up contact when showContactNames = false`() { + val recipientFormatter = createRecipientFormatter(showContactNames = false) + + val displayName = recipientFormatter.getDisplayName(Address("user1@domain.example", "User 1"), account) + + assertThat(displayName).isEqualTo("User 1") + } + + @Test + fun `contact lookup`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address("user1@domain.example"), account) + + assertThat(displayName).isEqualTo("Contact One") + } + + @Test + fun `contact lookup despite display name`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address("user1@domain.example", "User 1"), account) + + assertThat(displayName).isEqualTo("Contact One") + } + + @Test + fun `colored contact name`() { + val recipientFormatter = createRecipientFormatter(contactNameColor = Color.RED) + + val displayName = recipientFormatter.getDisplayName(Address("user1@domain.example"), account) + + assertThat(displayName.toString()).isEqualTo("Contact One") + assertThat(displayName).isInstanceOf(Spannable::class.java) + val spans = (displayName as Spannable).getSpans<ForegroundColorSpan>(0, displayName.length) + assertThat(spans.map { it.foregroundColor }).containsExactly(Color.RED) + } + + @Test + fun `email address with display name but not showing correspondent names`() { + val recipientFormatter = createRecipientFormatter(showCorrespondentNames = false) + + val displayName = recipientFormatter.getDisplayName(Address("alice@domain.example", "Alice"), account) + + assertThat(displayName).isEqualTo("alice@domain.example") + } + + @Test + fun `do not show display name that looks like an email address`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName( + Address("mallory@domain.example", "potus@whitehouse.gov"), + account + ) + + assertThat(displayName).isEqualTo("mallory@domain.example") + } + + @Test + fun `do show display name that contains an @ preceded by an opening parenthesis`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName( + Address("gitlab@gitlab.example", "username (@username)"), + account + ) + + assertThat(displayName).isEqualTo("username (@username)") + } + + @Test + fun `do show display name that starts with an @`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address("address@domain.example", "@username"), account) + + assertThat(displayName).isEqualTo("@username") + } + + @Test + fun `spoof prevention doesn't apply to contact names`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName( + Address("spoof@domain.example", "contact@important.example"), + account + ) + + assertThat(displayName).isEqualTo("contact@important.example") + } + + @Test + fun `display name matches me text`() { + val recipientFormatter = createRecipientFormatter() + + val displayName = recipientFormatter.getDisplayName(Address("someone_named_me@domain.example", "ME"), account) + + assertThat(displayName).isEqualTo("someone_named_me@domain.example") + } + + private fun createRecipientFormatter( + showCorrespondentNames: Boolean = true, + showContactNames: Boolean = true, + contactNameColor: Int? = null + ): RealMessageViewRecipientFormatter { + return RealMessageViewRecipientFormatter( + contactNameProvider = contactNameProvider, + showCorrespondentNames = showCorrespondentNames, + showContactNames = showContactNames, + contactNameColor = contactNameColor, + meText = ME_TEXT + ) + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/RecipientLayoutCreatorTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/RecipientLayoutCreatorTest.kt new file mode 100644 index 0000000..a92c8b6 --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/messageview/RecipientLayoutCreatorTest.kt @@ -0,0 +1,148 @@ +package com.fsck.k9.ui.messageview + +import assertk.assertThat +import assertk.assertions.isEqualTo +import assertk.assertions.isNull +import com.fsck.k9.RobolectricTest +import org.junit.Test + +class RecipientLayoutCreatorTest : RobolectricTest() { + private val textMeasure = object : TextMeasure { + override fun measureRecipientNames(text: CharSequence): Int { + return measureText(text) + } + + override fun measureRecipientCount(text: CharSequence): Int { + return measureText(text) + } + + private fun measureText(text: CharSequence): Int { + return text.length + } + } + + private val recipientLayoutCreator = RecipientLayoutCreator( + textMeasure = textMeasure, + maxNumberOfRecipientNames = 5, + recipientsPrefix = "to ", + additionalRecipientSpacing = 1, + additionalRecipientsPrefix = "+" + ) + + @Test(expected = IllegalArgumentException::class) + fun `empty recipient list should throw`() { + recipientLayoutCreator.createRecipientLayout( + recipientNames = emptyList(), + totalNumberOfRecipients = 0, + availableWidth = 100 + ) + } + + @Test + fun `single recipient name that fits available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("me"), + totalNumberOfRecipients = 1, + availableWidth = 10 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to me") + assertThat(result.additionalRecipients).isNull() + } + + @Test + fun `single recipient name that doesn't fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("me"), + totalNumberOfRecipients = 1, + availableWidth = 1 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to me") + assertThat(result.additionalRecipients).isNull() + } + + @Test + fun `two recipient names where first one doesn't fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("Alice", "Bob"), + totalNumberOfRecipients = 2, + availableWidth = 5 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to Alice") + assertThat(result.additionalRecipients).isEqualTo("+1") + } + + @Test + fun `two recipient names where both fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("Alice", "Bob"), + totalNumberOfRecipients = 2, + availableWidth = 13 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to Alice, Bob") + assertThat(result.additionalRecipients).isNull() + } + + @Test + fun `three recipient names where only first one fits available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("Alice", "Bob", "Charly"), + totalNumberOfRecipients = 3, + availableWidth = 13 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to Alice") + assertThat(result.additionalRecipients).isEqualTo("+2") + } + + @Test + fun `three recipient names where only first two fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("Alice", "Bob", "Charly"), + totalNumberOfRecipients = 3, + availableWidth = 16 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to Alice, Bob") + assertThat(result.additionalRecipients).isEqualTo("+1") + } + + @Test + fun `three recipient names where all fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("Alice", "Bob", "Charly"), + totalNumberOfRecipients = 3, + availableWidth = 100 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to Alice, Bob, Charly") + assertThat(result.additionalRecipients).isNull() + } + + @Test + fun `five recipient names and additional recipients where only two fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("One", "Two", "Three", "Four", "Five"), + totalNumberOfRecipients = 10, + availableWidth = 20 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to One, Two") + assertThat(result.additionalRecipients).isEqualTo("+8") + } + + @Test + fun `five recipient names and additional recipients where all five fit available width`() { + val result = recipientLayoutCreator.createRecipientLayout( + recipientNames = listOf("One", "Two", "Three", "Four", "Five"), + totalNumberOfRecipients = 10, + availableWidth = 100 + ) + + assertThat(result.recipientNames.toString()).isEqualTo("to One, Two, Three, Four, Five") + assertThat(result.additionalRecipients).isEqualTo("+5") + } +} diff --git a/app/ui/legacy/src/test/java/com/fsck/k9/ui/settings/general/GeneralSettingsViewModelTest.kt b/app/ui/legacy/src/test/java/com/fsck/k9/ui/settings/general/GeneralSettingsViewModelTest.kt new file mode 100644 index 0000000..ef1875c --- /dev/null +++ b/app/ui/legacy/src/test/java/com/fsck/k9/ui/settings/general/GeneralSettingsViewModelTest.kt @@ -0,0 +1,147 @@ +package com.fsck.k9.ui.settings.general + +import android.net.Uri +import app.cash.turbine.test +import assertk.assertThat +import assertk.assertions.isEmpty +import assertk.assertions.isEqualTo +import com.fsck.k9.logging.LogFileWriter +import java.io.IOException +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.mock + +@OptIn(ExperimentalCoroutinesApi::class) +class GeneralSettingsViewModelTest { + private val logFileWriter = TestLogFileWriter() + private val contentUri = mock<Uri>() + private val viewModel = GeneralSettingsViewModel(logFileWriter) + private val testCoroutineDispatcher = StandardTestDispatcher() + + @Before + fun setUp() { + Dispatchers.setMain(testCoroutineDispatcher) + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `export logs without errors`() = runTest { + viewModel.uiState.test { + viewModel.exportLogs(contentUri) + + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Exporting) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Success) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + testCoroutineDispatcher.scheduler.advanceUntilIdle() + assertThat(cancelAndConsumeRemainingEvents()).isEmpty() + } + } + + @Test + fun `export logs with consumer changing while LogFileWriter_writeLogTo is running`() = runTest { + logFileWriter.shouldWait() + + val mutex = Mutex(locked = true) + + // The first consumer + val job = launch(CoroutineName("ConsumerOne")) { + var first = true + val states = viewModel.uiState.onEach { + if (first) { + first = false + mutex.unlock() + } + }.take(2).toList() + + assertThat(states[0]).isEqualTo(GeneralSettingsUiState.Idle) + assertThat(states[1]).isEqualTo(GeneralSettingsUiState.Exporting) + } + + // Wait until the "ConsumerOne" coroutine has collected the initial UI state + mutex.lock() + + viewModel.exportLogs(contentUri) + + // Wait until the "ConsumerOne" coroutine has finished collecting items + job.join() + + // The second consumer + viewModel.uiState.test { + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Exporting) + logFileWriter.resume() + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Success) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + testCoroutineDispatcher.scheduler.advanceUntilIdle() + assertThat(cancelAndConsumeRemainingEvents()).isEmpty() + } + } + + @Test + fun `export logs with IOException`() = runTest { + logFileWriter.exception = IOException() + + viewModel.uiState.test { + viewModel.exportLogs(contentUri) + + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Exporting) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Failure) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + testCoroutineDispatcher.scheduler.advanceUntilIdle() + assertThat(cancelAndConsumeRemainingEvents()).isEmpty() + } + } + + @Test + fun `export logs with IllegalStateException`() = runTest { + logFileWriter.exception = IllegalStateException() + + viewModel.uiState.test { + viewModel.exportLogs(contentUri) + + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Exporting) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Failure) + assertThat(awaitItem()).isEqualTo(GeneralSettingsUiState.Idle) + testCoroutineDispatcher.scheduler.advanceUntilIdle() + assertThat(cancelAndConsumeRemainingEvents()).isEmpty() + } + } +} + +class TestLogFileWriter : LogFileWriter { + var exception: Throwable? = null + private var mutex: Mutex? = null + + override suspend fun writeLogTo(contentUri: Uri) { + exception?.let { throw it } + + mutex?.lock() + } + + fun shouldWait() { + mutex = Mutex(locked = true) + } + + fun resume() { + mutex!!.unlock() + } +} |
