src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ContactPictureLoader { @VisibleForTesting protected static String calcUnknownContactLetter(Address address) { String letter = null; String personal = address.getPersonal(); String str = (personal != null) ? personal : address.getAddress(); Matcher m = EXTRACT_LETTER_PATTERN.matcher(str); if (m.find()) { letter = m.group(0).toUpperCase(Locale.US); } return (TextUtils.isEmpty(letter)) ? FALLBACK_CONTACT_LETTER : letter; } ContactPictureLoader(Context context, int defaultBackgroundColor); void loadContactPicture(final Address address, final ImageView imageView); void loadContactPicture(Recipient recipient, ImageView imageView); } | @Test public void calcUnknownContactLetter_withNoNameUsesAddress() { Address address = new Address("<[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("C", result); }
@Test public void calcUnknownContactLetter_withAsciiName() { Address address = new Address("abcd <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("A", result); }
@Test public void calcUnknownContactLetter_withLstroke() { Address address = new Address("Łatynka <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("Ł", result); }
@Test public void calcUnknownContactLetter_withChinese() { Address address = new Address("千里之行﹐始于足下 <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("千", result); }
@Test public void calcUnknownContactLetter_withCombinedGlyphs() { Address address = new Address("\u0061\u0300 <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("\u0041\u0300", result); }
@Test public void calcUnknownContactLetter_withSurrogatePair() { Address address = new Address("\uD800\uDFB5 <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("\uD800\uDFB5", result); }
@Test public void calcUnknownContactLetter_ignoresSpace() { Address address = new Address(" abcd <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("A", result); }
@Test public void calcUnknownContactLetter_ignoresUsePunctuation() { Address address = new Address("-a <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("A", result); }
@Test public void calcUnknownContactLetter_ignoresMatchEmoji() { Address address = new Address("\uD83D\uDE00 <[email protected]>"); String result = ContactPictureLoader.calcUnknownContactLetter(address); assertEquals("?", result); } |
RecipientPresenter implements PermissionPingCallback { public void initFromReplyToMessage(Message message, ReplyMode replyMode) { ReplyToAddresses replyToAddresses; switch (replyMode) { case ALL: replyToAddresses = replyToParser.getRecipientsToReplyAllTo(message, account); break; case LIST: replyToAddresses = replyToParser.getRecipientsToReplyListTo(message, account); break; case NORMAL: replyToAddresses = replyToParser.getRecipientsToReplyTo(message, account); break; default: throw new IllegalArgumentException("Unexpected reply mode: " + replyMode); } addToAddresses(replyToAddresses.to); addCcAddresses(replyToAddresses.cc); boolean shouldSendAsPgpInline = composePgpInlineDecider.shouldReplyInline(message); if (shouldSendAsPgpInline) { cryptoEnablePgpInline = true; } boolean shouldEnablePgpByDefault = composePgpEnableByDefaultDecider.shouldEncryptByDefault(message); currentCryptoMode = shouldEnablePgpByDefault ? CryptoMode.CHOICE_ENABLED : CryptoMode.NO_CHOICE; } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void testInitFromReplyToMessage() throws Exception { Message message = mock(Message.class); when(replyToParser.getRecipientsToReplyTo(message, account)).thenReturn(TO_ADDRESSES); recipientPresenter.initFromReplyToMessage(message, ReplyMode.NORMAL); runBackgroundTask(); verify(recipientMvpView).addRecipients(eq(RecipientType.TO), any(Recipient[].class)); }
@Test public void testInitFromReplyToAllMessage() throws Exception { Message message = mock(Message.class); when(replyToParser.getRecipientsToReplyTo(message, account)).thenReturn(TO_ADDRESSES); ReplyToAddresses replyToAddresses = new ReplyToAddresses(ALL_TO_ADDRESSES, ALL_CC_ADDRESSES); when(replyToParser.getRecipientsToReplyAllTo(message, account)).thenReturn(replyToAddresses); recipientPresenter.initFromReplyToMessage(message, ReplyMode.ALL); runBackgroundTask(); runBackgroundTask(); verify(recipientMvpView).addRecipients(eq(RecipientType.TO), any(Recipient.class)); verify(recipientMvpView).addRecipients(eq(RecipientType.CC), any(Recipient.class)); }
@Test public void initFromReplyToMessage_shouldCallComposePgpInlineDecider() throws Exception { Message message = mock(Message.class); when(replyToParser.getRecipientsToReplyTo(message, account)).thenReturn(TO_ADDRESSES); recipientPresenter.initFromReplyToMessage(message, ReplyMode.NORMAL); verify(composePgpInlineDecider).shouldReplyInline(message); } |
RecipientPresenter implements PermissionPingCallback { @Nullable public ComposeCryptoStatus getCurrentCachedCryptoStatus() { return cachedCryptoStatus; } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void getCurrentCryptoStatus_withoutCryptoProvider() throws Exception { ComposeCryptoStatus status = recipientPresenter.getCurrentCachedCryptoStatus(); assertEquals(CryptoStatusDisplayType.UNCONFIGURED, status.getCryptoStatusDisplayType()); assertEquals(CryptoSpecialModeDisplayType.NONE, status.getCryptoSpecialModeDisplayType()); assertNull(status.getAttachErrorStateOrNull()); assertFalse(status.isProviderStateOk()); assertFalse(status.shouldUsePgpMessageBuilder()); } |
RecipientPresenter implements PermissionPingCallback { void onToTokenAdded() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onToTokenAdded_notifiesListenerOfRecipientChange() { recipientPresenter.onToTokenAdded(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onToTokenChanged() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onToTokenChanged_notifiesListenerOfRecipientChange() { recipientPresenter.onToTokenChanged(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onToTokenRemoved() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onToTokenRemoved_notifiesListenerOfRecipientChange() { recipientPresenter.onToTokenRemoved(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onCcTokenAdded() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onCcTokenAdded_notifiesListenerOfRecipientChange() { recipientPresenter.onCcTokenAdded(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onCcTokenChanged() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onCcTokenChanged_notifiesListenerOfRecipientChange() { recipientPresenter.onCcTokenChanged(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onCcTokenRemoved() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onCcTokenRemoved_notifiesListenerOfRecipientChange() { recipientPresenter.onCcTokenRemoved(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onBccTokenAdded() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onBccTokenAdded_notifiesListenerOfRecipientChange() { recipientPresenter.onBccTokenAdded(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onBccTokenChanged() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onBccTokenChanged_notifiesListenerOfRecipientChange() { recipientPresenter.onBccTokenChanged(); verify(listener).onRecipientsChanged(); } |
RecipientPresenter implements PermissionPingCallback { void onBccTokenRemoved() { asyncUpdateCryptoStatus(); listener.onRecipientsChanged(); } RecipientPresenter(Context context, LoaderManager loaderManager,
RecipientMvpView recipientMvpView, Account account, ComposePgpInlineDecider composePgpInlineDecider,
ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider,
AutocryptStatusInteractor autocryptStatusInteractor,
ReplyToParser replyToParser, RecipientsChangedListener recipientsChangedListener); List<Address> getToAddresses(); List<Address> getCcAddresses(); List<Address> getBccAddresses(); boolean checkRecipientsOkForSending(); void initFromReplyToMessage(Message message, ReplyMode replyMode); void initFromTrustIdAction(String trustId); void initFromMailto(MailTo mailTo); void initFromSendOrViewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); void onSaveInstanceState(Bundle outState); void initFromDraftMessage(Message message); void addBccAddresses(Address... bccRecipients); void onPrepareOptionsMenu(Menu menu); void onSwitchAccount(Account account); @SuppressWarnings("UnusedParameters") void onSwitchIdentity(Identity identity); void asyncUpdateCryptoStatus(); @Nullable ComposeCryptoStatus getCurrentCachedCryptoStatus(); boolean isForceTextMessageFormat(); void onCryptoModeChanged(CryptoMode cryptoMode); void onCryptoPgpInlineChanged(boolean enablePgpInline); void onMenuAddFromContacts(); void onActivityResult(int requestCode, int resultCode, Intent data); void onNonRecipientFieldFocused(); void showPgpSendError(SendErrorState sendErrorState); @Override void onPgpPermissionCheckResult(Intent result); void onActivityDestroy(); void builderSetProperties(MessageBuilder messageBuilder); void builderSetProperties(PgpMessageBuilder pgpMessageBuilder, ComposeCryptoStatus cryptoStatus); void onMenuSetPgpInline(boolean enablePgpInline); void onMenuSetSignOnly(boolean enableSignOnly); void onMenuSetEnableEncryption(boolean enableEncryption); void onCryptoPgpClickDisable(); void onCryptoPgpSignOnlyDisabled(); boolean shouldSaveRemotely(); } | @Test public void onBccTokenRemoved_notifiesListenerOfRecipientChange() { recipientPresenter.onBccTokenRemoved(); verify(listener).onRecipientsChanged(); } |
FolderInfoHolder implements Comparable<FolderInfoHolder> { public static String getDisplayName(Context context, Account account, String id, String name) { final String displayName; if (id.equals(account.getSpamFolderId())) { displayName = String.format( context.getString(R.string.special_mailbox_name_spam_fmt), name); } else if (id.equals(account.getArchiveFolderId())) { displayName = String.format( context.getString(R.string.special_mailbox_name_archive_fmt), name); } else if (id.equals(account.getSentFolderId())) { displayName = String.format( context.getString(R.string.special_mailbox_name_sent_fmt), name); } else if (id.equals(account.getTrashFolderId())) { displayName = String.format( context.getString(R.string.special_mailbox_name_trash_fmt), name); } else if (id.equals(account.getDraftsFolderId())) { displayName = String.format( context.getString(R.string.special_mailbox_name_drafts_fmt), name); } else if (id.equals(account.getOutboxFolderId())) { displayName = context.getString(R.string.special_mailbox_name_outbox); } else if (id.equalsIgnoreCase(account.getInboxFolderId())) { displayName = context.getString(R.string.special_mailbox_name_inbox); } else if (name == null) { displayName = id; } else { displayName = name; } return displayName; } FolderInfoHolder(); FolderInfoHolder(Context context, LocalFolder folder, Account account); FolderInfoHolder(Context context, LocalFolder folder, Account account, int unreadCount); @Override boolean equals(Object o); @Override int hashCode(); int compareTo(FolderInfoHolder o); void populate(Context context, LocalFolder folder, Account account, int unreadCount); void populate(Context context, LocalFolder folder, Account account); static String getDisplayName(Context context, Account account, String id, String name); void setMoreMessagesFromFolder(LocalFolder folder); public String id; public String name; public String displayName; public long lastChecked; public int unreadMessageCount; public int flaggedMessageCount; public boolean loading; public String status; public boolean lastCheckFailed; public Folder folder; public boolean pushActive; public boolean moreMessages; } | @Test public void getDisplayName_forUnknownFolder_returnsName() { String result = FolderInfoHolder.getDisplayName(context, mockAccount, "FolderID", "Folder"); assertEquals("Folder", result); }
@Test public void getDisplayName_forSpamFolder_returnsNameSpam() { when(mockAccount.getSpamFolderId()).thenReturn("FolderID"); String result = FolderInfoHolder.getDisplayName(context, mockAccount, "FolderID", "Folder"); assertEquals("Folder (Spam)", result); }
@Test public void getDisplayName_forOutboxFolder_returnsOutbox() { when(mockAccount.getOutboxFolderId()).thenReturn("FolderID"); String result = FolderInfoHolder.getDisplayName(context, mockAccount, "FolderID", "Folder"); assertEquals("Outbox", result); }
@Test public void getDisplayName_forInboxFolder_returnsInbox() { when(mockAccount.getInboxFolderId()).thenReturn("FolderID"); String result = FolderInfoHolder.getDisplayName(context, mockAccount, "FolderID", "Folder"); assertEquals("Inbox", result); }
@Test public void getDisplayName_forInboxFolderAlternativeCase_returnsInbox() { when(mockAccount.getInboxFolderId()).thenReturn("FOLDERID"); String result = FolderInfoHolder.getDisplayName(context, mockAccount, "FolderID", "Folder"); assertEquals("Inbox", result); } |
MessageReference { public String toIdentityString() { StringBuilder refString = new StringBuilder(); refString.append(IDENTITY_VERSION_1); refString.append(IDENTITY_SEPARATOR); refString.append(Base64.encode(accountUuid)); refString.append(IDENTITY_SEPARATOR); refString.append(Base64.encode(folderId)); refString.append(IDENTITY_SEPARATOR); refString.append(Base64.encode(uid)); if (flag != null) { refString.append(IDENTITY_SEPARATOR); refString.append(flag.name()); } return refString.toString(); } MessageReference(String accountUuid, String folderId, String uid, Flag flag); @Nullable static MessageReference parse(String identity); String toIdentityString(); @Override boolean equals(Object o); boolean equals(String accountUuid, String folderId, String uid); @Override int hashCode(); @Override String toString(); String getAccountUuid(); String getFolderId(); String getUid(); Flag getFlag(); MessageReference withModifiedUid(String newUid); MessageReference withModifiedFlag(Flag newFlag); } | @Test public void checkIdentityStringFromMessageReferenceWithoutFlag() { MessageReference messageReference = createMessageReference("o hai!", "folder", "10101010"); assertEquals("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=", messageReference.toIdentityString()); }
@Test public void checkIdentityStringFromMessageReferenceWithFlag() { MessageReference messageReference = createMessageReferenceWithFlag("o hai!", "folder", "10101010", Flag.ANSWERED); assertEquals("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED", messageReference.toIdentityString()); } |
MessageReference { @Nullable public static MessageReference parse(String identity) { if (identity == null || identity.length() < 1 || identity.charAt(0) != IDENTITY_VERSION_1) { return null; } StringTokenizer tokens = new StringTokenizer(identity.substring(2), IDENTITY_SEPARATOR, false); if (tokens.countTokens() < 3) { return null; } String accountUuid = Base64.decode(tokens.nextToken()); String folderId = Base64.decode(tokens.nextToken()); String uid = Base64.decode(tokens.nextToken()); if (!tokens.hasMoreTokens()) { return new MessageReference(accountUuid, folderId, uid, null); } Flag flag; try { flag = Flag.valueOf(tokens.nextToken()); } catch (IllegalArgumentException e) { return null; } return new MessageReference(accountUuid, folderId, uid, flag); } MessageReference(String accountUuid, String folderId, String uid, Flag flag); @Nullable static MessageReference parse(String identity); String toIdentityString(); @Override boolean equals(Object o); boolean equals(String accountUuid, String folderId, String uid); @Override int hashCode(); @Override String toString(); String getAccountUuid(); String getFolderId(); String getUid(); Flag getFlag(); MessageReference withModifiedUid(String newUid); MessageReference withModifiedFlag(Flag newFlag); } | @Test public void parseIdentityStringContainingBadVersionNumber() { MessageReference messageReference = MessageReference.parse("@:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED"); assertNull(messageReference); }
@Test public void parseNullIdentityString() { MessageReference messageReference = MessageReference.parse(null); assertNull(messageReference); }
@Test public void parseIdentityStringWithCorruptFlag() { MessageReference messageReference = MessageReference.parse("!:%^&%^*$&$by&(BYWkh:Zm9%^@sZGVy:MT-35#$AxMDEwMTA=:ANSWE!RED"); assertNull(messageReference); } |
MessageReference { @Override public boolean equals(Object o) { if (!(o instanceof MessageReference)) { return false; } MessageReference other = (MessageReference) o; return equals(other.accountUuid, other.folderId, other.uid); } MessageReference(String accountUuid, String folderId, String uid, Flag flag); @Nullable static MessageReference parse(String identity); String toIdentityString(); @Override boolean equals(Object o); boolean equals(String accountUuid, String folderId, String uid); @Override int hashCode(); @Override String toString(); String getAccountUuid(); String getFolderId(); String getUid(); Flag getFlag(); MessageReference withModifiedUid(String newUid); MessageReference withModifiedFlag(Flag newFlag); } | @Test public void equalsWithAnObjectShouldReturnFalse() { MessageReference messageReference = new MessageReference("a", "b", "c", null); Object object = new Object(); assertFalse(messageReference.equals(object)); }
@SuppressWarnings("ObjectEqualsNull") @Test public void equalsWithNullShouldReturnFalse() { MessageReference messageReference = createMessageReference("account", "folder", "uid"); assertFalse(messageReference.equals(null)); }
@Test public void equalsWithSameMessageReferenceShouldReturnTrue() { MessageReference messageReference = createMessageReference("account", "folder", "uid"); assertTrue(messageReference.equals(messageReference)); }
@Test public void alternativeEquals() { MessageReference messageReference = createMessageReference("account", "folder", "uid"); boolean equalsResult = messageReference.equals("account", "folder", "uid"); assertTrue(equalsResult); }
@Test public void equals_withNullAccount_shouldReturnFalse() { MessageReference messageReference = createMessageReference("account", "folder", "uid"); boolean equalsResult = messageReference.equals(null, "folder", "uid"); assertFalse(equalsResult); }
@Test public void equals_withNullFolder_shouldReturnFalse() { MessageReference messageReference = createMessageReference("account", "folder", "uid"); boolean equalsResult = messageReference.equals("account", null, "uid"); assertFalse(equalsResult); }
@Test public void equals_withNullUid_shouldReturnFalse() { MessageReference messageReference = createMessageReference("account", "folder", "uid"); boolean equalsResult = messageReference.equals("account", "folder", null); assertFalse(equalsResult); } |
BaseNotifications { protected NotificationCompat.Builder createAndInitializeNotificationBuilder(Account account) { return controller.createNotificationBuilder() .setSmallIcon(getNewMailNotificationIcon()) .setColor(account.getChipColor()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setCategory(NotificationCompat.CATEGORY_EMAIL); } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); } | @Test public void testCreateAndInitializeNotificationBuilder() throws Exception { Account account = createFakeAccount(); Builder builder = notifications.createAndInitializeNotificationBuilder(account); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setColor(ACCOUNT_COLOR); verify(builder).setAutoCancel(true); } |
BaseNotifications { protected boolean isDeleteActionEnabled() { NotificationQuickDelete deleteOption = QMail.getNotificationQuickDeleteBehaviour(); return deleteOption == NotificationQuickDelete.ALWAYS || deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG; } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); } | @Test public void testIsDeleteActionEnabled_NotificationQuickDelete_ALWAYS() throws Exception { QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.ALWAYS); boolean result = notifications.isDeleteActionEnabled(); assertTrue(result); }
@Test public void testIsDeleteActionEnabled_NotificationQuickDelete_FOR_SINGLE_MSG() throws Exception { QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.FOR_SINGLE_MSG); boolean result = notifications.isDeleteActionEnabled(); assertTrue(result); }
@Test public void testIsDeleteActionEnabled_NotificationQuickDelete_NEVER() throws Exception { QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.NEVER); boolean result = notifications.isDeleteActionEnabled(); assertFalse(result); } |
BaseNotifications { protected NotificationCompat.Builder createBigTextStyleNotification(Account account, NotificationHolder holder, int notificationId) { String accountName = controller.getAccountName(account); NotificationContent content = holder.content; String groupKey = NotificationGroupKeys.getGroupKey(account); NotificationCompat.Builder builder = createAndInitializeNotificationBuilder(account) .setTicker(content.summary) .setGroup(groupKey) .setContentTitle(content.sender) .setContentText(content.subject) .setSubText(accountName); NotificationCompat.BigTextStyle style = createBigTextStyle(builder); style.bigText(content.preview); builder.setStyle(style); PendingIntent contentIntent = actionCreator.createViewMessagePendingIntent( content.messageReference, notificationId); builder.setContentIntent(contentIntent); return builder; } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); } | @Test public void testCreateBigTextStyleNotification() throws Exception { Account account = createFakeAccount(); int notificationId = 23; NotificationHolder holder = createNotificationHolder(notificationId); Builder builder = notifications.createBigTextStyleNotification(account, holder, notificationId); verify(builder).setTicker(NOTIFICATION_SUMMARY); verify(builder).setGroup("newMailNotifications-" + ACCOUNT_NUMBER); verify(builder).setContentTitle(SENDER); verify(builder).setContentText(SUBJECT); verify(builder).setSubText(ACCOUNT_NAME); BigTextStyle bigTextStyle = notifications.bigTextStyle; verify(bigTextStyle).bigText(NOTIFICATION_PREVIEW); verify(builder).setStyle(bigTextStyle); } |
WearNotifications extends BaseNotifications { public Notification buildStackedNotification(Account account, NotificationHolder holder) { int notificationId = holder.notificationId; NotificationContent content = holder.content; NotificationCompat.Builder builder = createBigTextStyleNotification(account, holder, notificationId); PendingIntent deletePendingIntent = actionCreator.createDismissMessagePendingIntent( context, content.messageReference, holder.notificationId); builder.setDeleteIntent(deletePendingIntent); addActions(builder, account, holder); return builder.build(); } WearNotifications(NotificationController controller, NotificationActionCreator actionCreator); Notification buildStackedNotification(Account account, NotificationHolder holder); void addSummaryActions(Builder builder, NotificationData notificationData); } | @Test public void testBuildStackedNotification() throws Exception { disableOptionalActions(); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); MessageReference messageReference = createMessageReference(1); NotificationContent content = createNotificationContent(messageReference); NotificationHolder holder = createNotificationHolder(notificationId, content); PendingIntent replyPendingIntent = createFakePendingIntent(1); when(actionCreator.createReplyPendingIntent(messageReference, notificationId)).thenReturn(replyPendingIntent); PendingIntent markAsReadPendingIntent = createFakePendingIntent(2); when(actionCreator.createMarkMessageAsReadPendingIntent(messageReference, notificationId)) .thenReturn(markAsReadPendingIntent); Notification result = wearNotifications.buildStackedNotification(account, holder); assertEquals(notification, result); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_single_message_options_dark, "Reply", replyPendingIntent); verifyAddAction(R.drawable.ic_action_mark_as_read_dark, "Mark Read", markAsReadPendingIntent); verifyNumberOfActions(2); }
@Test public void testBuildStackedNotificationWithDeleteActionEnabled() throws Exception { enableDeleteAction(); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); MessageReference messageReference = createMessageReference(1); NotificationContent content = createNotificationContent(messageReference); NotificationHolder holder = createNotificationHolder(notificationId, content); PendingIntent deletePendingIntent = createFakePendingIntent(1); when(actionCreator.createDeleteMessagePendingIntent(messageReference, notificationId)) .thenReturn(deletePendingIntent); Notification result = wearNotifications.buildStackedNotification(account, holder); assertEquals(notification, result); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_delete_dark, "Delete", deletePendingIntent); }
@Test public void testBuildStackedNotificationWithArchiveActionEnabled() throws Exception { enableArchiveAction(); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); MessageReference messageReference = createMessageReference(1); NotificationContent content = createNotificationContent(messageReference); NotificationHolder holder = createNotificationHolder(notificationId, content); PendingIntent archivePendingIntent = createFakePendingIntent(1); when(actionCreator.createArchiveMessagePendingIntent(messageReference, notificationId)) .thenReturn(archivePendingIntent); Notification result = wearNotifications.buildStackedNotification(account, holder); assertEquals(notification, result); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_archive_dark, "Archive", archivePendingIntent); }
@Test public void testBuildStackedNotificationWithMarkAsSpamActionEnabled() throws Exception { enableSpamAction(); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); MessageReference messageReference = createMessageReference(1); NotificationContent content = createNotificationContent(messageReference); NotificationHolder holder = createNotificationHolder(notificationId, content); PendingIntent markAsSpamPendingIntent = createFakePendingIntent(1); when(actionCreator.createMarkMessageAsSpamPendingIntent(messageReference, notificationId)) .thenReturn(markAsSpamPendingIntent); Notification result = wearNotifications.buildStackedNotification(account, holder); assertEquals(notification, result); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_spam_dark, "Spam", markAsSpamPendingIntent); } |
WearNotifications extends BaseNotifications { public void addSummaryActions(Builder builder, NotificationData notificationData) { NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); addMarkAllAsReadAction(wearableExtender, notificationData); if (isDeleteActionAvailableForWear()) { addDeleteAllAction(wearableExtender, notificationData); } Account account = notificationData.getAccount(); if (isArchiveActionAvailableForWear(account)) { addArchiveAllAction(wearableExtender, notificationData); } builder.extend(wearableExtender); } WearNotifications(NotificationController controller, NotificationActionCreator actionCreator); Notification buildStackedNotification(Account account, NotificationHolder holder); void addSummaryActions(Builder builder, NotificationData notificationData); } | @Test public void testAddSummaryActions() throws Exception { disableOptionalSummaryActions(); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); ArrayList<MessageReference> messageReferences = createMessageReferenceList(); NotificationData notificationData = createNotificationData(messageReferences); PendingIntent markAllAsReadPendingIntent = createFakePendingIntent(1); when(actionCreator.getMarkAllAsReadPendingIntent(account, messageReferences, notificationId)) .thenReturn(markAllAsReadPendingIntent); wearNotifications.addSummaryActions(builder, notificationData); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_mark_as_read_dark, "Mark All Read", markAllAsReadPendingIntent); verifyNumberOfActions(1); }
@Test public void testAddSummaryActionsWithDeleteAllActionEnabled() throws Exception { enableDeleteAction(); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); ArrayList<MessageReference> messageReferences = createMessageReferenceList(); NotificationData notificationData = createNotificationData(messageReferences); PendingIntent deletePendingIntent = createFakePendingIntent(1); when(actionCreator.getDeleteAllPendingIntent(account, messageReferences, notificationId)) .thenReturn(deletePendingIntent); wearNotifications.addSummaryActions(builder, notificationData); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_delete_dark, "Delete All", deletePendingIntent); }
@Test public void testAddSummaryActionsWithArchiveAllActionEnabled() throws Exception { enableArchiveAction(); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); ArrayList<MessageReference> messageReferences = createMessageReferenceList(); NotificationData notificationData = createNotificationData(messageReferences); PendingIntent archivePendingIntent = createFakePendingIntent(1); when(actionCreator.createArchiveAllPendingIntent(account, messageReferences, notificationId)) .thenReturn(archivePendingIntent); wearNotifications.addSummaryActions(builder, notificationData); verifyExtendWasOnlyCalledOnce(); verifyAddAction(R.drawable.ic_action_archive_dark, "Archive All", archivePendingIntent); } |
AuthenticationErrorNotifications { public void showAuthenticationErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_authentication_error_title); String text = context.getString(R.string.notification_authentication_error_text, account.getDescription()); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(R.drawable.notification_icon_warning) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setStyle(new BigTextStyle().bigText(text)) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } AuthenticationErrorNotifications(NotificationController controller); void showAuthenticationErrorNotification(Account account, boolean incoming); void clearAuthenticationErrorNotification(Account account, boolean incoming); } | @Test public void showAuthenticationErrorNotification_withIncomingServer_shouldCreateNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); authenticationErrorNotifications.showAuthenticationErrorNotification(account, INCOMING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertAuthenticationErrorNotificationContents(); }
@Test public void showAuthenticationErrorNotification_withOutgoingServer_shouldCreateNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); authenticationErrorNotifications.showAuthenticationErrorNotification(account, OUTGOING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertAuthenticationErrorNotificationContents(); } |
AuthenticationErrorNotifications { public void clearAuthenticationErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } AuthenticationErrorNotifications(NotificationController controller); void showAuthenticationErrorNotification(Account account, boolean incoming); void clearAuthenticationErrorNotification(Account account, boolean incoming); } | @Test public void clearAuthenticationErrorNotification_withIncomingServer_shouldCancelNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); authenticationErrorNotifications.clearAuthenticationErrorNotification(account, INCOMING); verify(notificationManager).cancel(notificationId); }
@Test public void clearAuthenticationErrorNotification_withOutgoingServer_shouldCancelNotification() throws Exception { int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); authenticationErrorNotifications.clearAuthenticationErrorNotification(account, OUTGOING); verify(notificationManager).cancel(notificationId); } |
NotificationContentCreator { public NotificationContent createFromMessage(Account account, LocalMessage message) { MessageReference messageReference = message.makeMessageReference(); String sender = getMessageSender(account, message); String displaySender = getMessageSenderForDisplay(sender); String subject = getMessageSubject(message); CharSequence preview = getMessagePreview(message); CharSequence summary = buildMessageSummary(sender, subject); boolean starred = message.isSet(Flag.FLAGGED); return new NotificationContent(messageReference, displaySender, subject, preview, summary, starred); } NotificationContentCreator(Context context); NotificationContent createFromMessage(Account account, LocalMessage message); } | @Test public void createFromMessage_withRegularMessage() throws Exception { NotificationContent content = contentCreator.createFromMessage(account, message); assertEquals(messageReference, content.messageReference); assertEquals(SENDER_NAME, content.sender); assertEquals(SUBJECT, content.subject); assertEquals(SUBJECT + "\n" + PREVIEW, content.preview.toString()); assertEquals(SENDER_NAME + " " + SUBJECT, content.summary.toString()); assertEquals(false, content.starred); }
@Test public void createFromMessage_withoutSubject() throws Exception { when(message.getSubject()).thenReturn(null); NotificationContent content = contentCreator.createFromMessage(account, message); String noSubject = "(No subject)"; assertEquals(noSubject, content.subject); assertEquals(PREVIEW, content.preview.toString()); assertEquals(SENDER_NAME + " " + noSubject, content.summary.toString()); }
@Test public void createFromMessage_withoutSender() throws Exception { when(message.getFrom()).thenReturn(null); NotificationContent content = contentCreator.createFromMessage(account, message); assertEquals("No sender", content.sender); assertEquals(SUBJECT, content.summary.toString()); }
@Test public void createFromMessage_withMessageFromSelf() throws Exception { when(account.isAnIdentity(any(Address[].class))).thenReturn(true); NotificationContent content = contentCreator.createFromMessage(account, message); String insteadOfSender = "To:Bob"; assertEquals(insteadOfSender, content.sender); assertEquals(insteadOfSender + " " + SUBJECT, content.summary.toString()); }
@Test public void createFromMessage_withStarredMessage() throws Exception { when(message.isSet(Flag.FLAGGED)).thenReturn(true); NotificationContent content = contentCreator.createFromMessage(account, message); assertEquals(true, content.starred); } |
LockScreenNotification { public void configureLockScreenNotification(Builder builder, NotificationData notificationData) { if (!NotificationController.platformSupportsLockScreenNotifications()) { return; } switch (QMail.getLockScreenNotificationVisibility()) { case NOTHING: { builder.setVisibility(NotificationCompat.VISIBILITY_SECRET); break; } case APP_NAME: { builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE); break; } case EVERYTHING: { builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); break; } case SENDERS: { Notification publicNotification = createPublicNotificationWithSenderList(notificationData); builder.setPublicVersion(publicNotification); break; } case MESSAGE_COUNT: { Notification publicNotification = createPublicNotificationWithNewMessagesCount(notificationData); builder.setPublicVersion(publicNotification); break; } } } LockScreenNotification(NotificationController controller); static LockScreenNotification newInstance(NotificationController controller); void configureLockScreenNotification(Builder builder, NotificationData notificationData); } | @Test public void configureLockScreenNotification_NOTHING() throws Exception { QMail.setLockScreenNotificationVisibility(LockScreenNotificationVisibility.NOTHING); lockScreenNotification.configureLockScreenNotification(builder, notificationData); verify(builder).setVisibility(NotificationCompat.VISIBILITY_SECRET); }
@Test public void configureLockScreenNotification_APP_NAME() throws Exception { QMail.setLockScreenNotificationVisibility(LockScreenNotificationVisibility.APP_NAME); lockScreenNotification.configureLockScreenNotification(builder, notificationData); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PRIVATE); }
@Test public void configureLockScreenNotification_EVERYTHING() throws Exception { QMail.setLockScreenNotificationVisibility(LockScreenNotificationVisibility.EVERYTHING); lockScreenNotification.configureLockScreenNotification(builder, notificationData); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); }
@Test public void configureLockScreenNotification_SENDERS_withSingleMessage() throws Exception { QMail.setLockScreenNotificationVisibility(LockScreenNotificationVisibility.SENDERS); String senderName = "[email protected]"; NotificationContent content = createNotificationContent(senderName); NotificationHolder holder = new NotificationHolder(42, content); when(notificationData.getNewMessagesCount()).thenReturn(1); when(notificationData.getUnreadMessageCount()).thenReturn(1); when(notificationData.getHolderForLatestNotification()).thenReturn(holder); lockScreenNotification.configureLockScreenNotification(builder, notificationData); verify(publicBuilder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(publicBuilder).setNumber(1); verify(publicBuilder).setContentTitle("1 new message"); verify(publicBuilder).setContentText(senderName); verify(builder).setPublicVersion(publicBuilder.build()); }
@Test public void configureLockScreenNotification_SENDERS_withMultipleMessages() throws Exception { QMail.setLockScreenNotificationVisibility(LockScreenNotificationVisibility.SENDERS); NotificationContent content1 = createNotificationContent("[email protected]"); NotificationContent content2 = createNotificationContent("Bob <[email protected]>"); NotificationContent content3 = createNotificationContent("\"Peter Lustig\" <[email protected]>"); when(notificationData.getNewMessagesCount()).thenReturn(NEW_MESSAGE_COUNT); when(notificationData.getUnreadMessageCount()).thenReturn(UNREAD_MESSAGE_COUNT); when(notificationData.getContentForSummaryNotification()).thenReturn( Arrays.asList(content1, content2, content3)); lockScreenNotification.configureLockScreenNotification(builder, notificationData); verify(publicBuilder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(publicBuilder).setNumber(UNREAD_MESSAGE_COUNT); verify(publicBuilder).setContentTitle(NEW_MESSAGE_COUNT + " new messages"); verify(publicBuilder).setContentText( "[email protected], Bob <[email protected]>, \"Peter Lustig\" <[email protected]>"); verify(builder).setPublicVersion(publicBuilder.build()); }
@Test public void configureLockScreenNotification_MESSAGE_COUNT() throws Exception { QMail.setLockScreenNotificationVisibility(LockScreenNotificationVisibility.MESSAGE_COUNT); when(notificationData.getNewMessagesCount()).thenReturn(NEW_MESSAGE_COUNT); when(notificationData.getUnreadMessageCount()).thenReturn(UNREAD_MESSAGE_COUNT); lockScreenNotification.configureLockScreenNotification(builder, notificationData); verify(publicBuilder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(publicBuilder).setNumber(UNREAD_MESSAGE_COUNT); verify(publicBuilder).setContentTitle(NEW_MESSAGE_COUNT + " new messages"); verify(publicBuilder).setContentText(ACCOUNT_NAME); verify(builder).setPublicVersion(publicBuilder.build()); } |
LockScreenNotification { String createCommaSeparatedListOfSenders(List<NotificationContent> contents) { Set<CharSequence> senders = new LinkedHashSet<CharSequence>(MAX_NUMBER_OF_SENDERS_IN_LOCK_SCREEN_NOTIFICATION); for (NotificationContent content : contents) { senders.add(content.sender); if (senders.size() == MAX_NUMBER_OF_SENDERS_IN_LOCK_SCREEN_NOTIFICATION) { break; } } return TextUtils.join(", ", senders); } LockScreenNotification(NotificationController controller); static LockScreenNotification newInstance(NotificationController controller); void configureLockScreenNotification(Builder builder, NotificationData notificationData); } | @Test public void createCommaSeparatedListOfSenders_withMoreSendersThanShouldBeDisplayed() throws Exception { NotificationContent content1 = createNotificationContent("[email protected]"); NotificationContent content2 = createNotificationContent("[email protected]"); NotificationContent content3 = createNotificationContent("[email protected]"); NotificationContent content4 = createNotificationContent("[email protected]"); NotificationContent content5 = createNotificationContent("[email protected]"); NotificationContent content6 = createNotificationContent("[email protected]"); String result = lockScreenNotification.createCommaSeparatedListOfSenders( Arrays.asList(content1, content2, content3, content4, content5, content6)); assertEquals( "[email protected], [email protected], [email protected], [email protected], [email protected]", result); } |
NotificationIds { public static int getNewMailSummaryNotificationId(Account account) { return getBaseNotificationId(account) + OFFSET_NEW_MAIL_SUMMARY; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); } | @Test public void getNewMailSummaryNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); assertEquals(6, notificationId); }
@Test public void getNewMailSummaryNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); assertEquals(21, notificationId); } |
NotificationIds { public static int getNewMailStackedNotificationId(Account account, int index) { if (index < 0 || index >= NUMBER_OF_STACKED_NOTIFICATIONS) { throw new IndexOutOfBoundsException("Invalid value: " + index); } return getBaseNotificationId(account) + OFFSET_NEW_MAIL_STACKED + index; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); } | @Test public void getNewMailStackedNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); assertEquals(7, notificationId); }
@Test(expected = IndexOutOfBoundsException.class) public void getNewMailStackedNotificationId_withTooLowIndex() throws Exception { Account account = createMockAccountWithAccountNumber(0); NotificationIds.getNewMailStackedNotificationId(account, -1); }
@Test(expected = IndexOutOfBoundsException.class) public void getNewMailStackedNotificationId_withTooLargeIndex() throws Exception { Account account = createMockAccountWithAccountNumber(0); NotificationIds.getNewMailStackedNotificationId(account, 8); }
@Test public void getNewMailStackedNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationIndex = 7; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); assertEquals(29, notificationId); } |
MessageCryptoStructureDetector { public static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations) { List<Part> signedParts = new ArrayList<>(); Stack<Part> partsToCheck = new Stack<>(); partsToCheck.push(startPart); while (!partsToCheck.isEmpty()) { Part part = partsToCheck.pop(); if (messageCryptoAnnotations.has(part)) { CryptoResultAnnotation resultAnnotation = messageCryptoAnnotations.get(part); MimeBodyPart replacementData = resultAnnotation.getReplacementData(); if (replacementData != null) { part = replacementData; } } Body body = part.getBody(); if (isPartMultipartSigned(part)) { signedParts.add(part); continue; } if (body instanceof Multipart) { Multipart multipart = (Multipart) body; for (int i = multipart.getCount() - 1; i >= 0; i--) { BodyPart bodyPart = multipart.getBodyPart(i); partsToCheck.push(bodyPart); } } } return signedParts; } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findMultipartEncryptedParts(Part startPart); static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPartMultipartEncrypted(Part part); static boolean isMultipartEncryptedOpenPgpProtocol(Part part); static boolean isMultipartSignedOpenPgpProtocol(Part part); static boolean isMultipartEncryptedSMimeProtocol(Part part); static boolean isMultipartSignedSMimeProtocol(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); } | @Test public void findSigned__withSimpleMultipartSigned__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain"), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(message, signedParts.get(0)); }
@Test public void findSigned__withNoProtocolAndNoBody__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(message, signedParts.get(0)); }
@Test public void findSigned__withBadProtocol__shouldReturnNothing() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/not-pgp-signature\"", bodypart("text/plain", "content"), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertTrue(signedParts.isEmpty()); }
@Test public void findSigned__withEmptyProtocol__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", bodypart("text/plain", "content"), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertTrue(signedParts.isEmpty()); }
@Test public void findSigned__withMissingSignature__shouldReturnEmpty() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertTrue(signedParts.isEmpty()); }
@Test public void findSigned__withComplexMultipartSigned__shouldReturnRoot() throws Exception { Message message = messageFromBody( multipart("signed", "protocol=\"application/pgp-signature\"", multipart("mixed", bodypart("text/plain"), bodypart("application/pdf") ), bodypart("application/pgp-signature") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(message, signedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubSigned__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("signed", "protocol=\"application/pgp-signature\"", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 0), signedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubSignedAndText__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", multipart("signed", "application/pgp-signature", bodypart("text/plain"), bodypart("application/pgp-signature") ), bodypart("text/plain") ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 0), signedParts.get(0)); }
@Test public void findEncrypted__withMultipartMixedSubTextAndSigned__shouldReturnSigned() throws Exception { Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("signed", "application/pgp-signature", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); List<Part> signedParts = MessageCryptoStructureDetector .findMultipartSignedParts(message, messageCryptoAnnotations); assertEquals(1, signedParts.size()); assertSame(getPart(message, 1), signedParts.get(0)); } |
NotificationIds { public static int getFetchingMailNotificationId(Account account) { return getBaseNotificationId(account) + OFFSET_FETCHING_MAIL; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); } | @Test public void getFetchingMailNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getFetchingMailNotificationId(account); assertEquals(5, notificationId); }
@Test public void getFetchingMailNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getFetchingMailNotificationId(account); assertEquals(20, notificationId); } |
NotificationIds { public static int getSendFailedNotificationId(Account account) { return getBaseNotificationId(account) + OFFSET_SEND_FAILED_NOTIFICATION; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); } | @Test public void getSendFailedNotificationId_withDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getSendFailedNotificationId(account); assertEquals(0, notificationId); }
@Test public void getSendFailedNotificationId_withSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getSendFailedNotificationId(account); assertEquals(15, notificationId); } |
NotificationIds { public static int getCertificateErrorNotificationId(Account account, boolean incoming) { int offset = incoming ? OFFSET_CERTIFICATE_ERROR_INCOMING : OFFSET_CERTIFICATE_ERROR_OUTGOING; return getBaseNotificationId(account) + offset; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); } | @Test public void getCertificateErrorNotificationId_forIncomingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); assertEquals(1, notificationId); }
@Test public void getCertificateErrorNotificationId_forIncomingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); assertEquals(16, notificationId); }
@Test public void getCertificateErrorNotificationId_forOutgoingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); assertEquals(2, notificationId); }
@Test public void getCertificateErrorNotificationId_forOutgoingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); assertEquals(17, notificationId); } |
NotificationIds { public static int getAuthenticationErrorNotificationId(Account account, boolean incoming) { int offset = incoming ? OFFSET_AUTHENTICATION_ERROR_INCOMING : OFFSET_AUTHENTICATION_ERROR_OUTGOING; return getBaseNotificationId(account) + offset; } static int getNewMailSummaryNotificationId(Account account); static int getNewMailStackedNotificationId(Account account, int index); static int getFetchingMailNotificationId(Account account); static int getSendFailedNotificationId(Account account); static int getCertificateErrorNotificationId(Account account, boolean incoming); static int getAuthenticationErrorNotificationId(Account account, boolean incoming); } | @Test public void getAuthenticationErrorNotificationId_forIncomingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); assertEquals(3, notificationId); }
@Test public void getAuthenticationErrorNotificationId_forIncomingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, INCOMING); assertEquals(18, notificationId); }
@Test public void getAuthenticationErrorNotificationId_forOutgoingServerWithDefaultAccount() throws Exception { Account account = createMockAccountWithAccountNumber(0); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); assertEquals(4, notificationId); }
@Test public void getAuthenticationErrorNotificationId_forOutgoingServerWithSecondAccount() throws Exception { Account account = createMockAccountWithAccountNumber(1); int notificationId = NotificationIds.getAuthenticationErrorNotificationId(account, OUTGOING); assertEquals(19, notificationId); } |
DeviceNotifications extends BaseNotifications { public Notification buildSummaryNotification(Account account, NotificationData notificationData, boolean silent) { int unreadMessageCount = notificationData.getUnreadMessageCount(); NotificationCompat.Builder builder; if (isPrivacyModeActive() || !platformSupportsExtendedNotifications()) { builder = createSimpleSummaryNotification(account, unreadMessageCount); } else if (notificationData.isSingleMessageNotification()) { NotificationHolder holder = notificationData.getHolderForLatestNotification(); builder = createBigTextStyleSummaryNotification(account, holder); } else { builder = createInboxStyleSummaryNotification(account, notificationData, unreadMessageCount); } if (notificationData.containsStarredMessages()) { builder.setPriority(NotificationCompat.PRIORITY_HIGH); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); PendingIntent deletePendingIntent = actionCreator.createDismissAllMessagesPendingIntent( account, notificationId); builder.setDeleteIntent(deletePendingIntent); lockScreenNotification.configureLockScreenNotification(builder, notificationData); boolean ringAndVibrate = false; if (!silent && !account.isRingNotified()) { account.setRingNotified(true); ringAndVibrate = true; } NotificationSetting notificationSetting = account.getNotificationSetting(); controller.configureNotification( builder, (notificationSetting.isRingEnabled()) ? notificationSetting.getRingtone() : null, (notificationSetting.isVibrateEnabled()) ? notificationSetting.getVibration() : null, (notificationSetting.isLedEnabled()) ? notificationSetting.getLedColor() : null, NOTIFICATION_LED_BLINK_SLOW, ringAndVibrate); return builder.build(); } DeviceNotifications(NotificationController controller, NotificationActionCreator actionCreator,
LockScreenNotification lockScreenNotification, WearNotifications wearNotifications); static DeviceNotifications newInstance(NotificationController controller,
NotificationActionCreator actionCreator, WearNotifications wearNotifications); Notification buildSummaryNotification(Account account, NotificationData notificationData,
boolean silent); } | @Test public void buildSummaryNotification_withPrivacyModeActive() throws Exception { QMail.setNotificationHideSubject(NotificationHideSubject.ALWAYS); Notification result = notifications.buildSummaryNotification(account, notificationData, false); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setColor(ACCOUNT_COLOR); verify(builder).setAutoCancel(true); verify(builder).setNumber(UNREAD_MESSAGE_COUNT); verify(builder).setTicker("New mail"); verify(builder).setContentText("New mail"); verify(builder).setContentTitle(UNREAD_MESSAGE_COUNT + " Unread (" + ACCOUNT_NAME + ")"); verify(lockScreenNotification).configureLockScreenNotification(builder, notificationData); assertEquals(FAKE_NOTIFICATION, result); }
@Test public void buildSummaryNotification_withSingleMessageNotification() throws Exception { QMail.setNotificationHideSubject(NotificationHideSubject.NEVER); QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.ALWAYS); when(notificationData.isSingleMessageNotification()).thenReturn(true); Notification result = notifications.buildSummaryNotification(account, notificationData, false); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setColor(ACCOUNT_COLOR); verify(builder).setAutoCancel(true); verify(builder).setTicker(SUMMARY); verify(builder).setContentText(SUBJECT); verify(builder).setContentTitle(SENDER); verify(builder).setStyle(notifications.bigTextStyle); verify(notifications.bigTextStyle).bigText(PREVIEW); verify(builder).addAction(R.drawable.notification_action_reply, "Reply", null); verify(builder).addAction(R.drawable.notification_action_mark_as_read, "Mark Read", null); verify(builder).addAction(R.drawable.notification_action_delete, "Delete", null); verify(lockScreenNotification).configureLockScreenNotification(builder, notificationData); assertEquals(FAKE_NOTIFICATION, result); }
@Test public void buildSummaryNotification_withMultiMessageNotification() throws Exception { QMail.setNotificationHideSubject(NotificationHideSubject.NEVER); QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.ALWAYS); when(notificationData.isSingleMessageNotification()).thenReturn(false); when(notificationData.containsStarredMessages()).thenReturn(true); Notification result = notifications.buildSummaryNotification(account, notificationData, false); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setColor(ACCOUNT_COLOR); verify(builder).setAutoCancel(true); verify(builder).setTicker(SUMMARY); verify(builder).setContentTitle(NEW_MESSAGE_COUNT + " new messages"); verify(builder).setSubText(ACCOUNT_NAME); verify(builder).setGroup("newMailNotifications-" + ACCOUNT_NUMBER); verify(builder).setGroupSummary(true); verify(builder).setPriority(NotificationCompat.PRIORITY_HIGH); verify(builder).setStyle(notifications.inboxStyle); verify(notifications.inboxStyle).setBigContentTitle(NEW_MESSAGE_COUNT + " new messages"); verify(notifications.inboxStyle).setSummaryText(ACCOUNT_NAME); verify(notifications.inboxStyle).addLine(SUMMARY); verify(notifications.inboxStyle).addLine(SUMMARY_2); verify(builder).addAction(R.drawable.notification_action_mark_as_read, "Mark Read", null); verify(builder).addAction(R.drawable.notification_action_delete, "Delete", null); verify(lockScreenNotification).configureLockScreenNotification(builder, notificationData); assertEquals(FAKE_NOTIFICATION, result); }
@Test public void buildSummaryNotification_withAdditionalMessages() throws Exception { QMail.setNotificationHideSubject(NotificationHideSubject.NEVER); QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.ALWAYS); when(notificationData.isSingleMessageNotification()).thenReturn(false); when(notificationData.hasSummaryOverflowMessages()).thenReturn(true); when(notificationData.getSummaryOverflowMessagesCount()).thenReturn(23); notifications.buildSummaryNotification(account, notificationData, false); verify(notifications.inboxStyle).setSummaryText("+ 23 more on " + ACCOUNT_NAME); }
@Test public void buildSummaryNotification_withoutDeleteAllAction() throws Exception { QMail.setNotificationHideSubject(NotificationHideSubject.NEVER); QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.NEVER); when(notificationData.isSingleMessageNotification()).thenReturn(false); notifications.buildSummaryNotification(account, notificationData, false); verify(builder, never()).addAction(R.drawable.notification_action_delete, "Delete", null); }
@Test public void buildSummaryNotification_withoutDeleteAction() throws Exception { QMail.setNotificationHideSubject(NotificationHideSubject.NEVER); QMail.setNotificationQuickDeleteBehaviour(NotificationQuickDelete.NEVER); when(notificationData.isSingleMessageNotification()).thenReturn(true); notifications.buildSummaryNotification(account, notificationData, false); verify(builder, never()).addAction(R.drawable.notification_action_delete, "Delete", null); } |
SyncNotifications { public void showSendingNotification(Account account) { Context context = controller.getContext(); String accountName = controller.getAccountName(account); String title = context.getString(R.string.notification_bg_send_title); String tickerText = context.getString(R.string.notification_bg_send_ticker, accountName); int notificationId = NotificationIds.getFetchingMailNotificationId(account); String outboxFolderName = account.getOutboxFolderId(); PendingIntent showMessageListPendingIntent = actionBuilder.createViewFolderPendingIntent( account, outboxFolderName, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(R.drawable.ic_notify_check_mail) .setWhen(System.currentTimeMillis()) .setOngoing(true) .setTicker(tickerText) .setContentTitle(title) .setContentText(accountName) .setContentIntent(showMessageListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); if (NOTIFICATION_LED_WHILE_SYNCING) { controller.configureNotification(builder, null, null, account.getNotificationSetting().getLedColor(), NOTIFICATION_LED_BLINK_FAST, true); } getNotificationManager().notify(notificationId, builder.build()); } SyncNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendingNotification(Account account); void clearSendingNotification(Account account); void showFetchingMailNotification(Account account, Folder folder); void clearFetchingMailNotification(Account account); } | @Test public void testShowSendingNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.showSendingNotification(account); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); verify(builder).setSmallIcon(R.drawable.ic_notify_check_mail); verify(builder).setTicker("Sending mail: " + ACCOUNT_NAME); verify(builder).setContentTitle("Sending mail"); verify(builder).setContentText(ACCOUNT_NAME); verify(builder).setContentIntent(contentIntent); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); } |
SyncNotifications { public void clearSendingNotification(Account account) { int notificationId = NotificationIds.getFetchingMailNotificationId(account); getNotificationManager().cancel(notificationId); } SyncNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendingNotification(Account account); void clearSendingNotification(Account account); void showFetchingMailNotification(Account account, Folder folder); void clearFetchingMailNotification(Account account); } | @Test public void testClearSendingNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.clearSendingNotification(account); verify(notificationManager).cancel(notificationId); } |
SyncNotifications { public void showFetchingMailNotification(Account account, Folder folder) { String accountName = account.getDescription(); String folderName = folder.getId(); Context context = controller.getContext(); String tickerText = context.getString(R.string.notification_bg_sync_ticker, accountName, folderName); String title = context.getString(R.string.notification_bg_sync_title); String text = accountName + context.getString(R.string.notification_bg_title_separator) + folderName; int notificationId = NotificationIds.getFetchingMailNotificationId(account); PendingIntent showMessageListPendingIntent = actionBuilder.createViewFolderPendingIntent( account, folderName, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(R.drawable.ic_notify_check_mail) .setWhen(System.currentTimeMillis()) .setOngoing(true) .setTicker(tickerText) .setContentTitle(title) .setContentText(text) .setContentIntent(showMessageListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_SERVICE); if (NOTIFICATION_LED_WHILE_SYNCING) { controller.configureNotification(builder, null, null, account.getNotificationSetting().getLedColor(), NOTIFICATION_LED_BLINK_FAST, true); } getNotificationManager().notify(notificationId, builder.build()); } SyncNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendingNotification(Account account); void clearSendingNotification(Account account); void showFetchingMailNotification(Account account, Folder folder); void clearFetchingMailNotification(Account account); } | @Test public void testGetFetchingMailNotificationId() throws Exception { Folder folder = createFakeFolder(); int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.showFetchingMailNotification(account, folder); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); verify(builder).setSmallIcon(R.drawable.ic_notify_check_mail); verify(builder).setTicker("Checking mail: " + ACCOUNT_NAME + ":" + FOLDER_NAME); verify(builder).setContentTitle("Checking mail"); verify(builder).setContentText(ACCOUNT_NAME + ":" + FOLDER_NAME); verify(builder).setContentIntent(contentIntent); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); } |
SyncNotifications { public void clearFetchingMailNotification(Account account) { int notificationId = NotificationIds.getFetchingMailNotificationId(account); getNotificationManager().cancel(notificationId); } SyncNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendingNotification(Account account); void clearSendingNotification(Account account); void showFetchingMailNotification(Account account, Folder folder); void clearFetchingMailNotification(Account account); } | @Test public void testClearSendFailedNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.clearFetchingMailNotification(account); verify(notificationManager).cancel(notificationId); } |
SendFailedNotifications { public void showSendFailedNotification(Account account, Exception exception) { Context context = controller.getContext(); String title = context.getString(R.string.send_failure_subject); String text = ExceptionHelper.getRootCauseMessage(exception); int notificationId = NotificationIds.getSendFailedNotificationId(account); PendingIntent folderListPendingIntent = actionBuilder.createViewFolderListPendingIntent( account, notificationId); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getSendFailedNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(folderListPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); } | @Test public void testShowSendFailedNotification() throws Exception { Exception exception = new Exception(); sendFailedNotifications.showSendFailedNotification(account, exception); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); verify(builder).setSmallIcon(R.drawable.notification_icon_new_mail); verify(builder).setTicker("Failed to send some messages"); verify(builder).setContentTitle("Failed to send some messages"); verify(builder).setContentText("Exception"); verify(builder).setContentIntent(contentIntent); verify(builder).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); } |
SendFailedNotifications { public void clearSendFailedNotification(Account account) { int notificationId = NotificationIds.getSendFailedNotificationId(account); getNotificationManager().cancel(notificationId); } SendFailedNotifications(NotificationController controller, NotificationActionCreator actionBuilder); void showSendFailedNotification(Account account, Exception exception); void clearSendFailedNotification(Account account); } | @Test public void testClearSendFailedNotification() throws Exception { sendFailedNotifications.clearSendFailedNotification(account); verify(notificationManager).cancel(notificationId); } |
NotificationData { public AddNotificationResult addNotificationContent(NotificationContent content) { int notificationId; boolean cancelNotificationIdBeforeReuse; if (isMaxNumberOfActiveNotificationsReached()) { NotificationHolder notificationHolder = activeNotifications.removeLast(); addToAdditionalNotifications(notificationHolder); notificationId = notificationHolder.notificationId; cancelNotificationIdBeforeReuse = true; } else { notificationId = getNewNotificationId(); cancelNotificationIdBeforeReuse = false; } NotificationHolder notificationHolder = createNotificationHolder(notificationId, content); activeNotifications.addFirst(notificationHolder); if (cancelNotificationIdBeforeReuse) { return AddNotificationResult.replaceNotification(notificationHolder); } else { return AddNotificationResult.newNotification(notificationHolder); } } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testAddNotificationContent() throws Exception { NotificationContent content = createNotificationContent("1"); AddNotificationResult result = notificationData.addNotificationContent(content); assertFalse(result.shouldCancelNotification()); NotificationHolder holder = result.getNotificationHolder(); assertNotNull(holder); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), holder.notificationId); assertEquals(content, holder.content); }
@Test public void testAddNotificationContentWithReplacingNotification() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); notificationData.addNotificationContent(createNotificationContent("2")); notificationData.addNotificationContent(createNotificationContent("3")); notificationData.addNotificationContent(createNotificationContent("4")); notificationData.addNotificationContent(createNotificationContent("5")); notificationData.addNotificationContent(createNotificationContent("6")); notificationData.addNotificationContent(createNotificationContent("7")); notificationData.addNotificationContent(createNotificationContent("8")); AddNotificationResult result = notificationData.addNotificationContent(createNotificationContent("9")); assertTrue(result.shouldCancelNotification()); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), result.getNotificationId()); } |
NotificationData { public RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference) { NotificationHolder holder = getNotificationHolderForMessage(messageReference); if (holder == null) { return RemoveNotificationResult.unknownNotification(); } activeNotifications.remove(holder); int notificationId = holder.notificationId; markNotificationIdAsFree(notificationId); if (!additionalNotifications.isEmpty()) { NotificationContent newContent = additionalNotifications.removeFirst(); NotificationHolder replacement = createNotificationHolder(notificationId, newContent); activeNotifications.addLast(replacement); return RemoveNotificationResult.createNotification(replacement); } return RemoveNotificationResult.cancelNotification(notificationId); } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testRemoveNotificationForMessage() throws Exception { NotificationContent content = createNotificationContent("1"); notificationData.addNotificationContent(content); RemoveNotificationResult result = notificationData.removeNotificationForMessage(content.messageReference); assertFalse(result.isUnknownNotification()); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), result.getNotificationId()); assertFalse(result.shouldCreateNotification()); } |
NotificationData { public boolean containsStarredMessages() { for (NotificationHolder holder : activeNotifications) { if (holder.content.starred) { return true; } } for (NotificationContent content : additionalNotifications) { if (content.starred) { return true; } } return false; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testContainsStarredMessages() throws Exception { assertFalse(notificationData.containsStarredMessages()); notificationData.addNotificationContent(createNotificationContentForStarredMessage()); assertTrue(notificationData.containsStarredMessages()); } |
NotificationData { public boolean isSingleMessageNotification() { return activeNotifications.size() == 1; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testIsSingleMessageNotification() throws Exception { assertFalse(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("1")); assertTrue(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("2")); assertFalse(notificationData.isSingleMessageNotification()); } |
NotificationData { public List<NotificationContent> getContentForSummaryNotification() { int size = calculateNumberOfMessagesForSummaryNotification(); List<NotificationContent> result = new ArrayList<NotificationContent>(size); Iterator<NotificationHolder> iterator = activeNotifications.iterator(); int notificationCount = 0; while (iterator.hasNext() && notificationCount < MAX_NUMBER_OF_MESSAGES_FOR_SUMMARY_NOTIFICATION) { NotificationHolder holder = iterator.next(); result.add(holder.content); notificationCount++; } return result; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testGetContentForSummaryNotification() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); NotificationContent content4 = createNotificationContent("2"); notificationData.addNotificationContent(content4); NotificationContent content3 = createNotificationContent("3"); notificationData.addNotificationContent(content3); NotificationContent content2 = createNotificationContent("4"); notificationData.addNotificationContent(content2); NotificationContent content1 = createNotificationContent("5"); notificationData.addNotificationContent(content1); NotificationContent content0 = createNotificationContent("6"); notificationData.addNotificationContent(content0); List<NotificationContent> contents = notificationData.getContentForSummaryNotification(); assertEquals(5, contents.size()); assertEquals(content0, contents.get(0)); assertEquals(content1, contents.get(1)); assertEquals(content2, contents.get(2)); assertEquals(content3, contents.get(3)); assertEquals(content4, contents.get(4)); } |
NotificationData { public int[] getActiveNotificationIds() { int size = activeNotifications.size(); int[] notificationIds = new int[size]; for (int i = 0; i < size; i++) { NotificationHolder holder = activeNotifications.get(i); notificationIds[i] = holder.notificationId; } return notificationIds; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testGetActiveNotificationIds() throws Exception { notificationData.addNotificationContent(createNotificationContent("1")); notificationData.addNotificationContent(createNotificationContent("2")); int[] notificationIds = notificationData.getActiveNotificationIds(); assertEquals(2, notificationIds.length); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 1), notificationIds[0]); assertEquals(NotificationIds.getNewMailStackedNotificationId(account, 0), notificationIds[1]); } |
NotificationData { public Account getAccount() { return account; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testGetAccount() throws Exception { assertEquals(account, notificationData.getAccount()); } |
NotificationData { public ArrayList<MessageReference> getAllMessageReferences() { int newSize = activeNotifications.size() + additionalNotifications.size(); ArrayList<MessageReference> messageReferences = new ArrayList<MessageReference>(newSize); for (NotificationHolder holder : activeNotifications) { messageReferences.add(holder.content.messageReference); } for (NotificationContent content : additionalNotifications) { messageReferences.add(content.messageReference); } return messageReferences; } NotificationData(Account account); AddNotificationResult addNotificationContent(NotificationContent content); boolean containsStarredMessages(); boolean hasSummaryOverflowMessages(); int getSummaryOverflowMessagesCount(); int getNewMessagesCount(); boolean isSingleMessageNotification(); NotificationHolder getHolderForLatestNotification(); List<NotificationContent> getContentForSummaryNotification(); int[] getActiveNotificationIds(); RemoveNotificationResult removeNotificationForMessage(MessageReference messageReference); Account getAccount(); int getUnreadMessageCount(); void setUnreadMessageCount(int unreadMessageCount); ArrayList<MessageReference> getAllMessageReferences(); } | @Test public void testGetAllMessageReferences() throws Exception { MessageReference messageReference0 = createMessageReference("1"); MessageReference messageReference1 = createMessageReference("2"); MessageReference messageReference2 = createMessageReference("3"); MessageReference messageReference3 = createMessageReference("4"); MessageReference messageReference4 = createMessageReference("5"); MessageReference messageReference5 = createMessageReference("6"); MessageReference messageReference6 = createMessageReference("7"); MessageReference messageReference7 = createMessageReference("8"); MessageReference messageReference8 = createMessageReference("9"); notificationData.addNotificationContent(createNotificationContent(messageReference8)); notificationData.addNotificationContent(createNotificationContent(messageReference7)); notificationData.addNotificationContent(createNotificationContent(messageReference6)); notificationData.addNotificationContent(createNotificationContent(messageReference5)); notificationData.addNotificationContent(createNotificationContent(messageReference4)); notificationData.addNotificationContent(createNotificationContent(messageReference3)); notificationData.addNotificationContent(createNotificationContent(messageReference2)); notificationData.addNotificationContent(createNotificationContent(messageReference1)); notificationData.addNotificationContent(createNotificationContent(messageReference0)); List<MessageReference> messageReferences = notificationData.getAllMessageReferences(); assertEquals(9, messageReferences.size()); assertEquals(messageReference0, messageReferences.get(0)); assertEquals(messageReference1, messageReferences.get(1)); assertEquals(messageReference2, messageReferences.get(2)); assertEquals(messageReference3, messageReferences.get(3)); assertEquals(messageReference4, messageReferences.get(4)); assertEquals(messageReference5, messageReferences.get(5)); assertEquals(messageReference6, messageReferences.get(6)); assertEquals(messageReference7, messageReferences.get(7)); assertEquals(messageReference8, messageReferences.get(8)); } |
NewMailNotifications { public void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount) { NotificationContent content = contentCreator.createFromMessage(account, message); synchronized (lock) { NotificationData notificationData = getOrCreateNotificationData(account, unreadMessageCount); AddNotificationResult result = notificationData.addNotificationContent(content); if (result.shouldCancelNotification()) { int notificationId = result.getNotificationId(); cancelNotification(notificationId); } createStackedNotification(account, result.getNotificationHolder()); createSummaryNotification(account, notificationData, false); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator,
DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller,
NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); } | @Test public void testAddNewMailNotification() throws Exception { int notificationIndex = 0; LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); Notification wearNotification = createNotification(); Notification summaryNotification = createNotification(); addToWearNotifications(holder, wearNotification); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, message, 42); int wearNotificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).notify(wearNotificationId, wearNotification); verify(notificationManager).notify(summaryNotificationId, summaryNotification); }
@Test public void testAddNewMailNotificationWithCancelingExistingNotification() throws Exception { int notificationIndex = 0; LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.replaceNotification(holder)); Notification wearNotification = createNotification(); Notification summaryNotification = createNotification(); addToWearNotifications(holder, wearNotification); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, message, 42); int wearNotificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).notify(wearNotificationId, wearNotification); verify(notificationManager).cancel(wearNotificationId); verify(notificationManager).notify(summaryNotificationId, summaryNotification); }
@Test public void testAddNewMailNotificationWithPrivacyModeEnabled() throws Exception { enablePrivacyMode(); int notificationIndex = 0; LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); Notification wearNotification = createNotification(); addToDeviceNotifications(wearNotification); newMailNotifications.addNewMailNotification(account, message, 42); int wearNotificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager, never()).notify(eq(wearNotificationId), any(Notification.class)); verify(notificationManager).notify(summaryNotificationId, wearNotification); }
@Test public void testAddNewMailNotificationTwice() throws Exception { int notificationIndexOne = 0; int notificationIndexTwo = 1; LocalMessage messageOne = createLocalMessage(); LocalMessage messageTwo = createLocalMessage(); NotificationContent contentOne = createNotificationContent(); NotificationContent contentTwo = createNotificationContent(); NotificationHolder holderOne = createNotificationHolder(contentOne, notificationIndexOne); NotificationHolder holderTwo = createNotificationHolder(contentTwo, notificationIndexTwo); addToNotificationContentCreator(messageOne, contentOne); addToNotificationContentCreator(messageTwo, contentTwo); whenAddingContentReturn(contentOne, AddNotificationResult.newNotification(holderOne)); whenAddingContentReturn(contentTwo, AddNotificationResult.newNotification(holderTwo)); Notification wearNotificationOne = createNotification(); Notification wearNotificationTwo = createNotification(); Notification summaryNotification = createNotification(); addToWearNotifications(holderOne, wearNotificationOne); addToWearNotifications(holderTwo, wearNotificationTwo); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, messageOne, 42); newMailNotifications.addNewMailNotification(account, messageTwo, 42); int wearNotificationIdOne = NotificationIds.getNewMailStackedNotificationId(account, notificationIndexOne); int wearNotificationIdTwo = NotificationIds.getNewMailStackedNotificationId(account, notificationIndexTwo); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).notify(wearNotificationIdOne, wearNotificationOne); verify(notificationManager).notify(wearNotificationIdTwo, wearNotificationTwo); verify(notificationManager, times(2)).notify(summaryNotificationId, summaryNotification); } |
NewMailNotifications { public void removeNewMailNotification(Account account, MessageReference messageReference) { synchronized (lock) { NotificationData notificationData = getNotificationData(account); if (notificationData == null) { return; } RemoveNotificationResult result = notificationData.removeNotificationForMessage(messageReference); if (result.isUnknownNotification()) { return; } cancelNotification(result.getNotificationId()); if (result.shouldCreateNotification()) { createStackedNotification(account, result.getNotificationHolder()); } updateSummaryNotification(account, notificationData); } } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator,
DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller,
NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); } | @Test public void testRemoveNewMailNotificationWithoutNotificationData() throws Exception { MessageReference messageReference = createMessageReference(1); newMailNotifications.removeNewMailNotification(account, messageReference); verify(notificationManager, never()).cancel(anyInt()); }
@Test public void testRemoveNewMailNotification() throws Exception { enablePrivacyMode(); MessageReference messageReference = createMessageReference(1); int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); Notification summaryNotification = createNotification(); addToDeviceNotifications(summaryNotification); newMailNotifications.addNewMailNotification(account, message, 23); whenRemovingContentReturn(messageReference, RemoveNotificationResult.cancelNotification(notificationId)); newMailNotifications.removeNewMailNotification(account, messageReference); int summaryNotificationId = NotificationIds.getNewMailSummaryNotificationId(account); verify(notificationManager).cancel(notificationId); verify(notificationManager, times(2)).notify(summaryNotificationId, summaryNotification); } |
NewMailNotifications { public void clearNewMailNotifications(Account account) { NotificationData notificationData; synchronized (lock) { notificationData = removeNotificationData(account); } if (notificationData == null) { return; } for (int notificationId : notificationData.getActiveNotificationIds()) { cancelNotification(notificationId); } int notificationId = NotificationIds.getNewMailSummaryNotificationId(account); cancelNotification(notificationId); } NewMailNotifications(NotificationController controller, NotificationContentCreator contentCreator,
DeviceNotifications deviceNotifications, WearNotifications wearNotifications); static NewMailNotifications newInstance(NotificationController controller,
NotificationActionCreator actionCreator); void addNewMailNotification(Account account, LocalMessage message, int unreadMessageCount); void removeNewMailNotification(Account account, MessageReference messageReference); void clearNewMailNotifications(Account account); } | @Test public void testClearNewMailNotificationsWithoutNotificationData() throws Exception { newMailNotifications.clearNewMailNotifications(account); verify(notificationManager, never()).cancel(anyInt()); }
@Test public void testClearNewMailNotifications() throws Exception { int notificationIndex = 0; int notificationId = NotificationIds.getNewMailStackedNotificationId(account, notificationIndex); LocalMessage message = createLocalMessage(); NotificationContent content = createNotificationContent(); NotificationHolder holder = createNotificationHolder(content, notificationIndex); addToNotificationContentCreator(message, content); setActiveNotificationIds(notificationId); whenAddingContentReturn(content, AddNotificationResult.newNotification(holder)); newMailNotifications.addNewMailNotification(account, message, 3); newMailNotifications.clearNewMailNotifications(account); verify(notificationManager).cancel(notificationId); verify(notificationManager).cancel(NotificationIds.getNewMailSummaryNotificationId(account)); } |
CertificateErrorNotifications { public void showCertificateErrorNotification(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); Context context = controller.getContext(); PendingIntent editServerSettingsPendingIntent = createContentIntent(context, account, incoming); String title = context.getString(R.string.notification_certificate_error_title, account.getDescription()); String text = context.getString(R.string.notification_certificate_error_text); NotificationCompat.Builder builder = controller.createNotificationBuilder() .setSmallIcon(getCertificateErrorNotificationIcon()) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setTicker(title) .setContentTitle(title) .setContentText(text) .setContentIntent(editServerSettingsPendingIntent) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_ERROR); controller.configureNotification(builder, null, null, NOTIFICATION_LED_FAILURE_COLOR, NOTIFICATION_LED_BLINK_FAST, true); getNotificationManager().notify(notificationId, builder.build()); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); } | @Test public void testShowCertificateErrorNotificationForIncomingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); certificateErrorNotifications.showCertificateErrorNotification(account, INCOMING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertCertificateErrorNotificationContents(); }
@Test public void testShowCertificateErrorNotificationForOutgoingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); certificateErrorNotifications.showCertificateErrorNotification(account, OUTGOING); verify(notificationManager).notify(eq(notificationId), any(Notification.class)); assertCertificateErrorNotificationContents(); } |
CertificateErrorNotifications { public void clearCertificateErrorNotifications(Account account, boolean incoming) { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, incoming); getNotificationManager().cancel(notificationId); } CertificateErrorNotifications(NotificationController controller); void showCertificateErrorNotification(Account account, boolean incoming); void clearCertificateErrorNotifications(Account account, boolean incoming); } | @Test public void testClearCertificateErrorNotificationsForIncomingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, INCOMING); certificateErrorNotifications.clearCertificateErrorNotifications(account, INCOMING); verify(notificationManager).cancel(notificationId); }
@Test public void testClearCertificateErrorNotificationsForOutgoingServer() throws Exception { int notificationId = NotificationIds.getCertificateErrorNotificationId(account, OUTGOING); certificateErrorNotifications.clearCertificateErrorNotifications(account, OUTGOING); verify(notificationManager).cancel(notificationId); } |
ServerNameSuggester { public String suggestServerName(Type serverType, String domainPart) { switch (serverType) { case IMAP: { return "imap." + domainPart; } case SMTP: { return "smtp." + domainPart; } case EWS: return "outlook.office365.com"; case WebDAV: { return "exchange." + domainPart; } case POP3: { return "pop3." + domainPart; } } throw new AssertionError("Missed case: " + serverType); } String suggestServerName(Type serverType, String domainPart); } | @Test public void suggestServerName_forImapServer() throws Exception { Type serverType = Type.IMAP; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("imap.example.org", result); }
@Test public void suggestServerName_forPop3Server() throws Exception { Type serverType = Type.POP3; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("pop3.example.org", result); }
@Test public void suggestServerName_forWebDavServer() throws Exception { Type serverType = Type.WebDAV; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("exchange.example.org", result); }
@Test public void suggestServerName_forSmtpServer() throws Exception { Type serverType = Type.SMTP; String domainPart = "example.org"; String result = serverNameSuggester.suggestServerName(serverType, domainPart); assertEquals("smtp.example.org", result); } |
ReceivedHeaders { public static SecureTransportState wasMessageTransmittedSecurely(Message message) { String[] headers = message.getHeader(RECEIVED); Timber.d("Received headers: " + headers.length); for(String header: headers) { String fromAddress = "", toAddress = "", sslVersion = null, cipher, bits; header = header.trim(); Matcher matcher = fromPattern.matcher(header); if(matcher.find()) fromAddress = matcher.group(1); matcher = byPattern.matcher(header); if(matcher.find()) toAddress = matcher.group(1); matcher = usingPattern.matcher(header); if(matcher.find()) { sslVersion = matcher.group(1); cipher = matcher.group(2); bits = matcher.group(3); } if (fromAddress.equals("localhost") || fromAddress.equals("127.0.0.1") || toAddress.equals("localhost") || toAddress.equals("127.0.0.1")) { continue; } if (sslVersion == null || sslVersion.startsWith("SSL")) { return new SecureTransportState(SecureTransportError.INSECURELY_ENCRYPTED, R.string.transport_crypto_insecure_ssl_version); } return new SecureTransportState(SecureTransportError.SECURELY_ENCRYPTED); } return new SecureTransportState(SecureTransportError.UNKNOWN); } static SecureTransportState wasMessageTransmittedSecurely(Message message); static SPFState isEmailPotentialSpoof(Message message); static DKIMState isEmailIntegrityValid(Message message); static final String RECEIVED; static Pattern fromPattern; static Pattern byPattern; static Pattern usingPattern; static final String AUTHENTICATION_RESULTS; static Pattern spfPattern; static Pattern dkimPattern; } | @Test public void wasMessageTransmittedSecurely_withNoHeaders_shouldReturnUnknown() throws MessagingException { String[] noReceivedHeaders = new String[]{}; Message unknownMessage = mock(Message.class); when(unknownMessage.getHeader("Received")).thenReturn(noReceivedHeaders); assertEquals(SecureTransportError.UNKNOWN, ReceivedHeaders.wasMessageTransmittedSecurely(unknownMessage).getErrorType()); }
@Test public void wasMessageTransmittedSecurely_forInsecureMessage_shouldReturnFalse() throws MessagingException { String[] insecureReceivedHeaders = new String[]{ " from localhost (localhost [127.0.0.1])\n" + "by scarlet.richardwhiuk.com (Postfix)\n " + "with ESMTP id BB1057BA98\n " + "for <[email protected]>; Fri, 25 Mar 2016 10:38:29 +0000 (GMT)", " from scarlet.richardwhiuk.com ([127.0.0.1])\n" + "by localhost (scarlet.richardwhiuk.com [127.0.0.1]) (amavisd-new, port 10024)\n" + "with ESMTP id kEaYiQPLCxiT for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk (serpentine.unitedhosting.co.uk [83.223.125.16])\n" + "(using SSL with cipher DHE-RSA-AES256-SHA (256/256 bits))\n" + "(No client certificate requested)\n" + "by scarlet.richardwhiuk.com (Postfix)\n" + "with ESMTPS id C19917A8E9\n" + "for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk ([83.223.125.16]:56654 helo=serpentine.org.uk)\n" + "by serpentine.unitedhosting.co.uk\n" + "with esmtp (Exim 4.86_1) (envelope-from <[email protected]>)\n" + "id 1ajOr6-00020j-MM\n" + "for [email protected]; Fri, 25 Mar 2016 10:20:36 +0000\n" }; Message insecureMessage = mock(Message.class); when(insecureMessage.getHeader("Received")).thenReturn(insecureReceivedHeaders); assertEquals(SecureTransportError.INSECURELY_ENCRYPTED, ReceivedHeaders.wasMessageTransmittedSecurely(insecureMessage).getErrorType()); }
@Test public void wasMessageTransmittedSecurely_forSecureMessage_shouldReturnTrue() throws MessagingException { String[] secureReceivedHeaders = new String[]{ " from localhost (localhost [127.0.0.1])\n" + "by scarlet.richardwhiuk.com (Postfix)\n " + "with ESMTP id BB1057BA98\n " + "for <[email protected]>; Fri, 25 Mar 2016 10:38:29 +0000 (GMT)", " from scarlet.richardwhiuk.com ([127.0.0.1])\n" + "by localhost (scarlet.richardwhiuk.com [127.0.0.1]) (amavisd-new, port 10024)\n" + "with ESMTP id kEaYiQPLCxiT for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk (serpentine.unitedhosting.co.uk [83.223.125.16])\n" + "(using TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits))\n" + "(No client certificate requested)\n" + "by scarlet.richardwhiuk.com (Postfix)\n" + "with ESMTPS id C19917A8E9\n" + "for <[email protected]>; Fri, 25 Mar 2016 10:38:27 +0000 (GMT)\n", " from serpentine.unitedhosting.co.uk ([83.223.125.16]:56654 helo=serpentine.org.uk)\n" + "by serpentine.unitedhosting.co.uk\n" + "with esmtp (Exim 4.86_1) (envelope-from <[email protected]>)\n" + "id 1ajOr6-00020j-MM\n" + "for [email protected]; Fri, 25 Mar 2016 10:20:36 +0000\n" }; Message secureMessage = mock(Message.class); when(secureMessage.getHeader("Received")).thenReturn(secureReceivedHeaders); assertEquals(SecureTransportError.SECURELY_ENCRYPTED, ReceivedHeaders.wasMessageTransmittedSecurely(secureMessage).getErrorType()); } |
SettingsExporter { static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException { try { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, Boolean.TRUE); serializer.setFeature("http: serializer.startTag(null, ROOT_ELEMENT); serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION)); serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION)); Timber.i("Exporting preferences"); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); Set<String> exportAccounts; if (accountUuids == null) { List<Account> accounts = preferences.getAccounts(); exportAccounts = new HashSet<>(); for (Account account : accounts) { exportAccounts.add(account.getUuid()); } } else { exportAccounts = accountUuids; } Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll()); if (includeGlobals) { serializer.startTag(null, GLOBAL_ELEMENT); writeSettings(serializer, prefs); serializer.endTag(null, GLOBAL_ELEMENT); } serializer.startTag(null, ACCOUNTS_ELEMENT); for (String accountUuid : exportAccounts) { Account account = preferences.getAccount(accountUuid); writeAccount(serializer, account, prefs); } serializer.endTag(null, ACCOUNTS_ELEMENT); serializer.endTag(null, ROOT_ELEMENT); serializer.endDocument(); serializer.flush(); } catch (Exception e) { throw new SettingsImportExportException(e.getLocalizedMessage(), e); } } static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids); static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri); static String generateDatedExportFileName(); } | @Test public void exportPreferences_producesXML() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals("k9settings", document.getRootElement().getName()); }
@Test public void exportPreferences_setsVersionToLatest() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals(Integer.toString(Settings.VERSION), document.getRootElement().getAttributeValue("version")); }
@Test public void exportPreferences_setsFormatTo1() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertEquals("1", document.getRootElement().getAttributeValue("format")); }
@Test public void exportPreferences_exportsGlobalSettingsWhenRequested() throws Exception { Document document = exportPreferences(true, Collections.<String>emptySet()); assertNotNull(document.getRootElement().getChild("global")); }
@Test public void exportPreferences_ignoresGlobalSettingsWhenRequested() throws Exception { Document document = exportPreferences(false, Collections.<String>emptySet()); assertNull(document.getRootElement().getChild("global")); } |
SettingsImporter { public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException { try { boolean globalSettingsImported = false; List<AccountDescriptionPair> importedAccounts = new ArrayList<>(); List<AccountDescription> erroneousAccounts = new ArrayList<>(); Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false); Preferences preferences = Preferences.getPreferences(context); Storage storage = preferences.getStorage(); if (globalSettings) { try { StorageEditor editor = storage.edit(); if (imported.globalSettings != null) { importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings); } else { Timber.w("Was asked to import global settings but none found."); } if (editor.commit()) { Timber.v("Committed global settings to the preference storage."); globalSettingsImported = true; } else { Timber.v("Failed to commit global settings to the preference storage"); } } catch (Exception e) { Timber.e(e, "Exception while importing global settings"); } } if (accountUuids != null && accountUuids.size() > 0) { if (imported.accounts != null) { for (String accountUuid : accountUuids) { if (imported.accounts.containsKey(accountUuid)) { ImportedAccount account = imported.accounts.get(accountUuid); try { StorageEditor editor = storage.edit(); AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite); if (editor.commit()) { Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name); if (!importResult.overwritten) { editor = storage.edit(); String newUuid = importResult.imported.uuid; String oldAccountUuids = storage.getString("accountUuids", ""); String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid; putString(editor, "accountUuids", newAccountUuids); if (!editor.commit()) { throw new SettingsImportExportException("Failed to set account UUID list"); } } preferences.loadAccounts(); importedAccounts.add(importResult); } else { Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name); erroneousAccounts.add(importResult.original); } } catch (InvalidSettingValueException e) { Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } catch (Exception e) { Timber.e(e, "Exception while importing account \"%s\"", account.name); erroneousAccounts.add(new AccountDescription(account.name, account.uuid)); } } else { Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid); } } StorageEditor editor = storage.edit(); String defaultAccountUuid = storage.getString("defaultAccountUuid", null); if (defaultAccountUuid == null) { putString(editor, "defaultAccountUuid", accountUuids.get(0)); } if (!editor.commit()) { throw new SettingsImportExportException("Failed to set default account"); } } else { Timber.w("Was asked to import at least one account but none found."); } } preferences.loadAccounts(); QMail.loadPrefs(preferences); QMail.setServicesEnabled(context); return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings,
List<String> accountUuids, boolean overwrite); } | @Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnBlankFile() throws SettingsImportExportException { InputStream inputStream = new StringInputStream(""); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnMissingFormat() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings version=\"1\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnInvalidFormat() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings version=\"1\" format=\"A\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnNonPositiveFormat() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings version=\"1\" format=\"0\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnMissingVersion() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings format=\"1\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnInvalidVersion() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"A\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test(expected = SettingsImportExportException.class) public void importSettings_throwsExceptionOnNonPositiveVersion() throws SettingsImportExportException { InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"0\"></k9settings>"); List<String> accountUuids = new ArrayList<>(); SettingsImporter.importSettings(RuntimeEnvironment.application, inputStream, true, accountUuids, true); }
@Test public void importSettings_disablesAccountsNeedingPasswords() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name>" + "<incoming-server type=\"IMAP\">" + "<connection-security>SSL_TLS_REQUIRED</connection-security>" + "<username>[email protected]</username>" + "<authentication-type>CRAM_MD5</authentication-type>" + "<host>googlemail.com</host>" + "</incoming-server>" + "<outgoing-server type=\"SMTP\">" + "<connection-security>SSL_TLS_REQUIRED</connection-security>" + "<username>[email protected]</username>" + "<authentication-type>CRAM_MD5</authentication-type>" + "<host>googlemail.com</host>" + "</outgoing-server>" + "<settings><value key=\"a\">b</value></settings>" + "<identities><identity><email>[email protected]</email></identity></identities>" + "</account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add(validUUID); SettingsImporter.ImportResults results = SettingsImporter.importSettings( RuntimeEnvironment.application, inputStream, true, accountUuids, false); assertEquals(0, results.erroneousAccounts.size()); assertEquals(1, results.importedAccounts.size()); assertEquals("Account", results.importedAccounts.get(0).imported.name); assertEquals(validUUID, results.importedAccounts.get(0).imported.uuid); assertFalse(Preferences.getPreferences(RuntimeEnvironment.application) .getAccount(validUUID).isEnabled()); } |
SettingsImporter { @VisibleForTesting static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException { if (!overview && accountUuids == null) { throw new IllegalArgumentException("Argument 'accountUuids' must not be null."); } try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xpp = factory.newPullParser(); InputStreamReader reader = new InputStreamReader(inputStream); xpp.setInput(reader); Imported imported = null; int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) { imported = parseRoot(xpp, globalSettings, accountUuids, overview); } else { Timber.w("Unexpected start tag: %s", xpp.getName()); } } eventType = xpp.next(); } if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) { throw new SettingsImportExportException("Invalid import data"); } return imported; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings,
List<String> accountUuids, boolean overwrite); } | @Test public void parseSettings_account() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name></account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add("1"); SettingsImporter.Imported results = SettingsImporter.parseSettings(inputStream, true, accountUuids, true); assertEquals(1, results.accounts.size()); assertEquals("Account", results.accounts.get(validUUID).name); assertEquals(validUUID, results.accounts.get(validUUID).uuid); }
@Test public void parseSettings_account_identities() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name>" + "<identities><identity><email>[email protected]</email></identity></identities>" + "</account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add("1"); SettingsImporter.Imported results = SettingsImporter.parseSettings(inputStream, true, accountUuids, true); assertEquals(1, results.accounts.size()); assertEquals(validUUID, results.accounts.get(validUUID).uuid); assertEquals(1, results.accounts.get(validUUID).identities.size()); assertEquals("[email protected]", results.accounts.get(validUUID).identities.get(0).email); }
@Test public void parseSettings_account_cram_md5() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts><account uuid=\"" + validUUID + "\"><name>Account</name>" + "<incoming-server><authentication-type>CRAM_MD5</authentication-type></incoming-server>" + "</account></accounts></k9settings>"); List<String> accountUuids = new ArrayList<>(); accountUuids.add(validUUID); SettingsImporter.Imported results = SettingsImporter.parseSettings(inputStream, true, accountUuids, false); assertEquals("Account", results.accounts.get(validUUID).name); assertEquals(validUUID, results.accounts.get(validUUID).uuid); assertEquals(AuthType.CRAM_MD5, results.accounts.get(validUUID).incoming.authenticationType); } |
SettingsImporter { public static ImportContents getImportStreamContents(InputStream inputStream) throws SettingsImportExportException { try { Imported imported = parseSettings(inputStream, false, null, true); boolean globalSettings = (imported.globalSettings != null); final List<AccountDescription> accounts = new ArrayList<>(); if (imported.accounts != null) { for (ImportedAccount account : imported.accounts.values()) { String accountName = getAccountDisplayName(account); accounts.add(new AccountDescription(accountName, account.uuid)); } } return new ImportContents(globalSettings, accounts); } catch (SettingsImportExportException e) { throw e; } catch (Exception e) { throw new SettingsImportExportException(e); } } static ImportContents getImportStreamContents(InputStream inputStream); static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings,
List<String> accountUuids, boolean overwrite); } | @Test public void getImportStreamContents_account() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts>" + "<account uuid=\"" + validUUID + "\">" + "<name>Account</name>" + "<identities>" + "<identity>" + "<email>[email protected]</email>" + "</identity>" + "</identities>" + "</account>" + "</accounts></k9settings>"); SettingsImporter.ImportContents results = SettingsImporter.getImportStreamContents(inputStream); assertEquals(false, results.globalSettings); assertEquals(1, results.accounts.size()); assertEquals("Account", results.accounts.get(0).name); assertEquals(validUUID, results.accounts.get(0).uuid); }
@Test public void getImportStreamContents_alternativeName() throws SettingsImportExportException { String validUUID = UUID.randomUUID().toString(); InputStream inputStream = new StringInputStream("<k9settings format=\"1\" version=\"1\">" + "<accounts>" + "<account uuid=\"" + validUUID + "\">" + "<name></name>" + "<identities>" + "<identity>" + "<email>[email protected]</email>" + "</identity>" + "</identities>" + "</account>" + "</accounts></k9settings>"); SettingsImporter.ImportContents results = SettingsImporter.getImportStreamContents(inputStream); assertEquals(false, results.globalSettings); assertEquals(1, results.accounts.size()); assertEquals("[email protected]", results.accounts.get(0).name); assertEquals(validUUID, results.accounts.get(0).uuid); } |
ICalData { public List<ICalendarData> getCalendarData() { return calendarData; } ICalData(List<ICalendar> iCalendars); List<ICalendarData> getCalendarData(); static final String METHOD_PUBLISH; static final String METHOD_REPLY; static final String METHOD_REQUEST; static final String METHOD_COUNTER; } | @Test public void ICalendar_constructor_storedRequiredAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationLevel(ParticipationLevel.REQUIRED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getRequired()[0]); }
@Test public void ICalendar_constructor_storedOptionalAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationLevel(ParticipationLevel.OPTIONAL); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getOptional()[0]); }
@Test public void ICalendar_constructor_storedFyiAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationLevel(ParticipationLevel.FYI); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getFyi()[0]); }
@Test public void ICalendar_constructor_storedAcceptedAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.ACCEPTED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getAccepted()[0]); }
@Test public void ICalendar_constructor_storedTentativeAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.TENTATIVE); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getTentative()[0]); }
@Test public void ICalendar_constructor_storedDeclinedAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.DECLINED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getDeclined()[0]); }
@Test public void ICalendar_constructor_storedDelegatedAttendeesFromEvent() { List<ICalendar> iCalendars = new ArrayList<>(); ICalendar iCalendar = new ICalendar(); VEvent event = new VEvent(); Attendee requiredAttendee = new Attendee("A", "[email protected]"); requiredAttendee.setParticipationStatus(ParticipationStatus.DELEGATED); event.addAttendee(requiredAttendee); iCalendar.addEvent(event); iCalendars.add(iCalendar); ICalData data = new ICalData(iCalendars); assertEquals(requiredAttendee, data.getCalendarData().get(0).getDelegated()[0]); } |
ICalParser { public static ICalData parse(ICalPart part) { String iCalText = MessageExtractor.getTextFromPart(part.getPart()); if (iCalText == null) { return new ICalData(new ArrayList<ICalendar>()); } return new ICalData(Biweekly.parse(iCalText).all()); } static ICalData parse(ICalPart part); static final String MIME_TYPE; } | @Test public void parse_withNoText_returnsDataWithNoEvents() throws MessagingException { ICalPart part = new ICalPart(null); ICalData data = ICalParser.parse(part); assertEquals(0, data.getCalendarData().size()); }
@Test public void parse_returnsCorrectDataForMinimalPublishEvent() throws MessagingException { String calendar = "BEGIN:VCALENDAR\r\n" + "METHOD:PUBLISH\r\n" + "PRODID:-"VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "ORGANIZER:mailto:[email protected]\r\n" + "DTSTART:19970701T200000Z\r\n" + "DTSTAMP:19970611T190000Z\r\n" + "SUMMARY:ST. PAUL SAINTS -VS- DULUTH-SUPERIOR DUKES\r\n" + "UID:[email protected]\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR"; Body body = new TextBody(calendar); MimeBodyPart dataPart = new MimeBodyPart(body); ICalPart part = new ICalPart(dataPart); ICalData data = ICalParser.parse(part); assertEquals(1, data.getCalendarData().size()); assertEquals("PUBLISH", data.getCalendarData().get(0).getMethod().getValue()); assertEquals("[email protected]", data.getCalendarData().get(0).getOrganizer().getEmail()); } |
TransportUris { public static ServerSettings decodeTransportUri(String uri) { if (uri.startsWith("smtp")) { return decodeSmtpUri(uri); } else if (uri.startsWith("webdav")) { return decodeWebDavUri(uri); } else if (uri.startsWith("ews")) { return decodeEwsUri(uri); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); } | @Test public void decodeTransportUri_canDecodeAuthType() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(AuthType.PLAIN, result.authenticationType); }
@Test public void decodeTransportUri_canDecodeUsername() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("user", result.username); }
@Test public void decodeTransportUri_canDecodePassword() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("password", result.password); }
@Test public void decodeTransportUri_canDecodeUsername_withNoAuthType() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("user", result.username); }
@Test public void decodeTransportUri_canDecodeUsername_withNoPasswordOrAuthType() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("user", result.username); }
@Test public void decodeTransportUri_canDecodeAuthType_withEmptyPassword() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(AuthType.PLAIN, result.authenticationType); }
@Test public void decodeTransportUri_canDecodeHost() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("server", result.host); }
@Test public void decodeTransportUri_canDecodePort() { String storeUri = "smtp: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(123456, result.port); }
@Test public void decodeTransportUri_canDecodeTLS() { String storeUri = "smtp+tls+: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(ConnectionSecurity.STARTTLS_REQUIRED, result.connectionSecurity); }
@Test public void decodeTransportUri_canDecodeSSL() { String storeUri = "smtp+ssl+: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals(ConnectionSecurity.SSL_TLS_REQUIRED, result.connectionSecurity); }
@Test public void decodeTransportUri_canDecodeClientCert() { String storeUri = "smtp+ssl+: ServerSettings result = TransportUris.decodeTransportUri(storeUri); assertEquals("clientCert", result.clientCertificateAlias); }
@Test(expected = IllegalArgumentException.class) public void decodeTransportUri_forUnknownSchema_throwsIllegalArgumentException() { String storeUri = "unknown: TransportUris.decodeTransportUri(storeUri); } |
MessageCryptoStructureDetector { public static boolean isPartPgpInlineEncrypted(@Nullable Part part) { if (part == null) { return false; } if (!part.isMimeType(TEXT_PLAIN) && !part.isMimeType(APPLICATION_PGP)) { return false; } String text = MessageExtractor.getTextFromPart(part, TEXT_LENGTH_FOR_INLINE_CHECK); if (TextUtils.isEmpty(text)) { return false; } text = text.trim(); return text.startsWith(PGP_INLINE_START_MARKER); } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findMultipartEncryptedParts(Part startPart); static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPartMultipartEncrypted(Part part); static boolean isMultipartEncryptedOpenPgpProtocol(Part part); static boolean isMultipartSignedOpenPgpProtocol(Part part); static boolean isMultipartEncryptedSMimeProtocol(Part part); static boolean isMultipartSignedSMimeProtocol(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); } | @Test public void isPgpInlineMethods__withPgpInlineData__shouldReturnTrue() throws Exception { String pgpInlineData = "-----BEGIN PGP MESSAGE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertTrue(MessageCryptoStructureDetector.isPartPgpInlineEncrypted(message)); }
@Test public void isPartPgpInlineEncrypted__withSignedData__shouldReturnFalse() throws Exception { String pgpInlineData = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Header: Value\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP SIGNED MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertFalse(MessageCryptoStructureDetector.isPartPgpInlineEncrypted(message)); } |
TransportUris { public static String createTransportUri(ServerSettings server) { if (Type.SMTP == server.type) { return createSmtpUri(server); } else if (Type.WebDAV == server.type) { return createWebDavUri(server); } else if (Type.EWS == server.type) { return createEwsUri(server); } else { throw new IllegalArgumentException("Not a valid transport URI"); } } static ServerSettings decodeTransportUri(String uri); static String createTransportUri(ServerSettings server); } | @Test public void createTransportUri_canEncodeSmtpSslUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.SSL_TLS_REQUIRED, AuthType.EXTERNAL, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp+ssl+: }
@Test public void createTransportUri_canEncodeSmtpTlsUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.STARTTLS_REQUIRED, AuthType.PLAIN, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp+tls+: }
@Test public void createTransportUri_canEncodeSmtpUri() { ServerSettings serverSettings = new ServerSettings( ServerSettings.Type.SMTP, "server", 123456, ConnectionSecurity.NONE, AuthType.CRAM_MD5, "user", "password", "clientCert"); String result = TransportUris.createTransportUri(serverSettings); assertEquals("smtp: } |
SmtpTransport extends Transport { @Override public void open() throws MessagingException { try { boolean secureConnection = false; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) { try { SocketAddress socketAddress = new InetSocketAddress(addresses[i], port); if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); secureConnection = true; } else { socket = new Socket(); socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } } catch (SocketException e) { if (i < (addresses.length - 1)) { continue; } throw new MessagingException("Cannot connect to host", e); } break; } socket.setSoTimeout(SOCKET_READ_TIMEOUT); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); executeCommand(null); InetAddress localAddress = socket.getLocalAddress(); String localHost = getCanonicalHostName(localAddress); String ipAddr = localAddress.getHostAddress(); if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) { if (!ipAddr.equals("")) { if (localAddress instanceof Inet6Address) { localHost = "[IPv6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } else { localHost = "android"; } } Map<String, String> extensions = sendHello(localHost); is8bitEncodingAllowed = extensions.containsKey("8BITMIME"); isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES"); isPipeliningSupported = extensions.containsKey("PIPELINING"); if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) { if (extensions.containsKey("STARTTLS")) { executeCommand("STARTTLS"); socket = trustedSocketFactory.createSocket( socket, host, port, clientCertificateAlias); inputStream = new PeekableInputStream(new BufferedInputStream(socket.getInputStream(), 1024)); outputStream = new BufferedOutputStream(socket.getOutputStream(), 1024); extensions = sendHello(localHost); secureConnection = true; } else { throw new CertificateValidationException( "STARTTLS connection security not available"); } } boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; boolean authExternalSupported = false; boolean authXoauth2Supported = false; if (extensions.containsKey("AUTH")) { List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" ")); authLoginSupported = saslMech.contains("LOGIN"); authPlainSupported = saslMech.contains("PLAIN"); authCramMD5Supported = saslMech.contains("CRAM-MD5"); authExternalSupported = saslMech.contains("EXTERNAL"); authXoauth2Supported = saslMech.contains("XOAUTH2"); } parseOptionalSizeValue(extensions); if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(password) || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)) { switch (authType) { case LOGIN: case PLAIN: if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else { throw new MessagingException( "Authentication methods SASL PLAIN and LOGIN are unavailable."); } break; case CRAM_MD5: if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("Authentication method CRAM-MD5 is unavailable."); } break; case XOAUTH2: if (authXoauth2Supported && oauthTokenProvider != null) { saslXoauth2(); } else { throw new MessagingException("Authentication method XOAUTH2 is unavailable."); } break; case EXTERNAL: if (authExternalSupported) { saslAuthExternal(); } else { throw new CertificateValidationException(MissingCapability); } break; case AUTOMATIC: if (secureConnection) { if (authPlainSupported) { saslAuthPlain(); } else if (authLoginSupported) { saslAuthLogin(); } else if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException("No supported authentication methods available."); } } else { if (authCramMD5Supported) { saslAuthCramMD5(); } else { throw new MessagingException( "Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable."); } } break; default: throw new MessagingException( "Unhandled authentication method found in the server settings (bug)."); } } } catch (MessagingException e) { close(); throw e; } catch (SSLException e) { close(); throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { close(); throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { close(); throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory,
OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); } | @Test public void open_withoutAuthLoginExtension_shouldConnectWithoutAuthentication() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 OK"); SmtpTransport transport = startServerAndCreateSmtpTransportWithoutPassword(server); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withAuthPlainExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("AUTH PLAIN AHVzZXIAcGFzc3dvcmQ="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.PLAIN, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withAuthLoginExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH LOGIN"); server.expect("AUTH LOGIN"); server.output("250 OK"); server.expect("dXNlcg=="); server.output("250 OK"); server.expect("cGFzc3dvcmQ="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.PLAIN, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withoutLoginAndPlainAuthExtensions_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.PLAIN, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Authentication methods SASL PLAIN and LOGIN are unavailable.", e.getMessage()); } server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withCramMd5AuthExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH CRAM-MD5"); server.expect("AUTH CRAM-MD5"); server.output(Base64.encode("<24609.1047914046@localhost>")); server.expect("dXNlciA3NmYxNWEzZmYwYTNiOGI1NzcxZmNhODZlNTcyMDk2Zg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.CRAM_MD5, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withoutCramMd5AuthExtension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.CRAM_MD5, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Authentication method CRAM-MD5 is unavailable.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension_shouldThrowOn401Response() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.STATUS_401_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals( "5.7.1 Username and Password not accepted. Learn more at " + "5.7.1 http: e.getMessage()); } InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension_shouldInvalidateAndRetryOn400Response() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension_shouldInvalidateAndRetryOnInvalidJsonResponse() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.INVALID_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension_shouldInvalidateAndRetryOnMissingStatusJsonResponse() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 "+ XOAuth2ChallengeParserTest.MISSING_STATUS_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension_shouldThrowOnMultipleFailure() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 " + XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG5ld1Rva2VuAQE="); server.output("334 " + XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals( "5.7.1 Username and Password not accepted. Learn more at " + "5.7.1 http: e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withXoauth2Extension_shouldThrowOnFailure_fetchingToken() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH XOAUTH2"); server.expect("QUIT"); server.output("221 BYE"); when(oAuth2TokenProvider.getToken(anyString(), anyInt())).thenThrow(new AuthenticationFailedException("Failed to fetch token")); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals("Failed to fetch token", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withoutXoauth2Extension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Authentication method XOAUTH2 is unavailable.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withAuthExternalExtension() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH EXTERNAL"); server.expect("AUTH EXTERNAL dXNlcg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.EXTERNAL, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withoutAuthExternalExtension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.EXTERNAL, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (CertificateValidationException e) { assertEquals(CertificateValidationException.Reason.MissingCapability, e.getReason()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withAutomaticAuthAndNoTransportSecurityAndAuthCramMd5Extension_shouldUseAuthCramMd5() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH CRAM-MD5"); server.expect("AUTH CRAM-MD5"); server.output(Base64.encode("<24609.1047914046@localhost>")); server.expect("dXNlciA3NmYxNWEzZmYwYTNiOGI1NzcxZmNhODZlNTcyMDk2Zg=="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.AUTOMATIC, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withAutomaticAuthAndNoTransportSecurityAndAuthPlainExtension_shouldThrow() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250 AUTH PLAIN LOGIN"); server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.AUTOMATIC, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (MessagingException e) { assertEquals("Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withEhloFailing_shouldTryHelo() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("502 5.5.1, Unrecognized command."); server.expect("HELO localhost"); server.output("250 localhost"); SmtpTransport transport = startServerAndCreateSmtpTransportWithoutPassword(server); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
@Test public void open_withSupportWithEnhancedStatusCodesOnAuthFailure_shouldThrowEncodedMessage() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 localhost Simple Mail Transfer Service Ready"); server.expect("EHLO localhost"); server.output("250-localhost Hello client.localhost"); server.output("250-ENHANCEDSTATUSCODES"); server.output("250 AUTH XOAUTH2"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("334 " + XOAuth2ChallengeParserTest.STATUS_401_RESPONSE); server.expect(""); server.output("535-5.7.1 Username and Password not accepted. Learn more at"); server.output("535 5.7.1 http: server.expect("QUIT"); server.output("221 BYE"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); try { transport.open(); fail("Exception expected"); } catch (AuthenticationFailedException e) { assertEquals( "Username and Password not accepted. " + "Learn more at http: e.getMessage()); } InOrder inOrder = inOrder(oAuth2TokenProvider); inOrder.verify(oAuth2TokenProvider).getToken(eq(USERNAME), anyInt()); inOrder.verify(oAuth2TokenProvider).invalidateToken(USERNAME); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void open_withManyExtensions_shouldParseAll() throws Exception { MockSmtpServer server = new MockSmtpServer(); server.output("220 smtp.gmail.com ESMTP x25sm19117693wrx.27 - gsmtp"); server.expect("EHLO localhost"); server.output("250-smtp.gmail.com at your service, [86.147.34.216]"); server.output("250-SIZE 35882577"); server.output("250-8BITMIME"); server.output("250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH"); server.output("250-ENHANCEDSTATUSCODES"); server.output("250-PIPELINING"); server.output("250-CHUNKING"); server.output("250 SMTPUTF8"); server.expect("AUTH XOAUTH2 dXNlcj11c2VyAWF1dGg9QmVhcmVyIG9sZFRva2VuAQE="); server.output("235 2.7.0 Authentication successful"); SmtpTransport transport = startServerAndCreateSmtpTransport(server, AuthType.XOAUTH2, ConnectionSecurity.NONE); transport.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } |
MessageCryptoStructureDetector { @VisibleForTesting static boolean isPartPgpInlineEncryptedOrSigned(Part part) { if (!part.isMimeType(TEXT_PLAIN) && !part.isMimeType(APPLICATION_PGP)) { return false; } String text = MessageExtractor.getTextFromPart(part, TEXT_LENGTH_FOR_INLINE_CHECK); if (TextUtils.isEmpty(text)) { return false; } text = text.trim(); return text.startsWith(PGP_INLINE_START_MARKER) || text.startsWith(PGP_INLINE_SIGNED_START_MARKER); } static Part findPrimaryEncryptedOrSignedPart(Part part, List<Part> outputExtraParts); static List<Part> findMultipartEncryptedParts(Part startPart); static List<Part> findMultipartSignedParts(Part startPart, MessageCryptoAnnotations messageCryptoAnnotations); static List<Part> findPgpInlineParts(Part startPart); static byte[] getSignatureData(Part part); static boolean isPartMultipartEncrypted(Part part); static boolean isMultipartEncryptedOpenPgpProtocol(Part part); static boolean isMultipartSignedOpenPgpProtocol(Part part); static boolean isMultipartEncryptedSMimeProtocol(Part part); static boolean isMultipartSignedSMimeProtocol(Part part); static boolean isPartPgpInlineEncrypted(@Nullable Part part); } | @Test public void isPartPgpInlineEncryptedOrSigned__withSignedData__shouldReturnTrue() throws Exception { String pgpInlineData = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Header: Value\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Header: Value\n" + "\n" + "base64base64base64base64\n" + "-----END PGP SIGNED MESSAGE-----\n"; MimeMessage message = new MimeMessage(); message.setBody(new TextBody(pgpInlineData)); assertTrue(MessageCryptoStructureDetector.isPartPgpInlineEncryptedOrSigned(message)); } |
SmtpTransport extends Transport { @Override public void sendMessage(Message message) throws MessagingException { List<Address> addresses = new ArrayList<>(); { addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.TO))); addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.CC))); addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.BCC))); } message.setRecipients(RecipientType.BCC, null); Map<String, List<String>> charsetAddressesMap = new HashMap<>(); for (Address address : addresses) { String addressString = address.getAddress(); String charset = CharsetSupport.getCharsetFromAddress(addressString); List<String> addressesOfCharset = charsetAddressesMap.get(charset); if (addressesOfCharset == null) { addressesOfCharset = new ArrayList<>(); charsetAddressesMap.put(charset, addressesOfCharset); } addressesOfCharset.add(addressString); } for (Map.Entry<String, List<String>> charsetAddressesMapEntry : charsetAddressesMap.entrySet()) { String charset = charsetAddressesMapEntry.getKey(); List<String> addressesOfCharset = charsetAddressesMapEntry.getValue(); message.setCharset(charset); sendMessageTo(addressesOfCharset, message); } } SmtpTransport(StoreConfig storeConfig, TrustedSocketFactory trustedSocketFactory,
OAuth2TokenProvider oauthTokenProvider); @Override void open(); @Override void sendMessage(Message message); @Override void close(); } | @Test public void sendMessage_withoutAddressToSendTo_shouldNotOpenConnection() throws Exception { MimeMessage message = new MimeMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionNeverCreated(); }
@Test public void sendMessage_withSingleRecipient() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication(); server.expect("MAIL FROM:<user@localhost>"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessage_with8BitEncoding() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("8BITMIME"); server.expect("MAIL FROM:<user@localhost> BODY=8BITMIME"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessage_with8BitEncodingExtensionNotCaseSensitive() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("8bitmime"); server.expect("MAIL FROM:<user@localhost> BODY=8BITMIME"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessage_withMessageTooLarge_shouldThrow() throws Exception { Message message = getDefaultMessageBuilder() .setHasAttachments(true) .messageSize(1234L) .build(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("SIZE 1000"); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected message too large error"); } catch (MessagingException e) { assertTrue(e.isPermanentFailure()); assertEquals("Message too large for server", e.getMessage()); } }
@Test public void sendMessage_withNegativeReply_shouldThrow() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication(); server.expect("MAIL FROM:<user@localhost>"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("421 4.7.0 Temporary system problem"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(421, e.getReplyCode()); assertEquals("4.7.0 Temporary system problem", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessage_withPipelining() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("250 OK"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessage_withoutPipelining() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication(); server.expect("MAIL FROM:<user@localhost>"); server.output("250 OK"); server.expect("RCPT TO:<user2@localhost>"); server.output("250 OK"); server.expect("DATA"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessagePipelining_withNegativeReply() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("."); server.output("554 no valid recipients"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(550, e.getReplyCode()); assertEquals("remote mail to <user2@localhost> not allowed", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessagePipelining_without354ReplyforData_shouldThrow() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); server.output("554 no valid recipients given"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(554, e.getReplyCode()); assertEquals("no valid recipients given", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessagePipelining_with250and550ReplyforRecipients_shouldThrow() throws Exception { Message message = getMessageWithTwoRecipients(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("RCPT TO:<user3@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("250 OK"); server.output("550 remote mail to <user3@localhost> not allowed"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("."); server.output("554 no valid recipients given"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(550, e.getReplyCode()); assertEquals("remote mail to <user3@localhost> not allowed", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
@Test public void sendMessagePipelining_with250and550ReplyforRecipientsAnd250ForMessage_shouldThrow() throws Exception { Message message = getMessageWithTwoRecipients(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("RCPT TO:<user3@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("250 OK"); server.output("550 remote mail to <user3@localhost> not allowed"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("."); server.output("250 OK"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(550, e.getReplyCode()); assertEquals("remote mail to <user3@localhost> not allowed", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } |
OpenPgpApiHelper { public static String buildUserId(Identity identity) { StringBuilder sb = new StringBuilder(); String name = identity.getName(); if (!TextUtils.isEmpty(name)) { sb.append(name).append(" "); } sb.append("<").append(identity.getEmail()).append(">"); return sb.toString(); } static String buildUserId(Identity identity); } | @Test public void buildUserId_withName_shouldCreateOpenPgpAccountName() { Identity identity = new Identity(); identity.setEmail("[email protected]"); identity.setName("Name"); String result = OpenPgpApiHelper.buildUserId(identity); assertEquals("Name <[email protected]>", result); }
@Test public void buildUserId_withoutName_shouldCreateOpenPgpAccountName() { Identity identity = new Identity(); identity.setEmail("[email protected]"); String result = OpenPgpApiHelper.buildUserId(identity); assertEquals("<[email protected]>", result); } |
MessageIdGenerator { public String generateMessageId(Message message) { String hostname = null; Address[] from = message.getFrom(); if (from != null && from.length >= 1) { hostname = from[0].getHostname(); } if (hostname == null) { Address[] replyTo = message.getReplyTo(); if (replyTo != null && replyTo.length >= 1) { hostname = replyTo[0].getHostname(); } } if (hostname == null) { hostname = "email.android.com"; } String uuid = generateUuid(); return "<" + uuid + "@" + hostname + ">"; } @VisibleForTesting MessageIdGenerator(); static MessageIdGenerator getInstance(); String generateMessageId(Message message); } | @Test public void generateMessageId_withFromAndReplyToAddress() throws Exception { Message message = new MimeMessage(); message.setFrom(new Address("[email protected]")); message.setReplyTo(Address.parse("[email protected]")); String result = messageIdGenerator.generateMessageId(message); assertEquals("<[email protected]>", result); }
@Test public void generateMessageId_withReplyToAddress() throws Exception { Message message = new MimeMessage(); message.setReplyTo(Address.parse("[email protected]")); String result = messageIdGenerator.generateMessageId(message); assertEquals("<[email protected]>", result); }
@Test public void generateMessageId_withoutRelevantHeaders() throws Exception { Message message = new MimeMessage(); String result = messageIdGenerator.generateMessageId(message); assertEquals("<[email protected]>", result); } |
MessageExtractor { public static String getTextFromPart(Part part) { return getTextFromPart(part, NO_TEXT_SIZE_LIMIT); } private MessageExtractor(); static String getTextFromPart(Part part); static String getTextFromPart(Part part, long textSizeLimit); static boolean hasMissingParts(Part part); static void findViewablesAndAttachments(Part part,
@Nullable List<Viewable> outputViewableParts,
@Nullable List<Part> outputNonViewableParts,
@Nullable List<ICalPart> outputICalendarParts); static Set<Part> getTextParts(Part part); static List<Part> collectAttachments(Message message); static Set<Part> collectTextParts(Message message); static final long NO_TEXT_SIZE_LIMIT; } | @Test public void getTextFromPart_withNoBody_shouldReturnNull() throws Exception { part.setBody(null); String result = MessageExtractor.getTextFromPart(part); assertNull(result); }
@Test public void getTextFromPart_withTextBody_shouldReturnText() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain; charset=utf-8"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), MimeUtil.ENC_8BIT); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertEquals("Sample text body", result); }
@Test public void getTextFromPart_withRawDataBodyWithNonText_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "image/jpeg"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), MimeUtil.ENC_8BIT); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertNull(result); }
@Test public void getTextFromPart_withExceptionThrownGettingInputStream_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/html"); Body body = mock(Body.class); when(body.getInputStream()).thenThrow(new MessagingException("Test")); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertNull(result); }
@Test public void getTextFromPart_withUnknownEncoding_shouldReturnUnmodifiedBodyContents() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); String bodyText = "Sample text body"; BinaryMemoryBody body = new BinaryMemoryBody(bodyText.getBytes(), "unknown encoding"); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertEquals(bodyText, result); }
@Test public void getTextFromPart_withPlainTextWithCharsetInContentTypeRawDataBody_shouldReturnText() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain; charset=UTF-8"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), MimeUtil.ENC_8BIT); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertEquals("Sample text body", result); }
@Test public void getTextFromPart_withHtmlWithCharsetInContentTypeRawDataBody_shouldReturnHtmlText() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/html; charset=UTF-8"); BinaryMemoryBody body = new BinaryMemoryBody( "<html><body>Sample text body</body></html>".getBytes(), MimeUtil.ENC_8BIT); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertEquals("<html><body>Sample text body</body></html>", result); }
@Test public void getTextFromPart_withHtmlWithCharsetInHtmlRawDataBody_shouldReturnHtmlText() throws Exception { String bodyText = "<html><head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" + "</head><body>Sample text body</body></html>"; BinaryMemoryBody body = new BinaryMemoryBody(bodyText.getBytes(), MimeUtil.ENC_8BIT); part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/html"); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertNotNull(result); assertEquals(bodyText, result); } |
TextSignatureRemover { public static String stripSignature(String content) { if (DASH_SIGNATURE_PLAIN.matcher(content).find()) { content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n"); } return content; } static String stripSignature(String content); } | @Test public void shouldStripSignature() throws Exception { String text = "This is the body text\r\n" + "\r\n" + "-- \r\n" + "Sent from my Android device with K-9 Mail. Please excuse my brevity."; String withoutSignature = TextSignatureRemover.stripSignature(text); assertEquals("This is the body text\r\n\r\n", withoutSignature); } |
FlowedMessageUtils { static boolean isFormatFlowed(String contentType) { String mimeType = getHeaderParameter(contentType, null); if (isSameMimeType(TEXT_PLAIN, mimeType)) { String formatParameter = getHeaderParameter(contentType, HEADER_PARAM_FORMAT); return HEADER_FORMAT_FLOWED.equalsIgnoreCase(formatParameter); } return false; } } | @Test public void isFormatFlowed_withTextPlainFormatFlowed_shouldReturnTrue() throws Exception { assertTrue(isFormatFlowed("text/plain; format=flowed")); }
@Test public void isFormatFlowed_withTextPlain_shouldReturnFalse() throws Exception { assertFalse(isFormatFlowed("text/plain")); }
@Test public void isFormatFlowed_withTextHtmlFormatFlowed_shouldReturnFalse() throws Exception { assertFalse(isFormatFlowed("text/html; format=flowed")); } |
FlowedMessageUtils { static boolean isDelSp(String contentType) { if (isFormatFlowed(contentType)) { String delSpParameter = getHeaderParameter(contentType, HEADER_PARAM_DELSP); return HEADER_DELSP_YES.equalsIgnoreCase(delSpParameter); } return false; } } | @Test public void isDelSp_withFormatFlowed_shouldReturnTrue() throws Exception { assertTrue(isDelSp("text/plain; format=flowed; delsp=yes")); }
@Test public void isDelSp_withTextPlainFormatFlowed_shoulReturnFalse() throws Exception { assertFalse(isDelSp("text/plain; format=flowed")); }
@Test public void isDelSp_withoutFormatFlowed_shouldReturnFalse() throws Exception { assertFalse(isDelSp("text/plain; delsp=yes")); }
@Test public void idDelSp_withTextHtmlFormatFlowed_shouldReturnFalse() throws Exception { assertFalse(isDelSp("text/html; format=flowed; delsp=yes")); } |
ListHeaders { public static Address[] getListPostAddresses(Message message) { String[] headerValues = message.getHeader(LIST_POST_HEADER); if (headerValues.length < 1) { return new Address[0]; } List<Address> listPostAddresses = new ArrayList<>(); for (String headerValue : headerValues) { Address address = extractAddress(headerValue); if (address != null) { listPostAddresses.add(address); } } return listPostAddresses.toArray(new Address[listPostAddresses.size()]); } static Address[] getListPostAddresses(Message message); static final String LIST_POST_HEADER; } | @Test public void getListPostAddresses_withMailTo_shouldReturnCorrectAddress() throws Exception { for (String emailAddress : TEST_EMAIL_ADDRESSES) { String headerValue = "<mailto:" + emailAddress + ">"; Message message = buildMimeMessageWithListPostValue(headerValue); Address[] result = ListHeaders.getListPostAddresses(message); assertExtractedAddressMatchesEmail(emailAddress, result); } }
@Test public void getListPostAddresses_withMailtoWithNote_shouldReturnCorrectAddress() throws Exception { for (String emailAddress : TEST_EMAIL_ADDRESSES) { String headerValue = "<mailto:" + emailAddress + "> (Postings are Moderated)"; Message message = buildMimeMessageWithListPostValue(headerValue); Address[] result = ListHeaders.getListPostAddresses(message); assertExtractedAddressMatchesEmail(emailAddress, result); } }
@Test public void getListPostAddresses_withMailtoWithSubject_shouldReturnCorrectAddress() throws Exception { for (String emailAddress : TEST_EMAIL_ADDRESSES) { String headerValue = "<mailto:" + emailAddress + "?subject=list%20posting>"; Message message = buildMimeMessageWithListPostValue(headerValue); Address[] result = ListHeaders.getListPostAddresses(message); assertExtractedAddressMatchesEmail(emailAddress, result); } }
@Test public void getListPostAddresses_withMessageWithNo_shouldReturnEmptyList() throws Exception { MimeMessage message = buildMimeMessageWithListPostValue("NO (posting not allowed on this list)"); Address[] result = ListHeaders.getListPostAddresses(message); assertEquals(0, result.length); }
@Test public void getListPostAddresses_shouldProvideAllListPostHeaders() throws Exception { MimeMessage message = buildMimeMessageWithListPostValue( "<mailto:[email protected]>", "<mailto:[email protected]>"); Address[] result = ListHeaders.getListPostAddresses(message); assertNotNull(result); assertEquals(2, result.length); assertNotNull(result[0]); assertEquals("[email protected]", result[0].getAddress()); assertNotNull(result[1]); assertEquals("[email protected]", result[1].getAddress()); }
@Test public void getListPostAddresses_withoutMailtoUriInBrackets_shouldReturnEmptyList() throws Exception { MimeMessage message = buildMimeMessageWithListPostValue("<x-mailto:something>"); Address[] result = ListHeaders.getListPostAddresses(message); assertEquals(0, result.length); } |
HtmlSignatureRemover { public static String stripSignature(String content) { return new HtmlSignatureRemover().stripSignatureInternal(content); } static String stripSignature(String content); } | @Test public void shouldStripSignatureFromK9StyleHtml() throws Exception { String html = "This is the body text" + "<br>" + "-- <br>" + "Sent from my Android device with K-9 Mail. Please excuse my brevity."; String withoutSignature = HtmlSignatureRemover.stripSignature(html); assertEquals("This is the body text", extractText(withoutSignature)); }
@Test public void shouldStripSignatureFromThunderbirdStyleHtml() throws Exception { String html = "<html>\r\n" + " <head>\r\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\r\n" + " </head>\r\n" + " <body bgcolor=\"#FFFFFF\" text=\"#000000\">\r\n" + " <p>This is the body text<br>\r\n" + " </p>\r\n" + " -- <br>\r\n" + " <div class=\"moz-signature\">Sent from my Android device with K-9 Mail." + " Please excuse my brevity.</div>\r\n" + " </body>\r\n" + "</html>"; String withoutSignature = HtmlSignatureRemover.stripSignature(html); assertEquals("This is the body text", extractText(withoutSignature)); }
@Test public void shouldStripSignatureBeforeBlockquoteTag() throws Exception { String html = "<html><head></head><body>" + "<div>" + "This is the body text" + "<br>" + "-- <br>" + "<blockquote>" + "Sent from my Android device with K-9 Mail. Please excuse my brevity." + "</blockquote>" + "</div>" + "</body></html>"; String withoutSignature = HtmlSignatureRemover.stripSignature(html); assertEquals("<html><head></head><body>" + "<div>This is the body text</div>" + "</body></html>", withoutSignature); }
@Test public void shouldNotStripSignatureInsideBlockquoteTags() throws Exception { String html = "<html><head></head><body>" + "<blockquote>" + "This is some quoted text" + "<br>" + "-- <br>" + "Inner signature" + "</blockquote>" + "<div>" + "This is the body text" + "</div>" + "</body></html>"; String withoutSignature = HtmlSignatureRemover.stripSignature(html); assertEquals("<html><head></head><body>" + "<blockquote>" + "This is some quoted text" + "<br>" + "-- <br>" + "Inner signature" + "</blockquote>" + "<div>This is the body text</div>" + "</body></html>", withoutSignature); }
@Test public void shouldStripSignatureBetweenBlockquoteTags() throws Exception { String html = "<html><head></head><body>" + "<blockquote>" + "Some quote" + "</blockquote>" + "<div>" + "This is the body text" + "<br>" + "-- <br>" + "<blockquote>" + "Sent from my Android device with K-9 Mail. Please excuse my brevity." + "</blockquote>" + "<br>" + "-- <br>" + "Signature inside signature" + "</div>" + "</body></html>"; String withoutSignature = HtmlSignatureRemover.stripSignature(html); assertEquals("<html><head></head><body>" + "<blockquote>Some quote</blockquote>" + "<div>This is the body text</div>" + "</body></html>", withoutSignature); }
@Test public void shouldStripSignatureAfterLastBlockquoteTags() throws Exception { String html = "<html><head></head><body>" + "This is the body text" + "<br>" + "<blockquote>" + "Some quote" + "</blockquote>" + "<br>" + "-- <br>" + "Sent from my Android device with K-9 Mail. Please excuse my brevity." + "</body></html>"; String withoutSignature = HtmlSignatureRemover.stripSignature(html); assertEquals("<html><head></head><body>" + "This is the body text<br>" + "<blockquote>Some quote</blockquote>" + "</body></html>", withoutSignature); } |
MimeUtility { public static String getHeaderParameter(String headerValue, String parameterName) { if (headerValue == null) { return null; } headerValue = headerValue.replaceAll("\r|\n", ""); String[] parts = headerValue.split(";"); if (parameterName == null && parts.length > 0) { return parts[0].trim(); } for (String part : parts) { if (parameterName != null && part.trim().toLowerCase(Locale.US).startsWith(parameterName.toLowerCase(Locale.US))) { String[] partParts = part.split("=", 2); if (partParts.length == 2) { String parameter = partParts[1].trim(); int len = parameter.length(); if (len >= 2 && parameter.startsWith("\"") && parameter.endsWith("\"")) { return parameter.substring(1, len - 1); } else { return parameter; } } } } return null; } static String unfold(String s); static String unfoldAndDecode(String s); static String unfoldAndDecode(String s, Message message); static String foldAndEncode(String s); static String getHeaderParameter(String headerValue, String parameterName); static Map<String,String> getAllHeaderParameters(String headerValue); static Part findFirstPartByMimeType(Part part, String mimeType); static boolean mimeTypeMatches(String mimeType, String matchAgainst); static boolean isDefaultMimeType(String mimeType); static InputStream decodeBody(Body body); static void closeInputStreamWithoutDeletingTemporaryFiles(InputStream rawInputStream); static String getMimeTypeByExtension(String filename); static String getExtensionByMimeType(@NonNull String mimeType); static String getEncodingforType(String type); static boolean isMultipart(String mimeType); static boolean isMessage(String mimeType); static boolean isSameMimeType(String mimeType, String otherMimeType); static final String DEFAULT_ATTACHMENT_MIME_TYPE; static final String K9_SETTINGS_MIME_TYPE; } | @Test public void testGetHeaderParameter() { String result; result = MimeUtility.getHeaderParameter(";", null); assertEquals(null, result); result = MimeUtility.getHeaderParameter("name", "name"); assertEquals(null, result); result = MimeUtility.getHeaderParameter("name=", "name"); assertEquals("", result); result = MimeUtility.getHeaderParameter("name=\"", "name"); assertEquals("\"", result); result = MimeUtility.getHeaderParameter("name=value", "name"); assertEquals("value", result); result = MimeUtility.getHeaderParameter("name = value", "name"); assertEquals("value", result); result = MimeUtility.getHeaderParameter("name=\"value\"", "name"); assertEquals("value", result); result = MimeUtility.getHeaderParameter("name = \"value\"", "name"); assertEquals("value", result); result = MimeUtility.getHeaderParameter("name=\"\"", "name"); assertEquals("", result); result = MimeUtility.getHeaderParameter("text/html ; charset=\"windows-1251\"", null); assertEquals("text/html", result); result = MimeUtility.getHeaderParameter("text/HTML ; charset=\"windows-1251\"", null); assertEquals("text/HTML", result); } |
MimeUtility { public static boolean isMultipart(String mimeType) { return mimeType != null && mimeType.toLowerCase(Locale.US).startsWith("multipart/"); } static String unfold(String s); static String unfoldAndDecode(String s); static String unfoldAndDecode(String s, Message message); static String foldAndEncode(String s); static String getHeaderParameter(String headerValue, String parameterName); static Map<String,String> getAllHeaderParameters(String headerValue); static Part findFirstPartByMimeType(Part part, String mimeType); static boolean mimeTypeMatches(String mimeType, String matchAgainst); static boolean isDefaultMimeType(String mimeType); static InputStream decodeBody(Body body); static void closeInputStreamWithoutDeletingTemporaryFiles(InputStream rawInputStream); static String getMimeTypeByExtension(String filename); static String getExtensionByMimeType(@NonNull String mimeType); static String getEncodingforType(String type); static boolean isMultipart(String mimeType); static boolean isMessage(String mimeType); static boolean isSameMimeType(String mimeType, String otherMimeType); static final String DEFAULT_ATTACHMENT_MIME_TYPE; static final String K9_SETTINGS_MIME_TYPE; } | @Test public void isMultipart_withLowerCaseMultipart_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMultipart("multipart/mixed")); }
@Test public void isMultipart_withUpperCaseMultipart_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMultipart("MULTIPART/ALTERNATIVE")); }
@Test public void isMultipart_withMixedCaseMultipart_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMultipart("Multipart/Alternative")); }
@Test public void isMultipart_withoutMultipart_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMultipart("message/rfc822")); }
@Test public void isMultipart_withNullArgument_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMultipart(null)); } |
MimeUtility { public static boolean isMessage(String mimeType) { return isSameMimeType(mimeType, "message/rfc822"); } static String unfold(String s); static String unfoldAndDecode(String s); static String unfoldAndDecode(String s, Message message); static String foldAndEncode(String s); static String getHeaderParameter(String headerValue, String parameterName); static Map<String,String> getAllHeaderParameters(String headerValue); static Part findFirstPartByMimeType(Part part, String mimeType); static boolean mimeTypeMatches(String mimeType, String matchAgainst); static boolean isDefaultMimeType(String mimeType); static InputStream decodeBody(Body body); static void closeInputStreamWithoutDeletingTemporaryFiles(InputStream rawInputStream); static String getMimeTypeByExtension(String filename); static String getExtensionByMimeType(@NonNull String mimeType); static String getEncodingforType(String type); static boolean isMultipart(String mimeType); static boolean isMessage(String mimeType); static boolean isSameMimeType(String mimeType, String otherMimeType); static final String DEFAULT_ATTACHMENT_MIME_TYPE; static final String K9_SETTINGS_MIME_TYPE; } | @Test public void isMessage_withLowerCaseMessage_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMessage("message/rfc822")); }
@Test public void isMessage_withUpperCaseMessage_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMessage("MESSAGE/RFC822")); }
@Test public void isMessage_withMixedCaseMessage_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isMessage("Message/Rfc822")); }
@Test public void isMessage_withoutMessageRfc822_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMessage("Message/Partial")); }
@Test public void isMessage_withoutMessage_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMessage("multipart/mixed")); }
@Test public void isMessage_withNullArgument_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isMessage(null)); } |
MimeUtility { public static boolean isSameMimeType(String mimeType, String otherMimeType) { return mimeType != null && mimeType.equalsIgnoreCase(otherMimeType); } static String unfold(String s); static String unfoldAndDecode(String s); static String unfoldAndDecode(String s, Message message); static String foldAndEncode(String s); static String getHeaderParameter(String headerValue, String parameterName); static Map<String,String> getAllHeaderParameters(String headerValue); static Part findFirstPartByMimeType(Part part, String mimeType); static boolean mimeTypeMatches(String mimeType, String matchAgainst); static boolean isDefaultMimeType(String mimeType); static InputStream decodeBody(Body body); static void closeInputStreamWithoutDeletingTemporaryFiles(InputStream rawInputStream); static String getMimeTypeByExtension(String filename); static String getExtensionByMimeType(@NonNull String mimeType); static String getEncodingforType(String type); static boolean isMultipart(String mimeType); static boolean isMessage(String mimeType); static boolean isSameMimeType(String mimeType, String otherMimeType); static final String DEFAULT_ATTACHMENT_MIME_TYPE; static final String K9_SETTINGS_MIME_TYPE; } | @Test public void isSameMimeType_withSameTypeAndCase_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isSameMimeType("text/plain", "text/plain")); }
@Test public void isSameMimeType_withSameTypeButMixedCase_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isSameMimeType("text/plain", "Text/Plain")); }
@Test public void isSameMimeType_withSameTypeAndLowerAndUpperCase_shouldReturnTrue() throws Exception { assertTrue(MimeUtility.isSameMimeType("TEXT/PLAIN", "text/plain")); }
@Test public void isSameMimeType_withDifferentType_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isSameMimeType("text/plain", "text/html")); }
@Test public void isSameMimeType_withFirstArgumentBeingNull_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isSameMimeType(null, "text/html")); }
@Test public void isSameMimeType_withSecondArgumentBeingNull_shouldReturnFalse() throws Exception { assertFalse(MimeUtility.isSameMimeType("text/html", null)); } |
CharsetSupport { static String fixupCharset(String charset, Message message) throws MessagingException { if (charset == null || "0".equals(charset)) charset = "US-ASCII"; charset = charset.toLowerCase(Locale.US); if (charset.equals("cp932")) charset = SHIFT_JIS; if (charset.equals(SHIFT_JIS) || charset.equals("iso-2022-jp")) { String variant = JisSupport.getJisVariantFromMessage(message); if (variant != null) charset = "x-" + variant + "-" + charset + "-2007"; } return charset; } static void setCharset(String charset, Part part); static String getCharsetFromAddress(String address); } | @Test public void testFixupCharset() throws Exception { String charsetOnMail; String expect; charsetOnMail = "CP932"; expect = "shift_jis"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, new MimeMessage())); MimeMessage message; message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-docomo-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-docomo-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-docomo-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-docomo-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-docomo-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-docomo-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-softbank-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-softbank-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-softbank-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-softbank-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-kddi-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); message = new MimeMessage(); message.setHeader("From", "[email protected]"); charsetOnMail = "shift_jis"; expect = "x-kddi-shift_jis-2007"; assertEquals(expect, CharsetSupport.fixupCharset(charsetOnMail, message)); } |
DecoderUtil { public static String decodeEncodedWords(String body, Message message) { if (!body.contains("=?")) { return body; } int previousEnd = 0; boolean previousWasEncoded = false; StringBuilder sb = new StringBuilder(); while (true) { int begin = body.indexOf("=?", previousEnd); if (begin == -1) { sb.append(body.substring(previousEnd)); return sb.toString(); } int qm1 = body.indexOf('?', begin + 2); if (qm1 == -1) { sb.append(body.substring(previousEnd)); return sb.toString(); } int qm2 = body.indexOf('?', qm1 + 1); if (qm2 == -1) { sb.append(body.substring(previousEnd)); return sb.toString(); } int end = body.indexOf("?=", qm2 + 1); if (end == -1) { sb.append(body.substring(previousEnd)); return sb.toString(); } end += 2; String sep = body.substring(previousEnd, begin); String decoded = decodeEncodedWord(body, begin, end, message); if (decoded == null) { sb.append(sep); sb.append(body.substring(begin, end)); } else { if (!previousWasEncoded || !CharsetUtil.isWhitespace(sep)) { sb.append(sep); } sb.append(decoded); } previousEnd = end; previousWasEncoded = decoded != null; } } static String decodeEncodedWords(String body, Message message); } | @Test public void testDecodeEncodedWords() { String body, expect; MimeMessage message; body = "abc"; expect = "abc"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?us-ascii?q?abc?="; expect = "abc"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?"; expect = "=?"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=??"; expect = "=??"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=???"; expect = "=???"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=????"; expect = "=????"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=????="; expect = "=????="; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=??q??="; expect = "=??q??="; ; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=??q?a?="; expect = "a"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=??="; expect = "=??="; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?x?="; expect = "=?x?="; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?x??="; expect = "=?x??="; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?x?q?="; expect = "=?x?q?="; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?x?q??="; expect = "=?x?q??="; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?x?q?X?="; expect = "X"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?us-ascii?b?abc?="; expect = ""; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?us-ascii?q?abc?= =?"; expect = "abc =?"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?x?= =?"; expect = "=?x?= =?"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?utf-8?B?5Liq5Lq66YKu566xOkJVRyAjMzAyNDY6OumCruS7tuato+aWh+mZhOS7tuWQ?=\n" + "=?utf-8?B?jeensOecgeeVpeaYvuekuuS8mOWMlg==?="; expect = "个人邮箱:BUG #30246::邮件正文附件��称省略显示优化"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); body = "=?gb2312?B?Obv9t9az6cnu29rHsLqju6rHyLPHSlfN8rrAvsa16qOsuPzT0DIwvNIzOTnU?= " + "=?gb2312?B?qr6r0aG439DHytTLr77Gteq1yMTjwLSjoaOoQUSjqQ?="; expect = "9积分抽深圳前海华侨城JW万豪酒店,更有20家399��精选高星试睡酒店等你来!(AD�"; message = null; assertEquals(expect, DecoderUtil.decodeEncodedWords(body, message)); } |
SmtpDataStuffing extends FilterOutputStream { @Override public void write(int oneByte) throws IOException { if (oneByte == '\r') { state = STATE_CR; } else if ((state == STATE_CR) && (oneByte == '\n')) { state = STATE_CRLF; } else if ((state == STATE_CRLF) && (oneByte == '.')) { super.write('.'); state = STATE_NORMAL; } else { state = STATE_NORMAL; } super.write(oneByte); } SmtpDataStuffing(OutputStream out); @Override void write(int oneByte); } | @Test public void dotAtStartOfLine() throws IOException { smtpDataStuffing.write(bytesFor("Hello dot\r\n.")); assertEquals("Hello dot\r\n..", buffer.readUtf8()); }
@Test public void dotAtStartOfStream() throws IOException { smtpDataStuffing.write(bytesFor(".Hello dots")); assertEquals("..Hello dots", buffer.readUtf8()); }
@Test public void linesNotStartingWithDot() throws IOException { smtpDataStuffing.write(bytesFor("Hello\r\nworld\r\n")); assertEquals("Hello\r\nworld\r\n", buffer.readUtf8()); }
@Test public void dotsThatNeedStuffingMixedWithOnesThatDoNot() throws IOException { smtpDataStuffing.write(bytesFor("\r\n.Hello . dots.\r\n..\r\n.\r\n...")); assertEquals("\r\n..Hello . dots.\r\n...\r\n..\r\n....", buffer.readUtf8()); } |
FixedLengthInputStream extends InputStream { @Override public int read() throws IOException { if (mCount >= mLength) { return -1; } int d = mIn.read(); if (d != -1) { mCount++; } return d; } FixedLengthInputStream(InputStream in, int length); @Override int available(); @Override int read(); @Override int read(byte[] b, int offset, int length); @Override int read(byte[] b); @Override long skip(long n); @Override String toString(); void skipRemaining(); } | @Test public void read_withOverSizedByteArray_shouldReturnDataUpToLimit() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 6); byte[] data = new byte[100]; int numberOfBytesRead = fixedLengthInputStream.read(data); assertEquals(6, numberOfBytesRead); assertEquals("Hello ", ByteString.of(data, 0, numberOfBytesRead).utf8()); }
@Test public void read_withOverSizedByteArray_shouldNotConsumeMoreThanLimitFromUnderlyingStream() throws Exception { InputStream inputStream = inputStream("Hello World"); FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream, 6); fixedLengthInputStream.read(new byte[100]); assertRemainingInputStreamEquals("World", inputStream); }
@Test public void read_withByteArraySmallerThanLimit_shouldConsumeSizeOfByteArray() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 6); byte[] data = new byte[5]; int numberOfBytesRead = fixedLengthInputStream.read(data); assertEquals(5, numberOfBytesRead); assertEquals("Hello", ByteString.of(data).utf8()); }
@Test public void read_withOverSizedByteArrayInMiddleOfStream_shouldReturnDataUpToLimit() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 6); consumeBytes(fixedLengthInputStream, 5); byte[] data = new byte[10]; int numberOfBytesRead = fixedLengthInputStream.read(data); assertEquals(1, numberOfBytesRead); assertEquals(" ", ByteString.of(data, 0, numberOfBytesRead).utf8()); }
@Test public void read_withOverSizedByteArrayInMiddleOfStream_shouldNotConsumeMoreThanLimitFromUnderlyingStream() throws Exception { InputStream inputStream = inputStream("Hello World"); FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream, 6); consumeBytes(fixedLengthInputStream, 5); fixedLengthInputStream.read(new byte[10]); assertRemainingInputStreamEquals("World", inputStream); }
@Test public void read_atStartOfStream() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Word"), 2); int readByte = fixedLengthInputStream.read(); assertEquals('W', (char) readByte); }
@Test public void read_inMiddleOfStream() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Word"), 2); consumeBytes(fixedLengthInputStream, 1); int readByte = fixedLengthInputStream.read(); assertEquals('o', (char) readByte); }
@Test public void read_atEndOfStream_shouldReturnMinusOne() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello world"), 5); exhaustStream(fixedLengthInputStream); int readByte = fixedLengthInputStream.read(); assertEquals(-1, readByte); }
@Test public void readArray_atEndOfStream_shouldReturnMinusOne() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello world"), 5); exhaustStream(fixedLengthInputStream); int numberOfBytesRead = fixedLengthInputStream.read(new byte[2]); assertEquals(-1, numberOfBytesRead); }
@Test public void readArrayWithOffset_atEndOfStream_shouldReturnMinusOne() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello world"), 5); exhaustStream(fixedLengthInputStream); int numberOfBytesRead = fixedLengthInputStream.read(new byte[2], 0, 2); assertEquals(-1, numberOfBytesRead); } |
FixedLengthInputStream extends InputStream { @Override public int available() throws IOException { return mLength - mCount; } FixedLengthInputStream(InputStream in, int length); @Override int available(); @Override int read(); @Override int read(byte[] b, int offset, int length); @Override int read(byte[] b); @Override long skip(long n); @Override String toString(); void skipRemaining(); } | @Test public void available_atStartOfStream() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); int available = fixedLengthInputStream.available(); assertEquals(5, available); }
@Test public void available_afterPartialReadArray() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); consumeBytes(fixedLengthInputStream, 2); int available = fixedLengthInputStream.available(); assertEquals(3, available); }
@Test public void available_afterStreamHasBeenExhausted() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); exhaustStream(fixedLengthInputStream); int available = fixedLengthInputStream.available(); assertEquals(0, available); }
@Test public void available_afterSkip() throws Exception { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); guaranteedSkip(fixedLengthInputStream, 2); int available = fixedLengthInputStream.available(); assertEquals(3, available); } |
FixedLengthInputStream extends InputStream { public void skipRemaining() throws IOException { while (available() > 0) { skip(available()); } } FixedLengthInputStream(InputStream in, int length); @Override int available(); @Override int read(); @Override int read(byte[] b, int offset, int length); @Override int read(byte[] b); @Override long skip(long n); @Override String toString(); void skipRemaining(); } | @Test public void skipRemaining_shouldExhaustStream() throws IOException { FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream("Hello World"), 5); fixedLengthInputStream.skipRemaining(); assertInputStreamExhausted(fixedLengthInputStream); }
@Test public void skipRemaining_shouldNotConsumeMoreThanLimitFromUnderlyingInputStream() throws IOException { InputStream inputStream = inputStream("Hello World"); FixedLengthInputStream fixedLengthInputStream = new FixedLengthInputStream(inputStream, 6); fixedLengthInputStream.skipRemaining(); assertRemainingInputStreamEquals("World", inputStream); } |
SignSafeOutputStream extends FilterOutputStream { public SignSafeOutputStream(OutputStream out) { super(out); outBuffer = new byte[DEFAULT_BUFFER_SIZE]; } SignSafeOutputStream(OutputStream out); void encode(byte next); @Override void write(int b); @Override void write(byte[] b, int off, int len); @Override void flush(); @Override void close(); } | @Test public void testSignSafeOutputStream() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); OutputStream output = new SignSafeOutputStream(byteArrayOutputStream); output.write(INPUT_STRING.getBytes("US-ASCII")); output.close(); assertEquals(EXPECTED_SIGNSAFE, new String(byteArrayOutputStream.toByteArray(), "US-ASCII")); } |
Address implements Serializable { @VisibleForTesting static String quoteString(String s) { if (s == null) { return null; } if (!s.matches("^\".*\"$")) { return "\"" + s + "\""; } else { return s; } } Address(Address address); Address(String address, String personal); Address(String address); private Address(String address, String personal, boolean parse); String getAddress(); String getHostname(); void setAddress(String address); String getPersonal(); void setPersonal(String newPersonal); static Address[] parseUnencoded(String addressList); static Address[] parse(String addressList); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static String toString(Address[] addresses); String toEncodedString(); static String toEncodedString(Address[] addresses); static Address[] unpack(String addressList); static String pack(Address[] addresses); static String quoteAtoms(final String text); } | @Test public void stringQuotationShouldCorrectlyQuote() { assertEquals("\"sample\"", Address.quoteString("sample")); assertEquals("\"\"sample\"\"", Address.quoteString("\"\"sample\"\"")); assertEquals("\"sample\"", Address.quoteString("\"sample\"")); assertEquals("\"sa\"mp\"le\"", Address.quoteString("sa\"mp\"le")); assertEquals("\"sa\"mp\"le\"", Address.quoteString("\"sa\"mp\"le\"")); assertEquals("\"\"\"", Address.quoteString("\"")); } |
Pop3Store extends RemoteStore { public static ServerSettings decodeUri(String uri) { String host; int port; ConnectionSecurity connectionSecurity; String username = null; String password = null; String clientCertificateAlias = null; URI pop3Uri; try { pop3Uri = new URI(uri); } catch (URISyntaxException use) { throw new IllegalArgumentException("Invalid Pop3Store URI", use); } String scheme = pop3Uri.getScheme(); if (scheme.equals("pop3")) { connectionSecurity = ConnectionSecurity.NONE; port = Type.POP3.defaultPort; } else if (scheme.startsWith("pop3+tls")) { connectionSecurity = ConnectionSecurity.STARTTLS_REQUIRED; port = Type.POP3.defaultPort; } else if (scheme.startsWith("pop3+ssl")) { connectionSecurity = ConnectionSecurity.SSL_TLS_REQUIRED; port = Type.POP3.defaultTlsPort; } else { throw new IllegalArgumentException("Unsupported protocol (" + scheme + ")"); } host = pop3Uri.getHost(); if (pop3Uri.getPort() != -1) { port = pop3Uri.getPort(); } AuthType authType = AuthType.PLAIN; if (pop3Uri.getUserInfo() != null) { int userIndex = 0, passwordIndex = 1; String userinfo = pop3Uri.getUserInfo(); String[] userInfoParts = userinfo.split(":"); if (userInfoParts.length > 2 || userinfo.endsWith(":") ) { userIndex++; passwordIndex++; authType = AuthType.valueOf(userInfoParts[0]); } username = decodeUtf8(userInfoParts[userIndex]); if (userInfoParts.length > passwordIndex) { if (authType == AuthType.EXTERNAL) { clientCertificateAlias = decodeUtf8(userInfoParts[passwordIndex]); } else { password = decodeUtf8(userInfoParts[passwordIndex]); } } } return new ServerSettings(ServerSettings.Type.POP3, host, port, connectionSecurity, authType, username, password, clientCertificateAlias); } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); } | @Test public void decodeUri_withTLSUri_shouldUseStartTls() { ServerSettings settings = Pop3Store.decodeUri("pop3+tls+: assertEquals(settings.connectionSecurity, ConnectionSecurity.STARTTLS_REQUIRED); }
@Test public void decodeUri_withPlainUri_shouldUseNoSecurity() { ServerSettings settings = Pop3Store.decodeUri("pop3: assertEquals(settings.connectionSecurity, ConnectionSecurity.NONE); }
@Test public void decodeUri_withExternalCertificateShouldProvideAlias_shouldUseNoSecurity() { ServerSettings settings = Pop3Store.decodeUri("pop3: assertEquals(settings.clientCertificateAlias, "clientCert"); }
@Test(expected = IllegalArgumentException.class) public void decodeUri_withNonPop3Uri_shouldThrowException() { Pop3Store.decodeUri("imap: } |
Pop3Store extends RemoteStore { public static String createUri(ServerSettings server) { String userEnc = encodeUtf8(server.username); String passwordEnc = (server.password != null) ? encodeUtf8(server.password) : ""; String clientCertificateAliasEnc = (server.clientCertificateAlias != null) ? encodeUtf8(server.clientCertificateAlias) : ""; String scheme; switch (server.connectionSecurity) { case SSL_TLS_REQUIRED: scheme = "pop3+ssl+"; break; case STARTTLS_REQUIRED: scheme = "pop3+tls+"; break; default: case NONE: scheme = "pop3"; break; } AuthType authType = server.authenticationType; String userInfo; if (AuthType.EXTERNAL == authType) { userInfo = authType.name() + ":" + userEnc + ":" + clientCertificateAliasEnc; } else { userInfo = authType.name() + ":" + userEnc + ":" + passwordEnc; } try { return new URI(scheme, userInfo, server.host, server.port, null, null, null).toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Can't create Pop3Store URI", e); } } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); } | @Test public void createUri_withSSLTLS_required_shouldProduceSSLUri() { ServerSettings settings = new ServerSettings(Type.POP3, "server", 12345, ConnectionSecurity.SSL_TLS_REQUIRED, AuthType.PLAIN, "user", "password", null); String uri = Pop3Store.createUri(settings); assertEquals(uri, "pop3+ssl+: }
@Test public void createUri_withSTARTTLSRequired_shouldProduceTLSUri() { ServerSettings settings = new ServerSettings(Type.POP3, "server", 12345, ConnectionSecurity.STARTTLS_REQUIRED, AuthType.PLAIN, "user", "password", null); String uri = Pop3Store.createUri(settings); assertEquals(uri, "pop3+tls+: }
@Test public void createUri_withNONE_shouldProducePop3Uri() { ServerSettings settings = new ServerSettings(Type.POP3, "server", 12345, ConnectionSecurity.NONE, AuthType.PLAIN, "user", "password", null); String uri = Pop3Store.createUri(settings); assertEquals(uri, "pop3: }
@Test public void createUri_withPLAIN_shouldProducePlainAuthUri() { ServerSettings settings = new ServerSettings(Type.POP3, "server", 12345, ConnectionSecurity.NONE, AuthType.PLAIN, "user", "password", null); String uri = Pop3Store.createUri(settings); assertEquals(uri, "pop3: }
@Test public void createUri_withEXTERNAL_shouldProduceExternalAuthUri() { ServerSettings settings = new ServerSettings(Type.POP3, "server", 12345, ConnectionSecurity.NONE, AuthType.EXTERNAL, "user", "password", "clientCert"); String uri = Pop3Store.createUri(settings); assertEquals(uri, "pop3: }
@Test public void createUri_withCRAMMD5_shouldProduceCRAMMD5AuthUri() { ServerSettings settings = new ServerSettings(Type.POP3, "server", 12345, ConnectionSecurity.NONE, AuthType.CRAM_MD5, "user", "password", "clientCert"); String uri = Pop3Store.createUri(settings); assertEquals(uri, "pop3: } |
Pop3Store extends RemoteStore { @Override @NonNull public Pop3Folder getFolder(String name) { Pop3Folder folder = mFolders.get(name); if (folder == null) { folder = new Pop3Folder(this, name); mFolders.put(folder.getId(), folder); } return folder; } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); } | @Test public void getFolder_shouldReturnSameFolderEachTime() { Pop3Folder folderOne = store.getFolder("TestFolder"); Pop3Folder folderTwo = store.getFolder("TestFolder"); assertSame(folderOne, folderTwo); }
@Test public void getFolder_shouldReturnFolderWithCorrectName() throws Exception { Pop3Folder folder = store.getFolder("TestFolder"); assertEquals("TestFolder", folder.getId()); }
@Test public void open_withAuthResponseUsingAuthPlain_shouldRetrieveMessageCountOnAuthenticatedSocket() throws Exception { String response = INITIAL_RESPONSE + AUTH_HANDLE_RESPONSE + CAPA_RESPONSE + AUTH_PLAIN_AUTHENTICATED_RESPONSE + STAT_RESPONSE; when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8"))); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(byteArrayOutputStream); Pop3Folder folder = store.getFolder("Inbox"); folder.open(Folder.OPEN_MODE_RW); assertEquals(20, folder.getMessageCount()); assertEquals(AUTH + CAPA + AUTH_PLAIN_WITH_LOGIN + STAT, byteArrayOutputStream.toString("UTF-8")); }
@Test(expected = AuthenticationFailedException.class) public void open_withFailedAuth_shouldThrow() throws Exception { String response = INITIAL_RESPONSE + AUTH_HANDLE_RESPONSE + CAPA_RESPONSE + AUTH_PLAIN_FAILED_RESPONSE; when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8"))); Pop3Folder folder = store.getFolder("Inbox"); folder.open(Folder.OPEN_MODE_RW); } |
Pop3Store extends RemoteStore { @Override @NonNull public List <Pop3Folder> getFolders(boolean forceListAll) throws MessagingException { List<Pop3Folder> folders = new LinkedList<>(); folders.add(getFolder(mStoreConfig.getInboxFolderId())); return folders; } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); } | @Test public void getPersonalNamespace_shouldReturnListConsistingOfInbox() throws Exception { List<Pop3Folder> folders = store.getFolders(true); assertEquals(1, folders.size()); assertEquals("Inbox", folders.get(0).getId()); } |
EthereumUriParser implements UriParser { @Override public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { Matcher matcher = ETHEREUM_URI_PATTERN.matcher(text); if (!matcher.find(startPos) || matcher.start() != startPos) { return startPos; } String ethereumURI = matcher.group(); outputBuffer.append("<a href=\"") .append(ethereumURI) .append("\">") .append(ethereumURI) .append("</a>"); return matcher.end(); } @Override int linkifyUri(String text, int startPos, StringBuffer outputBuffer); } | @Test public void uriInMiddleOfInput() throws Exception { String prefix = "prefix "; String uri = "ethereum:0xfdf1210fc262c73d0436236a0e07be419babbbc4?value=42"; String text = prefix + uri; parser.linkifyUri(text, prefix.length(), outputBuffer); assertLinkOnly(uri, outputBuffer); } |
Pop3Store extends RemoteStore { @Override public boolean isSeenFlagSupported() { return false; } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); } | @Test public void isSeenFlagSupported_shouldReturnFalse() throws Exception { boolean result = store.isSeenFlagSupported(); assertFalse(result); } |
Pop3Store extends RemoteStore { @Override public void checkSettings() throws MessagingException { Pop3Folder folder = new Pop3Folder(this, mStoreConfig.getInboxFolderId()); try { folder.open(Folder.OPEN_MODE_RW); folder.requestUidl(); } finally { folder.close(); } } Pop3Store(StoreConfig storeConfig, TrustedSocketFactory socketFactory); static ServerSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override @NonNull Pop3Folder getFolder(String name); @Override @NonNull List <Pop3Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override void checkSettings(); @Override boolean isSeenFlagSupported(); Pop3Connection createConnection(); } | @Test(expected = MessagingException.class) public void checkSetting_whenConnectionThrowsException_shouldThrowMessagingException() throws Exception { when(mockTrustedSocketFactory.createSocket(any(Socket.class), anyString(), anyInt(), anyString())).thenThrow(new IOException("Test")); store.checkSettings(); }
@Test(expected = MessagingException.class) public void checkSetting_whenUidlUnsupported_shouldThrowMessagingException() throws Exception { String response = INITIAL_RESPONSE + AUTH_HANDLE_RESPONSE + CAPA_RESPONSE + AUTH_PLAIN_AUTHENTICATED_RESPONSE + STAT_RESPONSE + UIDL_UNSUPPORTED_RESPONSE; when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8"))); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(byteArrayOutputStream); store.checkSettings(); }
@Test public void checkSetting_whenUidlSupported_shouldReturn() throws Exception { String response = INITIAL_RESPONSE + AUTH_HANDLE_RESPONSE + CAPA_RESPONSE + AUTH_PLAIN_AUTHENTICATED_RESPONSE + STAT_RESPONSE + UIDL_SUPPORTED_RESPONSE; when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes("UTF-8"))); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(byteArrayOutputStream); store.checkSettings(); } |
Pop3Capabilities { @Override public String toString() { return String.format("CRAM-MD5 %b, PLAIN %b, STLS %b, TOP %b, UIDL %b, EXTERNAL %b", cramMD5, authPlain, stls, top, uidl, external); } @Override String toString(); } | @Test public void toString_producesReadableOutput() { String result = new Pop3Capabilities().toString(); assertEquals( "CRAM-MD5 false, PLAIN false, STLS false, TOP false, UIDL false, EXTERNAL false", result); } |
Pop3Folder extends Folder<Pop3Message> { @Override public boolean create(FolderType type) throws MessagingException { return false; } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp,
MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void create_withHoldsFoldersArgument_shouldDoNothing() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); boolean result = folder.create(FolderType.HOLDS_FOLDERS); assertFalse(result); verifyZeroInteractions(mockConnection); }
@Test public void create_withHoldsMessagesArgument_shouldDoNothing() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); boolean result = folder.create(FolderType.HOLDS_MESSAGES); assertFalse(result); verifyZeroInteractions(mockConnection); } |
Pop3Folder extends Folder<Pop3Message> { @Override public boolean exists() throws MessagingException { return name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderId()); } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp,
MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void exists_withInbox_shouldReturnTrue() throws Exception { boolean result = folder.exists(); assertTrue(result); }
@Test public void exists_withNonInboxFolder_shouldReturnFalse() throws Exception { folder = new Pop3Folder(mockStore, "TestFolder"); boolean result = folder.exists(); assertFalse(result); } |
UriLinkifier { public static void linkifyText(String text, StringBuffer outputBuffer) { int currentPos = 0; Matcher matcher = URI_SCHEME.matcher(text); while (matcher.find(currentPos)) { int startPos = matcher.start(1); String textBeforeMatch = text.substring(currentPos, startPos); outputBuffer.append(textBeforeMatch); String scheme = matcher.group(1).toLowerCase(Locale.US); UriParser parser = SUPPORTED_URIS.get(scheme); int newPos = parser.linkifyUri(text, startPos, outputBuffer); boolean uriWasNotLinkified = newPos <= startPos; if (uriWasNotLinkified) { outputBuffer.append(text.charAt(startPos)); currentPos = startPos + 1; } else { currentPos = (newPos > currentPos) ? newPos : currentPos + 1; } if (currentPos >= text.length()) { break; } } String textAfterLastMatch = text.substring(currentPos); outputBuffer.append(textAfterLastMatch); } static void linkifyText(String text, StringBuffer outputBuffer); } | @Test public void emptyText() { String text = ""; UriLinkifier.linkifyText(text, outputBuffer); assertEquals(text, outputBuffer.toString()); }
@Test public void textWithoutUri_shouldBeCopiedToOutputBuffer() { String text = "some text here"; UriLinkifier.linkifyText(text, outputBuffer); assertEquals(text, outputBuffer.toString()); }
@Test public void simpleUri() { String uri = "http: UriLinkifier.linkifyText(uri, outputBuffer); assertLinkOnly(uri, outputBuffer); }
@Test public void uriPrecededBySpace() { String text = " http: UriLinkifier.linkifyText(text, outputBuffer); assertEquals(" <a href=\"http: }
@Test public void uriPrecededByOpeningParenthesis() { String text = "(http: UriLinkifier.linkifyText(text, outputBuffer); assertEquals("(<a href=\"http: }
@Test public void uriPrecededBySomeText() { String uri = "Check out my fantastic URI: http: UriLinkifier.linkifyText(uri, outputBuffer); assertEquals("Check out my fantastic URI: <a href=\"http: outputBuffer.toString()); }
@Test public void uriWithTrailingText() { String uri = "http: UriLinkifier.linkifyText(uri, outputBuffer); assertEquals("<a href=\"http: }
@Test public void uriEmbeddedInText() { String uri = "prefix http: UriLinkifier.linkifyText(uri, outputBuffer); assertEquals("prefix <a href=\"http: }
@Test public void uriWithUppercaseScheme() { String uri = "HTTP: UriLinkifier.linkifyText(uri, outputBuffer); assertEquals("<a href=\"HTTP: }
@Test public void uriNotPrecededByValidSeparator_shouldNotBeLinkified() { String text = "myhttp: UriLinkifier.linkifyText(text, outputBuffer); assertEquals(text, outputBuffer.toString()); }
@Test public void uriNotPrecededByValidSeparatorFollowedByValidUri() { String text = "myhttp: http: UriLinkifier.linkifyText(text, outputBuffer); assertEquals("myhttp: <a href=\"http: }
@Test public void schemaMatchWithInvalidUriInMiddleOfTextFollowedByValidUri() { String text = "prefix http:42 http: UriLinkifier.linkifyText(text, outputBuffer); assertEquals("prefix http:42 <a href=\"http: }
@Test public void multipleValidUrisInRow() { String text = "prefix http: UriLinkifier.linkifyText(text, outputBuffer); assertEquals( "prefix <a href=\"http: "<a href=\"http: outputBuffer.toString()); } |
Pop3Folder extends Folder<Pop3Message> { @Override public int getUnreadMessageCount() throws MessagingException { return -1; } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp,
MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void getUnreadMessageCount_shouldBeMinusOne() throws Exception { int result = folder.getUnreadMessageCount(); assertEquals(-1, result); } |
Pop3Folder extends Folder<Pop3Message> { @Override public int getFlaggedMessageCount() throws MessagingException { return -1; } Pop3Folder(Pop3Store pop3Store, String name); @Override String getParentId(); @Override synchronized void open(int mode); @Override boolean isOpen(); @Override int getMode(); @Override void close(); @Override String getId(); @Override String getName(); @Override boolean create(FolderType type); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override Pop3Message getMessage(String uid); @Override List<Pop3Message> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<Pop3Message> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<Pop3Message> messages, FetchProfile fp,
MessageRetrievalListener<Pop3Message> listener); @Override Map<String, String> appendMessages(List<? extends Message> messages); @Override void delete(boolean recurse); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override boolean isFlagSupported(Flag flag); @Override boolean supportsFetchingFlags(); @Override boolean equals(Object o); @Override int hashCode(); } | @Test public void getFlaggedMessageCount_shouldBeMinusOne() throws Exception { int result = folder.getFlaggedMessageCount(); assertEquals(-1, result); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.