From 4bc003e17334f0c6825a2597f60d705010511b8c Mon Sep 17 00:00:00 2001 From: notfoss Date: Sat, 3 Jan 2015 16:43:01 +0530 Subject: [PATCH 01/22] Add Zoho Mail (personal) to providers.xml Added settings for Zoho Mail personal account (@zoho.com). --- k9mail/src/main/res/xml/providers.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/k9mail/src/main/res/xml/providers.xml b/k9mail/src/main/res/xml/providers.xml index 29e34d452..724f20805 100644 --- a/k9mail/src/main/res/xml/providers.xml +++ b/k9mail/src/main/res/xml/providers.xml @@ -129,6 +129,10 @@ + + + + From c7229e4724cf9505b000eef9b3696125c252b3e5 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Mon, 5 Jan 2015 23:24:24 +0100 Subject: [PATCH 02/22] Enable lint checks for k9mail-library --- k9mail-library/build.gradle | 5 +++-- .../main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java | 2 ++ .../fsck/k9/mail/store/webdav/WebDavSocketFactory.java | 8 +++----- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/k9mail-library/build.gradle b/k9mail-library/build.gradle index ad6a7fceb..b32294f08 100644 --- a/k9mail-library/build.gradle +++ b/k9mail-library/build.gradle @@ -20,11 +20,12 @@ android { defaultConfig { minSdkVersion 15 - targetSdkVersion 17 + targetSdkVersion 21 } lintOptions { - abortOnError false + abortOnError true + warningsAsErrors true lintConfig file("$rootProject.projectDir/config/lint/lint.xml") } diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java index d1d096427..922115e4e 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/pop3/Pop3Store.java @@ -1,6 +1,7 @@ package com.fsck.k9.mail.store.pop3; +import android.annotation.SuppressLint; import android.util.Log; import com.fsck.k9.mail.*; @@ -278,6 +279,7 @@ public class Pop3Store extends RemoteStore { private InputStream mIn; private OutputStream mOut; private Map mUidToMsgMap = new HashMap(); + @SuppressLint("UseSparseArrays") private Map mMsgNumToMsgMap = new HashMap(); private Map mUidToMsgNumMap = new HashMap(); private String mName; diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavSocketFactory.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavSocketFactory.java index 91c43a0a3..3beeb0131 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavSocketFactory.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/webdav/WebDavSocketFactory.java @@ -9,10 +9,8 @@ import com.fsck.k9.mail.ssl.TrustManagerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; -import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; @@ -32,7 +30,7 @@ public class WebDavSocketFactory implements LayeredSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(host, port) - }, new SecureRandom()); + }, null); mSocketFactory = sslContext.getSocketFactory(); mSchemeSocketFactory = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(); mSchemeSocketFactory.setHostnameVerifier( @@ -41,7 +39,7 @@ public class WebDavSocketFactory implements LayeredSocketFactory { public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) - throws IOException, UnknownHostException, ConnectTimeoutException { + throws IOException, ConnectTimeoutException { return mSchemeSocketFactory.connectSocket(sock, host, port, localAddress, localPort, params); } @@ -57,7 +55,7 @@ public class WebDavSocketFactory implements LayeredSocketFactory { final String host, final int port, final boolean autoClose - ) throws IOException, UnknownHostException { + ) throws IOException { SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket( socket, host, From 63abf05776ea04dd6a61661dea2a2177474344e3 Mon Sep 17 00:00:00 2001 From: cketti Date: Fri, 9 Jan 2015 16:16:00 +0100 Subject: [PATCH 03/22] Sanitize HTML to remove meta refresh Using in a HTML message causes WebView to load the URL in the default browser. Overriding WebViewClient.shouldOverrideUrlLoading() allows us to cancel loading this URL. Sadly, I found no way to find out whether the method was called because of a meta refresh or because the user clicked on a link. So now we're using HtmlCleaner to parse the HTML and remove all "meta" elements containing an "http-equiv" attribute with a value of "refresh". --- .../com/fsck/k9/helper/HtmlSanitizer.java | 54 +++++++++++ .../java/com/fsck/k9/view/MessageWebView.java | 6 +- .../com/fsck/k9/helper/HtmlSanitizerTest.java | 94 +++++++++++++++++++ 3 files changed, 153 insertions(+), 1 deletion(-) create mode 100644 k9mail/src/main/java/com/fsck/k9/helper/HtmlSanitizer.java create mode 100644 tests-on-jvm/src/test/java/com/fsck/k9/helper/HtmlSanitizerTest.java diff --git a/k9mail/src/main/java/com/fsck/k9/helper/HtmlSanitizer.java b/k9mail/src/main/java/com/fsck/k9/helper/HtmlSanitizer.java new file mode 100644 index 000000000..1c04eb632 --- /dev/null +++ b/k9mail/src/main/java/com/fsck/k9/helper/HtmlSanitizer.java @@ -0,0 +1,54 @@ +package com.fsck.k9.helper; + + +import org.htmlcleaner.CleanerProperties; +import org.htmlcleaner.HtmlCleaner; +import org.htmlcleaner.HtmlSerializer; +import org.htmlcleaner.SimpleHtmlSerializer; +import org.htmlcleaner.TagNode; + + +public class HtmlSanitizer { + private static final HtmlCleaner HTML_CLEANER; + private static final HtmlSerializer HTML_SERIALIZER; + + static { + CleanerProperties properties = createCleanerProperties(); + HTML_CLEANER = new HtmlCleaner(properties); + HTML_SERIALIZER = new SimpleHtmlSerializer(properties); + } + + + private HtmlSanitizer() {} + + public static String sanitize(String html) { + TagNode rootNode = HTML_CLEANER.clean(html); + + removeMetaRefresh(rootNode); + + return HTML_SERIALIZER.getAsString(rootNode, "UTF8"); + } + + private static CleanerProperties createCleanerProperties() { + CleanerProperties properties = new CleanerProperties(); + + // See http://htmlcleaner.sourceforge.net/parameters.php for descriptions + properties.setNamespacesAware(false); + properties.setAdvancedXmlEscape(false); + properties.setOmitXmlDeclaration(true); + properties.setOmitDoctypeDeclaration(false); + properties.setTranslateSpecialEntities(false); + properties.setRecognizeUnicodeChars(false); + + return properties; + } + + private static void removeMetaRefresh(TagNode rootNode) { + for (TagNode element : rootNode.getElementListByName("meta", true)) { + String httpEquiv = element.getAttributeByName("http-equiv"); + if (httpEquiv != null && httpEquiv.trim().equalsIgnoreCase("refresh")) { + element.removeFromTree(); + } + } + } +} diff --git a/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java b/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java index 3198d4723..0f64194e2 100644 --- a/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java +++ b/k9mail/src/main/java/com/fsck/k9/view/MessageWebView.java @@ -11,6 +11,8 @@ import android.widget.Toast; import com.fsck.k9.K9; import com.fsck.k9.R; import com.fsck.k9.helper.HtmlConverter; +import com.fsck.k9.helper.HtmlSanitizer; + public class MessageWebView extends RigidWebView { @@ -123,7 +125,9 @@ public class MessageWebView extends RigidWebView { } content += HtmlConverter.cssStylePre(); content += "" + text + ""; - loadDataWithBaseURL("http://", content, "text/html", "utf-8", null); + + String sanitizedContent = HtmlSanitizer.sanitize(content); + loadDataWithBaseURL("http://", sanitizedContent, "text/html", "utf-8", null); resumeTimers(); } diff --git a/tests-on-jvm/src/test/java/com/fsck/k9/helper/HtmlSanitizerTest.java b/tests-on-jvm/src/test/java/com/fsck/k9/helper/HtmlSanitizerTest.java new file mode 100644 index 000000000..ccff81412 --- /dev/null +++ b/tests-on-jvm/src/test/java/com/fsck/k9/helper/HtmlSanitizerTest.java @@ -0,0 +1,94 @@ +package com.fsck.k9.helper; + + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class HtmlSanitizerTest { + @Test + public void shouldRemoveMetaRefreshInHead() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshBetweenHeadAndBody() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshInBody() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshWithUpperCaseAttributeValue() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshWithMixedCaseAttributeValue() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshWithoutQuotesAroundAttributeValue() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshWithSpacesInAttributeValue() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMultipleMetaRefreshTags() { + String html = "" + + "" + + "Message" + + ""; + assertEquals("Message", HtmlSanitizer.sanitize(html)); + } + + @Test + public void shouldRemoveMetaRefreshButKeepOtherMetaTags() { + String html = "" + + "" + + "" + + "" + + "" + + "Message" + + ""; + assertEquals("" + + "Message", HtmlSanitizer.sanitize(html)); + } +} From b481d3f9786949dba3facf2ba0276d134cd3e67c Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Mon, 12 Jan 2015 19:36:42 +0100 Subject: [PATCH 04/22] Adding tests for IMAP connection, use greenmail snapshot --- .../k9/mail/store/imap/ImapConnection.java | 12 +- k9mail/build.gradle | 8 +- .../k9/endtoend/framework/StubMailServer.java | 4 + .../mail/store/imap/ImapConnectionTest.java | 160 ++++++++++++++++++ 4 files changed, 180 insertions(+), 4 deletions(-) create mode 100644 k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java index 88482c4b6..cd679a5f8 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java @@ -601,10 +601,18 @@ class ImapConnection { } private List receiveCapabilities(List responses) { - capabilities = ImapResponseParser.parseCapabilities(responses); + Set receivedCapabilities = ImapResponseParser.parseCapabilities(responses); + /* RFC 3501 6.2.3 + A server MAY include a CAPABILITY response code in the tagged OK + response to a successful LOGIN command in order to send + capabilities automatically. It is unnecessary for a client to + send a separate CAPABILITY command if it recognizes these + automatic capabilities. + */ if (K9MailLib.isDebug()) { - Log.d(LOG_TAG, "Saving " + capabilities + " capabilities for " + getLogId()); + Log.d(LOG_TAG, "Saving " + receivedCapabilities + " capabilities for " + getLogId()); } + capabilities.addAll(receivedCapabilities); return responses; } } diff --git a/k9mail/build.gradle b/k9mail/build.gradle index c99ed2f0c..bc8198a57 100644 --- a/k9mail/build.gradle +++ b/k9mail/build.gradle @@ -5,6 +5,9 @@ apply from: '../gradle/plugins/findbugs-android.gradle' repositories { jcenter() + maven { + url "https://oss.sonatype.org/content/repositories/snapshots/" + } } dependencies { @@ -21,9 +24,10 @@ dependencies { androidTestCompile 'com.android.support.test:testing-support-lib:0.1' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0' - androidTestCompile("com.icegreen:greenmail:1.3.1b") { + androidTestCompile("com.icegreen:greenmail:1.4.1-SNAPSHOT") { // Use a better, later version - exclude group: "javax.mail" + exclude group: "com.sun.mail" + exclude group: "junit" } // this version avoids some "Ignoring InnerClasses attribute for an anonymous inner class" warnings diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java index d8d1df2a3..c7d5b97ec 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java @@ -37,5 +37,9 @@ public class StubMailServer { public int getImapPort() { return IMAP_SERVER_SETUP.getPort(); } + + public void stop() { + greenmail.stop(); + } } diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java new file mode 100644 index 000000000..75074195e --- /dev/null +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java @@ -0,0 +1,160 @@ +package com.fsck.k9.mail.store.imap; + + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.fsck.k9.endtoend.framework.StubMailServer; +import com.fsck.k9.endtoend.framework.UserForImap; +import com.fsck.k9.mail.AuthType; +import com.fsck.k9.mail.AuthenticationFailedException; +import com.fsck.k9.mail.ConnectionSecurity; +import junit.framework.TestCase; + +import static org.junit.Assert.assertArrayEquals; + + +public class ImapConnectionTest extends TestCase { + private StubMailServer stubMailServer; + private ImapConnection connection; + private TestImapSettings settings = new TestImapSettings(UserForImap.TEST_USER); + + @Override + public void setUp() throws Exception { + super.setUp(); + stubMailServer = new StubMailServer(); + connection = new ImapConnection(settings, null, + null); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + stubMailServer.stop(); + } + + public void testOpenConnectionWithWrongCredentials() throws Exception { + connection = new ImapConnection(new TestImapSettings("wrong", "password"), null, null); + try { + connection.open(); + fail("expected exception"); + } catch (AuthenticationFailedException e) { + assertTrue(e.getMessage().contains("Invalid login/password")); + assertFalse(connection.isOpen()); + } + } + + public void testOpenConnection() throws Exception { + connection.open(); + assertTrue(connection.isOpen()); + } + + public void testOpenAndCloseConnection() throws Exception { + connection.open(); + connection.close(); + assertFalse(connection.isOpen()); + } + + public void testCapabilities() throws Exception { + connection.open(); + List capabilities = new ArrayList(connection.getCapabilities()); + Collections.sort(capabilities); + assertArrayEquals(new String[] { "IMAP4REV1", "LITERAL+", "QUOTA" }, capabilities.toArray()); + } + + public void testPathPrefixGetsSetCorrectly() throws Exception { + connection.open(); + assertEquals("", settings.getPathPrefix()); + } + + public void testPathDelimiterGetsParsedCorrectly() throws Exception { + connection.open(); + assertEquals(".", settings.getPathDelimiter()); + } + + private class TestImapSettings implements ImapSettings { + private String pathPrefix; + private String pathDelimiter; + private String username; + private String password; + + public TestImapSettings(UserForImap userForImap) { + this(userForImap.loginUsername, userForImap.password); + } + + public TestImapSettings(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public String getHost() { + return stubMailServer.getImapBindAddress(); + } + + @Override + public int getPort() { + return stubMailServer.getImapPort(); + } + + @Override + public ConnectionSecurity getConnectionSecurity() { + return ConnectionSecurity.NONE; + } + + @Override + public AuthType getAuthType() { + return AuthType.PLAIN; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getClientCertificateAlias() { + return null; + } + + @Override + public boolean useCompression(int type) { + return false; + } + + @Override + public String getPathPrefix() { + return pathPrefix; + } + + @Override + public void setPathPrefix(String prefix) { + pathPrefix = prefix; + } + + @Override + public String getPathDelimiter() { + return pathDelimiter; + } + + @Override + public void setPathDelimiter(String delimiter) { + pathDelimiter = delimiter; + } + + @Override + public String getCombinedPrefix() { + return null; + } + + @Override + public void setCombinedPrefix(String prefix) { + } + } +} From 79584675039e1c5ddb1869c1c60a383b8dd2e420 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 01:04:28 +0100 Subject: [PATCH 05/22] Convert from thread to AsyncTask for espresso tests --- .../setup/AccountSetupCheckSettings.java | 177 +++++++++--------- 1 file changed, 89 insertions(+), 88 deletions(-) diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java index 838472706..faa809b06 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java @@ -8,13 +8,12 @@ import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; +import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; -import android.os.Process; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; -import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; @@ -87,7 +86,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList setContentView(R.layout.account_setup_check_settings); mMessageView = (TextView)findViewById(R.id.message); mProgressBar = (ProgressBar)findViewById(R.id.progress); - ((Button)findViewById(R.id.cancel)).setOnClickListener(this); + findViewById(R.id.cancel).setOnClickListener(this); setMessage(R.string.account_setup_check_settings_retr_info_msg); mProgressBar.setIndeterminate(true); @@ -96,84 +95,10 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList mAccount = Preferences.getPreferences(this).getAccount(accountUuid); mDirection = (CheckDirection) getIntent().getSerializableExtra(EXTRA_CHECK_DIRECTION); - new Thread() { - @Override - public void run() { - Store store = null; - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - try { - if (mDestroyed) { - return; - } - if (mCanceled) { - finish(); - return; - } - - final MessagingController ctrl = MessagingController.getInstance(getApplication()); - ctrl.clearCertificateErrorNotifications(AccountSetupCheckSettings.this, - mAccount, mDirection); - - if (mDirection == CheckDirection.INCOMING) { - store = mAccount.getRemoteStore(); - - if (store instanceof WebDavStore) { - setMessage(R.string.account_setup_check_settings_authenticate); - } else { - setMessage(R.string.account_setup_check_settings_check_incoming_msg); - } - store.checkSettings(); - - if (store instanceof WebDavStore) { - setMessage(R.string.account_setup_check_settings_fetch); - } - MessagingController.getInstance(getApplication()).listFoldersSynchronous(mAccount, true, null); - MessagingController.getInstance(getApplication()).synchronizeMailbox(mAccount, mAccount.getInboxFolderName(), null, null); - } - if (mDestroyed) { - return; - } - if (mCanceled) { - finish(); - return; - } - if (mDirection == CheckDirection.OUTGOING) { - if (!(mAccount.getRemoteStore() instanceof WebDavStore)) { - setMessage(R.string.account_setup_check_settings_check_outgoing_msg); - } - Transport transport = Transport.getInstance(K9.app, mAccount); - transport.close(); - transport.open(); - transport.close(); - } - if (mDestroyed) { - return; - } - if (mCanceled) { - finish(); - return; - } - setResult(RESULT_OK); - finish(); - } catch (final AuthenticationFailedException afe) { - Log.e(K9.LOG_TAG, "Error while testing settings", afe); - showErrorDialog( - R.string.account_setup_failed_dlg_auth_message_fmt, - afe.getMessage() == null ? "" : afe.getMessage()); - } catch (final CertificateValidationException cve) { - handleCertificateValidationException(cve); - } catch (final Throwable t) { - Log.e(K9.LOG_TAG, "Error while testing settings", t); - showErrorDialog( - R.string.account_setup_failed_dlg_server_message_fmt, - (t.getMessage() == null ? "" : t.getMessage())); - } - } - - } - .start(); + new CheckAccountTask(mAccount).execute(mDirection); } + private void handleCertificateValidationException(CertificateValidationException cve) { Log.e(K9.LOG_TAG, "Error while testing settings", cve); @@ -199,14 +124,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList } private void setMessage(final int resId) { - mHandler.post(new Runnable() { - public void run() { - if (mDestroyed) { - return; - } - mMessageView.setText(getString(resId)); - } - }); + mMessageView.setText(getString(resId)); } private void acceptKeyDialog(final int msgResId, final CertificateValidationException ex) { @@ -266,7 +184,7 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList for (List subjectAlternativeName : subjectAlternativeNames) { Integer type = (Integer)subjectAlternativeName.get(0); Object value = subjectAlternativeName.get(1); - String name = ""; + String name; switch (type.intValue()) { case 0: Log.w(K9.LOG_TAG, "SubjectAltName of type OtherName not supported."); @@ -473,4 +391,87 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList default: return ""; } } + + class CheckAccountTask extends AsyncTask { + private final Account account; + CheckAccountTask(Account account) { + this.account = account; + } + @Override + protected Void doInBackground(CheckDirection... params) { + final CheckDirection direction = params[0]; + try { + if (mDestroyed) { + return null; + } + if (mCanceled) { + finish(); + return null; + } + final MessagingController ctrl = MessagingController.getInstance(getApplication()); + ctrl.clearCertificateErrorNotifications(AccountSetupCheckSettings.this, + account, direction); + + if (direction == CheckDirection.INCOMING) { + Store store = account.getRemoteStore(); + if (store instanceof WebDavStore) { + publishProgress(R.string.account_setup_check_settings_authenticate); + } else { + publishProgress(R.string.account_setup_check_settings_check_incoming_msg); + } + store.checkSettings(); + + if (store instanceof WebDavStore) { + publishProgress(R.string.account_setup_check_settings_fetch); + } + MessagingController.getInstance(getApplication()).listFoldersSynchronous(account, true, null); + MessagingController.getInstance(getApplication()) + .synchronizeMailbox(account, account.getInboxFolderName(), null, null); + } + if (mDestroyed) { + return null; + } + if (mCanceled) { + finish(); + return null; + } + if (direction == CheckDirection.OUTGOING) { + if (!(account.getRemoteStore() instanceof WebDavStore)) { + publishProgress(R.string.account_setup_check_settings_check_outgoing_msg); + } + Transport transport = Transport.getInstance(K9.app, account); + transport.close(); + transport.open(); + transport.close(); + } + if (mDestroyed) { + return null; + } + if (mCanceled) { + finish(); + return null; + } + setResult(RESULT_OK); + finish(); + } catch (AuthenticationFailedException afe) { + Log.e(K9.LOG_TAG, "Error while testing settings", afe); + showErrorDialog( + R.string.account_setup_failed_dlg_auth_message_fmt, + afe.getMessage() == null ? "" : afe.getMessage()); + } catch (CertificateValidationException cve) { + handleCertificateValidationException(cve); + } catch (Throwable t) { + Log.e(K9.LOG_TAG, "Error while testing settings", t); + showErrorDialog( + R.string.account_setup_failed_dlg_server_message_fmt, + (t.getMessage() == null ? "" : t.getMessage())); + } + return null; + } + + @Override + protected void onProgressUpdate(Integer... values) { + setMessage(values[0]); + } + } } From 111212b391e1424c0311bc51a2602b10c95a733a Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 01:04:49 +0100 Subject: [PATCH 06/22] Setup and tear down server between tests --- .../com/fsck/k9/endtoend/AbstractEndToEndTest.java | 11 +++++++---- .../java/com/fsck/k9/endtoend/AccountSetupFlow.java | 8 +++----- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java index b644c035d..5796596d6 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java @@ -37,6 +37,12 @@ public abstract class AbstractEndToEndTest extends ActivityI if (bypassWelcome) { bypassWelcomeScreen(); } + state.stubMailServer = new StubMailServer(); + } + + @Override + public void tearDown() throws Exception { + state.stubMailServer.stop(); } private void bypassWelcomeScreen() { @@ -51,10 +57,7 @@ public abstract class AbstractEndToEndTest extends ActivityI } } - protected StubMailServer setupMailServer() { - if (null == state.stubMailServer) { - state.stubMailServer = new StubMailServer(); - } + public StubMailServer stubMailServer() { return state.stubMailServer; } } diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java index 978ffd332..cdd087704 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java @@ -45,11 +45,9 @@ public class AccountSetupFlow { IncomingServerSettingsPage incoming = accountTypePage.clickImap(); - StubMailServer stubMailServer = test.setupMailServer(); + OutgoingServerSettingsPage outgoing = setupIncomingServerAndClickNext(incoming, test.stubMailServer()); - OutgoingServerSettingsPage outgoing = setupIncomingServerAndClickNext(incoming, stubMailServer); - - AccountOptionsPage accountOptionsPage = setupOutgoingServerAndClickNext(outgoing, stubMailServer); + AccountOptionsPage accountOptionsPage = setupOutgoingServerAndClickNext(outgoing, test.stubMailServer()); AccountSetupNamesPage accountSetupNamesPage = accountOptionsPage.clickNext(); @@ -61,7 +59,7 @@ public class AccountSetupFlow { accountsPage.assertAccountExists(accountDescription); - ApplicationState.getInstance().accounts.add(new AccountForTest(ACCOUNT_NAME, accountDescription, stubMailServer)); + ApplicationState.getInstance().accounts.add(new AccountForTest(ACCOUNT_NAME, accountDescription, test.stubMailServer())); return accountsPage; } From 60070b788310cc4cf2d4ee232d4393ea34802814 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 01:59:51 +0100 Subject: [PATCH 07/22] Add more tests + descriptive names --- .../mail/store/imap/ImapConnectionTest.java | 36 ++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java index 75074195e..73a3e364a 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java @@ -16,6 +16,8 @@ import static org.junit.Assert.assertArrayEquals; public class ImapConnectionTest extends TestCase { + private static final String[] CAPABILITIES = new String[] { "IMAP4REV1", "LITERAL+", "QUOTA" }; + private StubMailServer stubMailServer; private ImapConnection connection; private TestImapSettings settings = new TestImapSettings(UserForImap.TEST_USER); @@ -24,8 +26,7 @@ public class ImapConnectionTest extends TestCase { public void setUp() throws Exception { super.setUp(); stubMailServer = new StubMailServer(); - connection = new ImapConnection(settings, null, - null); + connection = new ImapConnection(settings, null, null); } @Override @@ -34,7 +35,7 @@ public class ImapConnectionTest extends TestCase { stubMailServer.stop(); } - public void testOpenConnectionWithWrongCredentials() throws Exception { + public void testOpenConnectionWithWrongCredentialsThrowsAuthenticationFailedException() throws Exception { connection = new ImapConnection(new TestImapSettings("wrong", "password"), null, null); try { connection.open(); @@ -45,22 +46,34 @@ public class ImapConnectionTest extends TestCase { } } - public void testOpenConnection() throws Exception { + public void testSuccessfulOpenConnectionTogglesOpenState() throws Exception { connection.open(); assertTrue(connection.isOpen()); } - public void testOpenAndCloseConnection() throws Exception { + public void testSuccessfulOpenAndCloseConnectionTogglesOpenState() throws Exception { connection.open(); connection.close(); assertFalse(connection.isOpen()); } - public void testCapabilities() throws Exception { + public void testCapabilitiesAreInitiallyEmpty() throws Exception { + assertTrue(connection.getCapabilities().isEmpty()); + } + + public void testCapabilitiesListGetsParsedCorrectly() throws Exception { connection.open(); List capabilities = new ArrayList(connection.getCapabilities()); Collections.sort(capabilities); - assertArrayEquals(new String[] { "IMAP4REV1", "LITERAL+", "QUOTA" }, capabilities.toArray()); + assertArrayEquals(CAPABILITIES, capabilities.toArray()); + } + + public void testHasCapabilityChecks() throws Exception { + connection.open(); + for (String capability : CAPABILITIES) { + assertTrue(connection.hasCapability(capability)); + } + assertFalse(connection.hasCapability("FROBAZIFCATE")); } public void testPathPrefixGetsSetCorrectly() throws Exception { @@ -73,11 +86,17 @@ public class ImapConnectionTest extends TestCase { assertEquals(".", settings.getPathDelimiter()); } + public void testCombinedPrefixGetsSetCorrectly() throws Exception { + connection.open(); + assertNull(settings.getCombinedPrefix()); + } + private class TestImapSettings implements ImapSettings { private String pathPrefix; private String pathDelimiter; private String username; private String password; + private String combinedPrefix; public TestImapSettings(UserForImap userForImap) { this(userForImap.loginUsername, userForImap.password); @@ -150,11 +169,12 @@ public class ImapConnectionTest extends TestCase { @Override public String getCombinedPrefix() { - return null; + return combinedPrefix; } @Override public void setCombinedPrefix(String prefix) { + combinedPrefix = prefix; } } } From f7da704007aed8bf9a9dd75aadc5c6ba15320d72 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 09:34:13 +0100 Subject: [PATCH 08/22] WS --- .../com/fsck/k9/activity/setup/AccountSetupCheckSettings.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java index faa809b06..10809631d 100644 --- a/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java +++ b/k9mail/src/main/java/com/fsck/k9/activity/setup/AccountSetupCheckSettings.java @@ -98,7 +98,6 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList new CheckAccountTask(mAccount).execute(mDirection); } - private void handleCertificateValidationException(CertificateValidationException cve) { Log.e(K9.LOG_TAG, "Error while testing settings", cve); @@ -394,9 +393,11 @@ public class AccountSetupCheckSettings extends K9Activity implements OnClickList class CheckAccountTask extends AsyncTask { private final Account account; + CheckAccountTask(Account account) { this.account = account; } + @Override protected Void doInBackground(CheckDirection... params) { final CheckDirection direction = params[0]; From e98f32322290e11714309b0c707ba33a453241e5 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 10:05:15 +0100 Subject: [PATCH 09/22] Initialize settings in setUp() --- .../com/fsck/k9/mail/store/imap/ImapConnectionTest.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java index 73a3e364a..b10705e06 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java @@ -17,15 +17,16 @@ import static org.junit.Assert.assertArrayEquals; public class ImapConnectionTest extends TestCase { private static final String[] CAPABILITIES = new String[] { "IMAP4REV1", "LITERAL+", "QUOTA" }; - + private StubMailServer stubMailServer; private ImapConnection connection; - private TestImapSettings settings = new TestImapSettings(UserForImap.TEST_USER); + private TestImapSettings settings; @Override public void setUp() throws Exception { super.setUp(); stubMailServer = new StubMailServer(); + settings = new TestImapSettings(UserForImap.TEST_USER); connection = new ImapConnection(settings, null, null); } @@ -46,6 +47,10 @@ public class ImapConnectionTest extends TestCase { } } + public void testConnectionIsInitiallyClosed() throws Exception { + assertFalse(connection.isOpen()); + } + public void testSuccessfulOpenConnectionTogglesOpenState() throws Exception { connection.open(); assertTrue(connection.isOpen()); From bdbe97639665b4994d32055c8b730755c35ccd9d Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 10:09:42 +0100 Subject: [PATCH 10/22] Test connection w/o server --- .../fsck/k9/mail/store/imap/ImapConnectionTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java index b10705e06..8355ebff2 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java @@ -10,6 +10,7 @@ import com.fsck.k9.endtoend.framework.UserForImap; import com.fsck.k9.mail.AuthType; import com.fsck.k9.mail.AuthenticationFailedException; import com.fsck.k9.mail.ConnectionSecurity; +import com.fsck.k9.mail.MessagingException; import junit.framework.TestCase; import static org.junit.Assert.assertArrayEquals; @@ -36,6 +37,16 @@ public class ImapConnectionTest extends TestCase { stubMailServer.stop(); } + public void testOpenConnectionWithoutRunningServerThrowsMessagingException() throws Exception { + stubMailServer.stop(); + try { + connection.open(); + fail("expected exception"); + } catch (MessagingException e) { + assertFalse(connection.isOpen()); + } + } + public void testOpenConnectionWithWrongCredentialsThrowsAuthenticationFailedException() throws Exception { connection = new ImapConnection(new TestImapSettings("wrong", "password"), null, null); try { From a15583a0806e111054fb1bfed8b242b9f78d4ea9 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 15:51:33 +0100 Subject: [PATCH 11/22] Start server early --- .../java/com/fsck/k9/endtoend/AbstractEndToEndTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java index 5796596d6..0db1b97b5 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java @@ -32,12 +32,12 @@ public abstract class AbstractEndToEndTest extends ActivityI @Override protected void setUp() throws Exception { super.setUp(); + state.stubMailServer = new StubMailServer(); getActivity(); if (bypassWelcome) { bypassWelcomeScreen(); } - state.stubMailServer = new StubMailServer(); } @Override From 055d4104b76600e46c42baea75166c1a442df182 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Tue, 13 Jan 2015 16:12:39 +0100 Subject: [PATCH 12/22] log ChangeLog click failure --- .../java/com/fsck/k9/endtoend/pages/AccountSetupNamesPage.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/pages/AccountSetupNamesPage.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/pages/AccountSetupNamesPage.java index 10f2a5f30..bbbe3cc4a 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/pages/AccountSetupNamesPage.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/pages/AccountSetupNamesPage.java @@ -1,8 +1,10 @@ package com.fsck.k9.endtoend.pages; +import com.fsck.k9.K9; import com.fsck.k9.R; import android.support.test.espresso.NoMatchingViewException; import android.support.test.espresso.matcher.ViewMatchers; +import android.util.Log; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.clearText; @@ -41,6 +43,7 @@ public class AccountSetupNamesPage extends AbstractPage { try { onView(ViewMatchers.withText("OK")).perform(click()); } catch (NoMatchingViewException ex) { + Log.w(K9.LOG_TAG, "did not find Changelog OK button - ignored"); // Ignored. Not the best way of doing this, but Espresso rightly makes // conditional flow difficult. } From 0f312f012e6406ddc5e8a9780cecdedd0ef675c0 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 03:08:44 +0100 Subject: [PATCH 13/22] Create test mailboxes --- .../k9/endtoend/framework/StubMailServer.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java index c7d5b97ec..85e1f4f4f 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/framework/StubMailServer.java @@ -1,5 +1,9 @@ package com.fsck.k9.endtoend.framework; +import android.util.Log; + +import com.fsck.k9.K9; +import com.icegreen.greenmail.user.GreenMailUser; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetup; @@ -18,7 +22,18 @@ public class StubMailServer { public StubMailServer() { greenmail = new GreenMail(new ServerSetup[]{IMAP_SERVER_SETUP, SMTP_SERVER_SETUP}); - greenmail.setUser(UserForImap.TEST_USER.emailAddress, UserForImap.TEST_USER.loginUsername, UserForImap.TEST_USER.password); + GreenMailUser user = greenmail + .setUser(UserForImap.TEST_USER.emailAddress, UserForImap.TEST_USER.loginUsername, + UserForImap.TEST_USER.password); + + for (String mailbox : new String[] {"Drafts", "Spam"}) { + Log.d(K9.LOG_TAG, "creating mailbox "+mailbox); + try { + greenmail.getManagers().getImapHostManager().createMailbox(user, mailbox); + } catch (Exception e) { + throw new RuntimeException(e); + } + } greenmail.start(); } From 0153766dd597d2ccdb9f2236cac7c6c836244105 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 03:09:00 +0100 Subject: [PATCH 14/22] Convert to JUnit4 --- .../mail/store/imap/ImapConnectionTest.java | 47 +++++++++++-------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java index 8355ebff2..b34ff85f2 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java @@ -5,78 +5,83 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import android.support.test.runner.AndroidJUnit4; + import com.fsck.k9.endtoend.framework.StubMailServer; import com.fsck.k9.endtoend.framework.UserForImap; import com.fsck.k9.mail.AuthType; import com.fsck.k9.mail.AuthenticationFailedException; import com.fsck.k9.mail.ConnectionSecurity; import com.fsck.k9.mail.MessagingException; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertArrayEquals; -public class ImapConnectionTest extends TestCase { +@RunWith(AndroidJUnit4.class) +public class ImapConnectionTest { private static final String[] CAPABILITIES = new String[] { "IMAP4REV1", "LITERAL+", "QUOTA" }; private StubMailServer stubMailServer; private ImapConnection connection; private TestImapSettings settings; - @Override + @Before public void setUp() throws Exception { - super.setUp(); stubMailServer = new StubMailServer(); settings = new TestImapSettings(UserForImap.TEST_USER); connection = new ImapConnection(settings, null, null); } - @Override + @After public void tearDown() throws Exception { - super.tearDown(); stubMailServer.stop(); } + @Test(expected = MessagingException.class) public void testOpenConnectionWithoutRunningServerThrowsMessagingException() throws Exception { stubMailServer.stop(); - try { - connection.open(); - fail("expected exception"); - } catch (MessagingException e) { - assertFalse(connection.isOpen()); - } + connection.open(); } + @Test(expected = AuthenticationFailedException.class) public void testOpenConnectionWithWrongCredentialsThrowsAuthenticationFailedException() throws Exception { connection = new ImapConnection(new TestImapSettings("wrong", "password"), null, null); - try { - connection.open(); - fail("expected exception"); - } catch (AuthenticationFailedException e) { - assertTrue(e.getMessage().contains("Invalid login/password")); - assertFalse(connection.isOpen()); - } + connection.open(); } + @Test public void testConnectionIsInitiallyClosed() throws Exception { assertFalse(connection.isOpen()); } + @Test public void testSuccessfulOpenConnectionTogglesOpenState() throws Exception { connection.open(); assertTrue(connection.isOpen()); } + @Test public void testSuccessfulOpenAndCloseConnectionTogglesOpenState() throws Exception { connection.open(); connection.close(); assertFalse(connection.isOpen()); } + @Test public void testCapabilitiesAreInitiallyEmpty() throws Exception { assertTrue(connection.getCapabilities().isEmpty()); } + @Test public void testCapabilitiesListGetsParsedCorrectly() throws Exception { connection.open(); List capabilities = new ArrayList(connection.getCapabilities()); @@ -84,6 +89,7 @@ public class ImapConnectionTest extends TestCase { assertArrayEquals(CAPABILITIES, capabilities.toArray()); } + @Test public void testHasCapabilityChecks() throws Exception { connection.open(); for (String capability : CAPABILITIES) { @@ -92,16 +98,19 @@ public class ImapConnectionTest extends TestCase { assertFalse(connection.hasCapability("FROBAZIFCATE")); } + @Test public void testPathPrefixGetsSetCorrectly() throws Exception { connection.open(); assertEquals("", settings.getPathPrefix()); } + @Test public void testPathDelimiterGetsParsedCorrectly() throws Exception { connection.open(); assertEquals(".", settings.getPathDelimiter()); } + @Test public void testCombinedPrefixGetsSetCorrectly() throws Exception { connection.open(); assertNull(settings.getCombinedPrefix()); From 4e964e271c865d58bdf5bc402aebd2887998f78c Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 03:09:48 +0100 Subject: [PATCH 15/22] Convert to JUnit4 test --- ...WelcomeAndSetupAccountIntegrationTest.java | 18 ++++++--- .../endtoend/A010_AccountIntegrationTest.java | 19 +++++++-- .../k9/endtoend/AbstractEndToEndTest.java | 39 ++++++++++++++----- .../fsck/k9/endtoend/AccountSetupFlow.java | 15 +++---- 4 files changed, 63 insertions(+), 28 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java index c6a9187dc..73cf51eb7 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java @@ -1,24 +1,32 @@ package com.fsck.k9.endtoend; +import android.support.test.runner.AndroidJUnit4; + import com.fsck.k9.activity.setup.WelcomeMessage; +import com.fsck.k9.endtoend.framework.ApplicationState; import com.fsck.k9.endtoend.pages.WelcomeMessagePage; +import org.junit.Test; +import org.junit.runner.RunWith; + /** * Creates a new IMAP account via the getting started flow. */ +@RunWith(AndroidJUnit4.class) public class A000_WelcomeAndSetupAccountIntegrationTest extends AbstractEndToEndTest { public A000_WelcomeAndSetupAccountIntegrationTest() { super(WelcomeMessage.class, false); } - public void testCreateAccount() throws Exception { - new AccountSetupFlow(this).setupAccountFromWelcomePage(new WelcomeMessagePage()); + @Test + public void createAccount() throws Exception { + new AccountSetupFlow().setupAccountFromWelcomePage(new WelcomeMessagePage()); } - public void testCreateSecondAccount() throws Exception { - new AccountSetupFlow(this).setupAccountFromWelcomePage(new WelcomeMessagePage()); + @Test + public void createSecondAccount() throws Exception { + new AccountSetupFlow().setupAccountFromWelcomePage(new WelcomeMessagePage()); } - } diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java index d3fc8701c..59cb41f44 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java @@ -1,9 +1,14 @@ package com.fsck.k9.endtoend; +import android.support.test.runner.AndroidJUnit4; + import com.fsck.k9.activity.Accounts; import com.fsck.k9.endtoend.framework.AccountForTest; import com.fsck.k9.endtoend.framework.ApplicationState; import com.fsck.k9.endtoend.pages.AccountsPage; +import org.junit.Test; +import org.junit.runner.RunWith; + /** * Creates and removes accounts. @@ -11,20 +16,26 @@ import com.fsck.k9.endtoend.pages.AccountsPage; * Because of the way K-9 shows the start page, there must already be two accounts * in existence for this test to work. */ +@RunWith(AndroidJUnit4.class) public class A010_AccountIntegrationTest extends AbstractEndToEndTest{ public A010_AccountIntegrationTest() { super(Accounts.class); } - public void testCreateAccountDirectly() throws Exception { - new AccountSetupFlow(this).setupAccountFromAccountsPage(new AccountsPage()); + @Test + public void createAccountDirectly() throws Exception { + new AccountSetupFlow().setupAccountFromAccountsPage(new AccountsPage()); } - public void testDeleteAccount() { - + @Test + public void deleteAccount() { AccountsPage accountsPage = new AccountsPage(); + // TODO should not have cross-test-dependencies + assertFalse("NB: this test is order dependent and requires A000_WelcomeAndSetupAccountIntegrationTest to run first", + ApplicationState.getInstance().accounts.isEmpty()); + AccountForTest accountForTest = ApplicationState.getInstance().accounts.get(0); accountsPage.assertAccountExists(accountForTest.description); diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java index 0db1b97b5..681ad25b6 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AbstractEndToEndTest.java @@ -1,6 +1,9 @@ package com.fsck.k9.endtoend; import android.app.Activity; +import android.support.test.InstrumentationRegistry; +import android.support.test.espresso.assertion.ViewAssertions; +import android.support.test.runner.AndroidJUnit4; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; @@ -8,16 +11,18 @@ import com.fsck.k9.R; import com.fsck.k9.endtoend.framework.ApplicationState; import com.fsck.k9.endtoend.framework.StubMailServer; import com.fsck.k9.endtoend.pages.WelcomeMessagePage; -import android.support.test.espresso.assertion.ViewAssertions; - import junit.framework.AssertionFailedError; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.matcher.ViewMatchers.withId; +@RunWith(AndroidJUnit4.class) public abstract class AbstractEndToEndTest extends ActivityInstrumentationTestCase2 { - - private ApplicationState state = ApplicationState.getInstance(); private final boolean bypassWelcome; public AbstractEndToEndTest(Class activityClass) { @@ -29,10 +34,22 @@ public abstract class AbstractEndToEndTest extends ActivityI this.bypassWelcome = bypassWelcome; } + @BeforeClass + public static void beforeClass() { + ApplicationState.getInstance().stubMailServer = new StubMailServer(); + } + + @AfterClass + public static void afterClass() { + ApplicationState.getInstance().stubMailServer.stop(); + } + + @Before @Override - protected void setUp() throws Exception { + public void setUp() throws Exception { super.setUp(); - state.stubMailServer = new StubMailServer(); + injectInstrumentation(InstrumentationRegistry.getInstrumentation()); + getActivity(); if (bypassWelcome) { @@ -40,9 +57,10 @@ public abstract class AbstractEndToEndTest extends ActivityI } } + @After @Override public void tearDown() throws Exception { - state.stubMailServer.stop(); + super.tearDown(); } private void bypassWelcomeScreen() { @@ -53,11 +71,12 @@ public abstract class AbstractEndToEndTest extends ActivityI * The view doesn't NOT exist == the view exists, and needs to be bypassed! */ Log.d(getClass().getName(), "Bypassing welcome"); - new AccountSetupFlow(this).setupAccountFromWelcomePage(new WelcomeMessagePage()); + new AccountSetupFlow().setupAccountFromWelcomePage(new WelcomeMessagePage()); } } - public StubMailServer stubMailServer() { - return state.stubMailServer; + + public void testEmpty() { + // workaround, needs to be empty so that JUnit4 test gets picked up } } diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java index cdd087704..af83737f1 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/AccountSetupFlow.java @@ -24,12 +24,6 @@ public class AccountSetupFlow { static final String ACCOUNT_NAME = "sendAndReceiveTestName"; - private final AbstractEndToEndTest test; - - public AccountSetupFlow(AbstractEndToEndTest test) { - this.test = test; - } - public AccountsPage setupAccountFromWelcomePage(WelcomeMessagePage welcomeMessagePage) { AccountSetupPage accountSetupPage = welcomeMessagePage.clickNext(); return setupAccountFromSetupNewAccountActivity(accountSetupPage); @@ -45,9 +39,12 @@ public class AccountSetupFlow { IncomingServerSettingsPage incoming = accountTypePage.clickImap(); - OutgoingServerSettingsPage outgoing = setupIncomingServerAndClickNext(incoming, test.stubMailServer()); - AccountOptionsPage accountOptionsPage = setupOutgoingServerAndClickNext(outgoing, test.stubMailServer()); + StubMailServer stubMailServer = ApplicationState.getInstance().stubMailServer; + + OutgoingServerSettingsPage outgoing = setupIncomingServerAndClickNext(incoming, stubMailServer); + + AccountOptionsPage accountOptionsPage = setupOutgoingServerAndClickNext(outgoing, stubMailServer); AccountSetupNamesPage accountSetupNamesPage = accountOptionsPage.clickNext(); @@ -59,7 +56,7 @@ public class AccountSetupFlow { accountsPage.assertAccountExists(accountDescription); - ApplicationState.getInstance().accounts.add(new AccountForTest(ACCOUNT_NAME, accountDescription, test.stubMailServer())); + ApplicationState.getInstance().accounts.add(new AccountForTest(ACCOUNT_NAME, accountDescription, stubMailServer)); return accountsPage; } From 79b03b5e4fdff65243334034e9b31f03ac984e1d Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 03:30:38 +0100 Subject: [PATCH 16/22] Remove account after creation * Avoid side-effects in static preferences which might interfere with other tests --- .../fsck/k9/mailstore/LocalMessageTest.java | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageTest.java index 01b4d8e22..e37c12da7 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageTest.java @@ -1,24 +1,43 @@ package com.fsck.k9.mailstore; -import android.test.AndroidTestCase; +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; +import com.fsck.k9.Account; import com.fsck.k9.Preferences; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeMultipart; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static junit.framework.Assert.assertEquals; -public class LocalMessageTest extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class LocalMessageTest { private LocalMessage message; + private Account account; + private Preferences preferences; - @Override + @Before public void setUp() throws Exception { - super.setUp(); - Preferences preferences = Preferences.getPreferences(getContext()); - LocalStore store = LocalStore.getInstance(preferences.newAccount(), getContext()); + Context targetContext = InstrumentationRegistry.getTargetContext(); + preferences = Preferences.getPreferences(targetContext); + account = preferences.newAccount(); + LocalStore store = LocalStore.getInstance(account, targetContext); message = new LocalMessage(store, "uid", new LocalFolder(store, "test")); } + @After + public void tearDown() throws Exception { + preferences.deleteAccount(account); + } + + @Test public void testGetDisplayTextWithPlainTextPart() throws Exception { String textBodyText = "text body"; @@ -29,6 +48,7 @@ public class LocalMessageTest extends AndroidTestCase { assertEquals("text body", message.getTextForDisplay()); } + @Test public void testGetDisplayTextWithHtmlPart() throws Exception { String htmlBodyText = "html body"; String textBodyText = "text body"; From 833d9c5de871126fb6146360ebf6cf255fecce27 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 03:34:57 +0100 Subject: [PATCH 17/22] Base class is already annotated --- .../endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java | 5 ----- .../com/fsck/k9/endtoend/A010_AccountIntegrationTest.java | 4 ---- 2 files changed, 9 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java index 73cf51eb7..736b25325 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A000_WelcomeAndSetupAccountIntegrationTest.java @@ -1,18 +1,13 @@ package com.fsck.k9.endtoend; -import android.support.test.runner.AndroidJUnit4; - import com.fsck.k9.activity.setup.WelcomeMessage; -import com.fsck.k9.endtoend.framework.ApplicationState; import com.fsck.k9.endtoend.pages.WelcomeMessagePage; import org.junit.Test; -import org.junit.runner.RunWith; /** * Creates a new IMAP account via the getting started flow. */ -@RunWith(AndroidJUnit4.class) public class A000_WelcomeAndSetupAccountIntegrationTest extends AbstractEndToEndTest { public A000_WelcomeAndSetupAccountIntegrationTest() { diff --git a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java index 59cb41f44..304efe91b 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/endtoend/A010_AccountIntegrationTest.java @@ -1,13 +1,10 @@ package com.fsck.k9.endtoend; -import android.support.test.runner.AndroidJUnit4; - import com.fsck.k9.activity.Accounts; import com.fsck.k9.endtoend.framework.AccountForTest; import com.fsck.k9.endtoend.framework.ApplicationState; import com.fsck.k9.endtoend.pages.AccountsPage; import org.junit.Test; -import org.junit.runner.RunWith; /** @@ -16,7 +13,6 @@ import org.junit.runner.RunWith; * Because of the way K-9 shows the start page, there must already be two accounts * in existence for this test to work. */ -@RunWith(AndroidJUnit4.class) public class A010_AccountIntegrationTest extends AbstractEndToEndTest{ public A010_AccountIntegrationTest() { From 4808406739ad517b638cd64b00093d1f59024a5e Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 03:45:09 +0100 Subject: [PATCH 18/22] Make deleteCertificate null-safe --- k9mail/src/main/java/com/fsck/k9/Account.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/k9mail/src/main/java/com/fsck/k9/Account.java b/k9mail/src/main/java/com/fsck/k9/Account.java index 3a66f88f8..8f85570d9 100644 --- a/k9mail/src/main/java/com/fsck/k9/Account.java +++ b/k9mail/src/main/java/com/fsck/k9/Account.java @@ -1894,9 +1894,15 @@ public class Account implements BaseAccount, StoreConfig { public void deleteCertificates() { LocalKeyStore localKeyStore = LocalKeyStore.getInstance(); - Uri uri = Uri.parse(getStoreUri()); - localKeyStore.deleteCertificate(uri.getHost(), uri.getPort()); - uri = Uri.parse(getTransportUri()); - localKeyStore.deleteCertificate(uri.getHost(), uri.getPort()); + String storeUri = getStoreUri(); + if (storeUri != null) { + Uri uri = Uri.parse(storeUri); + localKeyStore.deleteCertificate(uri.getHost(), uri.getPort()); + } + String transportUri = getTransportUri(); + if (transportUri != null) { + Uri uri = Uri.parse(transportUri); + localKeyStore.deleteCertificate(uri.getHost(), uri.getPort()); + } } } From dfb025033dba89ebcae84e073d8639a190514885 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 04:05:42 +0100 Subject: [PATCH 19/22] Convert remaining tests to JUnit4 --- .../com/fsck/k9/activity/AccountsTest.java | 21 ------- .../k9/activity/MessageReferenceTest.java | 20 +++++- .../com/fsck/k9/helper/FileHelperTest.java | 16 ++++- .../com/fsck/k9/helper/HtmlConverterTest.java | 63 ++++++++++++------- .../com/fsck/k9/helper/MessageHelperTest.java | 28 +++++++-- .../java/com/fsck/k9/mail/MessageTest.java | 34 +++++----- .../com/fsck/k9/mail/PgpMimeMessageTest.java | 13 +++- .../fsck/k9/mail/ReconstructMessageTest.java | 12 +++- .../k9/mail/ssl/TrustManagerFactoryTest.java | 40 +++++++++--- .../mailstore/LocalMessageExtractorTest.java | 27 +++++--- 10 files changed, 184 insertions(+), 90 deletions(-) delete mode 100644 k9mail/src/androidTest/java/com/fsck/k9/activity/AccountsTest.java diff --git a/k9mail/src/androidTest/java/com/fsck/k9/activity/AccountsTest.java b/k9mail/src/androidTest/java/com/fsck/k9/activity/AccountsTest.java deleted file mode 100644 index 81ef1c5f8..000000000 --- a/k9mail/src/androidTest/java/com/fsck/k9/activity/AccountsTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.fsck.k9.activity; - -import android.test.ActivityInstrumentationTestCase2; -import com.fsck.k9.activity.Accounts; -/** - * This is a simple framework for a test of an Application. See - * {@link android.test.ApplicationTestCase ApplicationTestCase} for more information on - * how to write and extend Application tests. - *

- * To run this test, you can type: - * adb shell am instrument -w \ - * -e class com.fsck.k9.activity.AccountsTest \ - * com.fsck.k9.tests/android.test.InstrumentationTestRunner - */ -public class AccountsTest extends ActivityInstrumentationTestCase2 { - - public AccountsTest() { - super("com.fsck.k9", Accounts.class); - } - -} diff --git a/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java b/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java index a80656a9f..539545d74 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java @@ -1,14 +1,24 @@ package com.fsck.k9.activity; +import android.support.test.runner.AndroidJUnit4; + import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.MessagingException; -import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; -public class MessageReferenceTest extends TestCase +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; +import static junit.framework.Assert.assertTrue; + +@RunWith(AndroidJUnit4.class) +public class MessageReferenceTest { /** * Typically happens during forwards. (You have a reference, but no flag since we don't currently consider FORWARDED a flag.) */ + @Test public void testIdentityStringNoFlag() { MessageReference mr = new MessageReference(); @@ -22,6 +32,7 @@ public class MessageReferenceTest extends TestCase /** * Typically happens during replies. */ + @Test public void testIdentityString() { MessageReference mr = new MessageReference(); @@ -33,6 +44,7 @@ public class MessageReferenceTest extends TestCase assertEquals("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED", mr.toIdentityString()); } + @Test public void testParseIdentityStringNoFlag() throws MessagingException { MessageReference mr = new MessageReference("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA="); @@ -42,6 +54,7 @@ public class MessageReferenceTest extends TestCase assertNull(mr.flag); } + @Test public void testParseIdentityString() throws MessagingException { MessageReference mr = new MessageReference("!:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED"); @@ -51,12 +64,14 @@ public class MessageReferenceTest extends TestCase assertEquals(Flag.ANSWERED, mr.flag); } + @Test public void testBadVersion() throws MessagingException { MessageReference mr = new MessageReference("@:byBoYWkh:Zm9sZGVy:MTAxMDEwMTA=:ANSWERED"); assertNull(mr.accountUuid); } + @Test public void testNull() throws MessagingException { try @@ -69,6 +84,7 @@ public class MessageReferenceTest extends TestCase } } + @Test public void testCorruption() throws MessagingException { MessageReference mr = new MessageReference("!:%^&%^*$&$by&(BYWkh:Zm9%^@sZGVy:MT-35#$AxMDEwMTA=:ANSWERED"); diff --git a/k9mail/src/androidTest/java/com/fsck/k9/helper/FileHelperTest.java b/k9mail/src/androidTest/java/com/fsck/k9/helper/FileHelperTest.java index 1e8260256..343126209 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/helper/FileHelperTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/helper/FileHelperTest.java @@ -1,27 +1,37 @@ package com.fsck.k9.helper; -import junit.framework.TestCase; +import android.support.test.runner.AndroidJUnit4; -import java.lang.String; +import org.junit.Test; +import org.junit.runner.RunWith; -public class FileHelperTest extends TestCase { +import static junit.framework.Assert.assertEquals; + +@RunWith(AndroidJUnit4.class) +public class FileHelperTest { + + @Test public void testSanitize1() { checkSanitization(".._bla_", "../bla_"); } + @Test public void testSanitize2() { checkSanitization("_etc_bla", "/etc/bla"); } + @Test public void testSanitize3() { checkSanitization("_пPп", "+пPп"); } + @Test public void testSanitize4() { checkSanitization(".東京_!", ".東京?!"); } + @Test public void testSanitize5() { checkSanitization("Plan 9", "Plan 9"); } diff --git a/k9mail/src/androidTest/java/com/fsck/k9/helper/HtmlConverterTest.java b/k9mail/src/androidTest/java/com/fsck/k9/helper/HtmlConverterTest.java index c79958150..701a9ec83 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/helper/HtmlConverterTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/helper/HtmlConverterTest.java @@ -1,16 +1,24 @@ package com.fsck.k9.helper; -import junit.framework.TestCase; - import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; -public class HtmlConverterTest extends TestCase { +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static junit.framework.Assert.assertEquals; + + +@RunWith(AndroidJUnit4.class) +public class HtmlConverterTest { // Useful if you want to write stuff to a file for debugging in a browser. private static final boolean WRITE_TO_FILE = Boolean.parseBoolean(System.getProperty("k9.htmlConverterTest.writeToFile", "false")); private static final String OUTPUT_FILE = "C:/temp/parse.html"; + @Test public void testTextQuoteToHtmlBlockquote() { String message = "Panama!\r\n" + "\r\n" + @@ -26,28 +34,33 @@ public class HtmlConverterTest extends TestCase { String result = HtmlConverter.textToHtml(message); writeToFile(result); assertEquals("

"
-            + "Panama!
" - + "
" - + "Bob Barker <bob@aol.com> wrote:
" - + "
" - + " a canal
" - + "
" - + " Dorothy Jo Gideon <dorothy@aol.com> espoused:
" - + "
" - + "A man, a plan...
" - + "
" - + " Too easy!
" - + "
" - + "
" - + "Nice job :)
" - + "
" - + "
" - + " Guess!" - + "
" - + "
" - + "
", result); + + "Panama!
" + + "
" + + "Bob Barker <bob@aol.com> wrote:
" + + + "
" + + " a canal
" + + "
" + + " Dorothy Jo Gideon <dorothy@aol.com> espoused:
" + + + "
" + + "A man, a plan...
" + + "
" + + " Too easy!
" + + "
" + + "
" + + "Nice job :)
" + + + "
" + + + "
" + + " Guess!" + + "
" + + "
" + + "", result); } + @Test public void testTextQuoteToHtmlBlockquoteIndented() { String message = "*facepalm*\r\n" + "\r\n" + @@ -73,6 +86,7 @@ public class HtmlConverterTest extends TestCase { } + @Test public void testQuoteDepthColor() { assertEquals(HtmlConverter.getQuoteColor(1), HtmlConverter.QUOTE_COLOR_LEVEL_1); assertEquals(HtmlConverter.getQuoteColor(2), HtmlConverter.QUOTE_COLOR_LEVEL_2); @@ -135,6 +149,7 @@ public class HtmlConverterTest extends TestCase { } } + @Test public void testPreserveSpacesAtFirst() { String message = "foo\r\n" + " bar\r\n" @@ -148,6 +163,7 @@ public class HtmlConverterTest extends TestCase { + "", result); } + @Test public void testPreserveSpacesAtFirstForSpecialCharacters() { String message = " \r\n" @@ -168,6 +184,7 @@ public class HtmlConverterTest extends TestCase { + "", result); } + @Test public void testLinkifyBitcoinAndHttpUri() { String text = "bitcoin:19W6QZkx8SYPG7BBCS7odmWGRxqRph5jFU http://example.com/"; diff --git a/k9mail/src/androidTest/java/com/fsck/k9/helper/MessageHelperTest.java b/k9mail/src/androidTest/java/com/fsck/k9/helper/MessageHelperTest.java index 0d71784e3..485f11520 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/helper/MessageHelperTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/helper/MessageHelperTest.java @@ -1,21 +1,31 @@ package com.fsck.k9.helper; +import android.content.Context; import android.graphics.Color; -import android.test.AndroidTestCase; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; import android.text.SpannableString; import com.fsck.k9.mail.Address; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; -public class MessageHelperTest extends AndroidTestCase { +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; + + +@RunWith(AndroidJUnit4.class) +public class MessageHelperTest { private Contacts contacts; private Contacts mockContacts; - @Override + @Before public void setUp() throws Exception { - super.setUp(); - contacts = new Contacts(getContext()); - mockContacts = new Contacts(getContext()) { + Context context = InstrumentationRegistry.getTargetContext(); + contacts = new Contacts(context); + mockContacts = new Contacts(context) { @Override public String getNameForAddress(String address) { if ("test@testor.com".equals(address)) { return "Tim Testor"; @@ -26,16 +36,19 @@ public class MessageHelperTest extends AndroidTestCase { }; } + @Test public void testToFriendlyShowsPersonalPartIfItExists() throws Exception { Address address = new Address("test@testor.com", "Tim Testor"); assertEquals("Tim Testor", MessageHelper.toFriendly(address, contacts)); } + @Test public void testToFriendlyShowsEmailPartIfNoPersonalPartExists() throws Exception { Address address = new Address("test@testor.com"); assertEquals("test@testor.com", MessageHelper.toFriendly(address, contacts)); } + @Test public void testToFriendlyArray() throws Exception { Address address1 = new Address("test@testor.com", "Tim Testor"); Address address2 = new Address("foo@bar.com", "Foo Bar"); @@ -43,11 +56,13 @@ public class MessageHelperTest extends AndroidTestCase { assertEquals("Tim Testor,Foo Bar", MessageHelper.toFriendly(addresses, contacts).toString()); } + @Test public void testToFriendlyWithContactLookup() throws Exception { Address address = new Address("test@testor.com"); assertEquals("Tim Testor", MessageHelper.toFriendly(address, mockContacts).toString()); } + @Test public void testToFriendlyWithChangeContactColor() throws Exception { Address address = new Address("test@testor.com"); CharSequence friendly = MessageHelper.toFriendly(address, mockContacts, true, true, Color.RED); @@ -55,6 +70,7 @@ public class MessageHelperTest extends AndroidTestCase { assertEquals("Tim Testor", friendly.toString()); } + @Test public void testToFriendlyWithoutCorrespondentNames() throws Exception { Address address = new Address("test@testor.com", "Tim Testor"); CharSequence friendly = MessageHelper.toFriendly(address, mockContacts, false, false, 0); diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/MessageTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/MessageTest.java index a9ec466e8..86f5ae0cc 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/MessageTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/MessageTest.java @@ -8,12 +8,8 @@ import java.io.OutputStream; import java.util.Date; import java.util.TimeZone; -import com.fsck.k9.mail.internet.MimeMessageHelper; -import org.apache.commons.io.IOUtils; -import org.apache.james.mime4j.codec.Base64InputStream; -import org.apache.james.mime4j.util.MimeUtil; - -import android.test.AndroidTestCase; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.internet.BinaryTempFileBody; @@ -22,13 +18,23 @@ import com.fsck.k9.mail.internet.CharsetSupport; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeMessage; +import com.fsck.k9.mail.internet.MimeMessageHelper; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.TextBody; +import org.apache.commons.io.IOUtils; +import org.apache.james.mime4j.util.MimeUtil; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; -public class MessageTest extends AndroidTestCase { - @Override +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +@RunWith(AndroidJUnit4.class) +public class MessageTest { + @Before public void setUp() throws Exception { - super.setUp(); TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")); } @@ -272,10 +278,7 @@ public class MessageTest extends AndroidTestCase { private int mMimeBoundary; - public MessageTest() { - super(); - } - + @Test public void testSetSendDateSetsSentDate() throws Exception { Message message = sampleMessage(); final int milliseconds = 0; @@ -286,23 +289,26 @@ public class MessageTest extends AndroidTestCase { assertEquals(milliseconds, sentDate.getTime()); } + @Test public void testSetSendDateFormatsHeaderCorrectlyWithCurrentTimeZone() throws Exception { Message message = sampleMessage(); message.setSentDate(new Date(0), false); assertEquals("Thu, 01 Jan 1970 09:00:00 +0900", message.getHeader("Date")[0]); } + @Test public void testSetSendDateFormatsHeaderCorrectlyWithoutTimeZone() throws Exception { Message message = sampleMessage(); message.setSentDate(new Date(0), true); assertEquals("Thu, 01 Jan 1970 00:00:00 +0000", message.getHeader("Date")[0]); } + @Test public void testMessage() throws MessagingException, IOException { MimeMessage message; ByteArrayOutputStream out; - BinaryTempFileBody.setTempDirectory(getContext().getCacheDir()); + BinaryTempFileBody.setTempDirectory(InstrumentationRegistry.getTargetContext().getCacheDir()); mMimeBoundary = 101; message = nestedMessage(nestedMessage(sampleMessage())); diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/PgpMimeMessageTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/PgpMimeMessageTest.java index 75cee3ba2..5fa6f5f1c 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/PgpMimeMessageTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/PgpMimeMessageTest.java @@ -6,10 +6,13 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import android.test.AndroidTestCase; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.internet.MimeMessage; +import org.junit.Test; +import org.junit.runner.RunWith; import org.spongycastle.openpgp.PGPCompressedData; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPObjectFactory; @@ -22,8 +25,11 @@ import org.spongycastle.openpgp.bc.BcPGPObjectFactory; import org.spongycastle.openpgp.bc.BcPGPPublicKeyRingCollection; import org.spongycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider; +import static junit.framework.Assert.assertTrue; -public class PgpMimeMessageTest extends AndroidTestCase { + +@RunWith(AndroidJUnit4.class) +public class PgpMimeMessageTest { private static final String PUBLIC_KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "Version: GnuPG v1\n" + "\n" + @@ -150,6 +156,7 @@ public class PgpMimeMessageTest extends AndroidTestCase { "-----END PGP PUBLIC KEY BLOCK-----\n"; + @Test public void testSignedMessage() throws IOException, MessagingException, PGPException { String messageSource = "Date: Mon, 08 Dec 2014 17:44:18 +0100\r\n" + "From: cketti \r\n" + @@ -209,7 +216,7 @@ public class PgpMimeMessageTest extends AndroidTestCase { "\r\n" + "--24Bem7EnUI1Ipn9jNXuLgsetqa6wOkIxM--\r\n"; - BinaryTempFileBody.setTempDirectory(getContext().getCacheDir()); + BinaryTempFileBody.setTempDirectory(InstrumentationRegistry.getTargetContext().getCacheDir()); InputStream messageInputStream = new ByteArrayInputStream(messageSource.getBytes()); MimeMessage message; diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/ReconstructMessageTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/ReconstructMessageTest.java index e36854354..fbf32f5e7 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/ReconstructMessageTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/ReconstructMessageTest.java @@ -6,14 +6,22 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; import android.test.AndroidTestCase; import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.internet.MimeMessage; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static junit.framework.Assert.assertEquals; -public class ReconstructMessageTest extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class ReconstructMessageTest { + @Test public void testMessage() throws IOException, MessagingException { String messageSource = "From: from@example.com\r\n" + @@ -45,7 +53,7 @@ public class ReconstructMessageTest extends AndroidTestCase { "------Boundary--\r\n" + "Hi, I'm the epilogue"; - BinaryTempFileBody.setTempDirectory(getContext().getCacheDir()); + BinaryTempFileBody.setTempDirectory(InstrumentationRegistry.getTargetContext().getCacheDir()); InputStream messageInputStream = new ByteArrayInputStream(messageSource.getBytes()); MimeMessage message; diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/ssl/TrustManagerFactoryTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/ssl/TrustManagerFactoryTest.java index 1574aaf03..8ed39808d 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/ssl/TrustManagerFactoryTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/ssl/TrustManagerFactoryTest.java @@ -1,18 +1,29 @@ package com.fsck.k9.mail.ssl; -import javax.net.ssl.X509TrustManager; - import java.io.ByteArrayInputStream; import java.io.File; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import android.test.AndroidTestCase; + +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import javax.net.ssl.X509TrustManager; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; + /** * Test the functionality of {@link TrustManagerFactory}. */ -public class TrustManagerFactoryTest extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class TrustManagerFactoryTest { public static final String MATCHING_HOST = "k9.example.com"; public static final String NOT_MATCHING_HOST = "bla.example.com"; public static final int PORT1 = 993; @@ -196,15 +207,16 @@ public class TrustManagerFactoryTest extends AndroidTestCase { new ByteArrayInputStream(encodedCert.getBytes())); } - @Override + @Before public void setUp() throws Exception { - mKeyStoreFile = File.createTempFile("localKeyStore", null, getContext().getCacheDir()); + mKeyStoreFile = File.createTempFile("localKeyStore", null, + InstrumentationRegistry.getTargetContext().getCacheDir()); mKeyStore = LocalKeyStore.getInstance(); mKeyStore.setKeyStoreFile(mKeyStoreFile); } - @Override - protected void tearDown() { + @After + public void tearDown() { mKeyStoreFile.delete(); } @@ -220,6 +232,7 @@ public class TrustManagerFactoryTest extends AndroidTestCase { * @throws Exception * if anything goes wrong */ + @Test public void testDifferentCertificatesOnSameServer() throws Exception { mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT1, mCert1); mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT2, mCert2); @@ -230,24 +243,28 @@ public class TrustManagerFactoryTest extends AndroidTestCase { trustManager1.checkServerTrusted(new X509Certificate[] { mCert1 }, "authType"); } + @Test public void testSelfSignedCertificateMatchingHost() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert1); X509TrustManager trustManager = TrustManagerFactory.get(MATCHING_HOST, PORT1); trustManager.checkServerTrusted(new X509Certificate[] { mCert1 }, "authType"); } + @Test public void testSelfSignedCertificateNotMatchingHost() throws Exception { mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT1, mCert1); X509TrustManager trustManager = TrustManagerFactory.get(NOT_MATCHING_HOST, PORT1); trustManager.checkServerTrusted(new X509Certificate[] { mCert1 }, "authType"); } + @Test public void testWrongCertificate() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert1); X509TrustManager trustManager = TrustManagerFactory.get(MATCHING_HOST, PORT1); assertCertificateRejection(trustManager, new X509Certificate[] { mCert2 }); } + @Test public void testCertificateOfOtherHost() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert1); mKeyStore.addCertificate(MATCHING_HOST, PORT2, mCert2); @@ -256,11 +273,13 @@ public class TrustManagerFactoryTest extends AndroidTestCase { assertCertificateRejection(trustManager, new X509Certificate[] { mCert2 }); } + @Test public void testUntrustedCertificateChain() throws Exception { X509TrustManager trustManager = TrustManagerFactory.get(MATCHING_HOST, PORT1); assertCertificateRejection(trustManager, new X509Certificate[] { mCert3, mCaCert }); } + @Test public void testLocallyTrustedCertificateChain() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert3); @@ -268,6 +287,7 @@ public class TrustManagerFactoryTest extends AndroidTestCase { trustManager.checkServerTrusted(new X509Certificate[] { mCert3, mCaCert }, "authType"); } + @Test public void testLocallyTrustedCertificateChainNotMatchingHost() throws Exception { mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT1, mCert3); @@ -275,17 +295,20 @@ public class TrustManagerFactoryTest extends AndroidTestCase { trustManager.checkServerTrusted(new X509Certificate[] { mCert3, mCaCert }, "authType"); } + @Test public void testGloballyTrustedCertificateChain() throws Exception { X509TrustManager trustManager = TrustManagerFactory.get("www.linux.com", PORT1); X509Certificate[] certificates = new X509Certificate[] { mLinuxComCert, mLinuxComFirstParentCert}; trustManager.checkServerTrusted(certificates, "authType"); } + @Test public void testGloballyTrustedCertificateNotMatchingHost() throws Exception { X509TrustManager trustManager = TrustManagerFactory.get(NOT_MATCHING_HOST, PORT1); assertCertificateRejection(trustManager, new X509Certificate[] { mLinuxComCert, mLinuxComFirstParentCert}); } + @Test public void testGloballyTrustedCertificateNotMatchingHostOverride() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mLinuxComCert); @@ -306,6 +329,7 @@ public class TrustManagerFactoryTest extends AndroidTestCase { assertFalse("The certificate should have been rejected but wasn't", certificateValid); } + @Test public void testKeyStoreLoading() throws Exception { mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert1); mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT2, mCert2); diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageExtractorTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageExtractorTest.java index 179f72053..6086118af 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageExtractorTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mailstore/LocalMessageExtractorTest.java @@ -3,22 +3,30 @@ package com.fsck.k9.mailstore; import java.util.Date; import java.util.Locale; import java.util.TimeZone; -import android.test.AndroidTestCase; + +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; import com.fsck.k9.activity.K9ActivityCommon; import com.fsck.k9.mail.Address; -import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Message.RecipientType; +import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeMessageHelper; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.TextBody; +import org.junit.Test; +import org.junit.runner.RunWith; import static com.fsck.k9.mailstore.LocalMessageExtractor.extractTextAndAttachments; +import static junit.framework.Assert.assertEquals; -public class LocalMessageExtractorTest extends AndroidTestCase { +@RunWith(AndroidJUnit4.class) +public class LocalMessageExtractorTest { + + @Test public void testSimplePlainTextMessage() throws MessagingException { String bodyText = "K-9 Mail rocks :>"; @@ -30,7 +38,7 @@ public class LocalMessageExtractorTest extends AndroidTestCase { MimeMessageHelper.setBody(message, body); // Extract text - ViewableContainer container = extractTextAndAttachments(getContext(), message); + ViewableContainer container = extractTextAndAttachments(InstrumentationRegistry.getTargetContext(), message); String expectedText = bodyText; String expectedHtml = @@ -42,6 +50,7 @@ public class LocalMessageExtractorTest extends AndroidTestCase { assertEquals(expectedHtml, container.html); } + @Test public void testSimpleHtmlMessage() throws MessagingException { String bodyText = "K-9 Mail rocks :>"; @@ -54,7 +63,7 @@ public class LocalMessageExtractorTest extends AndroidTestCase { MimeMessageHelper.setBody(message, body); // Extract text - ViewableContainer container = extractTextAndAttachments(getContext(), message); + ViewableContainer container = extractTextAndAttachments(InstrumentationRegistry.getTargetContext(), message); String expectedText = "K-9 Mail rocks :>"; String expectedHtml = @@ -64,6 +73,7 @@ public class LocalMessageExtractorTest extends AndroidTestCase { assertEquals(expectedHtml, container.html); } + @Test public void testMultipartPlainTextMessage() throws MessagingException { String bodyText1 = "text body 1"; String bodyText2 = "text body 2"; @@ -84,7 +94,7 @@ public class LocalMessageExtractorTest extends AndroidTestCase { MimeMessageHelper.setBody(message, multipart); // Extract text - ViewableContainer container = extractTextAndAttachments(getContext(), message); + ViewableContainer container = extractTextAndAttachments(InstrumentationRegistry.getTargetContext(), message); String expectedText = bodyText1 + "\r\n\r\n" + @@ -105,8 +115,9 @@ public class LocalMessageExtractorTest extends AndroidTestCase { assertEquals(expectedHtml, container.html); } + @Test public void testTextPlusRfc822Message() throws MessagingException { - K9ActivityCommon.setLanguage(getContext(), "en"); + K9ActivityCommon.setLanguage(InstrumentationRegistry.getTargetContext(), "en"); Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("GMT+01:00")); @@ -140,7 +151,7 @@ public class LocalMessageExtractorTest extends AndroidTestCase { MimeMessageHelper.setBody(message, multipart); // Extract text - ViewableContainer container = extractTextAndAttachments(getContext(), message); + ViewableContainer container = extractTextAndAttachments(InstrumentationRegistry.getTargetContext(), message); String expectedText = bodyText + From c79256684d08bf49c229ce42ec33b11624ad4aa7 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 04:29:09 +0100 Subject: [PATCH 20/22] simplify gradle config --- k9mail/build.gradle | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/k9mail/build.gradle b/k9mail/build.gradle index bc8198a57..ac4fe6ddb 100644 --- a/k9mail/build.gradle +++ b/k9mail/build.gradle @@ -23,17 +23,10 @@ dependencies { androidTestCompile 'com.android.support.test:testing-support-lib:0.1' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0' - - androidTestCompile("com.icegreen:greenmail:1.4.1-SNAPSHOT") { - // Use a better, later version - exclude group: "com.sun.mail" - exclude group: "junit" + androidTestCompile('com.icegreen:greenmail:1.4.1-SNAPSHOT') { + exclude group: 'junit' } - - // this version avoids some "Ignoring InnerClasses attribute for an anonymous inner class" warnings - androidTestCompile "javax.mail:javax.mail-api:1.5.2" - - androidTestCompile "com.madgag.spongycastle:pg:1.51.0.0" + androidTestCompile 'com.madgag.spongycastle:pg:1.51.0.0' } android { From 9523a589fc2c5b8225636a225f2214eb4063f5a4 Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 04:29:23 +0100 Subject: [PATCH 21/22] use `@Test(expected =` --- .../k9/activity/MessageReferenceTest.java | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java b/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java index 539545d74..a59e63a23 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/activity/MessageReferenceTest.java @@ -10,7 +10,6 @@ import org.junit.runner.RunWith; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; -import static junit.framework.Assert.assertTrue; @RunWith(AndroidJUnit4.class) public class MessageReferenceTest @@ -71,20 +70,13 @@ public class MessageReferenceTest assertNull(mr.accountUuid); } - @Test + @Test(expected = MessagingException.class) public void testNull() throws MessagingException { - try - { - new MessageReference(null); - assertTrue(false); - } catch (MessagingException e) - { - assertTrue(true); - } + new MessageReference(null); } - @Test + @Test(expected = MessagingException.class) public void testCorruption() throws MessagingException { MessageReference mr = new MessageReference("!:%^&%^*$&$by&(BYWkh:Zm9%^@sZGVy:MT-35#$AxMDEwMTA=:ANSWERED"); @@ -94,13 +86,6 @@ public class MessageReferenceTest assertNotNull(mr.uid); // Corruption in the Flag should throw MessagingException. - try - { - new MessageReference("!:%^&%^*$&$by&(BYWkh:Zm9%^@sZGVy:MT-35#$AxMDEwMTA=:ANSWE!RED"); - assertTrue(false); - } catch (MessagingException e) - { - assertTrue(true); - } + new MessageReference("!:%^&%^*$&$by&(BYWkh:Zm9%^@sZGVy:MT-35#$AxMDEwMTA=:ANSWE!RED"); } } From ecd316d0afe1fe112b1e40f920ad7c6255c95d7d Mon Sep 17 00:00:00 2001 From: Jan Berkel Date: Wed, 14 Jan 2015 04:22:04 +0100 Subject: [PATCH 22/22] Simplify ImapConnection#connect --- .../k9/mail/store/imap/ImapConnection.java | 19 ++++++++----------- .../mail/store/imap/ImapConnectionTest.java | 1 - 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java index cd679a5f8..9278f8708 100644 --- a/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java +++ b/k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapConnection.java @@ -555,14 +555,14 @@ class ImapConnection { private static Socket connect(ImapSettings settings, TrustedSocketFactory socketFactory) throws GeneralSecurityException, MessagingException, IOException { // Try all IPv4 and IPv6 addresses of the host - InetAddress[] addresses = InetAddress.getAllByName(settings.getHost()); - for (int i = 0; i < addresses.length; i++) { + Exception connectException = null; + for (InetAddress address : InetAddress.getAllByName(settings.getHost())) { try { if (K9MailLib.isDebug() && DEBUG_PROTOCOL_IMAP) { - Log.d(LOG_TAG, "Connecting to " + settings.getHost() + " as " + addresses[i]); + Log.d(LOG_TAG, "Connecting to " + settings.getHost() + " as " + address); } - SocketAddress socketAddress = new InetSocketAddress(addresses[i], settings.getPort()); + SocketAddress socketAddress = new InetSocketAddress(address, settings.getPort()); Socket socket; if (settings.getConnectionSecurity() == ConnectionSecurity.SSL_TLS_REQUIRED) { socket = socketFactory.createSocket( @@ -576,15 +576,12 @@ class ImapConnection { socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); // Successfully connected to the server; don't try any other addresses return socket; - } catch (SocketException e) { - if (i < (addresses.length - 1)) { - // There are still other addresses for that host to try - continue; - } - throw new MessagingException("Cannot connect to host", e); + } catch (IOException e) { + Log.w(LOG_TAG, "could not connect to "+address, e); + connectException = e; } } - throw new MessagingException("Cannot connect to host"); + throw new MessagingException("Cannot connect to host", connectException); } private void adjustDNSCacheTTL() { diff --git a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java index b34ff85f2..6465cb7cb 100644 --- a/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java +++ b/k9mail/src/androidTest/java/com/fsck/k9/mail/store/imap/ImapConnectionTest.java @@ -15,7 +15,6 @@ import com.fsck.k9.mail.ConnectionSecurity; import com.fsck.k9.mail.MessagingException; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith;