method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ReplyToParser { public ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account) { Address[] candidateAddress; Address[] listPostAddresses = ListHeaders.getListPostAddresses(message); Address[] replyToAddresses = message.getReplyTo(); Address[] fromAddresses = message.getFrom(); if (listPostAddresses.length > 0) { candidateAddress = listPostAddresses; } else if (replyToAddresses.length > 0) { candidateAddress = replyToAddresses; } else { candidateAddress = fromAddresses; } boolean replyToAddressIsUserIdentity = account.isAnIdentity(candidateAddress); if (replyToAddressIsUserIdentity) { candidateAddress = message.getRecipients(RecipientType.TO); } return new ReplyToAddresses(candidateAddress); } ReplyToAddresses getRecipientsToReplyTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyListTo(Message message, Account account); ReplyToAddresses getRecipientsToReplyAllTo(Message message, Account account); }### Answer:
@Test public void getRecipientsToReplyListTo_should_prefer_listPost_over_from_field() throws Exception { when(message.getReplyTo()).thenReturn(EMPTY_ADDRESSES); when(message.getHeader(ListHeaders.LIST_POST_HEADER)).thenReturn(LIST_POST_HEADER_VALUES); when(message.getFrom()).thenReturn(FROM_ADDRESSES); ReplyToAddresses result = replyToParser.getRecipientsToReplyListTo(message, account); assertArrayEquals(LIST_POST_ADDRESSES, result.to); assertArrayEquals(EMPTY_ADDRESSES, result.cc); verify(account).isAnIdentity(result.to); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void onToTokenAdded_notifiesListenerOfRecipientChange() { recipientPresenter.onToTokenAdded(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onToTokenChanged_notifiesListenerOfRecipientChange() { recipientPresenter.onToTokenChanged(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onToTokenRemoved_notifiesListenerOfRecipientChange() { recipientPresenter.onToTokenRemoved(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onCcTokenAdded_notifiesListenerOfRecipientChange() { recipientPresenter.onCcTokenAdded(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onCcTokenChanged_notifiesListenerOfRecipientChange() { recipientPresenter.onCcTokenChanged(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onCcTokenRemoved_notifiesListenerOfRecipientChange() { recipientPresenter.onCcTokenRemoved(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onBccTokenAdded_notifiesListenerOfRecipientChange() { recipientPresenter.onBccTokenAdded(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onBccTokenChanged_notifiesListenerOfRecipientChange() { recipientPresenter.onBccTokenChanged(); verify(listener).onRecipientsChanged(); } |
### Question:
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(); }### Answer:
@Test public void onBccTokenRemoved_notifiesListenerOfRecipientChange() { recipientPresenter.onBccTokenRemoved(); verify(listener).onRecipientsChanged(); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
BaseNotifications { protected boolean isDeleteActionEnabled() { NotificationQuickDelete deleteOption = QMail.getNotificationQuickDeleteBehaviour(); return deleteOption == NotificationQuickDelete.ALWAYS || deleteOption == NotificationQuickDelete.FOR_SINGLE_MSG; } protected BaseNotifications(NotificationController controller, NotificationActionCreator actionCreator); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void testClearSendingNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.clearSendingNotification(account); verify(notificationManager).cancel(notificationId); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void testClearSendFailedNotification() throws Exception { int notificationId = NotificationIds.getFetchingMailNotificationId(account); syncNotifications.clearFetchingMailNotification(account); verify(notificationManager).cancel(notificationId); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test public void testClearSendFailedNotification() throws Exception { sendFailedNotifications.clearSendFailedNotification(account); verify(notificationManager).cancel(notificationId); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void testContainsStarredMessages() throws Exception { assertFalse(notificationData.containsStarredMessages()); notificationData.addNotificationContent(createNotificationContentForStarredMessage()); assertTrue(notificationData.containsStarredMessages()); } |
### Question:
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(); }### Answer:
@Test public void testIsSingleMessageNotification() throws Exception { assertFalse(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("1")); assertTrue(notificationData.isSingleMessageNotification()); notificationData.addNotificationContent(createNotificationContent("2")); assertFalse(notificationData.isSingleMessageNotification()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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]); } |
### Question:
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(); }### Answer:
@Test public void testGetAccount() throws Exception { assertEquals(account, notificationData.getAccount()); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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: } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; } }### Answer:
@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")); } |
### Question:
FlowedMessageUtils { static boolean isDelSp(String contentType) { if (isFormatFlowed(contentType)) { String delSpParameter = getHeaderParameter(contentType, HEADER_PARAM_DELSP); return HEADER_DELSP_YES.equalsIgnoreCase(delSpParameter); } return false; } }### Answer:
@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")); } |
### Question:
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; }### Answer:
@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); } |
### Question:
HtmlSignatureRemover { public static String stripSignature(String content) { return new HtmlSignatureRemover().stripSignatureInternal(content); } static String stripSignature(String content); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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("\"")); } |
### Question:
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(); }### Answer:
@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: } |
### Question:
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(); }### Answer:
@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: } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void getPersonalNamespace_shouldReturnListConsistingOfInbox() throws Exception { List<Pop3Folder> folders = store.getFolders(true); assertEquals(1, folders.size()); assertEquals("Inbox", folders.get(0).getId()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void isSeenFlagSupported_shouldReturnFalse() throws Exception { boolean result = store.isSeenFlagSupported(); assertFalse(result); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void getUnreadMessageCount_shouldBeMinusOne() throws Exception { int result = folder.getUnreadMessageCount(); assertEquals(-1, result); } |
### Question:
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(); }### Answer:
@Test public void getFlaggedMessageCount_shouldBeMinusOne() throws Exception { int result = folder.getFlaggedMessageCount(); assertEquals(-1, result); } |
### Question:
Pop3Folder extends Folder<Pop3Message> { @Override public synchronized void open(int mode) throws MessagingException { if (isOpen()) { return; } if (!name.equalsIgnoreCase(pop3Store.getConfig().getInboxFolderId())) { throw new MessagingException("Folder does not exist"); } connection = pop3Store.createConnection(); String response = connection.executeSimpleCommand(STAT_COMMAND); String[] parts = response.split(" "); messageCount = Integer.parseInt(parts[1]); uidToMsgMap.clear(); msgNumToMsgMap.clear(); uidToMsgNumMap.clear(); } 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(); }### Answer:
@Test(expected = MessagingException.class) public void open_withoutInboxFolder_shouldThrow() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); folder.open(Folder.OPEN_MODE_RW); }
@Test public void open_withoutInboxFolder_shouldNotTryAndCreateConnection() throws Exception { Pop3Folder folder = new Pop3Folder(mockStore, "TestFolder"); try { folder.open(Folder.OPEN_MODE_RW); } catch (Exception ignored) {} verify(mockStore, never()).createConnection(); }
@Test(expected = MessagingException.class) public void open_withInboxFolderWithExceptionCreatingConnection_shouldThrow() throws MessagingException { when(mockStore.createConnection()).thenThrow(new MessagingException("Test")); folder.open(Folder.OPEN_MODE_RW); }
@Test(expected = MessagingException.class) public void open_withInboxFolder_whenStatCommandFails_shouldThrow() throws MessagingException { when(mockConnection.executeSimpleCommand(Pop3Commands.STAT_COMMAND)) .thenThrow(new MessagingException("Test")); folder.open(Folder.OPEN_MODE_RW); } |
### Question:
Pop3Folder extends Folder<Pop3Message> { @Override public void close() { try { if (isOpen()) { connection.executeSimpleCommand(QUIT_COMMAND); } } catch (Exception e) { } if (connection != null) { connection.close(); connection = null; } } 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(); }### Answer:
@Test public void close_onNonOpenedFolder_succeeds() throws MessagingException { folder.close(); } |
### Question:
Pop3Connection { InputStream getInputStream() { return in; } Pop3Connection(Pop3Settings settings,
TrustedSocketFactory trustedSocketFactory); }### Answer:
@Test public void withTLS_connectsToSocket() throws Exception { String response = INITIAL_RESPONSE + AUTH_HANDLE_RESPONSE + CAPA_RESPONSE + AUTH_PLAIN_AUTHENTICATED_RESPONSE; when(mockSocket.getInputStream()).thenReturn(new ByteArrayInputStream(response.getBytes())); setSettingsForMockSocket(); settings.setAuthType(AuthType.PLAIN); new Pop3Connection(settings, mockTrustedSocketFactory); assertEquals(AUTH + CAPA + AUTH_PLAIN_WITH_LOGIN, new String(outputStream.toByteArray())); } |
### Question:
WebDavStore extends RemoteStore { public static String createUri(ServerSettings server) { return WebDavStoreUriCreator.create(server); } WebDavStore(StoreConfig storeConfig, QMailHttpClientFactory clientFactory); static WebDavStoreSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override void checkSettings(); @Override @NonNull List<? extends Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override @NonNull WebDavFolder getFolder(String name); @Override boolean isMoveCapable(); @Override boolean isCopyCapable(); CookieStore getAuthCookies(); String getAlias(); String getUrl(); QMailHttpClient getHttpClient(); String getAuthString(); @Override boolean isSendCapable(); @Override void sendMessages(List<? extends Message> messages); }### Answer:
@Test public void createUri_withSetting_shouldProvideUri() { ServerSettings serverSettings = new ServerSettings(Type.WebDAV, "example.org", 123456, ConnectionSecurity.NONE, AuthType.PLAIN, "user", "password", null); String result = WebDavStore.createUri(serverSettings); assertEquals("webdav: }
@Test public void createUri_withSettingsWithTLS_shouldProvideSSLUri() { ServerSettings serverSettings = new ServerSettings(Type.WebDAV, "example.org", 123456, ConnectionSecurity.SSL_TLS_REQUIRED, AuthType.PLAIN, "user", "password", null); String result = WebDavStore.createUri(serverSettings); assertEquals("webdav+ssl+: } |
### Question:
WebDavStore extends RemoteStore { @Override @NonNull public WebDavFolder getFolder(String name) { WebDavFolder folder = this.folderList.get(name); if (folder == null) { folder = new WebDavFolder(this, name); folderList.put(name, folder); } return folder; } WebDavStore(StoreConfig storeConfig, QMailHttpClientFactory clientFactory); static WebDavStoreSettings decodeUri(String uri); static String createUri(ServerSettings server); @Override void checkSettings(); @Override @NonNull List<? extends Folder> getFolders(boolean forceListAll); @NonNull @Override List<? extends Folder> getSubFolders(String parentFolderId, boolean forceListAll); @Override @NonNull WebDavFolder getFolder(String name); @Override boolean isMoveCapable(); @Override boolean isCopyCapable(); CookieStore getAuthCookies(); String getAlias(); String getUrl(); QMailHttpClient getHttpClient(); String getAuthString(); @Override boolean isSendCapable(); @Override void sendMessages(List<? extends Message> messages); }### Answer:
@Test public void getFolder_shouldReturnWebDavFolderInstance() throws Exception { WebDavStore webDavStore = createDefaultWebDavStore(); Folder result = webDavStore.getFolder("INBOX"); assertEquals(WebDavFolder.class, result.getClass()); }
@Test public void getFolder_calledTwice_shouldReturnFirstInstance() throws Exception { WebDavStore webDavStore = createDefaultWebDavStore(); String folderName = "Trash"; Folder webDavFolder = webDavStore.getFolder(folderName); Folder result = webDavStore.getFolder(folderName); assertSame(webDavFolder, result); } |
### Question:
WebDavFolder extends Folder<WebDavMessage> { @Override public boolean isOpen() { return this.mIsOpen; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer:
@Test public void folder_does_not_start_open() throws MessagingException { assertFalse(folder.isOpen()); } |
### Question:
WebDavFolder extends Folder<WebDavMessage> { @Override public boolean exists() { return true; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer:
@Test public void exists_is_always_true() throws Exception { assertTrue(folder.exists()); } |
### Question:
WebDavFolder extends Folder<WebDavMessage> { private int getMessageCount(boolean read) throws MessagingException { String isRead; int messageCount = 0; Map<String, String> headers = new HashMap<String, String>(); String messageBody; if (read) { isRead = "True"; } else { isRead = "False"; } messageBody = store.getMessageCountXml(isRead); headers.put("Brief", "t"); DataSet dataset = store.processRequest(this.folderUrl, "SEARCH", messageBody, headers); if (dataset != null) { messageCount = dataset.getMessageCount(); } if (K9MailLib.isDebug() && DEBUG_PROTOCOL_WEBDAV) { Timber.v("Counted messages and webdav returned: %d", messageCount); } return messageCount; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer:
@Test public void can_fetch_message_count() throws Exception { int messageCount = 23; HashMap<String, String> headers = new HashMap<>(); headers.put("Brief", "t"); String messageCountXml = "<xml>MessageCountXml</xml>"; when(mockStore.getMessageCountXml("True")).thenReturn(messageCountXml); when(mockStore.processRequest("https: "SEARCH", messageCountXml, headers)).thenReturn(mockDataSet); when(mockDataSet.getMessageCount()).thenReturn(messageCount); int result = folder.getMessageCount(); assertEquals(messageCount, result); } |
### Question:
WebDavFolder extends Folder<WebDavMessage> { @Override public Map<String, String> moveMessages(List<? extends Message> messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getId(), true); return null; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer:
@Test public void moveMessages_should_requestMoveXml() throws Exception { setupMoveOrCopy(); folder.moveMessages(messages, destinationFolder); verify(mockStore).getMoveOrCopyMessagesReadXml(eq(new String[]{"url1"}), eq(true)); }
@Test public void moveMessages_should_send_move_command() throws Exception { setupMoveOrCopy(); folder.moveMessages(messages, destinationFolder); verify(mockStore).processRequest("https: moveOrCopyXml, moveOrCopyHeaders, false); } |
### Question:
WebDavFolder extends Folder<WebDavMessage> { @Override public Map<String, String> copyMessages(List<? extends Message> messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getId(), false); return null; } WebDavFolder(WebDavStore nStore, String id); void setUrl(String url); @Override void open(int mode); @Override Map<String, String> copyMessages(List<? extends Message> messages, Folder folder); @Override Map<String, String> moveMessages(List<? extends Message> messages, Folder folder); @Override void delete(List<? extends Message> msgs, String trashFolderName); @Override int getMessageCount(); @Override int getUnreadMessageCount(); @Override int getFlaggedMessageCount(); @Override boolean isOpen(); @Override int getMode(); @Override String getId(); @Override String getParentId(); @Override String getName(); @Override boolean exists(); @Override boolean canHaveSubFolders(); @Override void close(); @Override boolean create(FolderType type); @Override void delete(boolean recursive); @Override WebDavMessage getMessage(String uid); @Override List<WebDavMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<WebDavMessage> listener); @Override boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate); @Override void fetch(List<WebDavMessage> messages, FetchProfile fp, MessageRetrievalListener<WebDavMessage> listener); @Override void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value); @Override Map<String, String> appendMessages(List<? extends Message> messages); List<? extends Message> appendWebDavMessages(List<? extends Message> messages); @Override boolean equals(Object o); @Override String getUidFromMessageId(Message message); @Override void setFlags(final Set<Flag> flags, boolean value); String getUrl(); }### Answer:
@Test public void copyMessages_should_requestCopyXml() throws Exception { setupMoveOrCopy(); folder.copyMessages(messages, destinationFolder); verify(mockStore).getMoveOrCopyMessagesReadXml(eq(new String[]{"url1"}), eq(false)); }
@Test public void copyMessages_should_send_copy_command() throws Exception { setupMoveOrCopy(); folder.copyMessages(messages, destinationFolder); verify(mockStore).processRequest("https: moveOrCopyXml, moveOrCopyHeaders, false); } |
### Question:
WebDavMessage extends MimeMessage { @Override public void delete(String trashFolderName) throws MessagingException { WebDavFolder wdFolder = (WebDavFolder) getFolder(); Timber.i("Deleting message by moving to %s", trashFolderName); wdFolder.moveMessages(Collections.singletonList(this), wdFolder.getStore().getFolder(trashFolderName)); } WebDavMessage(String uid, Folder folder); void setUrl(String url); String getUrl(); void setSize(int size); void setFlagInternal(Flag flag, boolean set); void setNewHeaders(ParsedMessageEnvelope envelope); @Override void delete(String trashFolderName); @Override void setFlag(Flag flag, boolean set); }### Answer:
@Test public void delete_asks_folder_to_delete_message() throws MessagingException { when(mockFolder.getStore()).thenReturn(mockStore); when(mockStore.getFolder("Trash")).thenReturn(mockTrashFolder); message.delete("Trash"); verify(mockFolder).moveMessages(Collections.singletonList(message), mockTrashFolder); } |
### Question:
WebDavMessage extends MimeMessage { public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException { String[] headers = envelope.getHeaderList(); Map<String, String> messageHeaders = envelope.getMessageHeaders(); for (String header : headers) { String headerValue = messageHeaders.get(header); if (header.equals("Content-Length")) { int size = Integer.parseInt(headerValue); this.setSize(size); } if (headerValue != null && !headerValue.equals("")) { this.addHeader(header, headerValue); } } } WebDavMessage(String uid, Folder folder); void setUrl(String url); String getUrl(); void setSize(int size); void setFlagInternal(Flag flag, boolean set); void setNewHeaders(ParsedMessageEnvelope envelope); @Override void delete(String trashFolderName); @Override void setFlag(Flag flag, boolean set); }### Answer:
@Test public void setNewHeaders_updates_size() throws MessagingException { ParsedMessageEnvelope parsedMessageEnvelope = new ParsedMessageEnvelope(); parsedMessageEnvelope.addHeader("getcontentlength", "1024"); message.setNewHeaders(parsedMessageEnvelope); assertEquals(1024, message.getSize()); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.