diff --git a/emailcommon/src/com/android/emailcommon/VendorPolicyLoader.java b/emailcommon/src/com/android/emailcommon/VendorPolicyLoader.java index 7221551b4..c056f0e3e 100644 --- a/emailcommon/src/com/android/emailcommon/VendorPolicyLoader.java +++ b/emailcommon/src/com/android/emailcommon/VendorPolicyLoader.java @@ -99,7 +99,7 @@ public class VendorPolicyLoader { * Constructor for testing, where we need to use an alternate package/class name, and skip * the system apk check. */ - /* package */ VendorPolicyLoader(Context context, String apkPackageName, String className, + public VendorPolicyLoader(Context context, String apkPackageName, String className, boolean allowNonSystemApk) { if (!allowNonSystemApk && !isSystemPackage(context, apkPackageName)) { mPolicyMethod = null; @@ -127,7 +127,7 @@ public class VendorPolicyLoader { } // Not private for testing - /* package */ static boolean isSystemPackage(Context context, String packageName) { + public static boolean isSystemPackage(Context context, String packageName) { try { ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0); return (ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0; @@ -142,7 +142,7 @@ public class VendorPolicyLoader { * getPolicy returns null). */ // Not private for testing - /* package */ Bundle getPolicy(String policy, Bundle args) { + public Bundle getPolicy(String policy, Bundle args) { Bundle ret = null; if (mPolicyMethod != null) { try { diff --git a/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java b/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java index e889f9774..5afbab3ca 100644 --- a/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java +++ b/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java @@ -151,6 +151,20 @@ public class AttachmentUtilities { .build(); } + // exposed for testing + public static Uri getAttachmentThumbnailUri(long accountId, long id, long width, long height) { + if (sUri == null) { + sUri = Uri.parse(Attachment.ATTACHMENT_PROVIDER_URI_PREFIX); + } + return sUri.buildUpon() + .appendPath(Long.toString(accountId)) + .appendPath(Long.toString(id)) + .appendPath(FORMAT_THUMBNAIL) + .appendPath(Long.toString(width)) + .appendPath(Long.toString(height)) + .build(); + } + /** * Return the filename for a given attachment. This should be used by any code that is * going to *write* attachments. diff --git a/src/com/android/email/NotificationController.java b/src/com/android/email/NotificationController.java index f36264079..a81bb025c 100644 --- a/src/com/android/email/NotificationController.java +++ b/src/com/android/email/NotificationController.java @@ -89,7 +89,7 @@ public class NotificationController { private ContentObserver mAccountObserver; /** Constructor */ - private NotificationController(Context context, Clock clock) { + protected NotificationController(Context context, Clock clock) { mContext = context.getApplicationContext(); EmailContent.init(context); mNotificationManager = (NotificationManager) context.getSystemService( diff --git a/src/com/android/email/activity/setup/AccountSettingsUtils.java b/src/com/android/email/activity/setup/AccountSettingsUtils.java index a2234c26d..eaf50850f 100644 --- a/src/com/android/email/activity/setup/AccountSettingsUtils.java +++ b/src/com/android/email/activity/setup/AccountSettingsUtils.java @@ -178,7 +178,7 @@ public class AccountSettingsUtils { * part (i.e. substring demarcated by a period, '.') */ @VisibleForTesting - static boolean matchProvider(String testDomain, String providerDomain) { + public static boolean matchProvider(String testDomain, String providerDomain) { String[] testParts = testDomain.split(DOMAIN_SEPARATOR); String[] providerParts = providerDomain.split(DOMAIN_SEPARATOR); if (testParts.length != providerParts.length) { diff --git a/src/com/android/email/mail/transport/MailTransport.java b/src/com/android/email/mail/transport/MailTransport.java index 0e2ffede4..d47c831d6 100644 --- a/src/com/android/email/mail/transport/MailTransport.java +++ b/src/com/android/email/mail/transport/MailTransport.java @@ -55,7 +55,7 @@ public class MailTransport { private final String mDebugLabel; private final Context mContext; - private final HostAuth mHostAuth; + protected final HostAuth mHostAuth; private Socket mSocket; private InputStream mIn; diff --git a/src/com/android/email/mail/transport/SmtpSender.java b/src/com/android/email/mail/transport/SmtpSender.java index c4446fb38..eb109bf67 100644 --- a/src/com/android/email/mail/transport/SmtpSender.java +++ b/src/com/android/email/mail/transport/SmtpSender.java @@ -75,7 +75,7 @@ public class SmtpSender extends Sender { * up and ready to use. Do not use for real code. * @param testTransport The Transport to inject and use for all future communication. */ - /* package */ void setTransport(MailTransport testTransport) { + public void setTransport(MailTransport testTransport) { mTransport = testTransport; } diff --git a/src/com/android/email/provider/EmailProvider.java b/src/com/android/email/provider/EmailProvider.java index d1be0b2b3..742728fed 100644 --- a/src/com/android/email/provider/EmailProvider.java +++ b/src/com/android/email/provider/EmailProvider.java @@ -150,8 +150,10 @@ public class EmailProvider extends ContentProvider { public static String EMAIL_APP_MIME_TYPE; - private static final String DATABASE_NAME = "EmailProvider.db"; - private static final String BODY_DATABASE_NAME = "EmailProviderBody.db"; + // exposed for testing + public static final String DATABASE_NAME = "EmailProvider.db"; + public static final String BODY_DATABASE_NAME = "EmailProviderBody.db"; + private static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db"; /** @@ -342,7 +344,9 @@ public class EmailProvider extends ContentProvider { return match; } - private static Uri INTEGRITY_CHECK_URI; + // exposed for testing + public static Uri INTEGRITY_CHECK_URI; + public static Uri ACCOUNT_BACKUP_URI; private static Uri FOLDER_STATUS_URI; @@ -369,13 +373,14 @@ public class EmailProvider extends ContentProvider { /** * Orphan record deletion utility. Generates a sqlite statement like: * delete from where not in (select from ) + * Exposed for testing. * @param db the EmailProvider database * @param table the table whose orphans are to be removed * @param column the column deletion will be based on * @param foreignColumn the column in the foreign table whose absence will trigger the deletion * @param foreignTable the foreign table */ - private static void deleteUnlinked(SQLiteDatabase db, String table, String column, + public static void deleteUnlinked(SQLiteDatabase db, String table, String column, String foreignColumn, String foreignTable) { int count = db.delete(table, column + " not in (select " + foreignColumn + " from " + foreignTable + ")", null); @@ -425,8 +430,8 @@ public class EmailProvider extends ContentProvider { } - - private SQLiteDatabase getDatabase(Context context) { + // exposed for testing + public SQLiteDatabase getDatabase(Context context) { synchronized (sDatabaseLock) { // Always return the cached database, if we've got one if (mDatabase != null) { @@ -519,7 +524,8 @@ public class EmailProvider extends ContentProvider { } } - private static void deleteMessageOrphans(SQLiteDatabase database, String tableName) { + // exposed for testing + public static void deleteMessageOrphans(SQLiteDatabase database, String tableName) { if (database != null) { // We'll look at all of the items in the table; there won't be many typically Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null); @@ -2133,7 +2139,13 @@ public class EmailProvider extends ContentProvider { AttachmentDownloadService.attachmentChanged(context, id, flags); } }; - private final AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE; + private AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE; + + // exposed for testing + public void injectAttachmentService(AttachmentService attachmentService) { + mAttachmentService = + attachmentService == null ? DEFAULT_ATTACHMENT_SERVICE : attachmentService; + } private Cursor notificationQuery(final Uri uri) { final SQLiteDatabase db = getDatabase(getContext()); diff --git a/tests/oldAndroid.mk b/tests/oldAndroid.mk deleted file mode 100644 index 29f51720c..000000000 --- a/tests/oldAndroid.mk +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright 2008, The Android Open Source Project -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -LOCAL_PATH:= $(call my-dir) -include $(CLEAR_VARS) - -# We only want this apk build for tests. -LOCAL_MODULE_TAGS := tests - -LOCAL_JAVA_LIBRARIES := android.test.runner - -# Include all test java files. -LOCAL_SRC_FILES := $(call all-java-files-under, src) - -# Notice that we don't have to include the src files of Email because, by -# running the tests using an instrumentation targeting Email, we -# automatically get all of its classes loaded into our environment. - -LOCAL_PACKAGE_NAME := EmailTests - -LOCAL_INSTRUMENTATION_FOR := Email - -include $(BUILD_PACKAGE) diff --git a/tests/src/com/android/email/ControllerProviderOpsTests.java b/tests/src/com/android/email/ControllerProviderOpsTests.java index 80d08f9f6..51c7a932f 100644 --- a/tests/src/com/android/email/ControllerProviderOpsTests.java +++ b/tests/src/com/android/email/ControllerProviderOpsTests.java @@ -1,17 +1,17 @@ /* * Copyright (C) 2009 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. */ package com.android.email; @@ -44,11 +44,8 @@ import java.util.concurrent.ExecutionException; * runtest -c com.android.email.ControllerProviderOpsTests email */ public class ControllerProviderOpsTests extends ProviderTestCase2 { - private Context mProviderContext; private Context mContext; - private TestController mTestController; - public ControllerProviderOpsTests() { super(EmailProvider.class, EmailContent.AUTHORITY); @@ -59,7 +56,6 @@ public class ControllerProviderOpsTests extends ProviderTestCase2 super.setUp(); mProviderContext = getMockContext(); mContext = getContext(); - mTestController = new TestController(mProviderContext, mContext); // Invalidate all caches, since we reset the database for each test ContentCache.invalidateAllCaches(); } @@ -67,460 +63,36 @@ public class ControllerProviderOpsTests extends ProviderTestCase2 @Override public void tearDown() throws Exception { super.tearDown(); - mTestController.cleanupForTest(); - } - - /** - * Lightweight subclass of the Controller class allows injection of mock context - */ - public static class TestController extends Controller { - - protected TestController(Context providerContext, Context systemContext) { - super(systemContext); - setProviderContext(providerContext); - } } /** * These are strings that should not change per locale. */ public void testGetMailboxServerName() { - assertEquals("", Controller.getMailboxServerName(mContext, -1)); + try { + Mailbox.getSystemMailboxName(mContext, -1); + fail("Mailbox.getSystemMailboxName(mContext, -1) succeeded without an exception"); + } catch (IllegalArgumentException e) { + // we expect an exception, so do nothing + } - assertEquals("Inbox", Controller.getMailboxServerName(mContext, Mailbox.TYPE_INBOX)); - assertEquals("Outbox", Controller.getMailboxServerName(mContext, Mailbox.TYPE_OUTBOX)); - assertEquals("Trash", Controller.getMailboxServerName(mContext, Mailbox.TYPE_TRASH)); - assertEquals("Sent", Controller.getMailboxServerName(mContext, Mailbox.TYPE_SENT)); - assertEquals("Junk", Controller.getMailboxServerName(mContext, Mailbox.TYPE_JUNK)); + assertEquals("Inbox", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_INBOX)); + assertEquals("Outbox", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_OUTBOX)); + assertEquals("Trash", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_TRASH)); + assertEquals("Sent", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_SENT)); + assertEquals("Junk", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_JUNK)); // Now try again with translation Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); - assertEquals("Inbox", Controller.getMailboxServerName(mContext, Mailbox.TYPE_INBOX)); - assertEquals("Outbox", Controller.getMailboxServerName(mContext, Mailbox.TYPE_OUTBOX)); - assertEquals("Trash", Controller.getMailboxServerName(mContext, Mailbox.TYPE_TRASH)); - assertEquals("Sent", Controller.getMailboxServerName(mContext, Mailbox.TYPE_SENT)); - assertEquals("Junk", Controller.getMailboxServerName(mContext, Mailbox.TYPE_JUNK)); + assertEquals("Inbox", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_INBOX)); + assertEquals("Outbox", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_OUTBOX)); + assertEquals("Trash", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_TRASH)); + assertEquals("Sent", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_SENT)); + assertEquals("Junk", Mailbox.getSystemMailboxName(mContext, Mailbox.TYPE_JUNK)); Locale.setDefault(savedLocale); } - /** - * Test of Controller.createMailbox(). - * Sunny day test only - creates a mailbox that does not exist. - * Does not test duplication, bad accountID, or any other bad input. - */ - public void testCreateMailbox() { - // safety check that system mailboxes don't exist ... - assertEquals(Mailbox.NO_MAILBOX, - Mailbox.findMailboxOfType(mProviderContext, 1L, Mailbox.TYPE_DRAFTS)); - assertEquals(Mailbox.NO_MAILBOX, - Mailbox.findMailboxOfType(mProviderContext, 1L, Mailbox.TYPE_SENT)); - - long testMailboxId; - Mailbox testMailbox; - - // Test creating "drafts" mailbox - mTestController.createMailbox(1L, Mailbox.TYPE_DRAFTS); - testMailboxId = Mailbox.findMailboxOfType(mProviderContext, 1L, Mailbox.TYPE_DRAFTS); - assertTrue(testMailboxId != Mailbox.NO_MAILBOX); - testMailbox = Mailbox.restoreMailboxWithId(mProviderContext, testMailboxId); - assertNotNull(testMailbox); - assertEquals(8, testMailbox.mFlags); // Flags should be "holds mail" - assertEquals(-1L, testMailbox.mParentKey); // Parent is off the top-level - - // Test creating "sent" mailbox; same as drafts - mTestController.createMailbox(1L, Mailbox.TYPE_SENT); - testMailboxId = Mailbox.findMailboxOfType(mProviderContext, 1L, Mailbox.TYPE_SENT); - assertTrue(testMailboxId != Mailbox.NO_MAILBOX); - testMailbox = Mailbox.restoreMailboxWithId(mProviderContext, testMailboxId); - assertNotNull(testMailbox); - assertEquals(8, testMailbox.mFlags); // Flags should be "holds mail" - assertEquals(-1L, testMailbox.mParentKey); // Parent is off the top-level - } - - /** - * Test of Controller.findOrCreateMailboxOfType(). - * Checks: - * - finds correctly the ID of existing mailbox - * - creates non-existing mailbox - * - creates only once a new mailbox - * - when accountId or mailboxType are -1, returns NO_MAILBOX - */ - public void testFindOrCreateMailboxOfType() { - Account account = ProviderTestUtils.setupAccount("mailboxid", true, mProviderContext); - long accountId = account.mId; - Mailbox box = ProviderTestUtils.setupMailbox("box", accountId, false, mProviderContext); - final int boxType = Mailbox.TYPE_TRASH; - box.mType = boxType; - box.save(mProviderContext); - long boxId = box.mId; - - long testBoxId = mTestController.findOrCreateMailboxOfType(accountId, boxType); - - // check it found the right mailbox id - assertEquals(boxId, testBoxId); - - long boxId2 = mTestController.findOrCreateMailboxOfType(accountId, Mailbox.TYPE_DRAFTS); - assertTrue("mailbox created", boxId2 != Mailbox.NO_MAILBOX); - assertTrue("with different id", testBoxId != boxId2); - - // check it doesn't create twice when existing - long boxId3 = mTestController.findOrCreateMailboxOfType(accountId, Mailbox.TYPE_DRAFTS); - assertEquals("don't create if exists", boxId3, boxId2); - - // check invalid aruments - assertEquals(Mailbox.NO_MAILBOX, - mTestController.findOrCreateMailboxOfType(-1, Mailbox.TYPE_DRAFTS)); - assertEquals(Mailbox.NO_MAILBOX, mTestController.findOrCreateMailboxOfType(accountId, -1)); - } - - /** - * Test the "move message" function. - */ - public void testMoveMessage() throws InterruptedException, ExecutionException { - Account account1 = ProviderTestUtils.setupAccount("message-move", true, mProviderContext); - long account1Id = account1.mId; - Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mProviderContext); - long box1Id = box1.mId; - Mailbox box2 = ProviderTestUtils.setupMailbox("box2", account1Id, true, mProviderContext); - long box2Id = box2.mId; - Mailbox boxDest = ProviderTestUtils.setupMailbox("d", account1Id, true, mProviderContext); - long boxDestId = boxDest.mId; - - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mProviderContext); - Message message2 = ProviderTestUtils.setupMessage("message2", account1Id, box2Id, false, - true, mProviderContext); - long message1Id = message1.mId; - long message2Id = message2.mId; - - // Because moveMessage runs asynchronously, call get() to force it to complete - mTestController.moveMessages(new long[] { message1Id, message2Id }, boxDestId).get(); - - // now read back a fresh copy and confirm it's in the trash - assertEquals(boxDestId, EmailContent.Message.restoreMessageWithId(mProviderContext, - message1Id).mMailboxKey); - assertEquals(boxDestId, EmailContent.Message.restoreMessageWithId(mProviderContext, - message2Id).mMailboxKey); - } - - /** - * Test the "delete message" function. Sunny day: - * - message/mailbox/account all exist - * - trash mailbox exists - */ - public void testDeleteMessage() { - Account account1 = ProviderTestUtils.setupAccount("message-delete", true, mProviderContext); - long account1Id = account1.mId; - Mailbox box = ProviderTestUtils.setupMailbox("box1", account1Id, true, mProviderContext); - long boxId = box.mId; - - Mailbox trashBox = ProviderTestUtils.setupMailbox("box2", account1Id, false, - mProviderContext); - trashBox.mType = Mailbox.TYPE_TRASH; - trashBox.save(mProviderContext); - long trashBoxId = trashBox.mId; - - Mailbox draftBox = ProviderTestUtils.setupMailbox("box3", account1Id, false, - mProviderContext); - draftBox.mType = Mailbox.TYPE_DRAFTS; - draftBox.save(mProviderContext); - long draftBoxId = draftBox.mId; - - { - // Case 1: Message in a regular mailbox, account known. - Message message = ProviderTestUtils.setupMessage("message1", account1Id, boxId, false, - true, mProviderContext); - long messageId = message.mId; - - mTestController.deleteMessageSync(messageId); - - // now read back a fresh copy and confirm it's in the trash - Message restored = EmailContent.Message.restoreMessageWithId(mProviderContext, - messageId); - assertEquals(trashBoxId, restored.mMailboxKey); - } - - { - // Case 2: Already in trash - Message message = ProviderTestUtils.setupMessage("message3", account1Id, trashBoxId, - false, true, mProviderContext); - long messageId = message.mId; - - mTestController.deleteMessageSync(messageId); - - // Message should be deleted. - assertNull(EmailContent.Message.restoreMessageWithId(mProviderContext, messageId)); - } - - { - // Case 3: Draft - Message message = ProviderTestUtils.setupMessage("message3", account1Id, draftBoxId, - false, true, mProviderContext); - long messageId = message.mId; - - mTestController.deleteMessageSync(messageId); - - // Message should be deleted. - assertNull(EmailContent.Message.restoreMessageWithId(mProviderContext, messageId)); - } - } - - /** - * Test deleting message when there is no trash mailbox - */ - public void testDeleteMessageNoTrash() { - Account account1 = - ProviderTestUtils.setupAccount("message-delete-notrash", true, mProviderContext); - long account1Id = account1.mId; - Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mProviderContext); - long box1Id = box1.mId; - - Message message1 = - ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, true, - mProviderContext); - long message1Id = message1.mId; - - mTestController.deleteMessageSync(message1Id); - - // now read back a fresh copy and confirm it's in the trash - Message message1get = - EmailContent.Message.restoreMessageWithId(mProviderContext, message1Id); - - // check the new mailbox and see if it looks right - assertFalse(-1 == message1get.mMailboxKey); - assertFalse(box1Id == message1get.mMailboxKey); - Mailbox mailbox2get = Mailbox.restoreMailboxWithId(mProviderContext, - message1get.mMailboxKey); - assertEquals(Mailbox.TYPE_TRASH, mailbox2get.mType); - } - - /** - * Test read/unread flag - */ - public void testReadUnread() throws InterruptedException, ExecutionException { - Account account1 = ProviderTestUtils.setupAccount("read-unread", false, mProviderContext); - account1.mHostAuthRecv - = ProviderTestUtils.setupHostAuth("read-unread", 0, false, mProviderContext); - account1.save(mProviderContext); - long account1Id = account1.mId; - long box1Id = 2; - - Message message1 = - ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, true, - mProviderContext); - long message1Id = message1.mId; - - // test setting to "read" - mTestController.setMessageRead(message1Id, true).get(); - Message message1get = Message.restoreMessageWithId(mProviderContext, message1Id); - assertTrue(message1get.mFlagRead); - - // test setting to "unread" - mTestController.setMessageRead(message1Id, false).get(); - message1get = Message.restoreMessageWithId(mProviderContext, message1Id); - assertFalse(message1get.mFlagRead); - - // test setting to "read" - mTestController.setMessageRead(message1Id, true).get(); - message1get = Message.restoreMessageWithId(mProviderContext, message1Id); - assertTrue(message1get.mFlagRead); - } - - /** - * Test favorites flag - */ - public void testFavorites() throws InterruptedException, ExecutionException { - Account account1 = ProviderTestUtils.setupAccount("favorites", false, mProviderContext); - account1.mHostAuthRecv - = ProviderTestUtils.setupHostAuth("favorites", 0, false, mProviderContext); - account1.save(mProviderContext); - long account1Id = account1.mId; - long box1Id = 2; - - Message message1 = - ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, true, - mProviderContext); - long message1Id = message1.mId; - - // test setting to "favorite" - mTestController.setMessageFavorite(message1Id, true).get(); - Message message1get = Message.restoreMessageWithId(mProviderContext, message1Id); - assertTrue(message1get.mFlagFavorite); - - // test setting to "not favorite" - mTestController.setMessageFavorite(message1Id, false).get(); - message1get = Message.restoreMessageWithId(mProviderContext, message1Id); - assertFalse(message1get.mFlagFavorite); - - // test setting to "favorite" - mTestController.setMessageFavorite(message1Id, true).get(); - message1get = Message.restoreMessageWithId(mProviderContext, message1Id); - assertTrue(message1get.mFlagFavorite); - } - - public void testGetAndDeleteAttachmentMailbox() { - Mailbox box = mTestController.getAttachmentMailbox(); - assertNotNull(box); - Mailbox anotherBox = mTestController.getAttachmentMailbox(); - assertNotNull(anotherBox); - // We should always get back the same Mailbox row - assertEquals(box.mId, anotherBox.mId); - // Add two messages to this mailbox - ProviderTestUtils.setupMessage("message1", 0, box.mId, false, true, - mProviderContext); - ProviderTestUtils.setupMessage("message2", 0, box.mId, false, true, - mProviderContext); - // Make sure we can find them where they are expected - assertEquals(2, EmailContent.count(mProviderContext, Message.CONTENT_URI, - Message.MAILBOX_KEY + "=?", new String[] {Long.toString(box.mId)})); - // Delete them - mTestController.deleteAttachmentMessages(); - // Make sure they're gone - assertEquals(0, EmailContent.count(mProviderContext, Message.CONTENT_URI, - Message.MAILBOX_KEY + "=?", new String[] {Long.toString(box.mId)})); - } - - /** - * Test wiping an account's synced data. Everything should go, but account & empty inbox. - * Also ensures that the remaining account and the remaining inbox have cleared their - * server sync keys, to force refresh eventually. - */ - public void testWipeSyncedData() { - Account account1 = ProviderTestUtils.setupAccount("wipe-synced-1", false, mProviderContext); - account1.mSyncKey = "account-1-sync-key"; - account1.save(mProviderContext); - long account1Id = account1.mId; - Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, false, mProviderContext); - box1.mType = Mailbox.TYPE_INBOX; - box1.mSyncKey = "box-1-sync-key"; - box1.save(mProviderContext); - long box1Id = box1.mId; - Mailbox box2 = ProviderTestUtils.setupMailbox("box2", account1Id, true, mProviderContext); - long box2Id = box2.mId; - - Account account2 = ProviderTestUtils.setupAccount("wipe-synced-2", false, mProviderContext); - account2.mSyncKey = "account-2-sync-key"; - account2.save(mProviderContext); - long account2Id = account2.mId; - Mailbox box3 = ProviderTestUtils.setupMailbox("box3", account2Id, false, mProviderContext); - box3.mSyncKey = "box-3-sync-key"; - box3.mType = Mailbox.TYPE_INBOX; - box3.save(mProviderContext); - long box3Id = box3.mId; - Mailbox box4 = ProviderTestUtils.setupMailbox("box4", account2Id, true, mProviderContext); - long box4Id = box4.mId; - - // Now populate the 4 non-account boxes with messages - Message message = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mProviderContext); - long message1Id = message.mId; - message = ProviderTestUtils.setupMessage("message2", account1Id, box2Id, false, - true, mProviderContext); - long message2Id = message.mId; - message = ProviderTestUtils.setupMessage("message3", account2Id, box3Id, false, - true, mProviderContext); - long message3Id = message.mId; - message = ProviderTestUtils.setupMessage("message4", account2Id, box4Id, false, - true, mProviderContext); - long message4Id = message.mId; - - // Now wipe account 1's data - mTestController.deleteSyncedDataSync(account1Id); - - // Confirm: Mailboxes gone (except account box), all messages gone, account survives - assertNull(Mailbox.restoreMailboxWithId(mProviderContext, box1Id)); - assertNull(Mailbox.restoreMailboxWithId(mProviderContext, box2Id)); - assertNull(Message.restoreMessageWithId(mProviderContext, message1Id)); - assertNull(Message.restoreMessageWithId(mProviderContext, message2Id)); - account1 = Account.restoreAccountWithId(mProviderContext, account1Id); - assertNotNull(account1); - assertNull(account1.mSyncKey); - - // Confirm: Other account survived - assertNotNull(Mailbox.restoreMailboxWithId(mProviderContext, box3Id)); - assertNotNull(Mailbox.restoreMailboxWithId(mProviderContext, box4Id)); - assertNotNull(Message.restoreMessageWithId(mProviderContext, message3Id)); - assertNotNull(Message.restoreMessageWithId(mProviderContext, message4Id)); - assertNotNull(Account.restoreAccountWithId(mProviderContext, account2Id)); - } - - public void testLoadMessageFromUri() throws Exception { - // Create a simple message - Message msg = new Message(); - String text = "This is some text"; - msg.mText = text; - String sender = "sender@host.com"; - msg.mFrom = sender; - // Save this away - msg.save(mProviderContext); - - Uri fileUri = ProviderTestUtils.createTempEmlFile(mProviderContext, msg, - mContext.getFilesDir()); - - // Load the message via Controller and a Uri - Message loadedMsg = mTestController.loadMessageFromUri(fileUri); - - // Check server id, mailbox key, account key, and from - assertNotNull(loadedMsg); - assertTrue(loadedMsg.mServerId.startsWith(Controller.ATTACHMENT_MESSAGE_UID_PREFIX)); - Mailbox box = mTestController.getAttachmentMailbox(); - assertNotNull(box); - assertEquals(box.mId, loadedMsg.mMailboxKey); - assertEquals(0, loadedMsg.mAccountKey); - assertEquals(loadedMsg.mFrom, sender); - // Check body text - String loadedMsgText = Body.restoreBodyTextWithMessageId(mProviderContext, loadedMsg.mId); - assertEquals(text, loadedMsgText); - } - - /** - * Create a simple HostAuth with protocol - */ - private HostAuth setupSimpleHostAuth(String protocol) { - HostAuth hostAuth = new HostAuth(); - hostAuth.mProtocol = protocol; - return hostAuth; - } - - public void testIsMessagingController() { - Account account1 = ProviderTestUtils.setupAccount("account1", false, - mProviderContext); - account1.mHostAuthRecv = setupSimpleHostAuth("eas"); - account1.save(mProviderContext); - assertFalse(mTestController.isMessagingController(account1)); - Account account2 = ProviderTestUtils.setupAccount("account2", false, - mProviderContext); - account2.mHostAuthRecv = setupSimpleHostAuth("imap"); - account2.save(mProviderContext); - assertTrue(mTestController.isMessagingController(account2)); - Account account3 = ProviderTestUtils.setupAccount("account3", false, - mProviderContext); - account3.mHostAuthRecv = setupSimpleHostAuth("pop3"); - account3.save(mProviderContext); - assertTrue(mTestController.isMessagingController(account3)); - Account account4 = ProviderTestUtils.setupAccount("account4", false, - mProviderContext); - account4.mHostAuthRecv = setupSimpleHostAuth("smtp"); - account4.save(mProviderContext); - assertFalse(mTestController.isMessagingController(account4)); - // There should be values for all of these accounts in the legacy map - assertNotNull(mTestController.mLegacyControllerMap.get(account1.mId)); - assertNotNull(mTestController.mLegacyControllerMap.get(account2.mId)); - assertNotNull(mTestController.mLegacyControllerMap.get(account3.mId)); - assertNotNull(mTestController.mLegacyControllerMap.get(account4.mId)); - // The map should have the expected values - assertFalse(mTestController.mLegacyControllerMap.get(account1.mId)); - assertTrue(mTestController.mLegacyControllerMap.get(account2.mId)); - assertTrue(mTestController.mLegacyControllerMap.get(account3.mId)); - assertFalse(mTestController.mLegacyControllerMap.get(account4.mId)); - // This second pass should pull values from the cache - assertFalse(mTestController.isMessagingController(account1)); - assertTrue(mTestController.isMessagingController(account2)); - assertTrue(mTestController.isMessagingController(account3)); - assertFalse(mTestController.isMessagingController(account4)); - } - /** * TODO: releasing associated data (e.g. attachments, embedded images) */ diff --git a/tests/src/com/android/email/DBTestHelper.java b/tests/src/com/android/email/DBTestHelper.java index 0ba3eaa45..c3b9039c5 100644 --- a/tests/src/com/android/email/DBTestHelper.java +++ b/tests/src/com/android/email/DBTestHelper.java @@ -16,12 +16,6 @@ package com.android.email; -import com.android.email.provider.AttachmentProvider; -import com.android.email.provider.ContentCache; -import com.android.email.provider.EmailProvider; -import com.android.emailcommon.provider.EmailContent; -import com.android.emailcommon.utility.AttachmentUtilities; - import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; @@ -37,6 +31,12 @@ import android.test.mock.MockContentResolver; import android.test.mock.MockContext; import android.test.mock.MockCursor; +import com.android.email.provider.AttachmentProvider; +import com.android.email.provider.ContentCache; +import com.android.email.provider.EmailProvider; +import com.android.emailcommon.provider.EmailContent; +import com.android.emailcommon.provider.EmailContent.Attachment; + import java.io.File; /** @@ -238,7 +238,7 @@ public final class DBTestHelper { final AttachmentProvider ap = new AttachmentProvider(); ap.attachInfo(providerContext, null); - resolver.addProvider(AttachmentUtilities.AUTHORITY, ap); + resolver.addProvider(Attachment.ATTACHMENT_PROVIDER_LEGACY_URI_PREFIX, ap); ContentCache.invalidateAllCaches(); diff --git a/tests/src/com/android/email/FolderPropertiesTests.java b/tests/src/com/android/email/FolderPropertiesTests.java deleted file mode 100644 index 867c9a08c..000000000 --- a/tests/src/com/android/email/FolderPropertiesTests.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email; - -import com.android.emailcommon.provider.EmailContent.MailboxColumns; -import com.android.emailcommon.provider.Mailbox; - -import android.content.Context; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.graphics.drawable.Drawable; -import android.test.AndroidTestCase; - -import java.util.HashSet; -import java.util.Set; - -public class FolderPropertiesTests extends AndroidTestCase { - - private static Cursor buildCursor(String[] columns, Object... values) { - MatrixCursor c = new MatrixCursorWithCachedColumns(columns, 1); - c.addRow(values); - c.moveToFirst(); - return c; - } - - /** - * Tests of the syncronization of array and types of the display folder names - */ - public void testGetDisplayName() { - Context context = getContext(); - FolderProperties fp = FolderProperties.getInstance(context); - - assertEquals( - context.getString(R.string.mailbox_name_display_inbox), - fp.getDisplayName(Mailbox.TYPE_INBOX, 0, "ignored")); - - assertEquals( - "*name*", - fp.getDisplayName(Mailbox.TYPE_MAIL, 0, "*name*")); - - assertEquals( - "*name2*", - fp.getDisplayName(Mailbox.TYPE_PARENT, 0, "*name2*")); - - assertEquals( - context.getString(R.string.mailbox_name_display_drafts), - fp.getDisplayName(Mailbox.TYPE_DRAFTS, 0, "ignored")); - - assertEquals( - context.getString(R.string.mailbox_name_display_outbox), - fp.getDisplayName(Mailbox.TYPE_OUTBOX, 0, "ignored")); - - assertEquals( - context.getString(R.string.mailbox_name_display_sent), - fp.getDisplayName(Mailbox.TYPE_SENT, 0, "ignored")); - - assertEquals( - context.getString(R.string.mailbox_name_display_trash), - fp.getDisplayName(Mailbox.TYPE_TRASH, 0, "ignored")); - - assertEquals( - context.getString(R.string.mailbox_name_display_junk), - fp.getDisplayName(Mailbox.TYPE_JUNK, 0, "ignored")); - - // Testing illegal index - assertEquals( - "some name", - fp.getDisplayName(8, 12345678890L, "some name")); - - - // Combined mailboxes - assertEquals( - context.getString(R.string.account_folder_list_summary_inbox), - fp.getDisplayName(0, Mailbox.QUERY_ALL_INBOXES, "ignored")); - assertEquals( - context.getString(R.string.account_folder_list_summary_starred), - fp.getDisplayName(0, Mailbox.QUERY_ALL_FAVORITES, "ignored")); - assertEquals( - context.getString(R.string.account_folder_list_summary_drafts), - fp.getDisplayName(0, Mailbox.QUERY_ALL_DRAFTS, "ignored")); - assertEquals( - context.getString(R.string.account_folder_list_summary_outbox), - fp.getDisplayName(0, Mailbox.QUERY_ALL_OUTBOX, "ignored")); - } - - public void testGetDisplayNameWithCursor() { - Context context = getContext(); - FolderProperties fp = FolderProperties.getInstance(context); - String[] columns = new String[] {MailboxColumns.ID, MailboxColumns.TYPE, - MailboxColumns.DISPLAY_NAME}; - - assertEquals( - context.getString(R.string.mailbox_name_display_inbox), - fp.getDisplayName(buildCursor(columns, 1, Mailbox.TYPE_INBOX, "ignored")) - ); - - assertEquals( - "name", - fp.getDisplayName(buildCursor(columns, 1, Mailbox.TYPE_MAIL, "name")) - ); - } - - /** - * Confirm that all of the special icons are available and unique - */ - public void testSpecialIcons() { - FolderProperties fp = FolderProperties.getInstance(mContext); - - // Make sure they're available - Drawable inbox = fp.getIcon(Mailbox.TYPE_INBOX, -1, 0); - Drawable mail = fp.getIcon(Mailbox.TYPE_MAIL, -1, 0); - Drawable parent = fp.getIcon(Mailbox.TYPE_PARENT, -1, 0); - Drawable drafts = fp.getIcon(Mailbox.TYPE_DRAFTS, -1, 0); - Drawable outbox = fp.getIcon(Mailbox.TYPE_OUTBOX, -1, 0); - Drawable sent = fp.getIcon(Mailbox.TYPE_SENT, -1, 0); - Drawable trash = fp.getIcon(Mailbox.TYPE_TRASH, -1, 0); - Drawable junk = fp.getIcon(Mailbox.TYPE_JUNK, -1, 0); - - // Make sure they're unique - Set set = new HashSet(); - set.add(inbox); - set.add(parent); - set.add(drafts); - set.add(outbox); - set.add(sent); - set.add(trash); - set.add(junk); - assertEquals(7, set.size()); - - assertNull(mail); - } - - public void testGetMessageCountWithCursor() { - Context context = getContext(); - FolderProperties fp = FolderProperties.getInstance(context); - String[] columns = new String[] {MailboxColumns.TYPE, MailboxColumns.UNREAD_COUNT, - MailboxColumns.MESSAGE_COUNT}; - - assertEquals( - 1, - fp.getMessageCount(buildCursor(columns, Mailbox.TYPE_INBOX, 1, 2)) - ); - assertEquals( - 1, - fp.getMessageCount(buildCursor(columns, Mailbox.TYPE_MAIL, 1, 2)) - ); - - assertEquals( - 2, - fp.getMessageCount(buildCursor(columns, Mailbox.TYPE_DRAFTS, 1, 2)) - ); - assertEquals( - 2, - fp.getMessageCount(buildCursor(columns, Mailbox.TYPE_OUTBOX, 1, 2)) - ); - - assertEquals( - 0, - fp.getMessageCount(buildCursor(columns, Mailbox.TYPE_TRASH, 1, 2)) - ); - - assertEquals( - 0, - fp.getMessageCount(buildCursor(columns, Mailbox.TYPE_SENT, 1, 2)) - ); - } -} diff --git a/tests/src/com/android/email/GroupMessagingListenerUnitTests.java b/tests/src/com/android/email/GroupMessagingListenerUnitTests.java deleted file mode 100644 index bf950cd01..000000000 --- a/tests/src/com/android/email/GroupMessagingListenerUnitTests.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email; - -import android.test.suitebuilder.annotation.SmallTest; - -import junit.framework.TestCase; - -/** - * This is a series of unit tests for the GroupMessagingListener class. - */ -@SmallTest -public class GroupMessagingListenerUnitTests extends TestCase { - - /** - * Tests adding and removing elements from the listener - */ - public void testAddRemove() { - GroupMessagingListener groupListener = new GroupMessagingListener(); - - MessagingListener listener1 = new MessagingListener(); - MessagingListener listener2 = new MessagingListener(); - - groupListener.addListener(listener1); - groupListener.addListener(listener2); - - groupListener.removeListener(listener1); - groupListener.removeListener(listener2); - } - - /** - * Tests isActiveListener() - */ - public void testIsActiveListener() { - GroupMessagingListener groupListener = new GroupMessagingListener(); - - MessagingListener listener1 = new MessagingListener(); - MessagingListener listener2 = new MessagingListener(); - - assertFalse(groupListener.isActiveListener(listener1)); - assertFalse(groupListener.isActiveListener(listener2)); - - groupListener.addListener(listener1); - assertTrue(groupListener.isActiveListener(listener1)); - assertFalse(groupListener.isActiveListener(listener2)); - - groupListener.addListener(listener2); - assertTrue(groupListener.isActiveListener(listener1)); - assertTrue(groupListener.isActiveListener(listener2)); - - groupListener.removeListener(listener1); - assertFalse(groupListener.isActiveListener(listener1)); - assertTrue(groupListener.isActiveListener(listener2)); - - groupListener.removeListener(listener2); - assertFalse(groupListener.isActiveListener(listener1)); - assertFalse(groupListener.isActiveListener(listener2)); - } - - /** - * TODO: Test that if you add a set of listeners, they will be called - */ -} diff --git a/tests/src/com/android/email/LegacyConversionsTests.java b/tests/src/com/android/email/LegacyConversionsTests.java index 6be7758e6..dbba3554c 100644 --- a/tests/src/com/android/email/LegacyConversionsTests.java +++ b/tests/src/com/android/email/LegacyConversionsTests.java @@ -16,6 +16,12 @@ package com.android.email; +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.test.ProviderTestCase2; + import com.android.email.provider.EmailProvider; import com.android.email.provider.ProviderTestUtils; import com.android.emailcommon.internet.MimeBodyPart; @@ -36,12 +42,7 @@ import com.android.emailcommon.mail.Part; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.utility.ConversionUtilities; - -import android.content.ContentUris; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.test.ProviderTestCase2; +import com.android.emailcommon.utility.ConversionUtilities.BodyFieldData; import java.io.IOException; import java.util.ArrayList; @@ -410,7 +411,7 @@ public class LegacyConversionsTests extends ProviderTestCase2 { /** * Compare attachment that was converted from Part (expected) to Provider Attachment (actual) - * + * * TODO content URI should only be set if we also saved a file * TODO other data encodings */ @@ -431,7 +432,7 @@ public class LegacyConversionsTests extends ProviderTestCase2 { assertEquals(tag, expectedName, actual.mFileName); // content URI should be null - assertNull(tag, actual.mContentUri); + assertNull(tag, actual.getContentUri()); assertTrue(tag, 0 != actual.mMessageKey); diff --git a/tests/src/com/android/email/MessageListContextTests.java b/tests/src/com/android/email/MessageListContextTests.java deleted file mode 100644 index 939762424..000000000 --- a/tests/src/com/android/email/MessageListContextTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email; - -import android.os.Parcel; -import android.test.AndroidTestCase; - -import com.android.emailcommon.service.SearchParams; - -public class MessageListContextTests extends AndroidTestCase { - - public void testParcellingMailboxes() { - long accountId = 123; - long mailboxId = 456; - MessageListContext original = MessageListContext.forMailbox(accountId, mailboxId); - Parcel parcel = Parcel.obtain(); - - original.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - MessageListContext read = MessageListContext.CREATOR.createFromParcel(parcel); - assertEquals(original, read); - parcel.recycle(); - } - - public void testParcellingSearches() { - long accountId = 123; - long mailboxId = 456; - SearchParams params = new SearchParams(mailboxId, "search terms"); - MessageListContext original = MessageListContext.forSearch(accountId, mailboxId, params); - Parcel parcel = Parcel.obtain(); - - original.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - MessageListContext read = MessageListContext.CREATOR.createFromParcel(parcel); - assertEquals(original, read); - parcel.recycle(); - } -} diff --git a/tests/src/com/android/email/MockSharedPreferences.java b/tests/src/com/android/email/MockSharedPreferences.java index 025e06d91..f189fd228 100644 --- a/tests/src/com/android/email/MockSharedPreferences.java +++ b/tests/src/com/android/email/MockSharedPreferences.java @@ -16,7 +16,7 @@ package com.android.email; -import com.google.android.collect.Maps; +import com.google.common.collect.Maps; import android.content.SharedPreferences; diff --git a/tests/src/com/android/email/MockVendorPolicy.java b/tests/src/com/android/email/MockVendorPolicy.java index 86165c959..a1b75c82d 100644 --- a/tests/src/com/android/email/MockVendorPolicy.java +++ b/tests/src/com/android/email/MockVendorPolicy.java @@ -19,6 +19,8 @@ package com.android.email; import android.content.Context; import android.os.Bundle; +import com.android.emailcommon.VendorPolicyLoader; + public class MockVendorPolicy { public static String passedPolicy; public static Bundle passedBundle; diff --git a/tests/src/com/android/email/NotificationControllerTest.java b/tests/src/com/android/email/NotificationControllerTest.java index d674e0f52..f5c42033e 100644 --- a/tests/src/com/android/email/NotificationControllerTest.java +++ b/tests/src/com/android/email/NotificationControllerTest.java @@ -16,17 +16,9 @@ package com.android.email; -import android.app.Notification; import android.content.Context; -import android.media.AudioManager; -import android.net.Uri; import android.test.AndroidTestCase; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.EmailContent.Message; -import com.android.emailcommon.provider.Mailbox; - /** * Test for {@link NotificationController}. * @@ -42,15 +34,10 @@ public class NotificationControllerTest extends AndroidTestCase { /** * Subclass {@link NotificationController} to override un-mockable operations. */ - private class NotificationControllerForTest extends NotificationController { + protected class NotificationControllerForTest extends NotificationController { NotificationControllerForTest(Context context) { super(context, mMockClock); } - - @Override - int getRingerMode() { - return mRingerMode; - } } @Override @@ -60,157 +47,7 @@ public class NotificationControllerTest extends AndroidTestCase { mTarget = new NotificationControllerForTest(mProviderContext); } - public void testSetupSoundAndVibration() { - final Context c = mProviderContext; - final Account a1 = ProviderTestUtils.setupAccount("a1", true, c); - final Notification.Builder nb = new Notification.Builder(c); - final Uri expectedRingtone = Uri.parse(a1.mRingtoneUri); - Notification n; - - // === Ringer mode change === - mRingerMode = AudioManager.RINGER_MODE_NORMAL; - - // VIBRATE, with a ringer tone - a1.mFlags = Account.FLAGS_VIBRATE; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertEquals(expectedRingtone, n.sound); - assertTrue((n.defaults & Notification.DEFAULT_VIBRATE) != 0); - assertTrue((n.flags & Notification.FLAG_SHOW_LIGHTS) != 0); // always set - assertTrue((n.defaults & Notification.DEFAULT_LIGHTS) != 0); // always set - - // No VIBRATE flags, with a ringer tone - a1.mFlags = 0; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertEquals(expectedRingtone, n.sound); - assertFalse((n.defaults & Notification.DEFAULT_VIBRATE) != 0); // no vibe - assertTrue((n.flags & Notification.FLAG_SHOW_LIGHTS) != 0); // always set - assertTrue((n.defaults & Notification.DEFAULT_LIGHTS) != 0); // always set - - // === Ringer mode change === - mRingerMode = AudioManager.RINGER_MODE_VIBRATE; - - // VIBRATE, with a ringer tone - a1.mFlags = Account.FLAGS_VIBRATE; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertEquals(expectedRingtone, n.sound); - assertTrue((n.defaults & Notification.DEFAULT_VIBRATE) != 0); - assertTrue((n.flags & Notification.FLAG_SHOW_LIGHTS) != 0); // always set - assertTrue((n.defaults & Notification.DEFAULT_LIGHTS) != 0); // always set - - // No VIBRATE flags, with a ringer tone - a1.mFlags = 0; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertEquals(expectedRingtone, n.sound); - assertFalse((n.defaults & Notification.DEFAULT_VIBRATE) != 0); // no vibe - assertTrue((n.flags & Notification.FLAG_SHOW_LIGHTS) != 0); // always set - assertTrue((n.defaults & Notification.DEFAULT_LIGHTS) != 0); // always set - - // === Ringer mode change === - mRingerMode = AudioManager.RINGER_MODE_SILENT; - - // VIBRATE, with a ringer tone - a1.mFlags = Account.FLAGS_VIBRATE; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertEquals(expectedRingtone, n.sound); - assertTrue((n.defaults & Notification.DEFAULT_VIBRATE) != 0); - assertTrue((n.flags & Notification.FLAG_SHOW_LIGHTS) != 0); // always set - assertTrue((n.defaults & Notification.DEFAULT_LIGHTS) != 0); // always set - - // No VIBRATE flags, with a ringer tone - a1.mFlags = 0; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertEquals(expectedRingtone, n.sound); - assertFalse((n.defaults & Notification.DEFAULT_VIBRATE) != 0); // no vibe - assertTrue((n.flags & Notification.FLAG_SHOW_LIGHTS) != 0); // always set - assertTrue((n.defaults & Notification.DEFAULT_LIGHTS) != 0); // always set - - // No ringer tone - a1.mRingtoneUri = null; - - nb.setDefaults(0); - nb.setSound(null); - mTarget.setupSoundAndVibration(nb, a1); - n = nb.getNotification(); - - assertNull(n.sound); - } - - public void testCreateNewMessageNotification() { - final Context c = mProviderContext; - Notification n; - - // Case 1: 1 account, 1 unseen message - Account a1 = ProviderTestUtils.setupAccount("a1", true, c); - Mailbox b1 = ProviderTestUtils.setupMailbox("inbox", a1.mId, true, c, Mailbox.TYPE_INBOX); - Message m1 = ProviderTestUtils.setupMessage("message", a1.mId, b1.mId, true, true, c); - - n = mTarget.createNewMessageNotification(a1.mId, b1.mId, m1.mId, 1, 1); - - assertEquals(R.drawable.stat_notify_email_generic, n.icon); - assertEquals(mMockClock.mTime, n.when); - assertNotNull(n.largeIcon); - assertEquals(0, n.number); - - // TODO Check content -- how? - - // Case 2: 1 account, 2 unseen message - n = mTarget.createNewMessageNotification(a1.mId, b1.mId, m1.mId, 2, 2); - - assertEquals(R.drawable.stat_notify_email_generic, n.icon); - assertEquals(mMockClock.mTime, n.when); - assertNotNull(n.largeIcon); - assertEquals(2, n.number); - - // TODO Check content -- how? - - // TODO Add 2 account test, if we find a way to check content - } - - public void testCreateNewMessageNotificationWithEmptyFrom() { - final Context c = mProviderContext; - Notification n; - - // Message with no from fields. - Account a1 = ProviderTestUtils.setupAccount("a1", true, c); - Mailbox b1 = ProviderTestUtils.setupMailbox("inbox", a1.mId, true, c, Mailbox.TYPE_INBOX); - Message m1 = ProviderTestUtils.setupMessage("message", a1.mId, b1.mId, true, false, c); - m1.mFrom = null; - m1.save(c); - - // This shouldn't crash. - n = mTarget.createNewMessageNotification(a1.mId, b1.mId, m1.mId, 1, 1); - - // Minimum test for the result - assertEquals(R.drawable.stat_notify_email_generic, n.icon); - } + // the ringtone and vibration flags are depracated and the method that we use + // to test notification has been removed in + // https://googleplex-android-review.googlesource.com/#/c/271237/ } diff --git a/tests/src/com/android/email/RefreshManagerTest.java b/tests/src/com/android/email/RefreshManagerTest.java deleted file mode 100644 index 3c118591f..000000000 --- a/tests/src/com/android/email/RefreshManagerTest.java +++ /dev/null @@ -1,508 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email; - -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.Logging; -import com.android.emailcommon.mail.MessagingException; -import com.android.emailcommon.provider.Account; - -import android.content.Context; -import android.test.InstrumentationTestCase; -import android.test.suitebuilder.annotation.LargeTest; - -import junit.framework.Assert; - -@LargeTest -public class RefreshManagerTest extends InstrumentationTestCase { - private static final int WAIT_UNTIL_TIMEOUT_SECONDS = 15; - private MockClock mClock; - private MockController mController; - private RefreshManager mTarget; - private RefreshListener mListener; - - private Context mContext; - - // Isolated Context for providers. - private Context mProviderContext; - - private static final MessagingException EXCEPTION = new MessagingException("test"); - - // Looks silly, but it'll make it more readable. - private static final long ACCOUNT_1 = 1; - private static final long ACCOUNT_2 = 2; - private static final long MAILBOX_1 = 3; - private static final long MAILBOX_2 = 4; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - mClock = new MockClock(); - mContext = getInstrumentation().getTargetContext(); - mController = new MockController(mContext); - mListener = new RefreshListener(); - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext(mContext); - mTarget = new RefreshManager(mProviderContext, mController, mClock, null); - mTarget.registerListener(mListener); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - mController.cleanupForTest(); - } - - public void testRegisterUnregisterListener() { - // mListener is already registered - assertEquals(1, mTarget.getListenersForTest().size()); - - mTarget.unregisterListener(mListener); - assertEquals(0, mTarget.getListenersForTest().size()); - } - - public void testRefreshStatus() { - RefreshManager.Status s = new RefreshManager.Status(); - assertFalse(s.isRefreshing()); - assertTrue(s.canRefresh()); - assertEquals(0, s.getLastRefreshTime()); - - // Request refresh - s.onRefreshRequested(); - assertTrue(s.isRefreshing()); - assertFalse(s.canRefresh()); - assertEquals(0, s.getLastRefreshTime()); - - // Refresh start - s.onCallback(null, 0, mClock); - assertTrue(s.isRefreshing()); - assertFalse(s.canRefresh()); - assertEquals(0, s.getLastRefreshTime()); - - // Refresh 50% done -- nothing changes - s.onCallback(null, 50, mClock); - assertTrue(s.isRefreshing()); - assertFalse(s.canRefresh()); - assertEquals(0, s.getLastRefreshTime()); - - // Refresh finish - s.onCallback(null, 100, mClock); - assertFalse(s.isRefreshing()); - assertTrue(s.canRefresh()); - assertEquals(mClock.mTime, s.getLastRefreshTime()); - - // Refresh start without request - s.onCallback(null, 0, mClock); - assertTrue(s.isRefreshing()); - assertFalse(s.canRefresh()); - assertEquals(mClock.mTime, s.getLastRefreshTime()); - - mClock.advance(); - - // Refresh finish with error. - s.onCallback(EXCEPTION, 0, mClock); - assertFalse(s.isRefreshing()); - assertTrue(s.canRefresh()); - assertEquals(mClock.mTime, s.getLastRefreshTime()); - } - - public void testRefreshMailboxList() { - // request refresh for account 1 - assertTrue(mTarget.refreshMailboxList(ACCOUNT_1)); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mController.mCalledUpdateMailboxList); - assertEquals(ACCOUNT_1, mController.mAccountId); - assertEquals(-1, mController.mMailboxId); - mController.reset(); - assertTrue(mTarget.isMailboxListRefreshing(ACCOUNT_1)); - assertTrue(mTarget.isRefreshingAnyMailboxListForTest()); - - // Request again -- shouldn't be accepted. - assertFalse(mTarget.refreshMailboxList(ACCOUNT_1)); - - assertFalse(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - mListener.reset(); - assertFalse(mController.mCalledUpdateMailboxList); - mController.reset(); - - // request refresh for account 2 - assertTrue(mTarget.refreshMailboxList(ACCOUNT_2)); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mController.mCalledUpdateMailboxList); - assertEquals(ACCOUNT_2, mController.mAccountId); - assertEquals(-1, mController.mMailboxId); - mController.reset(); - assertTrue(mTarget.isMailboxListRefreshing(ACCOUNT_2)); - assertTrue(mTarget.isRefreshingAnyMailboxListForTest()); - - // Refreshing for account 1... - mController.mListener.updateMailboxListCallback(null, ACCOUNT_1, 0); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mTarget.isMailboxListRefreshing(ACCOUNT_1)); - assertEquals(0, mTarget.getMailboxListStatusForTest(ACCOUNT_1).getLastRefreshTime()); - - // Done. - LogUtils.w(Logging.LOG_TAG, "" + mController.mListener.getClass()); - mController.mListener.updateMailboxListCallback(null, ACCOUNT_1, 100); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertFalse(mTarget.isMailboxListRefreshing(ACCOUNT_1)); - assertEquals(mClock.mTime, mTarget.getMailboxListStatusForTest(ACCOUNT_1) - .getLastRefreshTime()); - - // Check "any" method. - assertTrue(mTarget.isRefreshingAnyMailboxListForTest()); // still refreshing account 2 - - // Refreshing for account 2... - mClock.advance(); - - mController.mListener.updateMailboxListCallback(null, ACCOUNT_2, 0); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mTarget.isMailboxListRefreshing(ACCOUNT_2)); - assertEquals(0, mTarget.getMailboxListStatusForTest(ACCOUNT_2).getLastRefreshTime()); - - // Done with exception. - mController.mListener.updateMailboxListCallback(EXCEPTION, ACCOUNT_2, 0); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertTrue(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - assertEquals(MessagingExceptionStrings.getErrorString(mContext, EXCEPTION), - mListener.mMessage); - mListener.reset(); - assertFalse(mTarget.isMailboxListRefreshing(ACCOUNT_2)); - assertEquals(mClock.mTime, mTarget.getMailboxListStatusForTest(ACCOUNT_2) - .getLastRefreshTime()); - - // Check "any" method. - assertFalse(mTarget.isRefreshingAnyMailboxListForTest()); - } - - public void testRefreshMessageList() { - // request refresh mailbox 1 - assertTrue(mTarget.refreshMessageList(ACCOUNT_1, MAILBOX_1, false)); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(MAILBOX_1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mController.mCalledUpdateMailbox); - assertEquals(ACCOUNT_1, mController.mAccountId); - assertEquals(MAILBOX_1, mController.mMailboxId); - mController.reset(); - assertTrue(mTarget.isMessageListRefreshing(MAILBOX_1)); - assertTrue(mTarget.isRefreshingAnyMessageListForTest()); - - // Request again -- shouldn't be accepted. - assertFalse(mTarget.refreshMessageList(ACCOUNT_1, MAILBOX_1, false)); - - assertFalse(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - mListener.reset(); - assertFalse(mController.mCalledUpdateMailbox); - mController.reset(); - - // request refresh mailbox 2 - assertTrue(mTarget.refreshMessageList(ACCOUNT_2, MAILBOX_2, false)); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(MAILBOX_2, mListener.mMailboxId); - mListener.reset(); - assertTrue(mController.mCalledUpdateMailbox); - assertEquals(ACCOUNT_2, mController.mAccountId); - assertEquals(MAILBOX_2, mController.mMailboxId); - mController.reset(); - assertTrue(mTarget.isMessageListRefreshing(MAILBOX_2)); - assertTrue(mTarget.isRefreshingAnyMessageListForTest()); - - // Refreshing mailbox 1... - mController.mListener.updateMailboxCallback(null, ACCOUNT_1, MAILBOX_1, 0, 0, null); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(MAILBOX_1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mTarget.isMessageListRefreshing(MAILBOX_1)); - assertEquals(0, mTarget.getMessageListStatusForTest(MAILBOX_1).getLastRefreshTime()); - - // Done. - LogUtils.w(Logging.LOG_TAG, "" + mController.mListener.getClass()); - mController.mListener.updateMailboxCallback(null, ACCOUNT_1, MAILBOX_1, 100, 0, null); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(MAILBOX_1, mListener.mMailboxId); - mListener.reset(); - assertFalse(mTarget.isMessageListRefreshing(MAILBOX_1)); - assertEquals(mClock.mTime, mTarget.getMessageListStatusForTest(MAILBOX_1) - .getLastRefreshTime()); - - // Check "any" method. - assertTrue(mTarget.isRefreshingAnyMessageListForTest()); // still refreshing mailbox 2 - - // Refreshing mailbox 2... - mClock.advance(); - - mController.mListener.updateMailboxCallback(null, ACCOUNT_2, MAILBOX_2, 0, 0, null); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(MAILBOX_2, mListener.mMailboxId); - mListener.reset(); - assertTrue(mTarget.isMessageListRefreshing(MAILBOX_2)); - assertEquals(0, mTarget.getMessageListStatusForTest(MAILBOX_2).getLastRefreshTime()); - - // Done with exception. - mController.mListener.updateMailboxCallback(EXCEPTION, ACCOUNT_2, MAILBOX_2, 0, 0, null); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertTrue(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(MAILBOX_2, mListener.mMailboxId); - assertEquals(MessagingExceptionStrings.getErrorString(mContext, EXCEPTION), - mListener.mMessage); - mListener.reset(); - assertFalse(mTarget.isMessageListRefreshing(MAILBOX_2)); - assertEquals(mClock.mTime, mTarget.getMessageListStatusForTest(MAILBOX_2) - .getLastRefreshTime()); - - // Check "any" method. - assertFalse(mTarget.isRefreshingAnyMessageListForTest()); - } - - public void testSendPendingMessages() { - // request sending for account 1 - assertTrue(mTarget.sendPendingMessages(ACCOUNT_1)); - - assertTrue(mListener.mCalledOnRefreshStatusChanged); - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_1, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mController.mCalledSendPendingMessages); - assertEquals(ACCOUNT_1, mController.mAccountId); - assertEquals(-1, mController.mMailboxId); - mController.reset(); - - // request sending for account 2 - assertTrue(mTarget.sendPendingMessages(ACCOUNT_2)); - - assertFalse(mListener.mCalledOnConnectionError); - assertEquals(ACCOUNT_2, mListener.mAccountId); - assertEquals(-1, mListener.mMailboxId); - mListener.reset(); - assertTrue(mController.mCalledSendPendingMessages); - assertEquals(ACCOUNT_2, mController.mAccountId); - assertEquals(-1, mController.mMailboxId); - mController.reset(); - - // Sending start for account 1... - // batch send start. (message id == -1, progress == 0) - mController.mListener.sendMailCallback(null, ACCOUNT_1, -1, 0); - - assertFalse(mListener.mCalledOnConnectionError); - mListener.reset(); - - // Per message callback - mController.mListener.sendMailCallback(null, ACCOUNT_1, 100, 0); - mController.mListener.sendMailCallback(null, ACCOUNT_1, 101, 0); - - assertFalse(mListener.mCalledOnConnectionError); - mListener.reset(); - - // Exception -- first error will be reported. - mController.mListener.sendMailCallback(EXCEPTION, ACCOUNT_1, 102, 0); - - assertTrue(mListener.mCalledOnConnectionError); - assertEquals(MessagingExceptionStrings.getErrorString(mContext, EXCEPTION), - mListener.mMessage); - mListener.reset(); - - // Exception again -- no more error callbacks - mController.mListener.sendMailCallback(null, ACCOUNT_1, 103, 0); - mController.mListener.sendMailCallback(EXCEPTION, ACCOUNT_1, 104, 0); - - assertFalse(mListener.mCalledOnConnectionError); - mListener.reset(); - - // Done. - LogUtils.w(Logging.LOG_TAG, "" + mController.mListener.getClass()); - mController.mListener.sendMailCallback(null, ACCOUNT_1, -1, 100); - - assertFalse(mListener.mCalledOnConnectionError); - mListener.reset(); - } - - public void testSendPendingMessagesForAllAccounts() throws Throwable { - Account acct1 = ProviderTestUtils.setupAccount("acct1", true, mProviderContext); - Account acct2 = ProviderTestUtils.setupAccount("acct2", true, mProviderContext); - - // AsyncTask needs to be created on the UI thread. - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mTarget.sendPendingMessagesForAllAccounts(); - } - }); - - // sendPendingMessagesForAllAccounts uses Utility.ForEachAccount, which has it's own test, - // so we don't really have to check everything. - // Here, we just check if sendPendingMessages() has been called at least for once, - // which is a enough check. - TestUtils.waitUntil(new TestUtils.Condition() { - @Override - public boolean isMet() { - // The write to this is done on the UI thread, but we're checking it here - // on the test thread, so mCalledSendPendingMessages needs to be volatile. - return mController.mCalledSendPendingMessages; - } - }, WAIT_UNTIL_TIMEOUT_SECONDS); - } - - public void testLoadMoreMessages() { - final long ACCOUNT_ID = 123; - final long MAILBOX_ID = 456; - - mTarget.loadMoreMessages(ACCOUNT_ID, MAILBOX_ID); - - assertTrue(mController.mCalledLoadMoreMessages); - assertEquals(mController.mMailboxId, MAILBOX_ID); - assertFalse(mController.mCalledUpdateMailbox); - } - - // volatile is necessary for testSendPendingMessagesForAllAccounts(). - // (Not all of them are actually necessary, but added for consistency.) - private static class MockController extends Controller { - public volatile long mAccountId = -1; - public volatile long mMailboxId = -1; - public volatile boolean mCalledSendPendingMessages; - public volatile boolean mCalledUpdateMailbox; - public volatile boolean mCalledUpdateMailboxList; - public volatile boolean mCalledLoadMoreMessages; - public volatile Result mListener; - - protected MockController(Context context) { - super(context); - } - - public void reset() { - mAccountId = -1; - mMailboxId = -1; - mCalledSendPendingMessages = false; - mCalledUpdateMailbox = false; - mCalledUpdateMailboxList = false; - } - - @Override - public void sendPendingMessages(long accountId) { - mCalledSendPendingMessages = true; - mAccountId = accountId; - } - - @Override - public void updateMailbox(long accountId, long mailboxId, boolean userRequest) { - mCalledUpdateMailbox = true; - mAccountId = accountId; - mMailboxId = mailboxId; - } - - @Override - public void updateMailboxList(long accountId) { - mCalledUpdateMailboxList = true; - mAccountId = accountId; - } - - @Override - public void loadMoreMessages(long mailboxId) { - mCalledLoadMoreMessages = true; - mAccountId = -1; - mMailboxId = mailboxId; - } - - @Override - public void addResultCallback(Result listener) { - Assert.assertTrue(mListener == null); - mListener = listener; - - // Let it call listener.setRegistered(). Otherwise callbacks won't fire. - super.addResultCallback(listener); - } - } - - private static class RefreshListener implements RefreshManager.Listener { - public long mAccountId = -1; - public long mMailboxId = -1; - public String mMessage; - public boolean mCalledOnConnectionError; - public boolean mCalledOnRefreshStatusChanged; - - public void reset() { - mAccountId = -1; - mMailboxId = -1; - mMessage = null; - mCalledOnConnectionError = false; - mCalledOnRefreshStatusChanged = false; - } - - @Override - public void onRefreshStatusChanged(long accountId, long mailboxId) { - mAccountId = accountId; - mMailboxId = mailboxId; - mCalledOnRefreshStatusChanged = true; - } - - @Override - public void onMessagingError(long accountId, long mailboxId, String message) { - mAccountId = accountId; - mMailboxId = mailboxId; - mMessage = message; - mCalledOnConnectionError = true; - } - } -} diff --git a/tests/src/com/android/email/SecurityPolicyTests.java b/tests/src/com/android/email/SecurityPolicyTests.java index ed264859a..cc8e87620 100644 --- a/tests/src/com/android/email/SecurityPolicyTests.java +++ b/tests/src/com/android/email/SecurityPolicyTests.java @@ -58,7 +58,6 @@ public class SecurityPolicyTests extends ProviderTestCase2 { mMockContext = new MockContext2(getMockContext(), mContext); // Invalidate all caches, since we reset the database for each test ContentCache.invalidateAllCaches(); - Controller.getInstance(mMockContext).markForTest(true); } /** @@ -66,7 +65,6 @@ public class SecurityPolicyTests extends ProviderTestCase2 { */ @Override protected void tearDown() throws Exception { - Controller.getInstance(mMockContext).markForTest(false); super.tearDown(); } @@ -142,7 +140,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Account a3 = ProviderTestUtils.setupAccount("sec-3", true, mMockContext); Policy p3ain = setupPolicy(10, Policy.PASSWORD_MODE_SIMPLE, 0, 0, false, 0, 0, 0, false, false); - Policy.setAccountPolicy(mMockContext, a3, p3ain, null); + SecurityPolicy.setAccountPolicy(mMockContext, a3, p3ain, null); Policy p3aout = mSecurityPolicy.computeAggregatePolicy(); assertNotNull(p3aout); assertEquals(p3ain, p3aout); @@ -150,7 +148,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { // Repeat that test with fully-populated policies Policy p3bin = setupPolicy(10, Policy.PASSWORD_MODE_SIMPLE, 15, 16, false, 6, 2, 3, false, false); - Policy.setAccountPolicy(mMockContext, a3, p3bin, null); + SecurityPolicy.setAccountPolicy(mMockContext, a3, p3bin, null); Policy p3bout = mSecurityPolicy.computeAggregatePolicy(); assertNotNull(p3bout); assertEquals(p3bin, p3bout); @@ -166,7 +164,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Policy p4in = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 0, 5, 7, false, true); Account a4 = ProviderTestUtils.setupAccount("sec-4", true, mMockContext); - Policy.setAccountPolicy(mMockContext, a4, p4in, null); + SecurityPolicy.setAccountPolicy(mMockContext, a4, p4in, null); Policy p4out = mSecurityPolicy.computeAggregatePolicy(); assertNotNull(p4out); assertEquals(20, p4out.mPasswordMinLength); @@ -192,7 +190,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Policy p5in = setupPolicy(4, Policy.PASSWORD_MODE_SIMPLE, 5, 6, true, 1, 0, 0, true, false); Account a5 = ProviderTestUtils.setupAccount("sec-5", true, mMockContext); - Policy.setAccountPolicy(mMockContext, a5, p5in, null); + SecurityPolicy.setAccountPolicy(mMockContext, a5, p5in, null); Policy p5out = mSecurityPolicy.computeAggregatePolicy(); assertNotNull(p5out); assertEquals(20, p5out.mPasswordMinLength); @@ -236,17 +234,17 @@ public class SecurityPolicyTests extends ProviderTestCase2 { long accountId = account.mId; Policy initial = setupPolicy(10, Policy.PASSWORD_MODE_SIMPLE, 0, 0, false, 0, 0, 0, false, false); - Policy.setAccountPolicy(mMockContext, accountId, initial, null); + SecurityPolicy.setAccountPolicy(mMockContext, account, initial, null); long oldKey = assertAccountPolicyConsistent(account.mId, 0); Policy updated = setupPolicy(10, Policy.PASSWORD_MODE_SIMPLE, 0, 0, false, 0, 0, 0, false, false); - Policy.setAccountPolicy(mMockContext, accountId, updated, null); + SecurityPolicy.setAccountPolicy(mMockContext, account, updated, null); oldKey = assertAccountPolicyConsistent(account.mId, oldKey); // Remove the policy - Policy.clearAccountPolicy( + SecurityPolicy.clearAccountPolicy( mMockContext, Account.restoreAccountWithId(mMockContext, accountId)); assertNull("old policy not cleaned up", Policy.restorePolicyWithId(mMockContext, oldKey)); @@ -275,28 +273,21 @@ public class SecurityPolicyTests extends ProviderTestCase2 { * Test the API to set/clear policy hold flags in an account */ public void testSetClearHoldFlag() { - Account a1 = ProviderTestUtils.setupAccount("holdflag-1", false, mMockContext); - a1.mFlags = Account.FLAGS_NOTIFY_NEW_MAIL; - a1.save(mMockContext); Account a2 = ProviderTestUtils.setupAccount("holdflag-2", false, mMockContext); - a2.mFlags = Account.FLAGS_VIBRATE_ALWAYS | Account.FLAGS_SECURITY_HOLD; + a2.mFlags = Account.FLAGS_SYNC_DISABLED | Account.FLAGS_SECURITY_HOLD; a2.save(mMockContext); - // confirm clear until set - Account a1a = Account.restoreAccountWithId(mMockContext, a1.mId); - assertEquals(Account.FLAGS_NOTIFY_NEW_MAIL, a1a.mFlags); - SecurityPolicy.setAccountHoldFlag(mMockContext, a1, true); - assertEquals(Account.FLAGS_NOTIFY_NEW_MAIL | Account.FLAGS_SECURITY_HOLD, a1.mFlags); - Account a1b = Account.restoreAccountWithId(mMockContext, a1.mId); - assertEquals(Account.FLAGS_NOTIFY_NEW_MAIL | Account.FLAGS_SECURITY_HOLD, a1b.mFlags); - // confirm set until cleared Account a2a = Account.restoreAccountWithId(mMockContext, a2.mId); - assertEquals(Account.FLAGS_VIBRATE_ALWAYS | Account.FLAGS_SECURITY_HOLD, a2a.mFlags); + assertEquals(Account.FLAGS_SYNC_DISABLED | Account.FLAGS_SECURITY_HOLD, a2a.mFlags); + + // set account hold flag off SecurityPolicy.setAccountHoldFlag(mMockContext, a2, false); - assertEquals(Account.FLAGS_VIBRATE_ALWAYS, a2.mFlags); + assertEquals(Account.FLAGS_SYNC_DISABLED, a2.mFlags); + + // confirm account hold flag set Account a2b = Account.restoreAccountWithId(mMockContext, a2.mId); - assertEquals(Account.FLAGS_VIBRATE_ALWAYS, a2b.mFlags); + assertEquals(Account.FLAGS_SYNC_DISABLED, a2b.mFlags); } /** @@ -306,15 +297,15 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Account a1 = ProviderTestUtils.setupAccount("disable-1", true, mMockContext); Policy p1 = setupPolicy(10, Policy.PASSWORD_MODE_SIMPLE, 0, 0, false, 0, 0, 0, false, false); - Policy.setAccountPolicy(mMockContext, a1, p1, "security-sync-key-1"); + SecurityPolicy.setAccountPolicy(mMockContext, a1, p1, "security-sync-key-1"); Account a2 = ProviderTestUtils.setupAccount("disable-2", true, mMockContext); Policy p2 = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 0, 0, 0, false, false); - Policy.setAccountPolicy(mMockContext, a2, p2, "security-sync-key-2"); + SecurityPolicy.setAccountPolicy(mMockContext, a2, p2, "security-sync-key-2"); Account a3 = ProviderTestUtils.setupAccount("disable-3", true, mMockContext); - Policy.clearAccountPolicy(mMockContext, a3); + SecurityPolicy.clearAccountPolicy(mMockContext, a3); mSecurityPolicy = SecurityPolicy.getInstance(mMockContext); @@ -359,7 +350,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { ProviderTestUtils.setupAccount("expiring-2", true, mMockContext); Policy p2 = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 30, 0, 0, false, true); - Policy.setAccountPolicy(mMockContext, a2, p2, null); + SecurityPolicy.setAccountPolicy(mMockContext, a2, p2, null); // The expiring account should be returned nextExpiringAccountId = SecurityPolicy.findShortestExpiration(mMockContext); @@ -369,7 +360,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Account a3 = ProviderTestUtils.setupAccount("expiring-3", true, mMockContext); Policy p3 = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 60, 0, 0, false, true); - Policy.setAccountPolicy(mMockContext, a3, p3, null); + SecurityPolicy.setAccountPolicy(mMockContext, a3, p3, null); // The original expiring account (a2) should be returned nextExpiringAccountId = SecurityPolicy.findShortestExpiration(mMockContext); @@ -379,37 +370,25 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Account a4 = ProviderTestUtils.setupAccount("expiring-4", true, mMockContext); Policy p4 = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 15, 0, 0, false, true); - Policy.setAccountPolicy(mMockContext, a4, p4, null); + SecurityPolicy.setAccountPolicy(mMockContext, a4, p4, null); // The new expiring account (a4) should be returned nextExpiringAccountId = SecurityPolicy.findShortestExpiration(mMockContext); assertEquals(a4.mId, nextExpiringAccountId); } - /** - * Lightweight subclass of the Controller class allows injection of mock context - */ - public static class TestController extends Controller { - protected TestController(Context providerContext, Context systemContext) { - super(systemContext); - setProviderContext(providerContext); - markForTest(true); - } - } - /** * Test the scanner that wipes expiring accounts */ public void testWipeExpiringAccounts() { mSecurityPolicy = SecurityPolicy.getInstance(mMockContext); - TestController testController = new TestController(mMockContext, getContext()); // Two accounts - a1 is normal, a2 has security (but no expiration) Account a1 = ProviderTestUtils.setupAccount("expired-1", true, mMockContext); Account a2 = ProviderTestUtils.setupAccount("expired-2", true, mMockContext); Policy p2 = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 0, 0, 0, false, true); - Policy.setAccountPolicy(mMockContext, a2, p2, null); + SecurityPolicy.setAccountPolicy(mMockContext, a2, p2, null); // Add a mailbox & messages to each account long account1Id = a1.mId; @@ -424,7 +403,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { ProviderTestUtils.setupMessage("message4", account2Id, box2Id, false, true, mMockContext); // Run the expiration code - should do nothing - boolean wiped = SecurityPolicy.wipeExpiredAccounts(mMockContext, testController); + boolean wiped = SecurityPolicy.wipeExpiredAccounts(mMockContext); assertFalse(wiped); // check mailboxes & messages not wiped assertEquals(2, EmailContent.count(mMockContext, Account.CONTENT_URI)); @@ -435,7 +414,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { Account a3 = ProviderTestUtils.setupAccount("expired-3", true, mMockContext); Policy p3 = setupPolicy(20, Policy.PASSWORD_MODE_STRONG, 25, 26, false, 30, 0, 0, false, true); - Policy.setAccountPolicy(mMockContext, a3, p3, null); + SecurityPolicy.setAccountPolicy(mMockContext, a3, p3, null); // Add mailbox & messages to 3rd account long account3Id = a3.mId; @@ -450,7 +429,7 @@ public class SecurityPolicyTests extends ProviderTestCase2 { assertEquals(6, EmailContent.count(mMockContext, Message.CONTENT_URI)); // Run the expiration code - wipe acct #3 - wiped = SecurityPolicy.wipeExpiredAccounts(mMockContext, testController); + wiped = SecurityPolicy.wipeExpiredAccounts(mMockContext); assertTrue(wiped); // check new counts - account survives but data is wiped assertEquals(3, EmailContent.count(mMockContext, Account.CONTENT_URI)); @@ -466,38 +445,6 @@ public class SecurityPolicyTests extends ProviderTestCase2 { assertEquals(Account.FLAGS_SECURITY_HOLD, account.mFlags & Account.FLAGS_SECURITY_HOLD); } - /** - * Test the code that clears unsupported policies - * TODO inject a mock DPM so we can directly control & test all cases, no matter what device - */ - public void testClearUnsupportedPolicies() { - Policy p1 = - setupPolicy(1, Policy.PASSWORD_MODE_STRONG, 3, 4, true, 7, 8, 9, false, false); - Policy p2 = - setupPolicy(1, Policy.PASSWORD_MODE_STRONG, 3, 4, true, 7, 8, 9, true, false); - - mSecurityPolicy = SecurityPolicy.getInstance(mMockContext); - DevicePolicyManager dpm = mSecurityPolicy.getDPM(); - boolean hasEncryption = - dpm.getStorageEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; - - Policy p1Result = mSecurityPolicy.clearUnsupportedPolicies(p1); - Policy p2Result = mSecurityPolicy.clearUnsupportedPolicies(p2); - - // No changes expected when encryptionRequested was false - assertEquals(p1, p1Result); - if (hasEncryption) { - // No changes expected - assertEquals(p2, p2Result); - } else { - // If encryption is unsupported, encryption policy bits are cleared - Policy policyExpect = - setupPolicy(1, Policy.PASSWORD_MODE_STRONG, 3, 4, true, 7, 8, 9, false, - false); - assertEquals(policyExpect, p2Result); - } - } - /** * Test the code that converts from exchange-style quality to DPM/Lockscreen style quality. */ diff --git a/tests/src/com/android/email/SingleRunningTaskTest.java b/tests/src/com/android/email/SingleRunningTaskTest.java index b41299f24..63edfa8bf 100644 --- a/tests/src/com/android/email/SingleRunningTaskTest.java +++ b/tests/src/com/android/email/SingleRunningTaskTest.java @@ -25,7 +25,7 @@ import junit.framework.TestCase; public class SingleRunningTaskTest extends TestCase { - private static class NormalTask extends SingleRunningTask { + /*private static class NormalTask extends SingleRunningTask { // # of times the task has actually run. public final AtomicInteger mCalledCount = new AtomicInteger(0); @@ -71,12 +71,12 @@ public class SingleRunningTaskTest extends TestCase { protected void runInternal(Void param) { throw new RuntimeException("Intentional exception"); } - } + }*/ /** * Run 3 tasks sequentially. */ - public void testSequential() { + /*public void testSequential() { final NormalTask e = new NormalTask(); e.run(null); @@ -84,12 +84,12 @@ public class SingleRunningTaskTest extends TestCase { e.run(null); assertEquals(3, e.mCalledCount.get()); - } + }*/ /** * Run 2 tasks in parallel, and then another call. */ - public void testParallel() { + /*public void testParallel() { final NormalTask e = new NormalTask(); // Block the first task @@ -133,12 +133,12 @@ public class SingleRunningTaskTest extends TestCase { e.run(null); assertEquals(2, e.mCalledCount.get()); - } + }*/ /** * If a task throws, isRunning should become false. */ - public void testException() { + /*public void testException() { final FailTask e = new FailTask(); try { @@ -147,5 +147,5 @@ public class SingleRunningTaskTest extends TestCase { } catch (RuntimeException expected) { } assertFalse(e.isRunningForTest()); - } + }*/ } diff --git a/tests/src/com/android/email/TestUtils.java b/tests/src/com/android/email/TestUtils.java index 87355783c..9a88c372c 100644 --- a/tests/src/com/android/email/TestUtils.java +++ b/tests/src/com/android/email/TestUtils.java @@ -16,8 +16,6 @@ package com.android.email; -import com.android.emailcommon.Logging; - import android.app.KeyguardManager; import android.content.Context; import android.os.PowerManager; @@ -26,6 +24,9 @@ import android.test.suitebuilder.annotation.LargeTest; import android.view.View; import android.view.ViewParent; +import com.android.emailcommon.Logging; +import com.android.mail.utils.LogUtils; + import junit.framework.AssertionFailedError; import junit.framework.TestCase; diff --git a/tests/src/com/android/email/ThrottleTest.java b/tests/src/com/android/email/ThrottleTest.java index f19a868f1..d31903029 100644 --- a/tests/src/com/android/email/ThrottleTest.java +++ b/tests/src/com/android/email/ThrottleTest.java @@ -21,6 +21,7 @@ import android.os.Message; import android.test.AndroidTestCase; import com.android.mail.utils.Clock; +import com.android.mail.utils.Throttle; import java.util.Timer; import java.util.TimerTask; diff --git a/tests/src/com/android/email/VendorPolicyLoaderTest.java b/tests/src/com/android/email/VendorPolicyLoaderTest.java index e08493f5d..c4aab5238 100644 --- a/tests/src/com/android/email/VendorPolicyLoaderTest.java +++ b/tests/src/com/android/email/VendorPolicyLoaderTest.java @@ -16,12 +16,13 @@ package com.android.email; -import com.android.email.activity.setup.AccountSettingsUtils.Provider; - import android.content.Context; import android.os.Bundle; import android.test.AndroidTestCase; +import com.android.emailcommon.VendorPolicyLoader; +import com.android.emailcommon.VendorPolicyLoader.Provider; + public class VendorPolicyLoaderTest extends AndroidTestCase { private String mTestApkPackageName; diff --git a/tests/src/com/android/email/activity/AccountSelectorAdapterTest.java b/tests/src/com/android/email/activity/AccountSelectorAdapterTest.java deleted file mode 100644 index d65ee8a2a..000000000 --- a/tests/src/com/android/email/activity/AccountSelectorAdapterTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.email.DBTestHelper; -import com.android.email.FolderProperties; -import com.android.email.R; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.Mailbox; - -import android.content.Context; -import android.content.Loader; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.test.LoaderTestCase; - -/** - * Tests for {@link AccountSelectorAdapter.AccountsLoader}. - * - * TODO add more tests. - */ -public class AccountSelectorAdapterTest extends LoaderTestCase { - private Context mProviderContext; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext(mContext); - } - - /** - * - Confirm that AccountsLoader adds the combined view row, iif there is more than 1 account. - * - Confirm that AccountsLoader doesn't add recent mailboxes. - * - * two-pane version. - * - * TODO add one-pane version - */ - public void testCombinedViewRow_twoPane() { - final Account a1 = ProviderTestUtils.setupAccount("a1", true, mProviderContext); - { - // Only 1 account -- no combined view row. - Loader l = new AccountSelectorAdapter.AccountsLoader(mProviderContext, 0L, - 0L, true); - AccountSelectorAdapter.CursorWithExtras result = - (AccountSelectorAdapter.CursorWithExtras) getLoaderResultSynchronously(l); - assertEquals(1, result.getAccountCount()); - assertEquals(2, result.getCount()); // +1 as the cursor has the header row - assertEquals(0, result.getRecentMailboxCount()); // No recent on two-pane. - } - - final Account a2 = ProviderTestUtils.setupAccount("a2", true, mProviderContext); - { - // 2 accounts -- with combined view row, so returns 3 account rows. - Loader l = new AccountSelectorAdapter.AccountsLoader(mProviderContext, 0L, - 0L, true); - AccountSelectorAdapter.CursorWithExtras result = - (AccountSelectorAdapter.CursorWithExtras) getLoaderResultSynchronously(l); - assertEquals(3, result.getAccountCount()); - assertEquals(4, result.getCount()); // +1 as the cursor has the header row - assertEquals(0, result.getRecentMailboxCount()); // No recent on two-pane. - } - } - - private static AccountSelectorAdapter.CursorWithExtras createCursorWithExtras() { - final MatrixCursor m = new MatrixCursorWithCachedColumns(new String[] {"column"}); - return new AccountSelectorAdapter.CursorWithExtras(m.getColumnNames(), m); - } - - public void testCursorWithExtras_setAccountMailboxInfo() { - final Context context = mProviderContext; - final Account a1 = ProviderTestUtils.setupAccount("a1", true, context); - final Account a2 = ProviderTestUtils.setupAccount("a2", true, context); - final Mailbox m1 = ProviderTestUtils.setupMailbox("Inbox", a1.mId, true, context, - Mailbox.TYPE_INBOX); - final Mailbox m2 = ProviderTestUtils.setupMailbox("box2", a2.mId, true, context, - Mailbox.TYPE_MAIL); - addMessage(m1, true, false); - addMessage(m2, false, false); - addMessage(m2, false, false); - addMessage(m2, true, true); - - // Account 1 - no mailbox - AccountSelectorAdapter.CursorWithExtras c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, a1.mId, Mailbox.NO_MAILBOX); - - assertTrue(c.accountExists()); - assertEquals(a1.mId, c.getAccountId()); - assertEquals("a1", c.getAccountDisplayName()); - assertEquals(Mailbox.NO_MAILBOX, c.getMailboxId()); - assertNull(c.getMailboxDisplayName()); - assertEquals(0, c.getMailboxMessageCount()); - - // Account 1 - inbox - c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, a1.mId, m1.mId); - - assertTrue(c.accountExists()); - assertEquals(a1.mId, c.getAccountId()); - assertEquals("a1", c.getAccountDisplayName()); - assertEquals(m1.mId, c.getMailboxId()); - assertEquals("Inbox", c.getMailboxDisplayName()); - assertEquals(1, c.getMailboxMessageCount()); - - // Account 2 - regular mailbox - c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, a2.mId, m2.mId); - - assertTrue(c.accountExists()); - assertEquals(a2.mId, c.getAccountId()); - assertEquals("a2", c.getAccountDisplayName()); - assertEquals(m2.mId, c.getMailboxId()); - assertEquals("box2", c.getMailboxDisplayName()); - assertEquals(2, c.getMailboxMessageCount()); - - // combined - no mailbox - c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, Account.ACCOUNT_ID_COMBINED_VIEW, Mailbox.NO_MAILBOX); - - assertTrue(c.accountExists()); - assertEquals(Account.ACCOUNT_ID_COMBINED_VIEW, c.getAccountId()); - assertEquals(getContext().getString(R.string.mailbox_list_account_selector_combined_view), - c.getAccountDisplayName()); - assertEquals(Mailbox.NO_MAILBOX, c.getMailboxId()); - assertNull(c.getMailboxDisplayName()); - assertEquals(0, c.getMailboxMessageCount()); - - // combined - all inbox - c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, Account.ACCOUNT_ID_COMBINED_VIEW, - Mailbox.QUERY_ALL_INBOXES); - - assertTrue(c.accountExists()); - assertEquals(Account.ACCOUNT_ID_COMBINED_VIEW, c.getAccountId()); - assertEquals(getContext().getString(R.string.mailbox_list_account_selector_combined_view), - c.getAccountDisplayName()); - assertEquals(Mailbox.QUERY_ALL_INBOXES, c.getMailboxId()); - assertEquals(getContext().getString(R.string.account_folder_list_summary_inbox), - c.getMailboxDisplayName()); - // (message count = 1, because account 2 doesn't have inbox) - -// TODO For some reason getMailboxMessageCount returns 0 in tests. Investigate it. -// assertEquals(1, c.getMailboxMessageCount()); - - // Account 1 - all starred - // Special case; it happens when you open "starred" on a normal account's mailbox list - // on two-pane. - c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, a1.mId, Mailbox.QUERY_ALL_FAVORITES); - - assertTrue(c.accountExists()); - assertEquals(a1.mId, c.getAccountId()); - assertEquals("a1", c.getAccountDisplayName()); - assertEquals(Mailbox.QUERY_ALL_FAVORITES, c.getMailboxId()); - assertEquals(getContext().getString(R.string.account_folder_list_summary_starred), - c.getMailboxDisplayName()); -// assertEquals(2, c.getMailboxMessageCount()); - - // Invalid id - c = createCursorWithExtras(); - c.setAccountMailboxInfo(context, 123456, 1232456); // no such account / mailbox - - assertFalse(c.accountExists()); - } - - private void addMessage(Mailbox m, boolean starred, boolean read) { - ProviderTestUtils.setupMessage("a", m.mAccountKey, m.mId, false, true, mProviderContext, - starred, read); - } -} diff --git a/tests/src/com/android/email/activity/FindParentMailboxTaskTest.java b/tests/src/com/android/email/activity/FindParentMailboxTaskTest.java deleted file mode 100644 index f20dc89b9..000000000 --- a/tests/src/com/android/email/activity/FindParentMailboxTaskTest.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.email.DBTestHelper; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.Mailbox; - -import android.content.Context; -import android.test.AndroidTestCase; - -/** - * Unit tests for {@link MailboxListFragment.FindParentMailboxTask}. - */ -public class FindParentMailboxTaskTest extends AndroidTestCase { - private Context mProviderContext; - - /** ID of the account created by {@link #setUpMailboxes}. */ - private long mAccountId; - - /** - * IDs for the mailboxes created by {@link #setUpMailboxes}. - * - * Mailbox hierarchy: - *
-     * |-Inbox
-     * |-Parent
-     *   |-Child1
-     *   |-Child2
-     *     |-GrandChild1
-     *     |-GrandChild2
-     * 
- */ - private long mIdInbox; - private long mIdParent; - private long mIdChild1; - private long mIdChild2; - private long mIdGrandChild1; - private long mIdGrandChild2; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( - getContext()); - setUpMailboxes(); - } - - /** - * Set up a test account and mailboxes. - */ - private void setUpMailboxes() { - Account a = ProviderTestUtils.setupAccount("a", true, mProviderContext); - mAccountId = a.mId; - - mIdInbox = createMailboxAndGetId("Inbox", a, Mailbox.TYPE_INBOX, Mailbox.NO_MAILBOX); - mIdParent = createMailboxAndGetId("P", a, Mailbox.TYPE_MAIL, Mailbox.NO_MAILBOX); - mIdChild1 = createMailboxAndGetId("C1", a, Mailbox.TYPE_MAIL, mIdParent); - mIdChild2 = createMailboxAndGetId("C2", a, Mailbox.TYPE_MAIL, mIdParent); - mIdGrandChild1 = createMailboxAndGetId("G1", a, Mailbox.TYPE_MAIL, mIdChild2); - mIdGrandChild2 = createMailboxAndGetId("G2", a, Mailbox.TYPE_MAIL, mIdChild2); - } - - private long createMailboxAndGetId(String name, Account account, int type, - long parentMailboxId) { - Mailbox m = ProviderTestUtils.setupMailbox(name, account.mId, false, mProviderContext, - type); - m.mParentKey = parentMailboxId; - m.save(mProviderContext); - return m.mId; - } - - /** - * Tests for two-pane. (highlighting is enabled) - */ - public void testWithHighlight() { - /* - * In the comments below, [MAILBOX] indicates "highlighted", and MAILBOX* indicates - * "selected". - */ - /* - * from: - * - [Child2] - * - GChild1 - * - GChild2 - * - * to: - * - Parent - * - Child1 - * - [Child2]* - */ - doCheckWithHighlight( - mIdChild2, // Current parent - mIdChild2, // Current highlighted - - mIdParent, // Next root - mIdChild2, // Next highlighted - mIdChild2 // Next selected - ); - - /* - * from: - * - Child2 - * - [GChild1] - * - GChild2 - * - * to: - * - [Parent]* - * - Child1 - * - Child2 - */ - doCheckWithHighlight( - mIdChild2, // Current parent - mIdGrandChild1, // Current highlighted - - mIdParent, // Next root - mIdParent, // Next highlighted - mIdParent // Next selected - ); - - /* - * from: - * - [Parent] - * - Child1 - * - Child2 - * - * to: - * - Inbox - * - [Parent]* - */ - doCheckWithHighlight( - mIdParent, // Current parent - mIdParent, // Current highlighted - - Mailbox.NO_MAILBOX, // Next root - mIdParent, // Next highlighted - mIdParent // Next selected - ); - - /* - * from: - * - Parent - * - [Child1] - * - Child2 - * - * to: - * - [Inbox]* - * - Parent - */ - doCheckWithHighlight( - mIdParent, // Current parent - mIdChild1, // Current highlighted - - Mailbox.NO_MAILBOX, // Next root - mIdInbox, // Next highlighted - mIdInbox // Next selected - ); - - /* - * Special case. - * Up from root view, with "Parent" highlighted. "Up" will be disabled in this case, but - * if we were to run the task, it'd work as if the current parent mailbox is gone. - * i.e. just show the top level mailboxes, with Inbox highlighted. - * - * from: - * - Inbox - * - [Parent] - * - * to: - * - [Inbox] - * - Parent - */ - doCheckWithHighlight( - Mailbox.NO_MAILBOX, // Current parent - mIdParent, // Current highlighted - - Mailbox.NO_MAILBOX, // Next root - mIdInbox, // Next highlighted - mIdInbox // Next selected - ); - - /* - * Special case. - * Current parent mailbox is gone. The result should be same as the above. - * - * from: - * (current mailbox just removed) - * - * to: - * - [Inbox] - * - Parent - */ - doCheckWithHighlight( - 12312234234L, // Current parent - mIdParent, // Current highlighted - - Mailbox.NO_MAILBOX, // Next root - mIdInbox, // Next highlighted - mIdInbox // Next selected - ); - } - - private void doCheckWithHighlight( - long parentMailboxId, long highlightedMailboxId, - long expectedNextParent, long expectedNextHighlighted, long expectedNextSelected) { - doCheck(true, parentMailboxId, highlightedMailboxId, - expectedNextParent, expectedNextHighlighted, expectedNextSelected); - } - - /** - * Tests for one-pane. (highlighting is disable) - */ - public void testWithNoHighlight() { - /* - * from: - * - Child2 - * - GChild1 - * - GChild2 - * - * to: - * - Parent - * - Child1 - * - Child2 - */ - doCheckWithNoHighlight( - mIdChild2, // Current parent - mIdParent // Next root - ); - /* - * from: - * - Parent - * - Child1 - * - Child2 - * - * to: - * - Inbox - * - Parent - */ - doCheckWithNoHighlight( - mIdParent, // Current parent - Mailbox.NO_MAILBOX // Next root - ); - - /* - * Special case. - * Current parent mailbox is gone. The top-level mailboxes should be shown. - * - * from: - * (current mailbox just removed) - * - * to: - * - Inbox - * - Parent - */ - doCheckWithNoHighlight( - 12312234234L, // Current parent - Mailbox.NO_MAILBOX // Next root - ); - } - - private void doCheckWithNoHighlight(long parentMailboxId, long expectedNextParent) { - doCheck(false, parentMailboxId, Mailbox.NO_MAILBOX, - expectedNextParent, Mailbox.NO_MAILBOX, - expectedNextParent /* parent should always be selected */); - } - - private void doCheck(boolean enableHighlight, - long parentMailboxId, long highlightedMailboxId, - long expectedNextParent, long expectedNextHighlighted, long expectedNextSelected) { - ResultCallback result = new ResultCallback(); - - MailboxListFragment.FindParentMailboxTask task - = new MailboxListFragment.FindParentMailboxTask( - mProviderContext, null, mAccountId, enableHighlight, parentMailboxId, - highlightedMailboxId, result); - - // Can't execute an async task on the test thread, so emulate execution... - task.onSuccess(task.doInBackground((Void[]) null)); - - assertEquals("parent", expectedNextParent, result.mNextParentMailboxId); - assertEquals("highlighted", expectedNextHighlighted, result.mNextHighlightedMailboxId); - assertEquals("selected", expectedNextSelected, result.mNextSelectedMailboxId); - } - - private static class ResultCallback - implements MailboxListFragment.FindParentMailboxTask.ResultCallback { - public long mNextParentMailboxId; - public long mNextHighlightedMailboxId; - public long mNextSelectedMailboxId; - - @Override - public void onResult(long nextParentMailboxId, long nextHighlightedMailboxId, - long nextSelectedMailboxId) { - mNextParentMailboxId = nextParentMailboxId; - mNextHighlightedMailboxId = nextHighlightedMailboxId; - mNextSelectedMailboxId = nextSelectedMailboxId; - } - } -} diff --git a/tests/src/com/android/email/activity/MailboxFinderTest.java b/tests/src/com/android/email/activity/MailboxFinderTest.java deleted file mode 100644 index 6087081db..000000000 --- a/tests/src/com/android/email/activity/MailboxFinderTest.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import android.content.Context; -import android.test.InstrumentationTestCase; -import android.test.ProviderTestCase2; -import android.test.suitebuilder.annotation.LargeTest; - -import com.android.email.Controller; -import com.android.email.DBTestHelper; -import com.android.email.Email; -import com.android.email.TestUtils; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.mail.MessagingException; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.Mailbox; - -/** - * Test case for {@link MailboxFinder}. - * - * We need to use {@link InstrumentationTestCase} so that we can create AsyncTasks on the UI thread - * using {@link InstrumentationTestCase#runTestOnUiThread}. This class also needs an isolated - * context, which is provided by {@link ProviderTestCase2}. We can't derive from two classes, - * so we just copy the code for an isolate context to here. - */ -@LargeTest -public class MailboxFinderTest extends InstrumentationTestCase { - private static final int TIMEOUT = 10; // in seconds - - // Test target - private MailboxFinder mMailboxFinder; - - // Isolted Context for providers. - private Context mProviderContext; - - // Mock to track callback invocations. - private MockController mMockController; - private MockCallback mCallback; - - private Context getContext() { - return getInstrumentation().getTargetContext(); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( - getInstrumentation().getTargetContext()); - mCallback = new MockCallback(); - mMockController = new MockController(getContext()); - Controller.injectMockControllerForTest(mMockController); - assertEquals(0, mMockController.getResultCallbacksForTest().size()); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (mMailboxFinder != null) { - mMailboxFinder.cancel(); - - // MailboxFinder should unregister its listener when closed. - checkControllerResultRemoved(mMockController); - } - mMockController.cleanupForTest(); - Controller.injectMockControllerForTest(null); - } - - /** - * Make sure no {@link MailboxFinder.Callback} is left registered to the controller. - */ - private static void checkControllerResultRemoved(Controller controller) { - for (Controller.Result callback : controller.getResultCallbacksForTest()) { - assertFalse(callback instanceof MailboxFinder.Callback); - } - } - - /** - * Create an account and returns the ID. - */ - private long createAccount(boolean securityHold) { - Account acct = ProviderTestUtils.setupAccount("acct1", false, mProviderContext); - if (securityHold) { - acct.mFlags |= Account.FLAGS_SECURITY_HOLD; - } - acct.save(mProviderContext); - return acct.mId; - } - - /** - * Create a mailbox and return the ID. - */ - private long createMailbox(long accountId, int mailboxType) { - Mailbox box = new Mailbox(); - box.mServerId = box.mDisplayName = "mailbox"; - box.mAccountKey = accountId; - box.mType = mailboxType; - box.mFlagVisible = true; - box.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT; - box.save(mProviderContext); - return box.mId; - } - - /** - * Create a {@link MailboxFinder} and kick it. - */ - private void createAndStartFinder(final long accountId, final int mailboxType) - throws Throwable { - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mMailboxFinder = new MailboxFinder(mProviderContext, accountId, mailboxType, - mCallback); - mMailboxFinder.startLookup(); - assertTrue(mMailboxFinder.isStartedForTest()); - } - }); - } - - /** - * Wait until any of the {@link MailboxFinder.Callback} method or - * {@link Controller#updateMailboxList} is called. - */ - private void waitUntilCallbackCalled() { - TestUtils.waitUntil("", new TestUtils.Condition() { - @Override - public boolean isMet() { - return mCallback.isAnyMethodCalled() || mMockController.mCalledUpdateMailboxList; - } - }, TIMEOUT); - } - - /** - * Test: Account is on security hold. - */ - public void testSecurityHold() throws Throwable { - final long accountId = createAccount(true); - - createAndStartFinder(accountId, Mailbox.TYPE_INBOX); - waitUntilCallbackCalled(); - - assertFalse(mCallback.mCalledAccountNotFound); - assertTrue(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * Test: Account does not exist. - */ - public void testAccountNotFound() throws Throwable { - createAndStartFinder(123456, Mailbox.TYPE_INBOX); // No such account. - waitUntilCallbackCalled(); - - assertTrue(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * Test: Mailbox found - */ - public void testMailboxFound() throws Throwable { - final long accountId = createAccount(false); - final long mailboxId = createMailbox(accountId, Mailbox.TYPE_INBOX); - - createAndStartFinder(accountId, Mailbox.TYPE_INBOX); - waitUntilCallbackCalled(); - - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertTrue(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertEquals(accountId, mCallback.mAccountId); - assertEquals(mailboxId, mCallback.mMailboxId); - - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * Common initialization for tests that involves network-lookup. - */ - private void prepareForNetworkLookupTest(final long accountId) throws Throwable { - // Look for non-existing mailbox. - createAndStartFinder(accountId, Mailbox.TYPE_INBOX); - waitUntilCallbackCalled(); - - // Mailbox not found, so the finder should try network-looking up. - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - - // Controller.updateMailboxList() should have been called, with the account id. - assertTrue(mMockController.mCalledUpdateMailboxList); - assertEquals(accountId, mMockController.mPassedAccountId); - - mMockController.reset(); - - assertFalse(mMailboxFinder.isReallyClosedForTest()); // Not closed yet - } - - /** - * Test: Account exists, but mailbox doesn't -> Get {@link Controller} to update the mailbox - * list -> mailbox still doesn't exist. - */ - public void testMailboxNotFound() throws Throwable { - final long accountId = createAccount(false); - - prepareForNetworkLookupTest(accountId); - - // Imitate the mCallback... - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mMailboxFinder.getControllerResultsForTest().updateMailboxListCallback( - null, accountId, 100); - } - }); - - // Task should have started, so wait for the response... - waitUntilCallbackCalled(); - - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertTrue(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * Test: Account exists, but mailbox doesn't -> Get {@link Controller} to update the mailbox - * list -> found mailbox this time. - */ - public void testMailboxFoundOnNetwork() throws Throwable { - final long accountId = createAccount(false); - - prepareForNetworkLookupTest(accountId); - - // Create mailbox at this point. - final long mailboxId = createMailbox(accountId, Mailbox.TYPE_INBOX); - - // Imitate the mCallback... - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mMailboxFinder.getControllerResultsForTest().updateMailboxListCallback( - null, accountId, 100); - } - }); - - // Task should have started, so wait for the response... - waitUntilCallbackCalled(); - - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertTrue(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertEquals(accountId, mCallback.mAccountId); - assertEquals(mailboxId, mCallback.mMailboxId); - - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * Test: Account exists, but mailbox doesn't -> Get {@link Controller} to update the mailbox - * list -> network error. - */ - public void testMailboxNotFoundNetworkError() throws Throwable { - final long accountId = createAccount(false); - - prepareForNetworkLookupTest(accountId); - - // Imitate the mCallback... - runTestOnUiThread(new Runnable() { - @Override - public void run() { - // network error. - mMailboxFinder.getControllerResultsForTest().updateMailboxListCallback( - new MessagingException("Network error"), accountId, 0); - } - }); - - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertTrue(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * Test: updateMailboxListCallback won't respond to update of a non-target account. - */ - public void testUpdateMailboxListCallbackNonTarget() throws Throwable { - final long accountId = createAccount(false); - - prepareForNetworkLookupTest(accountId); - - // Callback from Controller, but for a different account. - runTestOnUiThread(new Runnable() { - @Override - public void run() { - long nonTargetAccountId = accountId + 1; - mMailboxFinder.getControllerResultsForTest().updateMailboxListCallback( - new MessagingException("Network error"), nonTargetAccountId, 0); - } - }); - - // Nothing happened. - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - assertFalse(mMockController.mCalledUpdateMailboxList); - - assertFalse(mMailboxFinder.isReallyClosedForTest()); // Not closed yet - } - - /** - * Test: Mailbox not found (mailbox of different type exists) - */ - public void testMailboxNotFound2() throws Throwable { - final long accountId = createAccount(false); - final long mailboxId = createMailbox(accountId, Mailbox.TYPE_DRAFTS); - - createAndStartFinder(accountId, Mailbox.TYPE_INBOX); - waitUntilCallbackCalled(); - - assertFalse(mCallback.mCalledAccountNotFound); - assertFalse(mCallback.mCalledAccountSecurityHold); - assertFalse(mCallback.mCalledMailboxFound); - assertFalse(mCallback.mCalledMailboxNotFound); - assertTrue(mMockController.mCalledUpdateMailboxList); - - assertFalse(mMailboxFinder.isReallyClosedForTest()); // Not closed yet -- network lookup. - } - - /** - * Test: Call {@link MailboxFinder#startLookup()} twice, which should throw an ISE. - */ - public void testRunTwice() throws Throwable { - final long accountId = createAccount(true); - - createAndStartFinder(accountId, Mailbox.TYPE_INBOX); - try { - mMailboxFinder.startLookup(); - fail("Expected exception not thrown"); - } catch (IllegalStateException ok) { - } - } - - public void testCancel() throws Throwable { - final long accountId = createAccount(true); - - createAndStartFinder(accountId, Mailbox.TYPE_INBOX); - mMailboxFinder.cancel(); - assertTrue(mMailboxFinder.isReallyClosedForTest()); - } - - /** - * A {@link Controller} that remembers if updateMailboxList has been called. - */ - private static class MockController extends Controller { - public volatile long mPassedAccountId; - public volatile boolean mCalledUpdateMailboxList; - - public void reset() { - mPassedAccountId = -1; - mCalledUpdateMailboxList = false; - } - - protected MockController(Context context) { - super(context); - } - - @Override - public void updateMailboxList(long accountId) { - mCalledUpdateMailboxList = true; - mPassedAccountId = accountId; - } - } - - /** - * Callback that logs what method is called with what arguments. - */ - private static class MockCallback implements MailboxFinder.Callback { - public volatile boolean mCalledAccountNotFound; - public volatile boolean mCalledAccountSecurityHold; - public volatile boolean mCalledMailboxFound; - public volatile boolean mCalledMailboxNotFound; - - public volatile long mAccountId = -1; - public volatile long mMailboxId = -1; - - public boolean isAnyMethodCalled() { - return mCalledAccountNotFound || mCalledAccountSecurityHold || mCalledMailboxFound - || mCalledMailboxNotFound; - } - - @Override - public void onAccountNotFound() { - mCalledAccountNotFound = true; - } - - @Override - public void onAccountSecurityHold(long accountId) { - mCalledAccountSecurityHold = true; - mAccountId = accountId; - } - - @Override - public void onMailboxFound(long accountId, long mailboxId) { - mCalledMailboxFound = true; - mAccountId = accountId; - mMailboxId = mailboxId; - } - - @Override - public void onMailboxNotFound(long accountId) { - mCalledMailboxNotFound = true; - mAccountId = accountId; - } - } -} diff --git a/tests/src/com/android/email/activity/MailboxFragmentAdapterTest.java b/tests/src/com/android/email/activity/MailboxFragmentAdapterTest.java deleted file mode 100644 index 2bf19d1d9..000000000 --- a/tests/src/com/android/email/activity/MailboxFragmentAdapterTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.email.provider.EmailProvider; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.EmailContent; -import com.android.emailcommon.provider.EmailContent.Message; -import com.android.emailcommon.provider.Mailbox; - -import android.content.Context; -import android.database.Cursor; -import android.test.ProviderTestCase2; - -import junit.framework.Assert; - -public class MailboxFragmentAdapterTest extends ProviderTestCase2 { - - private Context mMockContext; - - public MailboxFragmentAdapterTest() { - super(EmailProvider.class, EmailContent.AUTHORITY); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - mMockContext = getMockContext(); - } - - public void testBuildCombinedMailboxes() { - final Context c = mMockContext; - - // Prepare test data - Account a1 = ProviderTestUtils.setupAccount("a1", true, c); - Account a2 = ProviderTestUtils.setupAccount("a2", true, c); - Account a3 = ProviderTestUtils.setupAccount("a3", true, c); - - Mailbox b1i = ProviderTestUtils.setupMailbox("box1i", a1.mId, true, c, Mailbox.TYPE_INBOX); - Mailbox b2i = ProviderTestUtils.setupMailbox("box2i", a2.mId, true, c, Mailbox.TYPE_INBOX); - Mailbox b3i = ProviderTestUtils.setupMailbox("box3i", a3.mId, true, c, Mailbox.TYPE_INBOX); - Mailbox b1o = ProviderTestUtils.setupMailbox("box1i", a1.mId, true, c, Mailbox.TYPE_OUTBOX); - Mailbox b2o = ProviderTestUtils.setupMailbox("box2i", a2.mId, true, c, Mailbox.TYPE_OUTBOX); - Mailbox b1d = ProviderTestUtils.setupMailbox("box1d", a1.mId, true, c, Mailbox.TYPE_DRAFTS); - Mailbox b2d = ProviderTestUtils.setupMailbox("box2d", a2.mId, true, c, Mailbox.TYPE_DRAFTS); - Mailbox b1t = ProviderTestUtils.setupMailbox("box1t", a1.mId, true, c, Mailbox.TYPE_TRASH); - Mailbox b2t = ProviderTestUtils.setupMailbox("box2t", a2.mId, true, c, Mailbox.TYPE_TRASH); - - createMessage(c, b1i, false, false, Message.FLAG_LOADED_COMPLETE); - createMessage(c, b2i, true, true, Message.FLAG_LOADED_COMPLETE); - createMessage(c, b2i, true, false, Message.FLAG_LOADED_COMPLETE); - // "unloaded" messages will not affect 'favorite' message count - createMessage(c, b3i, true, true, Message.FLAG_LOADED_UNLOADED); - - createMessage(c, b1o, true, true, Message.FLAG_LOADED_COMPLETE); - createMessage(c, b2o, false, true, Message.FLAG_LOADED_COMPLETE); - - createMessage(c, b1d, false, true, Message.FLAG_LOADED_COMPLETE); - createMessage(c, b2d, false, true, Message.FLAG_LOADED_COMPLETE); - createMessage(c, b2d, false, true, Message.FLAG_LOADED_COMPLETE); - createMessage(c, b2d, false, true, Message.FLAG_LOADED_COMPLETE); - - // Starred message in trash; All Starred excludes it. - createMessage(c, b2t, true, true, Message.FLAG_LOADED_UNLOADED); - - // Kick the method - Cursor cursor = MailboxFragmentAdapter.CombinedMailboxLoader.buildCombinedMailboxes(c, - null); - - // Check the result - assertEquals(4, cursor.getCount()); - - // Row 1 -- combined inbox (with unread count) - assertTrue(cursor.moveToFirst()); - checkSpecialMailboxRow(cursor, Mailbox.QUERY_ALL_INBOXES, Mailbox.TYPE_INBOX, 2); - - // Row 2 -- all starred (with total count) - assertTrue(cursor.moveToNext()); - checkSpecialMailboxRow(cursor, Mailbox.QUERY_ALL_FAVORITES, Mailbox.TYPE_MAIL, 3); - - // Row 3 -- all drafts (with total count) - assertTrue(cursor.moveToNext()); - checkSpecialMailboxRow(cursor, Mailbox.QUERY_ALL_DRAFTS, Mailbox.TYPE_DRAFTS, 4); - - // Row 4 -- combined outbox (with total count) - assertTrue(cursor.moveToNext()); - checkSpecialMailboxRow(cursor, Mailbox.QUERY_ALL_OUTBOX, Mailbox.TYPE_OUTBOX, 2); - } - - private static Message createMessage(Context c, Mailbox b, boolean starred, boolean read, - int flagLoaded) { - Message message = ProviderTestUtils.setupMessage( - "1", b.mAccountKey, b.mId, true, false, c, starred, read); - message.mFlagLoaded = flagLoaded; - message.save(c); - return message; - } - - private static void checkSpecialMailboxRow(Cursor cursor, long id, int type, - int count) { - // _id must always be >= 0; otherwise ListView gets confused. - Assert.assertTrue(cursor.getLong(cursor.getColumnIndex("_id")) >= 0); - Assert.assertEquals(id, MailboxFragmentAdapter.getId(cursor)); - Assert.assertEquals(type, MailboxFragmentAdapter.getType(cursor)); - Assert.assertEquals(count, MailboxFragmentAdapter.getMessageCount(cursor)); - Assert.assertEquals(count, MailboxFragmentAdapter.getUnreadCount(cursor)); - Assert.assertEquals(Account.ACCOUNT_ID_COMBINED_VIEW, - MailboxFragmentAdapter.getAccountId(cursor)); - } -} diff --git a/tests/src/com/android/email/activity/MessageComposeTests.java b/tests/src/com/android/email/activity/MessageComposeTests.java index d91c67319..cb1dcee26 100644 --- a/tests/src/com/android/email/activity/MessageComposeTests.java +++ b/tests/src/com/android/email/activity/MessageComposeTests.java @@ -1,46 +1,23 @@ /* * Copyright (C) 2008 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. */ package com.android.email.activity; -import android.content.ContentUris; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.test.ActivityInstrumentationTestCase2; -import android.test.UiThreadTest; +import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.SmallTest; -import android.view.View; -import android.widget.EditText; -import android.widget.MultiAutoCompleteTextView; - -import com.android.email.Email; -import com.android.email.EmailAddressValidator; -import com.android.email.R; -import com.android.email.TestUtils; -import com.android.emailcommon.Logging; -import com.android.emailcommon.mail.Address; -import com.android.emailcommon.mail.MessagingException; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.EmailContent.Attachment; -import com.android.emailcommon.provider.EmailContent.Message; -import com.google.android.collect.Lists; - -import java.util.ArrayList; /** @@ -52,982 +29,5 @@ import java.util.ArrayList; * runtest -c com.android.email.activity.MessageComposeTests email */ @LargeTest -public class MessageComposeTests - extends ActivityInstrumentationTestCase2 { - - private Context mContext; - - private MultiAutoCompleteTextView mToView; - private MultiAutoCompleteTextView mCcView; - private MultiAutoCompleteTextView mBccView; - private EditText mSubjectView; - private EditText mMessageView; - private long mCreatedAccountId = -1; - private String mSignature; - - private static final String ACCOUNT = "account@android.com"; - private static final String SENDER = "sender@android.com"; - private static final String REPLYTO = "replyto@android.com"; - private static final String RECIPIENT_TO = "recipient-to@android.com"; - private static final String RECIPIENT_CC = "recipient-cc@android.com"; - private static final String RECIPIENT_BCC = "recipient-bcc@android.com"; - private static final String SUBJECT = "This is the subject"; - private static final String BODY = "This is the body. This is also the body."; - private static final String SIGNATURE = "signature"; - - private static final String FROM = "Fred From "; - private static final String TO1 = "First To "; - private static final String TO2 = "Second To "; - private static final String TO3 = "CopyFirst Cc "; - private static final String CC1 = "First Cc "; - private static final String CC2 = "Second Cc "; - private static final String CC3 = "Third Cc "; - private static final String CC4 = "CopySecond To "; - - private static final String UTF16_SENDER = - "\u3042\u3044\u3046 \u3048\u304A "; - private static final String UTF16_REPLYTO = - "\u3042\u3044\u3046\u3048\u304A "; - private static final String UTF16_RECIPIENT_TO = - "\"\u3042\u3044\u3046,\u3048\u304A\" "; - private static final String UTF16_RECIPIENT_CC = - "\u30A2\u30AB \u30B5\u30BF\u30CA "; - private static final String UTF16_RECIPIENT_BCC = - "\"\u30A2\u30AB,\u30B5\u30BF\u30CA\" "; - private static final String UTF16_SUBJECT = "\u304A\u5BFF\u53F8\u306B\u3059\u308B\uFF1F"; - private static final String UTF16_BODY = "\u65E5\u672C\u8A9E\u306E\u6587\u7AE0"; - - private static final String UTF32_SENDER = - "\uD834\uDF01\uD834\uDF46 \uD834\uDF22 "; - private static final String UTF32_REPLYTO = - "\uD834\uDF01\uD834\uDF46\uD834\uDF22 "; - private static final String UTF32_RECIPIENT_TO = - "\"\uD834\uDF01\uD834\uDF46,\uD834\uDF22\" "; - private static final String UTF32_RECIPIENT_CC = - "\uD834\uDF22 \uD834\uDF01\uD834\uDF46 "; - private static final String UTF32_RECIPIENT_BCC = - "\"\uD834\uDF22,\uD834\uDF01\uD834\uDF46\" "; - private static final String UTF32_SUBJECT = "\uD834\uDF01\uD834\uDF46"; - private static final String UTF32_BODY = "\uD834\uDF01\uD834\uDF46"; - - /* - * The following action definitions are purposefully copied from MessageCompose, so that - * any changes to the action strings will break these tests. Changes to the actions should - * be done consciously to think about existing shortcuts and clients. - */ - - private static final String ACTION_REPLY = "com.android.email.intent.action.REPLY"; - private static final String ACTION_REPLY_ALL = "com.android.email.intent.action.REPLY_ALL"; - private static final String ACTION_FORWARD = "com.android.email.intent.action.FORWARD"; - private static final String ACTION_EDIT_DRAFT = "com.android.email.intent.action.EDIT_DRAFT"; - - public MessageComposeTests() { - super(MessageCompose.class); - } - - /* - * The Message Composer activity is only enabled if one or more accounts - * are configured on the device and a default account has been specified, - * so we do that here before every test. - */ - @Override - protected void setUp() throws Exception { - super.setUp(); - mContext = getInstrumentation().getTargetContext(); - - // Force assignment of a default account - long accountId = Account.getDefaultAccountId(mContext); - if (accountId == -1) { - Account account = new Account(); - account.mSenderName = "Bob Sender"; - account.mEmailAddress = "bob@sender.com"; - account.mSignature = SIGNATURE; - account.save(mContext); - accountId = account.mId; - mCreatedAccountId = accountId; - } - Account account = Account.restoreAccountWithId(mContext, accountId); - mSignature = account.getSignature(); - Email.setServicesEnabledSync(mContext); - - Intent intent = new Intent(Intent.ACTION_VIEW); - setActivityIntent(intent); - final MessageCompose a = getActivity(); - mToView = (MultiAutoCompleteTextView) a.findViewById(R.id.to); - mCcView = (MultiAutoCompleteTextView) a.findViewById(R.id.cc); - mBccView = (MultiAutoCompleteTextView) a.findViewById(R.id.bcc); - mSubjectView = (EditText) a.findViewById(R.id.subject); - mMessageView = (EditText) a.findViewById(R.id.message_content); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - Context context = getInstrumentation().getTargetContext(); - // If we created an account, delete it here - if (mCreatedAccountId > -1) { - context.getContentResolver().delete( - ContentUris.withAppendedId(Account.CONTENT_URI, mCreatedAccountId), null, null); - } - } - - /** - * The name 'test preconditions' is a convention to signal that if this - * test doesn't pass, the test case was not set up properly and it might - * explain any and all failures in other tests. This is not guaranteed - * to run before other tests, as junit uses reflection to find the tests. - */ - public void testPreconditions() { - assertNotNull(mToView); - assertEquals(0, mToView.length()); - assertNotNull(mSubjectView); - assertEquals(0, mSubjectView.length()); - assertNotNull(mMessageView); - - // Note that the signature is always preceeded with a newline. - int sigLength = (mSignature == null) ? 0 : (1 + mSignature.length()); - assertEquals(sigLength, mMessageView.length()); - } - - /** - * Test a couple of variations of processSourceMessage() for REPLY. - * To = Reply-To or From: (if REPLY) - * To = (Reply-To or From:), Cc = + To: + Cc: (if REPLY_ALL) - * Subject = Re: Subject - * Body = empty (and has cursor) - * - * TODO test REPLY_ALL - */ - public void testProcessSourceMessageReply() throws MessagingException, Throwable { - final Message message = buildTestMessage(RECIPIENT_TO, SENDER, SUBJECT, BODY); - Intent intent = new Intent(ACTION_REPLY); - final MessageCompose a = getActivity(); - a.setIntent(intent); - final Account account = new Account(); - account.mEmailAddress = ACCOUNT; - - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(SENDER + ", ", null, null, "Re: " + SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - - message.mFrom = null; - message.mReplyTo = Address.parseAndPack(REPLYTO); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(REPLYTO + ", ", null, null, "Re: " + SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - } - - /** - * Tests similar cases as testProcessSourceMessageReply, but when sender is in From: (or - * Reply-to: if applicable) field. - * - * To = To (if REPLY) - * To = To, Cc = Cc (if REPLY_ALL) - * Subject = Re: Subject - * Body = empty (and has cursor) - * - * @throws MessagingException - * @throws Throwable - */ - public void testRepliesWithREplyToFields() throws MessagingException, Throwable { - final Message message = buildTestMessage(RECIPIENT_TO, SENDER, SUBJECT, BODY); - message.mCc = RECIPIENT_CC; - Intent intent = new Intent(ACTION_REPLY); - final MessageCompose a = getActivity(); - a.setIntent(intent); - final Account account = new Account(); - account.mEmailAddress = SENDER; - - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(RECIPIENT_TO + ", ", null, null, "Re: " + SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - - message.mFrom = null; - message.mReplyTo = Address.parseAndPack(SENDER); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(RECIPIENT_TO + ", ", null, null, "Re: " + SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - - a.setIntent(new Intent(ACTION_REPLY_ALL)); - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(RECIPIENT_TO + ", ", RECIPIENT_CC + ", ", null, - "Re: " + SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - } - - public void testProcessSourceMessageReplyWithSignature() throws MessagingException, Throwable { - final Message message = buildTestMessage(RECIPIENT_TO, SENDER, SUBJECT, BODY); - Intent intent = new Intent(ACTION_REPLY); - final MessageCompose a = getActivity(); - a.setIntent(intent); - final Account account = new Account(); - account.mEmailAddress = ACCOUNT; - account.mSignature = SIGNATURE; - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, account); - a.setInitialComposeText(null, SIGNATURE); - checkFields(SENDER + ", ", null, null, "Re: " + SUBJECT, null, SIGNATURE); - checkFocused(mMessageView); - } - }); - - message.mFrom = null; - message.mReplyTo = Address.parseAndPack(REPLYTO); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processSourceMessage(message, account); - a.setInitialComposeText(null, SIGNATURE); - checkFields(REPLYTO + ", ", null, null, "Re: " + SUBJECT, null, SIGNATURE); - checkFocused(mMessageView); - } - }); - } - - public void testProcessSourceMessageForwardWithSignature() - throws MessagingException, Throwable { - final Message message = buildTestMessage(RECIPIENT_TO, SENDER, SUBJECT, BODY); - Intent intent = new Intent(ACTION_FORWARD); - final MessageCompose a = getActivity(); - a.setIntent(intent); - final Account account = new Account(); - account.mSignature = SIGNATURE; - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, account); - a.setInitialComposeText(null, SIGNATURE); - checkFields(null, null, null, "Fwd: " + SUBJECT, null, SIGNATURE); - checkFocused(mToView); - } - }); - } - - /** - * Test reply to utf-16 name and address - */ - public void testProcessSourceMessageReplyUtf16() throws MessagingException, Throwable { - final Message message = buildTestMessage(UTF16_RECIPIENT_TO, UTF16_SENDER, - UTF16_SUBJECT, UTF16_BODY); - Intent intent = new Intent(ACTION_REPLY); - final MessageCompose a = getActivity(); - a.setIntent(intent); - final Account account = new Account(); - account.mEmailAddress = ACCOUNT; - - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(UTF16_SENDER + ", ", null, null, "Re: " + UTF16_SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - - message.mFrom = null; - message.mReplyTo = Address.parseAndPack(UTF16_REPLYTO); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(UTF16_REPLYTO + ", ", null, null, "Re: " + UTF16_SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - } - - /** - * Test reply to utf-32 name and address - */ - public void testProcessSourceMessageReplyUtf32() throws MessagingException, Throwable { - final Message message = buildTestMessage(UTF32_RECIPIENT_TO, UTF32_SENDER, - UTF32_SUBJECT, UTF32_BODY); - Intent intent = new Intent(ACTION_REPLY); - final MessageCompose a = getActivity(); - a.setIntent(intent); - final Account account = new Account(); - account.mEmailAddress = ACCOUNT; - - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(UTF32_SENDER + ", ", null, null, "Re: " + UTF32_SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - - message.mFrom = null; - message.mReplyTo = Address.parseAndPack(UTF32_REPLYTO); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processSourceMessage(message, account); - a.setInitialComposeText(null, null); - checkFields(UTF32_REPLYTO + ", ", null, null, "Re: " + UTF32_SUBJECT, null, null); - checkFocused(mMessageView); - } - }); - } - - /** - * Test processSourceMessage() for FORWARD - * To = empty (and has cursor) - * Subject = Fwd: Subject - * Body = empty - */ - public void testProcessSourceMessageForward() throws MessagingException, Throwable { - final Message message = buildTestMessage(RECIPIENT_TO, SENDER, SUBJECT, BODY); - Intent intent = new Intent(ACTION_FORWARD); - final MessageCompose a = getActivity(); - a.setIntent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.processSourceMessage(message, null); - a.setInitialComposeText(null, null); - checkFields(null, null, null, "Fwd: " + SUBJECT, null, null); - checkFocused(mToView); - } - }); - } - - /** - * Test processSourceMessage() for EDIT_DRAFT - * Reply and ReplyAll should map: - * To = to - * Subject = Subject - * Body = body (has cursor) - * - * TODO check CC and BCC handling too - */ - public void testProcessDraftMessage() throws MessagingException, Throwable { - - final Message message = buildTestMessage(RECIPIENT_TO, SENDER, SUBJECT, BODY); - Intent intent = new Intent(ACTION_EDIT_DRAFT); - final MessageCompose a = getActivity(); - a.setIntent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.processDraftMessage(message, true); - checkFields(RECIPIENT_TO + ", ", null, null, SUBJECT, BODY, null); - checkFocused(mMessageView); - } - }); - - // if subject is null, then cursor should be there instead - - message.mSubject = ""; - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processDraftMessage(message, true); - checkFields(RECIPIENT_TO + ", ", null, null, null, BODY, null); - checkFocused(mSubjectView); - } - }); - - } - - /** - * Test processDraftMessage() for EDIT_DRAFT with utf-16 name and address - * TODO check CC and BCC handling too - */ - public void testProcessDraftMessageWithUtf16() throws MessagingException, Throwable { - - final Message message = buildTestMessage(UTF16_RECIPIENT_TO, UTF16_SENDER, - UTF16_SUBJECT, UTF16_BODY); - Intent intent = new Intent(ACTION_EDIT_DRAFT); - final MessageCompose a = getActivity(); - a.setIntent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.processDraftMessage(message, true); - checkFields(UTF16_RECIPIENT_TO + ", ", - null, null, UTF16_SUBJECT, UTF16_BODY, null); - checkFocused(mMessageView); - } - }); - - // if subject is null, then cursor should be there instead - - message.mSubject = ""; - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processDraftMessage(message, true); - checkFields(UTF16_RECIPIENT_TO + ", ", null, null, null, UTF16_BODY, null); - checkFocused(mSubjectView); - } - }); - - } - - /** - * Test processDraftMessage() for EDIT_DRAFT with utf-32 name and address - * TODO check CC and BCC handling too - */ - public void testProcessDraftMessageWithUtf32() throws MessagingException, Throwable { - - final Message message = buildTestMessage(UTF32_RECIPIENT_TO, UTF32_SENDER, - UTF32_SUBJECT, UTF32_BODY); - Intent intent = new Intent(ACTION_EDIT_DRAFT); - final MessageCompose a = getActivity(); - a.setIntent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.processDraftMessage(message, true); - checkFields(UTF32_RECIPIENT_TO + ", ", - null, null, UTF32_SUBJECT, UTF32_BODY, null); - checkFocused(mMessageView); - } - }); - - // if subject is null, then cursor should be there instead - - message.mSubject = ""; - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.processDraftMessage(message, true); - checkFields(UTF32_RECIPIENT_TO + ", ", null, null, null, UTF32_BODY, null); - checkFocused(mSubjectView); - } - }); - - } - - /** - * Check that we create the proper to and cc addressees in reply and reply-all, making sure - * to reject duplicate addressees AND the email address of the sending account - * - * In this case, we're doing a "reply" - * The user is TO1 (a "to" recipient) - * The to should be: FROM - * The cc should be empty - */ - public void testReplyAddresses() throws Throwable { - final MessageCompose a = getActivity(); - // Doesn't matter what Intent we use here - final Intent intent = new Intent(Intent.ACTION_VIEW); - Message msg = new Message(); - final Account account = new Account(); - - msg.mFrom = Address.parseAndPack(FROM); - msg.mTo = Address.parseAndPack(TO1 + ',' + TO2); - msg.mCc = Address.parseAndPack(CC1 + ',' + CC2 + ',' + CC3); - final Message message = msg; - account.mEmailAddress = "FiRsT.tO@gOoGlE.cOm"; - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(intent); - a.setupAddressViews(message, account, false); - assertEquals("", mCcView.getText().toString()); - String result = Address.parseAndPack(mToView.getText().toString()); - String expected = Address.parseAndPack(FROM); - assertEquals(expected, result); - - // It doesn't harm even if the CC view is visible. - } - }); - } - - /** - * Check that we create the proper to and cc addressees in reply and reply-all, making sure - * to reject duplicate addressees AND the email address of the sending account - * - * In this case, we're doing a "reply all" - * The user is TO1 (a "to" recipient) - * The to should be: FROM - * The cc should be: TO2, CC1, CC2, and CC3 - */ - public void testReplyAllAddresses1() throws Throwable { - final MessageCompose a = getActivity(); - // Doesn't matter what Intent we use here - final Intent intent = new Intent(Intent.ACTION_VIEW); - Message msg = new Message(); - final Account account = new Account(); - - msg.mFrom = Address.parseAndPack(FROM); - msg.mTo = Address.parseAndPack(TO1 + ',' + TO2); - msg.mCc = Address.parseAndPack(CC1 + ',' + CC2 + ',' + CC3); - final Message message = msg; - account.mEmailAddress = "FiRsT.tO@gOoGlE.cOm"; - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(intent); - a.setupAddressViews(message, account, true); - String result = Address.parseAndPack(mToView.getText().toString()); - String expected = Address.parseAndPack(FROM); - assertEquals(expected, result); - result = Address.parseAndPack(mCcView.getText().toString()); - expected = Address.parseAndPack(TO2 + ',' + CC1 + ',' + CC2 + ',' + CC3); - assertEquals(expected, result); - TestUtils.assertViewVisible(mCcView); - } - }); - } - - /** - * Check that we create the proper to and cc addressees in reply and reply-all, making sure - * to reject duplicate addressees AND the email address of the sending account - * - * In this case, we're doing a "reply all" - * The user is CC2 (a "cc" recipient) - * The to should be: FROM, - * The cc should be: TO1, TO2, CC1 and CC3 (CC2 is our account's email address) - */ - public void testReplyAllAddresses2() throws Throwable { - final MessageCompose a = getActivity(); - // Doesn't matter what Intent we use here - final Intent intent = new Intent(Intent.ACTION_VIEW); - Message msg = new Message(); - final Account account = new Account(); - - msg.mFrom = Address.parseAndPack(FROM); - msg.mTo = Address.parseAndPack(TO1 + ',' + TO2); - msg.mCc = Address.parseAndPack(CC1 + ',' + CC2 + ',' + CC3); - final Message message = msg; - account.mEmailAddress = "sEcOnD.cC@gOoGlE.cOm"; - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(intent); - a.setupAddressViews(message, account, true); - String result = Address.parseAndPack(mToView.getText().toString()); - String expected = Address.parseAndPack(FROM); - assertEquals(expected, result); - result = Address.parseAndPack(mCcView.getText().toString()); - expected = Address.parseAndPack(TO1 + ',' + TO2 + ',' + CC1 + ',' + CC3); - assertEquals(expected, result); - TestUtils.assertViewVisible(mCcView); - } - }); - } - - /** - * Check that we create the proper to and cc addressees in reply and reply-all, making sure - * to reject duplicate addressees AND the email address of the sending account - * - * In this case, we're doing a "reply all" - * The user is CC2 (a "cc" recipient) - * The to should be: FROM - * The cc should be: TO1, TO2, ,TO3, and CC3 (CC1/CC4 are duplicates; CC2 is the our - * account's email address) - */ - public void testReplyAllAddresses3() throws Throwable { - final MessageCompose a = getActivity(); - // Doesn't matter what Intent we use here - final Intent intent = new Intent(Intent.ACTION_VIEW); - Message msg = new Message(); - final Account account = new Account(); - - msg.mFrom = Address.parseAndPack(FROM); - msg.mTo = Address.parseAndPack(TO1 + ',' + TO2 + ',' + TO3); - msg.mCc = Address.parseAndPack(CC1 + ',' + CC2 + ',' + CC3 + ',' + CC4); - final Message message = msg; - account.mEmailAddress = "sEcOnD.cC@gOoGlE.cOm"; - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(intent); - a.setupAddressViews(message, account, true); - String result = Address.parseAndPack(mToView.getText().toString()); - String expected = Address.parseAndPack(FROM); - assertEquals(expected, result); - result = Address.parseAndPack(mCcView.getText().toString()); - expected = Address.parseAndPack(TO1 + ',' + TO2 + ',' + TO3+ ',' + CC3); - assertEquals(expected, result); - TestUtils.assertViewVisible(mCcView); - } - }); - } - - /** - * Test for processing of Intent EXTRA_* fields that impact the headers: - * Intent.EXTRA_EMAIL, Intent.EXTRA_CC, Intent.EXTRA_BCC, Intent.EXTRA_SUBJECT - */ - public void testIntentHeaderExtras() throws MessagingException, Throwable { - - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_EMAIL, new String[] { RECIPIENT_TO }); - intent.putExtra(Intent.EXTRA_CC, new String[] { RECIPIENT_CC }); - intent.putExtra(Intent.EXTRA_BCC, new String[] { RECIPIENT_BCC }); - intent.putExtra(Intent.EXTRA_SUBJECT, SUBJECT); - - final MessageCompose a = getActivity(); - final Intent i2 = new Intent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(i2); - checkFields(RECIPIENT_TO + ", ", RECIPIENT_CC + ", ", RECIPIENT_BCC + ", ", SUBJECT, - null, mSignature); - checkFocused(mMessageView); - } - }); - } - - /** - * Test for processing of Intent EXTRA_* fields that impact the headers with utf-16. - */ - public void testIntentHeaderExtrasWithUtf16() throws MessagingException, Throwable { - - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_EMAIL, new String[] { UTF16_RECIPIENT_TO }); - intent.putExtra(Intent.EXTRA_CC, new String[] { UTF16_RECIPIENT_CC }); - intent.putExtra(Intent.EXTRA_BCC, new String[] { UTF16_RECIPIENT_BCC }); - intent.putExtra(Intent.EXTRA_SUBJECT, UTF16_SUBJECT); - - final MessageCompose a = getActivity(); - final Intent i2 = new Intent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(i2); - checkFields(UTF16_RECIPIENT_TO + ", ", UTF16_RECIPIENT_CC + ", ", - UTF16_RECIPIENT_BCC + ", ", UTF16_SUBJECT, null, mSignature); - checkFocused(mMessageView); - } - }); - } - - /** - * Test for processing of Intent EXTRA_* fields that impact the headers with utf-32. - */ - public void testIntentHeaderExtrasWithUtf32() throws MessagingException, Throwable { - - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.putExtra(Intent.EXTRA_EMAIL, new String[] { UTF32_RECIPIENT_TO }); - intent.putExtra(Intent.EXTRA_CC, new String[] { UTF32_RECIPIENT_CC }); - intent.putExtra(Intent.EXTRA_BCC, new String[] { UTF32_RECIPIENT_BCC }); - intent.putExtra(Intent.EXTRA_SUBJECT, UTF32_SUBJECT); - - final MessageCompose a = getActivity(); - final Intent i2 = new Intent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(i2); - checkFields(UTF32_RECIPIENT_TO + ", ", UTF32_RECIPIENT_CC + ", ", - UTF32_RECIPIENT_BCC + ", ", UTF32_SUBJECT, null, mSignature); - checkFocused(mMessageView); - } - }); - } - - /** - * Test for processing of a typical browser "share" intent, e.g. - * type="text/plain", EXTRA_TEXT="http:link.server.com" - */ - public void testIntentSendPlainText() throws MessagingException, Throwable { - - Intent intent = new Intent(Intent.ACTION_SEND); - intent.setType("text/plain"); - intent.putExtra(Intent.EXTRA_TEXT, BODY); - - final MessageCompose a = getActivity(); - final Intent i2 = new Intent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(i2); - checkFields(null, null, null, null, BODY, mSignature); - checkFocused(mToView); - } - }); - } - - /** - * Test for processing of a typical browser Mailto intent, e.g. - * action=android.intent.action.VIEW - * categories={android.intent.category.BROWSABLE} - * data=mailto:user@domain.com?subject=This%20is%20%the%subject - */ - public void testBrowserMailToIntent() throws MessagingException, Throwable { - - Intent intent = new Intent(Intent.ACTION_VIEW); - Uri uri = Uri.parse("mailto:" + RECIPIENT_TO + "?subject=This%20is%20the%20subject"); - intent.setData(uri); - - final MessageCompose a = getActivity(); - final Intent i2 = new Intent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - a.initFromIntent(i2); - checkFields( - RECIPIENT_TO + ", ", null, null, "This is the subject", null, mSignature); - checkFocused(mMessageView); - } - }); - } - - /** - * TODO: test mailto: with simple encoding mode - * TODO: test mailto: URI with all optional fields - * TODO: come up with a way to add a very small attachment - * TODO: confirm the various details between handling of SEND, VIEW, SENDTO - */ - - /** - * Helper method to quickly check (and assert) on the to, subject, and content views. - * - * @param to expected value (null = it must be empty) - * @param cc expected value (null = it must be empty) - * @param bcc expected value (null = it must be empty) - * @param subject expected value (null = it must be empty) - * @param content expected value (null = it must be empty) - * @param signature expected value (null = it must be empty) - */ - private void checkFields(String to, String cc, String bcc, String subject, String content, - String signature) { - String toText = mToView.getText().toString(); - if (to == null) { - assertEquals(0, toText.length()); - } else { - assertEquals(to, toText); - TestUtils.assertViewVisible(mToView); - } - - String ccText = mCcView.getText().toString(); - if (cc == null) { - assertEquals(0, ccText.length()); - } else { - assertEquals(cc, ccText); - TestUtils.assertViewVisible(mCcView); - } - - String bccText = mBccView.getText().toString(); - if (bcc == null) { - assertEquals(0, bccText.length()); - } else { - assertEquals(bcc, bccText); - TestUtils.assertViewVisible(mBccView); - } - - String subjectText = mSubjectView.getText().toString(); - if (subject == null) { - assertEquals(0, subjectText.length()); - } else { - assertEquals(subject, subjectText); - } - - String contentText = mMessageView.getText().toString(); - if (content == null && signature == null) { - assertEquals(0, contentText.length()); - } else { - if (content == null) content = ""; - if (signature != null) { - int textLength = content.length(); - if (textLength == 0 || content.charAt(textLength - 1) != '\n') { - content += "\n"; - } - content += signature; - } - assertEquals(content, contentText); - } - } - - /** - * Helper method to verify which field has the focus - * @param focused The view that should be focused (all others should not have focus) - */ - private void checkFocused(View focused) { - assertEquals(focused == mToView, mToView.isFocused()); - assertEquals(focused == mSubjectView, mSubjectView.isFocused()); - assertEquals(focused == mMessageView, mMessageView.isFocused()); - } - - /** - * Helper used when running multiple calls to processSourceMessage within a test method. - * Simply clears out the views, so that we get fresh data and not appended data. - * - * Must call from UI thread. - */ - private void resetViews() { - mToView.setText(null); - mSubjectView.setText(null); - mMessageView.setText(null); - } - - /** - * Build a test message that can be used as input to processSourceMessage - * - * @param to Recipient(s) of the message - * @param sender Sender(s) of the message - * @param subject Subject of the message - * @param content Content of the message - * @return a complete Message object - */ - private Message buildTestMessage(String to, String sender, String subject, String content) { - Message message = new Message(); - - if (to != null) { - message.mTo = Address.parseAndPack(to); - } - - if (sender != null) { - Address[] addresses = Address.parse(sender); - assertTrue("from address", addresses.length > 0); - message.mFrom = addresses[0].pack(); - } - - message.mSubject = subject; - - if (content != null) { - message.mText = content; - } - - return message; - } - - /** - * Check AddressTextView email address validation. - */ - @UiThreadTest - public void testAddressTextView() { - MessageCompose messageCompose = getActivity(); - - mToView.setValidator(new EmailAddressValidator()); - mToView.setText("foo"); - mToView.performValidation(); - - // address is validated as errorneous - assertFalse(messageCompose.isAddressAllValid()); - - // the wrong address is preserved by validation - assertEquals("foo", mToView.getText().toString()); - - mToView.setText("a@b.c"); - mToView.performValidation(); - - // address is validated as correct - assertTrue(messageCompose.isAddressAllValid()); - - mToView.setText("a@b.c, foo"); - mToView.performValidation(); - - assertFalse(messageCompose.isAddressAllValid()); - assertEquals("a@b.c, foo", mToView.getText().toString()); - } - - /** - * Check message and selection with/without signature. - */ - public void testSetInitialComposeTextAndSelection() throws MessagingException, Throwable { - final Message msg = buildTestMessage(null, null, null, BODY); - final Intent intent = new Intent(ACTION_EDIT_DRAFT); - final Account account = new Account(); - final MessageCompose a = getActivity(); - a.setIntent(intent); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.setInitialComposeText(BODY, SIGNATURE); - checkFields(null, null, null, null, BODY, SIGNATURE); - a.setMessageContentSelection(SIGNATURE); - assertEquals(BODY.length(), mMessageView.getSelectionStart()); - } - }); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - a.setInitialComposeText(BODY, null); - checkFields(null, null, null, null, BODY, null); - a.setMessageContentSelection(null); - assertEquals(BODY.length(), mMessageView.getSelectionStart()); - } - }); - - runTestOnUiThread(new Runnable() { - public void run() { - resetViews(); - final String body2 = BODY + "\n\na\n\n"; - a.setInitialComposeText(body2, SIGNATURE); - checkFields(null, null, null, null, body2, SIGNATURE); - a.setMessageContentSelection(SIGNATURE); - assertEquals(BODY.length() + 3, mMessageView.getSelectionStart()); - } - }); - - } - - private static int sAttachmentId = 1; - private Attachment makeAttachment(String filename) { - Attachment a = new Attachment(); - a.mId = sAttachmentId++; - a.mFileName = filename; - return a; - } - - @SmallTest - public void testSourceAttachmentsProcessing() { - // Attachments currently in the draft. - ArrayList currentAttachments = Lists.newArrayList( - makeAttachment("a.png"), makeAttachment("b.png")); - - // Attachments in the message being forwarded. - Attachment c = makeAttachment("c.png"); - Attachment d = makeAttachment("d.png"); - ArrayList sourceAttachments = Lists.newArrayList(c, d); - - // Ensure the source attachments gets added. - final MessageCompose a = getActivity(); - a.processSourceMessageAttachments(currentAttachments, sourceAttachments, true /*include*/); - - assertEquals(4, currentAttachments.size()); - assertTrue(currentAttachments.contains(c)); - assertTrue(currentAttachments.contains(d)); - - // Now ensure they can be removed (e.g. in the case of switching from forward to reply). - a.processSourceMessageAttachments(currentAttachments, sourceAttachments, false /*include*/); - assertEquals(2, currentAttachments.size()); - assertFalse(currentAttachments.contains(c)); - assertFalse(currentAttachments.contains(d)); - } +public class MessageComposeTests extends AndroidTestCase { } diff --git a/tests/src/com/android/email/activity/MessageFileViewTest.java b/tests/src/com/android/email/activity/MessageFileViewTest.java deleted file mode 100644 index 0b193425d..000000000 --- a/tests/src/com/android/email/activity/MessageFileViewTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.email.DBTestHelper; -import com.android.email.TestUtils; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.EmailContent.Message; - -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.test.ActivityInstrumentationTestCase2; - -/** - * Test case for {@link MessageFileView}. - * - * TODO Add more tests. Any good way to test fragment?? - */ -public class MessageFileViewTest extends ActivityInstrumentationTestCase2 { - - private static int TIMEOUT = 10; // in seconds - - private Context mProviderContext; - - public MessageFileViewTest() { - super(MessageFileView.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( - getInstrumentation().getTargetContext()); - } - - private void setUpIntent(Uri uri) { - final Intent i = new Intent(getInstrumentation().getTargetContext(), MessageFileView.class); - i.setData(uri); - setActivityIntent(i); - } - - private Uri createEmlFile() throws Exception { - // Create a simple message - Message msg = new Message(); - String text = "This is some text"; - msg.mText = text; - String sender = "sender@host.com"; - msg.mFrom = sender; - // Save this away - msg.save(mProviderContext); - - return ProviderTestUtils.createTempEmlFile(mProviderContext, msg, - getInstrumentation().getContext().getFilesDir()); - } - - /** - * Set up an EML file, and open it in the activity. - * - * Expected: Message opens. - */ - public void testOpenMessage() throws Exception { - setUpIntent(createEmlFile()); - - final MessageFileView activity = getActivity(); - - TestUtils.waitUntil(new TestUtils.Condition() { - @Override - public boolean isMet() { - MessageFileViewFragment f = activity.getFragment(); - return f != null && f.isMessageLoadedForTest(); - } - }, TIMEOUT); - - // TODO Check UI elements, once our UI is settled. - } - -} diff --git a/tests/src/com/android/email/activity/MessageListTests.java b/tests/src/com/android/email/activity/MessageListTests.java deleted file mode 100644 index 76d921dcc..000000000 --- a/tests/src/com/android/email/activity/MessageListTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.email.DBTestHelper; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; - -import android.content.Context; -import android.content.Intent; -import android.test.AndroidTestCase; - -public class MessageListTests extends AndroidTestCase { - - private Context mMockContext; - - public MessageListTests() { - } - - @Override - public void setUp() throws Exception { - super.setUp(); - - // ProviderTestCase2 can't be used. It creates a mock context that doesn't support - // some methods we need here, such as getPackageName. - mMockContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( - getContext()); - } - - public void testGetAccountFromIntent() { - final Context c = mMockContext; - final Account a1 = ProviderTestUtils.setupAccount("a1", true, c); - final Account a2 = ProviderTestUtils.setupAccount("a2", true, c); - - assertEquals(a1.mId, MessageList.getAccountFromIntent(c, - MessageList.createFroyoIntent(c, a1))); - assertEquals(a2.mId, MessageList.getAccountFromIntent(c, - MessageList.createFroyoIntent(c, a2))); - - // Mixed -- UUID in the URI doesn't match the account ID in extra. - // It's a test for shortcuts for restored accounts. - final Intent i = MessageList.createFroyoIntent(c, a2); - i.putExtra(MessageList.EXTRA_ACCOUNT_ID, 12345); - assertEquals(a2.mId, MessageList.getAccountFromIntent(c, i)); - - // Invalid intent -- no extra, no URI. - assertEquals(Account.NO_ACCOUNT, MessageList.getAccountFromIntent(c, - new Intent(c, MessageList.class))); - } -} diff --git a/tests/src/com/android/email/activity/MessageOrderManagerTest.java b/tests/src/com/android/email/activity/MessageOrderManagerTest.java deleted file mode 100644 index da78627c2..000000000 --- a/tests/src/com/android/email/activity/MessageOrderManagerTest.java +++ /dev/null @@ -1,402 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import android.content.Context; -import android.database.AbstractCursor; -import android.database.Cursor; -import android.os.Handler; -import android.test.ProviderTestCase2; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.email.MessageListContext; -import com.android.email.provider.EmailProvider; -import com.android.emailcommon.provider.EmailContent; -import com.android.emailcommon.utility.DelayedOperations; - -import junit.framework.Assert; - -@SmallTest -public class MessageOrderManagerTest extends ProviderTestCase2 { - - private MyCallback mCallback; - - @Override protected void setUp() throws Exception { - super.setUp(); - mCallback = new MyCallback(); - } - - public MessageOrderManagerTest() { - super(EmailProvider.class, EmailContent.AUTHORITY); - } - - private static void assertCanMove(MessageOrderManager mom, boolean newer, boolean older) { - Assert.assertEquals(older, mom.canMoveToOlder()); - Assert.assertEquals(newer, mom.canMoveToNewer()); - } - - public void testBasic() { - MessageOrderManagerForTest mom = new MessageOrderManagerForTest(getContext(), 1, mCallback); - mom.assertStartQueryCalledAndReset(); - - // moveTo not called, so it returns -1 - assertEquals(-1, mom.getCurrentMessageId()); - - // Task not finished, so all returns false. - assertCanMove(mom, false, false); - assertFalse(mom.moveToNewer()); - assertFalse(mom.moveToOlder()); - - // Set current message - mom.moveTo(54); - assertEquals(54, mom.getCurrentMessageId()); - - // Task still not finished, so all returns false. - assertCanMove(mom, false, false); - assertFalse(mom.moveToNewer()); - assertFalse(mom.moveToOlder()); - - // Both callbacks shouldn't have called. - mCallback.assertCallbacksCalled(false, false); - - // Cursor not open yet, so these are both 0. - assertEquals(0, mom.getCurrentPosition()); - assertEquals(0, mom.getTotalMessageCount()); - } - - /** - * Test with actual message list. - * - * In this test, {@link MessageOrderManager#moveTo} is called AFTER the cursor opens. - */ - public void testWithList() { - MessageOrderManagerForTest mom = new MessageOrderManagerForTest(getContext(), 1, mCallback); - mom.assertStartQueryCalledAndReset(); - - // Callback not called yet. - mCallback.assertCallbacksCalled(false, false); - - // Inject mock cursor. (Imitate async query done.) - MyCursor cursor = new MyCursor(11, 22, 33, 44); // Newer to older - mom.onCursorOpenDone(cursor); - - assertEquals(0, mom.getCurrentPosition()); - assertEquals(4, mom.getTotalMessageCount()); - - // Current message id not set yet, so callback should have called yet. - mCallback.assertCallbacksCalled(false, false); - - // Set current message id -- now onMessagesChanged() should get called. - mom.moveTo(22); - assertEquals(1, mom.getCurrentPosition()); - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - - // Move to row 1 - assertTrue(mom.moveToNewer()); - assertEquals(0, mom.getCurrentPosition()); - assertEquals(11, mom.getCurrentMessageId()); - assertCanMove(mom, false, true); - mCallback.assertCallbacksCalled(true, false); - - // Try to move to newer, but no newer messages - assertFalse(mom.moveToNewer()); - assertEquals(0, mom.getCurrentPosition()); - assertEquals(11, mom.getCurrentMessageId()); // Still row 1 - mCallback.assertCallbacksCalled(false, false); - - // Move to row 2 - assertTrue(mom.moveToOlder()); - assertEquals(1, mom.getCurrentPosition()); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - mCallback.assertCallbacksCalled(true, false); - - // Move to row 3 - assertTrue(mom.moveToOlder()); - assertEquals(2, mom.getCurrentPosition()); - assertEquals(33, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - mCallback.assertCallbacksCalled(true, false); - - // Move to row 4 - assertTrue(mom.moveToOlder()); - assertEquals(3, mom.getCurrentPosition()); - assertEquals(44, mom.getCurrentMessageId()); - assertCanMove(mom, true, false); - mCallback.assertCallbacksCalled(true, false); - - // Try to move older, but no Older messages - assertFalse(mom.moveToOlder()); - assertEquals(3, mom.getCurrentPosition()); - mCallback.assertCallbacksCalled(false, false); - - // Move to row 3 - assertTrue(mom.moveToNewer()); - assertEquals(2, mom.getCurrentPosition()); - assertEquals(33, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - mCallback.assertCallbacksCalled(true, false); - } - - /** - * Test with actual message list. - * - * In this test, {@link MessageOrderManager#moveTo} is called BEFORE the cursor opens. - */ - public void testWithList2() { - MessageOrderManagerForTest mom = new MessageOrderManagerForTest(getContext(), 1, mCallback); - mom.assertStartQueryCalledAndReset(); - - // Callback not called yet. - mCallback.assertCallbacksCalled(false, false); - - mom.moveTo(22); - mCallback.assertCallbacksCalled(false, false); // Cursor not open, callback not called yet. - assertEquals(22, mom.getCurrentMessageId()); - - // cursor not open yet - assertEquals(0, mom.getCurrentPosition()); - assertEquals(0, mom.getTotalMessageCount()); - - // Inject mock cursor. (Imitate async query done.) - MyCursor cursor = new MyCursor(11, 22, 33, 44); // Newer to older - mom.onCursorOpenDone(cursor); - - // As soon as the cursor opens, callback gets called. - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - - assertEquals(1, mom.getCurrentPosition()); - assertEquals(4, mom.getTotalMessageCount()); - } - - public void testContentChanged() { - MessageOrderManagerForTest mom = new MessageOrderManagerForTest(getContext(), 1, mCallback); - - // Inject mock cursor. (Imitate async query done.) - MyCursor cursor = new MyCursor(11, 22, 33, 44); // Newer to older - mom.onCursorOpenDone(cursor); - - // Move to 22 - mom.moveTo(22); - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - - // Delete 33 - mom.updateMessageList(11, 22, 44); - - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - - // Delete 44 - mom.updateMessageList(11, 22); - - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, true, false); // Can't move to older - - // Append 55 - mom.updateMessageList(11, 22, 55); - - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, true, true); - - // Delete 11 - mom.updateMessageList(22, 55); - - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, false, true); - - // Delete 55 - mom.updateMessageList(22); - - mCallback.assertCallbacksCalled(true, false); - assertEquals(22, mom.getCurrentMessageId()); - assertCanMove(mom, false, false); // Can't move either way - - // Delete 22 -- no messages left. - mom.updateMessageList(); - mCallback.assertCallbacksCalled(false, true); - - // Test for the case where list is not empty, but the current message is gone. - // First, set up a list with 22 as the current message. - mom.updateMessageList(11, 22, 33, 44); - mom.moveTo(22); - assertEquals(22, mom.getCurrentMessageId()); - mCallback.assertCallbacksCalled(true, false); - - // Then remove the current message. - mom.updateMessageList(11, 33, 44); - mCallback.assertCallbacksCalled(false, true); - } - - /** - * Test using the actual {@link MessageOrderManager} rather than - * {@link MessageOrderManagerForTest}. - */ - public void testWithActualClass() { - // There are not many things we can test synchronously. - // Just open & close just to make sure it won't crash. - MessageOrderManager mom = new MessageOrderManager( - getContext(), MessageListContext.forMailbox(1, 1), new MyCallback()); - mom.moveTo(123); - mom.close(); - } - - private static class MyCallback implements MessageOrderManager.Callback { - public boolean mCalledOnMessageNotFound; - public boolean mCalledOnMessagesChanged; - - @Override public void onMessagesChanged() { - mCalledOnMessagesChanged = true; - } - - @Override public void onMessageNotFound() { - mCalledOnMessageNotFound = true; - } - - /** - * Asserts that the callbacks have/have not been called, and reset the flags. - */ - public void assertCallbacksCalled(boolean messagesChanged, boolean messageNotFound) { - assertEquals(messagesChanged, mCalledOnMessagesChanged); - assertEquals(messageNotFound, mCalledOnMessageNotFound); - - mCalledOnMessagesChanged = false; - mCalledOnMessageNotFound = false; - } - } - - /** - * "Non" delayed operation -- runs the runnable immediately - */ - private static final class NonDelayedOperations extends DelayedOperations { - public NonDelayedOperations() { - super(new Handler()); - } - - @Override - public void post(Runnable r) { - r.run(); - } - } - - /** - * MessageOrderManager for test. Overrides {@link #startQuery} - */ - private static class MessageOrderManagerForTest extends MessageOrderManager { - private Cursor mLastCursor; - public boolean mStartQueryCalled; - - public MessageOrderManagerForTest(Context context, long mailboxId, Callback callback) { - super(context, MessageListContext.forMailbox(1, mailboxId), - callback, new NonDelayedOperations()); - } - - @Override void startQuery() { - // To make tests synchronous, we replace this method. - mStartQueryCalled = true; - } - - @Override /* package */ Handler getHandlerForContentObserver() { - return null; - } - - @Override void onCursorOpenDone(Cursor cursor) { - super.onCursorOpenDone(cursor); - mLastCursor = cursor; - } - - /** - * Utility method to emulate data set changed. - */ - public void updateMessageList(long... idList) { - assertNotNull(mLastCursor); // Make sure a cursor is set. - - // Notify dataset change -- it should end up startQuery() gets called. - ((MyCursor) mLastCursor).notifyChanged(); - assertStartQueryCalledAndReset(); // Start - - // Set a new cursor with a new list. - onCursorOpenDone(new MyCursor(idList)); - } - - public void assertStartQueryCalledAndReset() { - assertTrue(mStartQueryCalled); - mStartQueryCalled = false; - } - } - - private static class MyCursor extends AbstractCursor { - private final long[] mList; - - public MyCursor(long... idList) { - mList = (idList == null) ? new long[0] : idList; - } - - public void notifyChanged() { - onChange(false); - } - - @Override public int getColumnCount() { - return 1; - } - - @Override public int getCount() { - return mList.length; - } - - @Override public String[] getColumnNames() { - return new String[] {EmailContent.RECORD_ID}; - } - - @Override public long getLong(int columnIndex) { - Assert.assertEquals(EmailContent.ID_PROJECTION_COLUMN, columnIndex); - return mList[mPos]; - } - - @Override public double getDouble(int column) { - throw new junit.framework.AssertionFailedError(); - } - - @Override public float getFloat(int column) { - throw new junit.framework.AssertionFailedError(); - } - - @Override public int getInt(int column) { - throw new junit.framework.AssertionFailedError(); - } - - @Override public short getShort(int column) { - throw new junit.framework.AssertionFailedError(); - } - - @Override public String getString(int column) { - throw new junit.framework.AssertionFailedError(); - } - - @Override public boolean isNull(int column) { - throw new junit.framework.AssertionFailedError(); - } - } -} diff --git a/tests/src/com/android/email/activity/MessagesAdapterTests.java b/tests/src/com/android/email/activity/MessagesAdapterTests.java deleted file mode 100644 index c1a91d827..000000000 --- a/tests/src/com/android/email/activity/MessagesAdapterTests.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import android.content.Context; -import android.test.LoaderTestCase; - -import com.android.email.DBTestHelper; -import com.android.email.MessageListContext; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.Mailbox; - -public class MessagesAdapterTests extends LoaderTestCase { - // Account ID that's probably not in the database. - private static final long NO_SUCH_ACCOUNT_ID = 1234567890123L; - - // Mailbox ID that's probably not in the database. - private static final long NO_SUCH_MAILBOX_ID = 1234567890123L; - - // Isolated Context for providers. - private Context mProviderContext; - - @Override - protected void setUp() throws Exception { - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext(getContext()); - } - - private long createAccount(boolean isEas) { - Account acct = ProviderTestUtils.setupAccount("acct1", false, mProviderContext); - String proto = isEas ? "eas" : "non-eas"; - acct.mHostAuthRecv = - ProviderTestUtils.setupHostAuth(proto, "hostauth", true, mProviderContext); - acct.mHostAuthKeyRecv = acct.mHostAuthRecv.mId; - acct.save(mProviderContext); - return acct.mId; - } - - private long createMailbox(long accountId, int type) { - Mailbox box = ProviderTestUtils.setupMailbox("name", accountId, false, mProviderContext); - box.mType = type; - box.save(mProviderContext); - return box.mId; - } - - private MessagesAdapter.MessagesCursor getLoaderResult(long accountId, long mailboxId) { - return (MessagesAdapter.MessagesCursor) getLoaderResultSynchronously( - MessagesAdapter.createLoader( - mProviderContext, - MessageListContext.forMailbox(accountId, mailboxId))); - } - - /** - * Test for normal case. (account, mailbox found) - */ - public void testLoad() { - final long accountId = createAccount(false); - final long mailboxId = createMailbox(accountId, Mailbox.TYPE_MAIL); - - MessagesAdapter.MessagesCursor result = getLoaderResult(accountId, mailboxId); - assertTrue(result.mIsFound); - assertEquals(accountId, result.mAccount.mId); - assertEquals(mailboxId, result.mMailbox.mId); - assertFalse(result.mIsEasAccount); - assertTrue(result.mIsRefreshable); - } - - /** - * Load -- isEas = true - */ - public void testLoadEas() { - final long accountId = createAccount(true); - final long mailboxId = createMailbox(accountId, Mailbox.TYPE_MAIL); - - MessagesAdapter.MessagesCursor result = getLoaderResult(accountId, mailboxId); - assertTrue(result.mIsFound); - assertEquals(accountId, result.mAccount.mId); - assertEquals(mailboxId, result.mMailbox.mId); - assertTrue(result.mIsEasAccount); - assertTrue(result.mIsRefreshable); - } - - /** - * Load -- drafts, not refreshable. - */ - public void testLoadNotRefreshable() { - final long accountId = createAccount(false); - final long mailboxId = createMailbox(accountId, Mailbox.TYPE_DRAFTS); - - MessagesAdapter.MessagesCursor result = getLoaderResult(accountId, mailboxId); - assertTrue(result.mIsFound); - assertEquals(accountId, result.mAccount.mId); - assertEquals(mailboxId, result.mMailbox.mId); - assertFalse(result.mIsEasAccount); - assertFalse(result.mIsRefreshable); - } - - /** - * Mailbox not found. - */ - public void testMailboxNotFound() { - MessagesAdapter.MessagesCursor result = getLoaderResult( - createAccount(false), NO_SUCH_MAILBOX_ID); - assertFalse(result.mIsFound); - assertNull(result.mAccount); - assertNull(result.mMailbox); - assertFalse(result.mIsEasAccount); - assertFalse(result.mIsRefreshable); - } - - /** - * Account not found. - */ - public void testAccountNotFound() { - final long mailboxId = createMailbox(NO_SUCH_ACCOUNT_ID, Mailbox.TYPE_MAIL); - - MessagesAdapter.MessagesCursor result = getLoaderResult(NO_SUCH_ACCOUNT_ID, mailboxId); - assertFalse(result.mIsFound); - assertNull(result.mAccount); - assertNull(result.mMailbox); - assertFalse(result.mIsEasAccount); - assertFalse(result.mIsRefreshable); - } - - /** - * Magic mailbox. (always found) - */ - public void testMagicMailbox() { - MessagesAdapter.MessagesCursor result = getLoaderResult( - Account.ACCOUNT_ID_COMBINED_VIEW, Mailbox.QUERY_ALL_INBOXES); - assertTrue(result.mIsFound); - assertNull(result.mAccount); - assertNull(result.mMailbox); - assertFalse(result.mIsEasAccount); - assertFalse(result.mIsRefreshable); - } -} diff --git a/tests/src/com/android/email/activity/RecentMailboxManagerTest.java b/tests/src/com/android/email/activity/RecentMailboxManagerTest.java deleted file mode 100644 index f24df816d..000000000 --- a/tests/src/com/android/email/activity/RecentMailboxManagerTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import android.content.ContentValues; -import android.content.Context; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; - -import com.android.email.Controller; -import com.android.email.DBTestHelper; -import com.android.email.MockClock; -import com.android.email.provider.ContentCache; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.EmailContent.MailboxColumns; -import com.android.emailcommon.provider.Mailbox; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -/** - * Tests for the recent mailbox manager. - * - * You can run this entire test case with: - * runtest -c com.android.email.activity.RecentMailboxManagerTest email - */ -@MediumTest -public class RecentMailboxManagerTest extends AndroidTestCase { - - private Context mMockContext; - private MockClock mMockClock; - private RecentMailboxManager mManager; - private Mailbox[] mMailboxArray; - - public RecentMailboxManagerTest() { - } - - @Override - public void setUp() throws Exception { - super.setUp(); - mMockContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( - getContext()); - mMockClock = new MockClock(); - RecentMailboxManager.sClock = mMockClock; - mManager = RecentMailboxManager.getInstance(mMockContext); - Controller.getInstance(mMockContext).setProviderContext(mMockContext); - mMailboxArray = new Mailbox[] { - ProviderTestUtils.setupMailbox("inbox", 1L, true, mMockContext, Mailbox.TYPE_INBOX), - ProviderTestUtils.setupMailbox("drafts", 1L, true, mMockContext, Mailbox.TYPE_DRAFTS), - ProviderTestUtils.setupMailbox("outbox", 1L, true, mMockContext, Mailbox.TYPE_OUTBOX), - ProviderTestUtils.setupMailbox("sent", 1L, true, mMockContext, Mailbox.TYPE_SENT), - ProviderTestUtils.setupMailbox("trash", 1L, true, mMockContext, Mailbox.TYPE_TRASH), - ProviderTestUtils.setupMailbox("junk", 1L, true, mMockContext, Mailbox.TYPE_JUNK), - ProviderTestUtils.setupMailbox("abbott", 1L, true, mMockContext, Mailbox.TYPE_MAIL), - ProviderTestUtils.setupMailbox("costello", 1L, true, mMockContext, Mailbox.TYPE_MAIL), - ProviderTestUtils.setupMailbox("bud_lou", 1L, true, mMockContext, Mailbox.TYPE_MAIL), - ProviderTestUtils.setupMailbox("laurel", 1L, true, mMockContext, Mailbox.TYPE_MAIL), - ProviderTestUtils.setupMailbox("hardy", 1L, true, mMockContext, Mailbox.TYPE_MAIL) - }; - // Invalidate all caches, since we reset the database for each test - ContentCache.invalidateAllCaches(); - } - - @Override - protected void tearDown() throws Exception { - RecentMailboxManager.sInstance = null; - super.tearDown(); - } - - public void testTouch() throws Exception { - Set defaultRecents = new HashSet() {{ - for (int type : RecentMailboxManager.DEFAULT_RECENT_TYPES) { - add(type); - } - }}; - - // Ensure all accounts can be touched - for (Mailbox mailbox : mMailboxArray) { - // Safety ... default touch time - Mailbox untouchedMailbox = Mailbox.restoreMailboxWithId(mMockContext, mailbox.mId); - if (!defaultRecents.contains(mailbox.mType)) { - assertEquals(0L, untouchedMailbox.mLastTouchedTime); - } - - // Touch the mailbox - mManager.touch(1L, mailbox.mId).get(); - - // Touch time is actually set - Mailbox touchedMailbox = Mailbox.restoreMailboxWithId(mMockContext, mailbox.mId); - assertEquals(mMockClock.getTime(), touchedMailbox.mLastTouchedTime); - - mMockClock.advance(1000L); - } - // Now ensure touching one didn't affect the others - long touchTime = MockClock.DEFAULT_TIME; - for (Mailbox mailbox : mMailboxArray) { - // Touch time is actually set - Mailbox touchedMailbox = Mailbox.restoreMailboxWithId(mMockContext, mailbox.mId); - assertEquals(touchTime, touchedMailbox.mLastTouchedTime); - touchTime += 1000L; - } - } - - /** Test default list */ - public void testGetMostRecent01() throws Exception { - ArrayList testList; - - // test default list - // With exclusions - testList = mManager.getMostRecent(1L, true); - assertEquals("w/ exclusions", 0, testList.size()); - - // Without exclusions -- we'll get "default" list. - testList = mManager.getMostRecent(1L, false); - assertEquals("w/o exclusions", 2, testList.size()); - - assertEquals(mMailboxArray[1].mId, (long) testList.get(0)); // Drafts - assertEquals(mMailboxArray[3].mId, (long) testList.get(1)); // Sent - } - - /** Test recent list not full */ - public void testGetMostRecent02() throws Exception { - ArrayList testList; - // need to wait for the last one to ensure getMostRecent() has something to work on - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[7].mId).get(); // costello - - // test recent list not full, so is padded with default mailboxes - testList = mManager.getMostRecent(1L, false); - assertEquals(3, testList.size()); - assertEquals(mMailboxArray[7].mId, (long) testList.get(0)); // costello - assertEquals(mMailboxArray[1].mId, (long) testList.get(1)); // Drafts - assertEquals(mMailboxArray[3].mId, (long) testList.get(2)); // Sent - testList = mManager.getMostRecent(1L, true); - assertEquals(1, testList.size()); - assertEquals(mMailboxArray[7].mId, (long) testList.get(0)); - } - - /** Test full recent list */ - public void testGetMostRecent03() throws Exception { - ArrayList testList; - - // touch some more mailboxes - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[3].mId); // sent - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[4].mId); // trash - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[2].mId); // outbox - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[8].mId); // bud_lou - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[7].mId); // costello - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[9].mId).get(); // laurel - - // test full recent list - testList = mManager.getMostRecent(1L, false); - assertEquals(5, testList.size()); - assertEquals(mMailboxArray[8].mId, (long) testList.get(0)); // bud_lou - assertEquals(mMailboxArray[7].mId, (long) testList.get(1)); // costello - assertEquals(mMailboxArray[9].mId, (long) testList.get(2)); // laurel - assertEquals(mMailboxArray[2].mId, (long) testList.get(3)); // outbox - assertEquals(mMailboxArray[4].mId, (long) testList.get(4)); // trash - testList = mManager.getMostRecent(1L, true); - assertEquals(3, testList.size()); - assertEquals(mMailboxArray[8].mId, (long) testList.get(0)); - assertEquals(mMailboxArray[7].mId, (long) testList.get(1)); - assertEquals(mMailboxArray[9].mId, (long) testList.get(2)); - } - - /** Test limit for system mailboxes */ - public void testGetMostRecent04() throws Exception { - ArrayList testList; - - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[0].mId); // inbox - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[1].mId); // drafts - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[2].mId); // outbox - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[3].mId); // sent - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[4].mId).get(); // trash - - // nothing but system mailboxes, but inbox is never included - testList = mManager.getMostRecent(1L, false); - assertEquals(4, testList.size()); - assertEquals(mMailboxArray[1].mId, (long) testList.get(0)); - assertEquals(mMailboxArray[2].mId, (long) testList.get(1)); - assertEquals(mMailboxArray[3].mId, (long) testList.get(2)); - assertEquals(mMailboxArray[4].mId, (long) testList.get(3)); - testList = mManager.getMostRecent(1L, true); - assertEquals(0, testList.size()); - } - - /** Test limit for user mailboxes */ - public void testGetMostRecent05() throws Exception { - ArrayList testList; - - // test limit for the filtered list - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[6].mId); // abbott - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[7].mId); // costello - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[8].mId); // bud_lou - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[9].mId); // laurel - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[10].mId); // hardy - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[1].mId); // drafts - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[2].mId); // outbox - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[3].mId); // sent - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[4].mId); // trash - mMockClock.advance(1000L); mManager.touch(1L, mMailboxArray[5].mId).get(); // junk - - // nothing but user mailboxes - testList = mManager.getMostRecent(1L, false); - assertEquals(5, testList.size()); - assertEquals(mMailboxArray[1].mId, (long) testList.get(0)); - assertEquals(mMailboxArray[5].mId, (long) testList.get(1)); - assertEquals(mMailboxArray[2].mId, (long) testList.get(2)); - assertEquals(mMailboxArray[3].mId, (long) testList.get(3)); - assertEquals(mMailboxArray[4].mId, (long) testList.get(4)); - testList = mManager.getMostRecent(1L, true); - assertEquals(5, testList.size()); - assertEquals(mMailboxArray[6].mId, (long) testList.get(0)); - assertEquals(mMailboxArray[8].mId, (long) testList.get(1)); - assertEquals(mMailboxArray[7].mId, (long) testList.get(2)); - assertEquals(mMailboxArray[10].mId, (long) testList.get(3)); - assertEquals(mMailboxArray[9].mId, (long) testList.get(4)); - } - - public void testDoesNotIncludeExtraMailboxes() throws Exception { - ArrayList testList; - - // The search mailbox should not be visible. - Mailbox searchMailbox = ProviderTestUtils.setupMailbox( - "search", 1L, true, mMockContext, Mailbox.TYPE_SEARCH); - ContentValues cv = new ContentValues(); - cv.put(MailboxColumns.FLAG_VISIBLE, false); - searchMailbox.mFlagVisible = false; - searchMailbox.update(mMockContext, cv); - - mMockClock.advance(1000L); mManager.touch(1L, searchMailbox.mId).get(); - - // Ensure search mailbox isn't returned - testList = mManager.getMostRecent(1L, false); - assertFalse(testList.contains(searchMailbox.mId)); - testList = mManager.getMostRecent(1L, true); - assertFalse(testList.contains(searchMailbox.mId)); - } -} diff --git a/tests/src/com/android/email/activity/UIControllerTwoPaneRefreshTaskTest.java b/tests/src/com/android/email/activity/UIControllerTwoPaneRefreshTaskTest.java deleted file mode 100644 index 5adb16bea..000000000 --- a/tests/src/com/android/email/activity/UIControllerTwoPaneRefreshTaskTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.mail.utils.Clock; -import com.android.email.Controller; -import com.android.email.MockClock; -import com.android.email.RefreshManager; - -import android.content.Context; -import android.os.Handler; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import junit.framework.Assert; - -/** - * Tests for {@link UIControllerTwoPane.RefreshTask}. - * - * TOOD Add more tests. - * Right now, it only has tests for the "shouldXxx" methods, because it's hard to notice when - * they're subtly broken. (And the spec may change.) - */ -@SmallTest -public class UIControllerTwoPaneRefreshTaskTest extends AndroidTestCase { - private MockClock mClock = new MockClock(); - private MockRefreshManager mRefreshManager; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mRefreshManager = new MockRefreshManager(getContext(), Controller.getInstance(getContext()), - mClock, null); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - mRefreshManager.cleanUpForTest(); - } - - public void testShouldRefreshMailboxList() { - final long ACCOUNT_ID = 5; - final long MAILBOX_ID = 10; - - UIControllerTwoPane.RefreshTask task = new UIControllerTwoPane.RefreshTask(null, - getContext(), ACCOUNT_ID, MAILBOX_ID, mClock, mRefreshManager); - - mRefreshManager.mExpectedAccountId = ACCOUNT_ID; - - mClock.mTime = 123456789; - - // Not refreshing, never refreshed == should sync - mRefreshManager.mIsMailboxListRefreshing = false; - mRefreshManager.mLastMailboxListRefresTime = 0; - assertTrue(task.shouldRefreshMailboxList()); - - // IS refreshing, never refreshed == should NOT sync - mRefreshManager.mIsMailboxListRefreshing = true; - mRefreshManager.mLastMailboxListRefresTime = 0; - assertFalse(task.shouldRefreshMailboxList()); - - // Not refreshing, just refreshed == should NOT sync - mRefreshManager.mIsMailboxListRefreshing = false; - mRefreshManager.mLastMailboxListRefresTime = 1234567890; - mClock.mTime = mRefreshManager.mLastMailboxListRefresTime; - assertFalse(task.shouldRefreshMailboxList()); - - // Not refreshing, refreshed 1 ms ago == should NOT sync - mRefreshManager.mLastMailboxListRefresTime = 1234567890; - mClock.mTime = mRefreshManager.mLastMailboxListRefresTime + 1; - assertFalse(task.shouldRefreshMailboxList()); - - // Not refreshing, refreshed TIMEOUT-1 ago == should NOT sync - mRefreshManager.mLastMailboxListRefresTime = 1234567890; - mClock.mTime = mRefreshManager.mLastMailboxListRefresTime - + UIControllerTwoPane.MAILBOX_REFRESH_MIN_INTERVAL - 1; - assertFalse(task.shouldRefreshMailboxList()); - - // 1 ms laster... should sync. - mClock.advance(); - assertTrue(task.shouldRefreshMailboxList()); - } - - public void testShouldAutoRefreshInbox() { - final long ACCOUNT_ID = 5; - final long MAILBOX_ID = 10; - - UIControllerTwoPane.RefreshTask task = new UIControllerTwoPane.RefreshTask(null, - getContext(), ACCOUNT_ID, MAILBOX_ID, mClock, mRefreshManager); - - mRefreshManager.mExpectedAccountId = ACCOUNT_ID; - - mClock.mTime = 123456789; - - // Current mailbox != inbox, not refreshing, never refreshed == should sync - mRefreshManager.mIsMessageListRefreshing = false; - mRefreshManager.mLastMessageListRefresTime = 0; - task.mInboxId = MAILBOX_ID + 1; - mRefreshManager.mExpectedMailboxId = MAILBOX_ID + 1; - assertTrue(task.shouldAutoRefreshInbox()); - - // Current mailbox == inbox should NOT sync. - task.mInboxId = MAILBOX_ID; - mRefreshManager.mExpectedMailboxId = MAILBOX_ID; - assertFalse(task.shouldAutoRefreshInbox()); - - // Fron here, Current mailbox != inbox - task.mInboxId = MAILBOX_ID + 1; - mRefreshManager.mExpectedMailboxId = MAILBOX_ID + 1; - - // IS refreshing, never refreshed == should NOT sync - mRefreshManager.mIsMessageListRefreshing = true; - mRefreshManager.mLastMessageListRefresTime = 0; - assertFalse(task.shouldAutoRefreshInbox()); - - // Not refreshing, just refreshed == should NOT sync - mRefreshManager.mIsMessageListRefreshing = false; - mRefreshManager.mLastMessageListRefresTime = 1234567890; - mClock.mTime = mRefreshManager.mLastMessageListRefresTime; - assertFalse(task.shouldAutoRefreshInbox()); - - // Not refreshing, refreshed 1 ms ago == should NOT sync - mRefreshManager.mLastMessageListRefresTime = 1234567890; - mClock.mTime = mRefreshManager.mLastMessageListRefresTime + 1; - assertFalse(task.shouldAutoRefreshInbox()); - - // Not refreshing, refreshed TIMEOUT-1 ago == should NOT sync - mRefreshManager.mLastMessageListRefresTime = 1234567890; - mClock.mTime = mRefreshManager.mLastMessageListRefresTime - + UIControllerTwoPane.INBOX_AUTO_REFRESH_MIN_INTERVAL - 1; - assertFalse(task.shouldAutoRefreshInbox()); - - // 1 ms laster... should sync. - mClock.advance(); - assertTrue(task.shouldAutoRefreshInbox()); - } - - private static class MockRefreshManager extends RefreshManager { - public long mExpectedAccountId; - public long mExpectedMailboxId; - public boolean mIsMailboxListRefreshing; - public long mLastMailboxListRefresTime; - public boolean mIsMessageListRefreshing; - public long mLastMessageListRefresTime; - - protected MockRefreshManager( - Context context, Controller controller, Clock clock, Handler handler) { - super(context, controller, clock, handler); - } - - @Override - public boolean isMailboxListRefreshing(long accountId) { - Assert.assertEquals(mExpectedAccountId, accountId); - return mIsMailboxListRefreshing; - } - - @Override - public long getLastMailboxListRefreshTime(long accountId) { - Assert.assertEquals(mExpectedAccountId, accountId); - return mLastMailboxListRefresTime; - } - - @Override - public boolean isMessageListRefreshing(long mailboxId) { - Assert.assertEquals(mExpectedMailboxId, mailboxId); - return mIsMessageListRefreshing; - } - - @Override - public long getLastMessageListRefreshTime(long mailboxId) { - Assert.assertEquals(mExpectedMailboxId, mailboxId); - return mLastMessageListRefresTime; - } - } -} diff --git a/tests/src/com/android/email/activity/WelcomeTests.java b/tests/src/com/android/email/activity/WelcomeTests.java deleted file mode 100644 index be0efbca1..000000000 --- a/tests/src/com/android/email/activity/WelcomeTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.email.activity; - -import com.android.email.DBTestHelper; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; - -import android.content.Context; -import android.test.AndroidTestCase; - -public class WelcomeTests extends AndroidTestCase { - - private Context mProviderContext; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mProviderContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( - getContext()); - } - - public void testResolveAccountId() { - final Context c = mProviderContext; - final Account account1 = ProviderTestUtils.setupAccount("account-1", true, c); - final long id1 = account1.mId; - final Account account2 = ProviderTestUtils.setupAccount("account-2", true, c); - final long id2 = account2.mId; - final Account account3 = ProviderTestUtils.setupAccount("account-3", true, c); - final long id3 = account3.mId; - - // Make sure the last one created (account 3) is the default. - assertTrue(Account.getDefaultAccountId(c) == id3); - - // No account specified -- should return the default account. - assertEquals(id3, Welcome.resolveAccountId(c, -1, null)); - - // Invalid account id -- should return the default account. - assertEquals(id3, Welcome.resolveAccountId(c, 12345, null)); - - // Valid ID - assertEquals(id1, Welcome.resolveAccountId(c, id1, null)); - - // Invalid UUID -- should return the default account. - assertEquals(id3, Welcome.resolveAccountId(c, -1, "xxx")); - - // Valid UUID - assertEquals(id1, Welcome.resolveAccountId(c, -1, account1.mCompatibilityUuid)); - } -} diff --git a/tests/src/com/android/email/activity/setup/AccountSettingsTests.java b/tests/src/com/android/email/activity/setup/AccountSettingsTests.java index d923c5b2b..59b9cfc6d 100644 --- a/tests/src/com/android/email/activity/setup/AccountSettingsTests.java +++ b/tests/src/com/android/email/activity/setup/AccountSettingsTests.java @@ -25,6 +25,7 @@ import android.preference.PreferenceFragment; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.MediumTest; +import com.android.email.activity.setup.AccountSettings; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.HostAuth; @@ -162,7 +163,8 @@ public class AccountSettingsTests extends ActivityInstrumentationTestCase2 { - //EXCHANGE-REMOVE-SECTION-START - private AccountSetupExchange mActivity; - private AccountSetupExchangeFragment mFragment; - private EditText mServerView; - private EditText mPasswordView; - private CheckBox mSslRequiredCheckbox; - private CheckBox mTrustAllCertificatesCheckbox; - //EXCHANGE-REMOVE-SECTION-END - - public AccountSetupExchangeTests() { - super(AccountSetupExchange.class); - } - - //EXCHANGE-REMOVE-SECTION-START - /** - * Common setup code for all tests. Sets up a default launch intent, which some tests - * will use (others will override). - */ - @Override - protected void setUp() throws Exception { - super.setUp(); - - // This sets up a default URI which can be used by any of the test methods below. - // Individual test methods can replace this with a custom URI if they wish - // (except those that run on the UI thread - for them, it's too late to change it.) - Intent i = getTestIntent("eas://user:password@server.com"); - setActivityIntent(i); - } - - /** - * Test processing with a complete, good URI -> good fields - */ - public void testGoodUri() throws URISyntaxException { - Intent i = getTestIntent("eas://user:password@server.com"); - setActivityIntent(i); - getActivityAndFields(); - assertTrue(mActivity.mNextButtonEnabled); - } - - // TODO Add tests for valid usernames in eas - // They would be or \ or / or a valid email address - - /** - * No user is not OK - not enabled - */ - public void testBadUriNoUser() throws URISyntaxException { - Intent i = getTestIntent("eas://:password@server.com"); - setActivityIntent(i); - getActivityAndFields(); - assertFalse(mActivity.mNextButtonEnabled); - } - - /** - * No password is not OK - not enabled - */ - public void testBadUriNoPassword() throws URISyntaxException { - Intent i = getTestIntent("eas://user@server.com"); - setActivityIntent(i); - getActivityAndFields(); - assertFalse(mActivity.mNextButtonEnabled); - } - - /** - * Test for non-standard but OK server names - */ - @UiThreadTest - public void testGoodServerVariants() { - getActivityAndFields(); - assertTrue(mActivity.mNextButtonEnabled); - - mServerView.setText(" server.com "); - assertTrue(mActivity.mNextButtonEnabled); - } - - /** - * Test for non-empty but non-OK server names - */ - @UiThreadTest - public void testBadServerVariants() { - getActivityAndFields(); - assertTrue(mActivity.mNextButtonEnabled); - - mServerView.setText(" "); - assertFalse(mActivity.mNextButtonEnabled); - - mServerView.setText("serv$er.com"); - assertFalse(mActivity.mNextButtonEnabled); - } - - /** - * Test to confirm that passwords with leading or trailing spaces are accepted verbatim. - */ - @UiThreadTest - public void testPasswordNoTrim() { - getActivityAndFields(); - - // Clear the password - should disable - checkPassword(null, false); - - // Various combinations of spaces should be OK - checkPassword(" leading", true); - checkPassword("trailing ", true); - checkPassword("em bedded", true); - checkPassword(" ", true); - } - - /** - * Check password field for a given password. Should be called in UI thread. Confirms that - * the password has not been trimmed. - * - * @param password the password to test with - * @param expectNext true if expected that this password will enable the "next" button - */ - private void checkPassword(String password, boolean expectNext) { - mPasswordView.setText(password); - if (expectNext) { - assertTrue(mActivity.mNextButtonEnabled); - } else { - assertFalse(mActivity.mNextButtonEnabled); - } - } - - /** - * Test aspects of loadSettings() - * - * TODO: More cases - */ - @UiThreadTest - public void testLoadSettings() { - // The default URI has no SSL and no "trust" - getActivityAndFields(); - assertFalse(mSslRequiredCheckbox.isChecked()); - assertFalse(mTrustAllCertificatesCheckbox.isChecked()); - assertFalse(mTrustAllCertificatesCheckbox.getVisibility() == View.VISIBLE); - - // Setup host auth with variants of SSL enabled and check. This also enables the - // "trust certificates" checkbox (not checked, but visible now). - Account account = - ProviderTestUtils.setupAccount("account", false, mActivity.getBaseContext()); - account.mHostAuthRecv = ProviderTestUtils.setupHostAuth( - "eas", "hostauth", false, mActivity.getBaseContext()); - account.mHostAuthRecv.mFlags |= HostAuth.FLAG_SSL; - account.mHostAuthRecv.mFlags &= ~HostAuth.FLAG_TRUST_ALL; - mActivity.mFragment.mLoaded = false; - boolean loadResult = mActivity.mFragment.loadSettings(account); - assertTrue(loadResult); - assertTrue(mSslRequiredCheckbox.isChecked()); - assertFalse(mTrustAllCertificatesCheckbox.isChecked()); - assertTrue(mTrustAllCertificatesCheckbox.getVisibility() == View.VISIBLE); - - // Setup host auth with variants of SSL enabled and check. This also enables the - // "trust certificates" checkbox (not checked, but visible now). - account.mHostAuthRecv.mFlags |= HostAuth.FLAG_TRUST_ALL; - mActivity.mFragment.mLoaded = false; - loadResult = mActivity.mFragment.loadSettings(account); - assertTrue(loadResult); - assertTrue(mSslRequiredCheckbox.isChecked()); - assertTrue(mTrustAllCertificatesCheckbox.isChecked()); - assertTrue(mTrustAllCertificatesCheckbox.getVisibility() == View.VISIBLE); - - // A simple test of an incomplete account, which will fail validation - account.mHostAuthRecv.mPassword = ""; - mActivity.mFragment.mLoaded = false; - loadResult = mActivity.mFragment.loadSettings(account); - assertFalse(loadResult); - } - - /** - * TODO: Directly test validateFields() checking boolean result - */ - - /** - * Get the activity (which causes it to be started, using our intent) and get the UI fields - */ - private void getActivityAndFields() { - mActivity = getActivity(); - mFragment = mActivity.mFragment; - mServerView = (EditText) mActivity.findViewById(R.id.account_server); - mPasswordView = (EditText) mActivity.findViewById(R.id.account_password); - mSslRequiredCheckbox = (CheckBox) mActivity.findViewById(R.id.account_ssl); - mTrustAllCertificatesCheckbox = - (CheckBox) mActivity.findViewById(R.id.account_trust_certificates); - } - - /** - * Create an intent with the Account in it - */ - private Intent getTestIntent(String storeUriString) throws URISyntaxException { - Account account = new Account(); - Context context = getInstrumentation().getTargetContext(); - HostAuth auth = account.getOrCreateHostAuthRecv(context); - HostAuth.setHostAuthFromString(auth, storeUriString); - Intent i = new Intent(Intent.ACTION_MAIN); - SetupData.init(SetupData.FLOW_MODE_NORMAL, account); - SetupData.setAllowAutodiscover(false); - return i; - } - //EXCHANGE-REMOVE-SECTION-END +public class AccountSetupExchangeTests extends AndroidTestCase { + // TODO: Remove this class because AccountSetupExchange no longer exists } diff --git a/tests/src/com/android/email/activity/setup/AccountSetupIncomingTests.java b/tests/src/com/android/email/activity/setup/AccountSetupIncomingTests.java index 5a5786ba2..fdcc63028 100644 --- a/tests/src/com/android/email/activity/setup/AccountSetupIncomingTests.java +++ b/tests/src/com/android/email/activity/setup/AccountSetupIncomingTests.java @@ -16,17 +16,21 @@ package com.android.email.activity.setup; -import com.android.email.R; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.HostAuth; - import android.content.Context; import android.content.Intent; +import android.os.Bundle; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.test.suitebuilder.annotation.MediumTest; import android.widget.EditText; +import com.android.email.R; +import com.android.email.activity.setup.AccountSetupIncoming; +import com.android.email.activity.setup.AccountSetupIncomingFragment; +import com.android.email.activity.setup.SetupData; +import com.android.emailcommon.provider.Account; +import com.android.emailcommon.provider.HostAuth; + import java.net.URISyntaxException; /** @@ -176,7 +180,7 @@ public class AccountSetupIncomingTests extends */ private void getActivityAndFields() { mActivity = getActivity(); - mFragment = mActivity.mFragment; + mFragment = (AccountSetupIncomingFragment) mActivity.mFragment; mServerView = (EditText) mActivity.findViewById(R.id.account_server); mPasswordView = (EditText) mActivity.findViewById(R.id.account_password); } @@ -190,8 +194,14 @@ public class AccountSetupIncomingTests extends Context context = getInstrumentation().getTargetContext(); HostAuth auth = account.getOrCreateHostAuthRecv(context); HostAuth.setHostAuthFromString(auth, storeUriString); - SetupData.init(SetupData.FLOW_MODE_NORMAL, account); - return new Intent(Intent.ACTION_MAIN); + + Bundle extras = new Bundle(); + extras.putParcelable(SetupData.EXTRA_SETUP_DATA, new SetupData(SetupData.FLOW_MODE_NORMAL, account)); + + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.putExtras(extras); + + return intent; } } diff --git a/tests/src/com/android/email/activity/setup/AccountSetupOptionsTests.java b/tests/src/com/android/email/activity/setup/AccountSetupOptionsTests.java index 7d7e9bdf3..745c19ff1 100644 --- a/tests/src/com/android/email/activity/setup/AccountSetupOptionsTests.java +++ b/tests/src/com/android/email/activity/setup/AccountSetupOptionsTests.java @@ -51,7 +51,7 @@ public class AccountSetupOptionsTests /** * Test that POP accounts aren't displayed with a push option */ - public void testPushOptionPOP() + public void testPushOptionPOP() throws URISyntaxException { Intent i = getTestIntent("Name", "pop3://user:password@server.com"); this.setActivityIntent(i); @@ -169,7 +169,7 @@ public class AccountSetupOptionsTests Context context = getInstrumentation().getTargetContext(); HostAuth auth = account.getOrCreateHostAuthRecv(context); HostAuth.setHostAuthFromString(auth, storeUri); - SetupData.init(SetupData.FLOW_MODE_NORMAL, account); + SetupData setupData = new SetupData(SetupData.FLOW_MODE_NORMAL, account); return new Intent(Intent.ACTION_MAIN); } diff --git a/tests/src/com/android/email/activity/setup/AccountSetupOutgoingTests.java b/tests/src/com/android/email/activity/setup/AccountSetupOutgoingTests.java index ff7832d3c..e4f6b3a62 100644 --- a/tests/src/com/android/email/activity/setup/AccountSetupOutgoingTests.java +++ b/tests/src/com/android/email/activity/setup/AccountSetupOutgoingTests.java @@ -16,10 +16,6 @@ package com.android.email.activity.setup; -import com.android.email.R; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.HostAuth; - import android.content.Context; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; @@ -27,6 +23,13 @@ import android.test.UiThreadTest; import android.test.suitebuilder.annotation.MediumTest; import android.widget.EditText; +import com.android.email.R; +import com.android.email.activity.setup.AccountSetupOutgoing; +import com.android.email.activity.setup.AccountSetupOutgoingFragment; +import com.android.email.activity.setup.SetupData; +import com.android.emailcommon.provider.Account; +import com.android.emailcommon.provider.HostAuth; + import java.net.URISyntaxException; /** @@ -174,7 +177,7 @@ public class AccountSetupOutgoingTests extends mActivity = getActivity(); mFragment = mActivity.mFragment; mServerView = (EditText) mActivity.findViewById(R.id.account_server); - mPasswordView = (EditText) mActivity.findViewById(R.id.account_password); + mPasswordView = (EditText) mActivity.findViewById(R.id.account_server); } /** @@ -186,7 +189,8 @@ public class AccountSetupOutgoingTests extends Context context = getInstrumentation().getTargetContext(); HostAuth auth = account.getOrCreateHostAuthSend(context); HostAuth.setHostAuthFromString(auth, senderUriString); - SetupData.init(SetupData.FLOW_MODE_NORMAL, account); + // TODO: we need to do something with this SetupData, add it as an extra in the intent? + SetupData setupData = new SetupData(SetupData.FLOW_MODE_NORMAL, account); return new Intent(Intent.ACTION_MAIN); } diff --git a/tests/src/com/android/email/mail/store/ImapStoreUnitTests.java b/tests/src/com/android/email/mail/store/ImapStoreUnitTests.java index b49af037b..39c2f9cb1 100644 --- a/tests/src/com/android/email/mail/store/ImapStoreUnitTests.java +++ b/tests/src/com/android/email/mail/store/ImapStoreUnitTests.java @@ -29,13 +29,12 @@ import android.test.suitebuilder.annotation.SmallTest; import com.android.email.DBTestHelper; import com.android.email.MockSharedPreferences; import com.android.email.MockVendorPolicy; -import com.android.email.VendorPolicyLoader; -import com.android.email.mail.Transport; import com.android.email.mail.store.ImapStore.ImapMessage; import com.android.email.mail.store.imap.ImapResponse; import com.android.email.mail.store.imap.ImapTestUtils; import com.android.email.mail.transport.MockTransport; import com.android.emailcommon.TempDirectory; +import com.android.emailcommon.VendorPolicyLoader; import com.android.emailcommon.internet.MimeBodyPart; import com.android.emailcommon.internet.MimeMultipart; import com.android.emailcommon.internet.MimeUtility; @@ -95,6 +94,7 @@ public class ImapStoreUnitTests extends InstrumentationTestCase { private ImapStore mStore = null; private ImapFolder mFolder = null; private Context mTestContext; + private HostAuth mHostAuth; /** The tag for the current IMAP command; used for mock transport responses */ private int mTag; @@ -204,7 +204,7 @@ public class ImapStoreUnitTests extends InstrumentationTestCase { */ public void testTlsOpen() throws MessagingException { - MockTransport mockTransport = openAndInjectMockTransport(Transport.CONNECTION_SECURITY_TLS, + MockTransport mockTransport = openAndInjectMockTransport(HostAuth.FLAG_TLS, false); // try to open it, with STARTTLS @@ -544,7 +544,7 @@ public class ImapStoreUnitTests extends InstrumentationTestCase { * Set up a basic MockTransport. open it, and inject it into mStore */ private MockTransport openAndInjectMockTransport() { - return openAndInjectMockTransport(Transport.CONNECTION_SECURITY_NONE, false); + return openAndInjectMockTransport(HostAuth.FLAG_NONE, false); } /** @@ -553,7 +553,7 @@ public class ImapStoreUnitTests extends InstrumentationTestCase { private MockTransport openAndInjectMockTransport(int connectionSecurity, boolean trustAllCertificates) { // Create mock transport and inject it into the ImapStore that's already set up - MockTransport mockTransport = new MockTransport(); + MockTransport mockTransport = MockTransport.createMockTransport(mTestContext); mockTransport.setSecurity(connectionSecurity, trustAllCertificates); mockTransport.setHost("mock.server.com"); mStore.setTransportForTest(mockTransport); diff --git a/tests/src/com/android/email/mail/store/Pop3StoreUnitTests.java b/tests/src/com/android/email/mail/store/Pop3StoreUnitTests.java index 113b8b418..6c66b9198 100644 --- a/tests/src/com/android/email/mail/store/Pop3StoreUnitTests.java +++ b/tests/src/com/android/email/mail/store/Pop3StoreUnitTests.java @@ -20,9 +20,7 @@ import android.content.Context; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; -import com.android.email.Controller; import com.android.email.DBTestHelper; -import com.android.email.mail.Transport; import com.android.email.mail.transport.MockTransport; import com.android.email.provider.ProviderTestUtils; import com.android.emailcommon.TempDirectory; @@ -54,6 +52,7 @@ public class Pop3StoreUnitTests extends AndroidTestCase { private Pop3Store.Pop3Folder mFolder = null; private Context mMockContext; + private HostAuth mHostAuth; /** * Setup code. We generate a lightweight Pop3Store and Pop3Store.Pop3Folder. @@ -63,19 +62,17 @@ public class Pop3StoreUnitTests extends AndroidTestCase { super.setUp(); mMockContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext( getContext()); - Controller.getInstance(mMockContext).setProviderContext(mMockContext); - Controller.getInstance(mMockContext).markForTest(true); // Use the target's (i.e. the Email application) context TempDirectory.setTempDirectory(mMockContext); // These are needed so we can get at the inner classes - HostAuth testAuth = new HostAuth(); + mHostAuth = new HostAuth(); Account testAccount = ProviderTestUtils.setupAccount("acct1", false, mMockContext); - testAuth.setLogin("user", "password"); - testAuth.setConnection("pop3", "server", 999); - testAccount.mHostAuthRecv = testAuth; + mHostAuth.setLogin("user", "password"); + mHostAuth.setConnection("pop3", "server", 999); + testAccount.mHostAuthRecv = mHostAuth; testAccount.save(mMockContext); mStore = (Pop3Store) Pop3Store.newInstance(testAccount, mMockContext); mFolder = (Pop3Store.Pop3Folder) mStore.getFolder("INBOX"); @@ -872,8 +869,8 @@ public class Pop3StoreUnitTests extends AndroidTestCase { */ private MockTransport openAndInjectMockTransport() { // Create mock transport and inject it into the POP3Store that's already set up - MockTransport mockTransport = new MockTransport(); - mockTransport.setSecurity(Transport.CONNECTION_SECURITY_NONE, false); + MockTransport mockTransport = new MockTransport(mContext, mHostAuth); + mockTransport.setSecurity(HostAuth.FLAG_NONE, false); mStore.setTransport(mockTransport); return mockTransport; } diff --git a/tests/src/com/android/email/mail/store/imap/ImapUtilityTests.java b/tests/src/com/android/email/mail/store/imap/ImapUtilityTests.java index 1396ae6c6..7e4a10970 100644 --- a/tests/src/com/android/email/mail/store/imap/ImapUtilityTests.java +++ b/tests/src/com/android/email/mail/store/imap/ImapUtilityTests.java @@ -16,14 +16,11 @@ package com.android.email.mail.store.imap; -import com.android.email.mail.store.imap.ImapUtility; - import android.test.AndroidTestCase; import android.test.MoreAsserts; -import libcore.util.EmptyArray; - public class ImapUtilityTests extends AndroidTestCase { + public static final String[] EmptyArrayString = new String[0]; /** * Tests of the IMAP quoting rules function. @@ -75,19 +72,19 @@ public class ImapUtilityTests extends AndroidTestCase { MoreAsserts.assertEquals(expected, actual); // Test invalid sets - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapSequenceValues(""); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapSequenceValues(null); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapSequenceValues("a"); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapSequenceValues("1:x"); MoreAsserts.assertEquals(expected, actual); } @@ -109,31 +106,31 @@ public class ImapUtilityTests extends AndroidTestCase { MoreAsserts.assertEquals(expected, actual); // Test in-valid ranges - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues(""); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues(null); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues("a"); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues("6"); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues("1:3,6"); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues("1:x"); MoreAsserts.assertEquals(expected, actual); - expected = EmptyArray.STRING; + expected = EmptyArrayString; actual = ImapUtility.getImapRangeValues("1:*"); MoreAsserts.assertEquals(expected, actual); } diff --git a/tests/src/com/android/email/mail/transport/MockTransport.java b/tests/src/com/android/email/mail/transport/MockTransport.java index bb1c136a9..572b93c8c 100644 --- a/tests/src/com/android/email/mail/transport/MockTransport.java +++ b/tests/src/com/android/email/mail/transport/MockTransport.java @@ -1,22 +1,27 @@ /* * Copyright (C) 2008 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. */ package com.android.email.mail.transport; -import com.android.email.mail.Transport; +import android.content.Context; + +import com.android.emailcommon.provider.HostAuth; +import com.android.mail.utils.LogUtils; + +import junit.framework.Assert; import java.io.IOException; import java.io.InputStream; @@ -26,12 +31,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Pattern; -import junit.framework.Assert; - /** * This is a mock Transport that is used to test protocols that use MailTransport. */ -public class MockTransport implements Transport { +public class MockTransport extends MailTransport { // All flags defining debug or development code settings must be FALSE // when code is checked in or released. @@ -45,9 +48,6 @@ public class MockTransport implements Transport { private boolean mOpen; private boolean mInputOpen; - private int mConnectionSecurity; - private boolean mTrustCertificates; - private String mHost; private InetAddress mLocalAddress; private ArrayList mQueuedInput = new ArrayList(); @@ -93,12 +93,20 @@ public class MockTransport implements Transport { private ArrayList mPairs = new ArrayList(); + public static MockTransport createMockTransport(Context context) { + return new MockTransport(context, new HostAuth()); + } + + public MockTransport(Context context, HostAuth hostAuth) { + super(context, LOG_TAG, hostAuth); + } + /** * Give the mock a pattern to wait for. No response will be sent. * @param pattern Java RegEx to wait for */ public void expect(String pattern) { - expect(pattern, (String[])null); + expect(pattern, (String[]) null); } /** @@ -107,7 +115,7 @@ public class MockTransport implements Transport { * @param response String to reply with, or null to acccept string but not respond to it */ public void expect(String pattern, String response) { - expect(pattern, (response == null) ? null : new String[] { response }); + expect(pattern, (response == null) ? null : new String[] {response}); } /** @@ -160,21 +168,6 @@ public class MockTransport implements Transport { } } - @Override - public boolean canTrySslSecurity() { - return (mConnectionSecurity == CONNECTION_SECURITY_SSL); - } - - @Override - public boolean canTryTlsSecurity() { - return (mConnectionSecurity == Transport.CONNECTION_SECURITY_TLS); - } - - @Override - public boolean canTrustAllCertificates() { - return mTrustCertificates; - } - /** * Check that TLS was started */ @@ -205,16 +198,6 @@ public class MockTransport implements Transport { mPairs.clear(); } - @Override - public void setHost(String host) { - mHost = host; - } - - @Override - public String getHost() { - return mHost; - } - public void setMockLocalAddress(InetAddress address) { mLocalAddress = address; } @@ -231,8 +214,8 @@ public class MockTransport implements Transport { * don't have to worry about dealing with test metadata like the expects list or socket state. */ @Override - public Transport clone() { - return this; + public MockTransport clone() { + return this; } @Override @@ -241,21 +224,6 @@ public class MockTransport implements Transport { return new MockOutputStream(); } - @Override - public void setPort(int port) { - SmtpSenderUnitTests.fail("setPort() not implemented"); - } - - @Override - public int getPort() { - SmtpSenderUnitTests.fail("getPort() not implemented"); - return 0; - } - - @Override - public int getSecurity() { - return mConnectionSecurity; - } @Override public boolean isOpen() { @@ -263,7 +231,10 @@ public class MockTransport implements Transport { } @Override - public void open() /* throws MessagingException, CertificateValidationException */ { + public void open() /* + * throws MessagingException, + * CertificateValidationException + */{ mOpen = true; mInputOpen = true; } @@ -278,13 +249,13 @@ public class MockTransport implements Transport { * * Logs the read text if DEBUG_LOG_STREAMS is true. */ - @Override public String readLine() throws IOException { SmtpSenderUnitTests.assertTrue(mOpen); if (!mInputOpen) { throw new IOException("Reading from MockTransport with closed input"); } - // if there's nothing to read, see if we can find a null-pattern response + // if there's nothing to read, see if we can find a null-pattern + // response if ((mQueuedInput.size() == 0) && (mPairs.size() > 0)) { Transaction pair = mPairs.get(0); if (pair.mPattern == null) { @@ -308,22 +279,24 @@ public class MockTransport implements Transport { } @Override - public void reopenTls() /* throws MessagingException */ { + public void reopenTls() /* throws MessagingException */{ SmtpSenderUnitTests.assertTrue(mOpen); Transaction expect = mPairs.remove(0); SmtpSenderUnitTests.assertTrue(expect.mAction == Transaction.ACTION_START_TLS); mTlsStarted = true; } - @Override public void setSecurity(int connectionSecurity, boolean trustAllCertificates) { - mConnectionSecurity = connectionSecurity; - mTrustCertificates = trustAllCertificates; + mHostAuth.mFlags = + connectionSecurity & (trustAllCertificates ? HostAuth.FLAG_TRUST_ALL : 0xff); + } + + public void setHost(String address) { + mHostAuth.mAddress = address; } @Override - public void setSoTimeout(int timeoutMilliseconds) /* throws SocketException */ { - } + public void setSoTimeout(int timeoutMilliseconds) /* throws SocketException */{} /** * Accepts a single string (command or text) that was written by the code under test. @@ -340,15 +313,14 @@ public class MockTransport implements Transport { LogUtils.d(LOG_TAG, ">>> " + s); } SmtpSenderUnitTests.assertTrue(mOpen); - SmtpSenderUnitTests.assertTrue("Overflow writing to MockTransport: Getting " + s, - 0 != mPairs.size()); + SmtpSenderUnitTests.assertTrue( + "Overflow writing to MockTransport: Getting " + s, 0 != mPairs.size()); Transaction pair = mPairs.remove(0); if (pair.mAction == Transaction.ACTION_IO_EXCEPTION) { throw new IOException("Expected IOException."); } SmtpSenderUnitTests.assertTrue("Unexpected string written to MockTransport: Actual=" + s - + " Expected=" + pair.mPattern, - pair.mPattern != null && s.matches(pair.mPattern)); + + " Expected=" + pair.mPattern, pair.mPattern != null && s.matches(pair.mPattern)); if (pair.mResponses != null) { sendResponse(pair); } @@ -408,7 +380,7 @@ public class MockTransport implements Transport { } else if (oneByte == '\n') { // swallow it } else { - sb.append((char)oneByte); + sb.append((char) oneByte); } } } diff --git a/tests/src/com/android/email/mail/transport/SmtpSenderUnitTests.java b/tests/src/com/android/email/mail/transport/SmtpSenderUnitTests.java index 8e9ab750d..d65a3c954 100644 --- a/tests/src/com/android/email/mail/transport/SmtpSenderUnitTests.java +++ b/tests/src/com/android/email/mail/transport/SmtpSenderUnitTests.java @@ -21,7 +21,6 @@ import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import com.android.email.DBTestHelper; -import com.android.email.mail.Transport; import com.android.email.provider.EmailProvider; import com.android.emailcommon.mail.Address; import com.android.emailcommon.mail.MessagingException; @@ -48,6 +47,7 @@ public class SmtpSenderUnitTests extends AndroidTestCase { EmailProvider mProvider; Context mProviderContext; Context mContext; + HostAuth mHostAuth; private static final String LOCAL_ADDRESS = "1.2.3.4"; /* These values are provided by setUp() */ @@ -67,12 +67,12 @@ public class SmtpSenderUnitTests extends AndroidTestCase { getContext()); mContext = getContext(); - HostAuth testAuth = new HostAuth(); + mHostAuth = new HostAuth(); Account testAccount = new Account(); - testAuth.setLogin("user", "password"); - testAuth.setConnection("smtp", "server", 999); - testAccount.mHostAuthSend = testAuth; + mHostAuth.setLogin("user", "password"); + mHostAuth.setConnection("smtp", "server", 999); + testAccount.mHostAuthSend = mHostAuth; mSender = (SmtpSender) SmtpSender.newInstance(testAccount, mProviderContext); } @@ -195,7 +195,7 @@ public class SmtpSenderUnitTests extends AndroidTestCase { attachment.mMimeType = "image/jpg"; attachment.mSize = 0; attachment.mContentId = null; - attachment.mContentUri = "content://com.android.email/1/1"; + attachment.setContentUri("content://com.android.email/1/1"); attachment.mMessageKey = messageId; attachment.mLocation = null; attachment.mEncoding = null; @@ -214,7 +214,8 @@ public class SmtpSenderUnitTests extends AndroidTestCase { mockTransport.expect(" filename=\"" + attachment.mFileName + "\";"); mockTransport.expect(" size=" + Long.toString(attachment.mSize)); mockTransport.expect(""); - if (attachment.mContentUri != null && attachment.mContentUri.startsWith("file://")) { + String attachmentContentUri = attachment.getContentUri(); + if (attachmentContentUri != null && attachmentContentUri.startsWith("file://")) { mockTransport.expect(TEST_STRING_BASE64); } } @@ -248,8 +249,8 @@ public class SmtpSenderUnitTests extends AndroidTestCase { */ private MockTransport openAndInjectMockTransport() throws UnknownHostException { // Create mock transport and inject it into the SmtpSender that's already set up - MockTransport mockTransport = new MockTransport(); - mockTransport.setSecurity(Transport.CONNECTION_SECURITY_NONE, false); + MockTransport mockTransport = new MockTransport(mContext, mHostAuth); + mockTransport.setSecurity(HostAuth.FLAG_NONE, false); mSender.setTransport(mockTransport); mockTransport.setMockLocalAddress(InetAddress.getByName(LOCAL_ADDRESS)); return mockTransport; diff --git a/tests/src/com/android/email/provider/AccountBackupRestoreTests.java b/tests/src/com/android/email/provider/AccountBackupRestoreTests.java index b1e06fe96..92fae579f 100644 --- a/tests/src/com/android/email/provider/AccountBackupRestoreTests.java +++ b/tests/src/com/android/email/provider/AccountBackupRestoreTests.java @@ -62,9 +62,7 @@ public class AccountBackupRestoreTests extends ProviderTestCase2 assertEquals(" mSyncLookback", expect.mSyncLookback, actual.mSyncLookback); assertEquals(" mSyncInterval", expect.mSyncInterval, actual.mSyncInterval); assertEquals(" mFlags", expect.mFlags, actual.mFlags); - assertEquals(" mIsDefault", expect.mIsDefault, actual.mIsDefault); assertEquals(" mSenderName", expect.mSenderName, actual.mSenderName); - assertEquals(" mRingtoneUri", expect.mRingtoneUri, actual.mRingtoneUri); assertEquals(" mProtocolVersion", expect.mProtocolVersion, actual.mProtocolVersion); assertEquals(" mNewMessageCount", expect.mNewMessageCount, @@ -88,7 +86,6 @@ public class AccountBackupRestoreTests extends ProviderTestCase2 ProviderTestUtils.setupHostAuth("legacy-recv", 0, false, mMockContext); saved1.mHostAuthSend = ProviderTestUtils.setupHostAuth("legacy-send", 0, false, mMockContext); - saved1.setDefaultAccount(true); saved1.save(mMockContext); Account saved2 = ProviderTestUtils.setupAccount("testBackup2", false, mMockContext); @@ -96,7 +93,6 @@ public class AccountBackupRestoreTests extends ProviderTestCase2 ProviderTestUtils.setupHostAuth("legacy-recv", 0, false, mMockContext); saved2.mHostAuthSend = ProviderTestUtils.setupHostAuth("legacy-send", 0, false, mMockContext); - saved2.setDefaultAccount(false); saved2.save(mMockContext); // Make sure they're in the database assertEquals(2, EmailContent.count(mMockContext, Account.CONTENT_URI)); diff --git a/tests/src/com/android/email/provider/AttachmentProviderTests.java b/tests/src/com/android/email/provider/AttachmentProviderTests.java index e02ccf7e9..88093588e 100644 --- a/tests/src/com/android/email/provider/AttachmentProviderTests.java +++ b/tests/src/com/android/email/provider/AttachmentProviderTests.java @@ -54,7 +54,7 @@ public class AttachmentProviderTests extends ProviderTestCase2 { // Setup two accounts with policies Account account1 = ProviderTestUtils.setupAccount("acct1", true, mMockContext); Policy policy1 = new Policy(); - Policy.setAccountPolicy(mMockContext, account1, policy1, securitySyncKey); + SecurityPolicy.setAccountPolicy(mMockContext, account1, policy1, securitySyncKey); Account account2 = ProviderTestUtils.setupAccount("acct2", true, mMockContext); Policy policy2 = new Policy(); - Policy.setAccountPolicy(mMockContext, account2, policy2, securitySyncKey); + SecurityPolicy.setAccountPolicy(mMockContext, account2, policy2, securitySyncKey); // Get the accounts back from the database account1.refresh(mMockContext); account2.refresh(mMockContext); @@ -92,7 +93,7 @@ public class PolicyTests extends ProviderTestCase2 { assertEquals(0, account.mPolicyKey); assertEquals(0, EmailContent.count(mMockContext, Policy.CONTENT_URI)); Policy policy = new Policy(); - Policy.setAccountPolicy(mMockContext, account, policy, securitySyncKey); + SecurityPolicy.setAccountPolicy(mMockContext, account, policy, securitySyncKey); account.refresh(mMockContext); // We should have a policyKey now assertTrue(account.mPolicyKey > 0); @@ -103,7 +104,7 @@ public class PolicyTests extends ProviderTestCase2 { assertEquals(policy, dbPolicy); // The account should have the security sync key set assertEquals(securitySyncKey, account.mSecuritySyncKey); - Policy.clearAccountPolicy(mMockContext, account); + SecurityPolicy.clearAccountPolicy(mMockContext, account); account.refresh(mMockContext); // Make sure policyKey is cleared and policy is deleted assertEquals(0, account.mPolicyKey); @@ -122,7 +123,7 @@ public class PolicyTests extends ProviderTestCase2 { Account acct = ProviderTestUtils.setupAccount("acct1", true, mMockContext); Policy policy1 = new Policy(); policy1.mDontAllowAttachments = true; - Policy.setAccountPolicy(mMockContext, acct, policy1, null); + SecurityPolicy.setAccountPolicy(mMockContext, acct, policy1, null); Mailbox box = ProviderTestUtils.setupMailbox("box1", acct.mId, true, mMockContext); Message msg1 = ProviderTestUtils.setupMessage("message1", acct.mId, box.mId, false, false, mMockContext); diff --git a/tests/src/com/android/email/provider/ProviderTestUtils.java b/tests/src/com/android/email/provider/ProviderTestUtils.java index 20491b511..3c430cad1 100644 --- a/tests/src/com/android/email/provider/ProviderTestUtils.java +++ b/tests/src/com/android/email/provider/ProviderTestUtils.java @@ -58,10 +58,8 @@ public class ProviderTestUtils extends Assert { account.mHostAuthKeyRecv = 0; account.mHostAuthKeySend = 0; account.mFlags = 4; - account.mIsDefault = true; account.mCompatibilityUuid = "test-uid-" + name; account.mSenderName = name; - account.mRingtoneUri = "content://ringtone-" + name; account.mProtocolVersion = "2.5" + name; account.mNewMessageCount = 5 + name.length(); account.mPolicyKey = 0; @@ -143,7 +141,6 @@ public class ProviderTestUtils extends Assert { box.mSyncTime = 3; box.mFlagVisible = true; box.mFlags = 5; - box.mVisibleLimit = 6; if (saveIt) { box.save(context); @@ -171,6 +168,7 @@ public class ProviderTestUtils extends Assert { message.mTimeStamp = 100 + name.length(); message.mSubject = "subject " + name; message.mFlagRead = read; + message.mFlagSeen = read; message.mFlagLoaded = Message.FLAG_LOADED_UNLOADED; message.mFlagFavorite = starred; message.mFlagAttachment = true; @@ -178,7 +176,6 @@ public class ProviderTestUtils extends Assert { message.mServerId = "serverid " + name; message.mServerTimeStamp = 300 + name.length(); - message.mClientId = "clientid " + name; message.mMessageId = "messageid " + name; message.mMailboxKey = mailboxId; @@ -220,12 +217,9 @@ public class ProviderTestUtils extends Assert { boolean saveIt, Context context) { Body body = new Body(); body.mMessageKey = messageId; - body.mTextContent = textContent; body.mHtmlContent = htmlContent; - body.mTextReply = "text reply " + messageId; - body.mHtmlReply = "html reply " + messageId; + body.mTextContent = textContent; body.mSourceKey = messageId + 0x1000; - body.mIntroText = "intro text " + messageId; if (saveIt) { body.save(context); } @@ -249,7 +243,7 @@ public class ProviderTestUtils extends Assert { att.mSize = length; att.mFileName = fileName; att.mContentId = "contentId " + fileName; - att.mContentUri = "contentUri " + fileName; + att.setContentUri("contentUri " + fileName); att.mMessageKey = messageId; att.mMimeType = "mimeType " + fileName; att.mLocation = "location " + fileName; @@ -310,19 +304,18 @@ public class ProviderTestUtils extends Assert { assertEquals(caller + " mHostAuthKeySend", expect.mHostAuthKeySend, actual.mHostAuthKeySend); assertEquals(caller + " mFlags", expect.mFlags, actual.mFlags); - assertEquals(caller + " mIsDefault", expect.mIsDefault, actual.mIsDefault); assertEquals(caller + " mCompatibilityUuid", expect.mCompatibilityUuid, actual.mCompatibilityUuid); assertEquals(caller + " mSenderName", expect.mSenderName, actual.mSenderName); - assertEquals(caller + " mRingtoneUri", expect.mRingtoneUri, actual.mRingtoneUri); assertEquals(caller + " mProtocolVersion", expect.mProtocolVersion, actual.mProtocolVersion); assertEquals(caller + " mNewMessageCount", expect.mNewMessageCount, actual.mNewMessageCount); - assertEquals(caller + " mPolicyKey", expect.mPolicyKey, actual.mPolicyKey); assertEquals(caller + " mSecuritySyncKey", expect.mSecuritySyncKey, actual.mSecuritySyncKey); assertEquals(caller + " mSignature", expect.mSignature, actual.mSignature); + assertEquals(caller + " mPolicyKey", expect.mPolicyKey, actual.mPolicyKey); + assertEquals(caller + " mPingDuration", expect.mPingDuration, actual.mPingDuration); } /** @@ -373,8 +366,13 @@ public class ProviderTestUtils extends Assert { assertEquals(caller + " mSyncInterval", expect.mSyncInterval, actual.mSyncInterval); assertEquals(caller + " mSyncTime", expect.mSyncTime, actual.mSyncTime); assertEquals(caller + " mFlagVisible", expect.mFlagVisible, actual.mFlagVisible); - assertEquals(caller + " mFlags", expect.mFlags, actual.mFlags); - assertEquals(caller + " mVisibleLimit", expect.mVisibleLimit, actual.mVisibleLimit); + assertEquals(caller + " mSyncStatus", expect.mSyncStatus, actual.mSyncStatus); + assertEquals(caller + " mLastTouchedTime", expect.mLastTouchedTime, actual.mLastTouchedTime); + assertEquals(caller + " mUiSyncStatus", expect.mUiSyncStatus, actual.mUiSyncStatus); + assertEquals(caller + " mUiLastSyncResult", expect.mUiLastSyncResult, actual.mUiLastSyncResult); + assertEquals(caller + " mTotalCount", expect.mTotalCount, actual.mTotalCount); + assertEquals(caller + " mHierarchicalName", expect.mHierarchicalName, actual.mHierarchicalName); + assertEquals(caller + " mLastFullSyncTime", expect.mLastFullSyncTime, actual.mLastFullSyncTime); } /** @@ -393,6 +391,7 @@ public class ProviderTestUtils extends Assert { assertEquals(caller + " mTimeStamp", expect.mTimeStamp, actual.mTimeStamp); assertEquals(caller + " mSubject", expect.mSubject, actual.mSubject); assertEquals(caller + " mFlagRead = false", expect.mFlagRead, actual.mFlagRead); + assertEquals(caller + " mFlagRead = false", expect.mFlagSeen, actual.mFlagSeen); assertEquals(caller + " mFlagLoaded", expect.mFlagLoaded, actual.mFlagLoaded); assertEquals(caller + " mFlagFavorite", expect.mFlagFavorite, actual.mFlagFavorite); assertEquals(caller + " mFlagAttachment", expect.mFlagAttachment, actual.mFlagAttachment); @@ -400,11 +399,12 @@ public class ProviderTestUtils extends Assert { assertEquals(caller + " mServerId", expect.mServerId, actual.mServerId); assertEquals(caller + " mServerTimeStamp", expect.mServerTimeStamp,actual.mServerTimeStamp); - assertEquals(caller + " mClientId", expect.mClientId, actual.mClientId); + assertEquals(caller + " mDraftInfo", expect.mDraftInfo,actual.mDraftInfo); assertEquals(caller + " mMessageId", expect.mMessageId, actual.mMessageId); assertEquals(caller + " mMailboxKey", expect.mMailboxKey, actual.mMailboxKey); assertEquals(caller + " mAccountKey", expect.mAccountKey, actual.mAccountKey); + assertEquals(caller + " mMainMailboxKey", expect.mMainMailboxKey, actual.mMainMailboxKey); assertEquals(caller + " mFrom", expect.mFrom, actual.mFrom); assertEquals(caller + " mTo", expect.mTo, actual.mTo); @@ -416,12 +416,21 @@ public class ProviderTestUtils extends Assert { assertEquals(caller + " mSnippet", expect.mSnippet, actual.mSnippet); + assertEquals(caller + " mProtocolSearchInfo", expect.mProtocolSearchInfo, actual.mProtocolSearchInfo); + + assertEquals(caller + " mThreadTopic", expect.mThreadTopic, actual.mThreadTopic); + + assertEquals(caller + " mSyncData", expect.mSyncData, actual.mSyncData); + + assertEquals(caller + " mSyncData", expect.mServerConversationId, actual.mServerConversationId); + assertEquals(caller + " mText", expect.mText, actual.mText); assertEquals(caller + " mHtml", expect.mHtml, actual.mHtml); assertEquals(caller + " mTextReply", expect.mTextReply, actual.mTextReply); assertEquals(caller + " mHtmlReply", expect.mHtmlReply, actual.mHtmlReply); assertEquals(caller + " mSourceKey", expect.mSourceKey, actual.mSourceKey); assertEquals(caller + " mIntroText", expect.mIntroText, actual.mIntroText); + assertEquals(caller + " mQuotedTextStartPos", expect.mQuotedTextStartPos, actual.mQuotedTextStartPos); } /** @@ -435,12 +444,13 @@ public class ProviderTestUtils extends Assert { } assertEmailContentEqual(caller, expect, actual); - assertEquals(caller + " mSize", expect.mSize, actual.mSize); assertEquals(caller + " mFileName", expect.mFileName, actual.mFileName); - assertEquals(caller + " mContentId", expect.mContentId, actual.mContentId); - assertEquals(caller + " mContentUri", expect.mContentUri, actual.mContentUri); - assertEquals(caller + " mMessageKey", expect.mMessageKey, actual.mMessageKey); assertEquals(caller + " mMimeType", expect.mMimeType, actual.mMimeType); + assertEquals(caller + " mSize", expect.mSize, actual.mSize); + assertEquals(caller + " mContentId", expect.mContentId, actual.mContentId); + assertEquals(caller + " mContentUri", expect.getContentUri(), actual.getContentUri()); + assertEquals(caller + " mCachedFileUri", expect.getCachedFileUri(), actual.getCachedFileUri()); + assertEquals(caller + " mMessageKey", expect.mMessageKey, actual.mMessageKey); assertEquals(caller + " mLocation", expect.mLocation, actual.mLocation); assertEquals(caller + " mEncoding", expect.mEncoding, actual.mEncoding); assertEquals(caller + " mContent", expect.mContent, actual.mContent); @@ -459,7 +469,7 @@ public class ProviderTestUtils extends Assert { File outputFile = File.createTempFile("message", "tmp", directory); assertNotNull(outputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); - Rfc822Output.writeTo(context, msg.mId, outputStream, true, false); + Rfc822Output.writeTo(context, msg, outputStream, true, false, null); outputStream.close(); return Uri.fromFile(outputFile); diff --git a/tests/src/com/android/email/provider/ProviderTests.java b/tests/src/com/android/email/provider/ProviderTests.java index ebf324399..947a35b9b 100644 --- a/tests/src/com/android/email/provider/ProviderTests.java +++ b/tests/src/com/android/email/provider/ProviderTests.java @@ -1,17 +1,17 @@ /* * Copyright (C) 2009 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. */ package com.android.email.provider; @@ -37,7 +37,6 @@ import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import com.android.email.provider.EmailProvider.AttachmentService; -import com.android.emailcommon.AccountManagerTypes; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.AccountColumns; @@ -82,7 +81,8 @@ public class ProviderTests extends ProviderTestCase2 { super(EmailProvider.class, EmailContent.AUTHORITY); } - // TODO: move this out to a common place. There are other places that have similar mocks. + // TODO: move this out to a common place. There are other places that have + // similar mocks. /** * Private context wrapper used to add back getPackageName() for these tests. */ @@ -138,16 +138,17 @@ public class ProviderTests extends ProviderTestCase2 { * TODO: Database upgrade tests */ - ////////////////////////////////////////////////////////// - ////// Utility methods - ////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////// + // //// Utility methods + // //////////////////////////////////////////////////////// /** Sets the message count of all mailboxes to {@code -1}. */ private void setMinusOneToMessageCounts() { ContentValues values = new ContentValues(); values.put(MailboxColumns.MESSAGE_COUNT, -1); - // EmailProvider.update() doesn't allow updating messageCount, so directly use the DB. + // EmailProvider.update() doesn't allow updating messageCount, so + // directly use the DB. SQLiteDatabase db = getProvider().getDatabase(mMockContext); db.update(Mailbox.TABLE_NAME, values, null, null); } @@ -156,22 +157,32 @@ public class ProviderTests extends ProviderTestCase2 { private int getMessageCount(long mailboxId) { return Utility.getFirstRowInt(mMockContext, ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), - new String[] {MailboxColumns.MESSAGE_COUNT}, null, null, null, 0); + new String[] {MailboxColumns.MESSAGE_COUNT}, + null, + null, + null, + 0); } /** Creates a new message. */ - private static Message createMessage(Context c, Mailbox b, boolean starred, boolean read, - int flagLoaded) { - Message message = ProviderTestUtils.setupMessage( - "1", b.mAccountKey, b.mId, true, false, c, starred, read); + private static Message createMessage( + Context c, Mailbox b, boolean starred, boolean read, int flagLoaded) { + Message message = ProviderTestUtils.setupMessage("1", + b.mAccountKey, + b.mId, + true, + false, + c, + starred, + read); message.mFlagLoaded = flagLoaded; message.save(c); return message; } - ////////////////////////////////////////////////////////// - ////// The tests - ////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////// + // //// The tests + // //////////////////////////////////////////////////////// /** * Test simple account save/retrieve @@ -193,10 +204,10 @@ public class ProviderTests extends ProviderTestCase2 { public void testAccountSaveHostAuth() { Account account1 = ProviderTestUtils.setupAccount("account-hostauth", false, mMockContext); // add hostauth data, which should be saved the first time - account1.mHostAuthRecv = ProviderTestUtils.setupHostAuth("account-hostauth-recv", -1, false, - mMockContext); - account1.mHostAuthSend = ProviderTestUtils.setupHostAuth("account-hostauth-send", -1, false, - mMockContext); + account1.mHostAuthRecv = + ProviderTestUtils.setupHostAuth("account-hostauth-recv", -1, false, mMockContext); + account1.mHostAuthSend = + ProviderTestUtils.setupHostAuth("account-hostauth-send", -1, false, mMockContext); account1.save(mMockContext); long account1Id = account1.mId; @@ -205,20 +216,20 @@ public class ProviderTests extends ProviderTestCase2 { ProviderTestUtils.assertAccountEqual("testAccountSave", account1, account1get); // Confirm hostauth fields can be accessed & read back correctly - HostAuth hostAuth1get = HostAuth.restoreHostAuthWithId(mMockContext, - account1get.mHostAuthKeyRecv); - ProviderTestUtils.assertHostAuthEqual("testAccountSaveHostAuth-recv", - account1.mHostAuthRecv, hostAuth1get); - HostAuth hostAuth2get = HostAuth.restoreHostAuthWithId(mMockContext, - account1get.mHostAuthKeySend); - ProviderTestUtils.assertHostAuthEqual("testAccountSaveHostAuth-send", - account1.mHostAuthSend, hostAuth2get); + HostAuth hostAuth1get = + HostAuth.restoreHostAuthWithId(mMockContext, account1get.mHostAuthKeyRecv); + ProviderTestUtils.assertHostAuthEqual( + "testAccountSaveHostAuth-recv", account1.mHostAuthRecv, hostAuth1get); + HostAuth hostAuth2get = + HostAuth.restoreHostAuthWithId(mMockContext, account1get.mHostAuthKeySend); + ProviderTestUtils.assertHostAuthEqual( + "testAccountSaveHostAuth-send", account1.mHostAuthSend, hostAuth2get); } public void testAccountGetHostAuthSend() { Account account = ProviderTestUtils.setupAccount("account-hostauth", false, mMockContext); - account.mHostAuthSend = ProviderTestUtils.setupHostAuth("account-hostauth-send", -1, false, - mMockContext); + account.mHostAuthSend = + ProviderTestUtils.setupHostAuth("account-hostauth-send", -1, false, mMockContext); account.save(mMockContext); HostAuth authGet; HostAuth authTest; @@ -232,8 +243,7 @@ public class ProviderTests extends ProviderTestCase2 { assertTrue(authGet == authTest); // return the same object // New HostAuth; based upon mHostAuthKeyRecv - authTest = HostAuth.restoreHostAuthWithId(mMockContext, - account.mHostAuthKeySend); + authTest = HostAuth.restoreHostAuthWithId(mMockContext, account.mHostAuthKeySend); account.mHostAuthSend = null; authGet = account.getOrCreateHostAuthSend(mMockContext); assertNotNull(authGet); @@ -252,8 +262,8 @@ public class ProviderTests extends ProviderTestCase2 { public void testAccountGetHostAuthRecv() { Account account = ProviderTestUtils.setupAccount("account-hostauth", false, mMockContext); - account.mHostAuthRecv = ProviderTestUtils.setupHostAuth("account-hostauth-recv", -1, false, - mMockContext); + account.mHostAuthRecv = + ProviderTestUtils.setupHostAuth("account-hostauth-recv", -1, false, mMockContext); account.save(mMockContext); HostAuth authGet; HostAuth authTest; @@ -267,8 +277,7 @@ public class ProviderTests extends ProviderTestCase2 { assertTrue(authGet == authTest); // return the same object // New HostAuth; based upon mHostAuthKeyRecv - authTest = HostAuth.restoreHostAuthWithId(mMockContext, - account.mHostAuthKeyRecv); + authTest = HostAuth.restoreHostAuthWithId(mMockContext, account.mHostAuthKeyRecv); account.mHostAuthRecv = null; authGet = account.getOrCreateHostAuthRecv(mMockContext); assertNotNull(authGet); @@ -295,7 +304,7 @@ public class ProviderTests extends ProviderTestCase2 { b.putParcelable("account", account1); Parcel p = Parcel.obtain(); b.writeToParcel(p, 0); - p.setDataPosition(0); // rewind it for reading + p.setDataPosition(0); // rewind it for reading Bundle b2 = new Bundle(Account.class.getClassLoader()); b2.readFromParcel(p); Account account2 = (Account) b2.getParcelable("account"); @@ -327,10 +336,10 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(account2Id, Account.getAccountIdFromShortcutSafeUri(mMockContext, uri2)); // Test for the Eclair(2.0-2.1) style URI. - assertEquals(account1Id, Account.getAccountIdFromShortcutSafeUri(mMockContext, - getEclairStyleShortcutUri(account1))); - assertEquals(account2Id, Account.getAccountIdFromShortcutSafeUri(mMockContext, - getEclairStyleShortcutUri(account2))); + assertEquals(account1Id, Account.getAccountIdFromShortcutSafeUri( + mMockContext, getEclairStyleShortcutUri(account1))); + assertEquals(account2Id, Account.getAccountIdFromShortcutSafeUri( + mMockContext, getEclairStyleShortcutUri(account2))); } private static Uri getEclairStyleShortcutUri(Account account) { @@ -341,17 +350,18 @@ public class ProviderTests extends ProviderTestCase2 { public void testGetProtocol() { Account account1 = ProviderTestUtils.setupAccount("account-hostauth", false, mMockContext); // add hostauth data, with protocol - account1.mHostAuthRecv = ProviderTestUtils.setupHostAuth("eas", "account-hostauth-recv", - false, mMockContext); - // Note that getProtocol uses the receive host auth, so the protocol here shouldn't matter + account1.mHostAuthRecv = ProviderTestUtils.setupHostAuth( + "eas", "account-hostauth-recv", false, mMockContext); + // Note that getProtocol uses the receive host auth, so the protocol + // here shouldn't matter // to the test result - account1.mHostAuthSend = ProviderTestUtils.setupHostAuth("foo", "account-hostauth-send", - false, mMockContext); + account1.mHostAuthSend = ProviderTestUtils.setupHostAuth( + "foo", "account-hostauth-send", false, mMockContext); account1.save(mMockContext); assertEquals("eas", Account.getProtocol(mMockContext, account1.mId)); assertEquals("eas", account1.getProtocol(mMockContext)); - Account account2 = ProviderTestUtils.setupAccount("account-nohostauth", false, - mMockContext); + Account account2 = + ProviderTestUtils.setupAccount("account-nohostauth", false, mMockContext); account2.save(mMockContext); // Make sure that we return null when there's no host auth assertNull(Account.getProtocol(mMockContext, account2.mId)); @@ -372,9 +382,8 @@ public class ProviderTests extends ProviderTestCase2 { assertFalse(Account.isValidId(mMockContext, -500)); } - private final static String[] MAILBOX_UNREAD_COUNT_PROJECTION = new String [] { - MailboxColumns.UNREAD_COUNT - }; + private final static String[] MAILBOX_UNREAD_COUNT_PROJECTION = + new String[] {MailboxColumns.UNREAD_COUNT}; private final static int MAILBOX_UNREAD_COUNT_COLMUN = 0; /** @@ -385,12 +394,9 @@ public class ProviderTests extends ProviderTestCase2 { String text = null; Cursor c = null; try { - c = mMockContext.getContentResolver().query( - Mailbox.CONTENT_URI, - MAILBOX_UNREAD_COUNT_PROJECTION, - EmailContent.RECORD_ID + "=?", - new String[] { String.valueOf(mailboxId) }, - null); + c = mMockContext.getContentResolver().query(Mailbox.CONTENT_URI, + MAILBOX_UNREAD_COUNT_PROJECTION, EmailContent.RECORD_ID + "=?", + new String[] {String.valueOf(mailboxId)}, null); c.moveToFirst(); text = c.getString(MAILBOX_UNREAD_COUNT_COLMUN); } finally { @@ -400,7 +406,7 @@ public class ProviderTests extends ProviderTestCase2 { } private static String[] expectedAttachmentNames = - new String[] {"attachment1.doc", "attachment2.xls", "attachment3"}; + new String[] {"attachment1.doc", "attachment2.xls", "attachment3"}; // The lengths need to be kept in ascending order private static long[] expectedAttachmentSizes = new long[] {31415L, 97701L, 151213L}; @@ -410,12 +416,9 @@ public class ProviderTests extends ProviderTestCase2 { private Body loadBodyForMessageId(long messageId) { Cursor c = null; try { - c = mMockContext.getContentResolver().query( - EmailContent.Body.CONTENT_URI, - EmailContent.Body.CONTENT_PROJECTION, - EmailContent.Body.MESSAGE_KEY + "=?", - new String[] {String.valueOf(messageId)}, - null); + c = mMockContext.getContentResolver().query(EmailContent.Body.CONTENT_URI, + EmailContent.Body.CONTENT_PROJECTION, EmailContent.Body.MESSAGE_KEY + "=?", + new String[] {String.valueOf(messageId)}, null); int numBodies = c.getCount(); assertTrue("at most one body", numBodies < 2); return c.moveToFirst() ? EmailContent.getContent(c, Body.class) : null; @@ -437,23 +440,29 @@ public class ProviderTests extends ProviderTestCase2 { long box1Id = box1.mId; // Test a simple message (saved with no body) - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; Message message1get = EmailContent.Message.restoreMessageWithId(mMockContext, message1Id); ProviderTestUtils.assertMessageEqual("testMessageSave", message1, message1get); // Test a message saved with a body - // Note that it will read back w/o the text & html so we must extract those - Message message2 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, true, - true, mMockContext); + // Note that it will read back w/o the text & html so we must extract + // those + Message message2 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + true, + true, + mMockContext); long message2Id = message2.mId; String text2 = message2.mText; String html2 = message2.mHtml; - String textReply2 = message2.mTextReply; - String htmlReply2 = message2.mHtmlReply; long sourceKey2 = message2.mSourceKey; - String introText2 = message2.mIntroText; message2.mText = null; message2.mHtml = null; message2.mTextReply = null; @@ -467,10 +476,7 @@ public class ProviderTests extends ProviderTestCase2 { Body body2 = loadBodyForMessageId(message2Id); assertEquals("body text", text2, body2.mTextContent); assertEquals("body html", html2, body2.mHtmlContent); - assertEquals("reply text", textReply2, body2.mTextReply); - assertEquals("reply html", htmlReply2, body2.mHtmlReply); assertEquals("source key", sourceKey2, body2.mSourceKey); - assertEquals("intro text", introText2, body2.mIntroText); } @MediumTest @@ -481,32 +487,34 @@ public class ProviderTests extends ProviderTestCase2 { long box1Id = box1.mId; // Message with attachments and body - Message message3 = ProviderTestUtils.setupMessage("message3", account1Id, box1Id, true, - false, mMockContext); + Message message3 = ProviderTestUtils.setupMessage("message3", + account1Id, + box1Id, + true, + false, + mMockContext); ArrayList atts = new ArrayList(); for (int i = 0; i < 3; i++) { atts.add(ProviderTestUtils.setupAttachment( - -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], - false, mMockContext)); + -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], false, + mMockContext)); } message3.mAttachments = atts; message3.save(mMockContext); long message3Id = message3.mId; - // Now check the attachments; there should be three and they should match name and size + // Now check the attachments; there should be three and they should + // match name and size Cursor c = null; try { - // Note that there is NO guarantee of the order of returned records in the general case, - // so we specifically ask for ordering by size. The expectedAttachmentSizes array must + // Note that there is NO guarantee of the order of returned records + // in the general case, + // so we specifically ask for ordering by size. The + // expectedAttachmentSizes array must // be kept sorted by size (ascending) for this test to work properly - c = mMockContext.getContentResolver().query( - Attachment.CONTENT_URI, - Attachment.CONTENT_PROJECTION, - Attachment.MESSAGE_KEY + "=?", - new String[] { - String.valueOf(message3Id) - }, - Attachment.SIZE); + c = mMockContext.getContentResolver().query(Attachment.CONTENT_URI, + Attachment.CONTENT_PROJECTION, Attachment.MESSAGE_KEY + "=?", + new String[] {String.valueOf(message3Id)}, Attachment.SIZE); int numAtts = c.getCount(); assertEquals(3, numAtts); int i = 0; @@ -530,33 +538,35 @@ public class ProviderTests extends ProviderTestCase2 { Cursor c = null; // Message with attachments but no body - Message message4 = ProviderTestUtils.setupMessage("message4", account1Id, box1Id, false, - false, mMockContext); + Message message4 = ProviderTestUtils.setupMessage("message4", + account1Id, + box1Id, + false, + false, + mMockContext); ArrayList atts = new ArrayList(); for (int i = 0; i < 3; i++) { atts.add(ProviderTestUtils.setupAttachment( - -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], - false, mMockContext)); + -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], false, + mMockContext)); } message4.mAttachments = atts; message4.save(mMockContext); long message4Id = message4.mId; - // Now check the attachments; there should be three and they should match name and size + // Now check the attachments; there should be three and they should + // match name and size c = null; try { - // Note that there is NO guarantee of the order of returned records in the general case, - // so we specifically ask for ordering by size. The expectedAttachmentSizes array must + // Note that there is NO guarantee of the order of returned records + // in the general case, + // so we specifically ask for ordering by size. The + // expectedAttachmentSizes array must // be kept sorted by size (ascending) for this test to work properly - c = mMockContext.getContentResolver().query( - Attachment.CONTENT_URI, - Attachment.CONTENT_PROJECTION, - Attachment.MESSAGE_KEY + "=?", - new String[] { - String.valueOf(message4Id) - }, - Attachment.SIZE); + c = mMockContext.getContentResolver().query(Attachment.CONTENT_URI, + Attachment.CONTENT_PROJECTION, Attachment.MESSAGE_KEY + "=?", + new String[] {String.valueOf(message4Id)}, Attachment.SIZE); int numAtts = c.getCount(); assertEquals(3, numAtts); int i = 0; @@ -571,7 +581,7 @@ public class ProviderTests extends ProviderTestCase2 { // test EmailContent.restoreAttachmentsWitdMessageId() Attachment[] attachments = - Attachment.restoreAttachmentsWithMessageId(mMockContext, message4Id); + Attachment.restoreAttachmentsWithMessageId(mMockContext, message4Id); int size = attachments.length; assertEquals(3, size); for (int i = 0; i < size; ++i) { @@ -587,26 +597,34 @@ public class ProviderTests extends ProviderTestCase2 { Mailbox box = ProviderTestUtils.setupMailbox("box1", account.mId, true, mMockContext); // Create a message without a body, unsaved - Message message = ProviderTestUtils.setupMessage("message", account.mId, box.mId, false, - false, mMockContext); + Message message = ProviderTestUtils.setupMessage("message", + account.mId, + box.mId, + false, + false, + mMockContext); message.mText = "This is some text"; message.mHtml = "This is some text"; message.save(mMockContext); Message restoredMessage = Message.restoreMessageWithId(mMockContext, message.mId); // We should have the plain text as the snippet - assertEquals(restoredMessage.mSnippet, - TextUtilities.makeSnippetFromPlainText(message.mText)); + assertEquals( + restoredMessage.mSnippet, TextUtilities.makeSnippetFromPlainText(message.mText)); // Start again - message = ProviderTestUtils.setupMessage("message", account.mId, box.mId, false, - false, mMockContext); + message = ProviderTestUtils.setupMessage("message", + account.mId, + box.mId, + false, + false, + mMockContext); message.mText = null; message.mHtml = "This is some text"; message.save(mMockContext); restoredMessage = Message.restoreMessageWithId(mMockContext, message.mId); // We should have the plain text as the snippet - assertEquals(restoredMessage.mSnippet, - TextUtilities.makeSnippetFromHtmlText(message.mHtml)); + assertEquals( + restoredMessage.mSnippet, TextUtilities.makeSnippetFromHtmlText(message.mHtml)); } /** @@ -666,15 +684,23 @@ public class ProviderTests extends ProviderTestCase2 { long box1Id = box1.mId; // 1. create message with no body, check that returned bodyId is -1 - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; long bodyId1 = Body.lookupBodyIdWithMessageId(mMockContext, message1Id); assertEquals(bodyId1, -1); // 2. create message with body, check that returned bodyId is correct - Message message2 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, true, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + true, + true, + mMockContext); long message2Id = message2.mId; long bodyId2 = Body.lookupBodyIdWithMessageId(mMockContext, message2Id); Body body = loadBodyForMessageId(message2Id); @@ -700,21 +726,19 @@ public class ProviderTests extends ProviderTestCase2 { final String textContent = "foobar some odd text"; final String htmlContent = "and some html"; - final String textReply = "plain text reply"; - final String htmlReply = "or the html reply"; - final String introText = "fred wrote:"; ContentValues values = new ContentValues(); values.put(BodyColumns.TEXT_CONTENT, textContent); values.put(BodyColumns.HTML_CONTENT, htmlContent); - values.put(BodyColumns.TEXT_REPLY, textReply); - values.put(BodyColumns.HTML_REPLY, htmlReply); values.put(BodyColumns.SOURCE_MESSAGE_KEY, 17); - values.put(BodyColumns.INTRO_TEXT, introText); // 1 - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; Body body1 = loadBodyForMessageId(message1Id); assertNull(body1); @@ -723,14 +747,15 @@ public class ProviderTests extends ProviderTestCase2 { assertNotNull(body1); assertEquals(body1.mTextContent, textContent); assertEquals(body1.mHtmlContent, htmlContent); - assertEquals(body1.mTextReply, textReply); - assertEquals(body1.mHtmlReply, htmlReply); assertEquals(body1.mSourceKey, 17); - assertEquals(body1.mIntroText, introText); // 2 - Message message2 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, true, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + true, + true, + mMockContext); long message2Id = message2.mId; Body body2 = loadBodyForMessageId(message2Id); assertNotNull(body2); @@ -740,10 +765,7 @@ public class ProviderTests extends ProviderTestCase2 { assertNotNull(body2); assertEquals(body2.mTextContent, textContent); assertEquals(body2.mHtmlContent, htmlContent); - assertEquals(body2.mTextReply, textReply); - assertEquals(body2.mHtmlReply, htmlReply); assertEquals(body2.mSourceKey, 17); - assertEquals(body2.mIntroText, introText); } /** @@ -752,22 +774,13 @@ public class ProviderTests extends ProviderTestCase2 { public void testBodyRetrieve() { // No account needed // No mailbox needed - Message message1 = ProviderTestUtils.setupMessage("bodyretrieve", 1, 1, true, - true, mMockContext); + Message message1 = + ProviderTestUtils.setupMessage("bodyretrieve", 1, 1, true, true, mMockContext); long messageId = message1.mId; - assertEquals(message1.mText, - Body.restoreBodyTextWithMessageId(mMockContext, messageId)); - assertEquals(message1.mHtml, - Body.restoreBodyHtmlWithMessageId(mMockContext, messageId)); - assertEquals(message1.mTextReply, - Body.restoreReplyTextWithMessageId(mMockContext, messageId)); - assertEquals(message1.mHtmlReply, - Body.restoreReplyHtmlWithMessageId(mMockContext, messageId)); - assertEquals(message1.mIntroText, - Body.restoreIntroTextWithMessageId(mMockContext, messageId)); - assertEquals(message1.mSourceKey, - Body.restoreBodySourceKey(mMockContext, messageId)); + assertEquals(message1.mText, Body.restoreBodyTextWithMessageId(mMockContext, messageId)); + assertEquals(message1.mHtml, Body.restoreBodyHtmlWithMessageId(mMockContext, messageId)); + assertEquals(message1.mSourceKey, Body.restoreBodySourceKey(mMockContext, messageId)); } /** @@ -788,13 +801,21 @@ public class ProviderTests extends ProviderTestCase2 { long box1Id = box1.mId; // 1. create message without body - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; // 2. create message with body - Message message2 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, true, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + true, + true, + mMockContext); long message2Id = message2.mId; // verify body is there assertNotNull(loadBodyForMessageId(message2Id)); @@ -830,15 +851,23 @@ public class ProviderTests extends ProviderTestCase2 { long box2Id = box2.mId; // 1. create message without body - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; // 2. create message with body - Message message2 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, true, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + true, + true, + mMockContext); long message2Id = message2.mId; - //verify body is there + // verify body is there assertNotNull(loadBodyForMessageId(message2Id)); // 3. delete first message @@ -847,7 +876,8 @@ public class ProviderTests extends ProviderTestCase2 { // 4. delete some mailbox (because it triggers "delete orphan bodies") resolver.delete(ContentUris.withAppendedId(Mailbox.CONTENT_URI, box2Id), null, null); - // 5. verify body for second message wasn't deleted during "delete orphan bodies" + // 5. verify body for second message wasn't deleted during + // "delete orphan bodies" assertNotNull(loadBodyForMessageId(message2Id)); } @@ -857,8 +887,8 @@ public class ProviderTests extends ProviderTestCase2 { * single column returned with count(*), rather than to the query itself) */ private int count(Context context, Uri uri, String selection, String[] selectionArgs) { - Cursor c = context.getContentResolver().query(uri, EmailContent.ID_PROJECTION, selection, - selectionArgs, null); + Cursor c = context.getContentResolver() + .query(uri, EmailContent.ID_PROJECTION, selection, selectionArgs, null); try { return c.getCount(); } finally { @@ -888,19 +918,18 @@ public class ProviderTests extends ProviderTestCase2 { // Check normal case, special case (limit 1), and arbitrary limits assertEquals(8, count(mMockContext, Message.CONTENT_URI, null, null)); - assertEquals(1, count(mMockContext, EmailContent.uriWithLimit(Message.CONTENT_URI, 1), - null, null)); - assertEquals(3, count(mMockContext, EmailContent.uriWithLimit(Message.CONTENT_URI, 3), - null, null)); + assertEquals(1, + count(mMockContext, EmailContent.uriWithLimit(Message.CONTENT_URI, 1), null, null)); + assertEquals(3, + count(mMockContext, EmailContent.uriWithLimit(Message.CONTENT_URI, 3), null, null)); assertEquals(8, count(mMockContext, EmailContent.uriWithLimit(Message.CONTENT_URI, 100), null, null)); // Check that it works with selection/selection args String[] args = new String[] {Long.toString(box1.mId)}; - assertEquals(4, count(mMockContext, Message.CONTENT_URI, - MessageColumns.MAILBOX_KEY + "=?", args)); - assertEquals(1, count(mMockContext, - EmailContent.uriWithLimit(Message.CONTENT_URI, 1), + assertEquals(4, + count(mMockContext, Message.CONTENT_URI, MessageColumns.MAILBOX_KEY + "=?", args)); + assertEquals(1, count(mMockContext, EmailContent.uriWithLimit(Message.CONTENT_URI, 1), MessageColumns.MAILBOX_KEY + "=?", args)); } @@ -912,7 +941,7 @@ public class ProviderTests extends ProviderTestCase2 { * 4. delete some other mailbox -- this triggers delete orphan bodies. * 5. verify that body for message 2 has not been deleted. */ - public void testDeleteOrphanMessages() { + public void testDeleteOrphanMessages() { final ContentResolver resolver = mMockContext.getContentResolver(); final Context context = mMockContext; @@ -922,34 +951,66 @@ public class ProviderTests extends ProviderTestCase2 { Mailbox box2 = ProviderTestUtils.setupMailbox("box2", acct.mId, true, context); // Create 4 messages in box1 - Message msg1_1 = - ProviderTestUtils.setupMessage("message1", acct.mId, box1.mId, false, true, context); - Message msg1_2 = - ProviderTestUtils.setupMessage("message2", acct.mId, box1.mId, false, true, context); - Message msg1_3 = - ProviderTestUtils.setupMessage("message3", acct.mId, box1.mId, false, true, context); - Message msg1_4 = - ProviderTestUtils.setupMessage("message4", acct.mId, box1.mId, false, true, context); + Message msg1_1 = ProviderTestUtils.setupMessage("message1", + acct.mId, + box1.mId, + false, + true, + context); + Message msg1_2 = ProviderTestUtils.setupMessage("message2", + acct.mId, + box1.mId, + false, + true, + context); + Message msg1_3 = ProviderTestUtils.setupMessage("message3", + acct.mId, + box1.mId, + false, + true, + context); + Message msg1_4 = ProviderTestUtils.setupMessage("message4", + acct.mId, + box1.mId, + false, + true, + context); // Create 4 messages in box2 - Message msg2_1 = - ProviderTestUtils.setupMessage("message1", acct.mId, box2.mId, false, true, context); - Message msg2_2 = - ProviderTestUtils.setupMessage("message2", acct.mId, box2.mId, false, true, context); - Message msg2_3 = - ProviderTestUtils.setupMessage("message3", acct.mId, box2.mId, false, true, context); - Message msg2_4 = - ProviderTestUtils.setupMessage("message4", acct.mId, box2.mId, false, true, context); + Message msg2_1 = ProviderTestUtils.setupMessage("message1", + acct.mId, + box2.mId, + false, + true, + context); + Message msg2_2 = ProviderTestUtils.setupMessage("message2", + acct.mId, + box2.mId, + false, + true, + context); + Message msg2_3 = ProviderTestUtils.setupMessage("message3", + acct.mId, + box2.mId, + false, + true, + context); + Message msg2_4 = ProviderTestUtils.setupMessage("message4", + acct.mId, + box2.mId, + false, + true, + context); // Delete 2 from each mailbox - resolver.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_1.mId), - null, null); - resolver.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_2.mId), - null, null); - resolver.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_1.mId), - null, null); - resolver.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_2.mId), - null, null); + resolver.delete( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_1.mId), null, null); + resolver.delete( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_2.mId), null, null); + resolver.delete( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_1.mId), null, null); + resolver.delete( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_2.mId), null, null); // There should be 4 items in the deleted item table assertEquals(4, EmailContent.count(context, Message.DELETED_CONTENT_URI, null, null)); @@ -957,36 +1018,56 @@ public class ProviderTests extends ProviderTestCase2 { // Update 2 from each mailbox ContentValues v = new ContentValues(); v.put(MessageColumns.DISPLAY_NAME, "--updated--"); - resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_3.mId), - v, null, null); - resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_4.mId), - v, null, null); - resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_3.mId), - v, null, null); - resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_4.mId), - v, null, null); + resolver.update( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_3.mId), v, null, null); + resolver.update( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg1_4.mId), v, null, null); + resolver.update( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_3.mId), v, null, null); + resolver.update( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg2_4.mId), v, null, null); - // There should be 4 items in the updated item table + // There should be 4 items in the updated item table assertEquals(4, EmailContent.count(context, Message.UPDATED_CONTENT_URI, null, null)); - // Manually add 2 messages from a "deleted" mailbox to deleted and updated tables + // Manually add 2 messages from a "deleted" mailbox to deleted and + // updated tables // Use a value > 2 for the deleted box id long delBoxId = 10; // Create 4 messages in the "deleted" mailbox - Message msgX_A = - ProviderTestUtils.setupMessage("messageA", acct.mId, delBoxId, false, false, context); - Message msgX_B = - ProviderTestUtils.setupMessage("messageB", acct.mId, delBoxId, false, false, context); - Message msgX_C = - ProviderTestUtils.setupMessage("messageC", acct.mId, delBoxId, false, false, context); - Message msgX_D = - ProviderTestUtils.setupMessage("messageD", acct.mId, delBoxId, false, false, context); + Message msgX_A = ProviderTestUtils.setupMessage("messageA", + acct.mId, + delBoxId, + false, + false, + context); + Message msgX_B = ProviderTestUtils.setupMessage("messageB", + acct.mId, + delBoxId, + false, + false, + context); + Message msgX_C = ProviderTestUtils.setupMessage("messageC", + acct.mId, + delBoxId, + false, + false, + context); + Message msgX_D = ProviderTestUtils.setupMessage("messageD", + acct.mId, + delBoxId, + false, + false, + context); ContentValues cv; - // We have to assign id's manually because there are no autoincrement id's for these tables - // Start with an id that won't exist, since id's in these tables must be unique + // We have to assign id's manually because there are no autoincrement + // id's for these tables + // Start with an id that won't exist, since id's in these tables must be + // unique long msgId = 10; - // It's illegal to manually insert these, so we need to catch the exception + // It's illegal to manually insert these, so we need to catch the + // exception // NOTE: The insert succeeds, and then throws the exception try { cv = msgX_A.toContentValues(); @@ -1018,12 +1099,13 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(6, EmailContent.count(context, Message.DELETED_CONTENT_URI, null, null)); // Delete the orphans - EmailProvider.deleteMessageOrphans(EmailProvider.getReadableDatabase(context), - Message.DELETED_TABLE_NAME); - EmailProvider.deleteMessageOrphans(EmailProvider.getReadableDatabase(context), - Message.UPDATED_TABLE_NAME); + EmailProvider.deleteMessageOrphans( + getProvider().getDatabase(context), Message.DELETED_TABLE_NAME); + EmailProvider.deleteMessageOrphans( + getProvider().getDatabase(context), Message.UPDATED_TABLE_NAME); - // There should now be 4 messages in each of the deleted and updated tables again + // There should now be 4 messages in each of the deleted and updated + // tables again assertEquals(4, EmailContent.count(context, Message.UPDATED_CONTENT_URI, null, null)); assertEquals(4, EmailContent.count(context, Message.DELETED_CONTENT_URI, null, null)); } @@ -1038,16 +1120,24 @@ public class ProviderTests extends ProviderTestCase2 { long account1Id = account1.mId; Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mMockContext); long box1Id = box1.mId; - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; - Message message2 = ProviderTestUtils.setupMessage("message2", account1Id, box1Id, false, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message2", + account1Id, + box1Id, + false, + true, + mMockContext); long message2Id = message2.mId; - String selection = EmailContent.MessageColumns.ACCOUNT_KEY + "=? AND " + - EmailContent.MessageColumns.MAILBOX_KEY + "=?"; - String[] selArgs = new String[] { String.valueOf(account1Id), String.valueOf(box1Id) }; + String selection = EmailContent.MessageColumns.ACCOUNT_KEY + "=? AND " + + EmailContent.MessageColumns.MAILBOX_KEY + "=?"; + String[] selArgs = new String[] {String.valueOf(account1Id), String.valueOf(box1Id)}; // make sure there are two messages int numMessages = EmailContent.count(mMockContext, Message.CONTENT_URI, selection, selArgs); @@ -1076,31 +1166,37 @@ public class ProviderTests extends ProviderTestCase2 { * TODO: attachments */ public void testSyncedMessageDelete() { - Account account1 = ProviderTestUtils.setupAccount("synced-message-delete", true, - mMockContext); + Account account1 = + ProviderTestUtils.setupAccount("synced-message-delete", true, mMockContext); long account1Id = account1.mId; Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mMockContext); long box1Id = box1.mId; - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; - Message message2 = ProviderTestUtils.setupMessage("message2", account1Id, box1Id, false, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message2", + account1Id, + box1Id, + false, + true, + mMockContext); long message2Id = message2.mId; String selection = EmailContent.MessageColumns.ACCOUNT_KEY + "=? AND " + EmailContent.MessageColumns.MAILBOX_KEY + "=?"; - String[] selArgs = new String[] { - String.valueOf(account1Id), String.valueOf(box1Id) - }; + String[] selArgs = new String[] {String.valueOf(account1Id), String.valueOf(box1Id)}; // make sure there are two messages int numMessages = EmailContent.count(mMockContext, Message.CONTENT_URI, selection, selArgs); assertEquals(2, numMessages); // make sure we start with no synced deletions - numMessages = EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, selArgs); assertEquals(0, numMessages); // now delete one of them SYNCED @@ -1112,8 +1208,8 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(1, numMessages); // make sure there's one synced deletion now - numMessages = EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, selArgs); assertEquals(1, numMessages); // now delete the other one NOT SYNCED @@ -1125,8 +1221,8 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(0, numMessages); // make sure there's still one deletion now - numMessages = EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, selArgs); assertEquals(1, numMessages); } @@ -1140,19 +1236,25 @@ public class ProviderTests extends ProviderTestCase2 { long account1Id = account1.mId; Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mMockContext); long box1Id = box1.mId; - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, false, - true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); long message1Id = message1.mId; - Message message2 = ProviderTestUtils.setupMessage("message2", account1Id, box1Id, false, - true, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message2", + account1Id, + box1Id, + false, + true, + mMockContext); long message2Id = message2.mId; ContentResolver cr = mMockContext.getContentResolver(); String selection = EmailContent.MessageColumns.ACCOUNT_KEY + "=? AND " + EmailContent.MessageColumns.MAILBOX_KEY + "=?"; - String[] selArgs = new String[] { - String.valueOf(account1Id), String.valueOf(box1Id) - }; + String[] selArgs = new String[] {String.valueOf(account1Id), String.valueOf(box1Id)}; // make sure there are two messages int numMessages = EmailContent.count(mMockContext, Message.CONTENT_URI, selection, selArgs); @@ -1165,8 +1267,8 @@ public class ProviderTests extends ProviderTestCase2 { cr.update(uri, cv, null, null); // make sure there's no updated message - numMessages = EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, selArgs); assertEquals(0, numMessages); // get the message back from the provider, make sure the change "stuck" @@ -1180,8 +1282,8 @@ public class ProviderTests extends ProviderTestCase2 { cr.update(uri, cv, null, null); // make sure there's one updated message - numMessages = EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, selArgs); assertEquals(1, numMessages); // get the message back from the provider, make sure the change "stuck", @@ -1190,8 +1292,8 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals("from-list", restoredMessage.mFrom); // get the original message back from the provider - Cursor c = cr.query(Message.UPDATED_CONTENT_URI, Message.CONTENT_PROJECTION, null, null, - null); + Cursor c = + cr.query(Message.UPDATED_CONTENT_URI, Message.CONTENT_PROJECTION, null, null, null); try { assertTrue(c.moveToFirst()); Message originalMessage = EmailContent.getContent(c, Message.class); @@ -1207,13 +1309,13 @@ public class ProviderTests extends ProviderTestCase2 { cr.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message2Id), null, null); // hey, presto! the change should be gone - numMessages = EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, selArgs); assertEquals(0, numMessages); // and there should now be a deleted record - numMessages = EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, selArgs); assertEquals(1, numMessages); } @@ -1225,15 +1327,23 @@ public class ProviderTests extends ProviderTestCase2 { * TODO: create other account, mailbox & messages and confirm the right objects were deleted */ public void testCascadeDeleteAccount() { - Account account1 = ProviderTestUtils.setupAccount("account-delete-cascade", true, - mMockContext); + Account account1 = + ProviderTestUtils.setupAccount("account-delete-cascade", true, mMockContext); long account1Id = account1.mId; Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mMockContext); long box1Id = box1.mId; - /* Message message1 = */ ProviderTestUtils.setupMessage("message1", account1Id, box1Id, - false, true, mMockContext); - /* Message message2 = */ ProviderTestUtils.setupMessage("message2", account1Id, box1Id, - false, true, mMockContext); + /* Message message1 = */ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); + /* Message message2 = */ProviderTestUtils.setupMessage("message2", + account1Id, + box1Id, + false, + true, + mMockContext); // make sure there is one account, one mailbox, and two messages int numAccounts = EmailContent.count(mMockContext, Account.CONTENT_URI, null, null); @@ -1263,25 +1373,41 @@ public class ProviderTests extends ProviderTestCase2 { * TODO: create other mailbox & messages and confirm the right objects were deleted */ public void testCascadeDeleteMailbox() { - Account account1 = ProviderTestUtils.setupAccount("mailbox-delete-cascade", true, - mMockContext); + Account account1 = + ProviderTestUtils.setupAccount("mailbox-delete-cascade", true, mMockContext); long account1Id = account1.mId; Mailbox box1 = ProviderTestUtils.setupMailbox("box1", account1Id, true, mMockContext); long box1Id = box1.mId; - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, - false, true, mMockContext); - Message message2 = ProviderTestUtils.setupMessage("message2", account1Id, box1Id, - false, true, mMockContext); - Message message3 = ProviderTestUtils.setupMessage("message3", account1Id, box1Id, - false, true, mMockContext); - Message message4 = ProviderTestUtils.setupMessage("message4", account1Id, box1Id, - false, true, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + false, + true, + mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message2", + account1Id, + box1Id, + false, + true, + mMockContext); + Message message3 = ProviderTestUtils.setupMessage("message3", + account1Id, + box1Id, + false, + true, + mMockContext); + Message message4 = ProviderTestUtils.setupMessage("message4", + account1Id, + box1Id, + false, + true, + mMockContext); ProviderTestUtils.setupMessage("message5", account1Id, box1Id, false, true, mMockContext); ProviderTestUtils.setupMessage("message6", account1Id, box1Id, false, true, mMockContext); - String selection = EmailContent.MessageColumns.ACCOUNT_KEY + "=? AND " + - EmailContent.MessageColumns.MAILBOX_KEY + "=?"; - String[] selArgs = new String[] { String.valueOf(account1Id), String.valueOf(box1Id) }; + String selection = EmailContent.MessageColumns.ACCOUNT_KEY + "=? AND " + + EmailContent.MessageColumns.MAILBOX_KEY + "=?"; + String[] selArgs = new String[] {String.valueOf(account1Id), String.valueOf(box1Id)}; // make sure there are six messages int numMessages = EmailContent.count(mMockContext, Message.CONTENT_URI, selection, selArgs); @@ -1292,24 +1418,25 @@ public class ProviderTests extends ProviderTestCase2 { ContentResolver resolver = mMockContext.getContentResolver(); // Update two messages - resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message1.mId), - cv, null, null); - resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message2.mId), - cv, null, null); + resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message1.mId), cv, + null, null); + resolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message2.mId), cv, + null, null); // Delete two messages - resolver.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message3.mId), - null, null); - resolver.delete(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message4.mId), - null, null); + resolver.delete( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message3.mId), null, null); + resolver.delete( + ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, message4.mId), null, null); - // There should now be two messages in updated/deleted, and 4 in messages + // There should now be two messages in updated/deleted, and 4 in + // messages numMessages = EmailContent.count(mMockContext, Message.CONTENT_URI, selection, selArgs); assertEquals(4, numMessages); - numMessages = EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, selArgs); assertEquals(2, numMessages); - numMessages = EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, selArgs); assertEquals(2, numMessages); // now delete the mailbox @@ -1319,11 +1446,11 @@ public class ProviderTests extends ProviderTestCase2 { // there should now be zero messages in all three tables numMessages = EmailContent.count(mMockContext, Message.CONTENT_URI, selection, selArgs); assertEquals(0, numMessages); - numMessages = EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.DELETED_CONTENT_URI, selection, selArgs); assertEquals(0, numMessages); - numMessages = EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, - selArgs); + numMessages = + EmailContent.count(mMockContext, Message.UPDATED_CONTENT_URI, selection, selArgs); assertEquals(0, numMessages); } @@ -1338,42 +1465,51 @@ public class ProviderTests extends ProviderTestCase2 { long box1Id = box1.mId; // Each message has a body, and also give each 2 attachments - Message message1 = ProviderTestUtils.setupMessage("message1", account1Id, box1Id, true, - false, mMockContext); + Message message1 = ProviderTestUtils.setupMessage("message1", + account1Id, + box1Id, + true, + false, + mMockContext); ArrayList atts = new ArrayList(); for (int i = 0; i < 2; i++) { atts.add(ProviderTestUtils.setupAttachment( - -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], - false, mMockContext)); + -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], false, + mMockContext)); } message1.mAttachments = atts; message1.save(mMockContext); long message1Id = message1.mId; - Message message2 = ProviderTestUtils.setupMessage("message2", account1Id, box1Id, true, - false, mMockContext); + Message message2 = ProviderTestUtils.setupMessage("message2", + account1Id, + box1Id, + true, + false, + mMockContext); atts = new ArrayList(); for (int i = 0; i < 2; i++) { atts.add(ProviderTestUtils.setupAttachment( - -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], - false, mMockContext)); + -1, expectedAttachmentNames[i], expectedAttachmentSizes[i], false, + mMockContext)); } message2.mAttachments = atts; message2.save(mMockContext); long message2Id = message2.mId; - // Set up to test total counts of bodies & attachments for our test messages + // Set up to test total counts of bodies & attachments for our test + // messages String bodySelection = BodyColumns.MESSAGE_KEY + " IN (?,?)"; String attachmentSelection = AttachmentColumns.MESSAGE_KEY + " IN (?,?)"; - String[] selArgs = new String[] { String.valueOf(message1Id), String.valueOf(message2Id) }; + String[] selArgs = new String[] {String.valueOf(message1Id), String.valueOf(message2Id)}; // make sure there are two bodies int numBodies = EmailContent.count(mMockContext, Body.CONTENT_URI, bodySelection, selArgs); assertEquals(2, numBodies); // make sure there are four attachments - int numAttachments = EmailContent.count(mMockContext, Attachment.CONTENT_URI, - attachmentSelection, selArgs); + int numAttachments = EmailContent.count( + mMockContext, Attachment.CONTENT_URI, attachmentSelection, selArgs); assertEquals(4, numAttachments); // now delete one of the messages @@ -1384,8 +1520,8 @@ public class ProviderTests extends ProviderTestCase2 { numBodies = EmailContent.count(mMockContext, Body.CONTENT_URI, bodySelection, selArgs); assertEquals(1, numBodies); - numAttachments = EmailContent.count(mMockContext, Attachment.CONTENT_URI, - attachmentSelection, selArgs); + numAttachments = EmailContent.count( + mMockContext, Attachment.CONTENT_URI, attachmentSelection, selArgs); assertEquals(2, numAttachments); // now delete the other message @@ -1396,8 +1532,8 @@ public class ProviderTests extends ProviderTestCase2 { numBodies = EmailContent.count(mMockContext, Body.CONTENT_URI, bodySelection, selArgs); assertEquals(0, numBodies); - numAttachments = EmailContent.count(mMockContext, Attachment.CONTENT_URI, - attachmentSelection, selArgs); + numAttachments = EmailContent.count( + mMockContext, Attachment.CONTENT_URI, attachmentSelection, selArgs); assertEquals(0, numAttachments); } @@ -1422,7 +1558,7 @@ public class ProviderTests extends ProviderTestCase2 { uniqueFile = Attachment.createUniqueFile(fileName); assertEquals("A11achm3n1-3.doc", uniqueFile.getName()); } - } + } fileName = "A11achm3n1"; uniqueFile = Attachment.createUniqueFile(fileName); assertEquals(fileName, uniqueFile.getName()); @@ -1432,7 +1568,8 @@ public class ProviderTests extends ProviderTestCase2 { } } finally { File directory = Environment.getExternalStorageDirectory(); - // These are the files that should be created earlier in the test. Make sure + // These are the files that should be created earlier in the test. + // Make sure // they are deleted for the next go-around String[] fileNames = new String[] {"A11achm3n1.doc", "A11achm3n1-2.doc", "A11achm3n1"}; int length = fileNames.length; @@ -1450,17 +1587,19 @@ public class ProviderTests extends ProviderTestCase2 { */ public void testGetAttachmentByMessageIdUri() { - // Note, we don't strictly need accounts, mailboxes or messages to run this test. + // Note, we don't strictly need accounts, mailboxes or messages to run + // this test. Attachment a1 = ProviderTestUtils.setupAttachment(1, "a1", 100, true, mMockContext); Attachment a2 = ProviderTestUtils.setupAttachment(1, "a2", 200, true, mMockContext); ProviderTestUtils.setupAttachment(2, "a3", 300, true, mMockContext); ProviderTestUtils.setupAttachment(2, "a4", 400, true, mMockContext); // Now ask for the attachments of message id=1 - // Note: Using the "sort by size" trick to bring them back in expected order + // Note: Using the "sort by size" trick to bring them back in expected + // order Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, 1); - Cursor c = mMockContext.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, - null, null, Attachment.SIZE); + Cursor c = mMockContext.getContentResolver() + .query(uri, Attachment.CONTENT_PROJECTION, null, null, Attachment.SIZE); assertEquals(2, c.getCount()); try { @@ -1481,7 +1620,8 @@ public class ProviderTests extends ProviderTestCase2 { public void testDeleteAttachmentByMessageIdUri() { ContentResolver mockResolver = mMockContext.getContentResolver(); - // Note, we don't strictly need accounts, mailboxes or messages to run this test. + // Note, we don't strictly need accounts, mailboxes or messages to run + // this test. ProviderTestUtils.setupAttachment(1, "a1", 100, true, mMockContext); ProviderTestUtils.setupAttachment(1, "a2", 200, true, mMockContext); Attachment a3 = ProviderTestUtils.setupAttachment(2, "a3", 300, true, mMockContext); @@ -1491,10 +1631,12 @@ public class ProviderTests extends ProviderTestCase2 { Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, 1); mockResolver.delete(uri, null, null); - // Read back all attachments and confirm that we have the expected remaining attachments - // (the attachments that are set for message id=2). Note order-by size to simplify test. - Cursor c = mockResolver.query(Attachment.CONTENT_URI, Attachment.CONTENT_PROJECTION, - null, null, Attachment.SIZE); + // Read back all attachments and confirm that we have the expected + // remaining attachments + // (the attachments that are set for message id=2). Note order-by size + // to simplify test. + Cursor c = mockResolver.query( + Attachment.CONTENT_URI, Attachment.CONTENT_PROJECTION, null, null, Attachment.SIZE); assertEquals(2, c.getCount()); try { @@ -1512,101 +1654,110 @@ public class ProviderTests extends ProviderTestCase2 { @SmallTest public void testGetDefaultAccountNoneExplicitlySet() { Account account1 = ProviderTestUtils.setupAccount("account-default-1", false, mMockContext); - account1.mIsDefault = false; account1.save(mMockContext); // We should find account1 as default - long defaultAccountId = Account.getDefaultAccountId(mMockContext); + long defaultAccountId = Account.getDefaultAccountId(mMockContext, Account.NO_ACCOUNT); assertEquals(defaultAccountId, account1.mId); Account account2 = ProviderTestUtils.setupAccount("account-default-2", false, mMockContext); - account2.mIsDefault = false; account2.save(mMockContext); Account account3 = ProviderTestUtils.setupAccount("account-default-3", false, mMockContext); - account3.mIsDefault = false; account3.save(mMockContext); - // We should find the earliest one as the default, so that it can be consistent on + // We should find the earliest one as the default, so that it can be + // consistent on // repeated calls. - defaultAccountId = Account.getDefaultAccountId(mMockContext); + defaultAccountId = Account.getDefaultAccountId(mMockContext, Account.NO_ACCOUNT); assertTrue(defaultAccountId == account1.mId); } /** - * Tests of default account behavior + * Tests of default account behavior. Note that default account behavior is handled differently + * now. If there is no last used account, the first account found by our account query is the + * default. If there is a last used account, the last used account is our default. * * 1. Simple set/get * 2. Moving default between 3 accounts * 3. Delete default, make sure another becomes default */ - public void testSetGetDefaultAccount() { + public void testGetDefaultAccountWithLastUsedAccount() { + long lastUsedAccountId = Account.NO_ACCOUNT; + // There should be no default account if there are no accounts - long defaultAccountId = Account.getDefaultAccountId(mMockContext); + long defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertEquals(Account.NO_ACCOUNT, defaultAccountId); Account account1 = ProviderTestUtils.setupAccount("account-default-1", false, mMockContext); - account1.mIsDefault = false; account1.save(mMockContext); long account1Id = account1.mId; Account account2 = ProviderTestUtils.setupAccount("account-default-2", false, mMockContext); - account2.mIsDefault = false; account2.save(mMockContext); long account2Id = account2.mId; Account account3 = ProviderTestUtils.setupAccount("account-default-3", false, mMockContext); - account3.mIsDefault = false; account3.save(mMockContext); long account3Id = account3.mId; - // With three accounts, but none marked default, confirm that the first one is the default. - defaultAccountId = Account.getDefaultAccountId(mMockContext); + // With three accounts, but none marked default, confirm that the first + // one is the default. + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertTrue(defaultAccountId == account1Id); - updateIsDefault(account1, true); - defaultAccountId = Account.getDefaultAccountId(mMockContext); + // updating lastUsedAccountId locally instead of updating through + // Preferences + lastUsedAccountId = defaultAccountId; + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertEquals(account1Id, defaultAccountId); - updateIsDefault(account2, true); - defaultAccountId = Account.getDefaultAccountId(mMockContext); + // updating lastUsedAccountId locally instead of updating through + // Preferences + lastUsedAccountId = account2Id; + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertEquals(account2Id, defaultAccountId); - updateIsDefault(account3, true); - defaultAccountId = Account.getDefaultAccountId(mMockContext); + // updating lastUsedAccountId locally instead of updating through + // Preferences + lastUsedAccountId = account3Id; + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertEquals(account3Id, defaultAccountId); // Now delete a non-default account and confirm no change Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, account1Id); mMockContext.getContentResolver().delete(uri, null, null); - defaultAccountId = Account.getDefaultAccountId(mMockContext); + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertEquals(account3Id, defaultAccountId); - // Now confirm deleting the default account and it switches to another one + // Now confirm deleting the default account and it switches to another + // one uri = ContentUris.withAppendedId(Account.CONTENT_URI, account3Id); mMockContext.getContentResolver().delete(uri, null, null); - defaultAccountId = Account.getDefaultAccountId(mMockContext); + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); assertEquals(account2Id, defaultAccountId); - // Now delete the final account and confirm there are no default accounts again + // updating lastUsedAccountId locally instead of updating through + // Preferences + lastUsedAccountId = defaultAccountId; + + // Now delete the final account and confirm there are no default + // accounts again uri = ContentUris.withAppendedId(Account.CONTENT_URI, account2Id); mMockContext.getContentResolver().delete(uri, null, null); - defaultAccountId = Account.getDefaultAccountId(mMockContext); - assertEquals(-1, defaultAccountId); + defaultAccountId = Account.getDefaultAccountId(mMockContext, lastUsedAccountId); + assertEquals(Account.NO_ACCOUNT, defaultAccountId); } - private void updateIsDefault(Account account, boolean newState) { - account.setDefaultAccount(newState); - ContentValues cv = new ContentValues(); - cv.put(AccountColumns.IS_DEFAULT, account.mIsDefault); - account.update(mMockContext, cv); - } - - public static Message setupUnreadMessage(String name, long accountId, long mailboxId, - boolean addBody, boolean saveIt, Context context) { + public static Message setupUnreadMessage(String name, + long accountId, + long mailboxId, + boolean addBody, + boolean saveIt, + Context context) { Message msg = - ProviderTestUtils.setupMessage(name, accountId, mailboxId, addBody, false, context); + ProviderTestUtils.setupMessage(name, accountId, mailboxId, addBody, false, context); msg.mFlagRead = false; if (saveIt) { msg.save(context); @@ -1627,12 +1778,12 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(0, getUnreadCount(boxC.mId)); // Create 4 unread messages (only 3 named) in boxA - Message message1 = setupUnreadMessage("message1", account.mId, boxA.mId, - false, true, mMockContext); - Message message2= setupUnreadMessage("message2", account.mId, boxA.mId, - false, true, mMockContext); - Message message3 = setupUnreadMessage("message3", account.mId, boxA.mId, - false, true, mMockContext); + Message message1 = + setupUnreadMessage("message1", account.mId, boxA.mId, false, true, mMockContext); + Message message2 = + setupUnreadMessage("message2", account.mId, boxA.mId, false, true, mMockContext); + Message message3 = + setupUnreadMessage("message3", account.mId, boxA.mId, false, true, mMockContext); setupUnreadMessage("message4", account.mId, boxC.mId, false, true, mMockContext); // Make sure the unreads are where we expect them @@ -1640,7 +1791,8 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(0, getUnreadCount(boxB.mId)); assertEquals(1, getUnreadCount(boxC.mId)); - // After deleting message 1, the count in box A should be decremented (to 2) + // After deleting message 1, the count in box A should be decremented + // (to 2) ContentResolver cr = mMockContext.getContentResolver(); Uri uri = ContentUris.withAppendedId(Message.CONTENT_URI, message1.mId); cr.delete(uri, null, null); @@ -1674,7 +1826,8 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(1, getUnreadCount(boxB.mId)); assertEquals(1, getUnreadCount(boxC.mId)); - // Mark message 3 unread; it's now in box C, so that box's count should go up to 3 + // Mark message 3 unread; it's now in box C, so that box's count should + // go up to 3 cv.clear(); cv.put(MessageColumns.FLAG_READ, 0); cr.update(ContentUris.withAppendedId(Message.CONTENT_URI, message3.mId), cv, null, null); @@ -1688,9 +1841,9 @@ public class ProviderTests extends ProviderTestCase2 { * Check that it returns exacly the same string as the one used previously for index creation. */ public void testCreateIndex() { - String oldStr = "create index message_" + MessageColumns.TIMESTAMP - + " on " + Message.TABLE_NAME + " (" + MessageColumns.TIMESTAMP + ");"; - String newStr = EmailProvider.createIndex(Message.TABLE_NAME, MessageColumns.TIMESTAMP); + String oldStr = "create index message_" + MessageColumns.TIMESTAMP + " on " + + Message.TABLE_NAME + " (" + MessageColumns.TIMESTAMP + ");"; + String newStr = DBHelper.createIndex(Message.TABLE_NAME, MessageColumns.TIMESTAMP); assertEquals(newStr, oldStr); } @@ -1717,7 +1870,8 @@ public class ProviderTests extends ProviderTestCase2 { // Find the EmailProvider.db file File dbFile = mMockContext.getDatabasePath(EmailProvider.DATABASE_NAME); - // The EmailProvider.db database should exist (the provider creates it automatically) + // The EmailProvider.db database should exist (the provider creates it + // automatically) assertTrue(dbFile != null); assertTrue(dbFile.exists()); // Delete it, and confirm it is gone @@ -1731,18 +1885,23 @@ public class ProviderTests extends ProviderTestCase2 { assertTrue(dbFile.exists()); // URI to uncache the databases - // This simulates the Provider starting up again (otherwise, it will still be pointing to + // This simulates the Provider starting up again (otherwise, it will + // still be pointing to // the already opened files) - // Note that we only have access to the EmailProvider via the ContentResolver; therefore, + // Note that we only have access to the EmailProvider via the + // ContentResolver; therefore, // we cannot directly call into the provider and use a URI for this resolver.update(EmailProvider.INTEGRITY_CHECK_URI, null, null, null); - // TODO We should check for the deletion of attachment files once this is implemented in + // TODO We should check for the deletion of attachment files once this + // is implemented in // the provider // Explanation for what happens below... - // The next time the database is created by the provider, it will notice that there's - // already a EmailProviderBody.db file. In this case, it will delete that database to + // The next time the database is created by the provider, it will notice + // that there's + // already a EmailProviderBody.db file. In this case, it will delete + // that database to // ensure that both are in sync (and empty) // Confirm there are no bodies @@ -1777,7 +1936,8 @@ public class ProviderTests extends ProviderTestCase2 { // Find the EmailProviderBody.db file File dbFile = mMockContext.getDatabasePath(EmailProvider.BODY_DATABASE_NAME); - // The EmailProviderBody.db database should exist (the provider creates it automatically) + // The EmailProviderBody.db database should exist (the provider creates + // it automatically) assertTrue(dbFile != null); assertTrue(dbFile.exists()); // Delete it, and confirm it is gone @@ -1791,18 +1951,23 @@ public class ProviderTests extends ProviderTestCase2 { assertTrue(dbFile.exists()); // URI to uncache the databases - // This simulates the Provider starting up again (otherwise, it will still be pointing to + // This simulates the Provider starting up again (otherwise, it will + // still be pointing to // the already opened files) - // Note that we only have access to the EmailProvider via the ContentResolver; therefore, + // Note that we only have access to the EmailProvider via the + // ContentResolver; therefore, // we cannot directly call into the provider and use a URI for this resolver.update(EmailProvider.INTEGRITY_CHECK_URI, null, null, null); - // TODO We should check for the deletion of attachment files once this is implemented in + // TODO We should check for the deletion of attachment files once this + // is implemented in // the provider // Explanation for what happens below... - // The next time the body database is created by the provider, it will notice that there's - // already a populated EmailProvider.db file. In this case, it will delete that database to + // The next time the body database is created by the provider, it will + // notice that there's + // already a populated EmailProvider.db file. In this case, it will + // delete that database to // ensure that both are in sync (and empty) // Confirm there are no messages @@ -1824,51 +1989,40 @@ public class ProviderTests extends ProviderTestCase2 { assertFalse(Account.isSecurityHold(context, acct1.mId)); assertTrue(Account.isSecurityHold(context, acct2.mId)); - assertFalse(Account.isSecurityHold(context, 9999999)); // No such account - } + assertFalse(Account.isSecurityHold(context, 9999999)); // No such + // account + } public void testClearAccountHoldFlags() { Account a1 = ProviderTestUtils.setupAccount("holdflag-1", false, mMockContext); - a1.mFlags = Account.FLAGS_NOTIFY_NEW_MAIL; + a1.mFlags = Account.FLAGS_SUPPORTS_SEARCH; a1.mPolicy = new Policy(); a1.save(mMockContext); Account a2 = ProviderTestUtils.setupAccount("holdflag-2", false, mMockContext); - a2.mFlags = Account.FLAGS_VIBRATE_ALWAYS | Account.FLAGS_SECURITY_HOLD; + a2.mFlags = Account.FLAGS_SUPPORTS_SMART_FORWARD | Account.FLAGS_SECURITY_HOLD; a2.mPolicy = new Policy(); a2.save(mMockContext); // bulk clear Account.clearSecurityHoldOnAllAccounts(mMockContext); - // confirm new values as expected - no hold flags; other flags unmolested + // confirm new values as expected - no hold flags; other flags + // unmolested Account a1a = Account.restoreAccountWithId(mMockContext, a1.mId); - assertEquals(Account.FLAGS_NOTIFY_NEW_MAIL, a1a.mFlags); + assertEquals(Account.FLAGS_SUPPORTS_SEARCH, a1a.mFlags); Account a2a = Account.restoreAccountWithId(mMockContext, a2.mId); - assertEquals(Account.FLAGS_VIBRATE_ALWAYS, a2a.mFlags); + assertEquals(Account.FLAGS_SUPPORTS_SMART_FORWARD, a2a.mFlags); } private static Message createMessage(Context c, Mailbox b, boolean starred, boolean read) { - return ProviderTestUtils.setupMessage( - "1", b.mAccountKey, b.mId, true, true, c, starred, read); - } - - public void testAccountIsEasAccount() { - Account account = new Account(); - // No hostauth - assertFalse(account.isEasAccount(mMockContext)); - - checkAccountIsEasAccount(null, false); - checkAccountIsEasAccount("", false); - checkAccountIsEasAccount("x", false); - checkAccountIsEasAccount("eas", true); - } - - private void checkAccountIsEasAccount(String protocol, boolean expected) { - Account account = ProviderTestUtils.setupAccount("account", false, mMockContext); - account.mHostAuthRecv = ProviderTestUtils.setupHostAuth(protocol, "account-hostauth-recv", - false, mMockContext); - account.save(mMockContext); - assertEquals(expected, account.isEasAccount(mMockContext)); + return ProviderTestUtils.setupMessage("1", + b.mAccountKey, + b.mId, + true, + true, + c, + starred, + read); } public void testGetKeyColumnLong() { @@ -1913,10 +2067,7 @@ public class ProviderTests extends ProviderTestCase2 { final Context c = mMockContext; // Prepare some data with red-herrings. - Account a1 = ProviderTestUtils.setupAccount("acct1", true, c); Account a2 = ProviderTestUtils.setupAccount("acct2", true, c); - Mailbox b1i = ProviderTestUtils.setupMailbox("b1i", a1.mId, true, c, Mailbox.TYPE_INBOX); - Mailbox b2a = ProviderTestUtils.setupMailbox("b2a", a2.mId, true, c, Mailbox.TYPE_MAIL); Mailbox b2i = ProviderTestUtils.setupMailbox("b2b", a2.mId, true, c, Mailbox.TYPE_INBOX); assertEquals(b2i.mId, Account.getInboxId(c, a2.mId)); @@ -1950,8 +2101,8 @@ public class ProviderTests extends ProviderTestCase2 { a5.save(c); // With ID in URI, no selection - cr.update(ContentUris.withAppendedId(Account.RESET_NEW_MESSAGE_COUNT_URI, a1.mId), - null, null, null); + cr.update(ContentUris.withAppendedId(Account.RESET_NEW_MESSAGE_COUNT_URI, a1.mId), null, + null, null); assertEquals(0, Account.restoreAccountWithId(c, a1.mId).mNewMessageCount); assertEquals(2, Account.restoreAccountWithId(c, a2.mId).mNewMessageCount); assertEquals(3, Account.restoreAccountWithId(c, a3.mId).mNewMessageCount); @@ -1959,8 +2110,8 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(5, Account.restoreAccountWithId(c, a5.mId).mNewMessageCount); // No ID in URI, with selection - cr.update(Account.RESET_NEW_MESSAGE_COUNT_URI, null, - EmailContent.ID_SELECTION, new String[] {Long.toString(a2.mId)}); + cr.update(Account.RESET_NEW_MESSAGE_COUNT_URI, null, EmailContent.ID_SELECTION, + new String[] {Long.toString(a2.mId)}); assertEquals(0, Account.restoreAccountWithId(c, a1.mId).mNewMessageCount); assertEquals(0, Account.restoreAccountWithId(c, a2.mId).mNewMessageCount); assertEquals(3, Account.restoreAccountWithId(c, a3.mId).mNewMessageCount); @@ -1990,6 +2141,11 @@ public class ProviderTests extends ProviderTestCase2 { */ public void testUpdateCacheAccountIdAddToField() { final Context c = mMockContext; + + // make sure Account.CONTENT_URI is defined + EmailContent.init(c); + Account.initAccount(); + Account a1 = ProviderTestUtils.setupAccount("a1", true, c); int start = Account.restoreAccountWithId(c, a1.mId).mNewMessageCount; @@ -1998,8 +2154,7 @@ public class ProviderTests extends ProviderTestCase2 { ContentValues cv = new ContentValues(); cv.put(EmailContent.FIELD_COLUMN_NAME, AccountColumns.NEW_MESSAGE_COUNT); cv.put(EmailContent.ADD_COLUMN_NAME, 1); - mProvider.update(ContentUris.withAppendedId(Account.ADD_TO_FIELD_URI, a1.mId), cv, - null, null); + mProvider.update(ContentUris.withAppendedId(Account.CONTENT_URI, a1.mId), cv, null, null); // Check assertEquals(start + 1, Account.restoreAccountWithId(c, a1.mId).mNewMessageCount); @@ -2138,7 +2293,7 @@ public class ProviderTests extends ProviderTestCase2 { // Batch update. SQLiteDatabase db = getProvider().getDatabase(mMockContext); - EmailProvider.recalculateMessageCount(db); + DBHelper.recalculateMessageCount(db); // Check message counts are valid again assertEquals(1, getMessageCount(b1.mId)); @@ -2165,8 +2320,8 @@ public class ProviderTests extends ProviderTestCase2 { } /** Creates a mailbox; redefine as we need version 17 mailbox values */ - private Mailbox createMailbox(Context c, String displayName, String serverId, long parentKey, - long accountId) { + private Mailbox createMailbox( + Context c, String displayName, String serverId, long parentKey, long accountId) { Mailbox box = new Mailbox(); box.mDisplayName = displayName; @@ -2182,7 +2337,6 @@ public class ProviderTests extends ProviderTestCase2 { box.mSyncTime = 3; box.mFlagVisible = true; box.mFlags = 5; - box.mVisibleLimit = 6; box.save(c); return box; } @@ -2211,93 +2365,6 @@ public class ProviderTests extends ProviderTestCase2 { assertEquals(expected.mAccountKey, actual.mAccountKey); } - /** Verifies updating the DB from v17 to v18 works as expected */ - public void testUpgradeFromVersion17ToVersion18() { - final Context c = mMockContext; - // Create accounts - Account a1 = createAccount(c, "exchange", - ProviderTestUtils.setupHostAuth("eas", "exchange.host.com", true, c), - null); - Account a2 = createAccount(c, "imap", - ProviderTestUtils.setupHostAuth("imap", "imap.host.com", true, c), - ProviderTestUtils.setupHostAuth("smtp", "smtp.host.com", true, c)); - Account a3 = createAccount(c, "pop3", - ProviderTestUtils.setupHostAuth("pop3", "imap.host.com", true, c), - ProviderTestUtils.setupHostAuth("smtp", "smtp.host.com", true, c)); - - // Create mailboxes; some w/ valid parent IDs, others without - Mailbox b11 = createMailbox(c, "box1", "12", 0L, a1.mId); - Mailbox b12 = createMailbox(c, "box2", "67", -1L, a1.mId); - Mailbox b13 = createMailbox(c, "box3", "18", b12.mId, a1.mId); - - Mailbox b21 = createMailbox(c, "box4", null, 0L, a2.mId); - Mailbox b22 = createMailbox(c, "box4/foo/bar", "will-be-replaced", 0L, a2.mId); - Mailbox b23 = createMailbox(c, "box5", null, -1L, a2.mId); - Mailbox b24 = createMailbox(c, "box6", "box5/box6", b23.mId, a2.mId); - - Mailbox b31 = createMailbox(c, "box7", "12", 0L, a3.mId); - Mailbox b32 = createMailbox(c, "box8/foo/bar", "will-be-replaced", 0L, a3.mId); - Mailbox b33 = createMailbox(c, "box9", "box9", -1L, a3.mId); - Mailbox b34 = createMailbox(c, "boxA", "box9/boxA", b33.mId, a3.mId); - - // Sanity check the mailboxes that were just added - Mailbox testMailbox; - testMailbox = Mailbox.restoreMailboxWithId(c, b11.mId); - assertEquals(b11, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b12.mId); - assertEquals(b12, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b13.mId); - assertEquals(b13, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b21.mId); - assertEqualsExceptServerId(b21, testMailbox, null); - testMailbox = Mailbox.restoreMailboxWithId(c, b22.mId); - assertEqualsExceptServerId(b22, testMailbox, "will-be-replaced"); - testMailbox = Mailbox.restoreMailboxWithId(c, b23.mId); - assertEquals(b23, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b24.mId); - assertEquals(b24, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b31.mId); - assertEqualsExceptServerId(b31, testMailbox, "12"); - testMailbox = Mailbox.restoreMailboxWithId(c, b32.mId); - assertEqualsExceptServerId(b32, testMailbox, "will-be-replaced"); - testMailbox = Mailbox.restoreMailboxWithId(c, b33.mId); - assertEquals(b33, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b34.mId); - assertEquals(b34, testMailbox); - - SQLiteDatabase db = getProvider().getDatabase(mMockContext); - EmailProvider.upgradeFromVersion17ToVersion18(db); - - // Verify that only IMAP/POP3 mailboxes w/ a parent key of '0' are changed - // Exchange mailboxes; none should be changed - testMailbox = Mailbox.restoreMailboxWithId(c, b11.mId); - assertEquals(b11, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b12.mId); - assertEquals(b12, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b13.mId); - assertEquals(b13, testMailbox); - - // IMAP mailboxes; only mailboxes w/ a parent id of '0' are changed - testMailbox = Mailbox.restoreMailboxWithId(c, b21.mId); - assertEqualsExceptServerId(b21, testMailbox, "box4"); - testMailbox = Mailbox.restoreMailboxWithId(c, b22.mId); - assertEqualsExceptServerId(b22, testMailbox, "box4/foo/bar"); - testMailbox = Mailbox.restoreMailboxWithId(c, b23.mId); - assertEquals(b23, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b24.mId); - assertEquals(b24, testMailbox); - - // POP3 mailboxes; only mailboxes w/ a parent id of '0' are changed - testMailbox = Mailbox.restoreMailboxWithId(c, b31.mId); - assertEqualsExceptServerId(b31, testMailbox, "box7"); - testMailbox = Mailbox.restoreMailboxWithId(c, b32.mId); - assertEqualsExceptServerId(b32, testMailbox, "box8/foo/bar"); - testMailbox = Mailbox.restoreMailboxWithId(c, b33.mId); - assertEquals(b33, testMailbox); - testMailbox = Mailbox.restoreMailboxWithId(c, b34.mId); - assertEquals(b34, testMailbox); - } - /** * Determine whether a list of AccountManager accounts includes a given EmailProvider account * @param amAccountList a list of AccountManager accounts @@ -2305,10 +2372,10 @@ public class ProviderTests extends ProviderTestCase2 { * @param context the caller's context (our test provider's context) * @return whether or not the EmailProvider account is represented in AccountManager */ - private boolean amAccountListHasAccount(android.accounts.Account[] amAccountList, - Account account, Context context) { + private boolean amAccountListHasAccount( + android.accounts.Account[] amAccountList, Account account, Context context) { String email = account.mEmailAddress; - for (android.accounts.Account amAccount: amAccountList) { + for (android.accounts.Account amAccount : amAccountList) { if (amAccount.name.equals(email)) { return true; } @@ -2316,19 +2383,6 @@ public class ProviderTests extends ProviderTestCase2 { return false; } - public void testAutoCacheNewContent() { - Account account = ProviderTestUtils.setupAccount("account-hostauth", false, mMockContext); - // add hostauth data, which should be saved the first time - account.mHostAuthRecv = ProviderTestUtils.setupHostAuth("account-hostauth-recv", -1, false, - mMockContext); - account.mHostAuthSend = ProviderTestUtils.setupHostAuth("account-hostauth-send", -1, false, - mMockContext); - account.save(mMockContext); - assertTrue(mProvider.isCached(Account.CONTENT_URI, account.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, account.mHostAuthRecv.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, account.mHostAuthSend.mId)); - } - /** Creates a mailbox; redefine as we need version 17 mailbox values */ private Mailbox createTypeMailbox(Context c, long accountId, int type) { Mailbox box = new Mailbox(); @@ -2343,163 +2397,6 @@ public class ProviderTests extends ProviderTestCase2 { return box; } - public void testAutoCacheInvalidate() { - // Create 3 accounts with hostauth and 3 mailboxes each (2 of which are pre-cached) - Account a = ProviderTestUtils.setupAccount("account1", false, mMockContext); - a.mHostAuthRecv = ProviderTestUtils.setupHostAuth("account-recv", -1, false, - mMockContext); - a.mHostAuthSend = ProviderTestUtils.setupHostAuth("account-send", -1, false, - mMockContext); - a.save(mMockContext); - Mailbox a1 = createTypeMailbox(mMockContext, a.mId, Mailbox.TYPE_INBOX); - Mailbox a2 = createTypeMailbox(mMockContext, a.mId, Mailbox.TYPE_MAIL); - Mailbox a3 = createTypeMailbox(mMockContext, a.mId, Mailbox.TYPE_DRAFTS); - Account b = ProviderTestUtils.setupAccount("account2", false, mMockContext); - b.mHostAuthRecv = ProviderTestUtils.setupHostAuth("account-recv", -1, false, - mMockContext); - b.mHostAuthSend = ProviderTestUtils.setupHostAuth("accoun-send", -1, false, - mMockContext); - b.save(mMockContext); - Mailbox b1 = createTypeMailbox(mMockContext, b.mId, Mailbox.TYPE_OUTBOX); - Mailbox b2 = createTypeMailbox(mMockContext, b.mId, Mailbox.TYPE_MAIL); - Mailbox b3 = createTypeMailbox(mMockContext, b.mId, Mailbox.TYPE_SENT); - Account c = ProviderTestUtils.setupAccount("account3", false, mMockContext); - c.mHostAuthRecv = ProviderTestUtils.setupHostAuth("account-recv", -1, false, - mMockContext); - c.mHostAuthSend = ProviderTestUtils.setupHostAuth("account-send", -1, false, - mMockContext); - c.save(mMockContext); - Mailbox c1 = createTypeMailbox(mMockContext, c.mId, Mailbox.TYPE_SEARCH); - Mailbox c2 = createTypeMailbox(mMockContext, c.mId, Mailbox.TYPE_MAIL); - Mailbox c3 = createTypeMailbox(mMockContext, c.mId, Mailbox.TYPE_TRASH); - - // Confirm expected cache state - assertTrue(mProvider.isCached(Account.CONTENT_URI, a.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, a.mHostAuthRecv.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, a.mHostAuthSend.mId)); - assertTrue(mProvider.isCached(Account.CONTENT_URI, b.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, b.mHostAuthRecv.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, b.mHostAuthSend.mId)); - assertTrue(mProvider.isCached(Account.CONTENT_URI, c.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, c.mHostAuthRecv.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, c.mHostAuthSend.mId)); - - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, a1.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, a2.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, a3.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, b1.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, b2.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, b3.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, c1.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, c2.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, c3.mId)); - - // Delete account b - EmailContent.delete(mMockContext, Account.CONTENT_URI, b.mId); - - // Confirm cache state - assertTrue(mProvider.isCached(Account.CONTENT_URI, a.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, a.mHostAuthRecv.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, a.mHostAuthSend.mId)); - assertFalse(mProvider.isCached(Account.CONTENT_URI, b.mId)); - assertFalse(mProvider.isCached(HostAuth.CONTENT_URI, b.mHostAuthRecv.mId)); - assertFalse(mProvider.isCached(HostAuth.CONTENT_URI, b.mHostAuthSend.mId)); - assertTrue(mProvider.isCached(Account.CONTENT_URI, c.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, c.mHostAuthRecv.mId)); - assertTrue(mProvider.isCached(HostAuth.CONTENT_URI, c.mHostAuthSend.mId)); - - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, a1.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, a2.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, a3.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, b1.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, b2.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, b3.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, c1.mId)); - assertFalse(mProvider.isCached(Mailbox.CONTENT_URI, c2.mId)); - assertTrue(mProvider.isCached(Mailbox.CONTENT_URI, c3.mId)); - } - - /** - * Remove a single pop/imap account from the AccountManager - * @param accountManager our AccountManager - * @param name the name of the test account to remove - */ - private void removeAccountManagerAccount(AccountManager accountManager, String name) { - try { - accountManager.removeAccount( - new android.accounts.Account(name, AccountManagerTypes.TYPE_POP_IMAP), - null, null).getResult(); - } catch (OperationCanceledException e) { - } catch (AuthenticatorException e) { - } catch (IOException e) { - } - } - - /** - * Remove all test accounts from the AccountManager - * @param accountManager the AccountManager - */ - private void cleanupTestAccountManagerAccounts(AccountManager accountManager) { - android.accounts.Account[] amAccountList = - accountManager.getAccountsByType(AccountManagerTypes.TYPE_POP_IMAP); - for (android.accounts.Account account: amAccountList) { - if (account.name.startsWith(AccountReconciler.ACCOUNT_MANAGER_ACCOUNT_TEST_PREFIX)) { - removeAccountManagerAccount(accountManager, account.name); - } - } - } - - /** Verifies updating the DB from v21 to v22 works as expected */ - public void testUpgradeFromVersion21ToVersion22() { - String imapTestLogin = - AccountReconciler.ACCOUNT_MANAGER_ACCOUNT_TEST_PREFIX + "imap.host.com"; - String pop3TestLogin = - AccountReconciler.ACCOUNT_MANAGER_ACCOUNT_TEST_PREFIX + "pop3.host.com"; - AccountManager accountManager = AccountManager.get(mContext); - - // Create provider accounts (one of each type) - Account a1 = createAccount(mMockContext, "exchange", - ProviderTestUtils.setupHostAuth("eas", "exchange.host.com", true, mMockContext), - null); - HostAuth h2 = - ProviderTestUtils.setupHostAuth("imap", "imap.host.com", false, mMockContext); - h2.mLogin = imapTestLogin; - h2.save(mMockContext); - Account a2 = createAccount(mMockContext, "imap", h2, - ProviderTestUtils.setupHostAuth("smtp", "smtp.host.com", true, mMockContext)); - HostAuth h3 = - ProviderTestUtils.setupHostAuth("pop3", "pop3.host.com", false, mMockContext); - h3.mLogin = pop3TestLogin; - h3.save(mMockContext); - Account a3 = createAccount(mMockContext, "pop3", h3, - ProviderTestUtils.setupHostAuth("smtp", "smtp.host.com", true, mMockContext)); - - // Get the current list of AccountManager accounts (we have to use the real context here), - // whereas we use the mock context for EmailProvider (this is because the mock context - // doesn't implement AccountManager hooks) - android.accounts.Account[] amAccountList = - accountManager.getAccountsByType(AccountManagerTypes.TYPE_POP_IMAP); - // There shouldn't be AccountManager accounts for these - assertFalse(amAccountListHasAccount(amAccountList, a1, mMockContext)); - assertFalse(amAccountListHasAccount(amAccountList, a2, mMockContext)); - assertFalse(amAccountListHasAccount(amAccountList, a3, mMockContext)); - - amAccountList = null; - try { - // Upgrade the database - SQLiteDatabase db = getProvider().getDatabase(mMockContext); - EmailProvider.upgradeFromVersion21ToVersion22(db, getContext()); - - // The pop3 and imap account should now be in account manager - amAccountList = accountManager.getAccountsByType(AccountManagerTypes.TYPE_POP_IMAP); - assertFalse(amAccountListHasAccount(amAccountList, a1, mMockContext)); - assertTrue(amAccountListHasAccount(amAccountList, a2, mMockContext)); - assertTrue(amAccountListHasAccount(amAccountList, a3, mMockContext)); - } finally { - cleanupTestAccountManagerAccounts(accountManager); - } - } - public void testCleanupOrphans() { EmailProvider ep = getProvider(); SQLiteDatabase db = ep.getDatabase(mMockContext); @@ -2528,19 +2425,19 @@ public class ProviderTests extends ProviderTestCase2 { p1.save(mMockContext); Policy p2 = new Policy(); p2.save(mMockContext); - Policy p3 = new Policy(); - Policy.setAccountPolicy(mMockContext, a.mId, p3, "0"); - // We don't want anything cached or the tests below won't work. Note that - // deleteUnlinked is only called by EmailProvider when the caches are empty + // We don't want anything cached or the tests below won't work. Note + // that + // deleteUnlinked is only called by EmailProvider when the caches are + // empty ContentCache.invalidateAllCaches(); // Delete orphaned mailboxes/messages/policies - ep.deleteUnlinked(db, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, AccountColumns.ID, - Account.TABLE_NAME); - ep.deleteUnlinked(db, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, AccountColumns.ID, - Account.TABLE_NAME); - ep.deleteUnlinked(db, Policy.TABLE_NAME, PolicyColumns.ID, AccountColumns.POLICY_KEY, - Account.TABLE_NAME); + EmailProvider.deleteUnlinked(db, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, + AccountColumns.ID, Account.TABLE_NAME); + EmailProvider.deleteUnlinked(db, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, + AccountColumns.ID, Account.TABLE_NAME); + EmailProvider.deleteUnlinked(db, Policy.TABLE_NAME, PolicyColumns.ID, + AccountColumns.POLICY_KEY, Account.TABLE_NAME); // Make sure the orphaned mailboxes are gone assertNull(Mailbox.restoreMailboxWithId(mMockContext, a1.mId)); diff --git a/tests/src/com/android/email/service/AttachmentDownloadServiceTests.java b/tests/src/com/android/email/service/AttachmentDownloadServiceTests.java index 43f9ec54d..d20d5d7a6 100644 --- a/tests/src/com/android/email/service/AttachmentDownloadServiceTests.java +++ b/tests/src/com/android/email/service/AttachmentDownloadServiceTests.java @@ -17,14 +17,12 @@ package com.android.email.service; import android.content.Context; -import android.content.Intent; import com.android.email.AccountTestCase; import com.android.email.EmailConnectivityManager; import com.android.email.provider.ProviderTestUtils; import com.android.email.service.AttachmentDownloadService.DownloadRequest; import com.android.email.service.AttachmentDownloadService.DownloadSet; -import com.android.email.service.EmailServiceUtils.NullEmailService; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.provider.EmailContent.Message; @@ -70,8 +68,9 @@ public class AttachmentDownloadServiceTests extends AccountTestCase { // Use the NullEmailService so that the loadAttachment calls become no-ops mService = new AttachmentDownloadService(); mService.mContext = mMockContext; - mService.addServiceIntentForTest(mAccountId, new Intent(mContext, - NullEmailService.class)); + // there's no NullEmailService class + /*mService.addServiceIntentForTest(mAccountId, new Intent(mContext, + NullEmailService.class));*/ mAccountManagerStub = new AttachmentDownloadService.AccountManagerStub(null); mService.mAccountManagerStub = mAccountManagerStub; mService.mConnectivityManager = new MockConnectivityManager(mContext, "mock"); diff --git a/tests/src/com/android/email/service/EmailBroadcastProcessorServiceTests.java b/tests/src/com/android/email/service/EmailBroadcastProcessorServiceTests.java index d171335cd..29c61fdce 100644 --- a/tests/src/com/android/email/service/EmailBroadcastProcessorServiceTests.java +++ b/tests/src/com/android/email/service/EmailBroadcastProcessorServiceTests.java @@ -135,17 +135,4 @@ public class EmailBroadcastProcessorServiceTests extends AccountTestCase { assertEquals(0x00000008, accountFlags6); } - public void testNoopRemover() { - final Map protocolMap = Maps.newHashMap(); - protocolMap.put("imap", "imap"); - protocolMap.put("pop3", "gPop3"); - - EmailBroadcastProcessorService.removeNoopUpgrades(protocolMap); - - final Map protocolMapExpected = Maps.newHashMap(); - protocolMapExpected.put("pop3", "gPop3"); - - assertEquals(protocolMap, protocolMapExpected); - } - } diff --git a/tests/src/com/android/email/service/MailServiceTests.java b/tests/src/com/android/email/service/MailServiceTests.java index 90f2d3060..8a7cc1e34 100644 --- a/tests/src/com/android/email/service/MailServiceTests.java +++ b/tests/src/com/android/email/service/MailServiceTests.java @@ -25,11 +25,9 @@ import android.content.Context; import android.content.pm.PackageManager; import com.android.email.AccountTestCase; -import com.android.email.Controller; import com.android.email.provider.AccountReconciler; import com.android.email.provider.EmailProvider; import com.android.email.provider.ProviderTestUtils; -import com.android.email.service.MailService.AccountSyncReport; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.HostAuth; @@ -46,7 +44,7 @@ import java.util.List; */ public class MailServiceTests extends AccountTestCase { - EmailProvider mProvider; + /*EmailProvider mProvider; Context mMockContext; public MailServiceTests() { @@ -71,13 +69,13 @@ public class MailServiceTests extends AccountTestCase { super.tearDown(); // Delete any test accounts we might have created earlier deleteTemporaryAccountManagerAccounts(); - } + }*/ /** * Confirm that the test below is functional (and non-destructive) when there are * prexisting (non-test) accounts in the account manager. */ - public void testTestReconcileAccounts() { + /*public void testTestReconcileAccounts() { Account firstAccount = null; final String TEST_USER_ACCOUNT = "__user_account_test_1"; Context context = getContext(); @@ -106,13 +104,13 @@ public class MailServiceTests extends AccountTestCase { assertTrue(firstAccountFound); } } - } + }*/ /** * Note, there is some inherent risk in this test, as it creates *real* accounts in the * system (it cannot use the mock context with the Account Manager). */ - public void testReconcileAccounts() { + /*public void testReconcileAccounts() { // Note that we can't use mMockContext for AccountManager interactions, as it isn't a fully // functional Context. Context context = getContext(); @@ -165,32 +163,32 @@ public class MailServiceTests extends AccountTestCase { assertEquals(1, accountManagerAccounts.length); // ... and it should be account "3" assertEquals(getTestAccountEmailAddress("3"), accountManagerAccounts[0].name); - } + }*/ /** * Lightweight subclass of the Controller class allows injection of mock context */ - public static class TestController extends Controller { + /*public static class TestController extends Controller { protected TestController(Context providerContext, Context systemContext) { super(systemContext); setProviderContext(providerContext); } - } + }*/ /** * Create a simple HostAuth with protocol */ - private HostAuth setupSimpleHostAuth(String protocol) { + /*private HostAuth setupSimpleHostAuth(String protocol) { HostAuth hostAuth = new HostAuth(); hostAuth.mProtocol = protocol; return hostAuth; - } + }*/ /** * Initial testing on setupSyncReportsLocked, making sure that EAS accounts aren't scheduled */ - public void testSetupSyncReportsLocked() { + /*public void testSetupSyncReportsLocked() { // TODO Test other functionality within setupSyncReportsLocked // Setup accounts of each type, all with manual sync at different intervals Account easAccount = ProviderTestUtils.setupAccount("account1", false, mMockContext); @@ -243,13 +241,13 @@ public class MailServiceTests extends AccountTestCase { } finally { mailService.mController.cleanupForTest(); } - } + }*/ /** * Test that setupSyncReports will skip over poorly-formed accounts which can be left * over after unit tests. */ - public void testSetupSyncReportsWithBadAccounts() { + /*public void testSetupSyncReportsWithBadAccounts() { // Setup accounts that trigger each skip-over case // 1: no email address Account account1 = ProviderTestUtils.setupAccount("account1", false, mMockContext); @@ -282,6 +280,5 @@ public class MailServiceTests extends AccountTestCase { } finally { mailService.mController.cleanupForTest(); } - - } + }*/ } diff --git a/tests/src/com/android/emailcommon/DeviceTests.java b/tests/src/com/android/emailcommon/DeviceTests.java index 481d1cc52..f5849e4ca 100644 --- a/tests/src/com/android/emailcommon/DeviceTests.java +++ b/tests/src/com/android/emailcommon/DeviceTests.java @@ -21,6 +21,8 @@ import android.content.Context; import android.telephony.TelephonyManager; import android.test.AndroidTestCase; +import com.android.mail.utils.LogUtils; + public class DeviceTests extends AndroidTestCase { public void testGetConsistentDeviceId() { diff --git a/tests/src/com/android/emailcommon/internet/Rfc822OutputTests.java b/tests/src/com/android/emailcommon/internet/Rfc822OutputTests.java index 0369e18b9..ba3ba0055 100644 --- a/tests/src/com/android/emailcommon/internet/Rfc822OutputTests.java +++ b/tests/src/com/android/emailcommon/internet/Rfc822OutputTests.java @@ -128,7 +128,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { Body body1 = createTestBody(message1); String[] bodyParts; - bodyParts = Rfc822Output.buildBodyText(body1, message1.mFlags, false); + bodyParts = Rfc822Output.buildBodyText(body1, false); assertEquals(REPLY_INTRO_TEXT + ">" + REPLY_TEXT_BODY, bodyParts[0]); message1.mId = -1; // Changing the message; need to reset the id @@ -136,7 +136,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { message1.save(mMockContext); body1 = createTestBody(message1); - bodyParts = Rfc822Output.buildBodyText(body1, message1.mFlags, false); + bodyParts = Rfc822Output.buildBodyText(body1, false); assertEquals(TEXT + REPLY_INTRO_TEXT + ">" + REPLY_TEXT_BODY, bodyParts[0]); // We have an HTML reply and no text reply; use the HTML reply @@ -145,7 +145,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { message1.save(mMockContext); body1 = createTestBody(message1); - bodyParts = Rfc822Output.buildBodyText(body1, message1.mFlags, false); + bodyParts = Rfc822Output.buildBodyText(body1, false); assertEquals(TEXT + REPLY_INTRO_TEXT + BODY_TEXT_REPLY_HTML, bodyParts[0]); // We have no HTML or text reply; use nothing @@ -154,14 +154,14 @@ public class Rfc822OutputTests extends ProviderTestCase2 { message1.save(mMockContext); body1 = createTestBody(message1); - bodyParts = Rfc822Output.buildBodyText(body1, message1.mFlags, false); + bodyParts = Rfc822Output.buildBodyText(body1, false); assertEquals(TEXT + REPLY_INTRO_TEXT, bodyParts[0]); // Test sending a message *with* using smart reply Message message2 = createTestMessage("", true); Body body2 = createTestBody(message2); - bodyParts = Rfc822Output.buildBodyText(body2, message2.mFlags, true); + bodyParts = Rfc822Output.buildBodyText(body2, true); assertEquals(REPLY_INTRO_TEXT, bodyParts[0]); message2.mId = -1; // Changing the message; need to reset the id @@ -169,7 +169,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { message2.save(mMockContext); body2 = createTestBody(message2); - bodyParts = Rfc822Output.buildBodyText(body2, message2.mFlags, true); + bodyParts = Rfc822Output.buildBodyText(body2, true); assertEquals(TEXT + REPLY_INTRO_TEXT, bodyParts[0]); // We have an HTML reply and no text reply; use nothing (smart reply) @@ -178,7 +178,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { message2.save(mMockContext); body2 = createTestBody(message2); - bodyParts = Rfc822Output.buildBodyText(body2, message2.mFlags, true); + bodyParts = Rfc822Output.buildBodyText(body2, true); assertEquals(TEXT + REPLY_INTRO_TEXT, bodyParts[0]); // We have no HTML or text reply; use nothing @@ -188,7 +188,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { message2.save(mMockContext); body2 = createTestBody(message2); - bodyParts = Rfc822Output.buildBodyText(body2, message2.mFlags, true); + bodyParts = Rfc822Output.buildBodyText(body2, true); assertEquals(TEXT + REPLY_INTRO_TEXT, bodyParts[0]); } @@ -208,7 +208,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { msg.mIntroText = mForwardIntro; msg.save(mMockContext); Body body = createTestBody(msg); - String[] bodyParts = Rfc822Output.buildBodyText(body, msg.mFlags, false); + String[] bodyParts = Rfc822Output.buildBodyText(body, false); assertEquals(TEXT + mForwardIntro + REPLY_TEXT_BODY, bodyParts[0]); } @@ -222,7 +222,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { // Write out an Rfc822 message ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - Rfc822Output.writeTo(mMockContext, msg.mId, byteStream, true, false); + Rfc822Output.writeTo(mMockContext, msg, byteStream, true, false, null); // Get the message and create a mime4j message from it // We'll take advantage of its parsing capabilities @@ -256,7 +256,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { // Write out an Rfc822 message ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - Rfc822Output.writeTo(mMockContext, msg.mId, byteStream, true, false); + Rfc822Output.writeTo(mMockContext, msg, byteStream, true, false, null); // Get the message and create a mime4j message from it // We'll take advantage of its parsing capabilities @@ -300,7 +300,7 @@ public class Rfc822OutputTests extends ProviderTestCase2 { // Write out an Rfc822 message ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - Rfc822Output.writeTo(mMockContext, msg.mId, byteStream, true, false); + Rfc822Output.writeTo(mMockContext, msg, byteStream, true, false, null); // Get the message and create a mime4j message from it // We'll take advantage of its parsing capabilities @@ -340,52 +340,6 @@ public class Rfc822OutputTests extends ProviderTestCase2 { assertEquals(HTML_NO_BODY_RESULT, actual); } - /** - * Tests that the entire HTML alternate string is valid for text entered by - * the user. We don't test all permutations of forwarded HTML here because - * that is verified by testGetHtmlBody(). - */ - public void testGetHtmlAlternate() { - Message message = createTestMessage(TEXT, true); - Body body = createTestBody(message); - String html; - - // Generic case - html = Rfc822Output.getHtmlAlternate(body, false); - assertEquals(TEXT + REPLY_INTRO_HTML + BODY_HTML_REPLY, html); - - // "smart reply" enabled; html body should not be added - html = Rfc822Output.getHtmlAlternate(body, true); - assertEquals(TEXT + REPLY_INTRO_HTML, html); - - // HTML special characters; dependent upon TextUtils#htmlEncode() - message.mId = -1; // Changing the message; need to reset the id - message.mText = "<>&'\""; - message.save(mMockContext); - body = createTestBody(message); - - html = Rfc822Output.getHtmlAlternate(body, false); - assertEquals("<>&'"" + REPLY_INTRO_HTML + BODY_HTML_REPLY, html); - - // Newlines in user text - message.mId = -1; // Changing the message; need to reset the id - message.mText = "dos\r\nunix\nthree\r\n\n\n"; - message.save(mMockContext); - body = createTestBody(message); - - html = Rfc822Output.getHtmlAlternate(body, false); - assertEquals("dos
unix
three


" + REPLY_INTRO_HTML + BODY_HTML_REPLY, html); - - // Null HTML reply - message.mId = -1; // Changing the message; need to reset the id - message.mHtmlReply = null; - message.save(mMockContext); - body = createTestBody(message); - - html = Rfc822Output.getHtmlAlternate(body, false); - assertNull(html); - } - /** * Test the boundary digit. We modify it indirectly. */ diff --git a/tests/src/com/android/emailcommon/mail/MockFolder.java b/tests/src/com/android/emailcommon/mail/MockFolder.java index 3ff549580..a35fb3db2 100644 --- a/tests/src/com/android/emailcommon/mail/MockFolder.java +++ b/tests/src/com/android/emailcommon/mail/MockFolder.java @@ -126,4 +126,14 @@ public class MockFolder extends Folder { return null; } + /* (non-Javadoc) + * @see com.android.emailcommon.mail.Folder#getMessages(long, long, + * com.android.emailcommon.mail.Folder.MessageRetrievalListener) + */ + @Override + public Message[] getMessages(long startDate, long endDate, MessageRetrievalListener listener) + throws MessagingException { + return null; + } + } diff --git a/tests/src/com/android/emailcommon/provider/MailboxTests.java b/tests/src/com/android/emailcommon/provider/MailboxTests.java index 9530b77d0..ab2fddb63 100644 --- a/tests/src/com/android/emailcommon/provider/MailboxTests.java +++ b/tests/src/com/android/emailcommon/provider/MailboxTests.java @@ -333,9 +333,6 @@ public class MailboxTests extends ProviderTestCase2 { * {@link EmailProvider#recalculateMessageCount}. * * It also covers: - * - {@link Mailbox#getMessageCountByMailboxType(Context, int)} - * - {@link Mailbox#getUnreadCountByAccountAndMailboxType(Context, long, int)} - * - {@link Mailbox#getUnreadCountByMailboxType(Context, int)} * - {@link Message#getFavoriteMessageCount(Context)} * - {@link Message#getFavoriteMessageCount(Context, long)} */ @@ -364,24 +361,6 @@ public class MailboxTests extends ProviderTestCase2 { assertEquals(0, Message.getFavoriteMessageCount(c)); assertEquals(0, Message.getFavoriteMessageCount(c, a1.mId)); assertEquals(0, Message.getFavoriteMessageCount(c, a2.mId)); - assertEquals(0, Mailbox.getUnreadCountByMailboxType(c, Mailbox.TYPE_INBOX)); - assertEquals(0, Mailbox.getUnreadCountByMailboxType(c, Mailbox.TYPE_OUTBOX)); - assertEquals(0, Mailbox.getMessageCountByMailboxType(c, Mailbox.TYPE_INBOX)); - assertEquals(0, Mailbox.getMessageCountByMailboxType(c, Mailbox.TYPE_OUTBOX)); - assertEquals(0, Mailbox.getMessageCountByMailboxType(c, Mailbox.TYPE_TRASH)); - - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a1.mId, Mailbox.TYPE_INBOX)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a1.mId, Mailbox.TYPE_OUTBOX)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a1.mId, Mailbox.TYPE_TRASH)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a2.mId, Mailbox.TYPE_INBOX)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a2.mId, Mailbox.TYPE_OUTBOX)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a2.mId, Mailbox.TYPE_TRASH)); // 1. Test for insert triggers. @@ -416,24 +395,6 @@ public class MailboxTests extends ProviderTestCase2 { assertEquals(3, Message.getFavoriteMessageCount(c)); // excludes starred in trash assertEquals(2, Message.getFavoriteMessageCount(c, a1.mId)); assertEquals(1, Message.getFavoriteMessageCount(c, a2.mId)); // excludes starred in trash - assertEquals(3, Mailbox.getUnreadCountByMailboxType(c, Mailbox.TYPE_INBOX)); - assertEquals(1, Mailbox.getUnreadCountByMailboxType(c, Mailbox.TYPE_OUTBOX)); - assertEquals(4, Mailbox.getMessageCountByMailboxType(c, Mailbox.TYPE_INBOX)); - assertEquals(2, Mailbox.getMessageCountByMailboxType(c, Mailbox.TYPE_OUTBOX)); - assertEquals(3, Mailbox.getMessageCountByMailboxType(c, Mailbox.TYPE_TRASH)); - - assertEquals(1, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a1.mId, Mailbox.TYPE_INBOX)); - assertEquals(1, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a1.mId, Mailbox.TYPE_OUTBOX)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a1.mId, Mailbox.TYPE_TRASH)); - assertEquals(2, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a2.mId, Mailbox.TYPE_INBOX)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a2.mId, Mailbox.TYPE_OUTBOX)); - assertEquals(3, Mailbox.getUnreadCountByAccountAndMailboxType(c, - a2.mId, Mailbox.TYPE_TRASH)); // 2. Check the "move mailbox" trigger. @@ -464,15 +425,6 @@ public class MailboxTests extends ProviderTestCase2 { assertEquals(1, getMessageCount(b2.mId)); assertEquals(2, getMessageCount(b3.mId)); assertEquals(1, getMessageCount(b4.mId)); - - // No such mailbox type. - assertEquals(0, Mailbox.getMessageCountByMailboxType(c, 99999)); - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, a1.mId, 99999)); - assertEquals(0, Mailbox.getUnreadCountByMailboxType(c, 99999)); - - // No such account - assertEquals(0, Mailbox.getUnreadCountByAccountAndMailboxType(c, - 99999, Mailbox.TYPE_INBOX)); } private Mailbox buildTestMailbox(String serverId) { @@ -480,11 +432,9 @@ public class MailboxTests extends ProviderTestCase2 { } private Mailbox buildTestMailbox(String serverId, String name) { - name = (name == null) ? TEST_DISPLAY_NAME : name; - Mailbox testMailbox = new Mailbox(); testMailbox.mServerId = serverId; - testMailbox.mDisplayName = name; + testMailbox.mDisplayName = (name == null) ? TEST_DISPLAY_NAME : name; testMailbox.mParentServerId = TEST_PARENT_SERVER_ID; testMailbox.mSyncKey = TEST_SYNC_KEY; testMailbox.mSyncStatus = TEST_SYNC_STATUS; @@ -497,8 +447,6 @@ public class MailboxTests extends ProviderTestCase2 { testMailbox.mSyncLookback = 5; testMailbox.mSyncTime = 6L; testMailbox.mType = 7; - testMailbox.mVisibleLimit = 8; - testMailbox.mLastSeenMessageKey = 9L; testMailbox.mLastTouchedTime = 10L; return testMailbox; diff --git a/tests/src/com/android/emailcommon/provider/QuickResponseTests.java b/tests/src/com/android/emailcommon/provider/QuickResponseTests.java index 9e0b6d5b5..673a1bc1f 100644 --- a/tests/src/com/android/emailcommon/provider/QuickResponseTests.java +++ b/tests/src/com/android/emailcommon/provider/QuickResponseTests.java @@ -44,27 +44,5 @@ public class QuickResponseTests extends ProviderTestCase2 { // Invalidate all caches, since we reset the database for each test ContentCache.invalidateAllCaches(); } - - // This class no longer has any content - public void brokenTestParcelling() { - QuickResponse original = new QuickResponse(7, "quick response text"); - - Parcel p = Parcel.obtain(); - original.writeToParcel(p, 0); - - // Reset. - p.setDataPosition(0); - - QuickResponse unparcelled = QuickResponse.CREATOR.createFromParcel(p); - assert(original.equals(unparcelled)); - - QuickResponse phony = new QuickResponse(17, "quick response text"); - assert(!(phony.equals(unparcelled))); - - QuickResponse phony2 = new QuickResponse(7, "different text"); - assert(!(phony2.equals(unparcelled))); - - p.recycle(); - } } diff --git a/tests/src/com/android/emailcommon/utility/AttachmentUtilitiesTests.java b/tests/src/com/android/emailcommon/utility/AttachmentUtilitiesTests.java index 851570ab3..6dde0d605 100644 --- a/tests/src/com/android/emailcommon/utility/AttachmentUtilitiesTests.java +++ b/tests/src/com/android/emailcommon/utility/AttachmentUtilitiesTests.java @@ -101,22 +101,6 @@ public class AttachmentUtilitiesTests extends AndroidTestCase { assertEquals(TEXT_PLAIN, AttachmentUtilities.inferMimeType("", TEXT_PLAIN)); } - public void testInferMimeTypeForUri() { - String type; - // Test for content URI - type = AttachmentUtilities.inferMimeTypeForUri(getContext(), EmailContent.Body.CONTENT_URI); - assertEquals("vnd.android.cursor.dir/email-body", type); - - // Test for file URI - type = AttachmentUtilities.inferMimeTypeForUri(getContext(), - Uri.fromFile(new File("a.png"))); - assertEquals("image/png", type); - - type = AttachmentUtilities.inferMimeTypeForUri(getContext(), - Uri.fromFile(new File("/a/b/c/d.png"))); - assertEquals("image/png", type); - } - /** * Text extension extractor */ diff --git a/tests/src/com/android/emailcommon/utility/SSLUtilsTest.java b/tests/src/com/android/emailcommon/utility/SSLUtilsTest.java index 301856010..d373b9c3a 100644 --- a/tests/src/com/android/emailcommon/utility/SSLUtilsTest.java +++ b/tests/src/com/android/emailcommon/utility/SSLUtilsTest.java @@ -48,8 +48,6 @@ public class SSLUtilsTest extends AndroidTestCase { assertSchemeNameValid(SSLUtils.escapeForSchemeName("name with spaces")); assertSchemeNameValid(SSLUtils.escapeForSchemeName("odd * & characters")); assertSchemeNameValid(SSLUtils.escapeForSchemeName("f3v!l;891023-47 +")); - assertSchemeNameValid( - SSLUtils.escapeForSchemeName("\u304d\u307f\u3092\u611b\u3057\u3066\u308b")); } private static final char[] RANDOM_DICT = new char[] { diff --git a/tests/src/com/android/emailcommon/utility/UtilityMediumTests.java b/tests/src/com/android/emailcommon/utility/UtilityMediumTests.java index 46ea4d78e..3fb9246c8 100644 --- a/tests/src/com/android/emailcommon/utility/UtilityMediumTests.java +++ b/tests/src/com/android/emailcommon/utility/UtilityMediumTests.java @@ -127,7 +127,7 @@ public class UtilityMediumTests extends ProviderTestCase2 { writer.write("Foo"); writer.flush(); writer.close(); - attachment.mContentUri = "file://" + file.getAbsolutePath(); + attachment.setContentUri("file://" + file.getAbsolutePath()); // Now, this should return true assertTrue(Utility.attachmentExists(mMockContext, attachment)); } diff --git a/tests/src/com/android/emailcommon/utility/UtilityUnitTests.java b/tests/src/com/android/emailcommon/utility/UtilityUnitTests.java index 96c224494..c56847d62 100644 --- a/tests/src/com/android/emailcommon/utility/UtilityUnitTests.java +++ b/tests/src/com/android/emailcommon/utility/UtilityUnitTests.java @@ -16,22 +16,9 @@ package com.android.emailcommon.utility; -import com.android.email.DBTestHelper; -import com.android.email.R; -import com.android.email.TestUtils; -import com.android.email.provider.ProviderTestUtils; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.EmailContent.Attachment; -import com.android.emailcommon.provider.EmailContent.MailboxColumns; -import com.android.emailcommon.provider.EmailContent.Message; -import com.android.emailcommon.provider.Mailbox; -import com.android.emailcommon.utility.Utility.NewFileCreator; - import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; -import android.database.MatrixCursor; -import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Environment; import android.test.AndroidTestCase; @@ -41,6 +28,17 @@ import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.widget.TextView; +import com.android.email.DBTestHelper; +import com.android.email.TestUtils; +import com.android.email.provider.ProviderTestUtils; +import com.android.emailcommon.provider.Account; +import com.android.emailcommon.provider.EmailContent.Attachment; +import com.android.emailcommon.provider.EmailContent.MailboxColumns; +import com.android.emailcommon.provider.EmailContent.Message; +import com.android.emailcommon.provider.Mailbox; +import com.android.emailcommon.utility.Utility.NewFileCreator; +import com.android.mail.utils.MatrixCursorWithCachedColumns; + import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -308,127 +306,6 @@ public class UtilityUnitTests extends AndroidTestCase { assertEquals(lastPathSegment, Utility.getContentFileName(providerContext, notExistUri)); } - private long getLastUpdateKey(Context mockContext, long mailboxId) { - return Utility.getFirstRowLong(mockContext, Mailbox.CONTENT_URI, - new String[] { MailboxColumns.LAST_SEEN_MESSAGE_KEY }, MailboxColumns.ID + "=?", - new String[] { Long.toString(mailboxId) }, null, 0, -1L); - } - - public void testUpdateLastSeenMessageKey() throws Exception { - Context mockContext = DBTestHelper.ProviderContextSetupHelper.getProviderContext(mContext); - - // Setup account & message stuff - Account account1 = ProviderTestUtils.setupAccount("account1", true, mockContext); - Account account2 = ProviderTestUtils.setupAccount("account2", true, mockContext); - Account account3 = ProviderTestUtils.setupAccount("account3", true, mockContext); - Account account4 = ProviderTestUtils.setupAccount("account4", true, mockContext); - Mailbox mailbox1_1 = ProviderTestUtils.setupMailbox("mbox1_1", account1.mId, true, - mockContext, Mailbox.TYPE_INBOX); - Mailbox mailbox1_2 = ProviderTestUtils.setupMailbox("mbox1_2", account1.mId, true, - mockContext, Mailbox.TYPE_MAIL); - Mailbox mailbox1_3 = ProviderTestUtils.setupMailbox("mbox1_3", account1.mId, true, - mockContext, Mailbox.TYPE_DRAFTS); - Mailbox mailbox1_4 = ProviderTestUtils.setupMailbox("mbox1_4", account1.mId, true, - mockContext, Mailbox.TYPE_OUTBOX); - Mailbox mailbox1_5 = ProviderTestUtils.setupMailbox("mbox1_5", account1.mId, true, - mockContext, Mailbox.TYPE_TRASH); - Mailbox mailbox2_1 = ProviderTestUtils.setupMailbox("mbox2_1", account2.mId, true, - mockContext, Mailbox.TYPE_MAIL); - Mailbox mailbox3_1 = ProviderTestUtils.setupMailbox("mbox3_1", account3.mId, true, - mockContext, Mailbox.TYPE_MAIL); - Mailbox mailbox3_2 = ProviderTestUtils.setupMailbox("mbox3_2", account3.mId, true, - mockContext, Mailbox.TYPE_INBOX); - Mailbox mailbox4_1 = ProviderTestUtils.setupMailbox("mbox4_1", account4.mId, true, - mockContext, Mailbox.TYPE_INBOX); - Message message1_1_1 = ProviderTestUtils.setupMessage("message_1_1_1", account1.mId, - mailbox1_1.mId, false, true, mockContext); - Message message1_1_2 = ProviderTestUtils.setupMessage("message_1_1_2", account1.mId, - mailbox1_1.mId, false, true, mockContext); - Message message1_1_3 = ProviderTestUtils.setupMessage("message_1_1_3", account1.mId, - mailbox1_1.mId, false, true, mockContext); - Message message1_2_1 = ProviderTestUtils.setupMessage("message_1_2_1", account1.mId, - mailbox1_2.mId, false, true, mockContext); - Message message1_3_1 = ProviderTestUtils.setupMessage("message_1_3_1", account1.mId, - mailbox1_3.mId, false, true, mockContext); - Message message1_4_1 = ProviderTestUtils.setupMessage("message_1_4_1", account1.mId, - mailbox1_4.mId, false, true, mockContext); - Message message1_5_1 = ProviderTestUtils.setupMessage("message_1_5_1", account1.mId, - mailbox1_5.mId, false, true, mockContext); - Message message2_1_1 = ProviderTestUtils.setupMessage("message_2_1_1", account2.mId, - mailbox2_1.mId, false, true, mockContext); - Message message2_1_2 = ProviderTestUtils.setupMessage("message_2_1_2", account2.mId, - mailbox2_1.mId, false, true, mockContext); - Message message3_1_1 = ProviderTestUtils.setupMessage("message_3_1_1", account3.mId, - mailbox3_1.mId, false, true, mockContext); - Message message4_1_1 = ProviderTestUtils.setupMessage("message_4_1_1", account4.mId, - mailbox4_1.mId, false, true, mockContext); - Message message4_1_2 = ProviderTestUtils.setupMessage("message_4_1_2", account4.mId, - mailbox4_1.mId, false, true, mockContext); - Message message4_1_3 = ProviderTestUtils.setupMessage("message_4_1_3", account4.mId, - mailbox4_1.mId, false, true, mockContext); - Message message4_1_4 = ProviderTestUtils.setupMessage("message_4_1_4", account4.mId, - mailbox4_1.mId, false, true, mockContext); - - // Verify the default case - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_3.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_4.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_5.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox2_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox4_1.mId)); - - // Test account; only INBOX is modified - Utility.updateLastSeenMessageKey(mockContext, account1.mId).get(); - assertEquals(message1_1_3.mId, getLastUpdateKey(mockContext, mailbox1_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_3.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_4.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_5.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox2_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox4_1.mId)); - - // Missing INBOX - Utility.updateLastSeenMessageKey(mockContext, account2.mId).get(); - assertEquals(message1_1_3.mId, getLastUpdateKey(mockContext, mailbox1_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_3.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_4.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_5.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox2_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox4_1.mId)); - - // No messages in mailbox - Utility.updateLastSeenMessageKey(mockContext, account3.mId).get(); - assertEquals(message1_1_3.mId, getLastUpdateKey(mockContext, mailbox1_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_3.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_4.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_5.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox2_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox4_1.mId)); - - // Test combined accounts - Utility.updateLastSeenMessageKey(mockContext, 0x1000000000000000L).get(); - assertEquals(message1_1_3.mId, getLastUpdateKey(mockContext, mailbox1_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_2.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_3.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_4.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox1_5.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox2_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_1.mId)); - assertEquals(0L, getLastUpdateKey(mockContext, mailbox3_2.mId)); - assertEquals(message4_1_4.mId, getLastUpdateKey(mockContext, mailbox4_1.mId)); - } - // used by testToPrimitiveLongArray private static Collection createLongCollection(long... values) { ArrayList ret = new ArrayList();