diff options
Diffstat (limited to 'tests')
57 files changed, 0 insertions, 10515 deletions
diff --git a/tests/Android.mk b/tests/Android.mk deleted file mode 100644 index 910d89376..000000000 --- a/tests/Android.mk +++ /dev/null @@ -1,28 +0,0 @@ -LOCAL_PATH:= $(call my-dir) -include $(CLEAR_VARS) - -# We only want this apk build for tests. -LOCAL_MODULE_TAGS := tests -LOCAL_CERTIFICATE := shared - -LOCAL_STATIC_JAVA_LIBRARIES := android-support-test - -# Include all test java files. -LOCAL_SRC_FILES := $(call all-java-files-under, src) - -src_dirs := src \ - ../../ContactsCommon/TestCommon/src - -# Include all test java files. -LOCAL_SRC_FILES := $(call all-java-files-under, $(src_dirs)) - -LOCAL_STATIC_JAVA_LIBRARIES += \ - mockito-target-minus-junit4 - -LOCAL_PACKAGE_NAME := DialerTests - -LOCAL_INSTRUMENTATION_FOR := Dialer - -LOCAL_SDK_VERSION := current - -include $(BUILD_PACKAGE) diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml deleted file mode 100644 index 40c5502da..000000000 --- a/tests/AndroidManifest.xml +++ /dev/null @@ -1,69 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - ~ Copyright (C) 2012 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 - --> - -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.android.dialer.tests"> - - <uses-sdk - android:minSdkVersion="23" - android:targetSdkVersion="23" /> - - <uses-permission android:name="android.permission.READ_CONTACTS" /> - <uses-permission android:name="android.permission.WRITE_CONTACTS" /> - <uses-permission android:name="android.permission.READ_CALL_LOG" /> - <uses-permission android:name="android.permission.WRITE_CALL_LOG" /> - <uses-permission android:name="android.permission.GET_ACCOUNTS" /> - - <uses-permission android:name="android.permission.USE_CREDENTIALS" /> - <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> - <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> - <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /> - <uses-permission android:name="android.permission.READ_SYNC_STATS" /> - <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" /> - <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" /> - - <uses-permission android:name="android.permission.READ_PROFILE" /> - <uses-permission android:name="android.permission.READ_SOCIAL_STREAM" /> - - <uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL" /> - - <application> - <uses-library android:name="android.test.runner" /> - <meta-data android:name="com.android.dialer.iconset" android:resource="@xml/iconset" /> - - <activity android:name=".calllog.FillCallLogTestActivity" - android:label="Call log filter test" - > - <intent-filter> - <action android:name="android.intent.action.MAIN" /> - <category android:name="android.intent.category.DEFAULT" /> - <category android:name="android.intent.category.LAUNCHER" /> - </intent-filter> - </activity> - </application> - - <instrumentation android:name="android.test.InstrumentationTestRunner" - android:targetPackage="com.android.dialer" - android:label="Dialer app tests"> - </instrumentation> - - <instrumentation android:name="com.android.dialer.DialerLaunchPerformance" - android:targetPackage="com.android.dialer" - android:label="Dialer launch performance"> - </instrumentation> - -</manifest> diff --git a/tests/assets/README.txt b/tests/assets/README.txt deleted file mode 100644 index 6cea058cf..000000000 --- a/tests/assets/README.txt +++ /dev/null @@ -1,3 +0,0 @@ -quick_test_recording.mp3 is copyright 2011 by Hugo Hudson and is licensed under a -Creative Commons Attribution 3.0 Unported License: - http://creativecommons.org/licenses/by/3.0/ diff --git a/tests/assets/quick_test_recording.mp3 b/tests/assets/quick_test_recording.mp3 Binary files differdeleted file mode 100644 index ad7cb9c20..000000000 --- a/tests/assets/quick_test_recording.mp3 +++ /dev/null diff --git a/tests/proguard.flags b/tests/proguard.flags deleted file mode 100644 index 3991a1452..000000000 --- a/tests/proguard.flags +++ /dev/null @@ -1,20 +0,0 @@ --keep class com.android.contacts.model.Sources { - public <init>(...); -} - -# Xml files containing onClick (menus and layouts) require that proguard not -# remove their handlers. --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); - public void *(android.view.MenuItem); -} - -# Any class or method annotated with NeededForTesting or NeededForReflection. --keep @com.android.contacts.common.test.NeededForTesting class * --keep @com.android.contacts.test.NeededForReflection class * --keepclassmembers class * { -@com.android.contacts.common.test.NeededForTesting *; -@com.android.contacts.test.NeededForReflection *; -} - --verbose diff --git a/tests/res/drawable/phone_icon.png b/tests/res/drawable/phone_icon.png Binary files differdeleted file mode 100644 index 4e613ecce..000000000 --- a/tests/res/drawable/phone_icon.png +++ /dev/null diff --git a/tests/res/layout/fill_call_log_test.xml b/tests/res/layout/fill_call_log_test.xml deleted file mode 100644 index 43f475b52..000000000 --- a/tests/res/layout/fill_call_log_test.xml +++ /dev/null @@ -1,267 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - ~ Copyright (C) 2012 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 - --> - -<LinearLayout - xmlns:android="http://schemas.android.com/apk/res/android" - android:orientation="vertical" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:gravity="left" -> - <TextView - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/numberOfCallLogEntries" - /> - <EditText - android:id="@+id/number" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:inputType="number" - android:text="10" - /> - <CheckBox - android:id="@+id/use_random_numbers" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/useRandomNumbers" - /> - <Button - android:id="@+id/add" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/addToCallLogButton" - /> - <ProgressBar - android:id="@+id/progress" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:indeterminate="false" - android:visibility="gone" - /> - <TextView - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/add_custom_entry" - /> - <LinearLayout - android:orientation="vertical" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="left" - > - <RadioGroup - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="horizontal"> - <RadioButton - android:id="@+id/call_type_incoming" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_type_incoming" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/call_type_missed" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_type_missed" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/call_type_outgoing" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_type_outgoing" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/call_type_voicemail" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_type_voicemail" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/call_type_custom" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="Custom" - android:textSize="9sp" /> - <EditText - android:id="@+id/call_type_custom_text" - android:layout_width="90dp" - android:layout_height="wrap_content" - android:text="" - android:inputType="number" /> - </RadioGroup> - <CheckBox - android:id="@+id/call_type_video" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/call_type_video" - android:textSize="9sp" - /> - </LinearLayout> - <LinearLayout - android:orientation="horizontal" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="left" - > - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_date" - /> - <TextView - android:id="@+id/call_date" - android:paddingStart="16dp" - android:layout_width="120dp" - android:layout_height="wrap_content" - /> - <Button - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/edit" - android:onClick="showDatePickerDialog" /> - </LinearLayout> - <LinearLayout - android:orientation="horizontal" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="left" - > - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_time" - /> - <TextView - android:id="@+id/call_time" - android:paddingStart="16dp" - android:layout_width="120dp" - android:layout_height="wrap_content" - /> - <Button - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/edit" - android:onClick="showTimePickerDialog" /> - </LinearLayout> - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_presentation" - /> - <RadioGroup - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="horizontal"> - <RadioButton - android:id="@+id/presentation_allowed" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/presentation_allowed" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/presentation_restricted" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/presentation_restricted" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/presentation_unknown" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/presentation_unknown" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/presentation_payphone" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/presentation_payphone" - android:textSize="9sp" /> - </RadioGroup> - <LinearLayout - android:orientation="horizontal" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="left" - > - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/number" - /> - <EditText - android:id="@+id/phone_number" - android:layout_width="180dp" - android:layout_height="wrap_content" - android:inputType="phone" - /> - </LinearLayout> - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/call_account" /> - <RadioGroup - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="horizontal"> - <RadioButton - android:id="@+id/account0" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/account0" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/account1" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/account1" - android:textSize="9sp" /> - <RadioButton - android:id="@+id/no_account" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/no_account" - android:textSize="9sp" /> - </RadioGroup> - <Button - android:id="@+id/add_custom" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/addToCallLogButton" - android:onClick="addManualEntry" - /> - <LinearLayout - android:orientation="horizontal" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:gravity="left" - > - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/delta_after_add" - /> - <EditText - android:id="@+id/delta_after_add" - android:layout_width="90dp" - android:layout_height="wrap_content" - android:text="-1" - android:inputType="number" - /> - </LinearLayout> -</LinearLayout> diff --git a/tests/res/values/donottranslate_strings.xml b/tests/res/values/donottranslate_strings.xml deleted file mode 100644 index 2f8017cd2..000000000 --- a/tests/res/values/donottranslate_strings.xml +++ /dev/null @@ -1,60 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - ~ Copyright (C) 2012 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 - --> -<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - - <string-array name="allIntents"> - <!-- List modes --> - <!-- Various ways to start Contacts --> - <item>DIAL</item> - <item>DIAL phone (deprecated)</item> - <item>DIAL person (deprecated)</item> - <item>DIAL voicemail</item> - <item>CALL BUTTON</item> - <item>DIAL tel</item> - <item>VIEW tel</item> - <item>VIEW calls (call-log after a phone call)</item> - <item>VIEW calls item</item> - <item>CallDetailActivity (legacy)</item> - <item>CallLogActivity (legacy)</item> - </string-array> - - <string name="addToCallLogButton">Add</string> - <string name="useRandomNumbers">Use random numbers</string> - <string name="numberOfCallLogEntries">Number of call log entries to add:</string> - <string name="addedLogEntriesToast">Added %1$d call log entries.</string> - <string name="noLogEntriesToast">No entries in the call log yet. Need at least one record for the template. Or use random numbers.</string> - <string name="add_custom_entry">Add custom call log entry:</string> - <string name="call_type_incoming">Incoming</string> - <string name="call_type_missed">Missed</string> - <string name="call_type_outgoing">Outgoing</string> - <string name="call_type_video">Video</string> - <string name="call_type_voicemail">Voicemail</string> - <string name="call_date">Call date</string> - <string name="call_time">Call time</string> - <string name="edit">Edit</string> - <string name="number">Number</string> - <string name="call_presentation">Presentation</string> - <string name="presentation_allowed">Allowed</string> - <string name="presentation_restricted">Restricted</string> - <string name="presentation_unknown">Unknown</string> - <string name="presentation_payphone">Payphone</string> - <string name="delta_after_add">Offset call time after add (min): </string> - <string name="call_account">Account</string> - <string name="account0">Account 0</string> - <string name="account1">Account 1</string> - <string name="no_account">No Account</string> -</resources> diff --git a/tests/res/xml/iconset.xml b/tests/res/xml/iconset.xml deleted file mode 100644 index 2f7798db1..000000000 --- a/tests/res/xml/iconset.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - ~ Copyright (C) 2012 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 - --> - -<icon-set xmlns:android="http://schemas.android.com/apk/res/android"> - - <icon android:mimeType="vnd.android.cursor.item/phone" - android:icon="@drawable/phone_icon" /> - -</icon-set> diff --git a/tests/src/com/android/dialer/CallDetailActivityTest.java b/tests/src/com/android/dialer/CallDetailActivityTest.java deleted file mode 100644 index fec25f655..000000000 --- a/tests/src/com/android/dialer/CallDetailActivityTest.java +++ /dev/null @@ -1,183 +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.dialer; - -import static com.android.dialer.calllog.CallLogAsyncTaskUtil.Tasks; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Intent; -import android.net.Uri; -import android.provider.CallLog; -import android.provider.VoicemailContract; -import android.test.ActivityInstrumentationTestCase2; -import android.test.suitebuilder.annotation.LargeTest; -import android.test.suitebuilder.annotation.Suppress; -import android.view.Menu; -import android.widget.PopupMenu; -import android.widget.TextView; - -import com.android.dialer.calllog.CallLogAsyncTaskUtil; -import com.android.dialer.util.AppCompatConstants; -import com.android.dialer.util.AsyncTaskExecutors; -import com.android.dialer.util.FakeAsyncTaskExecutor; - -/** - * Unit tests for the {@link CallDetailActivity}. NOTE: The screen needs to be on for the - * UI-related tests to pass. - */ -@LargeTest -public class CallDetailActivityTest extends ActivityInstrumentationTestCase2<CallDetailActivity> { - private static final String CONTACT_NUMBER = "+1412555555"; - private static final String VOICEMAIL_FILE_LOCATION = "/sdcard/sadlfj893w4j23o9sfu.mp3"; - - private Uri mCallLogUri; - private Uri mVoicemailUri; - private FakeAsyncTaskExecutor mFakeAsyncTaskExecutor; - private CallDetailActivity mActivityUnderTest; - - public CallDetailActivityTest() { - super(CallDetailActivity.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - mFakeAsyncTaskExecutor = new FakeAsyncTaskExecutor(getInstrumentation()); - AsyncTaskExecutors.setFactoryForTest(mFakeAsyncTaskExecutor.getFactory()); - - // I don't like the default of focus-mode for tests, the green focus border makes the - // screenshots look weak. - setActivityInitialTouchMode(true); - } - - @Override - protected void tearDown() throws Exception { - cleanUpUri(); - - AsyncTaskExecutors.setFactoryForTest(null); - CallLogAsyncTaskUtil.resetForTest(); - - super.tearDown(); - } - - /** Test for bug where missing Extras on intent used to start Activity causes NPE. */ - public void testCallLogUriWithMissingExtrasShouldNotCauseNPE() throws Throwable { - setActivityIntentForTestCallEntry(); - startActivityUnderTest(); - } - - /** - * Verifies the trash menu item is present and a voicemail URI is set. - */ - @Suppress - public void testVoicemailDeleteButton() throws Throwable { - setActivityIntentForTestVoicemailEntry(); - startActivityUnderTest(); - mFakeAsyncTaskExecutor.runTask(Tasks.GET_CALL_DETAILS); - - Menu optionsMenu = (new PopupMenu(mActivityUnderTest, null)).getMenu(); - mActivityUnderTest.onCreateOptionsMenu(optionsMenu); - mActivityUnderTest.onPrepareOptionsMenu(optionsMenu); - - assertTrue(mActivityUnderTest.hasVoicemail()); - mActivityUnderTest.runOnUiThread(new Runnable() { - public void run() { - mActivityUnderTest.findViewById(R.id.call_detail_delete_menu_item).performClick(); - } - }); - getInstrumentation().waitForIdleSync(); - mFakeAsyncTaskExecutor.runTask(Tasks.DELETE_VOICEMAIL); - } - - /** - * Verifies the trash menu item is present and a voicemail URI is not set. - */ - @Suppress - public void testRegularCallDoesHaveRemoveFromCallLog() throws Throwable { - setActivityIntentForTestCallEntry(); - startActivityUnderTest(); - mFakeAsyncTaskExecutor.runTask(Tasks.GET_CALL_DETAILS); - - Menu optionsMenu = (new PopupMenu(mActivityUnderTest, null)).getMenu(); - mActivityUnderTest.onCreateOptionsMenu(optionsMenu); - mActivityUnderTest.onPrepareOptionsMenu(optionsMenu); - - assertFalse(mActivityUnderTest.hasVoicemail()); - mActivityUnderTest.runOnUiThread(new Runnable() { - public void run() { - mActivityUnderTest.findViewById(R.id.call_detail_delete_menu_item).performClick(); - } - }); - getInstrumentation().waitForIdleSync(); - mFakeAsyncTaskExecutor.runTask(Tasks.DELETE_CALL); - } - - private void setActivityIntentForTestCallEntry() { - assertNull(mVoicemailUri); - assertNull(mCallLogUri); - ContentResolver contentResolver = getContentResolver(); - ContentValues values = new ContentValues(); - values.put(CallLog.Calls.NUMBER, CONTACT_NUMBER); - values.put(CallLog.Calls.NUMBER_PRESENTATION, CallLog.Calls.PRESENTATION_ALLOWED); - values.put(CallLog.Calls.TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - mCallLogUri = contentResolver.insert(CallLog.Calls.CONTENT_URI, values); - setActivityIntent(new Intent(Intent.ACTION_VIEW, mCallLogUri)); - } - - private void setActivityIntentForTestVoicemailEntry() { - assertNull(mVoicemailUri); - ContentResolver contentResolver = getContentResolver(); - ContentValues values = new ContentValues(); - values.put(VoicemailContract.Voicemails.NUMBER, CONTACT_NUMBER); - values.put(VoicemailContract.Voicemails.HAS_CONTENT, 1); - // VoicemailContract.Voicemails._DATA - values.put("_data", VOICEMAIL_FILE_LOCATION); - mVoicemailUri = contentResolver.insert(VoicemailContract.Voicemails.CONTENT_URI, values); - - Uri callLogUri = ContentUris.withAppendedId(CallLog.Calls.CONTENT_URI_WITH_VOICEMAIL, - ContentUris.parseId(mVoicemailUri)); - Intent intent = new Intent(Intent.ACTION_VIEW, callLogUri); - intent.putExtra(CallDetailActivity.EXTRA_VOICEMAIL_URI, mVoicemailUri); - setActivityIntent(intent); - } - - private void cleanUpUri() { - if (mVoicemailUri != null) { - getContentResolver().delete(VoicemailContract.Voicemails.CONTENT_URI, - "_ID = ?", new String[] { String.valueOf(ContentUris.parseId(mVoicemailUri)) }); - mVoicemailUri = null; - } - if (mCallLogUri != null) { - getContentResolver().delete(CallLog.Calls.CONTENT_URI_WITH_VOICEMAIL, - "_ID = ?", new String[] { String.valueOf(ContentUris.parseId(mCallLogUri)) }); - mCallLogUri = null; - } - } - - private ContentResolver getContentResolver() { - return getInstrumentation().getTargetContext().getContentResolver(); - } - - private void startActivityUnderTest() throws Throwable { - assertNull(mActivityUnderTest); - mActivityUnderTest = getActivity(); - assertNotNull("activity should not be null", mActivityUnderTest); - } -} diff --git a/tests/src/com/android/dialer/DialerLaunchPerformance.java b/tests/src/com/android/dialer/DialerLaunchPerformance.java deleted file mode 100644 index c409cc60b..000000000 --- a/tests/src/com/android/dialer/DialerLaunchPerformance.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2007 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.dialer; - -import android.app.Activity; -import android.content.ComponentName; -import android.content.Intent; -import android.os.Bundle; - -import com.android.contacts.common.test.LaunchPerformanceBase; - -/** - * Instrumentation class for Address Book launch performance testing. - */ -public class DialerLaunchPerformance extends LaunchPerformanceBase { - - @Override - public void onCreate(Bundle arguments) { - mIntent.setAction(Intent.ACTION_MAIN); - mIntent.addCategory(Intent.CATEGORY_LAUNCHER); - mIntent.setComponent(new ComponentName("com.android.contacts", - "testcom.android.dialer.DialtactsActivity")); - - start(); - } - - /** - * Calls LaunchApp and finish. - */ - @Override - public void onStart() { - super.onStart(); - LaunchApp(); - finish(Activity.RESULT_OK, mResults); - } -} diff --git a/tests/src/com/android/dialer/calllog/BlockReportSpamListenerTest.java b/tests/src/com/android/dialer/calllog/BlockReportSpamListenerTest.java deleted file mode 100644 index c63027d6b..000000000 --- a/tests/src/com/android/dialer/calllog/BlockReportSpamListenerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.android.dialer.calllog; - -import android.app.Activity; -import android.support.v7.widget.RecyclerView; -import android.test.ActivityInstrumentationTestCase2; - -import com.android.dialer.DialtactsActivity; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler; -import com.android.dialer.service.ExtendedCallInfoService; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Unit tests for {@link BlockReportSpamListener}. - */ -public class BlockReportSpamListenerTest extends ActivityInstrumentationTestCase2<DialtactsActivity> { - - private static final String TEST_DISPLAY_NUMBER = "(123)456-7890"; - private static final String TEST_NUMBER = "1234567890"; - private static final String TEST_COUNTRY_ISO = "us"; - private static final int TEST_CALL_TYPE = 0; - private static final int TEST_CALL_BLOCK_ID = 1; - - private BlockReportSpamListener blockReportSpamListener; - - @Mock private RecyclerView.Adapter adapter; - @Mock private ExtendedCallInfoService extendedCallInfoService; - @Mock private FilteredNumberAsyncQueryHandler filteredNumberAsyncQueryHandler; - - public BlockReportSpamListenerTest() { - super(DialtactsActivity.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - MockitoAnnotations.initMocks(this); - - blockReportSpamListener = new BlockReportSpamListener( - ((Activity) getActivity()).getFragmentManager(), adapter, - extendedCallInfoService, filteredNumberAsyncQueryHandler); - } - - public void testOnBlockReportSpam() { - blockReportSpamListener.onBlockReportSpam( - TEST_DISPLAY_NUMBER, TEST_NUMBER, TEST_COUNTRY_ISO, TEST_CALL_TYPE); - } - - public void testOnBlock() { - blockReportSpamListener.onBlock( - TEST_DISPLAY_NUMBER, TEST_NUMBER, TEST_COUNTRY_ISO, TEST_CALL_TYPE); - } - - public void testOnUnlock_isSpam() { - blockReportSpamListener.onUnblock( - TEST_DISPLAY_NUMBER, TEST_NUMBER, TEST_COUNTRY_ISO, TEST_CALL_BLOCK_ID, - true, TEST_CALL_TYPE); - } - - public void testOnUnlock_isNotSpam() { - blockReportSpamListener.onUnblock( - TEST_DISPLAY_NUMBER, TEST_NUMBER, TEST_COUNTRY_ISO, TEST_CALL_BLOCK_ID, - false, TEST_CALL_TYPE); - } - - public void testOnReportNotSpam() { - blockReportSpamListener.onReportNotSpam( - TEST_DISPLAY_NUMBER, TEST_NUMBER, TEST_COUNTRY_ISO, TEST_CALL_TYPE); - } -} diff --git a/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java b/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java deleted file mode 100644 index 3b1dd2c7d..000000000 --- a/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java +++ /dev/null @@ -1,918 +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.dialer.calllog; - -import com.google.common.collect.Lists; - -import android.content.ContentUris; -import android.content.Context; -import android.content.Intent; -import android.content.res.Resources; -import android.database.MatrixCursor; -import android.net.Uri; -import android.provider.CallLog.Calls; -import android.provider.ContactsContract.CommonDataKinds.Phone; -import android.provider.VoicemailContract; -import android.telephony.PhoneNumberUtils; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.text.TextUtils; -import android.view.View; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.contacts.common.preference.ContactsPreferences; -import com.android.dialer.contactinfo.ContactInfoCache; -import com.android.dialer.database.VoicemailArchiveContract; -import com.android.dialer.util.AppCompatConstants; -import com.android.dialer.util.TestConstants; -import com.android.dialer.R; - -import java.util.Date; -import java.util.List; -import java.util.Random; - -/** - * Unit tests for {@link CallLogAdapter}. - * - * adb shell am instrument \ - * -e com.android.dialer.calllog.CallLogAdapterTest \ - * -w com.android.dialer.tests/android.test.InstrumentationTestRunner - */ -public class CallLogAdapterTest extends AndroidTestCase { - private static final String EMPTY_STRING = ""; - private static final int NO_VALUE_SET = -1; - private static final int ARCHIVE_TYPE = -2; - - private static final String TEST_CACHED_NAME_PRIMARY = "Cached Name"; - private static final String TEST_CACHED_NAME_ALTERNATIVE = "Name Cached"; - private static final String CONTACT_NAME_PRIMARY = "Contact Name"; - private static final String CONTACT_NAME_ALTERNATIVE = "Name, Contact"; - private static final String TEST_CACHED_NUMBER_LABEL = "label"; - private static final int TEST_CACHED_NUMBER_TYPE = 1; - private static final String TEST_COUNTRY_ISO = "US"; - private static final String TEST_DEFAULT_CUSTOM_LABEL = "myLabel"; - private static final Uri TEST_LOOKUP_URI = Uri.parse("content://contacts/2"); - private static final String TEST_ACCOUNT_ID_LABEL = "label"; - - private static final String TEST_NUMBER = "12125551000"; - private static final String TEST_NUMBER_1 = "12345678"; - private static final String TEST_NUMBER_2 = "87654321"; - private static final String TEST_NUMBER_3 = "18273645"; - private static final String TEST_POST_DIAL_DIGITS = ";12345"; - private static final String TEST_VIA_NUMBER = "+16505551234"; - private static final String TEST_FORMATTED_NUMBER = "1 212-555-1000"; - - // The object under test. - private TestCallLogAdapter mAdapter; - - private MatrixCursor mCursor; - private Resources mResources; - - private CallLogListItemViewHolder mViewHolder; - private final Random mRandom = new Random(); - - @Override - protected void setUp() throws Exception { - super.setUp(); - mContext = getContext(); - mResources = mContext.getResources(); - - // Use a call fetcher that does not do anything. - CallLogAdapter.CallFetcher fakeCallFetcher = new CallLogAdapter.CallFetcher() { - @Override - public void fetchCalls() {} - }; - - ContactInfoHelper fakeContactInfoHelper = - new ContactInfoHelper(getContext(), TEST_COUNTRY_ISO) { - @Override - public ContactInfo lookupNumber(String number, String countryIso) { - ContactInfo info = new ContactInfo(); - info.number = number; - info.formattedNumber = number; - return info; - } - }; - - mAdapter = new TestCallLogAdapter(getContext(), fakeCallFetcher, fakeContactInfoHelper, - CallLogAdapter.ACTIVITY_TYPE_DIALTACTS); - - // The cursor used in the tests to store the entries to display. - mCursor = new MatrixCursor(CallLogQuery._PROJECTION); - mCursor.moveToFirst(); - - // The views into which to store the data. - mViewHolder = CallLogListItemViewHolder.createForTest(getContext()); - } - - @MediumTest - public void testBindView_NumberOnlyNoCache() { - createCallLogEntry(); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, TEST_NUMBER); - } - - @MediumTest - public void testBindView_PrivateCall() { - createPrivateCallLogEntry(); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertEquals(Calls.PRESENTATION_RESTRICTED, mViewHolder.numberPresentation); - assertNull(mViewHolder.primaryActionButtonView.getTag()); - // QC should be disabled since there are no actions to be performed on this - // call. - assertFalse(mViewHolder.quickContactView.isEnabled()); - } - - @MediumTest - public void testBindView_UnknownCall() { - createUnknownCallLogEntry(); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertEquals(Calls.PRESENTATION_UNKNOWN, mViewHolder.numberPresentation); - assertNull(mViewHolder.primaryActionButtonView.getTag()); - // QC should be disabled since there are no actions to be performed on this - // call. - assertFalse(mViewHolder.quickContactView.isEnabled()); - } - - @MediumTest - public void testBindView_WithoutQuickContactBadge() { - createCallLogEntry(); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - //assertFalse(mViewHolder.quickContactView.isEnabled()); - } - - @MediumTest - public void testBindView_CallButton() { - createCallLogEntry(); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // The primaryActionView tag is set when the ViewHolder is binded. If it is possible - // to place a call to the phone number, a call intent will have been created which - // starts a phone call to the entry's number. - assertHasCallAction(mViewHolder); - } - - @MediumTest - public void testBindView_FirstNameFirstOrder() { - createCallLogEntry(); - - mAdapter.getContactInfoCache() - .mockGetValue(createContactInfo(CONTACT_NAME_PRIMARY, CONTACT_NAME_ALTERNATIVE)); - - setNameDisplayOrder(getContext(), ContactsPreferences.DISPLAY_ORDER_PRIMARY); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - assertEquals(CONTACT_NAME_PRIMARY, mViewHolder.phoneCallDetailsViews.nameView.getText()); - } - - @MediumTest - public void testBindView_LastNameFirstOrder() { - createCallLogEntry(); - - mAdapter.getContactInfoCache() - .mockGetValue(createContactInfo(CONTACT_NAME_PRIMARY, CONTACT_NAME_ALTERNATIVE)); - - setNameDisplayOrder(getContext(), ContactsPreferences.DISPLAY_ORDER_ALTERNATIVE); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - assertEquals(CONTACT_NAME_ALTERNATIVE, - mViewHolder.phoneCallDetailsViews.nameView.getText()); - } - - @MediumTest - public void testBindView_NameOrderCorrectOnChange() { - createCallLogEntry(); - - mAdapter.getContactInfoCache() - .mockGetValue(createContactInfo(CONTACT_NAME_PRIMARY, CONTACT_NAME_ALTERNATIVE)); - - Context context = getContext(); - setNameDisplayOrder(context, ContactsPreferences.DISPLAY_ORDER_PRIMARY); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - assertEquals(CONTACT_NAME_PRIMARY, - mViewHolder.phoneCallDetailsViews.nameView.getText()); - - setNameDisplayOrder(context, ContactsPreferences.DISPLAY_ORDER_ALTERNATIVE); - mAdapter.onResume(); - - mAdapter.onBindViewHolder(mViewHolder, 0); - assertEquals(CONTACT_NAME_ALTERNATIVE, - mViewHolder.phoneCallDetailsViews.nameView.getText()); - } - - private void setNameDisplayOrder(Context context, int displayOrder) { - context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE).edit().putInt( - ContactsPreferences.DISPLAY_ORDER_KEY, displayOrder).commit(); - } - - @MediumTest - public void testBindView_CallButtonWithPostDialDigits() { - createCallLogEntry(TEST_NUMBER, TEST_POST_DIAL_DIGITS, NO_VALUE_SET, NO_VALUE_SET); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - if (CompatUtils.isNCompatible()) { - assertHasCallActionToGivenNumber(mViewHolder, TEST_NUMBER + TEST_POST_DIAL_DIGITS); - } - } - - @MediumTest - public void testBindView_VoicemailUri() { - createVoicemailCallLogEntry(); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertEquals(Uri.parse(mViewHolder.voicemailUri), - ContentUris.withAppendedId(VoicemailContract.Voicemails.CONTENT_URI, 0)); - assertNull(mViewHolder.primaryActionButtonView.getTag()); - } - - @MediumTest - public void testBindView_NumberWithPostDialDigits() { - createCallLogEntry(TEST_NUMBER, TEST_POST_DIAL_DIGITS, NO_VALUE_SET, NO_VALUE_SET); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - if (CompatUtils.isNCompatible()) { - assertNameIs(mViewHolder, TEST_NUMBER + TEST_POST_DIAL_DIGITS); - } - } - - @MediumTest - public void testBindView_ContactWithPostDialDigits() { - createCallLogEntry(TEST_NUMBER, TEST_POST_DIAL_DIGITS, NO_VALUE_SET, NO_VALUE_SET); - mAdapter.injectContactInfoForTest(TEST_NUMBER + TEST_POST_DIAL_DIGITS, TEST_COUNTRY_ISO, - createContactInfo()); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - if (CompatUtils.isNCompatible()) { - assertNameIs(mViewHolder, TEST_CACHED_NAME_PRIMARY); - } - } - - @MediumTest - public void testBindView_CallLogWithViaNumber() { - createCallLogEntry(TEST_NUMBER, EMPTY_STRING, TEST_VIA_NUMBER, NO_VALUE_SET, NO_VALUE_SET); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // Copy format of Resource String - String formattedNumber = mResources.getString(R.string.description_via_number, - TEST_VIA_NUMBER); - - if (CompatUtils.isNCompatible()) { - assertEquals(formattedNumber, - mViewHolder.phoneCallDetailsViews.callAccountLabel.getText()); - } - } - - @MediumTest - public void testBindView_CallLogWithoutViaNumber() { - createCallLogEntry(TEST_NUMBER, EMPTY_STRING, EMPTY_STRING, NO_VALUE_SET, NO_VALUE_SET); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - if (CompatUtils.isNCompatible()) { - assertEquals(View.GONE, - mViewHolder.phoneCallDetailsViews.callAccountLabel.getVisibility()); - } - } - - @MediumTest - public void testPresentationAfterRebindingViewHolders() { - final int increment = 10; - final int size = increment * 4; - - // Instantiate list of ViewHolders. - CallLogListItemViewHolder[] holders = new CallLogListItemViewHolder[size]; - for (int i = 0; i < size; i++) { - holders[i] = CallLogListItemViewHolder.createForTest(getContext()); - } - - // Add first set of entries to the cursor. - for (int i = 0; i < increment; i++) { - createCallLogEntry(); - createPrivateCallLogEntry(); - createCallLogEntry(); - createUnknownCallLogEntry(); - } - - mAdapter.changeCursor(mCursor); - - // Verify correct appearance for presentation. - for (int i = 0; i < size; i++) { - mAdapter.onBindViewHolder(holders[i], i); - if (holders[i].numberPresentation == Calls.PRESENTATION_ALLOWED) { - assertHasCallAction(holders[i]); - } else { - assertNull(holders[i].primaryActionButtonView.getTag()); - assertEquals(holders[i].number, EMPTY_STRING); - } - } - - // Append the rest of the entries to the cursor. Keep the first set of ViewHolders - // so they are updated and not buitl from scratch. This checks for bugs which may - // be evident only after the call log is updated. - for (int i = 0; i < increment; i++) { - createPrivateCallLogEntry(); - createCallLogEntry(); - createUnknownCallLogEntry(); - createCallLogEntry(); - } - - mCursor.move(size); - - // Verify correct appearnce for presentation. - for (int i = 0; i < size; i++) { - mAdapter.onBindViewHolder(holders[i], i + size); - if (holders[i].numberPresentation == Calls.PRESENTATION_ALLOWED) { - assertHasCallAction(holders[i]); - } else { - assertNull(holders[i].primaryActionButtonView.getTag()); - assertEquals(holders[i].number, EMPTY_STRING); - } - } - } - - @MediumTest - public void testBindView_NoCallLogCacheNorMemoryCache_EnqueueRequest() { - createCallLogEntry(); - - // Bind the views of a single row. - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // There is one request for contact details. - assertEquals(1, mAdapter.getContactInfoCache().requests.size()); - - TestContactInfoCache.Request request = mAdapter.getContactInfoCache().requests.get(0); - // It is for the number we need to show. - assertEquals(TEST_NUMBER, request.number); - // It has the right country. - assertEquals(TEST_COUNTRY_ISO, request.countryIso); - // Since there is nothing in the cache, it is an immediate request. - assertTrue("should be immediate", request.immediate); - } - - @MediumTest - public void testBindView_CallLogCacheButNoMemoryCache_EnqueueRequest() { - createCallLogEntryWithCachedValues(false); - - // Bind the views of a single row. - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // There is one request for contact details. - assertEquals(1, mAdapter.getContactInfoCache().requests.size()); - - TestContactInfoCache.Request request = mAdapter.getContactInfoCache().requests.get(0); - - // The values passed to the request, match the ones in the call log cache. - assertEquals(TEST_CACHED_NAME_PRIMARY, request.callLogInfo.name); - assertEquals(TEST_CACHED_NUMBER_TYPE, request.callLogInfo.type); - assertEquals(TEST_CACHED_NUMBER_LABEL, request.callLogInfo.label); - } - - @MediumTest - public void testBindView_NoCallLogButMemoryCache_EnqueueRequest() { - createCallLogEntry(); - mAdapter.injectContactInfoForTest(TEST_NUMBER, TEST_COUNTRY_ISO, createContactInfo()); - - // Bind the views of a single row. - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // There is one request for contact details. - assertEquals(1, mAdapter.getContactInfoCache().requests.size()); - - TestContactInfoCache.Request request = mAdapter.getContactInfoCache().requests.get(0); - // Since there is something in the cache, it is not an immediate request. - assertFalse("should not be immediate", request.immediate); - } - - @MediumTest - public void testBindView_BothCallLogAndMemoryCache_NoEnqueueRequest() { - createCallLogEntryWithCachedValues(true); - - // Bind the views of a single row. - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // Cache and call log are up-to-date: no need to request update. - assertEquals(0, mAdapter.getContactInfoCache().requests.size()); - } - - @MediumTest - public void testBindView_MismatchBetweenCallLogAndMemoryCache_EnqueueRequest() { - createCallLogEntryWithCachedValues(false); - - // Contact info contains a different name. - ContactInfo info = createContactInfo(); - info.name = "new name"; - mAdapter.injectContactInfoForTest(TEST_NUMBER, TEST_COUNTRY_ISO, info); - - // Bind the views of a single row. - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - // There is one request for contact details. - assertEquals(1, mAdapter.getContactInfoCache().requests.size()); - - TestContactInfoCache.Request request = mAdapter.getContactInfoCache().requests.get(0); - // Since there is something in the cache, it is not an immediate request. - assertFalse("should not be immediate", request.immediate); - } - - @MediumTest - public void testBindView_WithCachedName() { - createCallLogEntryWithCachedValues( - "John Doe", - Phone.TYPE_HOME, - TEST_CACHED_NUMBER_LABEL); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, "John Doe"); - assertLabel(mViewHolder, TEST_FORMATTED_NUMBER, getTypeLabel(Phone.TYPE_HOME)); - } - - @MediumTest - public void testBindView_UriNumber() { - createCallLogEntryWithCachedValues( - "sip:johndoe@gmail.com", - AppCompatConstants.CALLS_INCOMING_TYPE, - "John Doe", - Phone.TYPE_HOME, - TEST_DEFAULT_CUSTOM_LABEL, - EMPTY_STRING, - false /* inject */); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, "John Doe"); - assertLabel(mViewHolder, "sip:johndoe@gmail.com", "sip:johndoe@gmail.com"); - } - - @MediumTest - public void testBindView_HomeLabel() { - createCallLogEntryWithCachedValues( - "John Doe", - Phone.TYPE_HOME, - TEST_CACHED_NUMBER_LABEL); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, "John Doe"); - assertLabel(mViewHolder, TEST_FORMATTED_NUMBER, getTypeLabel(Phone.TYPE_HOME)); - } - - @MediumTest - public void testBindView_WorkLabel() { - createCallLogEntryWithCachedValues( - "John Doe", - Phone.TYPE_WORK, - TEST_CACHED_NUMBER_LABEL); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, "John Doe"); - assertLabel(mViewHolder, TEST_FORMATTED_NUMBER, getTypeLabel(Phone.TYPE_WORK)); - } - - @MediumTest - public void testBindView_CustomLabel() { - createCallLogEntryWithCachedValues( - "John Doe", - Phone.TYPE_CUSTOM, - TEST_DEFAULT_CUSTOM_LABEL); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, "John Doe"); - assertLabel(mViewHolder, TEST_FORMATTED_NUMBER, TEST_DEFAULT_CUSTOM_LABEL); - } - - @MediumTest - public void testBindView_NumberOnlyDbCachedFormattedNumber() { - createCallLogEntryWithCachedValues( - TEST_NUMBER, - AppCompatConstants.CALLS_INCOMING_TYPE, - EMPTY_STRING, - TEST_CACHED_NUMBER_TYPE, - TEST_CACHED_NUMBER_LABEL, - TEST_FORMATTED_NUMBER, - false /* inject */); - - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertNameIs(mViewHolder, TEST_FORMATTED_NUMBER); - } - - @MediumTest - public void testBindVoicemailPromoCard() { - createCallLogEntry(TEST_NUMBER_1); - createCallLogEntry(TEST_NUMBER_1); - createCallLogEntry(TEST_NUMBER_2); - createCallLogEntry(TEST_NUMBER_2); - createCallLogEntry(TEST_NUMBER_2); - createCallLogEntry(TEST_NUMBER_3); - - // Bind the voicemail promo card. - mAdapter.showVoicemailPromoCard(true); - mAdapter.changeCursor(mCursor); - mAdapter.onBindViewHolder(PromoCardViewHolder.createForTest(getContext()), 0); - - // Check that displaying the promo card does not affect the grouping or list display. - mAdapter.onBindViewHolder(mViewHolder, 1); - assertEquals(2, mAdapter.getGroupSize(1)); - assertEquals(TEST_NUMBER_1, mViewHolder.number); - - mAdapter.onBindViewHolder(mViewHolder, 2); - assertEquals(3, mAdapter.getGroupSize(2)); - assertEquals(TEST_NUMBER_2, mViewHolder.number); - - mAdapter.onBindViewHolder(mViewHolder, 3); - assertEquals(1, mAdapter.getGroupSize(3)); - assertEquals(TEST_NUMBER_3, mViewHolder.number); - } - - public void testVoicemailArchive() { - setUpArchiveAdapter(); - createVoicemailArchiveCallLogEntry(); - - mAdapter.changeCursorVoicemail(mCursor); - mAdapter.onBindViewHolder(mViewHolder, 0); - - assertEquals(Uri.parse(mViewHolder.voicemailUri), - ContentUris.withAppendedId( - VoicemailArchiveContract.VoicemailArchive.CONTENT_URI, 0)); - assertNull(mViewHolder.primaryActionButtonView.getTag()); - } - - private void createCallLogEntry() { - createCallLogEntry(TEST_NUMBER); - } - - private void createCallLogEntry(String testNumber) { - createCallLogEntry(testNumber, EMPTY_STRING, NO_VALUE_SET, NO_VALUE_SET); - } - - private void createPrivateCallLogEntry() { - createCallLogEntry( - EMPTY_STRING, - EMPTY_STRING, - Calls.PRESENTATION_RESTRICTED, - AppCompatConstants.CALLS_INCOMING_TYPE); - } - - private void createUnknownCallLogEntry() { - createCallLogEntry( - EMPTY_STRING, - EMPTY_STRING, - Calls.PRESENTATION_UNKNOWN, - AppCompatConstants.CALLS_INCOMING_TYPE); - } - - private void createVoicemailCallLogEntry() { - createCallLogEntry(TEST_NUMBER, EMPTY_STRING, NO_VALUE_SET, Calls.VOICEMAIL_TYPE); - } - - private void createVoicemailArchiveCallLogEntry() { - createCallLogEntry(TEST_NUMBER, EMPTY_STRING, NO_VALUE_SET, ARCHIVE_TYPE); - } - - private void createCallLogEntry(String number, String postDialDigits, int presentation, - int type) { - Object[] values = getValues(number, postDialDigits, presentation, type); - mCursor.addRow(values); - } - - private void createCallLogEntry(String number, String postDialDigits, String viaNumber, - int presentation, int type) { - Object[] values = getValues(number, postDialDigits, viaNumber, presentation, type); - mCursor.addRow(values); - } - - private void createCallLogEntryWithCachedValues(boolean inject) { - createCallLogEntryWithCachedValues( - TEST_NUMBER, - NO_VALUE_SET, - TEST_CACHED_NAME_PRIMARY, - TEST_CACHED_NUMBER_TYPE, - TEST_CACHED_NUMBER_LABEL, - EMPTY_STRING, - inject); - } - - private void createCallLogEntryWithCachedValues( - String cachedName, int cachedNumberType, String cachedNumberLabel) { - createCallLogEntryWithCachedValues( - TEST_NUMBER, - NO_VALUE_SET, - cachedName, - cachedNumberType, - cachedNumberLabel, - EMPTY_STRING, - false /* inject */); - } - - /** - * Inserts a new call log entry - * - * It includes the values for the cached contact associated with the number. - * - * @param number The phone number. - * @param type Valid value of {@code Calls.TYPE}. - * @param cachedName The name of the contact with this number - * @param cachedNumberType The type of the number, from the contact with this number. - * @param cachedNumberLabel The label of the number, from the contact with this number. - * @param cachedFormattedNumber The formatted number, from the contact with this number. - * @param inject Whether to inject the contact info into the adapter's ContactInfoCache. - */ - private void createCallLogEntryWithCachedValues( - String number, - int type, - String cachedName, - int cachedNumberType, - String cachedNumberLabel, - String cachedFormattedNumber, - boolean inject) { - Object[] values = getValues(number, EMPTY_STRING, NO_VALUE_SET, type); - values[CallLogQuery.CACHED_NAME] = cachedName; - values[CallLogQuery.CACHED_NUMBER_TYPE] = cachedNumberType; - values[CallLogQuery.CACHED_NUMBER_LABEL] = cachedNumberLabel; - values[CallLogQuery.CACHED_FORMATTED_NUMBER] = cachedFormattedNumber; - - mCursor.addRow(values); - - if (inject) { - ContactInfo contactInfo = - createContactInfo(cachedName, cachedName, cachedNumberType, cachedNumberLabel); - mAdapter.injectContactInfoForTest(number, TEST_COUNTRY_ISO, contactInfo); - } - } - - /** - * @param number The phone number. - * @param postDialDigits The post dial digits dialed (if any) - * @param presentation Number representing display rules for "allowed", - * "payphone", "restricted", or "unknown". - * @param type The type of the call (outgoing/ingoing) - */ - private Object[] getValues( - String number, - String postDialDigits, - int presentation, - int type) { - return getValues(number, postDialDigits, "", presentation, type); - } - - /** - * @param number The phone number. - * @param postDialDigits The post dial digits dialed (if any) - * @param viaNumber The secondary number that the call was placed via - * @param presentation Number representing display rules for "allowed", - * "payphone", "restricted", or "unknown". - * @param type The type of the call (outgoing/ingoing) - */ - private Object[] getValues( - String number, - String postDialDigits, - String viaNumber, - int presentation, - int type) { - Object[] values = CallLogQueryTestUtils.createTestValues(); - - values[CallLogQuery.ID] = mCursor.getCount(); - values[CallLogQuery.COUNTRY_ISO] = TEST_COUNTRY_ISO; - values[CallLogQuery.DATE] = new Date().getTime(); - values[CallLogQuery.DURATION] = mRandom.nextInt(10 * 60); - - if (!TextUtils.isEmpty(number)) { - values[CallLogQuery.NUMBER] = number; - } - if (!TextUtils.isEmpty(postDialDigits) && CompatUtils.isNCompatible()) { - values[CallLogQuery.POST_DIAL_DIGITS] = postDialDigits; - } - if (!TextUtils.isEmpty(viaNumber) && CompatUtils.isNCompatible()) { - values[CallLogQuery.VIA_NUMBER] = viaNumber; - } - if (presentation != NO_VALUE_SET) { - values[CallLogQuery.NUMBER_PRESENTATION] = presentation; - } - if (type != NO_VALUE_SET) { - values[CallLogQuery.CALL_TYPE] = type; - } - if (type == AppCompatConstants.CALLS_VOICEMAIL_TYPE) { - values[CallLogQuery.VOICEMAIL_URI] = ContentUris.withAppendedId( - VoicemailContract.Voicemails.CONTENT_URI, mCursor.getCount()); - } - if (type == ARCHIVE_TYPE) { - values[CallLogQuery.VOICEMAIL_URI] = ContentUris.withAppendedId( - VoicemailArchiveContract.VoicemailArchive.CONTENT_URI, mCursor.getCount()); - } - - return values; - } - - private ContactInfo createContactInfo() { - return createContactInfo( - TEST_CACHED_NAME_PRIMARY, - TEST_CACHED_NAME_ALTERNATIVE); - } - - private ContactInfo createContactInfo(String namePrimary, String nameAlternative) { - return createContactInfo( - namePrimary, - nameAlternative, - TEST_CACHED_NUMBER_TYPE, - TEST_CACHED_NUMBER_LABEL); - } - - /** Returns a contact info with default values. */ - private ContactInfo createContactInfo(String namePrimary, String nameAlternative, int type, String label) { - ContactInfo info = new ContactInfo(); - info.number = TEST_NUMBER; - info.name = namePrimary; - info.nameAlternative = nameAlternative; - info.type = type; - info.label = label; - info.formattedNumber = TEST_FORMATTED_NUMBER; - info.normalizedNumber = TEST_NUMBER; - info.lookupUri = TEST_LOOKUP_URI; - return info; - } - - // Asserts that the name text view is shown and contains the given text. - private void assertNameIs(CallLogListItemViewHolder viewHolder, String name) { - assertEquals(View.VISIBLE, viewHolder.phoneCallDetailsViews.nameView.getVisibility()); - assertEquals(name, viewHolder.phoneCallDetailsViews.nameView.getText()); - } - - // Asserts that the label text view contains the given text. - private void assertLabel( - CallLogListItemViewHolder viewHolder, CharSequence number, CharSequence label) { - if (label != null) { - assertTrue(viewHolder.phoneCallDetailsViews.callLocationAndDate.getText() - .toString().contains(label)); - } - } - - private void assertHasCallAction(CallLogListItemViewHolder viewHolder) { - assertHasCallActionToGivenNumber(viewHolder, TEST_NUMBER); - } - - private void assertHasCallActionToGivenNumber(CallLogListItemViewHolder viewHolder, - String number) { - IntentProvider intentProvider = - (IntentProvider) viewHolder.primaryActionButtonView.getTag(); - Intent intent = intentProvider.getIntent(getContext()); - assertEquals(TestConstants.CALL_INTENT_ACTION, intent.getAction()); - assertEquals(Uri.parse("tel:" + Uri.encode(number)), intent.getData()); - } - - /** Returns the label associated with a given phone type. */ - private CharSequence getTypeLabel(int phoneType) { - return Phone.getTypeLabel(getContext().getResources(), phoneType, ""); - } - - private void setUpArchiveAdapter() { - // Use a call fetcher that does not do anything. - CallLogAdapter.CallFetcher fakeCallFetcher = new CallLogAdapter.CallFetcher() { - @Override - public void fetchCalls() {} - }; - - ContactInfoHelper fakeContactInfoHelper = - new ContactInfoHelper(getContext(), TEST_COUNTRY_ISO) { - @Override - public ContactInfo lookupNumber(String number, String countryIso) { - ContactInfo info = new ContactInfo(); - info.number = number; - info.formattedNumber = number; - return info; - } - }; - - mAdapter = new TestCallLogAdapter(getContext(), fakeCallFetcher, fakeContactInfoHelper, - CallLogAdapter.ACTIVITY_TYPE_ARCHIVE); - } - - /// Subclass of {@link CallLogAdapter} used in tests to intercept certain calls. - private static final class TestCallLogAdapter extends CallLogAdapter { - public TestCallLogAdapter(Context context, CallFetcher callFetcher, - ContactInfoHelper contactInfoHelper, int mActivity) { - super(context, callFetcher, contactInfoHelper, null, - mActivity); - mContactInfoCache = new TestContactInfoCache( - contactInfoHelper, mOnContactInfoChangedListener); - } - - public TestContactInfoCache getContactInfoCache() { - return (TestContactInfoCache) mContactInfoCache; - } - - public void showVoicemailPromoCard(boolean show) { - mShowVoicemailPromoCard = show; - } - } - - private static final class TestContactInfoCache extends ContactInfoCache { - public static class Request { - public final String number; - public final String countryIso; - public final ContactInfo callLogInfo; - public final boolean immediate; - - public Request(String number, String countryIso, ContactInfo callLogInfo, - boolean immediate) { - this.number = number; - this.countryIso = countryIso; - this.callLogInfo = callLogInfo; - this.immediate = immediate; - } - } - - public final List<Request> requests = Lists.newArrayList(); - - /** - * Dummy contactInfo to return in the even that the getValue method has been mocked - */ - private ContactInfo mContactInfo; - - public TestContactInfoCache( - ContactInfoHelper contactInfoHelper, OnContactInfoChangedListener listener) { - super(contactInfoHelper, listener); - } - - /** - * Sets the given value to be returned by all calls to - * {@link #getValue(String, String, ContactInfo)} - * - * @param contactInfo the contactInfo - */ - public void mockGetValue(ContactInfo contactInfo) { - this.mContactInfo = contactInfo; - } - - @Override - public ContactInfo getValue(String number, String countryIso, - ContactInfo cachedContactInfo) { - if (mContactInfo != null) { - return mContactInfo; - } - return super.getValue(number, countryIso, cachedContactInfo); - } - - @Override - protected void enqueueRequest(String number, String countryIso, ContactInfo callLogInfo, - boolean immediate) { - requests.add(new Request(number, countryIso, callLogInfo, immediate)); - } - } -} diff --git a/tests/src/com/android/dialer/calllog/CallLogGroupBuilderTest.java b/tests/src/com/android/dialer/calllog/CallLogGroupBuilderTest.java deleted file mode 100644 index beb83b1ad..000000000 --- a/tests/src/com/android/dialer/calllog/CallLogGroupBuilderTest.java +++ /dev/null @@ -1,470 +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.dialer.calllog; - -import static com.google.common.collect.Lists.newArrayList; - -import android.database.MatrixCursor; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.dialer.util.AppCompatConstants; - -import java.util.List; - -/** - * Unit tests for {@link CallLogGroupBuilder} - */ -@SmallTest -public class CallLogGroupBuilderTest extends AndroidTestCase { - /** A phone number for testing. */ - private static final String TEST_NUMBER1 = "14125551234"; - /** A phone number for testing. */ - private static final String TEST_NUMBER2 = "14125555555"; - /** A post-dial string for testing */ - private static final String TEST_POST_DIAL_DIGITS = ";12435;0987"; - - /** The object under test. */ - private CallLogGroupBuilder mBuilder; - /** Records the created groups. */ - private FakeGroupCreator mFakeGroupCreator; - /** Cursor to store the values. */ - private MatrixCursor mCursor; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mFakeGroupCreator = new FakeGroupCreator(); - mBuilder = new CallLogGroupBuilder(mFakeGroupCreator); - createCursor(); - } - - @Override - protected void tearDown() throws Exception { - mCursor = null; - mBuilder = null; - mFakeGroupCreator = null; - super.tearDown(); - } - - public void testAddGroups_NoCalls() { - mBuilder.addGroups(mCursor); - assertEquals(0, mFakeGroupCreator.groups.size()); - } - - public void testAddGroups_OneCall() { - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - mBuilder.addGroups(mCursor); - assertEquals(1, mFakeGroupCreator.groups.size()); - } - - public void testAddGroups_TwoCallsNotMatching() { - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - addCallLogEntry(TEST_NUMBER2, AppCompatConstants.CALLS_INCOMING_TYPE); - mBuilder.addGroups(mCursor); - assertEquals(2, mFakeGroupCreator.groups.size()); - } - - public void testAddGroups_ThreeCallsMatching() { - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - mBuilder.addGroups(mCursor); - assertEquals(1, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 3, mFakeGroupCreator.groups.get(0)); - } - - public void testAddGroups_WithPostDialMatching() { - addCallLogEntryWithPostDialDigits(TEST_NUMBER1, TEST_POST_DIAL_DIGITS, - AppCompatConstants.CALLS_OUTGOING_TYPE); - addCallLogEntryWithPostDialDigits(TEST_NUMBER1, TEST_POST_DIAL_DIGITS, - AppCompatConstants.CALLS_OUTGOING_TYPE); - addCallLogEntryWithPostDialDigits(TEST_NUMBER1, "", - AppCompatConstants.CALLS_OUTGOING_TYPE); - - mBuilder.addGroups(mCursor); - - if (CompatUtils.isNCompatible()) { - assertEquals(2, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 2, mFakeGroupCreator.groups.get(0)); - assertGroupIs(2, 1, mFakeGroupCreator.groups.get(1)); - } else { - assertEquals(1, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 3, mFakeGroupCreator.groups.get(0)); - } - } - - public void testAddGroups_WithViaNumberMatching() { - addCallLogEntryWithViaNumber(TEST_NUMBER1, TEST_NUMBER2, - AppCompatConstants.CALLS_OUTGOING_TYPE); - addCallLogEntryWithViaNumber(TEST_NUMBER1, TEST_NUMBER2, - AppCompatConstants.CALLS_OUTGOING_TYPE); - addCallLogEntryWithViaNumber(TEST_NUMBER1, "", - AppCompatConstants.CALLS_OUTGOING_TYPE); - - mBuilder.addGroups(mCursor); - - if (CompatUtils.isNCompatible()) { - assertEquals(2, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 2, mFakeGroupCreator.groups.get(0)); - assertGroupIs(2, 1, mFakeGroupCreator.groups.get(1)); - } else { - assertEquals(1, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 3, mFakeGroupCreator.groups.get(0)); - } - } - - public void testAddGroups_MatchingIncomingAndOutgoing() { - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_OUTGOING_TYPE); - addCallLogEntry(TEST_NUMBER1, AppCompatConstants.CALLS_INCOMING_TYPE); - mBuilder.addGroups(mCursor); - assertEquals(1, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 3, mFakeGroupCreator.groups.get(0)); - } - - public void testGrouping_Voicemail() { - // Does not group with other types of calls, include voicemail themselves. - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_MISSED_TYPE); - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_VOICEMAIL_TYPE); - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_OUTGOING_TYPE); - } - - public void testGrouping_VoicemailArchive() { - // Does not group with other types of calls, include voicemail themselves. - assertVoicemailsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_MISSED_TYPE); - assertVoicemailsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_VOICEMAIL_TYPE); - assertVoicemailsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - assertVoicemailsAreNotGrouped( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_OUTGOING_TYPE); - } - - public void testGrouping_Missed() { - // Groups with one or more missed calls. - assertCallsAreGrouped( - AppCompatConstants.CALLS_MISSED_TYPE, AppCompatConstants.CALLS_MISSED_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE); - // Does not group with other types of calls. - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_MISSED_TYPE, AppCompatConstants.CALLS_VOICEMAIL_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_MISSED_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_MISSED_TYPE, AppCompatConstants.CALLS_OUTGOING_TYPE); - } - - public void testGrouping_Incoming() { - // Groups with one or more incoming or outgoing. - assertCallsAreGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_MISSED_TYPE); - // Does not group with voicemail and missed calls. - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_VOICEMAIL_TYPE); - } - - public void testGrouping_Outgoing() { - // Groups with one or more incoming or outgoing. - assertCallsAreGrouped( - AppCompatConstants.CALLS_OUTGOING_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_OUTGOING_TYPE, AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_MISSED_TYPE); - // Does not group with voicemail and missed calls. - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_VOICEMAIL_TYPE); - } - - public void testGrouping_Blocked() { - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_BLOCKED_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_BLOCKED_TYPE, AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallsAreNotGrouped( - AppCompatConstants.CALLS_BLOCKED_TYPE, AppCompatConstants.CALLS_MISSED_TYPE); - - } - - public void testAddGroups_Separate() { - addMultipleCallLogEntries(TEST_NUMBER1, - AppCompatConstants.CALLS_VOICEMAIL_TYPE, // Group 1: 0 - AppCompatConstants.CALLS_INCOMING_TYPE, // Group 2: 1 - AppCompatConstants.CALLS_OUTGOING_TYPE, // Group 3: 2 - AppCompatConstants.CALLS_MISSED_TYPE); // Group 4: 3 - mBuilder.addVoicemailGroups(mCursor); - - assertEquals(4, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 1, mFakeGroupCreator.groups.get(0)); - assertGroupIs(1, 1, mFakeGroupCreator.groups.get(1)); - assertGroupIs(2, 1, mFakeGroupCreator.groups.get(2)); - assertGroupIs(3, 1, mFakeGroupCreator.groups.get(3)); - } - - public void testAddGroups_Mixed() { - addMultipleCallLogEntries(TEST_NUMBER1, - AppCompatConstants.CALLS_VOICEMAIL_TYPE, // Group 1: 0 - AppCompatConstants.CALLS_INCOMING_TYPE, // Group 2: 1-4 - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_VOICEMAIL_TYPE, // Group 3: 5 - AppCompatConstants.CALLS_INCOMING_TYPE, // Group 4: 6 - AppCompatConstants.CALLS_VOICEMAIL_TYPE, // Group 5: 7 - AppCompatConstants.CALLS_MISSED_TYPE, // Group 6: 8-10 - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE); - mBuilder.addGroups(mCursor); - - assertEquals(6, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 1, mFakeGroupCreator.groups.get(0)); - assertGroupIs(1, 4, mFakeGroupCreator.groups.get(1)); - assertGroupIs(5, 1, mFakeGroupCreator.groups.get(2)); - assertGroupIs(6, 1, mFakeGroupCreator.groups.get(3)); - assertGroupIs(7, 1, mFakeGroupCreator.groups.get(4)); - assertGroupIs(8, 3, mFakeGroupCreator.groups.get(5)); - } - - public void testAddGroups_Blocked() { - addMultipleCallLogEntries(TEST_NUMBER1, - AppCompatConstants.CALLS_INCOMING_TYPE, // Group 1: 0-1 - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_BLOCKED_TYPE, // Group 2: 2 - AppCompatConstants.CALLS_MISSED_TYPE, // Group 3: 3 - AppCompatConstants.CALLS_BLOCKED_TYPE, // Group 4: 4-5 - AppCompatConstants.CALLS_BLOCKED_TYPE); - mBuilder.addGroups(mCursor); - - assertEquals(4, mFakeGroupCreator.groups.size()); - assertGroupIs(0, 2, mFakeGroupCreator.groups.get(0)); - assertGroupIs(2, 1, mFakeGroupCreator.groups.get(1)); - assertGroupIs(3, 1, mFakeGroupCreator.groups.get(2)); - assertGroupIs(4, 2, mFakeGroupCreator.groups.get(3)); - } - - public void testEqualPhoneNumbers() { - // Identical. - assertTrue(mBuilder.equalNumbers("6505555555", "6505555555")); - assertTrue(mBuilder.equalNumbers("650 555 5555", "650 555 5555")); - // Formatting. - assertTrue(mBuilder.equalNumbers("6505555555", "650 555 5555")); - assertTrue(mBuilder.equalNumbers("6505555555", "(650) 555-5555")); - assertTrue(mBuilder.equalNumbers("650 555 5555", "(650) 555-5555")); - // Short codes. - assertTrue(mBuilder.equalNumbers("55555", "55555")); - assertTrue(mBuilder.equalNumbers("55555", "555 55")); - // Different numbers. - assertFalse(mBuilder.equalNumbers("6505555555", "650555555")); - assertFalse(mBuilder.equalNumbers("6505555555", "6505555551")); - assertFalse(mBuilder.equalNumbers("650 555 5555", "650 555 555")); - assertFalse(mBuilder.equalNumbers("650 555 5555", "650 555 5551")); - assertFalse(mBuilder.equalNumbers("55555", "5555")); - assertFalse(mBuilder.equalNumbers("55555", "55551")); - // SIP addresses. - assertTrue(mBuilder.equalNumbers("6505555555@host.com", "6505555555@host.com")); - assertTrue(mBuilder.equalNumbers("6505555555@host.com", "6505555555@HOST.COM")); - assertTrue(mBuilder.equalNumbers("user@host.com", "user@host.com")); - assertTrue(mBuilder.equalNumbers("user@host.com", "user@HOST.COM")); - assertFalse(mBuilder.equalNumbers("USER@host.com", "user@host.com")); - assertFalse(mBuilder.equalNumbers("user@host.com", "user@host1.com")); - // SIP address vs phone number. - assertFalse(mBuilder.equalNumbers("6505555555@host.com", "6505555555")); - assertFalse(mBuilder.equalNumbers("6505555555", "6505555555@host.com")); - assertFalse(mBuilder.equalNumbers("user@host.com", "6505555555")); - assertFalse(mBuilder.equalNumbers("6505555555", "user@host.com")); - // Nulls. - assertTrue(mBuilder.equalNumbers(null, null)); - assertFalse(mBuilder.equalNumbers(null, "6505555555")); - assertFalse(mBuilder.equalNumbers("6505555555", null)); - assertFalse(mBuilder.equalNumbers(null, "6505555555@host.com")); - assertFalse(mBuilder.equalNumbers("6505555555@host.com", null)); - } - - public void testCompareSipAddresses() { - // Identical. - assertTrue(mBuilder.compareSipAddresses("6505555555@host.com", "6505555555@host.com")); - assertTrue(mBuilder.compareSipAddresses("user@host.com", "user@host.com")); - // Host is case insensitive. - assertTrue(mBuilder.compareSipAddresses("6505555555@host.com", "6505555555@HOST.COM")); - assertTrue(mBuilder.compareSipAddresses("user@host.com", "user@HOST.COM")); - // Userinfo is case sensitive. - assertFalse(mBuilder.compareSipAddresses("USER@host.com", "user@host.com")); - // Different hosts. - assertFalse(mBuilder.compareSipAddresses("user@host.com", "user@host1.com")); - // Different users. - assertFalse(mBuilder.compareSipAddresses("user1@host.com", "user@host.com")); - // Nulls. - assertTrue(mBuilder.compareSipAddresses(null, null)); - assertFalse(mBuilder.compareSipAddresses(null, "6505555555@host.com")); - assertFalse(mBuilder.compareSipAddresses("6505555555@host.com", null)); - } - - /** Creates (or recreates) the cursor used to store the call log content for the tests. */ - private void createCursor() { - mCursor = new MatrixCursor(CallLogQuery._PROJECTION); - } - - /** Clears the content of the {@link FakeGroupCreator} used in the tests. */ - private void clearFakeGroupCreator() { - mFakeGroupCreator.groups.clear(); - } - - /** Asserts that calls of the given types are grouped together into a single group. */ - private void assertCallsAreGrouped(int... types) { - createCursor(); - clearFakeGroupCreator(); - addMultipleCallLogEntries(TEST_NUMBER1, types); - mBuilder.addGroups(mCursor); - assertEquals(1, mFakeGroupCreator.groups.size()); - assertGroupIs(0, types.length, mFakeGroupCreator.groups.get(0)); - - } - - /** Asserts that calls of the given types are not grouped together at all. */ - private void assertCallsAreNotGrouped(int... types) { - createCursor(); - clearFakeGroupCreator(); - addMultipleCallLogEntries(TEST_NUMBER1, types); - mBuilder.addGroups(mCursor); - assertEquals(types.length, mFakeGroupCreator.groups.size()); - } - - /** Asserts that voicemails are not grouped together with other types at all. */ - private void assertVoicemailsAreNotGrouped(int... types) { - createCursor(); - clearFakeGroupCreator(); - addMultipleCallLogEntries(TEST_NUMBER1, types); - mBuilder.addVoicemailGroups(mCursor); - assertEquals(types.length, mFakeGroupCreator.groups.size()); - } - - /** Adds a set of calls with the given types, all from the same number, in the old section. */ - private void addMultipleCallLogEntries(String number, int... types) { - for (int type : types) { - addCallLogEntry(number, type); - } - } - /** Adds a call log entry with the given number and type to the cursor. */ - private void addCallLogEntry(String number, int type) { - addCallLogEntryWithPostDialDigits(number, "", type); - } - - /** Adds a call log entry with the given number, post-dial digits, and type to the cursor. */ - private void addCallLogEntryWithPostDialDigits(String number, String postDialDigits, int type) { - mCursor.moveToNext(); - Object[] values = CallLogQueryTestUtils.createTestValues(); - values[CallLogQuery.ID] = mCursor.getPosition(); - values[CallLogQuery.NUMBER] = number; - values[CallLogQuery.CALL_TYPE] = type; - if (CompatUtils.isNCompatible()) { - values[CallLogQuery.POST_DIAL_DIGITS] = postDialDigits; - } - mCursor.addRow(values); - } - - /** Adds a call log entry with the given number, post-dial digits, and type to the cursor. */ - private void addCallLogEntryWithViaNumber(String number, String viaNumber, int type) { - mCursor.moveToNext(); - Object[] values = CallLogQueryTestUtils.createTestValues(); - values[CallLogQuery.ID] = mCursor.getPosition(); - values[CallLogQuery.NUMBER] = number; - values[CallLogQuery.CALL_TYPE] = type; - if (CompatUtils.isNCompatible()) { - values[CallLogQuery.VIA_NUMBER] = viaNumber; - } - mCursor.addRow(values); - } - - /** Adds a call log entry with a header to the cursor. */ - private void addCallLogHeader(int section) { - mCursor.moveToNext(); - Object[] values = CallLogQueryTestUtils.createTestValues(); - values[CallLogQuery.ID] = mCursor.getPosition(); - mCursor.addRow(values); - } - - /** Asserts that the group matches the given values. */ - private void assertGroupIs(int cursorPosition, int size, GroupSpec group) { - assertEquals(cursorPosition, group.cursorPosition); - assertEquals(size, group.size); - } - - /** Defines an added group. Used by the {@link FakeGroupCreator}. */ - private static class GroupSpec { - /** The starting position of the group. */ - public final int cursorPosition; - /** The number of elements in the group. */ - public final int size; - - public GroupSpec(int cursorPosition, int size) { - this.cursorPosition = cursorPosition; - this.size = size; - } - } - - /** Fake implementation of a GroupCreator which stores the created groups in a member field. */ - private static class FakeGroupCreator implements CallLogGroupBuilder.GroupCreator { - /** The list of created groups. */ - public final List<GroupSpec> groups = newArrayList(); - - @Override - public void addGroup(int cursorPosition, int size) { - groups.add(new GroupSpec(cursorPosition, size)); - } - - @Override - public void setDayGroup(long rowId, int dayGroup) { - //No-op - } - - @Override - public void clearDayGroups() { - //No-op - } - } -} diff --git a/tests/src/com/android/dialer/calllog/CallLogListItemHelperTest.java b/tests/src/com/android/dialer/calllog/CallLogListItemHelperTest.java deleted file mode 100644 index daba42857..000000000 --- a/tests/src/com/android/dialer/calllog/CallLogListItemHelperTest.java +++ /dev/null @@ -1,304 +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.dialer.calllog; - -import android.content.Context; -import android.content.res.Resources; -import android.provider.CallLog.Calls; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.view.View; - -import com.android.contacts.common.CallUtil; -import com.android.dialer.PhoneCallDetails; -import com.android.dialer.R; -import com.android.dialer.calllog.calllogcache.TestTelecomCallLogCache; -import com.android.dialer.util.AppCompatConstants; - -/** - * Unit tests for {@link CallLogListItemHelper}. - */ -@MediumTest -public class CallLogListItemHelperTest extends AndroidTestCase { - /** A test phone number for phone calls. */ - private static final String TEST_NUMBER = "14125555555"; - /** The formatted version of {@link #TEST_NUMBER}. */ - private static final String TEST_FORMATTED_NUMBER = "1-412-255-5555"; - /** A test date value for phone calls. */ - private static final long TEST_DATE = 1300000000; - /** A test duration value for phone calls. */ - private static final long TEST_DURATION = 62300; - /** A test voicemail number. */ - private static final String TEST_VOICEMAIL_NUMBER = "123"; - /** The country ISO name used in the tests. */ - private static final String TEST_COUNTRY_ISO = "US"; - /** The geocoded location used in the tests. */ - private static final String TEST_GEOCODE = "United States"; - - /** The object under test. */ - private CallLogListItemHelper mHelper; - - /** The views used in the tests. */ - private CallLogListItemViewHolder mViewHolder; - - private Context mContext; - private Resources mResources; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mContext = getContext(); - mResources = mContext.getResources(); - final TestTelecomCallLogCache phoneUtils = - new TestTelecomCallLogCache(mContext, TEST_VOICEMAIL_NUMBER, ""); - PhoneCallDetailsHelper phoneCallDetailsHelper = - new PhoneCallDetailsHelper(mContext, mResources, phoneUtils); - mHelper = new CallLogListItemHelper(phoneCallDetailsHelper, mResources, phoneUtils); - mViewHolder = CallLogListItemViewHolder.createForTest(mContext); - - } - - @Override - protected void tearDown() throws Exception { - mHelper = null; - mViewHolder = null; - super.tearDown(); - } - - public void testSetPhoneCallDetails() { - setPhoneCallDetailsWithNumber("12125551234", Calls.PRESENTATION_ALLOWED, - "1-212-555-1234"); - assertEquals(View.VISIBLE, mViewHolder.primaryActionButtonView.getVisibility()); - } - - public void testSetPhoneCallDetails_Unknown() { - setPhoneCallDetailsWithNumber("", Calls.PRESENTATION_UNKNOWN, ""); - assertNoCallIntent(); - } - - public void testSetPhoneCallDetails_Private() { - setPhoneCallDetailsWithNumber("", Calls.PRESENTATION_RESTRICTED, ""); - assertNoCallIntent(); - } - - public void testSetPhoneCallDetails_Payphone() { - setPhoneCallDetailsWithNumber("", Calls.PRESENTATION_PAYPHONE, ""); - assertNoCallIntent(); - } - - public void testSetPhoneCallDetails_VoicemailNumber() { - setPhoneCallDetailsWithNumber(TEST_VOICEMAIL_NUMBER, - Calls.PRESENTATION_ALLOWED, TEST_VOICEMAIL_NUMBER); - assertEquals(View.VISIBLE, mViewHolder.voicemailPlaybackView.getVisibility()); - } - - public void testSetPhoneCallDetails_ReadVoicemail() { - PhoneCallDetails details = - getPhoneCallDetailsWithTypes(AppCompatConstants.CALLS_VOICEMAIL_TYPE); - mHelper.setPhoneCallDetails(mViewHolder, details); - assertEquals(View.VISIBLE, mViewHolder.voicemailPlaybackView.getVisibility()); - } - - public void testSetPhoneCallDetails_UnreadVoicemail() { - PhoneCallDetails details = - getPhoneCallDetailsWithTypes(AppCompatConstants.CALLS_VOICEMAIL_TYPE); - mHelper.setPhoneCallDetails(mViewHolder, details); - assertEquals(View.VISIBLE, mViewHolder.voicemailPlaybackView.getVisibility()); - } - - public void testSetPhoneCallDetails_VoicemailFromUnknown() { - setPhoneCallDetailsWithNumberAndType("", Calls.PRESENTATION_UNKNOWN, - "", AppCompatConstants.CALLS_VOICEMAIL_TYPE); - assertEquals(View.VISIBLE, mViewHolder.voicemailPlaybackView.getVisibility()); - } - - /** - * Test getCallDescriptionID method used to get the accessibility description for calls. - */ - public void testGetCallDescriptionID_Answered() { - int[] callTypes = new int[] {AppCompatConstants.CALLS_INCOMING_TYPE}; - assertEquals(R.string.description_incoming_answered_call, - mHelper.getCallDescriptionStringID(callTypes, true)); - } - - /** - * Test getCallDescriptionID method used to get the accessibility description for calls. - */ - public void testGetCallDescriptionID_Missed() { - int[] callTypes = new int[] {AppCompatConstants.CALLS_MISSED_TYPE}; - assertEquals(R.string.description_incoming_missed_call, - mHelper.getCallDescriptionStringID(callTypes, true)); - } - - /** - * Test getCallDescriptionID method used to get the accessibility description for calls. - * Test case where an outgoing call is made to a known number and there is a history of - * only a single call for this caller. - */ - public void testGetCallDescriptionID_OutgoingSingle() { - int[] callTypes = new int[] {AppCompatConstants.CALLS_OUTGOING_TYPE}; - assertEquals(R.string.description_outgoing_call, - mHelper.getCallDescriptionStringID(callTypes, true)); - } - - /** - * Test getCallDescriptionID method used to get the accessibility description for calls. - * Test case where an outgoing call is made to a known number and there is a history of - * many calls for this caller. - */ - public void testGetCallDescriptionID_OutgoingMultiple() { - int[] callTypes = new int[] { - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE - }; - assertEquals(R.string.description_outgoing_call, - mHelper.getCallDescriptionStringID(callTypes, true)); - } - - /** - * Test getCallDescription method used to get the accessibility description for calls. - * For read voicemail calls, we should have "Voicemail" in the description. - */ - public void testGetCallDescriptionID_Voicemail() { - int[] callTypes = new int[] {AppCompatConstants.CALLS_VOICEMAIL_TYPE}; - assertEquals(R.string.description_read_voicemail, - mHelper.getCallDescriptionStringID(callTypes, true)); - } - - /** - * Test getCallDescription method used to get the accessibility description for calls. - * For unread voicemail calls, we should have "Unread voicemail" in the description. - */ - public void testGetCallDescriptionID_UnreadVoicemail() { - int[] callTypes = new int[] {AppCompatConstants.CALLS_VOICEMAIL_TYPE}; - assertEquals(R.string.description_unread_voicemail, - mHelper.getCallDescriptionStringID(callTypes, false)); - } - - /** - * Test getCallDescription method used to get the accessibility description for calls. - * Test that the "X calls" message is not present if there is only a single call. - */ - public void testGetCallDescription_NumCallsSingle() { - PhoneCallDetails details = - getPhoneCallDetailsWithTypes(AppCompatConstants.CALLS_VOICEMAIL_TYPE); - CharSequence description = mHelper.getCallDescription(details); - - // Rather than hard coding the "X calls" string message, we'll generate it with an empty - // number of calls, and trim the resulting string. This gets us just the word "calls", - // and ensures any trivial changes to that string resource won't unnecessarily break - // the unit test. - assertFalse(description.toString() - .contains(this.mResources.getString(R.string.description_num_calls, "").trim())); - } - - /** - * Test getCallDescription method used to get the accessibility description for calls. - * Test that the "X calls" message is present if there are many calls. - */ - public void testGetCallDescription_NumCallsMultiple() { - PhoneCallDetails details = getPhoneCallDetailsWithTypes( - AppCompatConstants.CALLS_VOICEMAIL_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - CharSequence description = mHelper.getCallDescription(details); - assertTrue(description.toString() - .contains(this.mResources.getString(R.string.description_num_calls, 2))); - } - - /** - * Test getCallDescription method used to get the accessibility description for calls. - * Test that the "Video call." message is present if the call had video capability. - */ - public void testGetCallDescription_Video() { - PhoneCallDetails details = getPhoneCallDetailsWithTypes( - AppCompatConstants.CALLS_INCOMING_TYPE, AppCompatConstants.CALLS_INCOMING_TYPE); - details.features = Calls.FEATURES_VIDEO; - - CharSequence description = mHelper.getCallDescription(details); - final boolean isVideoEnabled = CallUtil.isVideoEnabled(getContext()); - assertTrue(description.toString() - .contains(this.mResources.getString( - isVideoEnabled - ? R.string.description_video_call - : R.string.description_num_calls, - 2))); - } - - /** Asserts that the primary action view does not have a call intent. */ - private void assertNoCallIntent() { - Object intentProvider = mViewHolder.primaryActionView.getTag(); - // The intent provider should be null as there is no ability to make a call. - assertNull(intentProvider); - } - - /** Sets the details of a phone call using the specified phone number. */ - private void setPhoneCallDetailsWithNumber(String number, - int presentation, String formattedNumber) { - setPhoneCallDetailsWithNumberTypeAndPostDialDigits(number, "", presentation, - formattedNumber, Calls.INCOMING_TYPE); - } - - /** Sets the details of a phone call using the specified phone number. */ - private void setPhoneCallDetailsWithNumberAndType(String number, - int presentation, String formattedNumber, int callType) { - setPhoneCallDetailsWithNumberTypeAndPostDialDigits(number, "", presentation, - formattedNumber, callType); - } - - /** Sets the details of a phone call using the specified phone number and post-dial digits. */ - private void setPhoneCallDetailsWithNumberTypeAndPostDialDigits(String number, - String postDialDigits, int presentation, String formattedNumber, int callType) { - PhoneCallDetails details = getPhoneCallDetails( - number, postDialDigits, presentation, formattedNumber); - details.callTypes = new int[] {callType}; - mHelper.setPhoneCallDetails(mViewHolder, details); - } - - private PhoneCallDetails getPhoneCallDetails( - String number, String postDialDigits, int presentation, String formattedNumber) { - PhoneCallDetails details = new PhoneCallDetails( - mContext, - number, - presentation, - formattedNumber, - postDialDigits, - false /* isVoicemail */); - setDefaultDetails(details); - return details; - } - - /** Returns the details of a phone call using the specified call type. */ - private PhoneCallDetails getPhoneCallDetailsWithTypes(int... types) { - PhoneCallDetails details = new PhoneCallDetails( - mContext, - TEST_NUMBER, - Calls.PRESENTATION_ALLOWED, - TEST_FORMATTED_NUMBER, - "", - false /* isVoicemail */); - setDefaultDetails(details); - details.callTypes = types; - return details; - } - - private void setDefaultDetails(PhoneCallDetails details) { - details.callTypes = new int[] {Calls.INCOMING_TYPE}; - details.countryIso = TEST_COUNTRY_ISO; - details.date = TEST_DATE; - details.duration = TEST_DURATION; - details.geocode = TEST_GEOCODE; - } -} diff --git a/tests/src/com/android/dialer/calllog/CallLogNotificationsHelperTest.java b/tests/src/com/android/dialer/calllog/CallLogNotificationsHelperTest.java deleted file mode 100644 index b5950d8b8..000000000 --- a/tests/src/com/android/dialer/calllog/CallLogNotificationsHelperTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.calllog; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import android.provider.CallLog; -import android.test.AndroidTestCase; - -import com.android.dialer.R; - -/** - * Unit tests for {@link CallLogNotificationsHelper}. - */ -public class CallLogNotificationsHelperTest extends AndroidTestCase { - private static final String TEST_COUNTRY_ISO = "US"; - private static final String TEST_VALID_NUMBER = "14125555555"; - private static final String TEST_INVALID_NUMBER = "asdna128937123"; - private static final String TEST_FORMATTED_NUMBER = "1 412-555-5555"; - private static final String TEST_E164_NUMBER = "+14125555555"; - - private final ContactInfoHelper mContactInfoHelper = mock(ContactInfoHelper.class); - - private CallLogNotificationsHelper mCallLogNotificationsHelper; - - @Override - public void setUp() throws Exception { - super.setUp(); - mCallLogNotificationsHelper = new CallLogNotificationsHelper(getContext(), - null, null, mContactInfoHelper, TEST_COUNTRY_ISO); - } - - public void testGetContactInfo_ValidNumberValidPresentationValidIso() { - ContactInfo contactInfo = getContactInfo( - TEST_VALID_NUMBER, CallLog.Calls.PRESENTATION_UNKNOWN, TEST_COUNTRY_ISO); - assertEquals(TEST_VALID_NUMBER, contactInfo.number); - assertEquals(mContext.getResources().getString(R.string.unknown), contactInfo.name); - assertEquals(TEST_E164_NUMBER, contactInfo.normalizedNumber); - } - - public void testGetContactInfo_ValidNumberInvalidPresentationValidIso() { - ContactInfo contactInfo = getContactInfo(TEST_VALID_NUMBER, -1, TEST_COUNTRY_ISO); - assertEquals(TEST_VALID_NUMBER, contactInfo.number); - assertEquals(TEST_FORMATTED_NUMBER, contactInfo.name); - assertEquals(TEST_E164_NUMBER, contactInfo.normalizedNumber); - } - - public void testGetContactInfo_ValidNumberValidPresentationNullIso() { - ContactInfo contactInfo = getContactInfo( - TEST_VALID_NUMBER, CallLog.Calls.PRESENTATION_UNKNOWN, null); - assertEquals(TEST_VALID_NUMBER, contactInfo.number); - assertEquals(mContext.getResources().getString(R.string.unknown), contactInfo.name); - assertEquals(TEST_E164_NUMBER, contactInfo.normalizedNumber); - } - - public void testGetContactInfo_ValidNumberInvalidPresentationNullIso() { - ContactInfo contactInfo = getContactInfo( - TEST_VALID_NUMBER, -1, null); - assertEquals(TEST_VALID_NUMBER, contactInfo.number); - assertEquals(TEST_FORMATTED_NUMBER, contactInfo.name); - assertEquals(TEST_E164_NUMBER, contactInfo.normalizedNumber); - } - - public void testGetContactInfo_NullNumberValidPresentationValidIso() { - ContactInfo contactInfo = getContactInfo( - null, CallLog.Calls.PRESENTATION_UNKNOWN, TEST_COUNTRY_ISO); - assertEquals("", contactInfo.number); - assertEquals(mContext.getResources().getString(R.string.unknown), contactInfo.name); - assertNull(contactInfo.normalizedNumber); - } - - public void testGetContactInfo_NullNumberInvalidPresentationValidIso() { - ContactInfo contactInfo = getContactInfo(null, -1, TEST_COUNTRY_ISO); - assertEquals("", contactInfo.number); - assertEquals(mContext.getResources().getString(R.string.unknown), contactInfo.name); - assertNull(contactInfo.normalizedNumber); - } - - public void testGetContactInfo_NullNumberValidPresentationNullIso() { - ContactInfo contactInfo = getContactInfo(null, CallLog.Calls.PRESENTATION_RESTRICTED, null); - assertEquals("", contactInfo.number); - assertEquals(mContext.getResources().getString(R.string.private_num), contactInfo.name); - assertNull(contactInfo.normalizedNumber); - } - - public void testGetContactInfo_NullNumberInValidPresentationNullIso() { - ContactInfo contactInfo = getContactInfo(null, -1, null); - assertEquals("", contactInfo.number); - assertEquals(mContext.getResources().getString(R.string.unknown), contactInfo.name); - assertNull(contactInfo.normalizedNumber); - } - - public void testGetContactInfo_InvalidNumberInValidPresentationNullIso() { - ContactInfo contactInfo = getContactInfo(TEST_INVALID_NUMBER, -1, null); - assertEquals(TEST_INVALID_NUMBER, contactInfo.name); - assertEquals(TEST_INVALID_NUMBER, contactInfo.formattedNumber); - assertEquals(null, contactInfo.normalizedNumber); - } - - public void testGetContactInfo_NonNullCachedLookup() { - when(mContactInfoHelper.lookupNumber(anyString(), anyString())).thenReturn(null); - ContactInfo contactInfo = getContactInfo(TEST_VALID_NUMBER, -1, TEST_COUNTRY_ISO); - assertEquals(TEST_VALID_NUMBER, contactInfo.number); - assertEquals(TEST_FORMATTED_NUMBER, contactInfo.formattedNumber); - } - - public void testGetContactInfo_NullCachedLookup() { - ContactInfo cachedContactInfo = new ContactInfo(); - cachedContactInfo.number = TEST_VALID_NUMBER; - cachedContactInfo.formattedNumber = TEST_FORMATTED_NUMBER; - when(mContactInfoHelper.lookupNumber(anyString(), anyString())) - .thenReturn(cachedContactInfo); - ContactInfo contactInfo = getContactInfo(TEST_VALID_NUMBER, -1, TEST_COUNTRY_ISO); - assertEquals(TEST_VALID_NUMBER, contactInfo.number); - assertEquals(TEST_FORMATTED_NUMBER, contactInfo.name); - } - - private ContactInfo getContactInfo(String number, int presentation, String countryIso) { - return mCallLogNotificationsHelper.getContactInfo(number, presentation, countryIso); - } -} diff --git a/tests/src/com/android/dialer/calllog/CallLogQueryTestUtils.java b/tests/src/com/android/dialer/calllog/CallLogQueryTestUtils.java deleted file mode 100644 index c2cfedbac..000000000 --- a/tests/src/com/android/dialer/calllog/CallLogQueryTestUtils.java +++ /dev/null @@ -1,46 +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.dialer.calllog; - -import static junit.framework.Assert.assertEquals; - -import android.provider.CallLog.Calls; - -import com.android.contacts.common.compat.CompatUtils; - -/** - * Helper class to create test values for {@link CallLogQuery}. - */ -public class CallLogQueryTestUtils { - public static Object[] createTestValues() { - Object[] values; - if (CompatUtils.isNCompatible()) { - values = new Object[]{ - 0L, "", 0L, 0L, Calls.INCOMING_TYPE, "", "", "", null, 0, null, null, null, - null, 0L, null, 0, Calls.PRESENTATION_ALLOWED, null, null, 0, null, null, - null, "", "" - }; - } else { - values = new Object[]{ - 0L, "", 0L, 0L, Calls.INCOMING_TYPE, "", "", "", null, 0, null, null, null, - null, 0L, null, 0, Calls.PRESENTATION_ALLOWED, null, null, 0, null, null, null - }; - } - assertEquals(CallLogQuery._PROJECTION.length, values.length); - return values; - } -} diff --git a/tests/src/com/android/dialer/calllog/ContactInfoHelperTest.java b/tests/src/com/android/dialer/calllog/ContactInfoHelperTest.java deleted file mode 100644 index df385f425..000000000 --- a/tests/src/com/android/dialer/calllog/ContactInfoHelperTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2015 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.dialer.calllog; - -import android.net.Uri; -import android.provider.ContactsContract; -import android.provider.ContactsContract.Contacts; -import android.provider.ContactsContract.PhoneLookup; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; - -import com.android.contacts.common.ContactsUtils; -import com.android.contacts.common.test.mocks.ContactsMockContext; -import com.android.contacts.common.test.mocks.MockContentProvider.Query; - -import junit.framework.Assert; - -@MediumTest -public class ContactInfoHelperTest extends AndroidTestCase { - - private static final String TEST_COUNTRY_ISO = "US"; - private static final String TEST_DISPLAY_NAME = "Display Name"; - private static final String TEST_DISPLAY_NAME_ALTERNATIVE = "Name, Display"; - private static final String[] TEST_DISPLAY_NAME_ALTERNATIVE_ROW = new String[]{ - TEST_DISPLAY_NAME_ALTERNATIVE}; - private static final String TEST_LOOKUP_KEY = "lookupKey"; - private static final String[] TEST_LOOKUP_ROW = new String[]{null, TEST_DISPLAY_NAME, - null, null, null, null, null, TEST_LOOKUP_KEY, null}; - - private Uri displayNameAlternativeUri; - private ContactsMockContext mContext; - private ContactInfo mContactInfo; - private ContactInfoHelper mContactInfoHelper; - - @Override - public void setUp() throws Exception { - super.setUp(); - - displayNameAlternativeUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, - TEST_LOOKUP_KEY); - mContext = new ContactsMockContext(getContext()); - mContactInfo = new ContactInfo(); - mContactInfo.name = TEST_DISPLAY_NAME; - mContactInfo.nameAlternative = TEST_DISPLAY_NAME_ALTERNATIVE; - mContactInfoHelper = new ContactInfoHelper(mContext, TEST_COUNTRY_ISO); - } - - public void testLookupContactFromUri_NullUri() { - Assert.assertNull(mContactInfoHelper.lookupContactFromUri(null, false)); - } - - public void testLookupContactFromUri_NoResults() { - setUpQueryExpectations(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, - PhoneQuery.getPhoneLookupProjection(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI)); - - Assert.assertEquals(ContactInfo.EMPTY, mContactInfoHelper.lookupContactFromUri( - PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, false)); - mContext.verify(); - } - - public void testLookupContactFromUri_NoDisplayNameAlternative() { - setUpQueryExpectations(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, - PhoneQuery.getPhoneLookupProjection(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI), - TEST_LOOKUP_ROW); - setUpQueryExpectations(displayNameAlternativeUri, - PhoneQuery.DISPLAY_NAME_ALTERNATIVE_PROJECTION); - - ContactInfo contactInfo = mContactInfoHelper.lookupContactFromUri( - PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, false); - Assert.assertEquals(TEST_DISPLAY_NAME, contactInfo.name); - Assert.assertNull(contactInfo.nameAlternative); - mContext.verify(); - } - - public void testLookupContactFromUri_HasDisplayNameAlternative() { - setUpQueryExpectations(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, - PhoneQuery.getPhoneLookupProjection(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI), - TEST_LOOKUP_ROW); - setUpQueryExpectations(displayNameAlternativeUri, - PhoneQuery.DISPLAY_NAME_ALTERNATIVE_PROJECTION, TEST_DISPLAY_NAME_ALTERNATIVE_ROW); - - ContactInfo contactInfo = mContactInfoHelper.lookupContactFromUri( - PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, false); - Assert.assertEquals(TEST_DISPLAY_NAME, contactInfo.name); - Assert.assertEquals(TEST_DISPLAY_NAME_ALTERNATIVE, contactInfo.nameAlternative); - mContext.verify(); - } - - public void testLookupDisplayNameAlternative_NullLookup() { - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, null, - ContactsUtils.USER_TYPE_CURRENT, null)); - } - - public void testLookupDisplayNameAlternative_NoResults() { - setUpQueryExpectations(displayNameAlternativeUri, - PhoneQuery.DISPLAY_NAME_ALTERNATIVE_PROJECTION); - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, - TEST_LOOKUP_KEY, ContactsUtils.USER_TYPE_CURRENT, null)); - mContext.verify(); - } - - public void testLookupDisplayNameAlternative_HasDisplayNameAlternative() { - setUpQueryExpectations(displayNameAlternativeUri, - PhoneQuery.DISPLAY_NAME_ALTERNATIVE_PROJECTION, TEST_DISPLAY_NAME_ALTERNATIVE_ROW); - Assert.assertEquals(TEST_DISPLAY_NAME_ALTERNATIVE, - mContactInfoHelper.lookUpDisplayNameAlternative(mContext, TEST_LOOKUP_KEY - , ContactsUtils.USER_TYPE_CURRENT, null)); - mContext.verify(); - } - - public void testLookupDisplayNameAlternative_EnterpriseLocalDirectory() { - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, TEST_LOOKUP_KEY, - ContactsUtils.USER_TYPE_WORK, ContactsContract.Directory.ENTERPRISE_DEFAULT)); - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, TEST_LOOKUP_KEY, - ContactsUtils.USER_TYPE_CURRENT, ContactsContract.Directory.ENTERPRISE_DEFAULT)); - } - - public void testLookupDisplayNameAlternative_EnterpriseRemoteDirectory() { - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, TEST_LOOKUP_KEY, - ContactsUtils.USER_TYPE_WORK, - ContactsContract.Directory.ENTERPRISE_DEFAULT + 10)); - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, TEST_LOOKUP_KEY, - ContactsUtils.USER_TYPE_CURRENT, - ContactsContract.Directory.ENTERPRISE_DEFAULT + 10)); - } - - public void testLookupDisplayNameAlternative_PersonalRemoteDirectory() { - Assert.assertNull(mContactInfoHelper.lookUpDisplayNameAlternative(mContext, null, - ContactsUtils.USER_TYPE_CURRENT, - ContactsContract.Directory.DEFAULT + 10)); - } - - /* - * Sets up query expectations to return the given row for all queries for the given - * uri and projection. If row is null, an empty cursor is returned for query calls - */ - private void setUpQueryExpectations(Uri uri, String[] projection, String...row) { - Query query = mContext.getContactsProvider().expectQuery(uri) - .withProjection(projection).withAnySelection().withAnySortOrder(); - if (row == null || row.length == 0) { - query.returnEmptyCursor(); - return; - } - query.returnRow(row); - } -} diff --git a/tests/src/com/android/dialer/calllog/GroupingListAdapterTests.java b/tests/src/com/android/dialer/calllog/GroupingListAdapterTests.java deleted file mode 100644 index 4d8cb9cc0..000000000 --- a/tests/src/com/android/dialer/calllog/GroupingListAdapterTests.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2015 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.dialer.calllog; - -import android.content.Context; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.support.v7.widget.RecyclerView; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.text.TextUtils; -import android.view.View; -import android.view.ViewGroup; - -/** - * Tests for {@link GroupingListAdapter}. - * - * Running all tests: - * - * adb shell am instrument -e class com.android.dialer.calllog.GroupingListAdapterTests \ - * -w com.android.dialer.tests/android.test.InstrumentationTestRunner - */ -@MediumTest -public class GroupingListAdapterTests extends AndroidTestCase { - - static private final String[] PROJECTION = new String[] { - "_id", - "group", - }; - - private static final int GROUPING_COLUMN_INDEX = 1; - - private MatrixCursor mCursor; - private long mNextId; - - private GroupingListAdapter mAdapter = new GroupingListAdapter(null) { - - @Override - protected void addGroups(Cursor cursor) { - int count = cursor.getCount(); - int groupItemCount = 1; - cursor.moveToFirst(); - String currentValue = cursor.getString(GROUPING_COLUMN_INDEX); - for (int i = 1; i < count; i++) { - cursor.moveToNext(); - String value = cursor.getString(GROUPING_COLUMN_INDEX); - if (TextUtils.equals(value, currentValue)) { - groupItemCount++; - } else { - addGroup(i - groupItemCount, groupItemCount); - groupItemCount = 1; - currentValue = value; - } - } - addGroup(count - groupItemCount, groupItemCount); - } - - @Override - protected void addVoicemailGroups(Cursor c) { - // Do nothing. - } - - @Override - public void onContentChanged() { - // Do nothing. - } - - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int position) { - return null; - } - - @Override - public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { - // Do nothing. - } - }; - - private void buildCursor(String... numbers) { - mCursor = new MatrixCursor(PROJECTION); - mNextId = 1; - for (String number : numbers) { - mCursor.addRow(new Object[]{mNextId, number}); - mNextId++; - } - } - - public void testGroupingWithoutGroups() { - buildCursor("1", "2", "3"); - mAdapter.changeCursor(mCursor); - - assertEquals(3, mAdapter.getItemCount()); - assertMetadata(0, 1, "1"); - assertMetadata(1, 1, "2"); - assertMetadata(2, 1, "3"); - } - - public void testGroupingWithGroupAtTheBeginning() { - buildCursor("1", "1", "2"); - mAdapter.changeCursor(mCursor); - - assertEquals(2, mAdapter.getItemCount()); - assertMetadata(0, 2, "1"); - assertMetadata(1, 1, "2"); - } - - public void testGroupingWithGroupInTheMiddle() { - buildCursor("1", "2", "2", "2", "3"); - mAdapter.changeCursor(mCursor); - - assertEquals(3, mAdapter.getItemCount()); - assertMetadata(0, 1, "1"); - assertMetadata(1, 3, "2"); - assertMetadata(2, 1, "3"); - } - - public void testGroupingWithGroupAtTheEnd() { - buildCursor("1", "2", "3", "3", "3"); - mAdapter.changeCursor(mCursor); - - assertEquals(3, mAdapter.getItemCount()); - assertMetadata(0, 1, "1"); - assertMetadata(1, 1, "2"); - assertMetadata(2, 3, "3"); - } - - public void testGroupingWithMultipleGroups() { - buildCursor("1", "2", "2", "3", "4", "4", "5", "5", "6"); - mAdapter.changeCursor(mCursor); - - assertEquals(6, mAdapter.getItemCount()); - assertMetadata(0, 1, "1"); - assertMetadata(1, 2, "2"); - assertMetadata(2, 1, "3"); - assertMetadata(3, 2, "4"); - assertMetadata(4, 2, "5"); - assertMetadata(5, 1, "6"); - } - - public void testGroupDescriptorArrayGrowth() { - String[] numbers = new String[500]; - for (int i = 0; i < numbers.length; i++) { - - // Make groups of 2 - numbers[i] = String.valueOf((i / 2) * 2); - } - - buildCursor(numbers); - mAdapter.changeCursor(mCursor); - - assertEquals(250, mAdapter.getItemCount()); - } - - private void assertMetadata(int listPosition, int groupSize, String objectValue) { - assertEquals(groupSize, mAdapter.getGroupSize(listPosition)); - MatrixCursor cursor = (MatrixCursor) mAdapter.getItem(listPosition); - assertEquals(objectValue, cursor.getString(GROUPING_COLUMN_INDEX)); - } -} diff --git a/tests/src/com/android/dialer/calllog/PhoneAccountUtilsTest.java b/tests/src/com/android/dialer/calllog/PhoneAccountUtilsTest.java deleted file mode 100644 index f2d0856bd..000000000 --- a/tests/src/com/android/dialer/calllog/PhoneAccountUtilsTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.calllog; - -import android.content.ComponentName; -import android.telecom.PhoneAccountHandle; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -public class PhoneAccountUtilsTest extends AndroidTestCase { - - private static final String VALID_COMPONENT_NAME = - "com.android.dialer.calllog/com.android.dialer.calllog.PhoneAccountUtilsTest"; - private static final String VALID_ACCOUNT_ID = "Account1"; - - @SmallTest - public void testGetAccount_CorrectParams() { - ComponentName correctComponentName = - ComponentName.unflattenFromString(VALID_COMPONENT_NAME); - PhoneAccountHandle correctPhoneAccountHandle = new PhoneAccountHandle(correctComponentName, - VALID_ACCOUNT_ID); - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(VALID_COMPONENT_NAME, VALID_ACCOUNT_ID); - - assertTrue(correctPhoneAccountHandle.equals(testPhoneAccountHandle)); - } - - @SmallTest - public void testGetAccount_ComponentStringNoClassName() { - final String malformedComponentName = "com.android.dialer.calllog/"; - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(malformedComponentName, VALID_ACCOUNT_ID); - - assertNull(testPhoneAccountHandle); - } - - @SmallTest - public void testGetAccount_ComponentStringInvalid() { - final String malformedComponentName = "com.android.dialer.calllog"; - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(malformedComponentName, VALID_ACCOUNT_ID); - - assertNull(testPhoneAccountHandle); - } - - @SmallTest - public void testGetAccount_NoComponentName() { - final String blankComponentName = ""; - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(blankComponentName, VALID_ACCOUNT_ID); - - assertNull(testPhoneAccountHandle); - } - - @SmallTest - public void testGetAccount_NoAccountId() { - final String blankAccountId = ""; - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(VALID_COMPONENT_NAME, blankAccountId); - - assertNull(testPhoneAccountHandle); - } - - @SmallTest - public void testGetAccount_NoAccountIdOrComponentName() { - final String blankComponentName = ""; - final String blankAccountId = ""; - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(VALID_COMPONENT_NAME, blankAccountId); - - assertNull(testPhoneAccountHandle); - } - - @SmallTest - public void testGetAccount_NullAccountIdAndComponentName() { - final String blankComponentName = null; - final String blankAccountId = null; - - PhoneAccountHandle testPhoneAccountHandle = - PhoneAccountUtils.getAccount(VALID_COMPONENT_NAME, blankAccountId); - - assertNull(testPhoneAccountHandle); - } -} diff --git a/tests/src/com/android/dialer/calllog/PhoneCallDetailsHelperTest.java b/tests/src/com/android/dialer/calllog/PhoneCallDetailsHelperTest.java deleted file mode 100644 index 0c57fde3c..000000000 --- a/tests/src/com/android/dialer/calllog/PhoneCallDetailsHelperTest.java +++ /dev/null @@ -1,581 +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.dialer.calllog; - -import android.content.ComponentName; -import android.content.Context; -import android.content.res.Resources; -import android.provider.CallLog.Calls; -import android.telecom.PhoneAccountHandle; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.MediumTest; -import android.text.Html; -import android.text.Spanned; -import android.view.View; -import android.widget.TextView; - -import com.android.dialer.PhoneCallDetails; -import com.android.dialer.R; -import com.android.dialer.calllog.calllogcache.TestTelecomCallLogCache; -import com.android.dialer.util.AppCompatConstants; -import com.android.dialer.util.LocaleTestUtils; - -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Unit tests for {@link PhoneCallDetailsHelper}. - */ -@MediumTest -public class PhoneCallDetailsHelperTest extends AndroidTestCase { - /** The number to be used to access the voicemail. */ - private static final String TEST_VOICEMAIL_NUMBER = "125"; - /** The date of the call log entry. */ - private static final long TEST_DATE = - new GregorianCalendar(2011, 5, 3, 13, 0, 0).getTimeInMillis(); - private static final long INJECTED_CURRENT_DATE = - new GregorianCalendar(2011, 5, 4, 13, 0, 0).getTimeInMillis(); - /** A test duration value for phone calls. */ - private static final long TEST_DURATION = 62300; - /** The number of the caller/callee in the log entry. */ - private static final String TEST_NUMBER = "14125555555"; - /** The formatted version of {@link #TEST_NUMBER}. */ - private static final String TEST_FORMATTED_NUMBER = "1-412-255-5555"; - /** The country ISO name used in the tests. */ - private static final String TEST_COUNTRY_ISO = "US"; - /** The geocoded location used in the tests. */ - private static final String TEST_GEOCODE = "United States"; - /** Empty geocode label */ - private static final String EMPTY_GEOCODE = ""; - /** Empty post-dial digits label */ - private static final String EMPTY_POSTDIAL = ""; - /** The number that the call was received via */ - private static final String TEST_VIA_NUMBER = "+16505551234"; - /** The Phone Account name that the Call was received on */ - private static final String TEST_ACCOUNT_LABEL = "T-Stationary"; - - /** The object under test. */ - private PhoneCallDetailsHelper mHelper; - /** The views to fill. */ - private PhoneCallDetailsViews mViews; - private TextView mNameView; - private LocaleTestUtils mLocaleTestUtils; - private TestTelecomCallLogCache mPhoneUtils; - - private Context mContext; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mContext = getContext(); - Resources resources = mContext.getResources(); - mPhoneUtils = new TestTelecomCallLogCache(mContext, TEST_VOICEMAIL_NUMBER, - TEST_ACCOUNT_LABEL); - mHelper = new PhoneCallDetailsHelper(mContext, resources, mPhoneUtils); - mHelper.setCurrentTimeForTest(INJECTED_CURRENT_DATE); - mViews = PhoneCallDetailsViews.createForTest(mContext); - mNameView = new TextView(mContext); - mLocaleTestUtils = new LocaleTestUtils(mContext); - mLocaleTestUtils.setLocale(Locale.US); - } - - @Override - protected void tearDown() throws Exception { - mLocaleTestUtils.restoreLocale(); - mNameView = null; - mViews = null; - mHelper = null; - super.tearDown(); - } - - public void testSetPhoneCallDetails_Unknown() { - setPhoneCallDetailsWithNumber("", Calls.PRESENTATION_UNKNOWN, ""); - assertNameEqualsResource(R.string.unknown); - } - - public void testSetPhoneCallDetails_Private() { - setPhoneCallDetailsWithNumber("", Calls.PRESENTATION_RESTRICTED, ""); - assertNameEqualsResource(R.string.private_num); - } - - public void testSetPhoneCallDetails_Payphone() { - setPhoneCallDetailsWithNumber("", Calls.PRESENTATION_PAYPHONE, ""); - assertNameEqualsResource(R.string.payphone); - } - - public void testSetPhoneCallDetails_Voicemail() { - setPhoneCallDetailsWithNumber(TEST_VOICEMAIL_NUMBER, - Calls.PRESENTATION_ALLOWED, TEST_VOICEMAIL_NUMBER); - assertNameEqualsResource(R.string.voicemail); - } - - public void testSetPhoneCallDetails_ViaNumber() { - setPhoneCallDetailsWithViaNumber(TEST_VIA_NUMBER); - assertViaNumberEquals(TEST_VIA_NUMBER); - } - - public void testSetPhoneCallDetails_NoViaNumber() { - setDefaultPhoneCallDetailsNoViaNumber(); - assertCallAccountInvisible(); - } - - public void testSetPhoneCallDetails_AccountLabel() { - setPhoneCallDetailsWithAccountHandle(); - assertAccountLabelEquals(TEST_ACCOUNT_LABEL); - } - - public void testSetPhoneCallDetails_AccountHandleViaNumber() { - setPhoneCallDetailsWithAccountLabelViaNumber(TEST_VIA_NUMBER); - assertAccountLabelEquals(TEST_VIA_NUMBER, TEST_ACCOUNT_LABEL); - } - - // Voicemail date string has 3 different formats depending on how long ago the call was placed - public void testSetVoicemailPhoneCallDetails_Today() { - setVoicemailPhoneCallDetailsWithDate(System.currentTimeMillis()); - assertLocationAndDateContains("Today at"); - } - - public void testSetVoicemailPhoneCallDetails_WithinCurrentYear() { - mHelper.setCurrentTimeForTest(INJECTED_CURRENT_DATE); - String formattedTestDate = "Jun 3 at 1:00 PM"; - setVoicemailPhoneCallDetailsWithDate(TEST_DATE); - assertLocationAndDateContains(formattedTestDate); - } - - public void testSetVoicemailPhoneCallDetails_OutsideCurrentYear() { - mHelper.setCurrentTimeForTest(INJECTED_CURRENT_DATE); - long testDate = new GregorianCalendar(2009, 5, 3, 13, 0, 0).getTimeInMillis(); - String formattedTestDate = "Jun 3, 2009 at 1:00 PM"; - setVoicemailPhoneCallDetailsWithDate(testDate); - assertLocationAndDateContains(formattedTestDate); - } - - public void testVoicemailLocationNotShownWithDate() { - setVoicemailPhoneCallDetailsWithDate(TEST_DATE); - assertLocationAndDateExactEquals("Jun 3 at 1:00 PM • 99:20"); - } - - public void testVoicemailDuration() { - setVoicemailPhoneCallDetailsWithDuration(100); - assertDurationExactEquals("01:40"); - } - - public void testVoicemailDuration_Capped() { - setVoicemailPhoneCallDetailsWithDuration(TEST_DURATION); - assertDurationExactEquals("99:20"); - } - - public void testVoicemailDuration_Zero() { - setVoicemailPhoneCallDetailsWithDuration(0); - assertLocationAndDateExactEquals("Jun 3 at 1:00 PM"); - } - - public void testVoicemailDuration_EvenMinute() { - setVoicemailPhoneCallDetailsWithDuration(60); - assertDurationExactEquals("01:00"); - } - - /** Asserts that a char sequence is actually a Spanned corresponding to the expected HTML. */ - private void assertEqualsHtml(String expectedHtml, CharSequence actualText) { - // In order to contain HTML, the text should actually be a Spanned. - assertTrue(actualText instanceof Spanned); - Spanned actualSpanned = (Spanned) actualText; - // Convert from and to HTML to take care of alternative formatting of HTML. - assertEquals(Html.toHtml(Html.fromHtml(expectedHtml)), Html.toHtml(actualSpanned)); - - } - - public void testSetPhoneCallDetails_Date() { - mHelper.setCurrentTimeForTest( - new GregorianCalendar(2011, 5, 3, 13, 0, 0).getTimeInMillis()); - - setPhoneCallDetailsWithDate( - new GregorianCalendar(2011, 5, 3, 13, 0, 0).getTimeInMillis()); - assertLocationAndDateContains("0 min. ago"); - - setPhoneCallDetailsWithDate( - new GregorianCalendar(2011, 5, 3, 12, 0, 0).getTimeInMillis()); - assertLocationAndDateContains("1 hr. ago"); - - setPhoneCallDetailsWithDate( - new GregorianCalendar(2011, 5, 2, 13, 0, 0).getTimeInMillis()); - assertLocationAndDateContains("Yesterday"); - - setPhoneCallDetailsWithDate( - new GregorianCalendar(2011, 5, 1, 13, 0, 0).getTimeInMillis()); - assertLocationAndDateContains("2 days ago"); - } - - public void testSetPhoneCallDetails_CallTypeIcons() { - setPhoneCallDetailsWithCallTypeIcons(AppCompatConstants.CALLS_INCOMING_TYPE); - assertCallTypeIconsEquals(AppCompatConstants.CALLS_INCOMING_TYPE); - - setPhoneCallDetailsWithCallTypeIcons(AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallTypeIconsEquals(AppCompatConstants.CALLS_OUTGOING_TYPE); - - setPhoneCallDetailsWithCallTypeIcons(AppCompatConstants.CALLS_MISSED_TYPE); - assertCallTypeIconsEquals(AppCompatConstants.CALLS_MISSED_TYPE); - - setPhoneCallDetailsWithCallTypeIcons(AppCompatConstants.CALLS_VOICEMAIL_TYPE); - assertCallTypeIconsEquals(AppCompatConstants.CALLS_VOICEMAIL_TYPE); - } - - /** - * Tests a case where the video call feature is present. - */ - public void testSetPhoneCallDetails_Video() { - PhoneCallDetails details = getPhoneCallDetails(); - details.features = Calls.FEATURES_VIDEO; - mHelper.setPhoneCallDetails(mViews, details); - - assertIsVideoCall(true); - } - - /** - * Tests a case where the video call feature is not present. - */ - public void testSetPhoneCallDetails_NoVideo() { - PhoneCallDetails details = getPhoneCallDetails(); - details.features = 0; - mHelper.setPhoneCallDetails(mViews, details); - - assertIsVideoCall(false); - } - - public void testSetPhoneCallDetails_MultipleCallTypeIcons() { - setPhoneCallDetailsWithCallTypeIcons( - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallTypeIconsEquals( - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE); - - setPhoneCallDetailsWithCallTypeIcons( - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE); - assertCallTypeIconsEquals( - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE); - } - - public void testSetPhoneCallDetails_MultipleCallTypeIconsLastOneDropped() { - setPhoneCallDetailsWithCallTypeIcons( - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE); - assertCallTypeIconsEqualsPlusOverflow("(4)", - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE, - AppCompatConstants.CALLS_INCOMING_TYPE); - } - - public void testSetPhoneCallDetails_Geocode() { - setPhoneCallDetailsWithNumberAndGeocode("+14125555555", "1-412-555-5555", "Pennsylvania"); - assertNameEquals("1-412-555-5555"); // The phone number is shown as the name. - assertLocationAndDateContains("Pennsylvania"); // The geocode is shown as the label. - } - - public void testSetPhoneCallDetails_NoGeocode() { - setPhoneCallDetailsWithNumberAndGeocode("+14125555555", "1-412-555-5555", null); - assertNameEquals("1-412-555-5555"); // The phone number is shown as the name. - assertLocationAndDateContains(EMPTY_GEOCODE); // The empty geocode is shown as the label. - } - - public void testSetPhoneCallDetails_EmptyGeocode() { - setPhoneCallDetailsWithNumberAndGeocode("+14125555555", "1-412-555-5555", ""); - assertNameEquals("1-412-555-5555"); // The phone number is shown as the name. - assertLocationAndDateContains(EMPTY_GEOCODE); // The empty geocode is shown as the label. - } - - public void testSetPhoneCallDetails_NoGeocodeForVoicemail() { - setPhoneCallDetailsWithNumberAndGeocode(TEST_VOICEMAIL_NUMBER, "", "United States"); - assertLocationAndDateContains(EMPTY_GEOCODE); // The empty geocode is shown as the label. - } - - public void testSetPhoneCallDetails_Highlighted() { - setPhoneCallDetailsWithNumber(TEST_VOICEMAIL_NUMBER, - Calls.PRESENTATION_ALLOWED, ""); - } - - public void testSetCallDetailsHeader_NumberOnly() { - setCallDetailsHeaderWithNumber(TEST_NUMBER, Calls.PRESENTATION_ALLOWED); - assertEquals(View.VISIBLE, mNameView.getVisibility()); - assertEquals("1-412-255-5555", mNameView.getText().toString()); - } - - public void testSetCallDetailsHeader_UnknownNumber() { - setCallDetailsHeaderWithNumber("", Calls.PRESENTATION_UNKNOWN); - assertEquals(View.VISIBLE, mNameView.getVisibility()); - assertEquals("Unknown", mNameView.getText().toString()); - } - - public void testSetCallDetailsHeader_PrivateNumber() { - setCallDetailsHeaderWithNumber("", Calls.PRESENTATION_RESTRICTED); - assertEquals(View.VISIBLE, mNameView.getVisibility()); - assertEquals("Private number", mNameView.getText().toString()); - } - - public void testSetCallDetailsHeader_PayphoneNumber() { - setCallDetailsHeaderWithNumber("", Calls.PRESENTATION_PAYPHONE); - assertEquals(View.VISIBLE, mNameView.getVisibility()); - assertEquals("Payphone", mNameView.getText().toString()); - } - - public void testSetCallDetailsHeader_VoicemailNumber() { - PhoneCallDetails details = getPhoneCallDetails( - TEST_VOICEMAIL_NUMBER, - Calls.PRESENTATION_ALLOWED, - TEST_FORMATTED_NUMBER); - mHelper.setCallDetailsHeader(mNameView, details); - assertEquals(View.VISIBLE, mNameView.getVisibility()); - assertEquals("Voicemail", mNameView.getText().toString()); - } - - public void testSetCallDetailsHeader() { - setCallDetailsHeader("John Doe"); - assertEquals(View.VISIBLE, mNameView.getVisibility()); - assertEquals("John Doe", mNameView.getText().toString()); - } - - public void testGetCallTypeOrLocation_Geocode() { - assertEquals(TEST_GEOCODE, mHelper.getCallTypeOrLocation(getPhoneCallDetails())); - } - - public void testGetCallTypeOrLocation_CallType() { - PhoneCallDetails details = getPhoneCallDetails(); - details.geocode = null; - details.numberType = Calls.INCOMING_TYPE; - mHelper.setPhoneTypeLabelForTest("mobile"); - assertEquals("mobile", mHelper.getCallTypeOrLocation(details)); - } - - public void testGetCallTypeOrLocation_DisplayNumber() { - PhoneCallDetails details = getPhoneCallDetails("", Calls.PRESENTATION_ALLOWED, - TEST_FORMATTED_NUMBER); - details.namePrimary = "name"; - assertEquals(TEST_FORMATTED_NUMBER, mHelper.getCallTypeOrLocation(details)); - } - - /** Asserts that the name text field contains the value of the given string resource. */ - private void assertNameEqualsResource(int resId) { - assertNameEquals(getContext().getString(resId)); - } - - /** Asserts that the name text field contains the given string value. */ - private void assertNameEquals(String text) { - assertEquals(text, mViews.nameView.getText().toString()); - } - - /** Asserts that the location and date text field contains the given string value. */ - private void assertLocationAndDateContains(String text) { - assertTrue(mViews.callLocationAndDate.getText().toString().contains(text)); - } - - /** Asserts that the location and date text field exactly equals the given string value. */ - private void assertLocationAndDateExactEquals(String text) { - assertEquals(text, mViews.callLocationAndDate.getText()); - } - - /** Asserts that the via number is correct. */ - private void assertViaNumberEquals(String text) { - final String callAccountText = - mContext.getResources().getString(R.string.description_via_number, text); - assertEquals(callAccountText, mViews.callAccountLabel.getText()); - } - - /** Asserts that the account label is correct. */ - private void assertAccountLabelEquals(String text) { - assertEquals(text, mViews.callAccountLabel.getText()); - } - - /** Asserts that the account label is correct when also showing the via number. */ - private void assertAccountLabelEquals(String viaNumber, String accountLabel) { - final String viaNumberText = - mContext.getResources().getString(R.string.description_via_number, viaNumber); - assertEquals(accountLabel + " " + viaNumberText, mViews.callAccountLabel.getText()); - } - - /** Asserts that the call account label is invisible. */ - private void assertCallAccountInvisible() { - assertEquals(mViews.callAccountLabel.getVisibility(), View.GONE); - } - - /** Asserts that the duration is exactly as included in the location and date text field. */ - private void assertDurationExactEquals(String text) { - Matcher matcher = Pattern.compile("(.*) (\\u2022) (\\d{2}:\\d{2})").matcher( - mViews.callLocationAndDate.getText()); - assertEquals(true, matcher.matches()); - assertEquals(text, matcher.group(3)); - } - - /** Asserts that the video icon is shown. */ - private void assertIsVideoCall(boolean isVideoCall) { - assertEquals(isVideoCall, mViews.callTypeIcons.isVideoShown()); - } - - /** Asserts that the call type contains the images with the given drawables. */ - private void assertCallTypeIconsEquals(int... ids) { - assertEquals(ids.length, mViews.callTypeIcons.getCount()); - for (int index = 0; index < ids.length; ++index) { - int id = ids[index]; - assertEquals(id, mViews.callTypeIcons.getCallType(index)); - } - assertEquals(View.VISIBLE, mViews.callTypeIcons.getVisibility()); - } - - /** - * Asserts that the call type contains the images with the given drawables and shows the given - * text next to the icons. - */ - private void assertCallTypeIconsEqualsPlusOverflow(String overflowText, int... ids) { - assertEquals(ids.length, mViews.callTypeIcons.getCount()); - for (int index = 0; index < ids.length; ++index) { - int id = ids[index]; - assertEquals(id, mViews.callTypeIcons.getCallType(index)); - } - assertEquals(View.VISIBLE, mViews.callTypeIcons.getVisibility()); - assertTrue(mViews.callLocationAndDate.getText().toString().contains(overflowText)); - assertTrue(mViews.callLocationAndDate.getText().toString().contains("Yesterday")); - } - - /** Sets the phone call details with default values and the given number. */ - private void setPhoneCallDetailsWithNumber(String number, int presentation, - String formattedNumber) { - PhoneCallDetails details = getPhoneCallDetails(number, presentation, formattedNumber); - details.callTypes = new int[]{ AppCompatConstants.CALLS_VOICEMAIL_TYPE }; - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the phone call details with default values and the given via number. */ - private void setPhoneCallDetailsWithViaNumber(String viaNumber) { - PhoneCallDetails details = getPhoneCallDetails(); - mPhoneUtils.setAccountLabel(""); - details.viaNumber = viaNumber; - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the phone call details with an account handle. */ - private void setPhoneCallDetailsWithAccountHandle() { - PhoneCallDetails details = getPhoneCallDetails(); - details.accountHandle = new PhoneAccountHandle(new ComponentName("",""), ""); - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the phone call details with an account handle and via number */ - private void setPhoneCallDetailsWithAccountLabelViaNumber(String viaNumber) { - PhoneCallDetails details = getPhoneCallDetails(); - details.viaNumber = viaNumber; - details.accountHandle = new PhoneAccountHandle(new ComponentName("",""), ""); - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Populates the phone call details with the Defaults. */ - private void setDefaultPhoneCallDetailsNoViaNumber() { - PhoneCallDetails details = getPhoneCallDetails(); - mPhoneUtils.setAccountLabel(""); - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the phone call details with default values and the given number. */ - private void setPhoneCallDetailsWithNumberAndGeocode( - String number, String formattedNumber, String geocodedLocation) { - PhoneCallDetails details = getPhoneCallDetails( - number, Calls.PRESENTATION_ALLOWED, formattedNumber); - details.geocode = geocodedLocation; - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the phone call details with default values and the given date. */ - private void setPhoneCallDetailsWithDate(long date) { - PhoneCallDetails details = getPhoneCallDetails(); - details.date = date; - mHelper.setPhoneCallDetails(mViews, details); - } - - private void setVoicemailPhoneCallDetailsWithDate(long date) { - PhoneCallDetails details = getPhoneCallDetails(); - details.date = date; - details.callTypes = new int[] {Calls.VOICEMAIL_TYPE}; - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the voice mail details with default values and the given duration. */ - private void setVoicemailPhoneCallDetailsWithDuration(long duration) { - PhoneCallDetails details = getPhoneCallDetails(); - details.duration = duration; - details.callTypes = new int[] {Calls.VOICEMAIL_TYPE}; - mHelper.setPhoneCallDetails(mViews, details); - } - - /** Sets the phone call details with default values and the given call types using icons. */ - private void setPhoneCallDetailsWithCallTypeIcons(int... callTypes) { - PhoneCallDetails details = getPhoneCallDetails(); - details.callTypes = callTypes; - mHelper.setPhoneCallDetails(mViews, details); - } - - private void setCallDetailsHeaderWithNumber(String number, int presentation) { - mHelper.setCallDetailsHeader(mNameView, - getPhoneCallDetails(number, presentation, TEST_FORMATTED_NUMBER)); - } - - private void setCallDetailsHeader(String name) { - PhoneCallDetails details = getPhoneCallDetails(); - details.namePrimary = name; - mHelper.setCallDetailsHeader(mNameView, details); - } - - private PhoneCallDetails getPhoneCallDetails() { - PhoneCallDetails details = new PhoneCallDetails( - mContext, - TEST_NUMBER, - Calls.PRESENTATION_ALLOWED, - TEST_FORMATTED_NUMBER, - EMPTY_POSTDIAL, - false /* isVoicemail */); - setDefaultDetails(details); - return details; - } - - private PhoneCallDetails getPhoneCallDetails( - String number, int presentation, String formattedNumber) { - PhoneCallDetails details = new PhoneCallDetails( - mContext, - number, - presentation, - formattedNumber, - EMPTY_POSTDIAL, - isVoicemail(number)); - setDefaultDetails(details); - return details; - } - - private void setDefaultDetails(PhoneCallDetails details) { - details.callTypes = new int[]{ AppCompatConstants.CALLS_INCOMING_TYPE }; - details.countryIso = TEST_COUNTRY_ISO; - details.date = TEST_DATE; - details.duration = TEST_DURATION; - details.geocode = TEST_GEOCODE; - } - - private boolean isVoicemail(String number) { - return number.equals(TEST_VOICEMAIL_NUMBER); - } -} diff --git a/tests/src/com/android/dialer/calllog/PhoneCallDetailsTest.java b/tests/src/com/android/dialer/calllog/PhoneCallDetailsTest.java deleted file mode 100644 index 5c500d8bb..000000000 --- a/tests/src/com/android/dialer/calllog/PhoneCallDetailsTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.android.dialer.calllog; - -import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.text.SpannableString; -import android.text.TextUtils; -import android.text.style.TtsSpan; - -import com.android.dialer.PhoneCallDetails; -import com.android.dialer.R; -import com.android.contacts.common.util.ContactDisplayUtils; - -/** - * Unit tests for {@link PhoneCallDetails}. - */ -public class PhoneCallDetailsTest extends AndroidTestCase { - private static final String VIA_NUMBER = "+16505551212"; - private static final String PHONE_ACCOUNT_LABEL = "TEST"; - - private Resources mResources; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResources = mContext.getResources(); - } - - @SmallTest - public void testCreateAccountLabelDescription_NoViaNumberNoAccountLabel() { - CharSequence result = PhoneCallDetails.createAccountLabelDescription(mResources, "",""); - assertEquals("", result); - } - - @SmallTest - public void testCreateAccountLabelDescription_ViaNumberAccountLabel() { - String msg = mResources.getString(R.string.description_via_number_phone_account, - PHONE_ACCOUNT_LABEL, VIA_NUMBER); - CharSequence accountNumberLabel = ContactDisplayUtils.getTelephoneTtsSpannable(msg, - VIA_NUMBER); - CharSequence result = PhoneCallDetails.createAccountLabelDescription(mResources, VIA_NUMBER, - PHONE_ACCOUNT_LABEL); - assertEquals(accountNumberLabel.toString(), result.toString()); - } - - @SmallTest - public void testCreateAccountLabelDescription_ViaNumber() { - CharSequence viaNumberLabel = ContactDisplayUtils.getTtsSpannedPhoneNumber(mResources, - R.string.description_via_number, VIA_NUMBER); - CharSequence result = PhoneCallDetails.createAccountLabelDescription(mResources, VIA_NUMBER, - ""); - assertEquals(viaNumberLabel.toString(), result.toString()); - } - - @SmallTest - public void testCreateAccountLabelDescription_AccountLabel() { - CharSequence accountLabel = TextUtils.expandTemplate( - mResources.getString(R.string.description_phone_account), PHONE_ACCOUNT_LABEL); - CharSequence result = PhoneCallDetails.createAccountLabelDescription(mResources, "", - PHONE_ACCOUNT_LABEL); - assertEquals(accountLabel, result); - } -} diff --git a/tests/src/com/android/dialer/calllog/calllogcache/TestTelecomCallLogCache.java b/tests/src/com/android/dialer/calllog/calllogcache/TestTelecomCallLogCache.java deleted file mode 100644 index 270019afd..000000000 --- a/tests/src/com/android/dialer/calllog/calllogcache/TestTelecomCallLogCache.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2013 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.dialer.calllog.calllogcache; - -import android.content.Context; -import android.telecom.PhoneAccount; -import android.telecom.PhoneAccountHandle; - -/** - * Modified version of {@link com.android.dialer.calllog.calllogcache.CallLogCache} to be used in - * tests that allows injecting the voicemail number. - * - * NOTE: This tests the pre-LMR1 version because currently none of the tests involve multi-SIM, - * but... - * TODO: write tests to test multi-SIM functionality in TelecomCallLogCache. - */ -public class TestTelecomCallLogCache extends CallLogCache { - private CharSequence mVoicemailNumber; - private String mAccountLabel; - - public TestTelecomCallLogCache(Context context, CharSequence voicemailNumber, - String accountLabel) { - super(context); - mVoicemailNumber = voicemailNumber; - mAccountLabel = accountLabel; - } - - @Override - public boolean isVoicemailNumber(PhoneAccountHandle accountHandle, CharSequence number) { - return mVoicemailNumber.equals(number); - } - - @Override - public String getAccountLabel(PhoneAccountHandle accountHandle) { - return mAccountLabel; - } - - public void setAccountLabel(String accountLabel) { - mAccountLabel = accountLabel; - } - - @Override - public int getAccountColor(PhoneAccountHandle accountHandle) { - return PhoneAccount.NO_HIGHLIGHT_COLOR; - } - - @Override - public boolean doesAccountSupportCallSubject(PhoneAccountHandle accountHandle) { - return false; - } -} diff --git a/tests/src/com/android/dialer/compat/FilteredNumberCompatInstrumentationTest.java b/tests/src/com/android/dialer/compat/FilteredNumberCompatInstrumentationTest.java deleted file mode 100644 index 8ceb25046..000000000 --- a/tests/src/com/android/dialer/compat/FilteredNumberCompatInstrumentationTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.compat; - -import android.app.AlertDialog; -import android.app.DialogFragment; -import android.app.FragmentManager; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.DialogInterface; -import android.provider.BlockedNumberContract.BlockedNumbers; -import android.test.ActivityInstrumentationTestCase2; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.dialer.DialtactsActivity; -import com.android.dialer.R; - -/** - * UI tests for FilteredNumberCompat - */ -public class FilteredNumberCompatInstrumentationTest extends - ActivityInstrumentationTestCase2<DialtactsActivity> { - - private static final String E164_NUMBER = "+16502530000"; - private static final String NUMBER = "6502530000"; - private static final String COUNTRY_ISO = "US"; - - private ContentResolver mContentResolver; - private FragmentManager mFragmentManager; - - public FilteredNumberCompatInstrumentationTest() { - super(DialtactsActivity.class); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - mContentResolver = getActivity().getContentResolver(); - mFragmentManager = getActivity().getFragmentManager(); - mContentResolver.delete(BlockedNumbersSdkCompat.CONTENT_URI, - BlockedNumbers.COLUMN_ORIGINAL_NUMBER + " = ?", new String[]{NUMBER}); - } - - public void testShowBlockNumberDialogFlow_AlreadyBlocked() throws InterruptedException { - if (!CompatUtils.isNCompatible()) { - return; - } - - ContentValues values = new ContentValues(); - values.put(BlockedNumbers.COLUMN_ORIGINAL_NUMBER, NUMBER); - mContentResolver.insert(BlockedNumbers.CONTENT_URI, values); - - FilteredNumberCompat.setHasMigratedToNewBlocking(false); - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - FilteredNumberCompat - .showBlockNumberDialogFlow(mContentResolver, null, NUMBER, COUNTRY_ISO, - E164_NUMBER, R.id.floating_action_button_container, - mFragmentManager, null); - } - }); - getInstrumentation().waitForIdleSync(); - - final DialogFragment migrateDialogFragment = (DialogFragment) mFragmentManager - .findFragmentByTag("MigrateBlockedNumbers"); - assertTrue(migrateDialogFragment.getDialog().isShowing()); - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - ((AlertDialog) migrateDialogFragment.getDialog()) - .getButton(DialogInterface.BUTTON_POSITIVE).performClick(); - } - }); - getInstrumentation().waitForIdleSync(); - assertNull(mFragmentManager.findFragmentByTag("BlockNumberDialog")); - } -} diff --git a/tests/src/com/android/dialer/compat/FilteredNumberCompatTest.java b/tests/src/com/android/dialer/compat/FilteredNumberCompatTest.java deleted file mode 100644 index 3572316db..000000000 --- a/tests/src/com/android/dialer/compat/FilteredNumberCompatTest.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.compat; - -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.content.ComponentName; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.UserManager; -import android.provider.BlockedNumberContract.BlockedNumbers; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.dialer.DialerApplication; -import com.android.dialer.database.FilteredNumberContract.FilteredNumber; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberColumns; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberSources; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberTypes; -import com.android.dialer.filterednumber.BlockedNumbersSettingsActivity; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.Arrays; - -@SmallTest -public class FilteredNumberCompatTest extends AndroidTestCase { - - private static final String E164_NUMBER = "+16502530000"; - private static final String NON_E164_NUMBER = "6502530000"; - private static final String COUNTRY_ISO = "US"; - - private static final Uri EXPECTED_BASE_URI = CompatUtils.isNCompatible() - ? BlockedNumbers.CONTENT_URI : FilteredNumber.CONTENT_URI; - - @Mock private Context mContext; - @Mock private SharedPreferences mSharedPreferences; - - @Override - public void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - DialerApplication.setContextForTest(mContext); - when(mContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mSharedPreferences); - FilteredNumberCompat.setIsEnabledForTest(true); - } - - public void testIsNewFilteringEnabled_TestValueFalse() { - FilteredNumberCompat.setIsEnabledForTest(false); - assertFalse(FilteredNumberCompat.canUseNewFiltering()); - } - - public void testIsNewFilteringEnabled_TestValueTrue() { - FilteredNumberCompat.setIsEnabledForTest(true); - assertEquals(CompatUtils.isNCompatible(), FilteredNumberCompat.canUseNewFiltering()); - } - - public void testHasMigratedToNewBlocking_False() { - assertFalse(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - public void testHasMigratedToNewBlocking_Migrated() { - when(mSharedPreferences - .getBoolean(FilteredNumberCompat.HAS_MIGRATED_TO_NEW_BLOCKING_KEY, false)) - .thenReturn(true); - assertTrue(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - public void testGetContentUri_NullId() { - assertEquals(FilteredNumber.CONTENT_URI, FilteredNumberCompat.getContentUri(null)); - } - - public void testGetContentUri_NotMigrated() { - assertEquals(ContentUris.withAppendedId(FilteredNumber.CONTENT_URI, 1), - FilteredNumberCompat.getContentUri(1)); - } - - public void testGetContentUri_Migrated() { - when(mSharedPreferences - .getBoolean(FilteredNumberCompat.HAS_MIGRATED_TO_NEW_BLOCKING_KEY, false)) - .thenReturn(true); - assertEquals(ContentUris.withAppendedId(EXPECTED_BASE_URI, 1), - FilteredNumberCompat.getContentUri(1)); - } - - public void testFilter_NullProjection() { - assertNull(FilteredNumberCompat.filter(null)); - } - - public void testFilter_NoNulls() { - assertArrayEquals(new String[] {"a", "b", "c"}, - FilteredNumberCompat.filter(new String[] {"a", "b", "c"})); - } - - public void testFilter_WithNulls() { - assertArrayEquals(new String[] {"a", "b"}, - FilteredNumberCompat.filter(new String[] {"a", null, "b"})); - } - - public void testNewBlockNumberContentValues_NullNumber() { - try { - FilteredNumberCompat.newBlockNumberContentValues(null, null, null); - fail(); - } catch (NullPointerException e) {} - } - - public void testNewBlockNumberContentValues_N_NotMigrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - assertEquals(newExpectedContentValuesM(NON_E164_NUMBER, null, null), - FilteredNumberCompat.newBlockNumberContentValues(NON_E164_NUMBER, null, null)); - } - - public void testNewBlockNumberContentValues_N_Migrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - ContentValues contentValues = new ContentValues(); - contentValues.put(BlockedNumbers.COLUMN_ORIGINAL_NUMBER, NON_E164_NUMBER); - when(mSharedPreferences - .getBoolean(FilteredNumberCompat.HAS_MIGRATED_TO_NEW_BLOCKING_KEY, false)) - .thenReturn(true); - assertEquals(contentValues, FilteredNumberCompat.newBlockNumberContentValues( - NON_E164_NUMBER, - null, null)); - } - - public void testNewBlockNumberContentValues_N_Disabled() { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - assertEquals(newExpectedContentValuesM(NON_E164_NUMBER, E164_NUMBER, COUNTRY_ISO), - FilteredNumberCompat.newBlockNumberContentValues(NON_E164_NUMBER, E164_NUMBER, COUNTRY_ISO)); - } - - public void testNewBlockNumberContentValues_M_NullE164() { - if (CompatUtils.isNCompatible()) { - return; - } - assertEquals(newExpectedContentValuesM(NON_E164_NUMBER, E164_NUMBER, COUNTRY_ISO), - FilteredNumberCompat.newBlockNumberContentValues(NON_E164_NUMBER, null, COUNTRY_ISO)); - } - - public void testNewBlockNumberContentValues_M_NullCountryIso() { - if (CompatUtils.isNCompatible()) { - return; - } - assertEquals(newExpectedContentValuesM(NON_E164_NUMBER, E164_NUMBER, null), - FilteredNumberCompat.newBlockNumberContentValues(NON_E164_NUMBER, E164_NUMBER, null)); - } - - public void testNewBlockNumberContentValues_M_NullE164AndCountryIso() { - if (CompatUtils.isNCompatible()) { - return; - } - // Number can't be formatted properly without country code - assertEquals(newExpectedContentValuesM(NON_E164_NUMBER, null, null), - FilteredNumberCompat.newBlockNumberContentValues(NON_E164_NUMBER, null, null)); - } - - public void testCreateManageBlockedNumbersIntent_NullContext() { - try { - FilteredNumberCompat.createManageBlockedNumbersIntent(null); - fail(); - } catch (NullPointerException e) {} - } - - public void testCreateManageBlockedNumbersIntent_M() { - if (CompatUtils.isNCompatible()) { - return; - } - assertEquals(new ComponentName(getContext(), BlockedNumbersSettingsActivity.class), - FilteredNumberCompat.createManageBlockedNumbersIntent(getContext()).getComponent()); - } - - public void testCreateManageBlockedNumbersIntent_N_Disabled_NotMigrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - assertEquals(new ComponentName(getContext(), BlockedNumbersSettingsActivity.class), - FilteredNumberCompat.createManageBlockedNumbersIntent(getContext()).getComponent()); - } - - public void testCreateManageBlockedNumbersIntent_N_Enabled_NotMigrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - assertEquals(new ComponentName(getContext(), BlockedNumbersSettingsActivity.class), - FilteredNumberCompat.createManageBlockedNumbersIntent(getContext()).getComponent()); - } - - public void testCreateManageBlockedNumbersIntent_N_Enabled_Migrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - when(mSharedPreferences - .getBoolean(FilteredNumberCompat.HAS_MIGRATED_TO_NEW_BLOCKING_KEY, false)) - .thenReturn(true); - assertFalse(new ComponentName(getContext(), BlockedNumbersSettingsActivity.class) - .equals(FilteredNumberCompat.createManageBlockedNumbersIntent(getContext()) - .getComponent())); - } - - public void testCanCurrentUserOpenBlockSettings_M_SecondaryUser() { - if (CompatUtils.isNCompatible()) { - return; - } - UserManager userManager = mock(UserManager.class); - when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(userManager); - when(userManager.isSystemUser()).thenReturn(false); - assertFalse(FilteredNumberCompat.canCurrentUserOpenBlockSettings(mContext)); - verify(mContext).getSystemService(Context.USER_SERVICE); - verify(userManager).isSystemUser(); - } - - public void testCanCurrentUserOpenBlockSettings_M_PrimaryUser() { - if (CompatUtils.isNCompatible()) { - return; - } - UserManager userManager = mock(UserManager.class); - when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(userManager); - when(userManager.isSystemUser()).thenReturn(true); - assertTrue(FilteredNumberCompat.canCurrentUserOpenBlockSettings(mContext)); - verify(mContext).getSystemService(Context.USER_SERVICE); - verify(userManager).isSystemUser(); - } - - public void testCanAttemptBlockOperations_M_SecondaryUser() { - if (CompatUtils.isNCompatible()) { - return; - } - UserManager userManager = mock(UserManager.class); - when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(userManager); - when(userManager.isSystemUser()).thenReturn(false); - assertFalse(FilteredNumberCompat.canAttemptBlockOperations(mContext)); - verify(mContext).getSystemService(Context.USER_SERVICE); - verify(userManager).isSystemUser(); - } - - public void testCanAttemptBlockOperations_M_PrimaryUser() { - if (CompatUtils.isNCompatible()) { - return; - } - UserManager userManager = mock(UserManager.class); - when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(userManager); - when(userManager.isSystemUser()).thenReturn(true); - assertTrue(FilteredNumberCompat.canAttemptBlockOperations(mContext)); - verify(mContext).getSystemService(Context.USER_SERVICE); - verify(userManager).isSystemUser(); - } - - private ContentValues newExpectedContentValuesM(String number, String e164Number, - String countryIso) { - ContentValues contentValues = new ContentValues(); - contentValues.put(FilteredNumberColumns.NUMBER, number); - contentValues.put(FilteredNumberColumns.NORMALIZED_NUMBER, e164Number); - contentValues.put(FilteredNumberColumns.COUNTRY_ISO, countryIso); - contentValues.put(FilteredNumberColumns.TYPE, FilteredNumberTypes.BLOCKED_NUMBER); - contentValues.put(FilteredNumberColumns.SOURCE, FilteredNumberSources.USER); - return contentValues; - } - - private void assertArrayEquals(String[] expected, String[] actual) { - assertEquals(Arrays.toString(expected), Arrays.toString(actual)); - } -} diff --git a/tests/src/com/android/dialer/compat/UserManagerCompatTest.java b/tests/src/com/android/dialer/compat/UserManagerCompatTest.java deleted file mode 100644 index ff734a19d..000000000 --- a/tests/src/com/android/dialer/compat/UserManagerCompatTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2015 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.dialer.compat; - -import android.test.AndroidTestCase; - -import com.android.contacts.common.compat.CompatUtils; - -public class UserManagerCompatTest extends AndroidTestCase { - - public void testIsUserUnlocked_N_NullContext() { - if (!CompatUtils.isNCompatible()) { - return; - } - try { - UserManagerCompat.isUserUnlocked(null); - fail("Expected NullPointerException but none was thrown"); - } catch (NullPointerException e) {} - } - - public void testIsUserUnlocked_M_NullContext() { - if (CompatUtils.isNCompatible()) { - return; - } - assertTrue(UserManagerCompat.isUserUnlocked(null)); - } - - public void testIsUserUnlocked() { - assertTrue(UserManagerCompat.isUserUnlocked(getContext())); - } -} diff --git a/tests/src/com/android/dialer/contactinfo/ContactPhotoLoaderTest.java b/tests/src/com/android/dialer/contactinfo/ContactPhotoLoaderTest.java deleted file mode 100644 index 42a5ae966..000000000 --- a/tests/src/com/android/dialer/contactinfo/ContactPhotoLoaderTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.contactinfo; - -import android.app.Instrumentation; -import android.content.ContentResolver; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.support.test.InstrumentationRegistry; -import android.support.v4.graphics.drawable.RoundedBitmapDrawable; -import android.test.AndroidTestCase; -import android.test.InstrumentationTestCase; -import android.text.TextUtils; - -import com.android.contacts.common.GeoUtil; -import com.android.contacts.common.lettertiles.LetterTileDrawable; -import com.android.dialer.calllog.ContactInfo; -import com.android.dialer.calllog.ContactInfoHelper; -import com.android.dialer.tests.R; - -public class ContactPhotoLoaderTest extends InstrumentationTestCase { - - private Context mContext; - - @Override - public void setUp() { - mContext = getInstrumentation().getTargetContext(); - } - - public void testConstructor() { - ContactPhotoLoader loader = new ContactPhotoLoader(mContext, new ContactInfo()); - } - - public void testConstructor_NullContext() { - try { - ContactPhotoLoader loader = new ContactPhotoLoader(null, new ContactInfo()); - fail(); - } catch (NullPointerException e) { - //expected - } - } - - public void testConstructor_NullContactInfo() { - try { - ContactPhotoLoader loader = new ContactPhotoLoader(mContext, null); - fail(); - } catch (NullPointerException e) { - //expected - } - } - - public void testGetIcon_Photo() { - ContactInfo info = getTestContactInfo(); - info.photoUri = getResourceUri(R.drawable.phone_icon); - ContactPhotoLoader loader = new ContactPhotoLoader(mContext, info); - assertTrue(loader.getIcon() instanceof RoundedBitmapDrawable); - } - - public void testGetIcon_Photo_Invalid() { - ContactInfo info = getTestContactInfo(); - info.photoUri = Uri.parse("file://invalid/uri"); - ContactPhotoLoader loader = new ContactPhotoLoader(mContext, info); - //Should fall back to LetterTileDrawable - assertTrue(loader.getIcon() instanceof LetterTileDrawable); - } - - public void testGetIcon_LetterTile() { - ContactInfo info = getTestContactInfo(); - ContactPhotoLoader loader = new ContactPhotoLoader(mContext, info); - assertTrue(loader.getIcon() instanceof LetterTileDrawable); - } - - private Uri getResourceUri(int resId) { - Context testContext = getInstrumentation().getContext(); - Resources resources = testContext.getResources(); - - assertNotNull(resources.getDrawable(resId)); - return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" - + testContext.getPackageName() - + '/' + resId); - } - - private ContactInfo getTestContactInfo() { - ContactInfo info = new ContactInfo(); - info.name = "foo"; - info.lookupKey = "bar"; - return info; - } -}
\ No newline at end of file diff --git a/tests/src/com/android/dialer/database/DatabaseTestUtils.java b/tests/src/com/android/dialer/database/DatabaseTestUtils.java deleted file mode 100644 index 19fff7f89..000000000 --- a/tests/src/com/android/dialer/database/DatabaseTestUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2015 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.dialer.database; - -import android.database.MatrixCursor; -import android.provider.ContactsContract.Contacts; -import android.provider.ContactsContract.Data; -import android.provider.ContactsContract.CommonDataKinds.Phone; -import android.text.TextUtils; - -import com.android.dialer.database.DialerDatabaseHelper.ContactNumber; - -public class DatabaseTestUtils { - public static MatrixCursor constructNewNameCursor() { - final MatrixCursor cursor = new MatrixCursor(new String[]{ - DialerDatabaseHelper.SmartDialDbColumns.DISPLAY_NAME_PRIMARY, - DialerDatabaseHelper.SmartDialDbColumns.CONTACT_ID}); - return cursor; - } - - public static MatrixCursor constructNewContactCursor() { - final MatrixCursor cursor = new MatrixCursor(new String[]{ - Phone._ID, // 0 - Phone.TYPE, // 1 - Phone.LABEL, // 2 - Phone.NUMBER, // 3 - Phone.CONTACT_ID, // 4 - Phone.LOOKUP_KEY, // 5 - Phone.DISPLAY_NAME_PRIMARY, // 6 - Phone.PHOTO_ID, // 7 - Data.LAST_TIME_USED, // 8 - Data.TIMES_USED, // 9 - Contacts.STARRED, // 10 - Data.IS_SUPER_PRIMARY, // 11 - Contacts.IN_VISIBLE_GROUP, // 12 - Data.IS_PRIMARY, // 13 - Data.CARRIER_PRESENCE}); // 14 - return cursor; - } - - public static ContactNumber constructNewContactWithDummyIds(MatrixCursor contactCursor, - MatrixCursor nameCursor, String number, int id, String displayName) { - return constructNewContact(contactCursor, nameCursor, id, number, id, String.valueOf(id), - displayName, 0, 0, 0, 0, 0, 0, 0, 0); - } - - public static ContactNumber constructNewContact(MatrixCursor contactCursor, - MatrixCursor nameCursor, int id, String number, int contactId, String lookupKey, - String displayName, int photoId, int lastTimeUsed, int timesUsed, int starred, - int isSuperPrimary, int inVisibleGroup, int isPrimary, int carrierPresence) { - if (contactCursor == null || nameCursor == null) { - throw new IllegalArgumentException("Provided MatrixCursors cannot be null"); - } - - if (TextUtils.isEmpty(number)) { - // Add a dummy number, otherwise DialerDatabaseHelper simply ignores the entire - // row if the number is empty - number = "0"; - } - - contactCursor.addRow(new Object[]{id, "", "", number, contactId, lookupKey, displayName, - photoId, lastTimeUsed, timesUsed, starred, isSuperPrimary, inVisibleGroup, - isPrimary, carrierPresence}); - nameCursor.addRow(new Object[]{displayName, contactId}); - - return new ContactNumber(contactId, id, displayName, number, lookupKey, 0, 0); - } -} diff --git a/tests/src/com/android/dialer/database/DialerDatabaseHelperTest.java b/tests/src/com/android/dialer/database/DialerDatabaseHelperTest.java deleted file mode 100644 index a95a79e08..000000000 --- a/tests/src/com/android/dialer/database/DialerDatabaseHelperTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2013 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.dialer.database; - -import static com.android.dialer.database.DatabaseTestUtils.*; - -import android.database.MatrixCursor; -import android.database.sqlite.SQLiteDatabase; -import android.test.suitebuilder.annotation.SmallTest; -import android.test.suitebuilder.annotation.Suppress; -import android.test.AndroidTestCase; - -import com.android.dialer.database.DialerDatabaseHelper; -import com.android.dialer.database.DialerDatabaseHelper.ContactNumber; -import com.android.dialer.dialpad.SmartDialNameMatcher; -import com.android.dialer.dialpad.SmartDialPrefix; - -import java.lang.Exception; -import java.lang.Override; -import java.util.ArrayList; - -/** - * Validates the behavior of the smart dial database helper with regards to contact updates and - * deletes. - * To run this test, use the command: - * adb shell am instrument -w -e class com.android.dialer.database.DialerDatabaseHelperTest / - * com.android.dialer.tests/android.test.InstrumentationTestRunner - */ -@SmallTest -public class DialerDatabaseHelperTest extends AndroidTestCase { - - private DialerDatabaseHelper mTestHelper; - private SQLiteDatabase mDb; - - @Override - protected void setUp() { - mTestHelper = DialerDatabaseHelper.getNewInstanceForTest(getContext()); - mDb = mTestHelper.getWritableDatabase(); - } - - @Override - protected void tearDown() throws Exception { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - mTestHelper.removeAllContacts(db); - super.tearDown(); - } - - /** - * Verifies that a new contact added into the database is a match after the update. - */ - public void testForNewContacts() { - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(mDb, contactCursor, 0L); - mTestHelper.insertNamePrefixes(mDb, nameCursor); - assertEquals(0, getMatchesFromDb("5105272357").size()); - - // Insert new contact - constructNewContactWithDummyIds(contactCursor, nameCursor, - "510-527-2357", 0, "James"); - mTestHelper.insertUpdatedContactsAndNumberPrefix(mDb, contactCursor, 1L); - mTestHelper.insertNamePrefixes(mDb, nameCursor); - assertEquals(1, getMatchesFromDb("5105272357").size()); - } - - /** - * Verifies that a contact that has its phone number changed is a match after the update. - */ - public void testForUpdatedContacts() { - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - constructNewContactWithDummyIds(contactCursor, nameCursor, - "510-527-2357", 0, "James"); - mTestHelper.insertUpdatedContactsAndNumberPrefix(mDb, contactCursor, 0L); - mTestHelper.insertNamePrefixes(mDb, nameCursor); - assertEquals(1, getMatchesFromDb("5105272357").size()); - assertEquals(0, getMatchesFromDb("6501234567").size()); - - // Update the database with the new contact information - final MatrixCursor nameCursor2 = constructNewNameCursor(); - final MatrixCursor contactCursor2 = constructNewContactCursor(); - constructNewContactWithDummyIds(contactCursor2, nameCursor2, - "650-123-4567", 0, "James"); - mTestHelper.removeUpdatedContacts(mDb, contactCursor2); - mTestHelper.insertUpdatedContactsAndNumberPrefix(mDb, contactCursor2, 1L); - mTestHelper.insertNamePrefixes(mDb, nameCursor2); - - // Now verify the matches are correct based on the new information - assertEquals(0, getMatchesFromDb("5105272357").size()); - assertEquals(1, getMatchesFromDb("6501234567").size()); - } - - /** - * Verifies that a contact that is deleted from CP2 is similarly deleted from the database - */ - public void testForDeletedContacts() { - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - constructNewContactWithDummyIds(contactCursor, nameCursor, - "510-527-2357", 0, "James"); - mTestHelper.insertUpdatedContactsAndNumberPrefix(mDb, contactCursor, 0L); - mTestHelper.insertNamePrefixes(mDb, nameCursor); - assertEquals(1, getMatchesFromDb("5105272357").size()); - - // Delete the contact and update its projection. - final MatrixCursor deletedCursor = - new MatrixCursor(DialerDatabaseHelper.DeleteContactQuery.PROJECTION); - deletedCursor.addRow(new Object[] {0, 1L}); - mTestHelper.removeDeletedContacts(mDb, deletedCursor); - assertEquals(0, getMatchesFromDb("5105272357").size()); - } - - /** - * Verifies that when a contact's number is deleted (but not the entire contact), the - * number is correctly deleted from the database. - */ - public void testForDeletedNumber() { - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - constructNewContactWithDummyIds(contactCursor, nameCursor, - "510-527-2357", 0, "James"); - mTestHelper.insertUpdatedContactsAndNumberPrefix(mDb, contactCursor, 0L); - mTestHelper.insertNamePrefixes(mDb, nameCursor); - assertEquals(1, getMatchesFromDb("5105272357").size()); - - // Match no longer exists after number was deleted from contact - final MatrixCursor updatedContactCursor = - new MatrixCursor(DialerDatabaseHelper.UpdatedContactQuery.PROJECTION); - updatedContactCursor.addRow(new Object[] {0}); - mTestHelper.removeUpdatedContacts(mDb, updatedContactCursor); - assertEquals(0, getMatchesFromDb("5105272357").size()); - } - - private ArrayList<ContactNumber> getMatchesFromDb(String query) { - final SmartDialNameMatcher nameMatcher = new SmartDialNameMatcher(query, - SmartDialPrefix.getMap()); - return mTestHelper.getLooseMatches(query, nameMatcher); - } -} diff --git a/tests/src/com/android/dialer/database/FilteredNumberAsyncQueryHandlerTest.java b/tests/src/com/android/dialer/database/FilteredNumberAsyncQueryHandlerTest.java deleted file mode 100644 index 625f3fdb5..000000000 --- a/tests/src/com/android/dialer/database/FilteredNumberAsyncQueryHandlerTest.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.database; - -import android.content.ContentUris; -import android.content.ContentValues; -import android.net.Uri; -import android.provider.BlockedNumberContract; -import android.provider.BlockedNumberContract.BlockedNumbers; -import android.test.InstrumentationTestCase; -import android.test.mock.MockContentResolver; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.contacts.common.test.mocks.MockContentProvider; -import com.android.contacts.common.test.mocks.MockContentProvider.Query; -import com.android.dialer.compat.FilteredNumberCompat; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler.OnBlockNumberListener; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler.OnHasBlockedNumbersListener; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler.OnUnblockNumberListener; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberColumns; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberSources; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberTypes; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -@SmallTest -public class FilteredNumberAsyncQueryHandlerTest extends InstrumentationTestCase { - - private static final String E164_NUMBER = "+16502530000"; - private static final String NUMBER = "6502530000"; - private static final String COUNTRY_ISO = "US"; - private static final Integer ID = 1; - private static final Integer ID2 = 2; - private static final Uri BLOCKED_NUMBER_URI_N = CompatUtils.isNCompatible() ? - Uri.withAppendedPath(BlockedNumberContract.AUTHORITY_URI, "blocked") : null; - private static final Uri BLOCKED_NUMBER_URI_M = - Uri.withAppendedPath(FilteredNumberContract.AUTHORITY_URI, "filtered_numbers_table"); - private static final Uri BLOCKED_NUMBER_URI = CompatUtils.isNCompatible() ? BLOCKED_NUMBER_URI_N - : BLOCKED_NUMBER_URI_M; - private static final Uri BLOCKED_NUMBER_URI_WITH_ID = - ContentUris.withAppendedId(BLOCKED_NUMBER_URI, ID); - private static final Uri EXPECTED_URI = Uri.fromParts("android", "google", "dialer"); - - private final MockContentResolver mContentResolver = new MockContentResolver(); - private final MockContentProvider mContentProvider = new MockContentProvider(); - - @Override - public void setUp() throws Exception { - super.setUp(); - FilteredNumberCompat.setIsEnabledForTest(true); - if (CompatUtils.isNCompatible()) { - mContentResolver.addProvider(BlockedNumberContract.AUTHORITY, mContentProvider); - } else { - mContentResolver.addProvider(FilteredNumberContract.AUTHORITY, mContentProvider); - } - } - - public void testHasBlockedNumbers_Disabled() throws Throwable { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - final MockContentResolver resolver = new MockContentResolver(); - MockContentProvider disabledProvider = new MockContentProvider(); - resolver.addProvider(FilteredNumberContract.AUTHORITY, disabledProvider); - - disabledProvider.expectQuery(BLOCKED_NUMBER_URI_M).withProjection(FilteredNumberColumns._ID) - .withSelection(FilteredNumberColumns.TYPE + "=" - + FilteredNumberTypes.BLOCKED_NUMBER, null).returnRow(ID); - final HasBlockedNumbersListener listener = new HasBlockedNumbersListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(resolver).hasBlockedNumbers(listener); - } - }); - assertTrue(listener.waitForCallback()); - disabledProvider.verify(); - } - - public void testHasBlockedNumbers_NoResults() throws Throwable { - newHasBlockedNumbersExpectedQuery().returnEmptyCursor(); - final HasBlockedNumbersListener listener = new HasBlockedNumbersListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver).hasBlockedNumbers(listener); - } - }); - assertFalse(listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testHasBlockedNumbers() throws Throwable { - newHasBlockedNumbersExpectedQuery().returnRow(ID); - final HasBlockedNumbersListener listener = new HasBlockedNumbersListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver).hasBlockedNumbers(listener); - } - }); - assertTrue(listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testIsBlockedNumber_Disabled() throws Throwable { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - final MockContentResolver resolver = new MockContentResolver(); - MockContentProvider disabledProvider = new MockContentProvider(); - resolver.addProvider(FilteredNumberContract.AUTHORITY, disabledProvider); - disabledProvider.expectQuery(BLOCKED_NUMBER_URI_M) - .withProjection(FilteredNumberColumns._ID, FilteredNumberColumns.TYPE) - .withSelection(FilteredNumberColumns.NORMALIZED_NUMBER + " = ?", E164_NUMBER) - .returnRow(ID, FilteredNumberTypes.BLOCKED_NUMBER); - final CheckBlockedListener listener = new CheckBlockedListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(resolver) - .isBlockedNumber(listener, NUMBER, COUNTRY_ISO); - } - }); - assertEquals(ID, listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testIsBlockedNumber_NoResults() throws Throwable { - newIsBlockedNumberExpectedQuery().returnEmptyCursor(); - final CheckBlockedListener listener = new CheckBlockedListener(); - - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver) - .isBlockedNumber(listener, NUMBER, COUNTRY_ISO); - } - }); - assertNull(listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testIsBlockedNumber() throws Throwable { - if (CompatUtils.isNCompatible()) { - newIsBlockedNumberExpectedQuery().returnRow(ID); - } else { - newIsBlockedNumberExpectedQuery().returnRow(ID, FilteredNumberTypes.BLOCKED_NUMBER); - } - final CheckBlockedListener listener = new CheckBlockedListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver) - .isBlockedNumber(listener, NUMBER, COUNTRY_ISO); - } - }); - assertEquals(ID, listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testIsBlockedNumber_MultipleResults() throws Throwable { - if (CompatUtils.isNCompatible()) { - newIsBlockedNumberExpectedQuery().returnRow(ID).returnRow(ID2); - } else { - newIsBlockedNumberExpectedQuery().returnRow(ID, FilteredNumberTypes.BLOCKED_NUMBER) - .returnRow(ID2, FilteredNumberTypes.BLOCKED_NUMBER); - } - final CheckBlockedListener listener = new CheckBlockedListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver) - .isBlockedNumber(listener, NUMBER, COUNTRY_ISO); - } - }); - // When there are multiple matches, the first is returned - assertEquals(ID, listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testBlockNumber_Disabled() throws Throwable { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - final MockContentResolver resolver = new MockContentResolver(); - MockContentProvider disabledProvider = new MockContentProvider(); - resolver.addProvider(FilteredNumberContract.AUTHORITY, disabledProvider); - - disabledProvider.expectInsert(BLOCKED_NUMBER_URI_M, newBlockNumberContentValuesM(), - EXPECTED_URI); - final BlockNumberListener listener = new BlockNumberListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(resolver).blockNumber(listener, E164_NUMBER, - NUMBER, COUNTRY_ISO); - } - }); - assertSame(EXPECTED_URI, listener.waitForCallback()); - disabledProvider.verify(); - } - - public void testBlockNumber() throws Throwable { - mContentProvider.expectInsert(BLOCKED_NUMBER_URI, newBlockNumberContentValues(), - EXPECTED_URI); - final BlockNumberListener listener = new BlockNumberListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver).blockNumber(listener, - E164_NUMBER, NUMBER, COUNTRY_ISO); - } - }); - assertSame(EXPECTED_URI, listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testBlockNumber_NullNormalizedNumber() throws Throwable { - mContentProvider.expectInsert(BLOCKED_NUMBER_URI, newBlockNumberContentValues(), - EXPECTED_URI); - final BlockNumberListener listener = new BlockNumberListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver).blockNumber(listener, - NUMBER, COUNTRY_ISO); - } - }); - assertSame(EXPECTED_URI, listener.waitForCallback()); - mContentProvider.verify(); - } - - public void testUnblockNumber_Disabled() throws Throwable { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - final MockContentResolver resolver = new MockContentResolver(); - MockContentProvider disabledProvider = new MockContentProvider(); - resolver.addProvider(FilteredNumberContract.AUTHORITY, disabledProvider); - - Uri uriWithId = ContentUris.withAppendedId(BLOCKED_NUMBER_URI_M, ID); - disabledProvider.expectQuery(uriWithId) - .withProjection(null) - .withDefaultProjection(FilteredNumberCompat.getIdColumnName()) - .withSelection(null, null) - .withSortOrder(null) - .returnRow(ID); - disabledProvider.expectDelete(uriWithId).returnRowsAffected(1); - final UnblockNumberListener listener = new UnblockNumberListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(resolver).unblock(listener, ID); - } - }); - assertNotNull(listener.waitForCallback()); - disabledProvider.verify(); - } - - public void testUnblockNumber_NullId() { - try { - new FilteredNumberAsyncQueryHandler(mContentResolver).unblock(null, (Integer) null); - fail(); - } catch (IllegalArgumentException e) {} - } - - public void testUnblockNumber() throws Throwable { - mContentProvider.expectQuery(BLOCKED_NUMBER_URI_WITH_ID) - .withProjection(null) - .withDefaultProjection(FilteredNumberCompat.getIdColumnName()) - .withSelection(null, null) - .withSortOrder(null) - .returnRow(ID); - mContentProvider.expectDelete(BLOCKED_NUMBER_URI_WITH_ID).returnRowsAffected(1); - final UnblockNumberListener listener = new UnblockNumberListener(); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - new FilteredNumberAsyncQueryHandler(mContentResolver).unblock(listener, ID); - } - }); - assertNotNull(listener.waitForCallback()); - mContentProvider.verify(); - } - - private Query newIsBlockedNumberExpectedQuery() { - if (CompatUtils.isNCompatible()) { - return newIsBlockedNumberExpectedQueryN(); - } - return newIsBlockedNumberExpectedQueryM(); - } - - private Query newIsBlockedNumberExpectedQueryN() { - return mContentProvider.expectQuery(BLOCKED_NUMBER_URI) - .withProjection(BlockedNumbers.COLUMN_ID) - .withSelection(BlockedNumbers.COLUMN_E164_NUMBER + " = ?", E164_NUMBER); - } - - private Query newIsBlockedNumberExpectedQueryM() { - return mContentProvider.expectQuery(BLOCKED_NUMBER_URI) - .withProjection(FilteredNumberColumns._ID, FilteredNumberColumns.TYPE) - .withSelection(FilteredNumberColumns.NORMALIZED_NUMBER + " = ?", E164_NUMBER); - } - - private Query newHasBlockedNumbersExpectedQuery() { - if (CompatUtils.isNCompatible()) { - return newHasBlockedNumbersExpectedQueryN(); - } - return newHasBlockedNumbersExpectedQueryM(); - } - - private Query newHasBlockedNumbersExpectedQueryN() { - return mContentProvider.expectQuery(BLOCKED_NUMBER_URI) - .withProjection(BlockedNumbers.COLUMN_ID) - .withSelection(null, null); - } - - private Query newHasBlockedNumbersExpectedQueryM() { - return mContentProvider.expectQuery(BLOCKED_NUMBER_URI).withProjection( - FilteredNumberColumns._ID) - .withSelection(FilteredNumberColumns.TYPE + "=" - + FilteredNumberTypes.BLOCKED_NUMBER, null); - } - - private ContentValues newBlockNumberContentValues() { - if (CompatUtils.isNCompatible()) { - return newBlockNumberContentValuesN(); - } - return newBlockNumberContentValuesM(); - } - - private ContentValues newBlockNumberContentValuesN() { - ContentValues contentValues = new ContentValues(); - contentValues.put(BlockedNumbers.COLUMN_ORIGINAL_NUMBER, NUMBER); - return contentValues; - } - - private ContentValues newBlockNumberContentValuesM() { - ContentValues contentValues = new ContentValues(); - contentValues.put(FilteredNumberColumns.NORMALIZED_NUMBER, E164_NUMBER); - contentValues.put(FilteredNumberColumns.NUMBER, NUMBER); - contentValues.put(FilteredNumberColumns.COUNTRY_ISO, COUNTRY_ISO); - contentValues.put(FilteredNumberColumns.TYPE, FilteredNumberTypes.BLOCKED_NUMBER); - contentValues.put(FilteredNumberColumns.SOURCE, FilteredNumberSources.USER); - return contentValues; - } - - private class CheckBlockedListener implements OnCheckBlockedListener { - public final CountDownLatch onCheckCompleteCalled; - public Integer id; - - public CheckBlockedListener() { - onCheckCompleteCalled = new CountDownLatch(1); - } - - @Override - public void onCheckComplete(Integer id) { - this.id = id; - onCheckCompleteCalled.countDown(); - } - - public Integer waitForCallback() throws InterruptedException { - if (!onCheckCompleteCalled.await(5000, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("Waiting on callback timed out."); - } - return id; - } - } - - private class HasBlockedNumbersListener implements OnHasBlockedNumbersListener { - public final CountDownLatch onHasBlockedNumbersCalled; - public boolean hasBlockedNumbers; - - public HasBlockedNumbersListener() { - onHasBlockedNumbersCalled = new CountDownLatch(1); - } - - @Override - public void onHasBlockedNumbers(boolean hasBlockedNumbers) { - this.hasBlockedNumbers = hasBlockedNumbers; - onHasBlockedNumbersCalled.countDown(); - } - - public boolean waitForCallback() throws InterruptedException { - if (!onHasBlockedNumbersCalled.await(5000, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("Waiting on callback timed out."); - } - return hasBlockedNumbers; - } - } - - private class BlockNumberListener implements OnBlockNumberListener { - public final CountDownLatch onBlockCompleteCalled; - public Uri uri; - - public BlockNumberListener() { - onBlockCompleteCalled = new CountDownLatch(1); - } - - @Override - public void onBlockComplete(Uri uri) { - this.uri = uri; - onBlockCompleteCalled.countDown(); - } - - public Uri waitForCallback() throws InterruptedException { - if (!onBlockCompleteCalled.await(5000, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("Waiting on callback timed out."); - } - return uri; - } - } - - private class UnblockNumberListener implements OnUnblockNumberListener { - public final CountDownLatch onUnblockCompleteCalled; - public Integer result; - - public UnblockNumberListener() { - onUnblockCompleteCalled = new CountDownLatch(1); - } - - @Override - public void onUnblockComplete(int rows, ContentValues values) { - result = rows; - onUnblockCompleteCalled.countDown(); - } - - public Integer waitForCallback() throws InterruptedException { - if (!onUnblockCompleteCalled.await(5000, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("Waiting on callback timed out."); - } - return result; - } - } -} diff --git a/tests/src/com/android/dialer/database/FilteredNumberProviderTest.java b/tests/src/com/android/dialer/database/FilteredNumberProviderTest.java deleted file mode 100644 index 1191560f5..000000000 --- a/tests/src/com/android/dialer/database/FilteredNumberProviderTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (C) 2015 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.dialer.database; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.database.DatabaseUtils; -import android.net.Uri; -import android.test.ProviderTestCase2; -import android.test.suitebuilder.annotation.MediumTest; - -@MediumTest -public class FilteredNumberProviderTest extends - ProviderTestCase2<FilteredNumberProviderTest.TestFilteredNumberProvider> { - private ContentResolver mResolver; - - private static final String TIME_ZONE_AMERICA_LOS_ANGELES = "America/Los_Angeles"; - private static final String DEFAULT_TIMEZONE = TIME_ZONE_AMERICA_LOS_ANGELES; - private static final String DEFAULT_COUNTRY_ISO = "US"; - private static final String TEST_NUMBER = "234567890"; - private static final String TEST_NORMALIZED_NUMBER = "+1234567890"; - private static final long TEST_TIME = 1439936706; - - public FilteredNumberProviderTest () { - super(TestFilteredNumberProvider.class, FilteredNumberContract.AUTHORITY); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResolver = getMockContentResolver(); - } - - public void testInsert() { - // Insert row - Uri uri = mResolver.insert( - FilteredNumberContract.FilteredNumber.CONTENT_URI, - getTestValues(null)); - assertNotNull(uri); - long id = ContentUris.parseId(uri); - assertTrue(id > 0); - } - - public void testQuery() { - Cursor cursor = mResolver.query( - FilteredNumberContract.FilteredNumber.CONTENT_URI, null, null, null, null); - assertNotNull(cursor); - assertEquals(cursor.getCount(), 0); - cursor.close(); - } - - public void testInsertAndQuery() { - // Insert row - ContentValues testValues = getTestValues(null); - Uri uri = mResolver.insert(FilteredNumberContract.FilteredNumber.CONTENT_URI, testValues); - - // Query - Cursor cursor = mResolver.query(uri, null, null, null, null); - assertNotNull(cursor); - assertEquals(cursor.getCount(), 1); - - cursor.moveToFirst(); - assertCursorValues(cursor, testValues); - cursor.close(); - } - - public void testIllegalUri() { - try { - mResolver.query( - Uri.withAppendedPath( - FilteredNumberContract.FilteredNumber.CONTENT_URI, - "ILLEGAL"), null, null, null, null); - fail("Expecting exception but none was thrown."); - } catch (IllegalArgumentException e) { - } - } - - public void testQueryWithId() { - // Insert row - ContentValues testValues = getTestValues(null); - Uri uri = mResolver.insert(FilteredNumberContract.FilteredNumber.CONTENT_URI, testValues); - long id = ContentUris.parseId(uri); - - // Query - Cursor cursor = mResolver.query( - ContentUris.withAppendedId( - FilteredNumberContract.FilteredNumber.CONTENT_URI, - id), null, null, null, null); - assertNotNull(cursor); - assertEquals(cursor.getCount(), 1); - - cursor.moveToFirst(); - assertCursorValues(cursor, testValues); - cursor.close(); - } - - public void testDelete() { - // Insert row - Uri uri = mResolver.insert( - FilteredNumberContract.FilteredNumber.CONTENT_URI, - getTestValues(null)); - long id = ContentUris.parseId(uri); - - // Delete row - int rows = mResolver.delete( - FilteredNumberContract.FilteredNumber.CONTENT_URI, - FilteredNumberContract.FilteredNumberColumns._ID + " = ?", - new String[]{Long.toString(id)}); - assertEquals(rows, 1); - - // Query - Cursor cursor = mResolver.query(uri, null, null, null, null); - assertNotNull(cursor); - assertEquals(cursor.getCount(), 0); - cursor.close(); - } - - public void testUpdate() { - // Insert row - Uri uri = mResolver.insert( - FilteredNumberContract.FilteredNumber.CONTENT_URI, - getTestValues(null)); - - // Update row - ContentValues v = new ContentValues(); - v.put(FilteredNumberContract.FilteredNumberColumns.TIMES_FILTERED, 3); - v.put(FilteredNumberContract.FilteredNumberColumns.LAST_TIME_FILTERED, TEST_TIME); - int rows = mResolver.update(FilteredNumberContract.FilteredNumber.CONTENT_URI, v, - FilteredNumberContract.FilteredNumberColumns.NORMALIZED_NUMBER + " = ?", - new String[]{TEST_NORMALIZED_NUMBER}); - assertEquals(rows, 1); - - ContentValues expected = getTestValues(TEST_TIME); - expected.put(FilteredNumberContract.FilteredNumberColumns.TIMES_FILTERED, 3); - expected.put(FilteredNumberContract.FilteredNumberColumns.LAST_TIME_FILTERED, TEST_TIME); - - // Re-query - Cursor cursor = mResolver.query(uri, null, null, null, null); - assertNotNull(cursor); - assertEquals(cursor.getCount(), 1); - cursor.moveToFirst(); - assertCursorValues(cursor, expected); - cursor.close(); - } - - public void testInsertDefaultValues() { - // Insert row - ContentValues v = getTestValues(null); - Uri uri = mResolver.insert(FilteredNumberContract.FilteredNumber.CONTENT_URI, v); - assertNotNull(uri); - long id = ContentUris.parseId(uri); - assertTrue(id > 0); - - // Query - Cursor cursor = mResolver.query(uri, null, null, null, null); - assertNotNull(cursor); - assertEquals(cursor.getCount(), 1); - - int creationTimeIndex = - cursor.getColumnIndex(FilteredNumberContract.FilteredNumberColumns.CREATION_TIME); - cursor.moveToFirst(); - assertEquals(cursor.getLong(creationTimeIndex), TEST_TIME); - cursor.close(); - } - - @Override - protected void tearDown() throws Exception { - getProvider().closeDb(); - super.tearDown(); - } - - private ContentValues getTestValues(Long timeNow) { - ContentValues v = new ContentValues(); - v.putNull(FilteredNumberContract.FilteredNumberColumns._ID); - v.put(FilteredNumberContract.FilteredNumberColumns.NORMALIZED_NUMBER, - TEST_NORMALIZED_NUMBER); - v.put(FilteredNumberContract.FilteredNumberColumns.NUMBER, TEST_NUMBER); - v.put(FilteredNumberContract.FilteredNumberColumns.COUNTRY_ISO, DEFAULT_COUNTRY_ISO); - v.put(FilteredNumberContract.FilteredNumberColumns.TIMES_FILTERED, 0); - v.putNull(FilteredNumberContract.FilteredNumberColumns.LAST_TIME_FILTERED); - v.put(FilteredNumberContract.FilteredNumberColumns.CREATION_TIME, timeNow); - v.put(FilteredNumberContract.FilteredNumberColumns.SOURCE, 1); - v.put(FilteredNumberContract.FilteredNumberColumns.TYPE, 1); - return v; - } - - private void assertCursorValues(Cursor cursor, ContentValues expectedValues) { - ContentValues v = new ContentValues(); - DatabaseUtils.cursorRowToContentValues(cursor, v); - v.remove(FilteredNumberContract.FilteredNumberColumns._ID); - expectedValues.remove(FilteredNumberContract.FilteredNumberColumns._ID); - assertEquals(v.toString(), expectedValues.toString()); - } - - public static class TestFilteredNumberProvider extends FilteredNumberProvider { - private DialerDatabaseHelper mDialerDatabaseHelper; - - @Override - protected DialerDatabaseHelper getDatabaseHelper(Context context) { - if (mDialerDatabaseHelper == null) { - mDialerDatabaseHelper = DialerDatabaseHelper.getNewInstanceForTest(context); - } - return mDialerDatabaseHelper; - } - - protected void closeDb() { - mDialerDatabaseHelper.close(); - } - - @Override - protected long getCurrentTimeMs() { - return TEST_TIME; - } - } -} diff --git a/tests/src/com/android/dialer/database/SmartDialPrefixTest.java b/tests/src/com/android/dialer/database/SmartDialPrefixTest.java deleted file mode 100644 index 78962e3f4..000000000 --- a/tests/src/com/android/dialer/database/SmartDialPrefixTest.java +++ /dev/null @@ -1,523 +0,0 @@ -/* - * Copyright (C) 2013 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.dialer.database; - -import static com.android.dialer.database.DatabaseTestUtils.*; - -import android.database.MatrixCursor; -import android.database.sqlite.SQLiteDatabase; -import android.test.suitebuilder.annotation.SmallTest; -import android.test.AndroidTestCase; - -import com.android.dialer.database.DialerDatabaseHelper; -import com.android.dialer.database.DialerDatabaseHelper.ContactNumber; -import com.android.dialer.dialpad.SmartDialNameMatcher; -import com.android.dialer.dialpad.SmartDialPrefix; - -import java.lang.Exception; -import java.lang.Override; -import java.lang.String; -import java.util.ArrayList; - -/** - * To run this test, use the command: - * adb shell am instrument -w -e class com.android.dialer.database.SmartDialPrefixTest / - * com.android.dialer.tests/android.test.InstrumentationTestRunner - */ -@SmallTest -public class SmartDialPrefixTest extends AndroidTestCase { - - private DialerDatabaseHelper mTestHelper; - - public void testIsCountryNanp_CaseInsensitive() { - assertFalse(SmartDialPrefix.isCountryNanp(null)); - assertFalse(SmartDialPrefix.isCountryNanp("CN")); - assertFalse(SmartDialPrefix.isCountryNanp("HK")); - assertFalse(SmartDialPrefix.isCountryNanp("uk")); - assertFalse(SmartDialPrefix.isCountryNanp("sg")); - assertTrue(SmartDialPrefix.isCountryNanp("US")); - assertTrue(SmartDialPrefix.isCountryNanp("CA")); - assertTrue(SmartDialPrefix.isCountryNanp("AS")); - assertTrue(SmartDialPrefix.isCountryNanp("AI")); - assertTrue(SmartDialPrefix.isCountryNanp("AG")); - assertTrue(SmartDialPrefix.isCountryNanp("BS")); - assertTrue(SmartDialPrefix.isCountryNanp("BB")); - assertTrue(SmartDialPrefix.isCountryNanp("bm")); - assertTrue(SmartDialPrefix.isCountryNanp("vg")); - assertTrue(SmartDialPrefix.isCountryNanp("ky")); - assertTrue(SmartDialPrefix.isCountryNanp("dm")); - assertTrue(SmartDialPrefix.isCountryNanp("do")); - assertTrue(SmartDialPrefix.isCountryNanp("gd")); - assertTrue(SmartDialPrefix.isCountryNanp("gu")); - assertTrue(SmartDialPrefix.isCountryNanp("jm")); - assertTrue(SmartDialPrefix.isCountryNanp("pr")); - assertTrue(SmartDialPrefix.isCountryNanp("ms")); - assertTrue(SmartDialPrefix.isCountryNanp("mp")); - assertTrue(SmartDialPrefix.isCountryNanp("kn")); - assertTrue(SmartDialPrefix.isCountryNanp("lc")); - assertTrue(SmartDialPrefix.isCountryNanp("vc")); - assertTrue(SmartDialPrefix.isCountryNanp("tt")); - assertTrue(SmartDialPrefix.isCountryNanp("tc")); - assertTrue(SmartDialPrefix.isCountryNanp("vi")); - } - - @Override - protected void setUp() { - mTestHelper = DialerDatabaseHelper.getNewInstanceForTest(getContext()); - } - - @Override - protected void tearDown() throws Exception { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - mTestHelper.removeAllContacts(db); - super.tearDown(); - } - - private ArrayList<ContactNumber> getLooseMatchesFromDb(String query) { - final SmartDialNameMatcher nameMatcher = new SmartDialNameMatcher(query, - SmartDialPrefix.getMap()); - return mTestHelper.getLooseMatches(query, nameMatcher); - } - - public void testPutForFullName() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber jasonsmith = constructNewContactWithDummyIds(contactCursor, nameCursor, - "", 0, "Jason Smith"); - final ContactNumber jasonsmitt = constructNewContactWithDummyIds(contactCursor, nameCursor, - "", 1, "Jason Smitt"); - final ContactNumber alphabet = constructNewContactWithDummyIds(contactCursor, nameCursor, - "12345678", 2, "abc def ghi jkl mno pqrs tuv wxyz"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - final ArrayList<ContactNumber> result1 = getLooseMatchesFromDb("5276676484"); - assertFalse(result1.contains(jasonsmitt)); - - final ArrayList<ContactNumber> result2 = getLooseMatchesFromDb("5276676488"); - assertFalse(result2.contains(jasonsmith)); - assertTrue(result2.contains(jasonsmitt)); - - assertTrue(getLooseMatchesFromDb("22233344455566677778889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("33344455566677778889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("44455566677778889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("55566677778889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("66677778889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("77778889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("8889999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("9999").contains(alphabet)); - - // Makes sure the phone number is correctly added. - assertTrue(getLooseMatchesFromDb("12345678").contains(alphabet)); - } - - public void testPutForPartialName() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber maryjane = constructNewContactWithDummyIds(contactCursor, nameCursor, - "", 0, "Mary Jane"); - final ContactNumber sarahsmith = constructNewContactWithDummyIds(contactCursor, nameCursor, - "", 1, "Sarah Smith"); - final ContactNumber jasonsmitt = constructNewContactWithDummyIds(contactCursor, nameCursor, - "", 2, "Jason Smitt"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - final ArrayList<ContactNumber> result1 = getLooseMatchesFromDb("6279"); - assertTrue(result1.contains(maryjane)); - assertFalse(result1.contains(jasonsmitt)); - - // 72 corresponds to sa = "Sarah Smith" but not "Jason Smitt" or "Mary Jane" - final ArrayList<ContactNumber> result2 = getLooseMatchesFromDb("72"); - assertFalse(result2.contains(maryjane)); - assertTrue(result2.contains(sarahsmith)); - assertFalse(result2.contains(jasonsmitt)); - - // 76 corresponds to sm = "Sarah Smith" and "Jason Smitt" but not "Mary Jane" - final ArrayList<ContactNumber> result3 = getLooseMatchesFromDb("76"); - assertFalse(result3.contains(maryjane)); - assertTrue(result3.contains(sarahsmith)); - assertTrue(result3.contains(jasonsmitt)); - } - - public void testPutForNameTokens() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber jasonfwilliams = constructNewContactWithDummyIds(contactCursor, - nameCursor, "", 0, "Jason F. Williams"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("527").contains(jasonfwilliams)); - // 72 corresponds to sa = "Sarah Smith" but not "Jason Smitt" or "Mary Jane" - assertTrue(getLooseMatchesFromDb("945").contains(jasonfwilliams)); - // 76 corresponds to sm = "Sarah Smith" and "Jason Smitt" but not "Mary Jane" - assertFalse(getLooseMatchesFromDb("66").contains(jasonfwilliams)); - } - - public void testPutForInitialMatches() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber martinjuniorharry = constructNewContactWithDummyIds(contactCursor, - nameCursor, "", 0, "Martin Jr Harry"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - // 654 corresponds to mjh = "(M)artin (J)r (H)arry" - assertTrue(getLooseMatchesFromDb("654").contains(martinjuniorharry)); - // The reverse (456) does not match (for now) - assertFalse(getLooseMatchesFromDb("456").contains(martinjuniorharry)); - // 6542 corresponds to mjha = "(M)artin (J)r (Ha)rry" - assertTrue(getLooseMatchesFromDb("6542").contains(martinjuniorharry)); - // 542 corresponds to jha = "Martin (J)r (Ha)rry" - assertTrue(getLooseMatchesFromDb("542").contains(martinjuniorharry)); - // 642 corresponds to mha = "(M)artin Jr (Ha)rry" - assertTrue(getLooseMatchesFromDb("642").contains(martinjuniorharry)); - // 6542779 (M)artin (J)r (Harry) - assertTrue(getLooseMatchesFromDb("6542779").contains(martinjuniorharry)); - // 65742779 (M)artin (Jr) (Harry) - assertTrue(getLooseMatchesFromDb("65742779").contains(martinjuniorharry)); - // 542779 Martin (J)r (Harry) - assertTrue(getLooseMatchesFromDb("542779").contains(martinjuniorharry)); - // 547 doesn't match - assertFalse(getLooseMatchesFromDb("547").contains(martinjuniorharry)); - // 655 doesn't match - assertFalse(getLooseMatchesFromDb("655").contains(martinjuniorharry)); - // 653 doesn't match - assertFalse(getLooseMatchesFromDb("653").contains(martinjuniorharry)); - // 6543 doesn't match - assertFalse(getLooseMatchesFromDb("6543").contains(martinjuniorharry)); - - // 7 actual rows, + 1 for the dummy number we added - assertEquals(8, mTestHelper.countPrefixTableRows(db)); - } - - public void testPutForInitialMatchesForLongTokenNames() { - - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber alphabet = constructNewContactWithDummyIds(contactCursor, nameCursor, - "12345678", 0, "abc def ghi jkl mno pqrs tuv wxyz"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - // Makes sure only only the first two and last two token are considered for initials. - // The cut-off constant can be set in SmartDialPrefix.java - assertTrue(getLooseMatchesFromDb("2389999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("239999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("23888").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("2333").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("289999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("2888").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("29999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("3888").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("39999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("389999").contains(alphabet)); - assertTrue(getLooseMatchesFromDb("89999").contains(alphabet)); - } - - public void testCheckLongToken() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber alphabet = constructNewContactWithDummyIds(contactCursor, nameCursor, - "1", 0, " aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk llll mmmm nnnn" + - " oooo pppp qqqq rrrr ssss tttt uuuu vvvv wwww xxxx yyyy zzzz"); - - final ContactNumber alphabet2 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "1", 1, "aaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrr" + - "ssssttttuuuuvvvvwwwwxxxxyyyyzzzz"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("2222").contains(alphabet)); - assertEquals(40, mTestHelper.countPrefixTableRows(db)); - } - - public void testAccentedCharacters() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber reene = constructNewContactWithDummyIds(contactCursor, nameCursor, - "0", 0, "Reenée"); - final ContactNumber bronte = constructNewContactWithDummyIds(contactCursor, nameCursor, - "0", 1, "Brontë"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("733633").contains(reene)); - assertTrue(getLooseMatchesFromDb("276683").contains(bronte)); - } - - public void testNumbersInName() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber contact = constructNewContactWithDummyIds(contactCursor, nameCursor, - "0", 0, "12345678"); - final ContactNumber teacher = constructNewContactWithDummyIds(contactCursor, nameCursor, - "0", 1, "1st Grade Teacher"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("12345678").contains(contact)); - assertTrue(getLooseMatchesFromDb("17847233").contains(teacher)); - assertTrue(getLooseMatchesFromDb("14832").contains(teacher)); - } - - public void testPutForNumbers() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber contactno1 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "510-527-2357", 0, "James"); - final ContactNumber contactno2 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "77212862357", 1, "James"); - final ContactNumber contactno3 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+13684976334", 2, "James"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("510").contains(contactno1)); - assertFalse(getLooseMatchesFromDb("511").contains(contactno1)); - assertTrue(getLooseMatchesFromDb("77212862357").contains(contactno2)); - assertFalse(getLooseMatchesFromDb("77212862356").contains(contactno2)); - assertTrue(getLooseMatchesFromDb("1368").contains(contactno3)); - assertFalse(getLooseMatchesFromDb("1367").contains(contactno3)); - } - - public void testPutNumbersCountryCode() { - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber contactno1 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+13684976334", 0, "James"); - final ContactNumber contactno2 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+65 9177-6930", 1, "Jason"); - final ContactNumber contactno3 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+85212345678", 2, "Mike"); - final ContactNumber contactno4 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+85112345678", 3, "Invalid"); - final ContactNumber contactno5 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+852", 4, "Invalid"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("1368").contains(contactno1)); - assertTrue(getLooseMatchesFromDb("368497").contains(contactno1)); - assertFalse(getLooseMatchesFromDb("2368497").contains(contactno1)); - - assertTrue(getLooseMatchesFromDb("6591776930").contains(contactno2)); - assertTrue(getLooseMatchesFromDb("91776930").contains(contactno2)); - assertFalse(getLooseMatchesFromDb("591776930").contains(contactno2)); - - assertTrue(getLooseMatchesFromDb("85212345678").contains(contactno3)); - assertTrue(getLooseMatchesFromDb("12345678").contains(contactno3)); - assertFalse(getLooseMatchesFromDb("5212345678").contains(contactno3)); - - assertTrue(getLooseMatchesFromDb("85112345678").contains(contactno4)); - assertFalse(getLooseMatchesFromDb("12345678").contains(contactno4)); - } - - // Tests special case handling for NANP numbers - public void testPutNumbersNANP() { - SmartDialPrefix.setUserInNanpRegion(true); - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - final ContactNumber contactno1 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "16503337596", 0, "James"); - final ContactNumber contactno2 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "5109921234", 1, "Michael"); - final ContactNumber contactno3 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "(415)-123-4567", 2, "Jason"); - final ContactNumber contactno4 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "1 510-284-9170", 3, "Mike"); - final ContactNumber contactno5 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "1-415-123-123", 4, "Invalid"); - final ContactNumber contactno6 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "415-123-123", 5, "Invalid2"); - final ContactNumber contactno7 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+1-510-284-9170", 6, "Mike"); - final ContactNumber contactno8 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+1-510-284-917", 7, "Invalid"); - final ContactNumber contactno9 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "+857-510-284-9170", 8, "Inv"); - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("16503337596").contains(contactno1)); - assertTrue(getLooseMatchesFromDb("6503337596").contains(contactno1)); - assertTrue(getLooseMatchesFromDb("3337596").contains(contactno1)); - - assertTrue(getLooseMatchesFromDb("5109921234").contains(contactno2)); - assertTrue(getLooseMatchesFromDb("9921234").contains(contactno2)); - - assertTrue(getLooseMatchesFromDb("4151234567").contains(contactno3)); - assertTrue(getLooseMatchesFromDb("1234567").contains(contactno3)); - - assertTrue(getLooseMatchesFromDb("15102849170").contains(contactno4)); - assertTrue(getLooseMatchesFromDb("5102849170").contains(contactno4)); - assertTrue(getLooseMatchesFromDb("2849170").contains(contactno4)); - - assertTrue(getLooseMatchesFromDb("1415123123").contains(contactno5)); - assertFalse(getLooseMatchesFromDb("415123123").contains(contactno5)); - assertFalse(getLooseMatchesFromDb("123123").contains(contactno5)); - - assertTrue(getLooseMatchesFromDb("415123123").contains(contactno6)); - assertFalse(getLooseMatchesFromDb("123123").contains(contactno6)); - - assertTrue(getLooseMatchesFromDb("15102849170").contains(contactno7)); - assertTrue(getLooseMatchesFromDb("5102849170").contains(contactno7)); - assertTrue(getLooseMatchesFromDb("2849170").contains(contactno7)); - assertFalse(getLooseMatchesFromDb("849170").contains(contactno7)); - assertFalse(getLooseMatchesFromDb("10849170").contains(contactno7)); - - assertTrue(getLooseMatchesFromDb("1510284917").contains(contactno8)); - assertTrue(getLooseMatchesFromDb("510284917").contains(contactno8)); - assertFalse(getLooseMatchesFromDb("2849170").contains(contactno8)); - - assertTrue(getLooseMatchesFromDb("8575102849170").contains(contactno9)); - assertFalse(getLooseMatchesFromDb("5102849170").contains(contactno9)); - assertFalse(getLooseMatchesFromDb("2849170").contains(contactno9)); - - // TODO(klp) Adds test for non-NANP region number matchings. - } - - // Tests special case handling for non-NANP numbers - public void testPutNumbersNonNANP() { - SmartDialPrefix.setUserInNanpRegion(false); - final SQLiteDatabase db = mTestHelper.getWritableDatabase(); - - final MatrixCursor nameCursor = constructNewNameCursor(); - final MatrixCursor contactCursor = constructNewContactCursor(); - - final ContactNumber contactno0 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "(415)-123-4567", 0, "Jason"); - final ContactNumber contactno1 = constructNewContactWithDummyIds(contactCursor, nameCursor, - "1 510-284-9170", 1, "Mike"); - - - mTestHelper.insertUpdatedContactsAndNumberPrefix(db, contactCursor, Long.valueOf(0)); - mTestHelper.insertNamePrefixes(db, nameCursor); - - nameCursor.close(); - contactCursor.close(); - - assertTrue(getLooseMatchesFromDb("4151234567").contains(contactno0)); - assertFalse(getLooseMatchesFromDb("1234567").contains(contactno0)); - - assertTrue(getLooseMatchesFromDb("15102849170").contains(contactno1)); - assertFalse(getLooseMatchesFromDb("5102849170").contains(contactno1)); - assertFalse(getLooseMatchesFromDb("2849170").contains(contactno1)); - } - - public void testParseInfo() { - final String name = "Mcdonald Jamie-Cullum"; - final ArrayList<String> info = SmartDialPrefix.parseToIndexTokens(name); - assertEquals(3, info.size()); - assertEquals(8, info.get(0).length()); - assertEquals(5, info.get(1).length()); - assertEquals(6, info.get(2).length()); - - final String name2 = "aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk"; - final ArrayList<String> info2 = SmartDialPrefix.parseToIndexTokens(name2); - assertEquals(11, info2.size()); - assertEquals(3, info2.get(0).length()); - assertEquals(3, info2.get(10).length()); - - final String name3 = "this is- a,test name"; - final ArrayList<String> info3 = SmartDialPrefix.parseToIndexTokens(name3); - assertEquals(5, info3.size()); - assertEquals(2, info3.get(1).length()); - assertEquals(1, info3.get(2).length()); - assertEquals(4, info3.get(3).length()); - assertEquals(4, info3.get(4).length()); - - final String name4 = "M c-Donald James"; - final ArrayList<String> info4 = SmartDialPrefix.parseToIndexTokens(name4); - assertEquals(4, info4.size()); - assertEquals(1, info4.get(1).length()); - assertEquals(6, info4.get(2).length()); - - final String name5 = " Aa'Bb c dddd e'e"; - final ArrayList<String> info5 = SmartDialPrefix.parseToIndexTokens(name5); - assertEquals(6, info5.size()); - assertEquals(2, info5.get(0).length()); - assertEquals(1, info5.get(5).length()); - } -} diff --git a/tests/src/com/android/dialer/database/VoicemailArchiveProviderTest.java b/tests/src/com/android/dialer/database/VoicemailArchiveProviderTest.java deleted file mode 100644 index abc2dc5b0..000000000 --- a/tests/src/com/android/dialer/database/VoicemailArchiveProviderTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.database; - -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.test.ProviderTestCase2; -import android.test.mock.MockContentResolver; -import com.android.dialer.database.VoicemailArchiveContract.VoicemailArchive; - -import java.io.File; -import java.io.OutputStream; - -/** - * Tests for {@link VoicemailArchiveProvider}. - */ -public class VoicemailArchiveProviderTest extends - ProviderTestCase2<VoicemailArchiveProviderTest.TestVoicemailArchiveProvider> { - private static final String TEST_MIME_TYPE = "audio/mp3"; - private static final String TEST_NUMBER = "+1412555555"; - private static final int TEST_ARCHIVED = 1; - private static final String TEST_STRING = "TEST"; - - private MockContentResolver mResolver; - private Cursor mCursor; - private Uri mVoicemailUri; - - public VoicemailArchiveProviderTest() { - super(TestVoicemailArchiveProvider.class, VoicemailArchiveContract.AUTHORITY); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - mResolver = getMockContentResolver(); - } - - @Override - protected void tearDown() throws Exception { - if (mCursor != null) { - mCursor.close(); - } - // Need to delete test.cache folder created by {@link android.test.ProviderTestCase2} - deleteRecursive(getContext().getCacheDir()); - getProvider().closeDb(); - super.tearDown(); - } - - public void testInsert() { - insertVoicemail(); - assertNotNull(mVoicemailUri); - assertTrue(doesRowExist()); - long id = ContentUris.parseId(mVoicemailUri); - assertTrue(id > 0); - } - - public void testQuery_createFile() throws Exception { - insertVoicemail(); - assertTrue(doesRowExist()); - assertFalse(doesFileExist()); - createFile(); - assertTrue(doesFileExist()); - } - - public void testQuery_createFileMimeTypeIsAMR() throws Exception { - insertVoicemailWithMimeType("audio/amr"); - assertTrue(doesRowExist()); - assertFalse(doesFileExist()); - createFile(); - assertTrue(doesFileExist()); - assertEquals("amr", getFileExtension(getFilePath())); - } - - public void testQuery_createFileMimeTypeIsMP3() throws Exception { - insertVoicemailWithMimeType("audio/mpeg"); - assertTrue(doesRowExist()); - assertFalse(doesFileExist()); - createFile(); - assertTrue(doesFileExist()); - assertEquals("mp3", getFileExtension(getFilePath())); - } - - public void testQuery_createFileMimeTypeNotExists() throws Exception { - insertVoicemailWithMimeType(TEST_STRING); - assertTrue(doesRowExist()); - assertFalse(doesFileExist()); - createFile(); - assertTrue(doesFileExist()); - assertEquals("", getFileExtension(getFilePath())); - } - - public void testQuery() { - insertVoicemail(); - updateCursor(); - assertCursorCount(1); - assertContentValues(); - } - - public void testQuery_correctValuesSelection() { - insertVoicemail(); - updateCursorWithIdQuery(); - assertCursorCount(1); - assertContentValues(); - } - - public void testQuery_illegalUri() { - try { - mResolver.query(Uri.withAppendedPath(VoicemailArchive.CONTENT_URI, TEST_STRING), - null, null, null, null); - fail("Expecting exception but none was thrown."); - } catch (IllegalArgumentException e) {} - } - - public void testUpdate() throws Exception { - insertVoicemail(); - assertTrue(doesRowExist()); - ContentValues values = new ContentValues(); - values.put(VoicemailArchive.MIME_TYPE, TEST_STRING); - values.put(VoicemailArchive.NUMBER, TEST_STRING); - values.put(VoicemailArchive.ARCHIVED, false); - mResolver.update(mVoicemailUri, values, null, null); - updateCursor(); - assertEquals(TEST_STRING, mCursor.getString(mCursor.getColumnIndex(VoicemailArchive.MIME_TYPE))); - assertEquals(TEST_STRING, mCursor.getString(mCursor.getColumnIndex(VoicemailArchive.NUMBER))); - assertEquals(false, mCursor.getInt( - mCursor.getColumnIndex(VoicemailArchive.ARCHIVED)) == 1); - } - - public void testUpdate_selection() throws Exception { - insertVoicemail(); - assertTrue(doesRowExist()); - ContentValues values = new ContentValues(); - values.put(VoicemailArchive.MIME_TYPE, TEST_STRING); - values.put(VoicemailArchive.NUMBER, TEST_STRING); - values.put(VoicemailArchive.ARCHIVED, false); - mResolver.update(VoicemailArchive.CONTENT_URI, values, getIdQuery(), null); - updateCursor(); - assertEquals(TEST_STRING, mCursor.getString(mCursor.getColumnIndex(VoicemailArchive.MIME_TYPE))); - assertEquals(TEST_STRING, mCursor.getString(mCursor.getColumnIndex(VoicemailArchive.NUMBER))); - assertEquals(false, mCursor.getInt( - mCursor.getColumnIndex(VoicemailArchive.ARCHIVED)) == 1); - } - - public void testUpdate_illegalUri() { - try { - mResolver.update(Uri.withAppendedPath(VoicemailArchive.CONTENT_URI, TEST_STRING), - null, null, null); - fail("Expecting exception but none was thrown."); - } catch (IllegalArgumentException e) {} - } - - public void testDelete() throws Exception { - insertVoicemail(); - createFile(); - assertTrue(doesRowExist()); - assertTrue(doesFileExist()); - mResolver.delete(mVoicemailUri, null, null); - assertFalse(doesRowExist()); - assertFalse(doesFileExist()); - } - - public void testDelete_selection() throws Exception{ - insertVoicemail(); - createFile(); - assertTrue(doesRowExist()); - assertTrue(doesFileExist()); - mResolver.delete(VoicemailArchive.CONTENT_URI, getIdQuery(), null); - assertFalse(doesRowExist()); - assertFalse(doesFileExist()); - } - - public void testDelete_illegalUri() { - try { - mResolver.delete(Uri.withAppendedPath(VoicemailArchive.CONTENT_URI, TEST_STRING), - null, null); - fail("Expecting exception but none was thrown."); - } catch (IllegalArgumentException e) {} - } - - private boolean doesRowExist() { - Cursor tempCursor = mResolver.query(mVoicemailUri, null, null, null, null); - boolean rowExists = tempCursor != null && tempCursor.getCount() > 0; - tempCursor.close(); - return rowExists; - } - - private boolean doesFileExist() { - File voicemailFile = new File(getFilePath()); - return voicemailFile.exists(); - } - - private static String getFileExtension(String filePath) { - File file = new File(filePath); - String fileName = file.getName(); - int index = fileName.lastIndexOf("."); - return index > 0 ? fileName.substring(index + 1) : ""; - } - - private void assertCursorCount(int count) { - assertEquals(count, mCursor.getCount()); - } - - private void assertContentValues() { - assertEquals(TEST_MIME_TYPE, mCursor - .getString(mCursor.getColumnIndex(VoicemailArchive.MIME_TYPE))); - assertEquals(TEST_NUMBER, mCursor - .getString(mCursor.getColumnIndex(VoicemailArchive.NUMBER))); - assertEquals(TEST_ARCHIVED, mCursor - .getInt(mCursor.getColumnIndex(VoicemailArchive.ARCHIVED))); - } - - private void insertVoicemail() { - mVoicemailUri = mResolver.insert(VoicemailArchive.CONTENT_URI, getTestValues()); - } - - private void insertVoicemailWithMimeType(String mimeType) { - ContentValues values = getTestValues(); - values.put(VoicemailArchive.MIME_TYPE, mimeType); - mVoicemailUri = mResolver.insert(VoicemailArchive.CONTENT_URI, values); - } - - private void updateCursor() { - mCursor = mResolver.query(mVoicemailUri, null, null, null, null); - assertEquals(true, mCursor.getCount() > 0); - mCursor.moveToFirst(); - } - - private void updateCursorWithIdQuery() { - mCursor = mResolver.query(mVoicemailUri, null, getIdQuery(), null, null); - assertEquals(true, mCursor.getCount() > 0); - mCursor.moveToFirst(); - } - - private void createFile() throws Exception { - assertFalse(doesFileExist()); - // Opening output stream and closing it should create the file - OutputStream outputStream = mResolver.openOutputStream(mVoicemailUri); - outputStream.close(); - } - - private String getIdQuery() { - return VoicemailArchive._ID + "=" + ContentUris.parseId(mVoicemailUri); - } - - private String getFilePath() { - if (mCursor == null) { - updateCursor(); - } - return mCursor.getString(mCursor.getColumnIndex(VoicemailArchive._DATA)); - } - - private static ContentValues getTestValues() { - ContentValues values = new ContentValues(); - values.put(VoicemailArchive.NUMBER, TEST_NUMBER); - values.put(VoicemailArchive.MIME_TYPE, TEST_MIME_TYPE); - values.put(VoicemailArchive.ARCHIVED, TEST_ARCHIVED); - return values; - } - - private void deleteRecursive(File fileOrDirectory) { - if (fileOrDirectory.isDirectory()) { - for (File child : fileOrDirectory.listFiles()) { - deleteRecursive(child); - } - } - fileOrDirectory.delete(); - } - - public static class TestVoicemailArchiveProvider extends VoicemailArchiveProvider { - private DialerDatabaseHelper mDialerDatabaseHelper; - - @Override - protected File getFilesDir() { - return getContext().getCacheDir(); - } - - @Override - protected DialerDatabaseHelper getDatabaseHelper(Context context) { - if (mDialerDatabaseHelper == null) { - mDialerDatabaseHelper = DialerDatabaseHelper.getNewInstanceForTest(context); - } - return mDialerDatabaseHelper; - } - - protected void closeDb() { - mDialerDatabaseHelper.close(); - } - } -} diff --git a/tests/src/com/android/dialer/dialpad/DialpadFragmentInstrumentationTest.java b/tests/src/com/android/dialer/dialpad/DialpadFragmentInstrumentationTest.java deleted file mode 100644 index 876c13ba1..000000000 --- a/tests/src/com/android/dialer/dialpad/DialpadFragmentInstrumentationTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.android.dialer.dialpad; - -import android.test.ActivityInstrumentationTestCase2; -import android.view.View; - -import com.android.dialer.DialtactsActivity; -import com.android.dialer.R; - -/** - * Tests that rely on instrumenting an actual instance of a {@link DialpadFragment}. - */ -public class DialpadFragmentInstrumentationTest extends - ActivityInstrumentationTestCase2<DialtactsActivity> { - private DialtactsActivity mActivity; - - public DialpadFragmentInstrumentationTest() { - super(DialtactsActivity.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - mActivity = getActivity(); - } - - /** - * Simulates a long click event on the zero key with a prior onPressed callback. - * - */ - public void testManualLongClickZero_DeletesPreviousCharacter() { - final DialpadFragment fragment = showDialpad(); - pressAndReleaseKey(9, fragment); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - final View zeroKey = findViewByDigit(0, fragment); - fragment.onPressed(zeroKey, true); - fragment.onLongClick(zeroKey); - } - }); - - assertEquals("9+", fragment.getDigitsWidget().getText().toString()); - } - - /** - * Simulates a long click event on the zero key without a prior onPressed - * callback. - */ - public void testSystemLongClickZero_PreservesPreviousCharacter() { - final DialpadFragment fragment = showDialpad(); - pressAndReleaseKey(9, fragment); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - final View zeroKey = findViewByDigit(0, fragment); - fragment.onLongClick(zeroKey); - } - }); - - assertEquals("9+", fragment.getDigitsWidget().getText().toString()); - } - - private DialpadFragment showDialpad() { - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mActivity.showDialpad(); - } - }); - getInstrumentation().waitForIdleSync(); - return (DialpadFragment) mActivity.getFragmentManager().findFragmentByTag( - DialtactsActivity.TAG_DIALPAD_FRAGMENT); - } - - private void pressAndReleaseKey(int digit, final DialpadFragment fragment) { - final View dialpadKey = findViewByDigit(digit, fragment); - final String digitsBefore = fragment.getDigitsWidget().getText().toString(); - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - fragment.onPressed(dialpadKey, true); - fragment.onPressed(dialpadKey, false); - } - }); - assertEquals(digitsBefore + String.valueOf(digit), - fragment.getDigitsWidget().getText().toString()); - } - - private View findViewByDigit(int digit, DialpadFragment fragment) { - return fragment.getView().findViewById(getViewIdByDigit(digit)); - } - - private int getViewIdByDigit(int digit) { - switch (digit) { - case 0: - return R.id.zero; - case 1: - return R.id.one; - case 2: - return R.id.two; - case 3: - return R.id.three; - case 4: - return R.id.four; - case 5: - return R.id.five; - case 6: - return R.id.six; - case 7: - return R.id.seven; - case 8: - return R.id.eight; - case 9: - return R.id.nine; - default: - return 0; - } - } -} diff --git a/tests/src/com/android/dialer/dialpad/DialpadFragmentTest.java b/tests/src/com/android/dialer/dialpad/DialpadFragmentTest.java deleted file mode 100644 index 3015e87ff..000000000 --- a/tests/src/com/android/dialer/dialpad/DialpadFragmentTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2012 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.dialer.dialpad; - -import android.test.suitebuilder.annotation.SmallTest; - -import junit.framework.TestCase; - -/** Unit tests for {@link DialpadFragment}. */ -@SmallTest -public class DialpadFragmentTest extends TestCase { - - public void testCanAddDigit_Valid() { - // end, middle, selection to end, middle selection - assertTrue(DialpadFragment.canAddDigit("123", 3, 3, ';')); - assertTrue(DialpadFragment.canAddDigit("123", 1, 1, ',')); - assertTrue(DialpadFragment.canAddDigit("123", 1, 3, ';')); - assertTrue(DialpadFragment.canAddDigit("123", 1, 2, ',')); - } - - public void testCanAddDigit_InvalidCharacter() { - // only handles wait/pause - try { - DialpadFragment.canAddDigit("123", 1, 1, '5'); - fail("Calling canAddDigit with invalid character should throw an exception"); - } catch (IllegalArgumentException e) { - } - } - - public void testCanAddDigit_BadOrNoSelection() { - // no selection - assertFalse(DialpadFragment.canAddDigit("123", -1, -1, ';')); - assertFalse(DialpadFragment.canAddDigit("123", -1, 1, ',')); - - // start > end - assertFalse(DialpadFragment.canAddDigit("123", 2, 1, ',')); - } - - public void testCanAddDigit_OutOfBounds() { - // start or end is > digits.length() - assertFalse(DialpadFragment.canAddDigit("123", 1, 4, ';')); - assertFalse(DialpadFragment.canAddDigit("123", 4, 4, ',')); - } - - public void testCanAddDigit_AsFirstCharacter() { - assertFalse(DialpadFragment.canAddDigit("", 0, 0, ',')); - assertFalse(DialpadFragment.canAddDigit("123", 0, 0, ';')); - assertFalse(DialpadFragment.canAddDigit("123", 0, 2, ',')); - assertFalse(DialpadFragment.canAddDigit("123", 0, 3, ',')); - } - - public void testCanAddDigit_AdjacentCharacters_Before() { - // before - assertFalse(DialpadFragment.canAddDigit("55;55", 2, 2, ';')); // WAIT - assertFalse(DialpadFragment.canAddDigit("55;55", 1, 2, ';')); - assertTrue(DialpadFragment.canAddDigit("55,55", 2, 2, ',')); // PAUSE - assertTrue(DialpadFragment.canAddDigit("55,55", 1, 2, ',')); - assertTrue(DialpadFragment.canAddDigit("55;55", 2, 2, ',')); // WAIT & PAUSE - assertTrue(DialpadFragment.canAddDigit("55,55", 1, 2, ';')); - } - - public void testCanAddDigit_AdjacentCharacters_After() { - // after - assertFalse(DialpadFragment.canAddDigit("55;55", 3, 3, ';')); // WAIT - assertFalse(DialpadFragment.canAddDigit("55;55", 3, 4, ';')); - assertTrue(DialpadFragment.canAddDigit("55,55", 3, 3, ',')); // PAUSE - assertTrue(DialpadFragment.canAddDigit("55,55", 3, 4, ',')); - assertTrue(DialpadFragment.canAddDigit("55;55", 3, 3, ',')); // WAIT & PAUSE - assertTrue(DialpadFragment.canAddDigit("55,55", 3, 4, ';')); - } - - public void testGetFormattedDigits_NoPostDialString() { - assertEquals("(510) 333-7596", - DialpadFragment.getFormattedDigits("5103337596", null, "US")); - assertEquals("(510) 333-7596", - DialpadFragment.getFormattedDigits("5103337596", "+15103337596", "US")); - } - - public void testGetFormattedDigits_WithPostDialString() { - assertEquals("(510) 333-7596,1234", - DialpadFragment.getFormattedDigits("5103337596,1234", null, "US")); - assertEquals("(510) 333-7596;;1234", - DialpadFragment.getFormattedDigits("5103337596;;1234", null, "US")); - assertEquals("(510) 333-7596;123,,4", - DialpadFragment.getFormattedDigits("(510)3337596;123,,4", "+15103337596", "US")); - } - - public void testGetFormattedDigits_PostDialStringOnly() { - assertEquals(",1234567", DialpadFragment.getFormattedDigits(",1234567", null, "US")); - assertEquals(";4321", DialpadFragment.getFormattedDigits(";4321", null, "US")); - } - - public void testGetFormattedDigits_Invalid() { - assertEquals(null, DialpadFragment.getFormattedDigits(null, null, "US")); - assertEquals("", DialpadFragment.getFormattedDigits("", "+15104233335", "US")); - } -} diff --git a/tests/src/com/android/dialer/dialpad/SmartDialNameMatcherTest.java b/tests/src/com/android/dialer/dialpad/SmartDialNameMatcherTest.java deleted file mode 100644 index c1365f5cf..000000000 --- a/tests/src/com/android/dialer/dialpad/SmartDialNameMatcherTest.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (C) 2012 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.dialer.dialpad; - -import android.test.suitebuilder.annotation.SmallTest; -import android.test.suitebuilder.annotation.Suppress; -import android.util.Log; -import android.test.AndroidTestCase; - -import com.android.dialer.dialpad.SmartDialNameMatcher; -import com.android.dialer.dialpad.SmartDialPrefix; - -import java.text.Normalizer; -import java.util.ArrayList; - -import junit.framework.TestCase; - -@SmallTest -public class SmartDialNameMatcherTest extends TestCase { - private static final String TAG = "SmartDialNameMatcherTest"; - - public void testMatches() { - // Test to ensure that all alphabetic characters are covered - checkMatches("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", - "22233344455566677778889999" + "22233344455566677778889999", true, 0, 26 * 2); - // Should fail because of a mistyped 2 instead of 9 in the second last character - checkMatches("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", - "22233344455566677778889999" + "22233344455566677778889929", false, 0, 0); - - // Basic name test - checkMatches("joe", "5", true, 0, 1); - checkMatches("joe", "56", true, 0, 2); - checkMatches("joe", "563", true, 0, 3); - - // Matches only word boundary. - checkMatches("joe", "63", false, 0, 0); - checkMatches("joe oe", "63", true, 4, 6); - - // Test for a match across word boundaries - checkMatches("joe oe", "56363", true, 0, 6); - } - - public void testMatches_repeatedLetters() { - checkMatches("aaaaaaaaaa", "2222222222", true, 0, 10); - // Fails because of one extra 2 - checkMatches("aaaaaaaaaa", "22222222222", false, 0, 0); - checkMatches("zzzzzzzzzz zzzzzzzzzz", "99999999999999999999", true, 0, 21); - } - - public void testMatches_repeatedSpaces() { - checkMatches("William J Smith", "9455426576", true, 0, 17); - checkMatches("William J Smith", "576", true, 12, 17); - // Fails because we start at non-word boundary - checkMatches("William J Smith", "6576", false, 0, 0); - } - - - public void testMatches_Initial() { - // wjs matches (W)illiam (J)ohn (S)mith - checkMatches("William John Smith", "957", true, 0, 1, 8, 9, 13, 14); - // wjsmit matches (W)illiam (J)ohn (Smit)h - checkMatches("William John Smith", "957648", true, 0, 1, 8, 9, 13, 17); - // wjohn matches (W)illiam (John) Smith - checkMatches("William John Smith", "95646", true, 0, 1, 8, 12); - // jsmi matches William (J)ohn (Smi)th - checkMatches("William John Smith", "5764", true, 8, 9, 13, 16); - // make sure multiple spaces don't mess things up - checkMatches("William John Smith", "5764", true, 15, 16, 22, 25); - } - - public void testMatches_InitialWithSeparator() { - // wjs matches (W)illiam (J)ohn (S)mith - checkMatches("William John-Smith", "957", true, 0, 1, 8, 9, 13, 14); - // wjsmit matches (W)illiam (J)ohn-(OShe)a - checkMatches("William John-O'Shea", "956743", true, 0, 1, 8, 9, 13, 18); - // wjohn matches (W)illiam-(John) Smith - checkMatches("William-John Smith", "95646", true, 0, 1, 8, 12); - // jsmi matches William (J)ohn-(Smi)th - checkMatches("William John-Smith", "5764", true, 8, 9, 13, 16); - // wsmi matches (W)illiam John (Smi)th - checkMatches("William John-Smith", "9764", true, 0, 1, 13, 16); - // make sure multiple spaces don't mess things up - checkMatches("William John---Smith", "5764", true, 15, 16, 22, 25); - // match tokens that are located directly after a non-space separator (studio) - checkMatches("Berkeley Hair-Studio", "788346", true, 14, 20); - // match tokens with same initials - checkMatches("H.Harold", "427653", true, 2, 8); - // various matching combinations of tokens with similar initials - checkMatches("Yo-Yoghurt Land", "964487", true, 3, 9); - checkMatches("Yo-Yoghurt Land", "96448785263", true, 3, 15); - checkMatches("Yo-Yoghurt Land", "95263", true, 3, 4, 11, 15); - checkMatches("Yo-Yoghurt Land", "995263", true, 0, 1, 3, 4, 11, 15); - - checkMatches("ab zz ef", "23", true, 0, 1, 6, 7); - } - - public void testMatches_repeatedSeparators() { - // Simple match for single token - checkMatches("John,,,,,Doe", "5646", true, 0, 4); - // Match across tokens - checkMatches("John,,,,,Doe", "56463", true, 0, 10); - // Match token after chain of separators - checkMatches("John,,,,,Doe", "363", true, 9, 12); - } - - public void testMatches_LatinMix() { - // Latin + Chinese characters - checkMatches("Lee王力Wang宏", "59264", true, 0, 1, 5, 9); - // Latin + Japanese characters - checkMatches("千Abcd佳智Efgh佳IJKL", "222333444555", true, 1, 16); - // Latin + Arabic characters - checkMatches("Peterعبد الرحمنJames", "752637", true, 0, 1, 15, 20); - } - - public void testMatches_umlaut() { - checkMatches("ÄÖÜäöü", "268268", true, 0, 6); - } - - public void testMatches_NumberInName() { - // Number used as display name - checkMatches("+1-123-456-6789", "1234566789", true, 3, 15); - // Mix of numbers and letters - checkMatches("3rd Grade Teacher", "373", true, 0, 3); - checkMatches("1800 Win A Prize", "1800", true, 0, 4); - checkMatches("1800 Win A Prize", "1800946277493", true, 0, 16); - checkMatches("1800 Win A Prize", "977493", true, 5, 6, 11, 16); - } - - - // TODO: Great if it was treated as "s" or "ss. Figure out if possible without prefix trie? - @Suppress - public void testMatches_germanSharpS() { - checkMatches("ß", "s", true, 0, 1); - checkMatches("ß", "ss", true, 0, 1); - } - - // TODO: Add this and make it work - @Suppress - public void testMatches_greek() { - // http://en.wikipedia.org/wiki/Greek_alphabet - fail("Greek letters aren't supported yet."); - } - - // TODO: Add this and make it work - @Suppress - public void testMatches_cyrillic() { - // http://en.wikipedia.org/wiki/Cyrillic_script - fail("Cyrillic letters aren't supported yet."); - } - - - public void testMatches_NumberBasic() { - // Simple basic examples that start the match from the start of the number - checkMatchesNumber("5103337596", "510", true, 0, 3); - checkMatchesNumber("5103337596", "511", false, 0, 0); - checkMatchesNumber("5103337596", "5103337596", true, 0, 10); - checkMatchesNumber("123-456-789", "123456789", true, 0, 11); - checkMatchesNumber("123-456-789", "123456788", false, 0, 0); - checkMatchesNumber("09999999999", "099", true, 0, 3); - } - - public void testMatches_NumberWithCountryCode() { - // These matches should ignore the country prefix - // USA (+1) - checkMatchesNumber("+15103337596", "5103337596", true, 2, 12); - checkMatchesNumber("+15103337596", "15103337596", true, 0, 12); - - // Singapore (+65) - checkMatchesNumber("+6591776930", "6591", true, 0, 5); - checkMatchesNumber("+6591776930", "9177", true, 3, 7); - checkMatchesNumber("+6591776930", "5917", false, 3, 7); - - // Hungary (+36) - checkMatchesNumber("+3612345678", "361234", true, 0, 7); - checkMatchesNumber("+3612345678", "1234", true, 3, 7); - - // Hongkong (+852) - checkMatchesNumber("+852 2222 2222", "85222222222", true, 0, 14); - checkMatchesNumber("+852 2222 3333", "2222", true, 5, 9); - - // Invalid (+854) - checkMatchesNumber("+854 1111 2222", "8541111", true, 0, 9); - checkMatchesNumber("+854 1111 2222", "1111", false, 0, 0); - } - - public void testMatches_NumberNANP() { - SmartDialPrefix.setUserInNanpRegion(true); - // An 11 digit number prefixed with 1 should be matched by the 10 digit number, as well as - // the 7 digit number (without area code) - checkMatchesNumber("1-510-333-7596", "5103337596", true, true, 2, 14); - checkMatchesNumber("1-510-333-7596", "3337596", true, true, 6, 14); - - // An 11 digit number prefixed with +1 should be matched by the 10 digit number, as well as - // the 7 digit number (without area code) - checkMatchesNumber("+1-510-333-7596", "5103337596", true, true, 3, 15); - checkMatchesNumber("+1-510-333-7596", "3337596", true, true, 7, 15); - checkMatchesNumber("+1-510-333-7596", "103337596", false, true, 0, 0); - checkMatchesNumber("+1-510-333-7596", "337596", false, true, 0, 0); - checkMatchesNumber("+1510 3337596", "5103337596", true, true, 2, 13); - checkMatchesNumber("+1510 3337596", "3337596", true, true, 6, 13); - checkMatchesNumber("+1510 3337596", "103337596", false, true, 0, 0); - checkMatchesNumber("+1510 3337596", "37596", false, true, 0, 0); - - // Invalid NANP numbers should not be matched - checkMatchesNumber("1-510-333-759", "510333759", false, true, 0, 0); - checkMatchesNumber("510-333-759", "333759", false, true, 0, 0); - - // match should fail if NANP flag is switched off - checkMatchesNumber("1-510-333-7596", "3337596", false, false, 0, 0); - - // A 10 digit number without a 1 prefix should be matched by the 7 digit number - checkMatchesNumber("(650) 292 2323", "2922323", true, true, 6, 14); - checkMatchesNumber("(650) 292 2323", "6502922323", true, true, 0, 14); - // match should fail if NANP flag is switched off - checkMatchesNumber("(650) 292 2323", "2922323", false, false, 0, 0); - // But this should still match (since it is the full number) - checkMatchesNumber("(650) 292 2323", "6502922323", true, false, 0, 14); - } - - - private void checkMatchesNumber(String number, String query, boolean expectedMatches, - int matchStart, int matchEnd) { - checkMatchesNumber(number, query, expectedMatches, false, matchStart, matchEnd); - } - - private void checkMatchesNumber(String number, String query, boolean expectedMatches, - boolean matchNanp, int matchStart, int matchEnd) { - final SmartDialNameMatcher matcher = new SmartDialNameMatcher(query); - final SmartDialMatchPosition pos = matcher.matchesNumber(number, query, matchNanp); - assertEquals(expectedMatches, pos != null); - if (expectedMatches) { - assertEquals("start", matchStart, pos.start); - assertEquals("end", matchEnd, pos.end); - } - } - - private void checkMatches(String displayName, String query, boolean expectedMatches, - int... expectedMatchPositions) { - final SmartDialNameMatcher matcher = new SmartDialNameMatcher(query); - final ArrayList<SmartDialMatchPosition> matchPositions = - new ArrayList<SmartDialMatchPosition>(); - final boolean matches = matcher.matchesCombination( - displayName, query, matchPositions); - Log.d(TAG, "query=" + query + " text=" + displayName - + " nfd=" + Normalizer.normalize(displayName, Normalizer.Form.NFD) - + " nfc=" + Normalizer.normalize(displayName, Normalizer.Form.NFC) - + " nfkd=" + Normalizer.normalize(displayName, Normalizer.Form.NFKD) - + " nfkc=" + Normalizer.normalize(displayName, Normalizer.Form.NFKC) - + " matches=" + matches); - assertEquals("matches", expectedMatches, matches); - final int length = expectedMatchPositions.length; - assertEquals(length % 2, 0); - if (matches) { - for (int i = 0; i < length/2; i++) { - assertEquals("start", expectedMatchPositions[i * 2], matchPositions.get(i).start); - assertEquals("end", expectedMatchPositions[i * 2 + 1], matchPositions.get(i).end); - } - } - } - -} diff --git a/tests/src/com/android/dialer/dialpad/UnicodeDialerKeyListenerTest.java b/tests/src/com/android/dialer/dialpad/UnicodeDialerKeyListenerTest.java deleted file mode 100644 index 21ccec3c0..000000000 --- a/tests/src/com/android/dialer/dialpad/UnicodeDialerKeyListenerTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2012 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.dialer.dialpad; - -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.dialer.dialpad.UnicodeDialerKeyListener; - -import junit.framework.TestCase; -/** - * Test case for {@link UnicodeDialerKeyListener}. - * - * adb shell am instrument -w -e class com.android.contacts.dialpad.UnicodeDialerKeyListenerTest \ - com.android.contacts.tests/android.test.InstrumentationTestRunner - */ -@SmallTest -public class UnicodeDialerKeyListenerTest extends TestCase { - private static UnicodeDialerKeyListener mUnicodeDialerKeyListener; - - // Pasted numeric digits should remain unchanged - public void testNumericDigits() { - // The last 3 arguments don't matter because {@link NumberKeyListener} doesn't care - // about dest, dstart, dend in - // public CharSequence filter (CharSequence source, int start, int end, - // Spanned dest, int dstart, int dend) - // anyway. This applies to all tests. - assertEquals(null, mUnicodeDialerKeyListener.filter("111222333", 0, 9, null, 0, 0)); - } - - // Pasted Arabic digits should be converted to ascii digits - public void testArabicDigits() { - assertEquals("0123456789", mUnicodeDialerKeyListener.filter("٠١٢٣٤٥٦٧٨٩", 0, 10, - null, 0, 0)); - } - - // Pasted Farsi(Persian) digits should be converted to ascii digits - // Note the difference in digits 4, 5 and 6 when compared to arabic. The rest of the digits - // look the same compared to the Arabic digits but they actually have different unicode codes. - public void testFarsiDigits() { - assertEquals("0123456789", mUnicodeDialerKeyListener.filter("۰۱۲۳۴۵۶۷۸۹", 0, 10, - null, 0, 0)); - } - - // This is a rare use case but we should make sure it works all the same. - public void testCombinationDigits() { - assertEquals("15102849177", mUnicodeDialerKeyListener.filter("۱510٢٨٤۹۱۷۷", 0, 11, - null, 0, 0)); - } - - // Test that a normal digit string with dashes is returned unfiltered - public void testDashes() { - assertEquals(null, mUnicodeDialerKeyListener.filter("1510-284-9177", 0, 13, - null, 0, 0)); - } - - @Override - protected void setUp() throws Exception { - mUnicodeDialerKeyListener = UnicodeDialerKeyListener.INSTANCE; - } -} diff --git a/tests/src/com/android/dialer/filterednumber/BlockedNumbersAutoMigratorTest.java b/tests/src/com/android/dialer/filterednumber/BlockedNumbersAutoMigratorTest.java deleted file mode 100644 index 505855528..000000000 --- a/tests/src/com/android/dialer/filterednumber/BlockedNumbersAutoMigratorTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.filterednumber; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.test.AndroidTestCase; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.dialer.compat.FilteredNumberCompat; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler; -import com.android.dialer.database.FilteredNumberAsyncQueryHandler.OnHasBlockedNumbersListener; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -public class BlockedNumbersAutoMigratorTest extends AndroidTestCase { - - private static final String HAS_CHECKED_AUTO_MIGRATE_KEY_FOR_TEST = "checkedAutoMigrateForTest"; - - @Mock - private FilteredNumberAsyncQueryHandler mockQueryHandler; - - private SharedPreferences sharedPreferences; - - private BlockedNumbersAutoMigrator blockedNumbersAutoMigrator; - - @Override - public void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - FilteredNumberCompat.setContextForTest(getContext()); - FilteredNumberCompat.setHasMigratedToNewBlocking(false); - - sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); - // SharedPreference state isn't cleaned up between each test automatically, clear it now - sharedPreferences.edit().clear().apply(); - - blockedNumbersAutoMigrator = new BlockedNumbersAutoMigrator(sharedPreferences, - mockQueryHandler); - } - - public void testConstructor_NullSharedPreferences() { - try { - new BlockedNumbersAutoMigrator(null, mockQueryHandler); - fail(); - } catch (NullPointerException e) { - } - } - - public void testConstructor_NullQueryHandler() { - try { - new BlockedNumbersAutoMigrator(sharedPreferences, null); - fail(); - } catch (NullPointerException e) { - } - } - - public void testAutoMigrate_M() { - if (CompatUtils.isNCompatible()) { - return; - } - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler, never()).hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - } - - public void testAutoMigrate_AlreadyMigrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setHasMigratedToNewBlocking(true); - - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler, never()).hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - } - - public void testAutoMigrate_AlreadyChecked() { - if (!CompatUtils.isNCompatible()) { - return; - } - sharedPreferences.edit() - .putBoolean(HAS_CHECKED_AUTO_MIGRATE_KEY_FOR_TEST, true) - .apply(); - - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler, never()).hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - } - - public void testAutoMigrate_HasNumbers() { - if (!CompatUtils.isNCompatible()) { - return; - } - setupFilteredNumberHasBlockedNumbersExpectation(true); - - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler).hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - assertFalse(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - public void testAutoMigrate_HasNumbers_MultipleCalls() { - if (!CompatUtils.isNCompatible()) { - return; - } - setupFilteredNumberHasBlockedNumbersExpectation(true); - - blockedNumbersAutoMigrator.autoMigrate(); - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler, times(1)) - .hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - assertFalse(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - public void testAutoMigrate_NoNumbers() { - if (!CompatUtils.isNCompatible()) { - return; - } - setupFilteredNumberHasBlockedNumbersExpectation(false); - - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler).hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - assertTrue(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - public void testAutoMigrate_NoNumbers_MultipleCalls() { - if (!CompatUtils.isNCompatible()) { - return; - } - setupFilteredNumberHasBlockedNumbersExpectation(false); - - blockedNumbersAutoMigrator.autoMigrate(); - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler, times(1)) - .hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - assertTrue(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - - public void testAutoMigrate_SimulateClearingAppData() { - if (!CompatUtils.isNCompatible()) { - return; - } - setupFilteredNumberHasBlockedNumbersExpectation(true); - - blockedNumbersAutoMigrator.autoMigrate(); - - // Clearing app data removes the sharedPreferences and all of the blocked numbers - sharedPreferences.edit().clear().apply(); - setupFilteredNumberHasBlockedNumbersExpectation(false); - - blockedNumbersAutoMigrator.autoMigrate(); - - verify(mockQueryHandler, times(2)) - .hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - assertTrue(FilteredNumberCompat.hasMigratedToNewBlocking()); - } - - /* - * Sets up the {@link #mockQueryHandler} to call the {@link OnHasBlockedNumbersListener} with - * the given hasBlockedNumbers value as the parameter, when - * {@link FilteredNumberAsyncQueryHandler#hasBlockedNumbers} is called. - */ - private void setupFilteredNumberHasBlockedNumbersExpectation(final boolean hasBlockedNumbers) { - doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - ((OnHasBlockedNumbersListener) invocation.getArguments()[0]) - .onHasBlockedNumbers(hasBlockedNumbers); - return null; - } - }).when(mockQueryHandler).hasBlockedNumbers(any(OnHasBlockedNumbersListener.class)); - } -} diff --git a/tests/src/com/android/dialer/filterednumber/BlockedNumbersFragmentInstrumentationTest.java b/tests/src/com/android/dialer/filterednumber/BlockedNumbersFragmentInstrumentationTest.java deleted file mode 100644 index ea4c51e21..000000000 --- a/tests/src/com/android/dialer/filterednumber/BlockedNumbersFragmentInstrumentationTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.filterednumber; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; - -import android.test.ActivityInstrumentationTestCase2; -import android.view.View; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.dialer.R; -import com.android.dialer.compat.FilteredNumberCompat; -import com.android.dialer.filterednumber.BlockedNumbersMigrator.Listener; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Instrumentation tests for {@link BlockedNumbersFragment}. Note for these tests to work properly, - * the device's screen must be on. - */ -public class BlockedNumbersFragmentInstrumentationTest extends - ActivityInstrumentationTestCase2<BlockedNumbersSettingsActivity> { - - private static final String FRAGMENT_TAG = "blocked_management"; - - private BlockedNumbersFragment blockedNumbersFragment; - @Mock private BlockedNumbersMigrator blockedNumbersMigrator; - - public BlockedNumbersFragmentInstrumentationTest() { - super(BlockedNumbersSettingsActivity.class); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - FilteredNumberCompat.setIsEnabledForTest(true); - blockedNumbersFragment = new BlockedNumbersFragment(); - blockedNumbersFragment.setBlockedNumbersMigratorForTest(blockedNumbersMigrator); - getActivity().getFragmentManager().beginTransaction() - .replace(R.id.blocked_numbers_activity_container, blockedNumbersFragment, FRAGMENT_TAG) - .commit(); - getInstrumentation().waitForIdleSync(); - } - - public void testMigrationPromo_NotShown_M() { - if (CompatUtils.isNCompatible()) { - return; - } - assertEquals(View.GONE, blockedNumbersFragment.migratePromoView.getVisibility()); - } - - public void testMigrationPromo_Shown_N() { - if (!CompatUtils.isNCompatible()) { - return; - } - assertEquals(View.VISIBLE, blockedNumbersFragment.migratePromoView.getVisibility()); - } - - public void testOnClick_Migrate() { - if (!CompatUtils.isNCompatible()) { - return; - } - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - blockedNumbersFragment.getListView().findViewById(R.id.migrate_promo_allow_button) - .performClick(); - } - }); - getInstrumentation().waitForIdleSync(); - assertFalse(blockedNumbersFragment.getListView().findViewById(R.id.migrate_promo_allow_button) - .isEnabled()); - verify(blockedNumbersMigrator).migrate(any(Listener.class)); - } -} diff --git a/tests/src/com/android/dialer/filterednumber/BlockedNumbersMigratorTest.java b/tests/src/com/android/dialer/filterednumber/BlockedNumbersMigratorTest.java deleted file mode 100644 index 565c206d8..000000000 --- a/tests/src/com/android/dialer/filterednumber/BlockedNumbersMigratorTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.filterednumber; - -import android.content.ContentUris; -import android.content.ContentValues; -import android.provider.BlockedNumberContract; -import android.provider.BlockedNumberContract.BlockedNumbers; -import android.test.AndroidTestCase; -import android.test.mock.MockContentResolver; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.contacts.common.test.mocks.MockContentProvider; -import com.android.dialer.compat.FilteredNumberCompat; -import com.android.dialer.database.FilteredNumberContract; -import com.android.dialer.database.FilteredNumberContract.FilteredNumber; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberColumns; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class BlockedNumbersMigratorTest extends AndroidTestCase { - - private static final String NUMBER = "6502530000"; - private static final String NUMBER1 = "6502530001"; - private static final String NUMBER2 = "6502530002"; - - @Mock private BlockedNumbersMigrator.Listener mListener; - private final MockContentResolver mContentResolver = new MockContentResolver(); - private final MockContentProvider mContentProvider = new MockContentProvider(); - private BlockedNumbersMigrator mMigrator; - - @Override - public void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - FilteredNumberCompat.setIsEnabledForTest(true); - mContentResolver.addProvider(FilteredNumberContract.AUTHORITY, mContentProvider); - mContentResolver.addProvider(BlockedNumberContract.AUTHORITY, mContentProvider); - mMigrator = new BlockedNumbersMigrator(mContentResolver); - } - - public void testConstructor_NullContentResolver() { - try { - new BlockedNumbersMigrator(null); - fail(); - } catch (NullPointerException e) {} - } - - public void testMigrate_M() { - if (CompatUtils.isNCompatible()) { - return; - } - assertFalse(mMigrator.migrate(mListener)); - } - - public void testMigrate_N_Disabled() { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(false); - assertFalse(mMigrator.migrate(mListener)); - } - - public void testMigrate_N_NullListener() { - if (!CompatUtils.isNCompatible()) { - return; - } - try { - mMigrator.migrate(null); - fail(); - } catch (NullPointerException e) {} - } - - public void testMigrate_N() throws InterruptedException { - if (!CompatUtils.isNCompatible()) { - return; - } - mContentProvider.expectQuery(FilteredNumber.CONTENT_URI) - .withProjection(FilteredNumberColumns.NUMBER).returnRow(NUMBER).returnRow(NUMBER1) - .returnRow(NUMBER2); - - setUpNewBlockedNumberExpectations(mContentProvider, NUMBER, 0); - setUpNewBlockedNumberExpectations(mContentProvider, NUMBER1, 1); - setUpNewBlockedNumberExpectations(mContentProvider, NUMBER2, 2); - - MigrationListener listener = new MigrationListener(); - assertTrue(mMigrator.migrate(listener)); - listener.waitForCallback(); - assertTrue(FilteredNumberCompat.hasMigratedToNewBlocking()); - mContentProvider.verify(); - } - - public void testMigrate_N_AlreadyBlocked() throws InterruptedException { - if (!CompatUtils.isNCompatible()) { - return; - } - mContentProvider.expectQuery(FilteredNumber.CONTENT_URI) - .withProjection(FilteredNumberColumns.NUMBER).returnRow(NUMBER); - mContentProvider.expectQuery(BlockedNumbers.CONTENT_URI) - .withProjection(BlockedNumbers.COLUMN_ID) - .withSelection(BlockedNumbers.COLUMN_ORIGINAL_NUMBER + " = ?", NUMBER).returnRow(0); - // No expectation for insert into BlockedNumbers.CONTENT_URI because it's already there - - MigrationListener listener = new MigrationListener(); - assertTrue(mMigrator.migrate(listener)); - listener.waitForCallback(); - assertTrue(FilteredNumberCompat.hasMigratedToNewBlocking()); - mContentProvider.verify(); - } - - private void setUpNewBlockedNumberExpectations(MockContentProvider contentProvider, - String number, int returnId) { - contentProvider.expectQuery(BlockedNumbers.CONTENT_URI) - .withProjection(BlockedNumbers.COLUMN_ID) - .withSelection(BlockedNumbers.COLUMN_ORIGINAL_NUMBER + " = ?", number).returnEmptyCursor(); - contentProvider.expectInsert(BlockedNumbers.CONTENT_URI, - createBlockedNumberInsertValues(number), - ContentUris.withAppendedId(BlockedNumbers.CONTENT_URI, returnId)); - } - - private ContentValues createBlockedNumberInsertValues(String number) { - ContentValues values = new ContentValues(); - values.put(BlockedNumbers.COLUMN_ORIGINAL_NUMBER, number); - return values; - } - - private static class MigrationListener implements BlockedNumbersMigrator.Listener { - - private final CountDownLatch mOnCompleteCalled = new CountDownLatch(1); - - @Override - public void onComplete() { - mOnCompleteCalled.countDown(); - } - - public void waitForCallback() throws InterruptedException { - if (!mOnCompleteCalled.await(5000, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("Waiting on callback timed out."); - } - } - } -} diff --git a/tests/src/com/android/dialer/filterednumber/FilteredNumbersUtilTest.java b/tests/src/com/android/dialer/filterednumber/FilteredNumbersUtilTest.java deleted file mode 100644 index d496b1845..000000000 --- a/tests/src/com/android/dialer/filterednumber/FilteredNumbersUtilTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2015 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.dialer.filterednumber; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -import android.content.Context; -import android.preference.PreferenceManager; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.contacts.common.compat.CompatUtils; -import com.android.contacts.common.test.mocks.ContactsMockContext; -import com.android.contacts.common.test.mocks.MockContentProvider.Query; -import com.android.dialer.compat.FilteredNumberCompat; -import com.android.dialer.database.FilteredNumberContract; -import com.android.dialer.database.FilteredNumberContract.FilteredNumber; -import com.android.dialer.database.FilteredNumberContract.FilteredNumberColumns; - -@SmallTest -public class FilteredNumbersUtilTest extends AndroidTestCase { - - private static final String COUNTRY_ISO = "US"; - - // Wed Nov 11 2015 15:00:00 - private static final long EARLIER_TIME = 1447282800000L; - - // Wed Nov 11 2015 15:01:40 - private static final long LATER_TIME = 1447282900000L; - - private static final String[] FILTERED_NUMBER_PROJECTION = new String[] { - FilteredNumberColumns.CREATION_TIME }; - - private static final String NORMALIZED_NUMBER = "+16503903411"; - - private static final long NULL_CREATION_TIME = -1; - - private ContactsMockContext mContext; - - @Override - public void setUp() throws Exception { - super.setUp(); - mContext = new ContactsMockContext(getContext(), FilteredNumberContract.AUTHORITY); - - // Reset whether an emergency number was dialed - PreferenceManager.getDefaultSharedPreferences(mContext) - .edit() - .putLong(FilteredNumbersUtil.LAST_EMERGENCY_CALL_MS_PREF_KEY, 0) - .apply(); - } - - public void testShouldBlockVoicemail_NotBlocked() { - setupShouldBlockVoicemailQuery(NULL_CREATION_TIME); - assertFalse(FilteredNumbersUtil.shouldBlockVoicemail(mContext, NORMALIZED_NUMBER, - COUNTRY_ISO, EARLIER_TIME)); - } - - public void testShouldBlockVoicemail_BlockedBeforeVoicemail() { - setupShouldBlockVoicemailQuery(EARLIER_TIME); - assertTrue(FilteredNumbersUtil.shouldBlockVoicemail(mContext, NORMALIZED_NUMBER, - COUNTRY_ISO, LATER_TIME)); - } - - public void testShouldBlockVoicemail_BlockedAfterVoicemail() { - setupShouldBlockVoicemailQuery(LATER_TIME); - assertFalse(FilteredNumbersUtil.shouldBlockVoicemail(mContext, NORMALIZED_NUMBER, - COUNTRY_ISO, EARLIER_TIME)); - } - - public void testShouldBlockVoicemail_BlockedSameTimeAsVoicemail() { - setupShouldBlockVoicemailQuery(EARLIER_TIME); - assertTrue(FilteredNumbersUtil.shouldBlockVoicemail(mContext, NORMALIZED_NUMBER, - COUNTRY_ISO, EARLIER_TIME)); - } - - public void testShouldBlockVoicemail_BlockedInSameMinuteAsVoicemail() { - setupShouldBlockVoicemailQuery(EARLIER_TIME); - assertTrue(FilteredNumbersUtil.shouldBlockVoicemail(mContext, NORMALIZED_NUMBER, - COUNTRY_ISO, EARLIER_TIME + 30000)); - } - - public void testShouldBlockVoicemail_AfterEmergencyCall() { - // Just called emergency services - PreferenceManager.getDefaultSharedPreferences(mContext) - .edit() - .putLong(FilteredNumbersUtil.LAST_EMERGENCY_CALL_MS_PREF_KEY, - System.currentTimeMillis()) - .apply(); - assertFalse(FilteredNumbersUtil.shouldBlockVoicemail(mContext, NORMALIZED_NUMBER, - COUNTRY_ISO, 0)); - } - - public void testMaybeNotifyCallBlockingDisabled_Migrated() { - if (!CompatUtils.isNCompatible()) { - return; - } - FilteredNumberCompat.setIsEnabledForTest(true); - FilteredNumberCompat.setHasMigratedToNewBlocking(true); - Context mockContext = mock(Context.class); - - FilteredNumbersUtil.maybeNotifyCallBlockingDisabled(mockContext); - verifyZeroInteractions(mockContext); - } - - private void setupShouldBlockVoicemailQuery(long creationTimeMs) { - Query query = mContext.getContactsProvider().expectQuery(FilteredNumber.CONTENT_URI) - .withProjection(FILTERED_NUMBER_PROJECTION) - .withAnySelection() - .withAnySortOrder(); - if (creationTimeMs == NULL_CREATION_TIME) { - query.returnEmptyCursor(); - return; - } - query.returnRow(creationTimeMs); - } -} diff --git a/tests/src/com/android/dialer/filterednumber/MigrateBlockedNumbersDialogFragmentInstrumentationTest.java b/tests/src/com/android/dialer/filterednumber/MigrateBlockedNumbersDialogFragmentInstrumentationTest.java deleted file mode 100644 index 0bfa6bcb2..000000000 --- a/tests/src/com/android/dialer/filterednumber/MigrateBlockedNumbersDialogFragmentInstrumentationTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.filterednumber; - -import android.app.AlertDialog; -import android.app.DialogFragment; -import android.content.ContentResolver; -import android.content.DialogInterface; -import android.test.ActivityInstrumentationTestCase2; - -import com.android.dialer.DialtactsActivity; -import com.android.dialer.filterednumber.BlockedNumbersMigrator.Listener; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -/** - * Instrumentation tests for {@link MigrateBlockedNumbersDialogFragment}. Note for these tests to - * work properly, the device's screen must be on. - */ -public class MigrateBlockedNumbersDialogFragmentInstrumentationTest extends - ActivityInstrumentationTestCase2<DialtactsActivity> { - - private static final String SHOW_TAG = "ShowTag"; - - private BlockedNumbersMigrator mBlockedNumbersMigrator; - @Mock private Listener mListener; - private DialogFragment mMigrateDialogFragment; - - public MigrateBlockedNumbersDialogFragmentInstrumentationTest() { - super(DialtactsActivity.class); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - mBlockedNumbersMigrator = new SynchronousBlockedNumbersMigrator( - getActivity().getContentResolver()); - mMigrateDialogFragment = MigrateBlockedNumbersDialogFragment - .newInstance(mBlockedNumbersMigrator, mListener); - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mMigrateDialogFragment.show(getActivity().getFragmentManager(), SHOW_TAG); - } - }); - getInstrumentation().waitForIdleSync(); - } - - public void testDialogAppears() { - assertTrue(mMigrateDialogFragment.getDialog().isShowing()); - } - - public void testDialogPositiveButtonPress() { - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - ((AlertDialog) mMigrateDialogFragment.getDialog()) - .getButton(DialogInterface.BUTTON_POSITIVE).performClick(); - } - }); - getInstrumentation().waitForIdleSync(); - // Dialog was dismissed - assertNull(mMigrateDialogFragment.getDialog()); - } - - private static class SynchronousBlockedNumbersMigrator extends BlockedNumbersMigrator { - public SynchronousBlockedNumbersMigrator(ContentResolver contentResolver) { - super(contentResolver); - } - - @Override - public boolean migrate(BlockedNumbersMigrator.Listener listener) { - listener.onComplete(); - return true; - } - } -} diff --git a/tests/src/com/android/dialer/filterednumber/MigrateBlockedNumbersDialogFragmentTest.java b/tests/src/com/android/dialer/filterednumber/MigrateBlockedNumbersDialogFragmentTest.java deleted file mode 100644 index 1b419cee8..000000000 --- a/tests/src/com/android/dialer/filterednumber/MigrateBlockedNumbersDialogFragmentTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.filterednumber; - -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.dialer.filterednumber.BlockedNumbersMigrator.Listener; - -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - - -/** - * Unit tests for {@link MigrateBlockedNumbersDialogFragment} - */ -@SmallTest -public class MigrateBlockedNumbersDialogFragmentTest extends AndroidTestCase { - - @Mock private BlockedNumbersMigrator mBlockedNumbersMigrator; - @Mock private Listener mListener; - - @Override - public void setUp() throws Exception { - super.setUp(); - MockitoAnnotations.initMocks(this); - } - - public void testNewInstance_NullMigrator() { - try { - MigrateBlockedNumbersDialogFragment.newInstance(null, mListener); - fail(); - } catch (NullPointerException e) {} - } - - public void testNewInstance_NullListener() { - try { - MigrateBlockedNumbersDialogFragment.newInstance(mBlockedNumbersMigrator, null); - fail(); - } catch (NullPointerException e) {} - } - - public void testNewInstance_WithListener() { - assertNotNull(MigrateBlockedNumbersDialogFragment.newInstance(mBlockedNumbersMigrator, - mListener)); - } -} diff --git a/tests/src/com/android/dialer/interactions/PhoneNumberInteractionTest.java b/tests/src/com/android/dialer/interactions/PhoneNumberInteractionTest.java deleted file mode 100644 index f58e6cc6c..000000000 --- a/tests/src/com/android/dialer/interactions/PhoneNumberInteractionTest.java +++ /dev/null @@ -1,262 +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.dialer.interactions; - -import android.content.ContentUris; -import android.content.Context; -import android.content.CursorLoader; -import android.content.DialogInterface.OnDismissListener; -import android.content.Intent; -import android.net.Uri; -import android.provider.ContactsContract.CommonDataKinds.Phone; -import android.provider.ContactsContract.CommonDataKinds.SipAddress; -import android.provider.ContactsContract.Contacts; -import android.provider.ContactsContract.Data; -import android.provider.ContactsContract.RawContacts; -import android.test.InstrumentationTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.contacts.common.test.mocks.ContactsMockContext; -import com.android.contacts.common.test.mocks.MockContentProvider; -import com.android.contacts.common.test.mocks.MockContentProvider.Query; -import com.android.contacts.common.util.ContactDisplayUtils; -import com.android.dialer.interactions.PhoneNumberInteraction.PhoneItem; -import com.android.dialer.util.TestConstants; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -/** - * Tests for {@link com.android.contacts.common.interactions.PhoneNumberInteraction}. - * - * adb shell am instrument \ - * -w com.android.dialer.tests/android.test.InstrumentationTestRunner - */ -@SmallTest -public class PhoneNumberInteractionTest extends InstrumentationTestCase { - private final static class TestPhoneNumberInteraction extends PhoneNumberInteraction { - private ArrayList<PhoneItem> mPhoneList; - - public TestPhoneNumberInteraction(Context context, int interactionType, - OnDismissListener dismissListener) { - super(context, interactionType, dismissListener); - } - - @Override - void showDisambiguationDialog(ArrayList<PhoneItem> phoneList) { - this.mPhoneList = phoneList; - } - - public void waitForLoader() { - final CursorLoader loader = getLoader(); - try { - final Method waitMethod = CursorLoader.class.getMethod("waitForLoader"); - waitMethod.invoke(loader, null); - } catch(Exception e) { - // ignore - } - } - } - - private ContactsMockContext mContext; - private MockContentProvider mContactsProvider; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mContext = new ContactsMockContext(getInstrumentation().getTargetContext()); - mContactsProvider = mContext.getContactsProvider(); - } - - @Override - protected void tearDown() throws Exception { - mContactsProvider.verify(); - super.tearDown(); - } - - public void testSendSmsWhenOnlyOneNumberAvailable() { - Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, 13); - expectQuery(contactUri) - .returnRow(1, "123", 0, null, null, Phone.TYPE_HOME, null, - Phone.CONTENT_ITEM_TYPE, 13); - - TestPhoneNumberInteraction interaction = new TestPhoneNumberInteraction( - mContext, ContactDisplayUtils.INTERACTION_SMS, null); - - interaction.startInteraction(contactUri); - interaction.waitForLoader(); - - Intent intent = mContext.getIntentForStartActivity(); - assertNotNull(intent); - - assertEquals(Intent.ACTION_SENDTO, intent.getAction()); - assertEquals("sms:123", intent.getDataString()); - } - - public void testSendSmsWhenDataIdIsProvided() { - Uri dataUri = ContentUris.withAppendedId(Data.CONTENT_URI, 1); - expectQuery(dataUri, true /* isDataUri */ ) - .returnRow(1, "987", 0, null, null, Phone.TYPE_HOME, null, - Phone.CONTENT_ITEM_TYPE, 1); - - TestPhoneNumberInteraction interaction = new TestPhoneNumberInteraction( - mContext, ContactDisplayUtils.INTERACTION_SMS, null); - - interaction.startInteraction(dataUri); - interaction.waitForLoader(); - - Intent intent = mContext.getIntentForStartActivity(); - assertNotNull(intent); - - assertEquals(Intent.ACTION_SENDTO, intent.getAction()); - assertEquals("sms:987", intent.getDataString()); - } - - public void testSendSmsWhenThereIsPrimaryNumber() { - Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, 13); - expectQuery(contactUri) - .returnRow(1, "123", 0, null, null, Phone.TYPE_HOME, null, - Phone.CONTENT_ITEM_TYPE, 13) - .returnRow(2, "456", 1, null, null, Phone.TYPE_HOME, null, - Phone.CONTENT_ITEM_TYPE, 13); - - TestPhoneNumberInteraction interaction = new TestPhoneNumberInteraction( - mContext, ContactDisplayUtils.INTERACTION_SMS, null); - - interaction.startInteraction(contactUri); - interaction.waitForLoader(); - - Intent intent = mContext.getIntentForStartActivity(); - assertNotNull(intent); - - assertEquals(Intent.ACTION_SENDTO, intent.getAction()); - assertEquals("sms:456", intent.getDataString()); - } - - public void testShouldCollapseWith() { - PhoneNumberInteraction.PhoneItem phoneItem1 = new PhoneNumberInteraction.PhoneItem(); - PhoneNumberInteraction.PhoneItem phoneItem2 = new PhoneNumberInteraction.PhoneItem(); - - phoneItem1.phoneNumber = "123"; - phoneItem2.phoneNumber = "123"; - - assertTrue(phoneItem1.shouldCollapseWith(phoneItem2, mContext)); - - phoneItem1.phoneNumber = "123"; - phoneItem2.phoneNumber = "456"; - - assertFalse(phoneItem1.shouldCollapseWith(phoneItem2, mContext)); - - phoneItem1.phoneNumber = "123#,123"; - phoneItem2.phoneNumber = "123#,456"; - - assertFalse(phoneItem1.shouldCollapseWith(phoneItem2, mContext)); - } - - public void testCallNumberWhenThereAreDuplicates() { - Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, 13); - expectQuery(contactUri) - .returnRow(1, "123", 0, null, null, Phone.TYPE_HOME, null, - Phone.CONTENT_ITEM_TYPE, 13) - .returnRow(2, "123", 0, null, null, Phone.TYPE_WORK, null, - Phone.CONTENT_ITEM_TYPE, 13); - - TestPhoneNumberInteraction interaction = new TestPhoneNumberInteraction( - mContext, ContactDisplayUtils.INTERACTION_CALL, null); - - interaction.startInteraction(contactUri); - interaction.waitForLoader(); - - Intent intent = mContext.getIntentForStartActivity(); - assertNotNull(intent); - - assertEquals(TestConstants.CALL_INTENT_ACTION, intent.getAction()); - assertEquals("tel:123", intent.getDataString()); - } - - public void testCallWithSip() { - Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, 13); - expectQuery(contactUri) - .returnRow(1, "example@example.com", 0, null, null, Phone.TYPE_HOME, null, - SipAddress.CONTENT_ITEM_TYPE, 13); - TestPhoneNumberInteraction interaction = new TestPhoneNumberInteraction( - mContext, ContactDisplayUtils.INTERACTION_CALL, null); - - interaction.startInteraction(contactUri); - interaction.waitForLoader(); - - Intent intent = mContext.getIntentForStartActivity(); - assertNotNull(intent); - - assertEquals(TestConstants.CALL_INTENT_ACTION, intent.getAction()); - assertEquals("sip:example%40example.com", intent.getDataString()); - } - - public void testShowDisambigDialogForCalling() { - Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, 13); - expectQuery(contactUri) - .returnRow(1, "123", 0, "account", null, Phone.TYPE_HOME, "label", - Phone.CONTENT_ITEM_TYPE, 13) - .returnRow(2, "456", 0, null, null, Phone.TYPE_WORK, null, - Phone.CONTENT_ITEM_TYPE, 13); - - TestPhoneNumberInteraction interaction = new TestPhoneNumberInteraction( - mContext, ContactDisplayUtils.INTERACTION_CALL, null); - - interaction.startInteraction(contactUri); - interaction.waitForLoader(); - - List<PhoneItem> items = interaction.mPhoneList; - assertNotNull(items); - assertEquals(2, items.size()); - - PhoneItem item = items.get(0); - assertEquals(1, item.id); - assertEquals("123", item.phoneNumber); - assertEquals("account", item.accountType); - assertEquals(Phone.TYPE_HOME, item.type); - assertEquals("label", item.label); - } - - private Query expectQuery(Uri contactUri) { - return expectQuery(contactUri, false); - } - - private Query expectQuery(Uri uri, boolean isDataUri) { - final Uri dataUri; - if (isDataUri) { - dataUri = uri; - } else { - dataUri = Uri.withAppendedPath(uri, Contacts.Data.CONTENT_DIRECTORY); - } - return mContactsProvider - .expectQuery(dataUri) - .withProjection( - Phone._ID, - Phone.NUMBER, - Phone.IS_SUPER_PRIMARY, - RawContacts.ACCOUNT_TYPE, - RawContacts.DATA_SET, - Phone.TYPE, - Phone.LABEL, - Phone.MIMETYPE, - Phone.CONTACT_ID) - .withSelection("mimetype IN ('vnd.android.cursor.item/phone_v2'," - + " 'vnd.android.cursor.item/sip_address') AND data1 NOT NULL", null); - } -} diff --git a/tests/src/com/android/dialer/list/PhoneFavoritesTileAdapterTest.java b/tests/src/com/android/dialer/list/PhoneFavoritesTileAdapterTest.java deleted file mode 100644 index 881938400..000000000 --- a/tests/src/com/android/dialer/list/PhoneFavoritesTileAdapterTest.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.android.dialer.list; - -import com.google.common.collect.Lists; - -import android.content.Context; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.provider.ContactsContract.PinnedPositions; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.contacts.common.ContactTileLoaderFactory; -import com.android.contacts.common.list.ContactEntry; -import com.android.contacts.common.preference.ContactsPreferences; -import com.android.dialer.list.PhoneFavoritesTileAdapter.OnDataSetChangedForAnimationListener; - -import junit.framework.Assert; - -import java.util.ArrayList; - -@SmallTest -public class PhoneFavoritesTileAdapterTest extends AndroidTestCase { - - private static final OnDataSetChangedForAnimationListener NOOP_ANIMATION_LISTENER = - new OnDataSetChangedForAnimationListener() { - @Override - public void onDataSetChangedForAnimation(long... idsInPlace) {} - - @Override - public void cacheOffsetsForDatasetChange() {} - }; - - private PhoneFavoritesTileAdapter mAdapter; - - @Override - public void setUp() { - this.mAdapter = new PhoneFavoritesTileAdapter(getContext(), null, NOOP_ANIMATION_LISTENER); - } - - /** - * For all arrangeContactsByPinnedPosition tests, the id for a particular ContactEntry - * represents the index at which it should be located after calling - * arrangeContactsByPinnedPosition - */ - - public void testArrangeContactsByPinnedPosition_NoPinned() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0), - getTestContactEntry(1), getTestContactEntry(2)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_NoPinned_RemoveDemoted() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0), - getTestContactEntry(-1, PinnedPositions.DEMOTED), getTestContactEntry(1)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 2); - } - - public void testArrangeContactsByPinnedPosition_OnePinned_Beginning() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1), - getTestContactEntry(0, 1), getTestContactEntry(2)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_OnePinned_Middle() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0), - getTestContactEntry(1, 2), getTestContactEntry(2)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_OnePinned_End() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0), - getTestContactEntry(2, 3), getTestContactEntry(1)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_OnePinned_Outside() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0), - getTestContactEntry(2, 5), getTestContactEntry(1)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_OnePinned_RemoveDemoted() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1, 2), - getTestContactEntry(-1, PinnedPositions.DEMOTED), getTestContactEntry(0)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 2); - } - - public void testArrangeContactsByPinnedPosition_TwoPinned_Split() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0, 1), - getTestContactEntry(1), getTestContactEntry(2, 3)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_TwoPinned_Adjacent() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1, 2), - getTestContactEntry(0), getTestContactEntry(2, 3)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_TwoPinned_Conflict_UnpinnedBefore() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1, 2), - getTestContactEntry(0), getTestContactEntry(2, 2)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_TwoPinned_Conflict_UnpinnedAfter() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0, 1), - getTestContactEntry(2), getTestContactEntry(1, 1)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_TwoPinned_Conflict_RemoveDemoted() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1, 2), - getTestContactEntry(-1, PinnedPositions.DEMOTED), getTestContactEntry(0, 2)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 2); - } - - public void testArrangeContactsByPinnedPosition_AllPinned() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1, 2), - getTestContactEntry(0, 1), getTestContactEntry(2, 3)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_AllPinned_TwoConflicts_ConflictsFirst() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(1, 2), - getTestContactEntry(0, 2), getTestContactEntry(2, 3)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_AllPinned_TwoConflicts_ConflictsLast() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(0, 2), - getTestContactEntry(1, 3), getTestContactEntry(2, 3)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_AllPinned_AllConflicts() { - ArrayList<ContactEntry> toArrange = Lists.newArrayList(getTestContactEntry(2, 3), - getTestContactEntry(1, 3), getTestContactEntry(0, 3)); - mAdapter.arrangeContactsByPinnedPosition(toArrange); - - assertContactEntryListPositionsMatchId(toArrange, 3); - } - - public void testArrangeContactsByPinnedPosition_All_Pinned_AllConflicts_SortNameAlternative() { - Context context = getContext(); - context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE).edit() - .putInt(ContactsPreferences.SORT_ORDER_KEY, - ContactsPreferences.SORT_ORDER_ALTERNATIVE) - .commit(); - ArrayList<ContactEntry> actual = Lists.newArrayList( - getTestContactEntry(1, 3, "2", "1"), - getTestContactEntry(2, 3, "0", "2"), - getTestContactEntry(0, 3, "1", "0") - ); - mAdapter.arrangeContactsByPinnedPosition(actual); - - assertContactEntryListPositionsMatchId(actual, 3); - } - - /** - * TODO: Add tests - * - * This method assumes that contacts have already been reordered by - * arrangeContactsByPinnedPosition, so we can test it with a less expansive set of test data. - * - * Test cases: - * Pin a single contact at the start, middle and end of a completely unpinned list - * Pin a single contact at the start, middle and end of a list with various numbers of - * pinned contacts - * Pin a single contact at the start, middle and end of a list where all contacts are pinned - * such that contacts are forced to the left as necessary. - */ - public void testGetReflowedPinnedPositions() { - - } - - public void testSetContactCursor_DisplayNameOrder_Primary() { - setNameDisplayOrder(getContext(), ContactsPreferences.DISPLAY_ORDER_PRIMARY); - Cursor testCursor = getCursorForTest(1, 0); - mAdapter.setContactCursor(testCursor); - Assert.assertEquals(1, mAdapter.mContactEntries.size()); - Assert.assertEquals(ContactsPreferences.DISPLAY_ORDER_PRIMARY, - mAdapter.mContactEntries.get(0).nameDisplayOrder); - } - - public void testSetContactCursor_DisplayNameOrder_Alternative() { - setNameDisplayOrder(getContext(), ContactsPreferences.DISPLAY_ORDER_ALTERNATIVE); - Cursor testCursor = getCursorForTest(1, 0); - mAdapter.setContactCursor(testCursor); - Assert.assertEquals(1, mAdapter.mContactEntries.size()); - Assert.assertEquals(ContactsPreferences.DISPLAY_ORDER_ALTERNATIVE, - mAdapter.mContactEntries.get(0).nameDisplayOrder); - } - - public void testSetContactCursor_DisplayNameOrder_Changed() { - setNameDisplayOrder(getContext(), ContactsPreferences.DISPLAY_ORDER_PRIMARY); - Cursor testCursor = getCursorForTest(1, 0); - mAdapter.setContactCursor(testCursor); - Assert.assertEquals(1, mAdapter.mContactEntries.size()); - Assert.assertEquals(ContactsPreferences.DISPLAY_ORDER_PRIMARY, - mAdapter.mContactEntries.get(0).nameDisplayOrder); - - setNameDisplayOrder(getContext(), ContactsPreferences.DISPLAY_ORDER_ALTERNATIVE); - mAdapter.refreshContactsPreferences(); - mAdapter.setContactCursor(testCursor); - Assert.assertEquals(1, mAdapter.mContactEntries.size()); - Assert.assertEquals(ContactsPreferences.DISPLAY_ORDER_ALTERNATIVE, - mAdapter.mContactEntries.get(0).nameDisplayOrder); - } - - private void setNameDisplayOrder(Context context, int displayOrder) { - context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE).edit().putInt( - ContactsPreferences.DISPLAY_ORDER_KEY, displayOrder).commit(); - } - - /** - * Returns a cursor containing starred and frequent contacts for test purposes. - * - * @param numStarred Number of starred contacts in the cursor. Cannot be a negative number. - * @param numFrequents Number of frequent contacts in the cursor. Cannot be a negative number. - * @return Cursor containing the required number of rows, each representing one ContactEntry - */ - private Cursor getCursorForTest(int numStarred, int numFrequents) { - assertTrue(numStarred >= 0); - assertTrue(numFrequents >= 0); - final MatrixCursor c = new MatrixCursor(ContactTileLoaderFactory.COLUMNS_PHONE_ONLY); - int countId = 0; - - // Add starred contact entries. These entries have the starred field set to 1 (true). - // The only field that really matters for testing is the contact id. - for (int i = 0; i < numStarred; i++) { - c.addRow(new Object[] {countId, null, 1, null, null, 0, 0, null, 0, - PinnedPositions.UNPINNED, countId, null}); - countId++; - } - - // Add frequent contact entries. These entries have the starred field set to 0 (false). - for (int i = 0; i < numFrequents; i++) { - c.addRow(new Object[] {countId, null, 0, null, null, 0, 0, null, 0, - PinnedPositions.UNPINNED, countId, null}); - countId++; - } - return c; - } - - private ContactEntry getTestContactEntry(int id) { - return getTestContactEntry(id, PinnedPositions.UNPINNED); - } - - private ContactEntry getTestContactEntry(int id, int pinned) { - return getTestContactEntry(id, pinned, String.valueOf(id), String.valueOf(id)); - } - - private ContactEntry getTestContactEntry(int id, int pinned, String namePrimaryAppend, - String nameAlternativeAppend) { - ContactEntry contactEntry = new ContactEntry(); - contactEntry.id = id; - contactEntry.pinned = pinned; - contactEntry.namePrimary = namePrimaryAppend; - contactEntry.nameAlternative = nameAlternativeAppend; - return contactEntry; - } - - private void assertContactEntryListPositionsMatchId(ArrayList<ContactEntry> contactEntries, - int expectedSize) { - Assert.assertEquals(expectedSize, contactEntries.size()); - for (int i = 0; i < expectedSize; ++i) { - Assert.assertEquals(i, contactEntries.get(i).id); - } - } -} diff --git a/tests/src/com/android/dialer/tests/calllog/FillCallLogTestActivity.java b/tests/src/com/android/dialer/tests/calllog/FillCallLogTestActivity.java deleted file mode 100644 index da41dfce4..000000000 --- a/tests/src/com/android/dialer/tests/calllog/FillCallLogTestActivity.java +++ /dev/null @@ -1,658 +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.dialer.tests.calllog; - -import android.app.Activity; -import android.app.DatePickerDialog; -import android.app.Dialog; -import android.app.DialogFragment; -import android.app.LoaderManager; -import android.app.TimePickerDialog; -import android.content.ContentProviderClient; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.content.CursorLoader; -import android.content.Loader; -import android.database.Cursor; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.RemoteException; -import android.provider.CallLog.Calls; -import android.provider.VoicemailContract; -import android.provider.VoicemailContract.Status; -import android.provider.VoicemailContract.Voicemails; -import android.telecom.PhoneAccount; -import android.telecom.PhoneAccountHandle; -import android.text.Editable; -import android.text.TextWatcher; -import android.text.format.DateFormat; -import android.util.Log; -import android.view.MotionEvent; -import android.view.View; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.DatePicker; -import android.widget.EditText; -import android.widget.ProgressBar; -import android.widget.RadioButton; -import android.widget.TextView; -import android.widget.TimePicker; -import android.widget.Toast; - -import com.android.contacts.common.compat.telecom.TelecomManagerCompat; -import com.android.dialer.tests.R; -import com.android.dialer.util.AppCompatConstants; -import com.android.dialer.util.TelecomUtil; - -import java.util.Calendar; -import java.util.List; -import java.util.Random; - -/** - * Activity to add entries to the call log for testing. - */ -public class FillCallLogTestActivity extends Activity { - private static final String TAG = "FillCallLogTestActivity"; - /** Identifier of the loader for querying the call log. */ - private static final int CALLLOG_LOADER_ID = 1; - - private static final Random RNG = new Random(); - private static final int[] CALL_TYPES = new int[] { - AppCompatConstants.CALLS_INCOMING_TYPE, - AppCompatConstants.CALLS_OUTGOING_TYPE, - AppCompatConstants.CALLS_MISSED_TYPE - }; - - private TextView mNumberTextView; - private Button mAddButton; - private ProgressBar mProgressBar; - private CheckBox mUseRandomNumbers; - private RadioButton mCallTypeIncoming; - private RadioButton mCallTypeMissed; - private RadioButton mCallTypeOutgoing; - private RadioButton mCallTypeVoicemail; - private RadioButton mCallTypeCustom; - private EditText mCustomCallTypeTextView; - private CheckBox mCallTypeVideo; - private RadioButton mPresentationAllowed; - private RadioButton mPresentationRestricted; - private RadioButton mPresentationUnknown; - private RadioButton mPresentationPayphone; - private TextView mCallDate; - private TextView mCallTime; - private TextView mPhoneNumber; - private EditText mOffset; - - private int mCallTimeHour; - private int mCallTimeMinute; - private int mCallDateYear; - private int mCallDateMonth; - private int mCallDateDay; - private RadioButton mAccount0; - private RadioButton mAccount1; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.fill_call_log_test); - mNumberTextView = (TextView) findViewById(R.id.number); - mAddButton = (Button) findViewById(R.id.add); - mProgressBar = (ProgressBar) findViewById(R.id.progress); - mUseRandomNumbers = (CheckBox) findViewById(R.id.use_random_numbers); - - mAddButton.setOnClickListener(new View.OnClickListener(){ - @Override - public void onClick(View v) { - int count; - try { - count = Integer.parseInt(mNumberTextView.getText().toString()); - if (count > 100) { - throw new RuntimeException("Number too large. Max=100"); - } - } catch (RuntimeException e) { - Toast.makeText(FillCallLogTestActivity.this, e.toString(), Toast.LENGTH_LONG) - .show(); - return; - } - addEntriesToCallLog(count, mUseRandomNumbers.isChecked()); - mNumberTextView.setEnabled(false); - mAddButton.setEnabled(false); - mProgressBar.setProgress(0); - mProgressBar.setMax(count); - mProgressBar.setVisibility(View.VISIBLE); - } - }); - - mCallTypeIncoming = (RadioButton) findViewById(R.id.call_type_incoming); - mCallTypeMissed = (RadioButton) findViewById(R.id.call_type_missed); - mCallTypeOutgoing = (RadioButton) findViewById(R.id.call_type_outgoing); - mCallTypeVoicemail = (RadioButton) findViewById(R.id.call_type_voicemail); - mCallTypeCustom = (RadioButton) findViewById(R.id.call_type_custom); - mCustomCallTypeTextView = (EditText) findViewById(R.id.call_type_custom_text); - mCallTypeVideo = (CheckBox) findViewById(R.id.call_type_video); - mPresentationAllowed = (RadioButton) findViewById(R.id.presentation_allowed); - mPresentationPayphone = (RadioButton) findViewById(R.id.presentation_payphone); - mPresentationUnknown = (RadioButton) findViewById(R.id.presentation_unknown); - mPresentationRestricted = (RadioButton) findViewById(R.id.presentation_restricted); - mCallTime = (TextView) findViewById(R.id.call_time); - mCallDate = (TextView) findViewById(R.id.call_date); - mPhoneNumber = (TextView) findViewById(R.id.phone_number); - mOffset = (EditText) findViewById(R.id.delta_after_add); - mAccount0 = (RadioButton) findViewById(R.id.account0); - mAccount1 = (RadioButton) findViewById(R.id.account1); - - mCustomCallTypeTextView.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - // Do nothing. - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - // Toggle the custom call type radio button if the text is changed/focused. - mCallTypeCustom.toggle(); - } - - @Override - public void afterTextChanged(Editable s) { - // Do nothing. - } - }); - - // Use the current time as the default values for the picker - final Calendar c = Calendar.getInstance(); - mCallTimeHour = c.get(Calendar.HOUR_OF_DAY); - mCallTimeMinute = c.get(Calendar.MINUTE); - mCallDateYear = c.get(Calendar.YEAR); - mCallDateMonth = c.get(Calendar.MONTH); - mCallDateDay = c.get(Calendar.DAY_OF_MONTH); - setDisplayDate(); - setDisplayTime(); - } - - /** - * Adds a number of entries to the call log. The content of the entries is based on existing - * entries. - * - * @param count the number of entries to add - */ - private void addEntriesToCallLog(final int count, boolean useRandomNumbers) { - if (useRandomNumbers) { - addRandomNumbers(count); - } else { - getLoaderManager().initLoader(CALLLOG_LOADER_ID, null, - new CallLogLoaderListener(count)); - } - } - - /** - * Calls when the insertion has completed. - * - * @param message the message to show in a toast to the user - */ - private void insertCompleted(String message) { - // Hide the progress bar. - mProgressBar.setVisibility(View.GONE); - // Re-enable the add button. - mNumberTextView.setEnabled(true); - mAddButton.setEnabled(true); - mNumberTextView.setText(""); - Toast.makeText(this, message, Toast.LENGTH_LONG).show(); - } - - - /** - * Creates a {@link ContentValues} object containing values corresponding to the given cursor. - * - * @param cursor the cursor from which to get the values - * @return a newly created content values object - */ - private ContentValues createContentValuesFromCursor(Cursor cursor) { - ContentValues values = new ContentValues(); - for (int column = 0; column < cursor.getColumnCount(); - ++column) { - String name = cursor.getColumnName(column); - switch (cursor.getType(column)) { - case Cursor.FIELD_TYPE_STRING: - values.put(name, cursor.getString(column)); - break; - case Cursor.FIELD_TYPE_INTEGER: - values.put(name, cursor.getLong(column)); - break; - case Cursor.FIELD_TYPE_FLOAT: - values.put(name, cursor.getDouble(column)); - break; - case Cursor.FIELD_TYPE_BLOB: - values.put(name, cursor.getBlob(column)); - break; - case Cursor.FIELD_TYPE_NULL: - values.putNull(name); - break; - default: - Log.d(TAG, "Invalid value in cursor: " + cursor.getType(column)); - break; - } - } - return values; - } - - private void addRandomNumbers(int count) { - ContentValues[] values = new ContentValues[count]; - for (int i = 0; i < count; i++) { - values[i] = new ContentValues(); - values[i].put(Calls.NUMBER, generateRandomNumber()); - values[i].put(Calls.NUMBER_PRESENTATION, Calls.PRESENTATION_ALLOWED); - values[i].put(Calls.DATE, System.currentTimeMillis()); // Will be randomized later - values[i].put(Calls.DURATION, 1); // Will be overwritten later - } - new AsyncCallLogInserter(values).execute(new Void[0]); - } - - private static String generateRandomNumber() { - return String.format("5%09d", RNG.nextInt(1000000000)); - } - - /** Invokes {@link AsyncCallLogInserter} when the call log has loaded. */ - private final class CallLogLoaderListener implements LoaderManager.LoaderCallbacks<Cursor> { - /** The number of items to insert when done. */ - private final int mCount; - - private CallLogLoaderListener(int count) { - mCount = count; - } - - @Override - public Loader<Cursor> onCreateLoader(int id, Bundle args) { - Log.d(TAG, "onCreateLoader"); - return new CursorLoader(FillCallLogTestActivity.this, Calls.CONTENT_URI, - null, null, null, null); - } - - @Override - public void onLoadFinished(Loader<Cursor> loader, Cursor data) { - try { - Log.d(TAG, "onLoadFinished"); - - if (data.getCount() == 0) { - // If there are no entries in the call log, we cannot generate new ones. - insertCompleted(getString(R.string.noLogEntriesToast)); - return; - } - - data.moveToPosition(-1); - - ContentValues[] values = new ContentValues[mCount]; - for (int index = 0; index < mCount; ++index) { - if (!data.moveToNext()) { - data.moveToFirst(); - } - values[index] = createContentValuesFromCursor(data); - } - new AsyncCallLogInserter(values).execute(new Void[0]); - } finally { - // This is a one shot loader. - getLoaderManager().destroyLoader(CALLLOG_LOADER_ID); - } - } - - @Override - public void onLoaderReset(Loader<Cursor> loader) {} - } - - /** Inserts a given number of entries in the call log based on the values given. */ - private final class AsyncCallLogInserter extends AsyncTask<Void, Integer, Integer> { - /** The number of items to insert. */ - private final ContentValues[] mValues; - - public AsyncCallLogInserter(ContentValues[] values) { - mValues = values; - } - - @Override - protected Integer doInBackground(Void... params) { - Log.d(TAG, "doInBackground"); - return insertIntoCallLog(); - } - - @Override - protected void onProgressUpdate(Integer... values) { - Log.d(TAG, "onProgressUpdate"); - updateCount(values[0]); - } - - @Override - protected void onPostExecute(Integer count) { - Log.d(TAG, "onPostExecute"); - insertCompleted(getString(R.string.addedLogEntriesToast, count)); - } - - /** - * Inserts a number of entries in the call log based on the given templates. - * - * @return the number of inserted entries - */ - private Integer insertIntoCallLog() { - int inserted = 0; - - for (int index = 0; index < mValues.length; ++index) { - ContentValues values = mValues[index]; - // These should not be set. - values.putNull(Calls._ID); - // Add some randomness to the date. For each new entry being added, add an extra - // day to the maximum possible offset from the original. - values.put(Calls.DATE, - values.getAsLong(Calls.DATE) - - RNG.nextInt(24 * 60 * 60 * (index + 1)) * 1000L); - // Add some randomness to the duration. - if (values.getAsLong(Calls.DURATION) > 0) { - values.put(Calls.DURATION, RNG.nextInt(30 * 60 * 60 * 1000)); - } - - // Overwrite type. - values.put(Calls.TYPE, CALL_TYPES[RNG.nextInt(CALL_TYPES.length)]); - - // Clear cached columns. - values.putNull(Calls.CACHED_FORMATTED_NUMBER); - values.putNull(Calls.CACHED_LOOKUP_URI); - values.putNull(Calls.CACHED_MATCHED_NUMBER); - values.putNull(Calls.CACHED_NAME); - values.putNull(Calls.CACHED_NORMALIZED_NUMBER); - values.putNull(Calls.CACHED_NUMBER_LABEL); - values.putNull(Calls.CACHED_NUMBER_TYPE); - values.putNull(Calls.CACHED_PHOTO_ID); - - // Insert into the call log the newly generated entry. - ContentProviderClient contentProvider = - getContentResolver().acquireContentProviderClient( - Calls.CONTENT_URI); - try { - Log.d(TAG, "adding entry to call log"); - contentProvider.insert(Calls.CONTENT_URI, values); - ++inserted; - this.publishProgress(inserted); - } catch (RemoteException e) { - Log.d(TAG, "insert failed", e); - } - } - return inserted; - } - } - - /** - * Updates the count shown to the user corresponding to the number of entries added. - * - * @param count the number of entries inserted so far - */ - public void updateCount(Integer count) { - mProgressBar.setProgress(count); - } - - /** - * Determines the call type for a manually entered call. - * - * @return Call type. - */ - private int getManualCallType() { - if (mCallTypeIncoming.isChecked()) { - return AppCompatConstants.CALLS_INCOMING_TYPE; - } else if (mCallTypeOutgoing.isChecked()) { - return AppCompatConstants.CALLS_OUTGOING_TYPE; - } else if (mCallTypeVoicemail.isChecked()) { - return AppCompatConstants.CALLS_VOICEMAIL_TYPE; - } else if (mCallTypeCustom.isChecked()) { - return Integer.parseInt(mCustomCallTypeTextView.getText().toString()); - } else { - return AppCompatConstants.CALLS_MISSED_TYPE; - } - } - - /** - * Determines the presentation for a manually entered call. - * - * @return Presentation. - */ - private int getManualPresentation() { - if (mPresentationAllowed.isChecked()) { - return Calls.PRESENTATION_ALLOWED; - } else if (mPresentationPayphone.isChecked()) { - return Calls.PRESENTATION_PAYPHONE; - } else if (mPresentationRestricted.isChecked()) { - return Calls.PRESENTATION_RESTRICTED; - } else { - return Calls.PRESENTATION_UNKNOWN; - } - } - - private PhoneAccountHandle getManualAccount() { - List <PhoneAccountHandle> accountHandles = TelecomUtil.getCallCapablePhoneAccounts(this); - //TODO: hide the corresponding radio buttons if no accounts are available. - if (mAccount0.isChecked()) { - return accountHandles.get(0); - } else if (mAccount1.isChecked()){ - return accountHandles.get(1); - } else { - return null; - } - } - - /** - * Shows a time picker dialog, storing the results in the time field. - */ - public void showTimePickerDialog(View v) { - DialogFragment newFragment = new TimePickerFragment(); - newFragment.show(getFragmentManager(),"timePicker"); - } - - /** - * Helper class to display time picker and store the hour/minute. - */ - public class TimePickerFragment extends DialogFragment - implements TimePickerDialog.OnTimeSetListener { - - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Create a new instance of TimePickerDialog and return it - return new TimePickerDialog(getActivity(), this, mCallTimeHour, mCallTimeMinute, - DateFormat.is24HourFormat(getActivity())); - } - - public void onTimeSet(TimePicker view, int hourOfDay, int minute) { - mCallTimeHour = hourOfDay; - mCallTimeMinute = minute; - setDisplayTime(); - } - } - - /** - * Sets the call time TextView to the current selected time. - */ - private void setDisplayTime() { - mCallTime.setText(String.format("%02d:%02d", mCallTimeHour, mCallTimeMinute)); - } - - /** - * Sets the call date Textview to the current selected date - */ - private void setDisplayDate() { - mCallDate.setText(String.format("%04d-%02d-%02d", mCallDateYear, mCallDateMonth, - mCallDateDay)); - } - - /** - * Shows a date picker dialog. - */ - public void showDatePickerDialog(View v) { - DialogFragment newFragment = new DatePickerFragment(); - newFragment.show(getFragmentManager(),"datePicker"); - } - - /** - * Helper class to show a date picker. - */ - public class DatePickerFragment extends DialogFragment - implements DatePickerDialog.OnDateSetListener { - - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - // Create a new instance of DatePickerDialog and return it - return new DatePickerDialog(getActivity(), this, mCallDateYear, mCallDateMonth, - mCallDateDay); - } - - public void onDateSet(DatePicker view, int year, int month, int day) { - mCallDateYear = year; - mCallDateMonth = month; - mCallDateDay = day; - setDisplayDate(); - } - } - - /** - * OnClick handler for the button that adds a manual call log entry to the call log. - * - * @param v Calling view. - */ - public void addManualEntry(View v) { - Calendar dateTime = Calendar.getInstance(); - dateTime.set(mCallDateYear, mCallDateMonth, mCallDateDay, mCallTimeHour, mCallTimeMinute); - - int features = mCallTypeVideo.isChecked() ? Calls.FEATURES_VIDEO : 0; - Long dataUsage = null; - if (mCallTypeVideo.isChecked()) { - // Some random data usage up to 50MB. - dataUsage = (long) RNG.nextInt(52428800); - } - - if (getManualCallType() == AppCompatConstants.CALLS_VOICEMAIL_TYPE) { - addManualVoicemail(dateTime.getTimeInMillis()); - } else { - addCall(mPhoneNumber.getText().toString(), getManualPresentation(), - getManualCallType(), features, getManualAccount(), - dateTime.getTimeInMillis(), RNG.nextInt(60 * 60), dataUsage); - } - - // Subtract offset from the call date/time and store as new date/time - int offset = Integer.parseInt(mOffset.getText().toString()); - - dateTime.add(Calendar.MINUTE, offset); - mCallDateYear = dateTime.get(Calendar.YEAR); - mCallDateMonth = dateTime.get(Calendar.MONTH); - mCallDateDay = dateTime.get(Calendar.DAY_OF_MONTH); - mCallTimeHour = dateTime.get(Calendar.HOUR_OF_DAY); - mCallTimeMinute = dateTime.get(Calendar.MINUTE); - setDisplayDate(); - setDisplayTime(); - } - - // Copied and modified to compile unbundled from android.provider.CallLog - public Uri addCall(String number, - int presentation, int callType, int features, PhoneAccountHandle accountHandle, - long start, int duration, Long dataUsage) { - final ContentResolver resolver = getContentResolver(); - int numberPresentation = Calls.PRESENTATION_ALLOWED; - - String accountAddress = null; - if (accountHandle != null) { - PhoneAccount account = TelecomUtil.getPhoneAccount(this, accountHandle); - if (account != null) { - Uri address = account.getSubscriptionAddress(); - if (address != null) { - accountAddress = address.getSchemeSpecificPart(); - } - } - } - - if (numberPresentation != Calls.PRESENTATION_ALLOWED) { - number = ""; - } - - // accountHandle information - String accountComponentString = null; - String accountId = null; - if (accountHandle != null) { - accountComponentString = accountHandle.getComponentName().flattenToString(); - accountId = accountHandle.getId(); - } - - ContentValues values = new ContentValues(6); - - values.put(Calls.NUMBER, number); - values.put(Calls.NUMBER_PRESENTATION, Integer.valueOf(numberPresentation)); - values.put(Calls.TYPE, Integer.valueOf(callType)); - values.put(Calls.FEATURES, features); - values.put(Calls.DATE, Long.valueOf(start)); - values.put(Calls.DURATION, Long.valueOf(duration)); - if (dataUsage != null) { - values.put(Calls.DATA_USAGE, dataUsage); - } - values.put(Calls.PHONE_ACCOUNT_COMPONENT_NAME, accountComponentString); - values.put(Calls.PHONE_ACCOUNT_ID, accountId); - // Calls.PHONE_ACCOUNT_ADDRESS - values.put("phone_account_address", accountAddress); - values.put(Calls.NEW, Integer.valueOf(1)); - - if (callType == AppCompatConstants.CALLS_MISSED_TYPE) { - values.put(Calls.IS_READ, 0); - } - - return addEntryAndRemoveExpiredEntries(this, Calls.CONTENT_URI, values); - } - - // Copied from android.provider.CallLog - private static Uri addEntryAndRemoveExpiredEntries(Context context, Uri uri, - ContentValues values) { - final ContentResolver resolver = context.getContentResolver(); - Uri result = resolver.insert(uri, values); - resolver.delete(uri, "_id IN " + - "(SELECT _id FROM calls ORDER BY " + Calls.DEFAULT_SORT_ORDER - + " LIMIT -1 OFFSET 500)", null); - return result; - } - - private void addManualVoicemail(Long time) { - final ContentValues contentValues = new ContentValues(); - contentValues.put(Voicemails.DATE, time); - contentValues.put(Voicemails.NUMBER, mPhoneNumber.getText().toString()); - contentValues.put(Voicemails.DURATION, 5000); - contentValues.put(Voicemails.SOURCE_PACKAGE, getPackageName()); - contentValues.put(Voicemails.SOURCE_DATA, 500); - contentValues.put(Voicemails.IS_READ, 0); - - getContentResolver().insert(VoicemailContract.Voicemails.buildSourceUri(getPackageName()), - contentValues); - - updateVoicemailStatus(); - } - - private void updateVoicemailStatus() { - ContentResolver contentResolver = getContentResolver(); - Uri statusUri = VoicemailContract.Status.buildSourceUri(getPackageName()); - final PhoneAccountHandle accountHandle = getManualAccount(); - - ContentValues values = new ContentValues(); - values.put(Status.PHONE_ACCOUNT_COMPONENT_NAME, getPackageName()); - values.put(Status.PHONE_ACCOUNT_ID, "ACCOUNT_ID"); - values.put(Status.CONFIGURATION_STATE, VoicemailContract.Status.CONFIGURATION_STATE_OK); - values.put(Status.DATA_CHANNEL_STATE, VoicemailContract.Status.DATA_CHANNEL_STATE_OK); - values.put(Status.NOTIFICATION_CHANNEL_STATE, - VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_OK); - - contentResolver.insert(statusUri, values); - } -} diff --git a/tests/src/com/android/dialer/util/DialerUtilsTest.java b/tests/src/com/android/dialer/util/DialerUtilsTest.java deleted file mode 100644 index ccd6dfdd5..000000000 --- a/tests/src/com/android/dialer/util/DialerUtilsTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2014 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.dialer.util; - -import com.android.dialer.calllog.PhoneCallDetailsHelper; -import com.google.common.collect.Lists; - -import android.content.Context; -import android.content.res.Resources; -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import java.util.ArrayList; - -/** - * Performs tests of the DialerUtils class. - */ -@SmallTest -public class DialerUtilsTest extends AndroidTestCase { - - private Resources mResources; - - /** - * List of items to be concatenated together for CharSequence join tests. - */ - private ArrayList<CharSequence> mItems = Lists.newArrayList(); - - @Override - protected void setUp() throws Exception { - super.setUp(); - Context context = getContext(); - mResources = context.getResources(); - } - - /** - * Tests joining an empty list of {@link CharSequence}. - */ - public void testJoinEmpty() { - mItems.clear(); - CharSequence joined = DialerUtils.join(mResources, mItems); - assertEquals("", joined); - } - - /** - * Tests joining a list of {@link CharSequence} with a single entry. - */ - public void testJoinOne() { - mItems.clear(); - mItems.add("Hello"); - CharSequence joined = DialerUtils.join(mResources, mItems); - assertEquals("Hello", joined); - } - - /** - * Tests joining a list of {@link CharSequence} with a multiple entries. - */ - public void testJoinTwo() { - mItems.clear(); - mItems.add("Hello"); - mItems.add("there"); - CharSequence joined = DialerUtils.join(mResources, mItems); - assertEquals("Hello, there", joined); - } -} diff --git a/tests/src/com/android/dialer/util/ExpirableCacheTest.java b/tests/src/com/android/dialer/util/ExpirableCacheTest.java deleted file mode 100644 index b81ad754f..000000000 --- a/tests/src/com/android/dialer/util/ExpirableCacheTest.java +++ /dev/null @@ -1,125 +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.dialer.util; - -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; -import android.util.LruCache; - -import com.android.dialer.util.ExpirableCache.CachedValue; - -/** - * Unit tests for {@link ExpirableCache}. - */ -@SmallTest -public class ExpirableCacheTest extends AndroidTestCase { - /** The object under test. */ - private ExpirableCache<String, Integer> mCache; - - @Override - protected void setUp() throws Exception { - super.setUp(); - LruCache<String, CachedValue<Integer>> lruCache = - new LruCache<String, ExpirableCache.CachedValue<Integer>>(20); - mCache = ExpirableCache.create(lruCache); - } - - @Override - protected void tearDown() throws Exception { - mCache = null; - super.tearDown(); - } - - public void testPut() { - mCache.put("a", 1); - mCache.put("b", 2); - assertEquals(1, mCache.getPossiblyExpired("a").intValue()); - assertEquals(2, mCache.getPossiblyExpired("b").intValue()); - mCache.put("a", 3); - assertEquals(3, mCache.getPossiblyExpired("a").intValue()); - } - - public void testGet_NotExisting() { - assertNull(mCache.getPossiblyExpired("a")); - mCache.put("b", 1); - assertNull(mCache.getPossiblyExpired("a")); - } - - public void testGet_Expired() { - mCache.put("a", 1); - assertEquals(1, mCache.getPossiblyExpired("a").intValue()); - mCache.expireAll(); - assertEquals(1, mCache.getPossiblyExpired("a").intValue()); - } - - public void testGetNotExpired_NotExisting() { - assertNull(mCache.get("a")); - mCache.put("b", 1); - assertNull(mCache.get("a")); - } - - public void testGetNotExpired_Expired() { - mCache.put("a", 1); - assertEquals(1, mCache.get("a").intValue()); - mCache.expireAll(); - assertNull(mCache.get("a")); - } - - public void testGetCachedValue_NotExisting() { - assertNull(mCache.getCachedValue("a")); - mCache.put("b", 1); - assertNull(mCache.getCachedValue("a")); - } - - public void testGetCachedValue_Expired() { - mCache.put("a", 1); - assertFalse("Should not be expired", mCache.getCachedValue("a").isExpired()); - mCache.expireAll(); - assertTrue("Should be expired", mCache.getCachedValue("a").isExpired()); - } - - public void testGetChangedValue_PutAfterExpired() { - mCache.put("a", 1); - mCache.expireAll(); - mCache.put("a", 1); - assertFalse("Should not be expired", mCache.getCachedValue("a").isExpired()); - } - - public void testComputingCache() { - // Creates a cache in which all unknown values default to zero. - mCache = ExpirableCache.create( - new LruCache<String, ExpirableCache.CachedValue<Integer>>(10) { - @Override - protected CachedValue<Integer> create(String key) { - return mCache.newCachedValue(0); - } - }); - - // The first time we request a new value, we add it to the cache. - CachedValue<Integer> cachedValue = mCache.getCachedValue("a"); - assertNotNull("Should have been created implicitly", cachedValue); - assertEquals(0, cachedValue.getValue().intValue()); - assertFalse("Should not be expired", cachedValue.isExpired()); - - // If we expire all the values, the implicitly created value will also be marked as expired. - mCache.expireAll(); - CachedValue<Integer> expiredCachedValue = mCache.getCachedValue("a"); - assertNotNull("Should have been created implicitly", expiredCachedValue); - assertEquals(0, expiredCachedValue.getValue().intValue()); - assertTrue("Should be expired", expiredCachedValue.isExpired()); - } -} diff --git a/tests/src/com/android/dialer/util/FakeAsyncTaskExecutor.java b/tests/src/com/android/dialer/util/FakeAsyncTaskExecutor.java deleted file mode 100644 index 52cdf7e77..000000000 --- a/tests/src/com/android/dialer/util/FakeAsyncTaskExecutor.java +++ /dev/null @@ -1,231 +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.dialer.util; - -import android.app.Instrumentation; -import android.os.AsyncTask; - -import com.google.common.collect.Lists; - -import junit.framework.Assert; - -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; - -import javax.annotation.concurrent.GuardedBy; -import javax.annotation.concurrent.ThreadSafe; - -/** - * Test implementation of AsyncTaskExecutor. - * <p> - * This class is thread-safe. As per the contract of the AsyncTaskExecutor, the submit methods must - * be called from the main ui thread, however the other public methods may be called from any thread - * (most commonly the test thread). - * <p> - * Tasks submitted to this executor will not be run immediately. Rather they will be stored in a - * list of submitted tasks, where they can be examined. They can also be run on-demand using the run - * methods, so that different ordering of AsyncTask execution can be simulated. - * <p> - * The onPreExecute method of the submitted AsyncTask will be called synchronously during the - * call to {@link #submit(Object, AsyncTask, Object...)}. - */ -@ThreadSafe -public class FakeAsyncTaskExecutor implements AsyncTaskExecutor { - private static final long DEFAULT_TIMEOUT_MS = 10000; - - /** The maximum length of time in ms to wait for tasks to execute during tests. */ - private final long mTimeoutMs = DEFAULT_TIMEOUT_MS; - - private final Object mLock = new Object(); - @GuardedBy("mLock") private final List<SubmittedTask> mSubmittedTasks = Lists.newArrayList(); - - private final DelayedExecutor mBlockingExecutor = new DelayedExecutor(); - private final Instrumentation mInstrumentation; - - /** Create a fake AsyncTaskExecutor for use in unit tests. */ - public FakeAsyncTaskExecutor(Instrumentation instrumentation) { - Assert.assertNotNull(instrumentation); - mInstrumentation = instrumentation; - } - - /** Encapsulates an async task with the params and identifier it was submitted with. */ - public interface SubmittedTask { - Runnable getRunnable(); - Object getIdentifier(); - AsyncTask<?, ?, ?> getAsyncTask(); - } - - private static final class SubmittedTaskImpl implements SubmittedTask { - private final Object mIdentifier; - private final Runnable mRunnable; - private final AsyncTask<?, ?, ?> mAsyncTask; - - public SubmittedTaskImpl(Object identifier, Runnable runnable, - AsyncTask<?, ?, ?> asyncTask) { - mIdentifier = identifier; - mRunnable = runnable; - mAsyncTask = asyncTask; - } - - @Override - public Object getIdentifier() { - return mIdentifier; - } - - @Override - public Runnable getRunnable() { - return mRunnable; - } - - @Override - public AsyncTask<?, ?, ?> getAsyncTask() { - return mAsyncTask; - } - - @Override - public String toString() { - return "SubmittedTaskImpl [mIdentifier=" + mIdentifier + "]"; - } - } - - private class DelayedExecutor implements Executor { - private final Object mNextLock = new Object(); - @GuardedBy("mNextLock") private Object mNextIdentifier; - @GuardedBy("mNextLock") private AsyncTask<?, ?, ?> mNextTask; - - @Override - public void execute(Runnable command) { - synchronized (mNextLock) { - Assert.assertNotNull(mNextTask); - mSubmittedTasks.add(new SubmittedTaskImpl(mNextIdentifier, - command, mNextTask)); - mNextIdentifier = null; - mNextTask = null; - } - } - - public <T> AsyncTask<T, ?, ?> submit(Object identifier, - AsyncTask<T, ?, ?> task, T... params) { - synchronized (mNextLock) { - Assert.assertNull(mNextIdentifier); - Assert.assertNull(mNextTask); - mNextIdentifier = identifier; - Assert.assertNotNull("Already had a valid task.\n" - + "Are you calling AsyncTaskExecutor.submit(...) from within the " - + "onPreExecute() method of another task being submitted?\n" - + "Sorry! Not that's not supported.", task); - mNextTask = task; - } - return task.executeOnExecutor(this, params); - } - } - - @Override - public <T> AsyncTask<T, ?, ?> submit(Object identifier, AsyncTask<T, ?, ?> task, T... params) { - AsyncTaskExecutors.checkCalledFromUiThread(); - return mBlockingExecutor.submit(identifier, task, params); - } - - /** - * Runs a single task matching the given identifier. - * <p> - * Removes the matching task from the list of submitted tasks, then runs it. The executor used - * to execute this async task will be a same-thread executor. - * <p> - * Fails if there was not exactly one task matching the given identifier. - * <p> - * This method blocks until the AsyncTask has completely finished executing. - */ - public void runTask(Object identifier) throws InterruptedException { - List<SubmittedTask> tasks = getSubmittedTasksByIdentifier(identifier, true); - Assert.assertEquals("Expected one task " + identifier + ", got " + tasks, 1, tasks.size()); - runTask(tasks.get(0)); - } - - /** - * Runs all tasks whose identifier matches the given identifier. - * <p> - * Removes all matching tasks from the list of submitted tasks, and runs them. The executor used - * to execute these async tasks will be a same-thread executor. - * <p> - * Fails if there were no tasks matching the given identifier. - * <p> - * This method blocks until the AsyncTask objects have completely finished executing. - */ - public void runAllTasks(Object identifier) throws InterruptedException { - List<SubmittedTask> tasks = getSubmittedTasksByIdentifier(identifier, true); - Assert.assertTrue("There were no tasks with identifier " + identifier, tasks.size() > 0); - for (SubmittedTask task : tasks) { - runTask(task); - } - } - - /** - * Executes a single {@link SubmittedTask}. - * <p> - * Blocks until the task has completed running. - */ - private <T> void runTask(final SubmittedTask submittedTask) throws InterruptedException { - submittedTask.getRunnable().run(); - // Block until the onPostExecute or onCancelled has finished. - // Unfortunately we can't be sure when the AsyncTask will have posted its result handling - // code to the main ui thread, the best we can do is wait for the Status to be FINISHED. - final CountDownLatch latch = new CountDownLatch(1); - class AsyncTaskHasFinishedRunnable implements Runnable { - @Override - public void run() { - if (submittedTask.getAsyncTask().getStatus() == AsyncTask.Status.FINISHED) { - latch.countDown(); - } else { - mInstrumentation.waitForIdle(this); - } - } - } - mInstrumentation.waitForIdle(new AsyncTaskHasFinishedRunnable()); - Assert.assertTrue(latch.await(mTimeoutMs, TimeUnit.MILLISECONDS)); - } - - private List<SubmittedTask> getSubmittedTasksByIdentifier( - Object identifier, boolean remove) { - Assert.assertNotNull(identifier); - List<SubmittedTask> results = Lists.newArrayList(); - synchronized (mLock) { - Iterator<SubmittedTask> iter = mSubmittedTasks.iterator(); - while (iter.hasNext()) { - SubmittedTask task = iter.next(); - if (identifier.equals(task.getIdentifier())) { - results.add(task); - iter.remove(); - } - } - } - return results; - } - - /** Get a factory that will return this instance - useful for testing. */ - public AsyncTaskExecutors.AsyncTaskExecutorFactory getFactory() { - return new AsyncTaskExecutors.AsyncTaskExecutorFactory() { - @Override - public AsyncTaskExecutor createAsyncTaskExeuctor() { - return FakeAsyncTaskExecutor.this; - } - }; - } -} diff --git a/tests/src/com/android/dialer/util/LocaleTestUtils.java b/tests/src/com/android/dialer/util/LocaleTestUtils.java deleted file mode 100644 index b893ccb76..000000000 --- a/tests/src/com/android/dialer/util/LocaleTestUtils.java +++ /dev/null @@ -1,119 +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.dialer.util; - -import android.content.Context; -import android.content.res.Configuration; -import android.content.res.Resources; - -import java.util.Locale; - -/** - * Utility class to save and restore the locale of the system. - * <p> - * This can be used for tests that assume to be run in a certain locale, e.g., because they - * check against strings in a particular language or require an assumption on how the system - * will behave in a specific locale. - * <p> - * In your test, you can change the locale with the following code: - * <pre> - * public class CanadaFrenchTest extends AndroidTestCase { - * private LocaleTestUtils mLocaleTestUtils; - * - * @Override - * public void setUp() throws Exception { - * super.setUp(); - * mLocaleTestUtils = new LocaleTestUtils(getContext()); - * mLocaleTestUtils.setLocale(Locale.CANADA_FRENCH); - * } - * - * @Override - * public void tearDown() throws Exception { - * mLocaleTestUtils.restoreLocale(); - * mLocaleTestUtils = null; - * super.tearDown(); - * } - * - * ... - * } - * </pre> - * Note that one should not call {@link #setLocale(Locale)} more than once without calling - * {@link #restoreLocale()} first. - * <p> - * This class is not thread-safe. Usually its methods should be invoked only from the test thread. - */ -public class LocaleTestUtils { - private final Context mContext; - private boolean mSaved; - private Locale mSavedContextLocale; - private Locale mSavedSystemLocale; - - /** - * Create a new instance that can be used to set and reset the locale for the given context. - * - * @param context the context on which to alter the locale - */ - public LocaleTestUtils(Context context) { - mContext = context; - mSaved = false; - } - - /** - * Set the locale to the given value and saves the previous value. - * - * @param locale the value to which the locale should be set - * @throws IllegalStateException if the locale was already set - */ - public void setLocale(Locale locale) { - if (mSaved) { - throw new IllegalStateException( - "call restoreLocale() before calling setLocale() again"); - } - mSavedContextLocale = setResourcesLocale(mContext.getResources(), locale); - mSavedSystemLocale = setResourcesLocale(Resources.getSystem(), locale); - mSaved = true; - } - - /** - * Restores the previously set locale. - * - * @throws IllegalStateException if the locale was not set using {@link #setLocale(Locale)} - */ - public void restoreLocale() { - if (!mSaved) { - throw new IllegalStateException("call setLocale() before calling restoreLocale()"); - } - setResourcesLocale(mContext.getResources(), mSavedContextLocale); - setResourcesLocale(Resources.getSystem(), mSavedSystemLocale); - mSaved = false; - } - - /** - * Sets the locale for the given resources and returns the previous locale. - * - * @param resources the resources on which to set the locale - * @param locale the value to which to set the locale - * @return the previous value of the locale for the resources - */ - private Locale setResourcesLocale(Resources resources, Locale locale) { - Configuration contextConfiguration = new Configuration(resources.getConfiguration()); - Locale savedLocale = contextConfiguration.locale; - contextConfiguration.locale = locale; - resources.updateConfiguration(contextConfiguration, null); - return savedLocale; - } -} diff --git a/tests/src/com/android/dialer/util/TestConstants.java b/tests/src/com/android/dialer/util/TestConstants.java deleted file mode 100644 index a3dd05166..000000000 --- a/tests/src/com/android/dialer/util/TestConstants.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.android.dialer.util; - -public class TestConstants { - public static final String CALL_INTENT_ACTION = IntentUtil.CALL_ACTION; -} diff --git a/tests/src/com/android/dialer/voicemail/VoicemailActivityInstrumentationTestCase2.java b/tests/src/com/android/dialer/voicemail/VoicemailActivityInstrumentationTestCase2.java deleted file mode 100644 index cabaf6732..000000000 --- a/tests/src/com/android/dialer/voicemail/VoicemailActivityInstrumentationTestCase2.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.voicemail; - -import android.app.Activity; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.res.AssetManager; -import android.net.Uri; -import android.provider.VoicemailContract; -import android.test.ActivityInstrumentationTestCase2; -import android.test.suitebuilder.annotation.Suppress; -import android.view.View; - -import com.android.dialer.R; -import com.android.dialer.util.AsyncTaskExecutors; -import com.android.dialer.util.FakeAsyncTaskExecutor; -import com.android.dialer.util.LocaleTestUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Locale; - -import static com.android.dialer.voicemail.VoicemailPlaybackPresenter.Tasks.CHECK_FOR_CONTENT; - -/** - * Common methods and attributes between {@link VoicemailArchiveTest} and - * {@link VoicemailPlaybackTest}. - */ -public class VoicemailActivityInstrumentationTestCase2<T extends Activity> - extends ActivityInstrumentationTestCase2<T> { - protected static final String TEST_ASSET_NAME = "quick_test_recording.mp3"; - protected static final String MIME_TYPE = "audio/mp3"; - protected static final String CONTACT_NUMBER = "+1412555555"; - protected static final String VOICEMAIL_FILE_LOCATION = "/sdcard/sadlfj893w4j23o9sfu.mp3"; - - private T mActivity; - protected VoicemailPlaybackPresenter mPresenter; - private VoicemailPlaybackLayout mLayout; - - protected Uri mVoicemailUri; - private LocaleTestUtils mLocaleTestUtils; - protected FakeAsyncTaskExecutor mFakeAsyncTaskExecutor; - - public VoicemailActivityInstrumentationTestCase2(Class<T> activityClass) { - super(activityClass); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - - mFakeAsyncTaskExecutor = new FakeAsyncTaskExecutor(getInstrumentation()); - AsyncTaskExecutors.setFactoryForTest(mFakeAsyncTaskExecutor.getFactory()); - - // Some of the tests rely on the text - safest to force a specific locale. - mLocaleTestUtils = new LocaleTestUtils(getInstrumentation().getTargetContext()); - mLocaleTestUtils.setLocale(Locale.US); - - mActivity = getActivity(); - mLayout = new VoicemailPlaybackLayout(mActivity); - mLayout.onFinishInflate(); - } - - @Override - protected void tearDown() throws Exception { - cleanUpVoicemailUri(); - - mLocaleTestUtils.restoreLocale(); - mLocaleTestUtils = null; - - mPresenter.clearInstance(); - AsyncTaskExecutors.setFactoryForTest(null); - - mActivity = null; - mPresenter = null; - mLayout = null; - - super.tearDown(); - } - - @Suppress - public void testFetchingVoicemail() throws Throwable { - setUriForUnfetchedVoicemailEntry(); - setPlaybackViewForPresenter(); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.resumePlayback(); - assertStateTextContains("Loading voicemail"); - } - }); - } - - @Suppress - public void testInvalidVoicemailShowsErrorMessage() throws Throwable { - setUriForInvalidVoicemailEntry(); - setPlaybackViewForPresenter(); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.resumePlayback(); - } - }); - mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT); - getInstrumentation().waitForIdleSync(); - - // The media player will have thrown an IOException since the file doesn't exist. - // This should have put a failed to play message on screen, buffering is gone. - assertStateTextContains("Couldn't play voicemail"); - assertStateTextNotContains("Buffering"); - } - - public void testClickingSpeakerphoneButton() throws Throwable { - setUriForRealFileVoicemailEntry(); - setPlaybackViewForPresenter(); - - // Check that the speakerphone is false to start. - assertFalse(mPresenter.isSpeakerphoneOn()); - - View speakerphoneButton = mLayout.findViewById(R.id.playback_speakerphone); - speakerphoneButton.performClick(); - assertTrue(mPresenter.isSpeakerphoneOn()); - } - - protected void cleanUpVoicemailUri() { - if (mVoicemailUri != null) { - getContentResolver().delete(VoicemailContract.Voicemails.CONTENT_URI, - "_ID = ?", new String[] { String.valueOf(ContentUris.parseId(mVoicemailUri)) }); - mVoicemailUri = null; - } - } - - protected void setUriForRealFileVoicemailEntry() throws IOException { - assertNull(mVoicemailUri); - ContentValues values = new ContentValues(); - values.put(VoicemailContract.Voicemails.DATE, String.valueOf(System.currentTimeMillis())); - values.put(VoicemailContract.Voicemails.NUMBER, CONTACT_NUMBER); - values.put(VoicemailContract.Voicemails.MIME_TYPE, MIME_TYPE); - values.put(VoicemailContract.Voicemails.HAS_CONTENT, 1); - String packageName = getInstrumentation().getTargetContext().getPackageName(); - mVoicemailUri = getContentResolver().insert( - VoicemailContract.Voicemails.buildSourceUri(packageName), values); - AssetManager assets = getAssets(); - try (InputStream inputStream = assets.open(TEST_ASSET_NAME); - OutputStream outputStream = getContentResolver().openOutputStream(mVoicemailUri)) { - copyBetweenStreams(inputStream, outputStream); - } - } - - protected void setUriForUnfetchedVoicemailEntry() { - assertNull(mVoicemailUri); - ContentValues values = new ContentValues(); - values.put(VoicemailContract.Voicemails.DATE, String.valueOf(System.currentTimeMillis())); - values.put(VoicemailContract.Voicemails.NUMBER, CONTACT_NUMBER); - values.put(VoicemailContract.Voicemails.MIME_TYPE, MIME_TYPE); - values.put(VoicemailContract.Voicemails.HAS_CONTENT, 0); - String packageName = getInstrumentation().getTargetContext().getPackageName(); - mVoicemailUri = getContentResolver().insert( - VoicemailContract.Voicemails.buildSourceUri(packageName), values); - } - - protected void setUriForInvalidVoicemailEntry() { - assertNull(mVoicemailUri); - ContentResolver contentResolver = getContentResolver(); - ContentValues values = new ContentValues(); - values.put(VoicemailContract.Voicemails.NUMBER, CONTACT_NUMBER); - values.put(VoicemailContract.Voicemails.HAS_CONTENT, 1); - // VoicemailContract.Voicemails._DATA - values.put("_data", VOICEMAIL_FILE_LOCATION); - mVoicemailUri = contentResolver.insert(VoicemailContract.Voicemails.CONTENT_URI, values); - } - - protected void setPlaybackViewForPresenter() { - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.setPlaybackView(mLayout, mVoicemailUri, false); - } - }); - } - - protected void copyBetweenStreams(InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = in.read(buffer)) > 0) { - out.write(buffer, 0, bytesRead); - } - } - - protected void assertStateTextContains(String text) { - assertNotNull(mLayout); - assertTrue(mLayout.getStateText().contains(text)); - } - - protected void assertStateTextNotContains(String text) { - assertNotNull(mLayout); - assertFalse(mLayout.getStateText().contains(text)); - } - - protected ContentResolver getContentResolver() { - return getInstrumentation().getTargetContext().getContentResolver(); - } - - protected AssetManager getAssets() { - return getInstrumentation().getContext().getAssets(); - } - -} diff --git a/tests/src/com/android/dialer/voicemail/VoicemailArchiveTest.java b/tests/src/com/android/dialer/voicemail/VoicemailArchiveTest.java deleted file mode 100644 index bbd5edc48..000000000 --- a/tests/src/com/android/dialer/voicemail/VoicemailArchiveTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.voicemail; - -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.res.AssetManager; - -import com.android.dialer.database.VoicemailArchiveContract.VoicemailArchive; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Unit tests for {@link VoicemailArchiveActivity} and {@link VoicemailArchivePlaybackPresenter}. - */ -public class VoicemailArchiveTest - extends VoicemailActivityInstrumentationTestCase2<VoicemailArchiveActivity> { - - public VoicemailArchiveTest() { - super(VoicemailArchiveActivity.class); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - mPresenter = VoicemailArchivePlaybackPresenter.getInstance(getActivity(), null); - } - - @Override - public void testFetchingVoicemail() throws Throwable { - setUriForRealFileVoicemailEntry(); - setPlaybackViewForPresenter(); - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.checkForContent( - new VoicemailPlaybackPresenter.OnContentCheckedListener() { - @Override - public void onContentChecked(boolean hasContent) { - mPresenter.resumePlayback(); - assertEquals(true, mPresenter.isPlaying()); - } - }); - } - }); - } - - @Override - public void testInvalidVoicemailShowsErrorMessage() throws Throwable { - setUriForInvalidVoicemailEntry(); - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.checkForContent( - new VoicemailPlaybackPresenter.OnContentCheckedListener() { - @Override - public void onContentChecked(boolean hasContent) { - assertStateTextContains("Couldn't play voicemail"); - } - }); - } - }); - } - - @Override - protected void setUriForInvalidVoicemailEntry() { - assertNull(mVoicemailUri); - ContentValues values = new ContentValues(); - values.put(VoicemailArchive.NUMBER, CONTACT_NUMBER); - values.put(VoicemailArchive.DATE, String.valueOf(System.currentTimeMillis())); - values.put(VoicemailArchive.MIME_TYPE, MIME_TYPE); - values.put(VoicemailArchive._DATA, VOICEMAIL_FILE_LOCATION); - mVoicemailUri = getContentResolver().insert(VoicemailArchive.CONTENT_URI, values); - } - - @Override - protected void setUriForRealFileVoicemailEntry() throws IOException { - assertNull(mVoicemailUri); - ContentValues values = new ContentValues(); - values.put(VoicemailArchive.DATE, String.valueOf(System.currentTimeMillis())); - values.put(VoicemailArchive.NUMBER, CONTACT_NUMBER); - values.put(VoicemailArchive.MIME_TYPE, MIME_TYPE); - values.put(VoicemailArchive.DURATION, 0); - mVoicemailUri = getContentResolver().insert(VoicemailArchive.CONTENT_URI, values); - AssetManager assets = getAssets(); - try (InputStream inputStream = assets.open(TEST_ASSET_NAME); - OutputStream outputStream = getContentResolver().openOutputStream(mVoicemailUri)) { - copyBetweenStreams(inputStream, outputStream); - } - } - - @Override - protected void cleanUpVoicemailUri() { - if (mVoicemailUri != null) { - getContentResolver().delete(VoicemailArchive.CONTENT_URI, - "_ID = ?", new String[] { String.valueOf(ContentUris.parseId(mVoicemailUri)) }); - mVoicemailUri = null; - } - } -} diff --git a/tests/src/com/android/dialer/voicemail/VoicemailAsyncTaskUtilTest.java b/tests/src/com/android/dialer/voicemail/VoicemailAsyncTaskUtilTest.java deleted file mode 100644 index d98d9fa59..000000000 --- a/tests/src/com/android/dialer/voicemail/VoicemailAsyncTaskUtilTest.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.voicemail; - -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.res.AssetFileDescriptor; -import android.net.Uri; -import android.os.Bundle; -import android.os.ParcelFileDescriptor; -import android.provider.CallLog; -import android.provider.VoicemailContract; -import android.test.InstrumentationTestCase; -import android.test.mock.MockContentResolver; - -import com.android.contacts.common.test.mocks.MockContentProvider; -import com.android.contacts.common.test.mocks.MockContentProvider.Query; -import com.android.dialer.calllog.CallLogQuery; -import com.android.dialer.database.VoicemailArchiveContract; -import com.android.dialer.util.AsyncTaskExecutors; -import com.android.dialer.util.FakeAsyncTaskExecutor; -import com.android.dialer.voicemail.VoicemailAsyncTaskUtil.OnGetArchivedVoicemailFilePathListener; -import com.android.dialer.voicemail.VoicemailAsyncTaskUtil.OnArchiveVoicemailListener; -import com.android.dialer.voicemail.VoicemailAsyncTaskUtil.OnSetVoicemailArchiveStatusListener; - -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; -import static org.mockito.Mockito.*; - -import java.io.FileNotFoundException; -import java.io.IOException; - -public class VoicemailAsyncTaskUtilTest extends InstrumentationTestCase { - private static final String TEST_MIME_TYPE = "audio/mp3"; - private static final String TEST_NUMBER = "+1412555555"; - private static final String TEST_FILE_PATH = "TEST_PATH"; - private static final String TEST_TRANSCRIPTION = "TEST_TRANSCRIPTION"; - private static final long TEST_DATE = 0; - private static final long TEST_DURATION = 0; - private static final int TEST_SERVER_ID = 1; - private static final int TEST_ID = 2; - private static final Uri ARCHIVED_VOICEMAIL_URI = - VoicemailArchiveContract.VoicemailArchive.buildWithId(TEST_ID); - private static final Uri VOICEMAIL_URI = VoicemailContract.Voicemails.CONTENT_URI - .buildUpon().appendPath(Integer.toString(TEST_SERVER_ID)).build(); - private static final String[] CALLLOG_QUERY_PROJECTION = new String[] { - CallLog.Calls._ID, - CallLog.Calls.NUMBER, - CallLog.Calls.DATE, - CallLog.Calls.DURATION, - CallLog.Calls.TYPE, - CallLog.Calls.COUNTRY_ISO, - CallLog.Calls.VOICEMAIL_URI, - CallLog.Calls.GEOCODED_LOCATION, - CallLog.Calls.CACHED_NAME, - CallLog.Calls.CACHED_NUMBER_TYPE, - CallLog.Calls.CACHED_NUMBER_LABEL, - CallLog.Calls.CACHED_LOOKUP_URI, - CallLog.Calls.CACHED_MATCHED_NUMBER, - CallLog.Calls.CACHED_NORMALIZED_NUMBER, - CallLog.Calls.CACHED_PHOTO_ID, - CallLog.Calls.CACHED_FORMATTED_NUMBER, - CallLog.Calls.IS_READ, - CallLog.Calls.NUMBER_PRESENTATION, - CallLog.Calls.PHONE_ACCOUNT_COMPONENT_NAME, - CallLog.Calls.PHONE_ACCOUNT_ID, - CallLog.Calls.FEATURES, - CallLog.Calls.DATA_USAGE, - CallLog.Calls.TRANSCRIPTION, - CallLog.Calls.CACHED_PHOTO_URI - }; - private static final String[] VOICEMAIL_PROJECTION = new String[] { - VoicemailContract.Voicemails._ID, - VoicemailContract.Voicemails.NUMBER, - VoicemailContract.Voicemails.DATE, - VoicemailContract.Voicemails.DURATION, - VoicemailContract.Voicemails.MIME_TYPE, - VoicemailContract.Voicemails.TRANSCRIPTION, - }; - - private final MockContentResolver mContentResolver = new MockContentResolver(); - private final MockContentProvider mArchiveContentProvider = new TestVoicemailContentProvider(); - private final MockContentProvider mVoicemailContentProvider = - new TestVoicemailContentProvider(); - private final MockContentProvider mCallLogContentProvider = new MockContentProvider(); - @Rule - private final TemporaryFolder mTemporaryFolder = new TemporaryFolder(); - - private VoicemailAsyncTaskUtil mVoicemailAsyncTaskUtil; - private FakeAsyncTaskExecutor mFakeAsyncTaskExecutor; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mFakeAsyncTaskExecutor = new FakeAsyncTaskExecutor(getInstrumentation()); - AsyncTaskExecutors.setFactoryForTest(mFakeAsyncTaskExecutor.getFactory()); - mContentResolver.addProvider(VoicemailArchiveContract.AUTHORITY, mArchiveContentProvider); - mContentResolver.addProvider(VoicemailContract.AUTHORITY, mVoicemailContentProvider); - mContentResolver.addProvider(CallLog.AUTHORITY, mCallLogContentProvider); - mVoicemailAsyncTaskUtil = new VoicemailAsyncTaskUtil(mContentResolver); - } - - @Override - protected void tearDown() throws Exception { - AsyncTaskExecutors.setFactoryForTest(null); - super.tearDown(); - } - - public void testGetVoicemailFilePath_VoicemailExists() throws Throwable { - newVoicemailArchiveQuery().withAnyProjection() - .returnRow(getCombinedContentValuesWithData()); - final OnGetArchivedVoicemailFilePathListener listener = - mock(OnGetArchivedVoicemailFilePathListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.getVoicemailFilePath(listener, ARCHIVED_VOICEMAIL_URI); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.GET_VOICEMAIL_FILE_PATH); - verify(listener).onGetArchivedVoicemailFilePath(TEST_FILE_PATH); - verifyQueries(); - } - - public void testGetVoicemailFilePath_VoicemailNotExists() throws Throwable { - newVoicemailArchiveFakeQuery().withAnyProjection().returnEmptyCursor(); - final OnGetArchivedVoicemailFilePathListener listener = - mock(OnGetArchivedVoicemailFilePathListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.getVoicemailFilePath(listener, getFakeVoicemailUri()); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.GET_VOICEMAIL_FILE_PATH); - verify(listener).onGetArchivedVoicemailFilePath(null); - verifyQueries(); - } - - public void testSetVoicemailArchiveStatus_VoicemailNotExists() throws Throwable { - newVoicemailArchiveNotExistsUpdateQuery(true); - final OnSetVoicemailArchiveStatusListener listener = - mock(OnSetVoicemailArchiveStatusListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.setVoicemailArchiveStatus(listener, - getFakeVoicemailUri(), true); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.SET_VOICEMAIL_ARCHIVE_STATUS); - verify(listener).onSetVoicemailArchiveStatus(false); - verifyQueries(); - } - - public void testSetVoicemailArchiveStatus_VoicemailExists() throws Throwable { - newVoicemailArchiveExistsUpdateQuery(true); - final OnSetVoicemailArchiveStatusListener listener = - mock(OnSetVoicemailArchiveStatusListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.setVoicemailArchiveStatus(listener, - ARCHIVED_VOICEMAIL_URI, true); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.SET_VOICEMAIL_ARCHIVE_STATUS); - verify(listener).onSetVoicemailArchiveStatus(true); - verifyQueries(); - } - - public void testArchiveVoicemailContent_ArchiveNotExists() throws Throwable { - newVoicemailArchiveExistsQuery().returnEmptyCursor(); - newQueryCallLogInfo().returnRow(getCallLogContentValues()); - newVoicemailQuery().returnRow(getVoicemailContentValues()); - newVoicemailArchiveInsert(); - final OnArchiveVoicemailListener listener = mock(OnArchiveVoicemailListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.archiveVoicemailContent(listener, VOICEMAIL_URI); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.ARCHIVE_VOICEMAIL_CONTENT); - verify(listener).onArchiveVoicemail(ARCHIVED_VOICEMAIL_URI); - verifyQueries(); - } - - public void testArchiveVoicemailContent_ArchiveExists() throws Throwable { - newVoicemailArchiveExistsQuery().returnRow(getCombinedValuesWithId()); - final OnArchiveVoicemailListener listener = mock(OnArchiveVoicemailListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.archiveVoicemailContent(listener, VOICEMAIL_URI); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.ARCHIVE_VOICEMAIL_CONTENT); - verify(listener).onArchiveVoicemail(ARCHIVED_VOICEMAIL_URI); - verifyQueries(); - } - - public void testArchiveVoicemailContent_CallLogInfoNotExists() throws Throwable { - newVoicemailArchiveExistsQuery().returnEmptyCursor(); - newQueryCallLogInfo().returnEmptyCursor(); - newVoicemailQuery().returnEmptyCursor(); - final OnArchiveVoicemailListener listener = mock(OnArchiveVoicemailListener.class); - runTestOnUiThread(new Runnable() { - @Override - public void run() { - mVoicemailAsyncTaskUtil.archiveVoicemailContent(listener, VOICEMAIL_URI); - } - }); - mFakeAsyncTaskExecutor.runTask(VoicemailAsyncTaskUtil.Tasks.ARCHIVE_VOICEMAIL_CONTENT); - verify(listener).onArchiveVoicemail(null); - verifyQueries(); - } - - private Query newVoicemailArchiveQuery() { - return mArchiveContentProvider.expectQuery(ARCHIVED_VOICEMAIL_URI); - } - - private Query newVoicemailArchiveFakeQuery() { - return mArchiveContentProvider.expectQuery(getFakeVoicemailUri()); - } - - private Query newQueryCallLogInfo() { - return mCallLogContentProvider.expectQuery(ContentUris.withAppendedId( - CallLog.Calls.CONTENT_URI_WITH_VOICEMAIL, ContentUris.parseId(VOICEMAIL_URI))) - .withProjection(CALLLOG_QUERY_PROJECTION); - } - - private Query newVoicemailQuery() { - return mVoicemailContentProvider.expectQuery(VOICEMAIL_URI).withAnySelection() - .withProjection(VOICEMAIL_PROJECTION); - } - - private Query newVoicemailArchiveExistsQuery() { - return mArchiveContentProvider.expectQuery( - VoicemailArchiveContract.VoicemailArchive.CONTENT_URI) - .withSelection(VoicemailArchiveContract.VoicemailArchive.SERVER_ID + "=" - + ContentUris.parseId(VOICEMAIL_URI), (String[]) null) - .withProjection(VoicemailArchiveContract.VoicemailArchive._ID); - } - - private void newVoicemailArchiveInsert() { - mArchiveContentProvider.expectInsert( - VoicemailArchiveContract.VoicemailArchive.CONTENT_URI, getCombinedContentValues(), - ARCHIVED_VOICEMAIL_URI); - } - - private void newVoicemailArchiveNotExistsUpdateQuery(boolean status) { - mArchiveContentProvider.expectUpdate(getFakeVoicemailUri(), - getArchiveStatusUpdateValues(status), null, null).returnRowsAffected(0); - } - - private void newVoicemailArchiveExistsUpdateQuery(boolean status) { - mArchiveContentProvider.expectUpdate(ARCHIVED_VOICEMAIL_URI, - getArchiveStatusUpdateValues(status), null, null).returnRowsAffected(1); - } - - private static ContentValues getCallLogContentValues() { - ContentValues values = new ContentValues(); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.GEOCODED_LOCATION], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_NAME], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.COUNTRY_ISO], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_NUMBER_TYPE], 0); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_NUMBER_LABEL], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_LOOKUP_URI], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_MATCHED_NUMBER], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_NORMALIZED_NUMBER], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.CACHED_FORMATTED_NUMBER], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.NUMBER_PRESENTATION], 0); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.ACCOUNT_COMPONENT_NAME], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.ACCOUNT_ID], ""); - values.put(CALLLOG_QUERY_PROJECTION[CallLogQuery.FEATURES], 0); - values.put(CALLLOG_QUERY_PROJECTION[23], ""); - return values; - } - - private static ContentValues getVoicemailContentValues() { - ContentValues values = new ContentValues(); - values.put(VoicemailContract.Voicemails.NUMBER, TEST_NUMBER); - values.put(VoicemailContract.Voicemails.DATE, TEST_DATE); - values.put(VoicemailContract.Voicemails.DURATION, TEST_DURATION); - values.put(VoicemailContract.Voicemails.MIME_TYPE, TEST_MIME_TYPE); - values.put(VoicemailContract.Voicemails._ID, TEST_SERVER_ID); - values.put(VoicemailContract.Voicemails.TRANSCRIPTION, TEST_TRANSCRIPTION); - values.put("_data", TEST_FILE_PATH); // VoicemailContract.Voicemails._DATA - return values; - } - - private static ContentValues getCombinedContentValues() { - ContentValues values = new ContentValues(); - // Call log info - values.put(VoicemailArchiveContract.VoicemailArchive.GEOCODED_LOCATION, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_NAME, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_NUMBER_TYPE, 0); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_NUMBER_LABEL, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_LOOKUP_URI, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_MATCHED_NUMBER, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_NORMALIZED_NUMBER, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_FORMATTED_NUMBER, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.NUMBER_PRESENTATION, 0); - values.put(VoicemailArchiveContract.VoicemailArchive.ACCOUNT_COMPONENT_NAME, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.ACCOUNT_ID, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.FEATURES, 0); - values.put(VoicemailArchiveContract.VoicemailArchive.CACHED_PHOTO_URI, ""); - values.put(VoicemailArchiveContract.VoicemailArchive.COUNTRY_ISO, ""); - - // Voicemail content info - values.put(VoicemailArchiveContract.VoicemailArchive.NUMBER, TEST_NUMBER); - values.put(VoicemailArchiveContract.VoicemailArchive.DATE, TEST_DATE); - values.put(VoicemailArchiveContract.VoicemailArchive.DURATION, TEST_DURATION); - values.put(VoicemailArchiveContract.VoicemailArchive.MIME_TYPE, TEST_MIME_TYPE); - values.put(VoicemailArchiveContract.VoicemailArchive.SERVER_ID, TEST_SERVER_ID); - values.put(VoicemailArchiveContract.VoicemailArchive.TRANSCRIPTION, TEST_TRANSCRIPTION); - - // Custom fields - values.put(VoicemailArchiveContract.VoicemailArchive.ARCHIVED, false); - return values; - } - - private static ContentValues getCombinedContentValuesWithData() { - ContentValues values = getCombinedContentValues(); - values.put(VoicemailArchiveContract.VoicemailArchive._DATA, TEST_FILE_PATH); - return values; - } - - private static ContentValues getCombinedValuesWithId() { - ContentValues values = getCombinedContentValuesWithData(); - values.put(VoicemailArchiveContract.VoicemailArchive._ID, TEST_ID); - return values; - } - - private static ContentValues getArchiveStatusUpdateValues(boolean status) { - ContentValues values = new ContentValues(); - values.put(VoicemailArchiveContract.VoicemailArchive.ARCHIVED, status); - return values; - } - - private static Uri getFakeVoicemailUri() { - return VoicemailArchiveContract.VoicemailArchive.buildWithId(0); - } - - private void verifyQueries() { - mArchiveContentProvider.verify(); - mCallLogContentProvider.verify(); - mVoicemailContentProvider.verify(); - } - - private class TestVoicemailContentProvider extends MockContentProvider { - @Override - public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { - int modeBits = ParcelFileDescriptor.parseMode(mode); - try { - return ParcelFileDescriptor.open(mTemporaryFolder.newFile(), modeBits); - } catch (IOException e) { - return null; - } - } - - @Override - public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts) { - try { - return new AssetFileDescriptor(openFile(uri, "r"), 0, - AssetFileDescriptor.UNKNOWN_LENGTH); - } catch (FileNotFoundException e) { - return null; - } - } - } -} - diff --git a/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java b/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java deleted file mode 100644 index be9905edd..000000000 --- a/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2016 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.dialer.voicemail; - -import android.content.ContentUris; -import android.database.Cursor; -import android.net.Uri; -import android.test.suitebuilder.annotation.Suppress; - -import com.android.dialer.calllog.CallLogActivity; -import com.android.dialer.database.VoicemailArchiveContract; -import static com.android.dialer.voicemail.VoicemailAsyncTaskUtil.Tasks.ARCHIVE_VOICEMAIL_CONTENT; -import static com.android.dialer.voicemail.VoicemailPlaybackPresenter.Tasks.CHECK_FOR_CONTENT; - -/** - * Unit tests for {@link VoicemailPlaybackPresenter} and {@link VoicemailPlaybackLayout}. - */ -public class VoicemailPlaybackTest - extends VoicemailActivityInstrumentationTestCase2<CallLogActivity> { - - public VoicemailPlaybackTest() { - super(CallLogActivity.class); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - mPresenter = VoicemailPlaybackPresenter.getInstance(getActivity(), null); - } - - @Override - public void tearDown() throws Exception { - cleanUpArchivedVoicemailUri(); - super.tearDown(); - } - - @Suppress - public void testWhenCheckForContentCompletes() throws Throwable { - setUriForRealFileVoicemailEntry(); - setPlaybackViewForPresenter(); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.resumePlayback(); - } - }); - mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT); - getInstrumentation().waitForIdleSync(); - - assertStateTextContains("Loading voicemail"); - } - - public void testArchiveContent() throws Throwable { - setUriForRealFileVoicemailEntry(); - setPlaybackViewForPresenter(); - mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.archiveContent(mVoicemailUri, true); - } - }); - mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT); - mFakeAsyncTaskExecutor.runTask(ARCHIVE_VOICEMAIL_CONTENT); - getInstrumentation().waitForIdleSync(); - assertVoicemailArchived(); - } - - public void testShareContent() throws Throwable { - setUriForRealFileVoicemailEntry(); - setPlaybackViewForPresenter(); - mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT); - - getInstrumentation().runOnMainSync(new Runnable() { - @Override - public void run() { - mPresenter.archiveContent(mVoicemailUri, false); - } - }); - mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT); - mFakeAsyncTaskExecutor.runTask(ARCHIVE_VOICEMAIL_CONTENT); - getInstrumentation().waitForIdleSync(); - assertVoicemailArchived(); - } - - private void assertVoicemailArchived() { - try (Cursor cursor = getArchivedVoicemailCursor()) { - assertTrue(hasContent(cursor)); - assertEquals(ContentUris.parseId(mVoicemailUri), getRowServerId(cursor)); - } catch (Exception e) { - fail("Voicemail was not archived: " + e.toString()); - } - } - - private void cleanUpArchivedVoicemailUri() { - try (Cursor cursor = getArchivedVoicemailCursor()) { - if (hasContent(cursor)) { - getContentResolver().delete(getRowUri(cursor), null, null); - } - } - } - - private Cursor getArchivedVoicemailCursor() { - return getContentResolver().query( - VoicemailArchiveContract.VoicemailArchive.CONTENT_URI, - new String[] { - VoicemailArchiveContract.VoicemailArchive._ID, - VoicemailArchiveContract.VoicemailArchive.SERVER_ID - }, - VoicemailArchiveContract.VoicemailArchive.SERVER_ID + "=" - + ContentUris.parseId(mVoicemailUri), - null, - null); - } - - private int getRowServerId(Cursor cursor) { - return cursor - .getInt(cursor.getColumnIndex(VoicemailArchiveContract.VoicemailArchive.SERVER_ID)); - } - - private Uri getRowUri(Cursor cursor) { - return VoicemailArchiveContract.VoicemailArchive.buildWithId(cursor.getInt( - cursor.getColumnIndex(VoicemailArchiveContract.VoicemailArchive._ID))); - } - - private boolean hasContent(Cursor cursor) { - return cursor != null && cursor.moveToFirst(); - } -}
\ No newline at end of file diff --git a/tests/src/com/android/dialer/voicemail/VoicemailStatusHelperImplTest.java b/tests/src/com/android/dialer/voicemail/VoicemailStatusHelperImplTest.java deleted file mode 100644 index 03776440f..000000000 --- a/tests/src/com/android/dialer/voicemail/VoicemailStatusHelperImplTest.java +++ /dev/null @@ -1,274 +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.dialer.voicemail; - -import static android.provider.VoicemailContract.Status.CONFIGURATION_STATE; -import static android.provider.VoicemailContract.Status.CONFIGURATION_STATE_CAN_BE_CONFIGURED; -import static android.provider.VoicemailContract.Status.CONFIGURATION_STATE_NOT_CONFIGURED; -import static android.provider.VoicemailContract.Status.DATA_CHANNEL_STATE; -import static android.provider.VoicemailContract.Status.DATA_CHANNEL_STATE_NO_CONNECTION; -import static android.provider.VoicemailContract.Status.DATA_CHANNEL_STATE_OK; -import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE; -import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_MESSAGE_WAITING; -import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_NO_CONNECTION; -import static android.provider.VoicemailContract.Status.NOTIFICATION_CHANNEL_STATE_OK; - -import android.content.ContentResolver; -import android.content.ContentValues; -import android.database.Cursor; -import android.net.Uri; -import android.provider.VoicemailContract.Status; -import android.test.AndroidTestCase; - -import com.android.dialer.R; -import com.android.dialer.voicemail.VoicemailStatusHelper.StatusMessage; - -import java.util.List; - -/** - * Unit tests for {@link VoicemailStatusHelperImpl}. - */ -public class VoicemailStatusHelperImplTest extends AndroidTestCase { - private static final String[] TEST_PACKAGES = new String[] { - "com.test.package1", - "com.test.package2" - }; - - private static final Uri TEST_SETTINGS_URI = Uri.parse("http://www.visual.voicemail.setup"); - private static final Uri TEST_VOICEMAIL_URI = Uri.parse("tel:901"); - - private static final int ACTION_MSG_CALL_VOICEMAIL = - R.string.voicemail_status_action_call_server; - private static final int ACTION_MSG_CONFIGURE = R.string.voicemail_status_action_configure; - - private static final int STATUS_MSG_NONE = -1; - private static final int STATUS_MSG_VOICEMAIL_NOT_AVAILABLE = - R.string.voicemail_status_voicemail_not_available; - private static final int STATUS_MSG_AUDIO_NOT_AVAIALABLE = - R.string.voicemail_status_audio_not_available; - private static final int STATUS_MSG_MESSAGE_WAITING = R.string.voicemail_status_messages_waiting; - private static final int STATUS_MSG_INVITE_FOR_CONFIGURATION = - R.string.voicemail_status_configure_voicemail; - - // Object under test. - private VoicemailStatusHelper mStatusHelper; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mStatusHelper = new VoicemailStatusHelperImpl(); - } - - @Override - protected void tearDown() throws Exception { - for (String sourcePackage : TEST_PACKAGES) { - deleteEntryForPackage(sourcePackage); - } - // Set member variables to null so that they are garbage collected across different runs - // of the tests. - mStatusHelper = null; - super.tearDown(); - } - - - public void testNoStatusEntries() { - assertEquals(0, getStatusMessages().size()); - } - - public void testAllOK() { - insertEntryForPackage(TEST_PACKAGES[0], getAllOkStatusValues()); - insertEntryForPackage(TEST_PACKAGES[1], getAllOkStatusValues()); - assertEquals(0, getStatusMessages().size()); - } - - public void testNotAllOKForOnePackage() { - insertEntryForPackage(TEST_PACKAGES[0], getAllOkStatusValues()); - insertEntryForPackage(TEST_PACKAGES[1], getAllOkStatusValues()); - - ContentValues values = new ContentValues(); - // Good data channel + no notification - // action: call voicemail - // msg: voicemail not available in call log page & none in call details page. - values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_NO_CONNECTION); - values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_OK); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_VOICEMAIL_NOT_AVAILABLE, - STATUS_MSG_NONE, ACTION_MSG_CALL_VOICEMAIL); - - // Message waiting + good data channel - no action. - values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_MESSAGE_WAITING); - values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_OK); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkNoMessages(TEST_PACKAGES[1], values); - - // No data channel + no notification - // action: call voicemail - // msg: voicemail not available in call log page & audio not available in call details page. - values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_OK); - values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_VOICEMAIL_NOT_AVAILABLE, - STATUS_MSG_AUDIO_NOT_AVAIALABLE, ACTION_MSG_CALL_VOICEMAIL); - - // No data channel + Notification OK - // action: call voicemail - // msg: voicemail not available in call log page & audio not available in call details page. - values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_NO_CONNECTION); - values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_VOICEMAIL_NOT_AVAILABLE, - STATUS_MSG_AUDIO_NOT_AVAIALABLE, ACTION_MSG_CALL_VOICEMAIL); - - // No data channel + Notification OK - // action: call voicemail - // msg: message waiting in call log page & audio not available in call details page. - values.put(NOTIFICATION_CHANNEL_STATE, NOTIFICATION_CHANNEL_STATE_MESSAGE_WAITING); - values.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_MESSAGE_WAITING, - STATUS_MSG_AUDIO_NOT_AVAIALABLE, ACTION_MSG_CALL_VOICEMAIL); - - // Not configured. No user action, so no message. - values.put(CONFIGURATION_STATE, CONFIGURATION_STATE_NOT_CONFIGURED); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkNoMessages(TEST_PACKAGES[1], values); - - // Can be configured - invite user for configure voicemail. - values.put(CONFIGURATION_STATE, CONFIGURATION_STATE_CAN_BE_CONFIGURED); - updateEntryForPackage(TEST_PACKAGES[1], values); - checkExpectedMessage(TEST_PACKAGES[1], values, STATUS_MSG_INVITE_FOR_CONFIGURATION, - STATUS_MSG_NONE, ACTION_MSG_CONFIGURE, TEST_SETTINGS_URI); - } - - // Test that priority of messages are handled well. - public void testMessageOrdering() { - insertEntryForPackage(TEST_PACKAGES[0], getAllOkStatusValues()); - insertEntryForPackage(TEST_PACKAGES[1], getAllOkStatusValues()); - - final ContentValues valuesNoNotificationGoodDataChannel = new ContentValues(); - valuesNoNotificationGoodDataChannel.put(NOTIFICATION_CHANNEL_STATE, - NOTIFICATION_CHANNEL_STATE_NO_CONNECTION); - valuesNoNotificationGoodDataChannel.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_OK); - - final ContentValues valuesNoNotificationNoDataChannel = new ContentValues(); - valuesNoNotificationNoDataChannel.put(NOTIFICATION_CHANNEL_STATE, - NOTIFICATION_CHANNEL_STATE_NO_CONNECTION); - valuesNoNotificationNoDataChannel.put(DATA_CHANNEL_STATE, DATA_CHANNEL_STATE_NO_CONNECTION); - - // Package1 with valuesNoNotificationGoodDataChannel and - // package2 with valuesNoNotificationNoDataChannel. Package2 should be above. - updateEntryForPackage(TEST_PACKAGES[0], valuesNoNotificationGoodDataChannel); - updateEntryForPackage(TEST_PACKAGES[1], valuesNoNotificationNoDataChannel); - List<StatusMessage> messages = getStatusMessages(); - assertEquals(2, messages.size()); - assertEquals(TEST_PACKAGES[0], messages.get(1).sourcePackage); - assertEquals(TEST_PACKAGES[1], messages.get(0).sourcePackage); - - // Now reverse the values - ordering should be reversed as well. - updateEntryForPackage(TEST_PACKAGES[0], valuesNoNotificationNoDataChannel); - updateEntryForPackage(TEST_PACKAGES[1], valuesNoNotificationGoodDataChannel); - messages = getStatusMessages(); - assertEquals(2, messages.size()); - assertEquals(TEST_PACKAGES[0], messages.get(0).sourcePackage); - assertEquals(TEST_PACKAGES[1], messages.get(1).sourcePackage); - } - - /** Checks that the expected source status message is returned by VoicemailStatusHelper. */ - private void checkExpectedMessage(String sourcePackage, ContentValues values, - int expectedCallLogMsg, int expectedCallDetailsMsg, int expectedActionMsg, - Uri expectedUri) { - List<StatusMessage> messages = getStatusMessages(); - assertEquals(1, messages.size()); - checkMessageMatches(messages.get(0), sourcePackage, expectedCallLogMsg, - expectedCallDetailsMsg, expectedActionMsg, expectedUri); - } - - private void checkExpectedMessage(String sourcePackage, ContentValues values, - int expectedCallLogMsg, int expectedCallDetailsMessage, int expectedActionMsg) { - checkExpectedMessage(sourcePackage, values, expectedCallLogMsg, expectedCallDetailsMessage, - expectedActionMsg, TEST_VOICEMAIL_URI); - } - - private void checkMessageMatches(StatusMessage message, String expectedSourcePackage, - int expectedCallLogMsg, int expectedCallDetailsMsg, int expectedActionMsg, - Uri expectedUri) { - assertEquals(expectedSourcePackage, message.sourcePackage); - assertEquals(expectedCallLogMsg, message.callLogMessageId); - assertEquals(expectedCallDetailsMsg, message.callDetailsMessageId); - assertEquals(expectedActionMsg, message.actionMessageId); - if (expectedUri == null) { - assertNull(message.actionUri); - } else { - assertEquals(expectedUri, message.actionUri); - } - } - - private void checkNoMessages(String sourcePackage, ContentValues values) { - assertEquals(1, updateEntryForPackage(sourcePackage, values)); - List<StatusMessage> messages = getStatusMessages(); - assertEquals(0, messages.size()); - } - - private ContentValues getAllOkStatusValues() { - ContentValues values = new ContentValues(); - values.put(Status.SETTINGS_URI, TEST_SETTINGS_URI.toString()); - values.put(Status.VOICEMAIL_ACCESS_URI, TEST_VOICEMAIL_URI.toString()); - values.put(Status.CONFIGURATION_STATE, Status.CONFIGURATION_STATE_OK); - values.put(Status.DATA_CHANNEL_STATE, Status.DATA_CHANNEL_STATE_OK); - values.put(Status.NOTIFICATION_CHANNEL_STATE, Status.NOTIFICATION_CHANNEL_STATE_OK); - return values; - } - - private void insertEntryForPackage(String sourcePackage, ContentValues values) { - // If insertion fails then try update as the record might already exist. - if (getContentResolver().insert(Status.buildSourceUri(sourcePackage), values) == null) { - updateEntryForPackage(sourcePackage, values); - } - } - - private void deleteEntryForPackage(String sourcePackage) { - getContentResolver().delete(Status.buildSourceUri(sourcePackage), null, null); - } - - private int updateEntryForPackage(String sourcePackage, ContentValues values) { - return getContentResolver().update( - Status.buildSourceUri(sourcePackage), values, null, null); - } - - private List<StatusMessage> getStatusMessages() { - // Restrict the cursor to only the the test packages to eliminate any side effects if there - // are other status messages already stored on the device. - Cursor cursor = getContentResolver().query(Status.CONTENT_URI, - VoicemailStatusHelperImpl.PROJECTION, getTestPackageSelection(), null, null); - return mStatusHelper.getStatusMessages(cursor); - } - - private String getTestPackageSelection() { - StringBuilder sb = new StringBuilder(); - for (String sourcePackage : TEST_PACKAGES) { - if (sb.length() > 0) { - sb.append(" OR "); - } - sb.append(String.format("(source_package='%s')", sourcePackage)); - } - return sb.toString(); - } - - private ContentResolver getContentResolver() { - return getContext().getContentResolver(); - } -} diff --git a/tests/src/com/android/dialer/widget/ActionBarControllerTest.java b/tests/src/com/android/dialer/widget/ActionBarControllerTest.java deleted file mode 100644 index 316c15537..000000000 --- a/tests/src/com/android/dialer/widget/ActionBarControllerTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2014 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.dialer.widget; - -import android.content.Context; -import android.test.InstrumentationTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.dialer.widget.ActionBarController.ActivityUi; - -@SmallTest -public class ActionBarControllerTest extends InstrumentationTestCase { - - private static final int ACTION_BAR_HEIGHT = 100; - private ActionBarController mActionBarController; - private SearchEditTextLayout mSearchBox; - private MockActivityUi mActivityUi; - - private class MockActivityUi implements ActivityUi { - boolean isInSearchUi; - boolean hasSearchQuery; - boolean shouldShowActionBar; - int actionBarHideOffset; - - @Override - public boolean isInSearchUi() { - return isInSearchUi; - } - - @Override - public boolean hasSearchQuery() { - return hasSearchQuery; - } - - @Override - public boolean shouldShowActionBar() { - return shouldShowActionBar; - } - - @Override - public int getActionBarHeight() { - return ACTION_BAR_HEIGHT; - } - - @Override - public int getActionBarHideOffset() { - return actionBarHideOffset; - } - - @Override - public void setActionBarHideOffset(int offset) { - actionBarHideOffset = offset; - } - } - - /** - * Mock version of the searchbox, that updates its state immediately instead of animating - */ - private class MockSearchBox extends SearchEditTextLayout { - - public MockSearchBox(Context context) { - super(context, null); - } - - @Override - public void expand(boolean animate, boolean requestFocus) { - mIsExpanded = true; - } - - @Override - public void collapse(boolean animate) { - mIsExpanded = false; - } - } - - @Override - protected void setUp() { - mActivityUi = new MockActivityUi(); - mSearchBox = new MockSearchBox(this.getInstrumentation().getContext()); - mActionBarController = new ActionBarController(mActivityUi, mSearchBox); - } - - // Tapping the search box should only do something when the activity is not in the search UI - public void testSearchBoxTapped() { - mSearchBox.collapse(false); - mActivityUi.isInSearchUi = false; - mActionBarController.onSearchBoxTapped(); - assertActionBarState(true, false, false); - - // Collapse the search box manually again. This time tapping on the search box should not - // expand the search box because isInSearchUi is not true. - mSearchBox.collapse(false); - mActivityUi.isInSearchUi = true; - mActionBarController.onSearchBoxTapped(); - assertActionBarState(false, false, false); - } - - // The search box should always end up being faded in and collapsed. If necessary, it should - // be slid down or up depending on what the state of the action bar was before that. - public void testOnSearchUiExited() { - // ActionBar shown previously before entering searchUI - mSearchBox.expand(true, false); - mSearchBox.setVisible(false); - mActivityUi.shouldShowActionBar = true; - mActionBarController.onSearchUiExited(); - assertActionBarState(false, false, false); - - // ActionBar slid up previously before entering searchUI - mSearchBox.collapse(false); - mSearchBox.setVisible(false); - mActivityUi.shouldShowActionBar = false; - mActionBarController.onSearchUiExited(); - assertActionBarState(false, false, true); - } - - // Depending on what state the UI was in previously, sliding the dialpad down can mean either - // displaying the expanded search box by sliding it down, displaying the unexpanded search box, - // or nothing at all. - public void testOnDialpadDown() { - // No search query typed in the dialpad and action bar was showing before - mActivityUi.shouldShowActionBar = true; - mActivityUi.isInSearchUi = true; - mSearchBox.setVisible(false); - mActionBarController.onDialpadDown(); - assertActionBarState(false, false, false); - - // No search query typed in the dialpad, but action bar was not showing before - mActionBarController.slideActionBar(true /* slideUp */, false /* animate */); - mActivityUi.shouldShowActionBar = false; - mSearchBox.setVisible(false); - mActionBarController.onDialpadDown(); - assertActionBarState(false, false, true); - - // Something typed in the dialpad - so remain in search UI and slide the expanded search - // box down - mActionBarController.slideActionBar(true /* slideUp */, false /* animate */); - mActivityUi.shouldShowActionBar = true; - mActivityUi.hasSearchQuery= true; - mSearchBox.setVisible(false); - mSearchBox.expand(false, false); - mActionBarController.onDialpadDown(); - assertActionBarState(true, false, false); - } - - // Sliding the dialpad up should fade out the search box if we weren't already in search, or - // slide up the search box otherwise - public void testOnDialpadUp() { - mActivityUi.isInSearchUi = false; - mActionBarController.onDialpadUp(); - assertActionBarState(false, true, false); - - // In Search UI, with expanded search box and something currently typed in the search box - mActivityUi.isInSearchUi = true; - mActivityUi.hasSearchQuery = true; - mSearchBox.expand(true, false); - mSearchBox.setVisible(true); - mActionBarController.slideActionBar(true /* slideUp */, false /* animate */); - mActionBarController.onDialpadUp(); - assertActionBarState(true, false, true); - } - - private void assertActionBarState(boolean isExpanded, boolean isFadedOut, boolean isSlidUp) { - assertEquals(isExpanded, mSearchBox.isExpanded()); - assertEquals(isFadedOut, mSearchBox.isFadedOut()); - assertEquals(isSlidUp, mActionBarController.getIsActionBarSlidUp()); - } -} |