Merge Android R (rvc-dev-plus-aosp-without-vendor@6692709)

Bug: 166295507
Merged-In: Ie9d2c4d6d4618a167af1c5627d5d7918a404f398
Change-Id: I2ae428e37fd96226ce4e06032e2c0beaacbd0301
This commit is contained in:
Xin Li
2020-08-28 13:20:55 -07:00
2628 changed files with 514897 additions and 439664 deletions

View File

@@ -53,7 +53,7 @@ public final class AirplaneModeEnablerTest {
@Test
public void onRadioPowerStateChanged_beenInvoke_invokeOnAirplaneModeChanged() {
mAirplaneModeEnabler.resume();
mAirplaneModeEnabler.start();
ShadowSettings.setAirplaneMode(true);

View File

@@ -0,0 +1,226 @@
/*
* Copyright (C) 2020 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.settings;
import static com.android.settings.AllInOneTetherSettings.BLUETOOTH_TETHER_KEY;
import static com.android.settings.AllInOneTetherSettings.ETHERNET_TETHER_KEY;
import static com.android.settings.AllInOneTetherSettings.EXPANDED_CHILD_COUNT_DEFAULT;
import static com.android.settings.AllInOneTetherSettings.EXPANDED_CHILD_COUNT_MAX;
import static com.android.settings.AllInOneTetherSettings.EXPANDED_CHILD_COUNT_WITH_SECURITY_NON;
import static com.android.settings.AllInOneTetherSettings.USB_TETHER_KEY;
import static com.android.settings.AllInOneTetherSettings.WIFI_TETHER_DISABLE_KEY;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.SoftApConfiguration;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.FeatureFlagUtils;
import androidx.preference.PreferenceGroup;
import androidx.preference.PreferenceScreen;
import com.android.settings.core.FeatureFlags;
import com.android.settings.testutils.shadow.ShadowWifiManager;
import com.android.settings.wifi.tether.WifiTetherAutoOffPreferenceController;
import com.android.settings.wifi.tether.WifiTetherSecurityPreferenceController;
import com.android.settingslib.core.lifecycle.Lifecycle;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowWifiManager.class})
public class AllInOneTetherSettingsTest {
private static final String[] WIFI_REGEXS = {"wifi_regexs"};
private static final String[] USB_REGEXS = {"usb_regexs"};
private static final String[] BT_REGEXS = {"bt_regexs"};
private static final String[] ETHERNET_REGEXS = {"ethernet_regexs"};
private Context mContext;
private AllInOneTetherSettings mAllInOneTetherSettings;
@Mock
private ConnectivityManager mConnectivityManager;
@Mock
private UserManager mUserManager;
@Mock
private WifiTetherSecurityPreferenceController mSecurityPreferenceController;
@Mock
private PreferenceScreen mPreferenceScreen;
@Mock
private PreferenceGroup mWifiTetherGroup;
@Before
public void setUp() {
mContext = spy(RuntimeEnvironment.application);
MockitoAnnotations.initMocks(this);
doReturn(mConnectivityManager)
.when(mContext).getSystemService(Context.CONNECTIVITY_SERVICE);
doReturn(WIFI_REGEXS).when(mConnectivityManager).getTetherableWifiRegexs();
doReturn(USB_REGEXS).when(mConnectivityManager).getTetherableUsbRegexs();
doReturn(BT_REGEXS).when(mConnectivityManager).getTetherableBluetoothRegexs();
doReturn(ETHERNET_REGEXS).when(mConnectivityManager).getTetherableIfaces();
doReturn(mUserManager).when(mContext).getSystemService(Context.USER_SERVICE);
// Assume the feature is enabled for most test cases.
FeatureFlagUtils.setEnabled(mContext, FeatureFlags.TETHER_ALL_IN_ONE, true);
mAllInOneTetherSettings = spy(new AllInOneTetherSettings());
doReturn(mPreferenceScreen).when(mAllInOneTetherSettings).getPreferenceScreen();
ReflectionHelpers.setField(mAllInOneTetherSettings, "mLifecycle", mock(Lifecycle.class));
ReflectionHelpers.setField(mAllInOneTetherSettings, "mSecurityPreferenceController",
mSecurityPreferenceController);
ReflectionHelpers.setField(mAllInOneTetherSettings, "mWifiTetherGroup", mWifiTetherGroup);
}
@Test
public void getNonIndexableKeys_tetherAvailable_featureEnabled_keysReturnedCorrectly() {
// To let TetherUtil.isTetherAvailable return true, select one of the combinations
setupIsTetherAvailable(true);
FeatureFlagUtils.setEnabled(mContext, FeatureFlags.TETHER_ALL_IN_ONE, true);
final List<String> niks =
AllInOneTetherSettings.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
assertThat(niks).doesNotContain(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_NAME);
assertThat(niks).doesNotContain(
AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_PASSWORD);
assertThat(niks).doesNotContain(AllInOneTetherSettings.KEY_WIFI_TETHER_AUTO_OFF);
assertThat(niks).doesNotContain(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_AP_BAND);
assertThat(niks).doesNotContain(AllInOneTetherSettings.KEY_WIFI_TETHER_SECURITY);
assertThat(niks).doesNotContain(BLUETOOTH_TETHER_KEY);
assertThat(niks).doesNotContain(USB_TETHER_KEY);
assertThat(niks).doesNotContain(ETHERNET_TETHER_KEY);
// This key should be returned because it's not visible by default.
assertThat(niks).contains(WIFI_TETHER_DISABLE_KEY);
}
@Test
public void getNonIndexableKeys_tetherAvailable_featureDisabled_keysReturned() {
setupIsTetherAvailable(true);
FeatureFlagUtils.setEnabled(mContext, FeatureFlags.TETHER_ALL_IN_ONE, false);
final List<String> niks =
AllInOneTetherSettings.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_NAME);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_PASSWORD);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_AUTO_OFF);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_AP_BAND);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_SECURITY);
assertThat(niks).contains(WIFI_TETHER_DISABLE_KEY);
assertThat(niks).contains(BLUETOOTH_TETHER_KEY);
assertThat(niks).contains(USB_TETHER_KEY);
assertThat(niks).contains(ETHERNET_TETHER_KEY);
}
@Test
public void getNonIndexableKeys_tetherNotAvailable_keysReturned() {
// To let TetherUtil.isTetherAvailable return false, select one of the combinations
setupIsTetherAvailable(false);
final List<String> niks =
AllInOneTetherSettings.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_NAME);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_PASSWORD);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_AUTO_OFF);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_NETWORK_AP_BAND);
assertThat(niks).contains(AllInOneTetherSettings.KEY_WIFI_TETHER_SECURITY);
assertThat(niks).contains(WIFI_TETHER_DISABLE_KEY);
assertThat(niks).doesNotContain(BLUETOOTH_TETHER_KEY);
assertThat(niks).doesNotContain(USB_TETHER_KEY);
assertThat(niks).doesNotContain(ETHERNET_TETHER_KEY);
}
@Test
public void getPreferenceControllers_notEmpty() {
assertThat(AllInOneTetherSettings.SEARCH_INDEX_DATA_PROVIDER
.getPreferenceControllers(mContext)).isNotEmpty();
}
@Test
public void createPreferenceControllers_hasAutoOffPreference() {
assertThat(mAllInOneTetherSettings.createPreferenceControllers(mContext)
.stream()
.filter(controller -> controller instanceof WifiTetherAutoOffPreferenceController)
.count())
.isEqualTo(1);
}
@Test
public void getInitialChildCount_withSecurity() {
when(mSecurityPreferenceController.getSecurityType())
.thenReturn(SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);
assertThat(mAllInOneTetherSettings.getInitialExpandedChildCount()).isEqualTo(
EXPANDED_CHILD_COUNT_DEFAULT);
}
@Test
public void getInitialChildCount_withoutSecurity() {
when(mSecurityPreferenceController.getSecurityType())
.thenReturn(SoftApConfiguration.SECURITY_TYPE_OPEN);
assertThat(mAllInOneTetherSettings.getInitialExpandedChildCount()).isEqualTo(
EXPANDED_CHILD_COUNT_WITH_SECURITY_NON);
}
@Test
public void getInitialExpandedChildCount_expandAllChild() {
assertThat(mAllInOneTetherSettings.getInitialExpandedChildCount())
.isNotEqualTo(EXPANDED_CHILD_COUNT_MAX);
ReflectionHelpers.setField(mAllInOneTetherSettings, "mShouldShowWifiConfig", false);
assertThat(mAllInOneTetherSettings.getInitialExpandedChildCount())
.isEqualTo(EXPANDED_CHILD_COUNT_MAX);
ReflectionHelpers.setField(mAllInOneTetherSettings, "mShouldShowWifiConfig", true);
assertThat(mAllInOneTetherSettings.getInitialExpandedChildCount())
.isEqualTo(EXPANDED_CHILD_COUNT_MAX);
}
private void setupIsTetherAvailable(boolean returnValue) {
when(mConnectivityManager.isTetheringSupported()).thenReturn(true);
// For RestrictedLockUtils.checkIfRestrictionEnforced
final int userId = UserHandle.myUserId();
List<UserManager.EnforcingUser> enforcingUsers = new ArrayList<>();
when(mUserManager.getUserRestrictionSources(
UserManager.DISALLOW_CONFIG_TETHERING, UserHandle.of(userId)))
.thenReturn(enforcingUsers);
// For RestrictedLockUtils.hasBaseUserRestriction
when(mUserManager.hasBaseUserRestriction(
UserManager.DISALLOW_CONFIG_TETHERING, UserHandle.of(userId)))
.thenReturn(!returnValue);
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2020 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.settings;
import static com.google.common.truth.Truth.assertThat;
import android.text.Spannable;
import android.text.style.ClickableSpan;
import android.widget.TextView;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class LinkifyUtilsTest {
private static final String TEST_STRING = "to LINK_BEGINscanning settingsLINK_END.";
private static final String WRONG_STRING = "to scanning settingsLINK_END.";
private final LinkifyUtils.OnClickListener mClickListener = () -> { /* Do nothing */ };
private StringBuilder mSpanStringBuilder;
private StringBuilder mWrongSpanStringBuilder;
TextView mTextView;
@Before
public void setUp() throws Exception {
mSpanStringBuilder = new StringBuilder(TEST_STRING);
mWrongSpanStringBuilder = new StringBuilder(WRONG_STRING);
mTextView = new TextView(RuntimeEnvironment.application);
}
@Test
public void linkify_whenSpanStringCorrect_shouldReturnTrue() {
final boolean linkifyResult = LinkifyUtils.linkify(mTextView, mSpanStringBuilder,
mClickListener);
assertThat(linkifyResult).isTrue();
}
@Test
public void linkify_whenSpanStringWrong_shouldReturnFalse() {
final boolean linkifyResult = LinkifyUtils.linkify(mTextView, mWrongSpanStringBuilder,
mClickListener);
assertThat(linkifyResult).isFalse();
}
@Test
public void linkify_whenSpanStringCorrect_shouldContainClickableSpan() {
LinkifyUtils.linkify(mTextView, mSpanStringBuilder, mClickListener);
final Spannable spannableContent = (Spannable) mTextView.getText();
final int len = spannableContent.length();
final Object[] spans = spannableContent.getSpans(0, len, Object.class);
assertThat(spans[1] instanceof ClickableSpan).isTrue();
}
}

View File

@@ -18,23 +18,50 @@ package com.android.settings;
import static com.google.common.truth.Truth.assertThat;
import android.app.Activity;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.admin.DevicePolicyManager;
import android.app.admin.FactoryResetProtectionPolicy;
import android.content.Context;
import android.service.persistentdata.PersistentDataBlockManager;
import android.view.LayoutInflater;
import android.widget.TextView;
import androidx.fragment.app.FragmentActivity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import java.util.ArrayList;
@RunWith(RobolectricTestRunner.class)
public class MasterClearConfirmTest {
private Activity mActivity;
private FragmentActivity mActivity;
@Mock
private FragmentActivity mMockActivity;
@Mock
private DevicePolicyManager mDevicePolicyManager;
@Mock
private PersistentDataBlockManager mPersistentDataBlockManager;
private MasterClearConfirm mMasterClearConfirm;
@Before
public void setUp() {
mActivity = Robolectric.setupActivity(Activity.class);
MockitoAnnotations.initMocks(this);
mActivity = Robolectric.setupActivity(FragmentActivity.class);
mMasterClearConfirm = spy(new MasterClearConfirm());
}
@Test
@@ -64,4 +91,79 @@ public class MasterClearConfirmTest {
.findViewById(R.id.sud_layout_description)).getText())
.isEqualTo(mActivity.getString(R.string.master_clear_final_desc));
}
@Test
public void shouldWipePersistentDataBlock_noPersistentDataBlockManager_shouldReturnFalse() {
assertThat(mMasterClearConfirm.shouldWipePersistentDataBlock(null)).isFalse();
}
@Test
public void shouldWipePersistentDataBlock_deviceIsStillBeingProvisioned_shouldReturnFalse() {
doReturn(true).when(mMasterClearConfirm).isDeviceStillBeingProvisioned();
assertThat(mMasterClearConfirm.shouldWipePersistentDataBlock(
mPersistentDataBlockManager)).isFalse();
}
@Test
public void shouldWipePersistentDataBlock_oemUnlockAllowed_shouldReturnFalse() {
doReturn(false).when(mMasterClearConfirm).isDeviceStillBeingProvisioned();
doReturn(true).when(mMasterClearConfirm).isOemUnlockedAllowed();
assertThat(mMasterClearConfirm.shouldWipePersistentDataBlock(
mPersistentDataBlockManager)).isFalse();
}
@Test
public void shouldWipePersistentDataBlock_frpPolicyNotSupported_shouldReturnFalse() {
when(mMasterClearConfirm.getActivity()).thenReturn(mMockActivity);
doReturn(false).when(mMasterClearConfirm).isDeviceStillBeingProvisioned();
doReturn(false).when(mMasterClearConfirm).isOemUnlockedAllowed();
when(mMockActivity.getSystemService(Context.DEVICE_POLICY_SERVICE))
.thenReturn(mDevicePolicyManager);
when(mDevicePolicyManager.isFactoryResetProtectionPolicySupported()).thenReturn(false);
assertThat(mMasterClearConfirm.shouldWipePersistentDataBlock(
mPersistentDataBlockManager)).isFalse();
}
@Test
public void shouldWipePersistentDataBlock_hasFactoryResetProtectionPolicy_shouldReturnFalse() {
when(mMasterClearConfirm.getActivity()).thenReturn(mMockActivity);
doReturn(false).when(mMasterClearConfirm).isDeviceStillBeingProvisioned();
doReturn(false).when(mMasterClearConfirm).isOemUnlockedAllowed();
ArrayList<String> accounts = new ArrayList<>();
accounts.add("test");
FactoryResetProtectionPolicy frp = new FactoryResetProtectionPolicy.Builder()
.setFactoryResetProtectionAccounts(accounts)
.setFactoryResetProtectionEnabled(true)
.build();
when(mMockActivity.getSystemService(Context.DEVICE_POLICY_SERVICE))
.thenReturn(mDevicePolicyManager);
when(mDevicePolicyManager.isFactoryResetProtectionPolicySupported()).thenReturn(true);
when(mDevicePolicyManager.getFactoryResetProtectionPolicy(null)).thenReturn(frp);
when(mDevicePolicyManager.isOrganizationOwnedDeviceWithManagedProfile()).thenReturn(true);
assertThat(mMasterClearConfirm.shouldWipePersistentDataBlock(
mPersistentDataBlockManager)).isFalse();
}
@Test
public void shouldWipePersistentDataBlock_isNotOrganizationOwnedDevice_shouldReturnTrue() {
when(mMasterClearConfirm.getActivity()).thenReturn(mMockActivity);
doReturn(false).when(mMasterClearConfirm).isDeviceStillBeingProvisioned();
doReturn(false).when(mMasterClearConfirm).isOemUnlockedAllowed();
when(mMockActivity.getSystemService(Context.DEVICE_POLICY_SERVICE))
.thenReturn(mDevicePolicyManager);
when(mDevicePolicyManager.isFactoryResetProtectionPolicySupported()).thenReturn(true);
when(mDevicePolicyManager.getFactoryResetProtectionPolicy(null)).thenReturn(null);
when(mDevicePolicyManager.isOrganizationOwnedDeviceWithManagedProfile()).thenReturn(false);
assertThat(mMasterClearConfirm.shouldWipePersistentDataBlock(
mPersistentDataBlockManager)).isTrue();
}
}

View File

@@ -16,9 +16,11 @@
package com.android.settings;
import static com.android.settings.SettingsActivity.EXTRA_SHOW_FRAGMENT;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -34,12 +36,14 @@ import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.android.settings.core.OnActivityResultListener;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@@ -61,7 +65,7 @@ public class SettingsActivityTest {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mActivity = spy(new SettingsActivity());
mActivity = spy(Robolectric.buildActivity(SettingsActivity.class).create().get());
}
@Test
@@ -69,7 +73,6 @@ public class SettingsActivityTest {
when(mActivity.getSupportFragmentManager()).thenReturn(mFragmentManager);
doReturn(mContext.getContentResolver()).when(mActivity).getContentResolver();
when(mFragmentManager.beginTransaction()).thenReturn(mock(FragmentTransaction.class));
doReturn(RuntimeEnvironment.application.getClassLoader()).when(mActivity).getClassLoader();
mActivity.launchSettingFragment(null, mock(Intent.class));
@@ -79,7 +82,18 @@ public class SettingsActivityTest {
public void setTaskDescription_shouldUpdateIcon() {
mActivity.setTaskDescription(mTaskDescription);
verify(mTaskDescription).setIcon(anyInt());
verify(mTaskDescription).setIcon(any());
}
@Test
public void getSharedPreferences_intentExtraIsNull_shouldNotCrash() {
final Intent intent = new Intent();
intent.putExtra(EXTRA_SHOW_FRAGMENT, (String)null);
doReturn(intent).when(mActivity).getIntent();
doReturn(mContext.getPackageName()).when(mActivity).getPackageName();
FakeFeatureFactory.setupForTest();
mActivity.getSharedPreferences(mContext.getPackageName() + "_preferences", 0);
}
@Test

View File

@@ -29,6 +29,7 @@ import static org.mockito.Mockito.when;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
@@ -37,6 +38,7 @@ import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settings.widget.WorkOnlyCategory;
import org.junit.Before;
@@ -46,6 +48,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
@@ -147,6 +150,7 @@ public class SettingsPreferenceFragmentTest {
}
@Test
@Config(shadows = ShadowFragment.class)
public void onCreate_hasExtraFragmentKey_shouldExpandPreferences() {
doReturn(mContext.getTheme()).when(mActivity).getTheme();
doReturn(mContext.getResources()).when(mFragment).getResources();
@@ -161,6 +165,7 @@ public class SettingsPreferenceFragmentTest {
}
@Test
@Config(shadows = ShadowFragment.class)
public void onCreate_noPreferenceScreen_shouldNotCrash() {
doReturn(mContext.getTheme()).when(mActivity).getTheme();
doReturn(mContext.getResources()).when(mFragment).getResources();
@@ -187,6 +192,24 @@ public class SettingsPreferenceFragmentTest {
verify(workOnlyCategory).setVisible(false);
}
@Test
public void showPinnedHeader_shouldBeVisible() {
mFragment.mPinnedHeaderFrameLayout = new FrameLayout(mContext);
mFragment.showPinnedHeader(true);
assertThat(mFragment.mPinnedHeaderFrameLayout.getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void hidePinnedHeader_shouldBeInvisible() {
mFragment.mPinnedHeaderFrameLayout = new FrameLayout(mContext);
mFragment.showPinnedHeader(false);
assertThat(mFragment.mPinnedHeaderFrameLayout.getVisibility()).isEqualTo(View.INVISIBLE);
}
public static class TestFragment extends SettingsPreferenceFragment {
@Override

View File

@@ -19,13 +19,22 @@ package com.android.settings;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.FeatureFlagUtils;
import androidx.preference.Preference;
import com.android.settings.core.FeatureFlags;
import org.junit.Before;
import org.junit.Test;
@@ -66,6 +75,7 @@ public class TetherSettingsTest {
@Test
public void testTetherNonIndexableKeys_tetherAvailable_keysNotReturned() {
FeatureFlagUtils.setEnabled(mContext, FeatureFlags.TETHER_ALL_IN_ONE, false);
// To let TetherUtil.isTetherAvailable return true, select one of the combinations
setupIsTetherAvailable(true);
@@ -100,6 +110,7 @@ public class TetherSettingsTest {
@Test
public void testTetherNonIndexableKeys_usbAvailable_usbKeyNotReturned() {
FeatureFlagUtils.setEnabled(mContext, FeatureFlags.TETHER_ALL_IN_ONE, false);
// We can ignore the condition of Utils.isMonkeyRunning()
// In normal case, monkey and robotest should not execute at the same time
when(mConnectivityManager.getTetherableUsbRegexs()).thenReturn(new String[]{"dummyRegex"});
@@ -122,6 +133,7 @@ public class TetherSettingsTest {
@Test
public void testTetherNonIndexableKeys_bluetoothAvailable_bluetoothKeyNotReturned() {
FeatureFlagUtils.setEnabled(mContext, FeatureFlags.TETHER_ALL_IN_ONE, false);
when(mConnectivityManager.getTetherableBluetoothRegexs())
.thenReturn(new String[]{"dummyRegex"});
@@ -131,6 +143,23 @@ public class TetherSettingsTest {
assertThat(niks).doesNotContain(TetherSettings.KEY_ENABLE_BLUETOOTH_TETHERING);
}
@Test
public void testSetFooterPreferenceTitle_isStaApConcurrencySupported_showStaApString() {
final TetherSettings spyTetherSettings = spy(new TetherSettings());
when(spyTetherSettings.getContext()).thenReturn(mContext);
final Preference mockPreference = mock(Preference.class);
when(spyTetherSettings.findPreference(TetherSettings.KEY_TETHER_PREFS_FOOTER))
.thenReturn(mockPreference);
final WifiManager mockWifiManager = mock(WifiManager.class);
when(mContext.getSystemService(Context.WIFI_SERVICE)).thenReturn(mockWifiManager);
when(mockWifiManager.isStaApConcurrencySupported()).thenReturn(true);
spyTetherSettings.setFooterPreferenceTitle();
verify(mockPreference, never()).setTitle(R.string.tethering_footer_info);
verify(mockPreference).setTitle(R.string.tethering_footer_info_sta_ap_concurrency);
}
private void setupIsTetherAvailable(boolean returnValue) {
when(mConnectivityManager.isTetheringSupported()).thenReturn(true);

View File

@@ -29,7 +29,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.ActionBar;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
@@ -67,6 +66,7 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowBinder;
import java.net.InetAddress;
import java.util.ArrayList;
@@ -281,4 +281,22 @@ public class UtilsTest {
assertThat(actionBar.getElevation()).isEqualTo(0.f);
}
@Test
public void isSettingsIntelligence_IsSI_returnTrue() {
final String siPackageName = mContext.getString(
R.string.config_settingsintelligence_package_name);
ShadowBinder.setCallingUid(USER_ID);
when(mPackageManager.getPackagesForUid(USER_ID)).thenReturn(new String[]{siPackageName});
assertThat(Utils.isSettingsIntelligence(mContext)).isTrue();
}
@Test
public void isSettingsIntelligence_IsNotSI_returnFalse() {
ShadowBinder.setCallingUid(USER_ID);
when(mPackageManager.getPackagesForUid(USER_ID)).thenReturn(new String[]{PACKAGE_NAME});
assertThat(Utils.isSettingsIntelligence(mContext)).isFalse();
}
}

View File

@@ -32,6 +32,9 @@ import android.os.Bundle;
import android.view.accessibility.AccessibilityManager;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.testutils.shadow.ShadowFragment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -39,6 +42,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowAccessibilityManager;
import org.xmlpull.v1.XmlPullParserException;
@@ -47,6 +51,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Config(shadows = ShadowFragment.class)
@RunWith(RobolectricTestRunner.class)
public class AccessibilityDetailsSettingsFragmentTest {
private final static String PACKAGE_NAME = "com.foo.bar";

View File

@@ -0,0 +1,89 @@
/*
* Copyright (C) 2020 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.settings.accessibility;
import static com.android.settings.accessibility.AccessibilityGestureNavigationTutorial.createAccessibilityTutorialDialog;
import static com.android.settings.accessibility.AccessibilityGestureNavigationTutorial.createShortcutTutorialPages;
import static com.android.settings.accessibility.AccessibilityUtil.UserShortcutType;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import androidx.appcompat.app.AlertDialog;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
/** Tests for {@link AccessibilityGestureNavigationTutorial}. */
@RunWith(RobolectricTestRunner.class)
public final class AccessibilityGestureNavigationTutorialTest {
private Context mContext;
private int mShortcutTypes;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mShortcutTypes = /* initial */ 0;
}
@Test(expected = IllegalArgumentException.class)
public void createTutorialPages_shortcutListIsEmpty_throwsException() {
createAccessibilityTutorialDialog(mContext, mShortcutTypes);
}
@Test
public void createTutorialPages_turnOnTripleTapShortcut_hasOnePage() {
mShortcutTypes |= UserShortcutType.TRIPLETAP;
final AlertDialog alertDialog =
createAccessibilityTutorialDialog(mContext, mShortcutTypes);
assertThat(createShortcutTutorialPages(mContext,
mShortcutTypes)).hasSize(/* expectedSize= */ 1);
assertThat(alertDialog).isNotNull();
}
@Test
public void createTutorialPages_turnOnSoftwareShortcut_hasOnePage() {
mShortcutTypes |= UserShortcutType.SOFTWARE;
final AlertDialog alertDialog =
createAccessibilityTutorialDialog(mContext, mShortcutTypes);
assertThat(createShortcutTutorialPages(mContext,
mShortcutTypes)).hasSize(/* expectedSize= */ 1);
assertThat(alertDialog).isNotNull();
}
@Test
public void createTutorialPages_turnOnSoftwareAndHardwareShortcuts_hasTwoPages() {
mShortcutTypes |= UserShortcutType.SOFTWARE;
mShortcutTypes |= UserShortcutType.HARDWARE;
final AlertDialog alertDialog =
createAccessibilityTutorialDialog(mContext, mShortcutTypes);
assertThat(createShortcutTutorialPages(mContext,
mShortcutTypes)).hasSize(/* expectedSize= */ 2);
assertThat(alertDialog).isNotNull();
}
}

View File

@@ -111,7 +111,7 @@ public class AccessibilityHearingAidPreferenceControllerTest {
@Test
public void onHearingAidStateChanged_connected_updateHearingAidSummary() {
when(mHearingAidProfile.getConnectedDevices()).thenReturn(generateHearingAidDeviceList());
mPreferenceController.onResume();
mPreferenceController.onStart();
Intent intent = new Intent(BluetoothHearingAid.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothHearingAid.EXTRA_STATE, BluetoothHearingAid.STATE_CONNECTED);
sendIntent(intent);
@@ -121,7 +121,7 @@ public class AccessibilityHearingAidPreferenceControllerTest {
@Test
public void onHearingAidStateChanged_disconnected_updateHearingAidSummary() {
mPreferenceController.onResume();
mPreferenceController.onStart();
Intent intent = new Intent(BluetoothHearingAid.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothHearingAid.EXTRA_STATE, BluetoothHearingAid.STATE_DISCONNECTED);
sendIntent(intent);
@@ -132,7 +132,7 @@ public class AccessibilityHearingAidPreferenceControllerTest {
@Test
public void onBluetoothStateChanged_bluetoothOff_updateHearingAidSummary() {
mPreferenceController.onResume();
mPreferenceController.onStart();
Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
sendIntent(intent);
@@ -173,11 +173,11 @@ public class AccessibilityHearingAidPreferenceControllerTest {
HEARING_AID_PREFERENCE);
mPreferenceController.setPreference(mHearingAidPreference);
//not call registerReceiver()
mPreferenceController.onResume();
mPreferenceController.onStart();
verify(mContext, never()).registerReceiver(any(), any());
//not call unregisterReceiver()
mPreferenceController.onPause();
mPreferenceController.onStop();
verify(mContext, never()).unregisterReceiver(any());
}

View File

@@ -18,57 +18,82 @@ package com.android.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.UiModeManager;
import android.content.ContentResolver;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.AccessibilityShortcutInfo;
import android.content.ComponentName;
import android.content.Context;
import android.os.Vibrator;
import android.provider.DeviceConfig;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.provider.Settings;
import androidx.preference.Preference;
import android.view.accessibility.AccessibilityManager;
import com.android.settings.R;
import com.android.settings.testutils.XmlTestUtils;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
import com.android.settingslib.RestrictedPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowAccessibilityManager;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class AccessibilitySettingsTest {
private static final String VIBRATION_PREFERENCE_SCREEN = "vibration_preference_screen";
private static final String ACCESSIBILITY_CONTROL_TIMEOUT_PREFERENCE =
"accessibility_control_timeout_preference_fragment";
private static final String DARK_UI_MODE_PREFERENCE =
"dark_ui_mode_accessibility";
private static final String DUMMY_PACKAGE_NAME = "com.dummy.example";
private static final String DUMMY_CLASS_NAME = DUMMY_PACKAGE_NAME + ".dummy_a11y_service";
private static final ComponentName DUMMY_COMPONENT_NAME = new ComponentName(DUMMY_PACKAGE_NAME,
DUMMY_CLASS_NAME);
private static final int ON = 1;
private static final int OFF = 0;
private static final String EMPTY_STRING = "";
private static final String DEFAULT_SUMMARY = "default summary";
private static final String DEFAULT_DESCRIPTION = "default description";
private static final String DEFAULT_LABEL = "default label";
private static final Boolean SERVICE_ENABLED = true;
private static final Boolean SERVICE_DISABLED = false;
private Context mContext;
private ContentResolver mContentResolver;
private AccessibilitySettings mSettings;
private UiModeManager mUiModeManager;
private ShadowAccessibilityManager mShadowAccessibilityManager;
private AccessibilityServiceInfo mServiceInfo;
@Mock
private AccessibilityShortcutInfo mShortcutInfo;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mContentResolver = mContext.getContentResolver();
mContext = spy(RuntimeEnvironment.application);
mSettings = spy(new AccessibilitySettings());
mServiceInfo = spy(getMockAccessibilityServiceInfo());
mShadowAccessibilityManager = Shadow.extract(AccessibilityManager.getInstance(mContext));
mShadowAccessibilityManager.setInstalledAccessibilityServiceList(new ArrayList<>());
doReturn(mContext).when(mSettings).getContext();
mUiModeManager = mContext.getSystemService(UiModeManager.class);
}
@Test
public void testNonIndexableKeys_existInXmlLayout() {
public void getNonIndexableKeys_existInXmlLayout() {
final List<String> niks = AccessibilitySettings.SEARCH_INDEX_DATA_PROVIDER
.getNonIndexableKeys(mContext);
final List<String> keys =
@@ -77,111 +102,183 @@ public class AccessibilitySettingsTest {
assertThat(keys).containsAllIn(niks);
}
@Test
public void testUpdateVibrationSummary_shouldUpdateSummary() {
final Preference vibrationPreferenceScreen = new Preference(mContext);
doReturn(vibrationPreferenceScreen).when(mSettings).findPreference(
VIBRATION_PREFERENCE_SCREEN);
vibrationPreferenceScreen.setKey(VIBRATION_PREFERENCE_SCREEN);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.NOTIFICATION_VIBRATION_INTENSITY,
Vibrator.VIBRATION_INTENSITY_OFF);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_INTENSITY,
Vibrator.VIBRATION_INTENSITY_OFF);
mSettings.updateVibrationSummary(vibrationPreferenceScreen);
assertThat(vibrationPreferenceScreen.getSummary()).isEqualTo(
VibrationIntensityPreferenceController.getIntensityString(mContext,
Vibrator.VIBRATION_INTENSITY_OFF));
}
@Test
public void testUpdateAccessibilityTimeoutSummary_shouldUpdateSummary() {
String[] testingValues = {null, "0", "10000", "30000", "60000", "120000"};
int[] exceptedResIds = {R.string.accessibility_timeout_default,
R.string.accessibility_timeout_default,
R.string.accessibility_timeout_10secs,
R.string.accessibility_timeout_30secs,
R.string.accessibility_timeout_1min,
R.string.accessibility_timeout_2mins
};
for (int i = 0; i < testingValues.length; i++) {
Settings.Secure.putString(mContentResolver,
Settings.Secure.ACCESSIBILITY_INTERACTIVE_UI_TIMEOUT_MS, testingValues[i]);
verifyAccessibilityTimeoutSummary(ACCESSIBILITY_CONTROL_TIMEOUT_PREFERENCE,
exceptedResIds[i]);
}
}
@Test
public void testUpdateAccessibilityControlTimeoutSummary_invalidData_shouldUpdateSummary() {
String[] testingValues = {"-9009", "98277466643738977979666555536362343", "Hello,a prank"};
for (String value : testingValues) {
Settings.Secure.putString(mContentResolver,
Settings.Secure.ACCESSIBILITY_NON_INTERACTIVE_UI_TIMEOUT_MS, value);
verifyAccessibilityTimeoutSummary(ACCESSIBILITY_CONTROL_TIMEOUT_PREFERENCE,
R.string.accessibility_timeout_default);
Settings.Secure.putString(mContentResolver,
Settings.Secure.ACCESSIBILITY_INTERACTIVE_UI_TIMEOUT_MS, value);
verifyAccessibilityTimeoutSummary(ACCESSIBILITY_CONTROL_TIMEOUT_PREFERENCE,
R.string.accessibility_timeout_default);
}
}
@Test
@Config(shadows = {ShadowDeviceConfig.class})
public void testIsRampingRingerEnabled_bothFlagsOn_Enabled() {
public void isRampingRingerEnabled_settingsFlagOn_Enabled() {
Settings.Global.putInt(
mContext.getContentResolver(), Settings.Global.APPLY_RAMPING_RINGER, 1 /* ON */);
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TELEPHONY,
AccessibilitySettings.RAMPING_RINGER_ENABLED, "true", false /* makeDefault*/);
assertThat(AccessibilitySettings.isRampingRingerEnabled(mContext)).isTrue();
mContext.getContentResolver(), Settings.Global.APPLY_RAMPING_RINGER, ON);
assertThat(AccessibilitySettings.isRampingRingerEnabled(mContext)).isTrue();
}
@Test
@Config(shadows = {ShadowDeviceConfig.class})
public void testIsRampingRingerEnabled_settingsFlagOff_Disabled() {
public void isRampingRingerEnabled_settingsFlagOff_Disabled() {
Settings.Global.putInt(
mContext.getContentResolver(), Settings.Global.APPLY_RAMPING_RINGER, 0 /* OFF */);
assertThat(AccessibilitySettings.isRampingRingerEnabled(mContext)).isFalse();
mContext.getContentResolver(), Settings.Global.APPLY_RAMPING_RINGER, OFF);
assertThat(AccessibilitySettings.isRampingRingerEnabled(mContext)).isFalse();
}
@Test
@Config(shadows = {ShadowDeviceConfig.class})
public void testIsRampingRingerEnabled_deviceConfigFlagOff_Disabled() {
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TELEPHONY,
AccessibilitySettings.RAMPING_RINGER_ENABLED, "false", false /* makeDefault*/);
assertThat(AccessibilitySettings.isRampingRingerEnabled(mContext)).isFalse();
public void getServiceSummary_serviceCrash_showsStopped() {
mServiceInfo.crashed = true;
final CharSequence summary = AccessibilitySettings.getServiceSummary(mContext,
mServiceInfo, SERVICE_ENABLED);
assertThat(summary).isEqualTo(
mContext.getString(R.string.accessibility_summary_state_stopped));
}
private void verifyAccessibilityTimeoutSummary(String preferenceKey, int resId) {
final Preference preference = new Preference(mContext);
doReturn(preference).when(mSettings).findPreference(preferenceKey);
preference.setKey(preferenceKey);
mSettings.updateAccessibilityTimeoutSummary(mContentResolver, preference);
@Test
public void getServiceSummary_invisibleToggle_shortcutDisabled_showsOffSummary() {
setInvisibleToggleFragmentType(mServiceInfo);
doReturn(DEFAULT_SUMMARY).when(mServiceInfo).loadSummary(any());
assertThat(preference.getSummary()).isEqualTo(mContext.getResources().getString(resId));
final CharSequence summary = AccessibilitySettings.getServiceSummary(mContext,
mServiceInfo, SERVICE_ENABLED);
assertThat(summary).isEqualTo(
mContext.getString(R.string.preference_summary_default_combination,
mContext.getString(R.string.accessibility_summary_shortcut_disabled),
DEFAULT_SUMMARY));
}
private String modeToDescription(int mode) {
String[] values = mContext.getResources().getStringArray(R.array.dark_ui_mode_entries);
switch (mode) {
case UiModeManager.MODE_NIGHT_YES:
return values[0];
case UiModeManager.MODE_NIGHT_NO:
case UiModeManager.MODE_NIGHT_AUTO:
default:
return values[1];
@Test
public void getServiceSummary_enableService_showsEnabled() {
doReturn(EMPTY_STRING).when(mServiceInfo).loadSummary(any());
final CharSequence summary = AccessibilitySettings.getServiceSummary(mContext,
mServiceInfo, SERVICE_ENABLED);
assertThat(summary).isEqualTo(
mContext.getString(R.string.accessibility_summary_state_enabled));
}
@Test
public void getServiceSummary_disableService_showsDisabled() {
doReturn(EMPTY_STRING).when(mServiceInfo).loadSummary(any());
final CharSequence summary = AccessibilitySettings.getServiceSummary(mContext,
mServiceInfo, SERVICE_DISABLED);
assertThat(summary).isEqualTo(
mContext.getString(R.string.accessibility_summary_state_disabled));
}
@Test
public void getServiceSummary_enableServiceAndHasSummary_showsEnabledSummary() {
final String service_enabled = mContext.getString(
R.string.accessibility_summary_state_enabled);
doReturn(DEFAULT_SUMMARY).when(mServiceInfo).loadSummary(any());
final CharSequence summary = AccessibilitySettings.getServiceSummary(mContext,
mServiceInfo, SERVICE_ENABLED);
assertThat(summary).isEqualTo(
mContext.getString(R.string.preference_summary_default_combination, service_enabled,
DEFAULT_SUMMARY));
}
@Test
public void getServiceSummary_disableServiceAndHasSummary_showsCombineDisabledSummary() {
final String service_disabled = mContext.getString(
R.string.accessibility_summary_state_disabled);
doReturn(DEFAULT_SUMMARY).when(mServiceInfo).loadSummary(any());
final CharSequence summary = AccessibilitySettings.getServiceSummary(mContext,
mServiceInfo, SERVICE_DISABLED);
assertThat(summary).isEqualTo(
mContext.getString(R.string.preference_summary_default_combination,
service_disabled, DEFAULT_SUMMARY));
}
@Test
public void getServiceDescription_serviceCrash_showsStopped() {
mServiceInfo.crashed = true;
final CharSequence description = AccessibilitySettings.getServiceDescription(mContext,
mServiceInfo, SERVICE_ENABLED);
assertThat(description).isEqualTo(
mContext.getString(R.string.accessibility_description_state_stopped));
}
@Test
public void getServiceDescription_haveDescription_showsDescription() {
doReturn(DEFAULT_DESCRIPTION).when(mServiceInfo).loadDescription(any());
final CharSequence description = AccessibilitySettings.getServiceDescription(mContext,
mServiceInfo, SERVICE_ENABLED);
assertThat(description).isEqualTo(DEFAULT_DESCRIPTION);
}
@Test
public void createAccessibilityServicePreferenceList_hasOneInfo_containsSameKey() {
final String key = DUMMY_COMPONENT_NAME.flattenToString();
final AccessibilitySettings.RestrictedPreferenceHelper helper =
new AccessibilitySettings.RestrictedPreferenceHelper(mContext);
final List<AccessibilityServiceInfo> infoList = new ArrayList<>(
Collections.singletonList(mServiceInfo));
final List<RestrictedPreference> preferenceList =
helper.createAccessibilityServicePreferenceList(infoList);
RestrictedPreference preference = preferenceList.get(0);
assertThat(preference.getKey()).isEqualTo(key);
}
@Test
public void createAccessibilityActivityPreferenceList_hasOneInfo_containsSameKey() {
final String key = DUMMY_COMPONENT_NAME.flattenToString();
final AccessibilitySettings.RestrictedPreferenceHelper helper =
new AccessibilitySettings.RestrictedPreferenceHelper(mContext);
setMockAccessibilityShortcutInfo(mShortcutInfo);
final List<AccessibilityShortcutInfo> infoList = new ArrayList<>(
Collections.singletonList(mShortcutInfo));
final List<RestrictedPreference> preferenceList =
helper.createAccessibilityActivityPreferenceList(infoList);
RestrictedPreference preference = preferenceList.get(0);
assertThat(preference.getKey()).isEqualTo(key);
}
private AccessibilityServiceInfo getMockAccessibilityServiceInfo() {
final ApplicationInfo applicationInfo = new ApplicationInfo();
final ServiceInfo serviceInfo = new ServiceInfo();
applicationInfo.packageName = DUMMY_PACKAGE_NAME;
serviceInfo.packageName = DUMMY_PACKAGE_NAME;
serviceInfo.name = DUMMY_CLASS_NAME;
serviceInfo.applicationInfo = applicationInfo;
final ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
try {
final AccessibilityServiceInfo info = new AccessibilityServiceInfo(resolveInfo,
mContext);
info.setComponentName(DUMMY_COMPONENT_NAME);
return info;
} catch (XmlPullParserException | IOException e) {
// Do nothing
}
return null;
}
private void setMockAccessibilityShortcutInfo(AccessibilityShortcutInfo mockInfo) {
final ActivityInfo activityInfo = Mockito.mock(ActivityInfo.class);
when(mockInfo.getActivityInfo()).thenReturn(activityInfo);
when(activityInfo.loadLabel(any())).thenReturn(DEFAULT_LABEL);
when(mockInfo.loadSummary(any())).thenReturn(DEFAULT_SUMMARY);
when(mockInfo.loadDescription(any())).thenReturn(DEFAULT_DESCRIPTION);
when(mockInfo.getComponentName()).thenReturn(DUMMY_COMPONENT_NAME);
}
private void setInvisibleToggleFragmentType(AccessibilityServiceInfo info) {
info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion = Build.VERSION_CODES.R;
info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON;
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (C) 2020 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.settings.accessibility;
import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.UserHandle;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class AccessibilityShortcutPreferenceControllerTest {
private Context mContext;
private SwitchPreference mPreference;
private AccessibilityShortcutPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new AccessibilityShortcutPreferenceController(mContext,
"accessibility_shortcut_preference");
}
@Test
public void isChecked_enabledShortcutOnLockScreen_shouldReturnTrue() {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN, ON, UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void isChecked_disabledShortcutOnLockScreen_shouldReturnFalse() {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN, OFF,
UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void setChecked_setTrue_shouldEnableShortcutOnLockScreen() {
mController.setChecked(true);
assertThat(Settings.Secure.getIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN, OFF,
UserHandle.USER_CURRENT)).isEqualTo(ON);
}
@Test
public void setChecked_setFalse_shouldDisableShortcutOnLockScreen() {
mController.setChecked(false);
assertThat(Settings.Secure.getIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SHORTCUT_ON_LOCK_SCREEN, ON,
UserHandle.USER_CURRENT)).isEqualTo(OFF);
}
}

View File

@@ -121,6 +121,16 @@ public class AccessibilitySlicePreferenceControllerTest {
new AccessibilitySlicePreferenceController(mContext, "not_split_by_slash");
}
@Test
public void isSliceable_returnTrue() {
assertThat(mController.isSliceable()).isTrue();
}
@Test
public void isPublicSlice_returnTrue() {
assertThat(mController.isPublicSlice()).isTrue();
}
private List<AccessibilityServiceInfo> getFakeServiceList() {
final List<AccessibilityServiceInfo> infoList = new ArrayList<>();

View File

@@ -31,8 +31,8 @@ import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.R;
import com.android.settings.widget.RadioButtonPreference;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.RadioButtonPreference;
import org.junit.Before;
import org.junit.Test;

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class AccessibilityTimeoutPreferenceControllerTest {
private Context mContext;
private AccessibilityTimeoutPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new AccessibilityTimeoutPreferenceController(mContext, "control_timeout");
}
@Test
public void getAvailabilityStatus_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
public void getSummary_byDefault_shouldReturnDefaultSummary() {
final String[] timeoutSummarys = mContext.getResources().getStringArray(
R.array.accessibility_timeout_summaries);
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_INTERACTIVE_UI_TIMEOUT_MS, "0");
assertThat(mController.getSummary()).isEqualTo(timeoutSummarys[0]);
}
@Test
public void getSummary_invalidTimeout_shouldReturnDefaultSummary() {
final String[] timeoutSummarys = mContext.getResources().getStringArray(
R.array.accessibility_timeout_summaries);
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_INTERACTIVE_UI_TIMEOUT_MS, "invalid_timeout");
assertThat(mController.getSummary()).isEqualTo(timeoutSummarys[0]);
}
@Test
public void getSummary_validTimeout_shouldReturnValidSummary() {
final String[] timeoutSummarys = mContext.getResources().getStringArray(
R.array.accessibility_timeout_summaries);
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_INTERACTIVE_UI_TIMEOUT_MS, "60000");
assertThat(mController.getSummary()).isEqualTo(timeoutSummarys[3]);
}
}

View File

@@ -0,0 +1,269 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.provider.Settings;
import com.android.settings.R;
import com.android.settings.accessibility.AccessibilityUtil.UserShortcutType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
@RunWith(RobolectricTestRunner.class)
public final class AccessibilityUtilTest {
private static final int ON = 1;
private static final int OFF = 0;
private static final String SECURE_TEST_KEY = "secure_test_key";
private static final String DUMMY_PACKAGE_NAME = "com.dummy.example";
private static final String DUMMY_CLASS_NAME = DUMMY_PACKAGE_NAME + ".dummy_a11y_service";
private static final String DUMMY_CLASS_NAME2 = DUMMY_PACKAGE_NAME + ".dummy_a11y_service2";
private static final ComponentName DUMMY_COMPONENT_NAME = new ComponentName(DUMMY_PACKAGE_NAME,
DUMMY_CLASS_NAME);
private static final ComponentName DUMMY_COMPONENT_NAME2 = new ComponentName(DUMMY_PACKAGE_NAME,
DUMMY_CLASS_NAME2);
private static final String SOFTWARE_SHORTCUT_KEY =
Settings.Secure.ACCESSIBILITY_BUTTON_TARGETS;
private static final String HARDWARE_SHORTCUT_KEY =
Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE;
private Context mContext;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
}
@Test
public void capitalize_shouldReturnCapitalizedString() {
assertThat(AccessibilityUtil.capitalize(null)).isNull();
assertThat(AccessibilityUtil.capitalize("")).isEmpty();
assertThat(AccessibilityUtil.capitalize("Hans")).isEqualTo("Hans");
assertThat(AccessibilityUtil.capitalize("hans")).isEqualTo("Hans");
assertThat(AccessibilityUtil.capitalize(",hans")).isEqualTo(",hans");
assertThat(AccessibilityUtil.capitalize("Hans, Hans")).isEqualTo("Hans, hans");
}
@Test
public void getSummary_hasValueAndEqualsToOne_shouldReturnOnString() {
Settings.Secure.putInt(mContext.getContentResolver(), SECURE_TEST_KEY, ON);
final CharSequence result = AccessibilityUtil.getSummary(mContext, SECURE_TEST_KEY);
assertThat(result)
.isEqualTo(mContext.getText(R.string.accessibility_feature_state_on));
}
@Test
public void getSummary_hasValueAndEqualsToZero_shouldReturnOffString() {
Settings.Secure.putInt(mContext.getContentResolver(), SECURE_TEST_KEY, OFF);
final CharSequence result = AccessibilityUtil.getSummary(mContext, SECURE_TEST_KEY);
assertThat(result)
.isEqualTo(mContext.getText(R.string.accessibility_feature_state_off));
}
@Test
public void getSummary_noValue_shouldReturnOffString() {
final CharSequence result = AccessibilityUtil.getSummary(mContext, SECURE_TEST_KEY);
assertThat(result)
.isEqualTo(mContext.getText(R.string.accessibility_feature_state_off));
}
@Test
public void getAccessibilityServiceFragmentType_targetSdkQ_volumeShortcutType() {
final AccessibilityServiceInfo info = getMockAccessibilityServiceInfo();
info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion = Build.VERSION_CODES.Q;
info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON;
assertThat(AccessibilityUtil.getAccessibilityServiceFragmentType(info)).isEqualTo(
AccessibilityUtil.AccessibilityServiceFragmentType.VOLUME_SHORTCUT_TOGGLE);
}
@Test
public void getAccessibilityServiceFragmentType_targetSdkR_HaveA11yButton_invisibleType() {
final AccessibilityServiceInfo info = getMockAccessibilityServiceInfo();
info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion = Build.VERSION_CODES.R;
info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON;
assertThat(AccessibilityUtil.getAccessibilityServiceFragmentType(info)).isEqualTo(
AccessibilityUtil.AccessibilityServiceFragmentType.INVISIBLE_TOGGLE);
}
@Test
public void getAccessibilityServiceFragmentType_targetSdkR_NoA11yButton_toggleType() {
final AccessibilityServiceInfo info = getMockAccessibilityServiceInfo();
info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion = Build.VERSION_CODES.R;
info.flags |= ~AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON;
assertThat(AccessibilityUtil.getAccessibilityServiceFragmentType(info)).isEqualTo(
AccessibilityUtil.AccessibilityServiceFragmentType.TOGGLE);
}
@Test
public void hasValueInSettings_putValue_hasValue() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
assertThat(AccessibilityUtil.hasValueInSettings(mContext, UserShortcutType.SOFTWARE,
DUMMY_COMPONENT_NAME)).isTrue();
}
@Test
public void getUserShortcutTypeFromSettings_putOneValue_hasValue() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
final int shortcutType = AccessibilityUtil.getUserShortcutTypesFromSettings(mContext,
DUMMY_COMPONENT_NAME);
assertThat(
(shortcutType & UserShortcutType.SOFTWARE) == UserShortcutType.SOFTWARE).isTrue();
}
@Test
public void getUserShortcutTypeFromSettings_putTwoValues_hasValue() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
putStringIntoSettings(HARDWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
final int shortcutType = AccessibilityUtil.getUserShortcutTypesFromSettings(mContext,
DUMMY_COMPONENT_NAME);
assertThat(
(shortcutType & UserShortcutType.SOFTWARE) == UserShortcutType.SOFTWARE).isTrue();
assertThat(
(shortcutType & UserShortcutType.HARDWARE) == UserShortcutType.HARDWARE).isTrue();
}
@Test
public void optInAllValuesToSettings_optInValue_haveMatchString() {
int shortcutTypes = UserShortcutType.SOFTWARE | UserShortcutType.HARDWARE;
AccessibilityUtil.optInAllValuesToSettings(mContext, shortcutTypes, DUMMY_COMPONENT_NAME);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString());
assertThat(getStringFromSettings(HARDWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString());
}
@Test
public void optInValueToSettings_optInValue_haveMatchString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
AccessibilityUtil.optInValueToSettings(mContext, UserShortcutType.SOFTWARE,
DUMMY_COMPONENT_NAME2);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString() + ":"
+ DUMMY_COMPONENT_NAME2.flattenToString());
}
@Test
public void optInValueToSettings_optInTwoValues_haveMatchString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
AccessibilityUtil.optInValueToSettings(mContext, UserShortcutType.SOFTWARE,
DUMMY_COMPONENT_NAME2);
AccessibilityUtil.optInValueToSettings(mContext, UserShortcutType.SOFTWARE,
DUMMY_COMPONENT_NAME2);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString() + ":"
+ DUMMY_COMPONENT_NAME2.flattenToString());
}
@Test
public void optOutAllValuesToSettings_optOutValue_emptyString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
putStringIntoSettings(HARDWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
int shortcutTypes =
UserShortcutType.SOFTWARE | UserShortcutType.HARDWARE | UserShortcutType.TRIPLETAP;
AccessibilityUtil.optOutAllValuesFromSettings(mContext, shortcutTypes,
DUMMY_COMPONENT_NAME);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEmpty();
assertThat(getStringFromSettings(HARDWARE_SHORTCUT_KEY)).isEmpty();
}
@Test
public void optOutValueFromSettings_optOutValue_emptyString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
AccessibilityUtil.optOutValueFromSettings(mContext, UserShortcutType.SOFTWARE,
DUMMY_COMPONENT_NAME);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEmpty();
}
@Test
public void optOutValueFromSettings_optOutValue_haveMatchString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString() + ":"
+ DUMMY_COMPONENT_NAME2.flattenToString());
AccessibilityUtil.optOutValueFromSettings(mContext, UserShortcutType.SOFTWARE,
DUMMY_COMPONENT_NAME2);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString());
}
private AccessibilityServiceInfo getMockAccessibilityServiceInfo() {
final ApplicationInfo applicationInfo = new ApplicationInfo();
final ServiceInfo serviceInfo = new ServiceInfo();
applicationInfo.packageName = DUMMY_PACKAGE_NAME;
serviceInfo.packageName = DUMMY_PACKAGE_NAME;
serviceInfo.name = DUMMY_CLASS_NAME;
serviceInfo.applicationInfo = applicationInfo;
final ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
try {
final AccessibilityServiceInfo info = new AccessibilityServiceInfo(resolveInfo,
mContext);
info.setComponentName(DUMMY_COMPONENT_NAME);
return info;
} catch (XmlPullParserException | IOException e) {
// Do nothing
}
return null;
}
private void putStringIntoSettings(String key, String componentName) {
Settings.Secure.putString(mContext.getContentResolver(), key, componentName);
}
private String getStringFromSettings(String key) {
return Settings.Secure.getString(mContext.getContentResolver(), key);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import android.view.accessibility.AccessibilityManager;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class AutoclickPreferenceControllerTest {
private Context mContext;
private AutoclickPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new AutoclickPreferenceController(mContext, "auto_click");
}
@Test
public void getAvailabilityStatus_shouldReturnAvailableUnsearchable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getSummary_disabledAutoclick_shouldReturnOffSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_AUTOCLICK_ENABLED, 0);
assertThat(mController.getSummary())
.isEqualTo(mContext.getText(R.string.accessibility_feature_state_off));
}
@Test
public void getSummary_enabledAutoclick_shouldReturnOnSummary() {
final int autoclickDelayDefault = AccessibilityManager.AUTOCLICK_DELAY_DEFAULT;
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_AUTOCLICK_ENABLED, 1);
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_AUTOCLICK_DELAY, autoclickDelayDefault);
assertThat(mController.getSummary())
.isEqualTo(ToggleAutoclickPreferenceFragment.getAutoclickPreferenceSummary(
mContext.getResources(), autoclickDelayDefault));
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class CaptioningPreferenceControllerTest {
private static final int ON = 1;
private static final int OFF = 0;
private Context mContext;
private CaptioningPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new CaptioningPreferenceController(mContext, "captioning_pref");
}
@Test
public void getAvailabilityStatus_byDefault_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getSummary_enabledCaptions_shouldReturnOnSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_CAPTIONING_ENABLED, ON);
assertThat(mController.getSummary()).isEqualTo(
mContext.getText(R.string.accessibility_feature_state_on));
}
@Test
public void getSummary_disabledCaptions_shouldReturnOffSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_CAPTIONING_ENABLED, OFF);
assertThat(mController.getSummary()).isEqualTo(
mContext.getText(R.string.accessibility_feature_state_off));
}
}

View File

@@ -16,82 +16,57 @@
package com.android.settings.accessibility;
import static com.android.settings.accessibility.ColorInversionPreferenceController.OFF;
import static com.android.settings.accessibility.ColorInversionPreferenceController.ON;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@RunWith(RobolectricTestRunner.class)
public class ColorInversionPreferenceControllerTest {
private static final int UNKNOWN = -1;
private static final String PREF_KEY = "toggle_inversion_preference";
private static final String DISPLAY_INVERSION_ENABLED =
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED;
private Context mContext;
private ColorInversionPreferenceController mController;
private SwitchPreference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new ColorInversionPreferenceController(mContext, "pref_key");
mPreference = new SwitchPreference(mContext);
mController.updateState(mPreference);
mController = new ColorInversionPreferenceController(mContext, PREF_KEY);
}
@Test
public void getAvailabilityStatus_available() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
public void isChecked_enabled() {
public void getSummary_enabledColorInversion_shouldReturnOnSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, ON);
DISPLAY_INVERSION_ENABLED, State.ON);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
assertThat(mController.getSummary().toString().contains(
mContext.getText(R.string.accessibility_feature_state_on))).isTrue();
}
@Test
public void isChecked_disabled() {
public void getSummary_disabledColorInversion_shouldReturnOffSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, OFF);
DISPLAY_INVERSION_ENABLED, State.OFF);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
assertThat(mController.getSummary().toString().contains(
mContext.getText(R.string.accessibility_feature_state_off))).isTrue();
}
@Test
public void setChecked_enabled() {
mController.setChecked(true);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, UNKNOWN)).isEqualTo(ON);
}
@Test
public void setChecked_disabled() {
mController.setChecked(false);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, UNKNOWN)).isEqualTo(OFF);
@Retention(RetentionPolicy.SOURCE)
private @interface State {
int OFF = 0;
int ON = 1;
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class DaltonizerPreferenceControllerTest {
private static final String PREF_KEY = "daltonizer_preference";
private static final int ON = 1;
private static final int OFF = 0;
private Context mContext;
private DaltonizerPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new DaltonizerPreferenceController(mContext, PREF_KEY);
}
@Test
public void getSummary_enabledColorCorrection_shouldReturnOnSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, ON);
assertThat(mController.getSummary().toString().contains(
mContext.getText(R.string.accessibility_feature_state_on))).isTrue();
}
@Test
public void getSummary_disabledColorCorrection_shouldReturnOffSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, OFF);
assertThat(mController.getSummary().toString().contains(
mContext.getText(R.string.accessibility_feature_state_off))).isTrue();
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.RadioButtonPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class DaltonizerRadioButtonPreferenceControllerTest implements
DaltonizerRadioButtonPreferenceController.OnChangeListener {
private static final String PREF_KEY = "daltonizer_mode_protanomaly";
private static final String PREF_VALUE = "11";
private static final String PREF_FAKE_VALUE = "-1";
private DaltonizerRadioButtonPreferenceController mController;
@Mock
private RadioButtonPreference mMockPref;
private Context mContext;
@Mock
private PreferenceScreen mScreen;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new DaltonizerRadioButtonPreferenceController(mContext, mock(Lifecycle.class),
PREF_KEY);
mController.setOnChangeListener(this);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mMockPref);
when(mMockPref.getKey()).thenReturn(PREF_KEY);
mController.displayPreference(mScreen);
}
@Override
public void onCheckedChanged(Preference preference) {
mController.updateState(preference);
}
@Test
public void isAvailable() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void updateState_notChecked() {
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_FAKE_VALUE);
mController.updateState(mMockPref);
// the first checked state is set to false by control
verify(mMockPref, atLeastOnce()).setChecked(false);
verify(mMockPref, never()).setChecked(true);
}
@Test
public void updateState_checked() {
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_VALUE);
mController.updateState(mMockPref);
// the first checked state is set to false by control
verify(mMockPref, atLeastOnce()).setChecked(false);
verify(mMockPref, atLeastOnce()).setChecked(true);
}
@Test
public void onRadioButtonClick_shouldReturnDaltonizerValue() {
mController.onRadioButtonClicked(mMockPref);
final String accessibilityDaltonizerValue = Settings.Secure.getString(
mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER);
assertThat(accessibilityDaltonizerValue).isEqualTo(PREF_VALUE);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.android.settings.accessibility.DisableAnimationsPreferenceController.ANIMATION_OFF_VALUE;
import static com.android.settings.accessibility.DisableAnimationsPreferenceController.ANIMATION_ON_VALUE;
import static com.android.settings.accessibility.DisableAnimationsPreferenceController.TOGGLE_ANIMATION_TARGETS;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class DisableAnimationsPreferenceControllerTest {
private Context mContext;
private SwitchPreference mPreference;
private DisableAnimationsPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new DisableAnimationsPreferenceController(mContext, "disable_animation");
}
@Test
public void getAvailabilityStatus_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
public void isChecked_enabledAnimation_shouldReturnFalse() {
for (String animationPreference : TOGGLE_ANIMATION_TARGETS) {
Settings.Global.putString(mContext.getContentResolver(), animationPreference,
ANIMATION_ON_VALUE);
}
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void isChecked_disabledAnimation_shouldReturnTrue() {
for (String animationPreference : TOGGLE_ANIMATION_TARGETS) {
Settings.Global.putString(mContext.getContentResolver(), animationPreference,
ANIMATION_OFF_VALUE);
}
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void setChecked_disabledAnimation_shouldDisableAnimationTargets() {
mController.setChecked(true);
for (String animationSetting : TOGGLE_ANIMATION_TARGETS) {
assertThat(Settings.Global.getString(mContext.getContentResolver(), animationSetting))
.isEqualTo(ANIMATION_OFF_VALUE);
}
}
@Test
public void setChecked_enabledAnimation_shouldEnableAnimationTargets() {
mController.setChecked(false);
for (String animationSetting : TOGGLE_ANIMATION_TARGETS) {
assertThat(Settings.Global.getString(mContext.getContentResolver(), animationSetting))
.isEqualTo(ANIMATION_ON_VALUE);
}
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class HighTextContrastPreferenceControllerTest {
private static final int ON = 1;
private static final int OFF = 0;
private static final int UNKNOWN = -1;
private Context mContext;
private SwitchPreference mPreference;
private HighTextContrastPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new HighTextContrastPreferenceController(mContext, "text_contrast");
}
@Test
public void getAvailabilityStatus_byDefault_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
public void isChecked_enabledTextContrast_shouldReturnTrue() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_HIGH_TEXT_CONTRAST_ENABLED, ON);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void isChecked_disabledTextContrast_shouldReturnFalse() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_HIGH_TEXT_CONTRAST_ENABLED, OFF);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void setChecked_setTrue_shouldEnableTextContrast() {
mController.setChecked(true);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_HIGH_TEXT_CONTRAST_ENABLED, UNKNOWN)).isEqualTo(ON);
}
@Test
public void setChecked_setFalse_shouldDisableTextContrast() {
mController.setChecked(false);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_HIGH_TEXT_CONTRAST_ENABLED, UNKNOWN)).isEqualTo(OFF);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.text.Editable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import androidx.preference.PreferenceViewHolder;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.xml.sax.XMLReader;
/** Tests for {@link HtmlTextPreference} */
@RunWith(RobolectricTestRunner.class)
public final class HtmlTextPreferenceTest {
private HtmlTextPreference mHtmlTextPreference;
private PreferenceViewHolder mPreferenceViewHolder;
private String mHandledTag;
private final Html.TagHandler mTagHandler = new Html.TagHandler() {
@Override
public void handleTag(boolean opening, String tag, Editable editable, XMLReader xmlReader) {
mHandledTag = tag;
}
};
@Before
public void setUp() {
final Context context = RuntimeEnvironment.application;
mHtmlTextPreference = new HtmlTextPreference(context);
final LayoutInflater inflater = LayoutInflater.from(context);
final View view =
inflater.inflate(R.layout.preference_static_text, null);
mPreferenceViewHolder = PreferenceViewHolder.createInstanceForTests(view);
}
@Test
public void testTagHandler() {
final String testStr = "<testTag>Real description</testTag>";
mHtmlTextPreference.setSummary(testStr);
mHtmlTextPreference.setTagHandler(mTagHandler);
mHtmlTextPreference.onBindViewHolder(mPreferenceViewHolder);
assertThat(mHandledTag).isEqualTo("testTag");
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.android.settings.accessibility.LargePointerIconPreferenceController.OFF;
import static com.android.settings.accessibility.LargePointerIconPreferenceController.ON;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class LargePointerIconPreferenceControllerTest {
private static final int UNKNOWN = -1;
private Context mContext;
private SwitchPreference mPreference;
private LargePointerIconPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new LargePointerIconPreferenceController(mContext, "large_pointer");
}
@Test
public void getAvailabilityStatus_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
public void isChecked_enabledLargePointer_shouldReturnTrue() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON, ON);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void isChecked_disabledLargePointer_shouldReturnFalse() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON, OFF);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void setChecked_enabled_shouldEnableLargePointer() {
mController.setChecked(true);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON, UNKNOWN)).isEqualTo(ON);
}
@Test
public void setChecked_disabled_shouldDisableLargePointer() {
mController.setChecked(false);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON, UNKNOWN)).isEqualTo(OFF);
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.UserHandle;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.internal.view.RotationPolicy;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.testutils.shadow.ShadowRotationPolicy;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class LockScreenRotationPreferenceControllerTest {
private Context mContext;
private SwitchPreference mPreference;
private LockScreenRotationPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new LockScreenRotationPreferenceController(mContext, "lock_screen");
}
@Test
@Config(shadows = {ShadowRotationPolicy.class})
public void getAvailabilityStatus_supportedRotation_shouldReturnAvailable() {
ShadowRotationPolicy.setRotationSupported(true /* supported */);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
@Config(shadows = {ShadowRotationPolicy.class})
public void getAvailabilityStatus_unsupportedRotation_shouldReturnUnsupportedOnDevice() {
ShadowRotationPolicy.setRotationSupported(false /* supported */);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
@Config(shadows = {ShadowRotationPolicy.class})
public void setChecked_enabled() {
mController.setChecked(true /* isChecked */);
assertThat(mController.isChecked()).isTrue();
assertThat(RotationPolicy.isRotationLocked(mContext)).isFalse();
}
@Test
@Config(shadows = {ShadowRotationPolicy.class})
public void setChecked_disabled() {
mController.setChecked(false /* isChecked */);
assertThat(mController.isChecked()).isFalse();
assertThat(RotationPolicy.isRotationLocked(mContext)).isTrue();
}
@Test
public void updateState_settingIsOn_shouldTurnOnToggle() {
Settings.System.putIntForUser(mContext.getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 1, UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void updateState_settingIsOff_shouldTurnOffToggle() {
Settings.System.putIntForUser(mContext.getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (C) 2020 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.UserHandle;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class MagnificationEnablePreferenceControllerTest {
private static final String PREF_KEY = "screen_magnification_enable";
private static final String KEY_ENABLE = Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE;
private static final int UNKNOWN = -1;
private Context mContext;
private SwitchPreference mPreference;
private MagnificationEnablePreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new MagnificationEnablePreferenceController(mContext, PREF_KEY);
}
@Test
public void isChecked_enabledFullscreenMagnificationMode_shouldReturnTrue() {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
KEY_ENABLE, Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_FULLSCREEN,
UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void isChecked_enabledWindowMagnificationMode_shouldReturnFalse() {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
KEY_ENABLE, Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_WINDOW,
UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void setChecked_setTrue_shouldEnableFullscreenMagnificationMode() {
mController.setChecked(true);
assertThat(Settings.Secure.getIntForUser(mContext.getContentResolver(),
KEY_ENABLE, UNKNOWN,
UserHandle.USER_CURRENT)).isEqualTo(
Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_FULLSCREEN);
}
@Test
public void setChecked_setFalse_shouldEnableWindowMagnificationMode() {
mController.setChecked(false);
assertThat(Settings.Secure.getIntForUser(mContext.getContentResolver(),
KEY_ENABLE, UNKNOWN,
UserHandle.USER_CURRENT)).isEqualTo(
Settings.Secure.ACCESSIBILITY_MAGNIFICATION_MODE_WINDOW);
}
}

View File

@@ -130,4 +130,9 @@ public class MagnificationGesturesPreferenceControllerTest {
new MagnificationGesturesPreferenceController(mContext, "bad_key");
assertThat(controller.isSliceable()).isFalse();
}
@Test
public void isPublicSlice_returnTrue() {
assertThat(mController.isPublicSlice()).isTrue();
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class MagnificationModePreferenceControllerTest {
private static final String PREF_KEY = "screen_magnification_mode";
// TODO(b/146019459): Use magnification_capability.
private static final String KEY_CAPABILITY = Settings.System.MASTER_MONO;
private static final int WINDOW_SCREEN_VALUE = 2;
private static final int ALL_VALUE = 3;
private Context mContext;
private MagnificationModePreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new MagnificationModePreferenceController(mContext, PREF_KEY);
}
@Test
public void getSummary_saveWindowScreen_shouldReturnWindowScreenSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
KEY_CAPABILITY, WINDOW_SCREEN_VALUE);
assertThat(mController.getSummary())
.isEqualTo(mContext.getString(
R.string.accessibility_magnification_area_settings_window_screen_summary));
}
@Test
public void getSummary_saveAll_shouldReturnAllSummary() {
Settings.Secure.putInt(mContext.getContentResolver(),
KEY_CAPABILITY, ALL_VALUE);
assertThat(mController.getSummary())
.isEqualTo(mContext.getString(
R.string.accessibility_magnification_area_settings_all_summary));
}
}

View File

@@ -174,4 +174,9 @@ public class MagnificationNavbarPreferenceControllerTest {
new MagnificationNavbarPreferenceController(mContext, "bad_key");
assertThat(controller.isSliceable()).isFalse();
}
@Test
public void isPublicSlice_returnTrue() {
assertThat(mController.isPublicSlice()).isTrue();
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class MagnificationPreferenceControllerTest {
private Context mContext;
private MagnificationPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new MagnificationPreferenceController(mContext, "magnification");
}
@Test
public void getAvailabilityStatus_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.UserHandle;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class MasterMonoPreferenceControllerTest {
private static final int ON = 1;
private static final int OFF = 0;
private static final int UNKNOWN = -1;
private Context mContext;
private SwitchPreference mPreference;
private MasterMonoPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new MasterMonoPreferenceController(mContext, "master_mono");
}
@Test
public void getAvailabilityStatus_byDefault_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
}
@Test
public void isChecked_enabledMonoAudio_shouldReturnTrue() {
Settings.System.putIntForUser(mContext.getContentResolver(),
Settings.System.MASTER_MONO, ON, UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void isChecked_disabledMonoAudio_shouldReturnFalse() {
Settings.System.putIntForUser(mContext.getContentResolver(),
Settings.System.MASTER_MONO, OFF, UserHandle.USER_CURRENT);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void setChecked_setTrue_shouldEnableMonoAudio() {
mController.setChecked(true);
assertThat(Settings.System.getIntForUser(mContext.getContentResolver(),
Settings.System.MASTER_MONO, UNKNOWN, UserHandle.USER_CURRENT)).isEqualTo(ON);
}
@Test
public void setChecked_setFalse_shouldDisableMonoAudio() {
mController.setChecked(false);
assertThat(Settings.System.getIntForUser(mContext.getContentResolver(),
Settings.System.MASTER_MONO, UNKNOWN, UserHandle.USER_CURRENT)).isEqualTo(OFF);
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (C) 2020 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
/** Tests for {@link PaletteListView} */
@RunWith(RobolectricTestRunner.class)
public class PaletteListViewTest {
private final Context mContext = ApplicationProvider.getApplicationContext();
private PaletteListView mPaletteListView;
@Before
public void setUp() {
mPaletteListView = new PaletteListView(mContext);
}
@Test
public void setColors_applySameLengthArray_configureSuccessful() {
final String[] colorName = {"White", "Black", "Yellow"};
final String[] colorCode = {"#ffffff", "#000000", "#f9ab00"};
assertThat(mPaletteListView.setPaletteListColors(colorName, colorCode)).isTrue();
}
@Test
public void setColors_applyDifferentLengthArray_configureSuccessful() {
final String[] colorName = {"White", "Black", "Yellow", "Orange", "Red"};
final String[] colorCode = {"#ffffff", "#000000", "#f9ab00"};
assertThat(mPaletteListView.setPaletteListColors(colorName, colorCode)).isTrue();
}
@Test
public void setColors_configureFailed() {
final String[] colorName = null;
final String[] colorCode = null;
assertThat(mPaletteListView.setPaletteListColors(colorName, colorCode)).isFalse();
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.testutils.shadow.ShadowKeyCharacterMap;
import com.android.settings.testutils.shadow.ShadowUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowUtils.class, ShadowKeyCharacterMap.class})
public class PowerButtonEndsCallPreferenceControllerTest {
private static final int UNKNOWN = -1;
private Context mContext;
private SwitchPreference mPreference;
private PowerButtonEndsCallPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mController = new PowerButtonEndsCallPreferenceController(mContext, "power_button");
}
@After
public void tearDown() {
ShadowUtils.reset();
ShadowKeyCharacterMap.reset();
}
@Test
public void getAvailabilityStatus_hasPowerKeyAndVoiceCapable_shouldReturnAvailable() {
ShadowKeyCharacterMap.setDevicehasKey(true);
ShadowUtils.setIsVoiceCapable(true);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_noVoiceCapable_shouldReturnUnsupportedOnDevice() {
ShadowKeyCharacterMap.setDevicehasKey(true);
ShadowUtils.setIsVoiceCapable(false);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_noPowerKey_shouldReturnUnsupportedOnDevice() {
ShadowKeyCharacterMap.setDevicehasKey(false);
ShadowUtils.setIsVoiceCapable(true);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void isChecked_enabledHangUp_shouldReturnTrue() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void isChecked_disabledHangUp_shouldReturnFalse() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_SCREEN_OFF);
mController.updateState(mPreference);
assertThat(mController.isChecked()).isFalse();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void setChecked_enabled_shouldEnableHangUp() {
mController.setChecked(true);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR, UNKNOWN))
.isEqualTo(Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP);
}
@Test
public void setChecked_disabled_shouldDisableHangUp() {
mController.setChecked(false);
assertThat(Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR, UNKNOWN))
.isEqualTo(Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_SCREEN_OFF);
}
}

View File

@@ -20,10 +20,8 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.provider.DeviceConfig;
import android.provider.Settings;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
@@ -54,8 +52,6 @@ public class RingVibrationPreferenceFragmentTest {
// Turn on both flags to enable ramping ringer.
Settings.Global.putInt(
mContext.getContentResolver(), Settings.Global.APPLY_RAMPING_RINGER, 1 /* ON */);
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_TELEPHONY,
AccessibilitySettings.RAMPING_RINGER_ENABLED, "true", false /* makeDefault*/);
assertThat(mFragment.getVibrationEnabledSetting()).isEqualTo(
Settings.Global.APPLY_RAMPING_RINGER);
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.provider.Settings;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class SelectLongPressTimeoutPreferenceControllerTest {
private static final int VALID_VALUE = 1500;
private static final int INVALID_VALUE = 0;
private static final int DEFAULT_VALUE = 400;
private Context mContext;
private SelectLongPressTimeoutPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new SelectLongPressTimeoutPreferenceController(mContext, "press_timeout");
}
@Test
public void getAvailabilityStatus_byDefault_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getSummary_byDefault_shouldReturnShort() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LONG_PRESS_TIMEOUT, DEFAULT_VALUE);
final String expected = "Short";
assertThat(mController.getSummary()).isEqualTo(expected);
}
@Test
public void getSummary_validValue_shouldReturnLong() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LONG_PRESS_TIMEOUT, VALID_VALUE);
final String expected = "Long";
assertThat(mController.getSummary()).isEqualTo(expected);
}
@Test
public void getSummary_invalidValue_shouldReturnNull() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LONG_PRESS_TIMEOUT, INVALID_VALUE);
assertThat(mController.getSummary()).isNull();
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import androidx.preference.PreferenceViewHolder;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
/** Tests for {@link ShortcutPreference} */
@RunWith(RobolectricTestRunner.class)
public class ShortcutPreferenceTest {
private static final String TOGGLE_CLICKED = "toggle_clicked";
private static final String SETTINGS_CLICKED = "settings_clicked";
private ShortcutPreference mShortcutPreference;
private PreferenceViewHolder mPreferenceViewHolder;
private String mResult;
private ShortcutPreference.OnClickCallback mListener =
new ShortcutPreference.OnClickCallback() {
@Override
public void onToggleClicked(ShortcutPreference preference) {
mResult = TOGGLE_CLICKED;
}
@Override
public void onSettingsClicked(ShortcutPreference preference) {
mResult = SETTINGS_CLICKED;
}
};
@Before
public void setUp() {
final Context context = RuntimeEnvironment.application;
mShortcutPreference = new ShortcutPreference(context, null);
final LayoutInflater inflater = LayoutInflater.from(context);
final View view =
inflater.inflate(R.layout.accessibility_shortcut_secondary_action, null);
mPreferenceViewHolder = PreferenceViewHolder.createInstanceForTests(view);
}
@Test
public void clickToggle_toggleClicked() {
mShortcutPreference.onBindViewHolder(mPreferenceViewHolder);
mShortcutPreference.setOnClickCallback(mListener);
mPreferenceViewHolder.itemView.performClick();
assertThat(mResult).isEqualTo(TOGGLE_CLICKED);
assertThat(mShortcutPreference.isChecked()).isTrue();
}
@Test
public void clickSettings_settingsClicked() {
mShortcutPreference.onBindViewHolder(mPreferenceViewHolder);
mShortcutPreference.setOnClickCallback(mListener);
final View settings = mPreferenceViewHolder.itemView.findViewById(R.id.main_frame);
settings.performClick();
assertThat(mResult).isEqualTo(SETTINGS_CLICKED);
}
@Test
public void setCheckedTrue_getToggleIsTrue() {
mShortcutPreference.setChecked(true);
assertThat(mShortcutPreference.isChecked()).isEqualTo(true);
}
}

View File

@@ -1,70 +0,0 @@
/*
* Copyright (C) 2017 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.os.UserManager;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class ShortcutServicePickerFragmentTest {
private static final String TEST_SERVICE_KEY_1 = "abc/123";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
private ShortcutServicePickerFragment mFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
FakeFeatureFactory.setupForTest();
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mFragment = spy(new ShortcutServicePickerFragment());
mFragment.onAttach(mActivity);
doReturn(RuntimeEnvironment.application).when(mFragment).getContext();
}
@Test
public void setAndGetDefaultAppKey_shouldUpdateDefaultAppKey() {
assertThat(mFragment.setDefaultKey(TEST_SERVICE_KEY_1)).isTrue();
assertThat(mFragment.getDefaultKey()).isEqualTo(TEST_SERVICE_KEY_1);
}
}

View File

@@ -16,6 +16,8 @@
package com.android.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@@ -29,23 +31,87 @@ import androidx.annotation.XmlRes;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.R;
import com.android.settings.widget.SwitchBar;
import com.android.settings.accessibility.ToggleFeaturePreferenceFragment.AccessibilityUserShortcutType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
@RunWith(RobolectricTestRunner.class)
public class ToggleFeaturePreferenceFragmentTest {
private ToggleFeaturePreferenceFragmentTestable mFragment;
private static final String TEST_SERVICE_KEY_1 = "abc:111";
private static final String TEST_SERVICE_KEY_2 = "mno:222";
private static final String TEST_SERVICE_KEY_3 = "xyz:333";
private static final String TEST_SERVICE_NAME_1 = "abc";
private static final int TEST_SERVICE_VALUE_1 = 111;
@Test
public void a11yUserShortcutType_setConcatString_shouldReturnTargetValue() {
final AccessibilityUserShortcutType shortcut = new AccessibilityUserShortcutType(
TEST_SERVICE_KEY_1);
assertThat(shortcut.getComponentName()).isEqualTo(TEST_SERVICE_NAME_1);
assertThat(shortcut.getType()).isEqualTo(TEST_SERVICE_VALUE_1);
}
@Test
public void a11yUserShortcutType_shouldUpdateConcatString() {
final AccessibilityUserShortcutType shortcut = new AccessibilityUserShortcutType(
TEST_SERVICE_KEY_2);
shortcut.setComponentName(TEST_SERVICE_NAME_1);
shortcut.setType(TEST_SERVICE_VALUE_1);
assertThat(shortcut.flattenToString()).isEqualTo(TEST_SERVICE_KEY_1);
}
@Test
public void stringSet_convertA11yPreferredShortcut_shouldRemoveTarget() {
Set<String> mySet = new HashSet<>();
mySet.add(TEST_SERVICE_KEY_1);
mySet.add(TEST_SERVICE_KEY_2);
mySet.add(TEST_SERVICE_KEY_3);
final Set<String> filtered = mySet.stream()
.filter(str -> str.contains(TEST_SERVICE_NAME_1))
.collect(Collectors.toSet());
mySet.removeAll(filtered);
assertThat(mySet).doesNotContain(TEST_SERVICE_KEY_1);
assertThat(mySet).hasSize(/* expectedSize= */2);
}
@Test
public void stringSet_convertA11yUserShortcutType_shouldReturnPreferredShortcut() {
Set<String> mySet = new HashSet<>();
mySet.add(TEST_SERVICE_KEY_1);
mySet.add(TEST_SERVICE_KEY_2);
mySet.add(TEST_SERVICE_KEY_3);
final Set<String> filtered = mySet.stream()
.filter(str -> str.contains(TEST_SERVICE_NAME_1))
.collect(Collectors.toSet());
final String str = (String) filtered.toArray()[0];
final AccessibilityUserShortcutType shortcut = new AccessibilityUserShortcutType(str);
final int type = shortcut.getType();
assertThat(type).isEqualTo(TEST_SERVICE_VALUE_1);
}
@Test
public void createFragment_shouldOnlyAddPreferencesOnce() {
mFragment = spy(new ToggleFeaturePreferenceFragmentTestable());
FragmentController.setupFragment(mFragment, FragmentActivity.class, 0 /* containerViewId*/,
null /* bundle */);
FragmentController.setupFragment(mFragment, FragmentActivity.class,
/* containerViewId= */ 0, /* bundle= */null);
// execute exactly once
verify(mFragment).addPreferencesFromResource(R.xml.placeholder_prefs);
@@ -63,6 +129,11 @@ public class ToggleFeaturePreferenceFragmentTest {
return 0;
}
@Override
int getUserShortcutTypes() {
return 0;
}
@Override
public int getPreferenceScreenResId() {
return R.xml.placeholder_prefs;
@@ -83,11 +154,5 @@ public class ToggleFeaturePreferenceFragmentTest {
public void onViewCreated(View view, Bundle savedInstanceState) {
// do nothing
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
mSwitchBar = mock(SwitchBar.class);
super.onActivityCreated(savedInstanceState);
}
}
}

View File

@@ -0,0 +1,141 @@
/*
* Copyright (C) 2020 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.settings.accessibility;
import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
import static com.android.settings.accessibility.AccessibilityUtil.UserShortcutType;
import static com.google.common.truth.Truth.assertThat;
import android.content.ComponentName;
import android.content.Context;
import android.provider.Settings;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class ToggleScreenMagnificationPreferenceFragmentTest {
private static final String DUMMY_PACKAGE_NAME = "com.dummy.example";
private static final String DUMMY_CLASS_NAME = DUMMY_PACKAGE_NAME + ".dummy_a11y_service";
private static final ComponentName DUMMY_COMPONENT_NAME = new ComponentName(DUMMY_PACKAGE_NAME,
DUMMY_CLASS_NAME);
private static final String SOFTWARE_SHORTCUT_KEY =
Settings.Secure.ACCESSIBILITY_BUTTON_TARGETS;
private static final String HARDWARE_SHORTCUT_KEY =
Settings.Secure.ACCESSIBILITY_SHORTCUT_TARGET_SERVICE;
private static final String TRIPLETAP_SHORTCUT_KEY =
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED;
private static final String MAGNIFICATION_CONTROLLER_NAME =
"com.android.server.accessibility.MagnificationController";
private Context mContext;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
}
@Test
public void hasValueInSettings_putValue_hasValue() {
setMagnificationTripleTapEnabled(/* enabled= */ true);
assertThat(ToggleScreenMagnificationPreferenceFragment.hasMagnificationValuesInSettings(
mContext, UserShortcutType.TRIPLETAP)).isTrue();
}
@Test
public void optInAllValuesToSettings_optInValue_haveMatchString() {
int shortcutTypes = UserShortcutType.SOFTWARE | UserShortcutType.TRIPLETAP;
ToggleScreenMagnificationPreferenceFragment.optInAllMagnificationValuesToSettings(mContext,
shortcutTypes);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
MAGNIFICATION_CONTROLLER_NAME);
assertThat(getMagnificationTripleTapStatus()).isTrue();
}
@Test
public void optInAllValuesToSettings_existOtherValue_optInValue_haveMatchString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, DUMMY_COMPONENT_NAME.flattenToString());
ToggleScreenMagnificationPreferenceFragment.optInAllMagnificationValuesToSettings(mContext,
UserShortcutType.SOFTWARE);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString() + ":" + MAGNIFICATION_CONTROLLER_NAME);
}
@Test
public void optOutAllValuesToSettings_optOutValue_emptyString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY, MAGNIFICATION_CONTROLLER_NAME);
putStringIntoSettings(HARDWARE_SHORTCUT_KEY, MAGNIFICATION_CONTROLLER_NAME);
setMagnificationTripleTapEnabled(/* enabled= */ true);
int shortcutTypes =
UserShortcutType.SOFTWARE | UserShortcutType.HARDWARE | UserShortcutType.TRIPLETAP;
ToggleScreenMagnificationPreferenceFragment.optOutAllMagnificationValuesFromSettings(
mContext, shortcutTypes);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEmpty();
assertThat(getStringFromSettings(HARDWARE_SHORTCUT_KEY)).isEmpty();
assertThat(getMagnificationTripleTapStatus()).isFalse();
}
@Test
public void optOutValueFromSettings_existOtherValue_optOutValue_haveMatchString() {
putStringIntoSettings(SOFTWARE_SHORTCUT_KEY,
DUMMY_COMPONENT_NAME.flattenToString() + ":" + MAGNIFICATION_CONTROLLER_NAME);
putStringIntoSettings(HARDWARE_SHORTCUT_KEY,
DUMMY_COMPONENT_NAME.flattenToString() + ":" + MAGNIFICATION_CONTROLLER_NAME);
int shortcutTypes = UserShortcutType.SOFTWARE | UserShortcutType.HARDWARE;
ToggleScreenMagnificationPreferenceFragment.optOutAllMagnificationValuesFromSettings(
mContext, shortcutTypes);
assertThat(getStringFromSettings(SOFTWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString());
assertThat(getStringFromSettings(HARDWARE_SHORTCUT_KEY)).isEqualTo(
DUMMY_COMPONENT_NAME.flattenToString());
}
private void putStringIntoSettings(String key, String componentName) {
Settings.Secure.putString(mContext.getContentResolver(), key, componentName);
}
private void setMagnificationTripleTapEnabled(boolean enabled) {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, enabled ? ON : OFF);
}
private String getStringFromSettings(String key) {
return Settings.Secure.getString(mContext.getContentResolver(), key);
}
private boolean getMagnificationTripleTapStatus() {
return Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, OFF) == ON;
}
}

View File

@@ -16,23 +16,19 @@
package com.android.settings.accessibility;
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
@RunWith(RobolectricTestRunner.class)
public class TopLevelAccessibilityPreferenceControllerTest {
@@ -48,7 +44,7 @@ public class TopLevelAccessibilityPreferenceControllerTest {
@Test
public void getAvailibilityStatus_availableByDefault() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2019 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.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.Vibrator;
import android.provider.Settings;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class VibrationPreferenceControllerTest {
private static final String VIBRATION_ON = "On";
private static final String VIBRATION_OFF = "Off";
private Context mContext;
private VibrationPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new VibrationPreferenceController(mContext, "vibration_pref");
}
@Test
public void getAvailabilityStatus_byDefault_shouldReturnAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getSummary_disabledVibration_shouldReturnOffSummary() {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.RING_VIBRATION_INTENSITY, Vibrator.VIBRATION_INTENSITY_OFF);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.NOTIFICATION_VIBRATION_INTENSITY, Vibrator.VIBRATION_INTENSITY_OFF);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_INTENSITY, Vibrator.VIBRATION_INTENSITY_OFF);
final String expectedResult = mContext.getString(R.string.switch_off_text);
assertThat(mController.getSummary()).isEqualTo(expectedResult);
}
@Test
public void getSummary_enabledSomeVibration_shouldReturnVibrationOnSummary() {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.RING_VIBRATION_INTENSITY, Vibrator.VIBRATION_INTENSITY_MEDIUM);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.VIBRATE_WHEN_RINGING, 1);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.NOTIFICATION_VIBRATION_INTENSITY, Vibrator.VIBRATION_INTENSITY_OFF);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_INTENSITY, Vibrator.VIBRATION_INTENSITY_MEDIUM);
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 1);
final String expectedResult = mContext.getString(R.string.accessibility_vibration_summary,
VIBRATION_ON /* ring */,
VIBRATION_OFF /* notification */,
VIBRATION_ON /* touch */);
assertThat(mController.getSummary()).isEqualTo(expectedResult);
}
}

View File

@@ -17,26 +17,55 @@ package com.android.settings.accounts;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.pm.UserInfo;
import android.os.UserManager;
import android.provider.SearchIndexableResource;
import com.android.settingslib.drawer.CategoryKey;
import com.android.settingslib.search.SearchIndexableRaw;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class AccountDashboardFragmentTest {
private static final int PROFILE_ID = 10;
private static final String PROFILE_NAME = "User";
private static final String ACCOUNT_TYPE = "com.android.settings";
private static final String ACCOUNT_NAME = "test account";
@Mock
private UserManager mUserManager;
@Mock
private AccountManager mAccountManager;
private Context mContext;
private AccountDashboardFragment mFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mFragment = new AccountDashboardFragment();
doReturn(mUserManager).when(mContext).getSystemService(Context.USER_SERVICE);
}
@Test
@@ -45,7 +74,7 @@ public class AccountDashboardFragmentTest {
}
@Test
public void testSearchIndexProvider_shouldIndexResource() {
public void searchIndexProvider_shouldIndexResource() {
final List<SearchIndexableResource> indexRes =
AccountDashboardFragment.SEARCH_INDEX_DATA_PROVIDER
.getXmlResourcesToIndex(RuntimeEnvironment.application, true /* enabled */);
@@ -53,4 +82,36 @@ public class AccountDashboardFragmentTest {
assertThat(indexRes).isNotNull();
assertThat(indexRes.get(0).xmlResId).isEqualTo(mFragment.getPreferenceScreenResId());
}
@Test
public void searchIndexProvider_hasManagedProfile_shouldNotIndex() {
final List<UserInfo> infos = new ArrayList<>();
infos.add(new UserInfo(PROFILE_ID, PROFILE_NAME, UserInfo.FLAG_MANAGED_PROFILE));
doReturn(infos).when(mUserManager).getProfiles(anyInt());
final List<SearchIndexableRaw> indexRaws =
AccountDashboardFragment.SEARCH_INDEX_DATA_PROVIDER
.getDynamicRawDataToIndex(mContext, true /* enabled */);
assertThat(indexRaws).isEmpty();
}
@Test
public void searchIndexProvider_hasAccounts_shouldIndex() {
final List<UserInfo> infos = new ArrayList<>();
infos.add(new UserInfo(PROFILE_ID, PROFILE_NAME, UserInfo.FLAG_PRIMARY));
doReturn(infos).when(mUserManager).getProfiles(anyInt());
final Account[] accounts = {
new Account(ACCOUNT_NAME, ACCOUNT_TYPE)
};
when(AccountManager.get(mContext)).thenReturn(mAccountManager);
doReturn(accounts).when(mAccountManager).getAccounts();
final List<SearchIndexableRaw> indexRaws =
AccountDashboardFragment.SEARCH_INDEX_DATA_PROVIDER
.getDynamicRawDataToIndex(mContext, true /* enabled */);
assertThat(indexRaws).isNotEmpty();
}
}

View File

@@ -47,6 +47,7 @@ import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.dashboard.DashboardFeatureProviderImpl;
import com.android.settings.testutils.shadow.ShadowAccountManager;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.drawer.ActivityTile;
import com.android.settingslib.drawer.CategoryKey;
import com.android.settingslib.drawer.Tile;
@@ -105,7 +106,7 @@ public class AccountDetailDashboardFragmentTest {
@Test
public void refreshDashboardTiles_HasAccountType_shouldDisplay() {
final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
final Tile tile = new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(METADATA_CATEGORY, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(METADATA_ACCOUNT_TYPE, "com.abc");
@@ -114,7 +115,7 @@ public class AccountDetailDashboardFragmentTest {
@Test
public void refreshDashboardTiles_NoAccountType_shouldNotDisplay() {
final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
final Tile tile = new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(METADATA_CATEGORY, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
assertThat(mFragment.displayTile(tile)).isFalse();
@@ -122,7 +123,7 @@ public class AccountDetailDashboardFragmentTest {
@Test
public void refreshDashboardTiles_OtherAccountType_shouldNotDisplay() {
final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
final Tile tile = new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(METADATA_CATEGORY, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(METADATA_ACCOUNT_TYPE, "com.other");
@@ -138,7 +139,7 @@ public class AccountDetailDashboardFragmentTest {
when(packageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(mock(ResolveInfo.class));
final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
final Tile tile = new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(META_DATA_PREFERENCE_KEYHINT, "key");
mActivityInfo.metaData.putString(METADATA_CATEGORY, CategoryKey.CATEGORY_ACCOUNT);
mActivityInfo.metaData.putString(METADATA_ACCOUNT_TYPE, "com.abc");
@@ -150,9 +151,9 @@ public class AccountDetailDashboardFragmentTest {
final FragmentActivity activity = Robolectric.setupActivity(FragmentActivity.class);
final Preference preference = new Preference(mContext);
dashboardFeatureProvider.bindPreferenceToTile(activity, false /* forceRoundedIcon */,
MetricsProto.MetricsEvent.DASHBOARD_SUMMARY, preference, tile, null /* key */,
Preference.DEFAULT_ORDER);
dashboardFeatureProvider.bindPreferenceToTileAndGetObservers(activity,
false /* forceRoundedIcon */, MetricsProto.MetricsEvent.DASHBOARD_SUMMARY,
preference, tile, null /* key */, Preference.DEFAULT_ORDER);
assertThat(preference.getKey()).isEqualTo(tile.getKey(mContext));
preference.performClick();
@@ -166,7 +167,7 @@ public class AccountDetailDashboardFragmentTest {
public void displayTile_shouldAddUserHandleToTileIntent() {
mFragment.mUserHandle = new UserHandle(1);
final Tile tile = new Tile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
final Tile tile = new ActivityTile(mActivityInfo, CategoryKey.CATEGORY_ACCOUNT_DETAIL);
mActivityInfo.metaData.putString(METADATA_CATEGORY, CategoryKey.CATEGORY_ACCOUNT);
mActivityInfo.metaData.putString(METADATA_ACCOUNT_TYPE, "com.abc");

View File

@@ -36,7 +36,7 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.R;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.accounts.AuthenticatorHelper;
import com.android.settings.testutils.shadow.ShadowAuthenticationHelper;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.LayoutPreference;
@@ -48,11 +48,9 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = AccountHeaderPreferenceControllerTest.ShadowAuthenticatorHelper.class)
@Config(shadows = ShadowAuthenticationHelper.class)
public class AccountHeaderPreferenceControllerTest {
@Mock
@@ -109,12 +107,4 @@ public class AccountHeaderPreferenceControllerTest {
assertThat(label).isEqualTo(account.name);
}
@Implements(AuthenticatorHelper.class)
public static class ShadowAuthenticatorHelper {
@Implementation
protected void onAccountsUpdated(Account[] accounts) {
}
}
}

View File

@@ -46,9 +46,11 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.AccessiblePreferenceCategory;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.search.SearchIndexableRaw;
import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
import com.android.settings.testutils.shadow.ShadowAccountManager;
import com.android.settings.testutils.shadow.ShadowContentResolver;
import com.android.settings.testutils.shadow.ShadowSettingsLibUtils;
import com.android.settingslib.search.SearchIndexableRaw;
import org.junit.After;
import org.junit.Before;
@@ -66,7 +68,8 @@ import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class})
@Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class,
ShadowSettingsLibUtils.class})
public class AccountPreferenceControllerTest {
@Mock(answer = RETURNS_DEEP_STUBS)
@@ -94,9 +97,10 @@ public class AccountPreferenceControllerTest {
when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
when(mFragment.getPreferenceManager().getContext()).thenReturn(mContext);
when(mAccountManager.getAuthenticatorTypesAsUser(anyInt()))
.thenReturn(new AuthenticatorDescription[0]);
.thenReturn(new AuthenticatorDescription[0]);
when(mAccountManager.getAccountsAsUser(anyInt())).thenReturn(new Account[0]);
mController = new AccountPreferenceController(mContext, mFragment, null, mAccountHelper);
mController = new AccountPreferenceController(mContext, mFragment, null, mAccountHelper,
ProfileSelectFragment.ProfileType.ALL);
}
@After
@@ -272,33 +276,33 @@ public class AccountPreferenceControllerTest {
}
@Test
public void updateRawDataToIndex_EnabledUser_shouldAddOne() {
public void updateDynamicRawDataToIndex_enabledUser_notManagedUser_shouldNotUpdate() {
final List<SearchIndexableRaw> data = new ArrayList<>();
final List<UserInfo> infos = new ArrayList<>();
infos.add(new UserInfo(1, "user 1", 0));
when(mUserManager.isManagedProfile()).thenReturn(false);
when(mUserManager.getProfiles(anyInt())).thenReturn(infos);
mController.updateRawDataToIndex(data);
mController.updateDynamicRawDataToIndex(data);
assertThat(data.size()).isEqualTo(1);
assertThat(data.size()).isEqualTo(0);
}
@Test
public void updateRawDataToIndex_ManagedUser_shouldAddThree() {
public void updateDynamicRawDataToIndex_managedUser_shouldAddTwo() {
final List<SearchIndexableRaw> data = new ArrayList<>();
final List<UserInfo> infos = new ArrayList<>();
infos.add(new UserInfo(1, "user 1", UserInfo.FLAG_MANAGED_PROFILE));
when(mUserManager.isManagedProfile()).thenReturn(false);
when(mUserManager.getProfiles(anyInt())).thenReturn(infos);
mController.updateRawDataToIndex(data);
mController.updateDynamicRawDataToIndex(data);
assertThat(data.size()).isEqualTo(3);
assertThat(data.size()).isEqualTo(2);
}
@Test
public void updateRawDataToIndex_DisallowRemove_shouldAddTwo() {
public void updateDynamicRawDataToIndex_disallowRemove_shouldAddOne() {
final List<SearchIndexableRaw> data = new ArrayList<>();
final List<UserInfo> infos = new ArrayList<>();
infos.add(new UserInfo(1, "user 1", UserInfo.FLAG_MANAGED_PROFILE));
@@ -308,13 +312,13 @@ public class AccountPreferenceControllerTest {
eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), anyInt()))
.thenReturn(true);
mController.updateRawDataToIndex(data);
mController.updateDynamicRawDataToIndex(data);
assertThat(data.size()).isEqualTo(2);
assertThat(data.size()).isEqualTo(1);
}
@Test
public void updateRawDataToIndex_DisallowModify_shouldAddTwo() {
public void updateDynamicRawDataToIndex_disallowModify_shouldAddTwo() {
final List<SearchIndexableRaw> data = new ArrayList<>();
final List<UserInfo> infos = new ArrayList<>();
infos.add(new UserInfo(1, "user 1", UserInfo.FLAG_MANAGED_PROFILE));
@@ -323,7 +327,7 @@ public class AccountPreferenceControllerTest {
when(mAccountHelper.hasBaseUserRestriction(
eq(UserManager.DISALLOW_MODIFY_ACCOUNTS), anyInt())).thenReturn(true);
mController.updateRawDataToIndex(data);
mController.updateDynamicRawDataToIndex(data);
assertThat(data.size()).isEqualTo(2);
}
@@ -339,8 +343,8 @@ public class AccountPreferenceControllerTest {
when(mAccountManager.getAccountsAsUser(anyInt())).thenReturn(accounts);
Account[] accountType1 = {
new Account("Account11", "com.acct1"),
new Account("Account12", "com.acct1")
new Account("Account11", "com.acct1"),
new Account("Account12", "com.acct1")
};
when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
.thenReturn(accountType1);
@@ -533,8 +537,8 @@ public class AccountPreferenceControllerTest {
when(mAccountManager.getAccountsAsUser(anyInt())).thenReturn(accounts);
Account[] accountType1 = {
new Account("Acct11", "com.acct1"),
new Account("Acct12", "com.acct1")
new Account("Acct11", "com.acct1"),
new Account("Acct12", "com.acct1")
};
when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
.thenReturn(accountType1);
@@ -553,7 +557,7 @@ public class AccountPreferenceControllerTest {
mController.onResume();
// remove an account
accountType1 = new Account[] {new Account("Acct11", "com.acct1")};
accountType1 = new Account[]{new Account("Acct11", "com.acct1")};
when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
.thenReturn(accountType1);
@@ -575,19 +579,19 @@ public class AccountPreferenceControllerTest {
Account[] accounts = {new Account("Acct1", "com.acct1")};
when(mAccountManager.getAccountsAsUser(1)).thenReturn(accounts);
when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
.thenReturn(accounts);
.thenReturn(accounts);
AuthenticatorDescription[] authDescs = {
new AuthenticatorDescription("com.acct1", "com.android.settings",
R.string.account_settings_title, 0 /* iconId */, 0 /* smallIconId */,
0 /* prefId */, false /* customTokens */)
new AuthenticatorDescription("com.acct1", "com.android.settings",
R.string.account_settings_title, 0 /* iconId */, 0 /* smallIconId */,
0 /* prefId */, false /* customTokens */)
};
when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(authDescs);
AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
when(preferenceGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class)))
.thenReturn(preferenceGroup);
.thenReturn(preferenceGroup);
// First time resume will build the UI with no account
mController.onResume();

View File

@@ -15,6 +15,8 @@
*/
package com.android.settings.accounts;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@@ -24,10 +26,13 @@ import android.content.Context;
import android.os.UserHandle;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import com.android.settings.testutils.shadow.ShadowContentResolver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@@ -38,6 +43,14 @@ import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowContentResolver.class})
public class AccountSyncSettingsTest {
private Context mContext;
private AccountSyncSettings mAccountSyncSettings;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mAccountSyncSettings = spy(new TestAccountSyncSettings(mContext));
}
@After
public void tearDown() {
@@ -46,15 +59,52 @@ public class AccountSyncSettingsTest {
@Test
public void onPreferenceTreeClick_nullAuthority_shouldNotCrash() {
final Context context = RuntimeEnvironment.application;
final AccountSyncSettings settings = spy(new AccountSyncSettings());
when(settings.getActivity()).thenReturn(mock(FragmentActivity.class));
final SyncStateSwitchPreference preference = new SyncStateSwitchPreference(context,
when(mAccountSyncSettings.getActivity()).thenReturn(mock(FragmentActivity.class));
final SyncStateSwitchPreference preference = new SyncStateSwitchPreference(mContext,
new Account("acct1", "type1"), "" /* authority */, "testPackage", 1 /* uid */);
preference.setOneTimeSyncMode(false);
ReflectionHelpers.setField(settings, "mUserHandle", UserHandle.CURRENT);
ReflectionHelpers.setField(mAccountSyncSettings, "mUserHandle", UserHandle.CURRENT);
settings.onPreferenceTreeClick(preference);
mAccountSyncSettings.onPreferenceTreeClick(preference);
// no crash
}
@Test
public void enabledSyncNowMenu_noSyncStateSwitchPreference_returnFalse() {
assertThat(mAccountSyncSettings.enabledSyncNowMenu()).isFalse();
}
@Test
public void enabledSyncNowMenu_addSyncStateSwitchPreferenceAndSwitchOn_returnTrue() {
final SyncStateSwitchPreference preference = new SyncStateSwitchPreference(mContext,
new Account("acct1", "type1"), "" /* authority */, "testPackage", 1 /* uid */);
preference.setChecked(true);
mAccountSyncSettings.getPreferenceScreen().addPreference(preference);
assertThat(mAccountSyncSettings.enabledSyncNowMenu()).isTrue();
}
@Test
public void enabledSyncNowMenu_addSyncStateSwitchPreferenceAndSwitchOff_returnFalse() {
final SyncStateSwitchPreference preference = new SyncStateSwitchPreference(mContext,
new Account("acct1", "type1"), "" /* authority */, "testPackage", 1 /* uid */);
preference.setChecked(false);
mAccountSyncSettings.getPreferenceScreen().addPreference(preference);
assertThat(mAccountSyncSettings.enabledSyncNowMenu()).isFalse();
}
public static class TestAccountSyncSettings extends AccountSyncSettings {
private PreferenceScreen mScreen;
public TestAccountSyncSettings(Context context) {
final PreferenceManager preferenceManager = new PreferenceManager(context);
mScreen = preferenceManager.createPreferenceScreen(context);
}
@Override
public PreferenceScreen getPreferenceScreen() {
return mScreen;
}
}
}

View File

@@ -130,6 +130,17 @@ public class AvatarViewMixinTest {
verify(mockAvatar).hasAccount();
}
@Test
@Config(qualifiers = "mcc999")
public void onStart_noAccount_mAccountNameShouldBeNull() {
final AvatarViewMixin avatarViewMixin = new AvatarViewMixin(mActivity, mImageView);
avatarViewMixin.mAccountName = DUMMY_ACCOUNT;
avatarViewMixin.onStart();
assertThat(avatarViewMixin.mAccountName).isNull();
}
@Test
public void queryProviderAuthority_useShadowPackagteManager_returnNull() {
final AvatarViewMixin avatarViewMixin = new AvatarViewMixin(mActivity, mImageView);

View File

@@ -1,99 +0,0 @@
/*
* Copyright (C) 2018 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.settings.accounts;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.DISABLED_FOR_USER;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.RuntimeEnvironment.application;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.UserHandle;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.shadows.ShadowDevicePolicyManager;
import java.util.Collections;
@RunWith(RobolectricTestRunner.class)
public class CrossProfileCalendarDisabledPreferenceControllerTest {
private static final String PREF_KEY = "cross_profile_calendar_disabled";
private static final int MANAGED_USER_ID = 10;
private static final String TEST_PACKAGE_NAME = "com.test";
private static final ComponentName TEST_COMPONENT_NAME = new ComponentName("test", "test");
@Mock
private UserHandle mManagedUser;
private Context mContext;
private CrossProfileCalendarDisabledPreferenceController mController;
private ShadowDevicePolicyManager mDpm;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mController = new CrossProfileCalendarDisabledPreferenceController(mContext, PREF_KEY);
mController.setManagedUser(mManagedUser);
mDpm = Shadows.shadowOf(application.getSystemService(DevicePolicyManager.class));
when(mManagedUser.getIdentifier()).thenReturn(MANAGED_USER_ID);
doReturn(mContext).when(mContext).createPackageContextAsUser(
any(String.class), anyInt(), any(UserHandle.class));
}
@Test
public void getAvailabilityStatus_noPackageAllowed_shouldBeAvailable() {
mDpm.setProfileOwner(TEST_COMPONENT_NAME);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_somePackagesAllowed_shouldBeDisabledForUser() {
mDpm.setProfileOwner(TEST_COMPONENT_NAME);
mDpm.setCrossProfileCalendarPackages(TEST_COMPONENT_NAME,
Collections.singleton(TEST_PACKAGE_NAME));
assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
}
@Test
public void getAvailabilityStatus_allPackagesAllowed_shouldBeDisabledForUser() {
mDpm.setProfileOwner(TEST_COMPONENT_NAME);
mDpm.setCrossProfileCalendarPackages(TEST_COMPONENT_NAME, null);
assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
}
}

View File

@@ -36,9 +36,9 @@ import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.R;
import com.android.settings.search.SearchIndexableRaw;
import com.android.settings.testutils.shadow.ShadowAccountManager;
import com.android.settings.testutils.shadow.ShadowContentResolver;
import com.android.settingslib.search.SearchIndexableRaw;
import org.junit.After;
import org.junit.Before;
@@ -156,10 +156,11 @@ public class EmergencyInfoPreferenceControllerTest {
final Preference preference = new Preference(activity);
preference.setKey("emergency_info");
mController = new EmergencyInfoPreferenceController(activity, preference.getKey());
mController.mIntent = new Intent("com.example.action.new").setPackage("com.example.test");
mController.handlePreferenceTreeClick(preference);
assertThat(application.getNextStartedActivity().getAction())
.isEqualTo("android.settings.EDIT_EMERGENCY_INFO");
.isEqualTo("com.example.action.new");
}
}

View File

@@ -18,46 +18,37 @@ package com.android.settings.accounts;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import android.content.Context;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.preference.Preference;
import com.android.settings.core.BasePreferenceController;
import com.android.settingslib.widget.FooterPreferenceMixinCompat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class EnterpriseDisclosurePreferenceControllerTest {
private static final String TEST_DISCLOSURE = "This is a test disclosure.";
private ChooseAccountFragment mFragment;
private Context mContext;
private EnterpriseDisclosurePreferenceController mController;
private FooterPreferenceMixinCompat mFooterPreferenceMixin;
private PreferenceManager mPreferenceManager;
private PreferenceScreen mPreferenceScreen;
private Preference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = spy(new EnterpriseDisclosurePreferenceController(mContext));
mFragment = spy(new ChooseAccountFragment());
mFooterPreferenceMixin = new FooterPreferenceMixinCompat(mFragment,
mFragment.getSettingsLifecycle());
mPreferenceManager = new PreferenceManager(mContext);
mPreferenceScreen = mPreferenceManager.createPreferenceScreen(mContext);
mController = spy(new EnterpriseDisclosurePreferenceController(mContext, "my_key"));
mPreference = spy(new Preference(mContext));
}
@Test
@@ -77,24 +68,20 @@ public class EnterpriseDisclosurePreferenceControllerTest {
}
@Test
public void displayPreference_hasDisclosure_shouldSetTitle() {
public void updateState_hasDisclosure_shouldSetTitle() {
doReturn(TEST_DISCLOSURE).when(mController).getDisclosure();
doReturn(mPreferenceScreen).when(mFragment).getPreferenceScreen();
doReturn(mPreferenceManager).when(mFragment).getPreferenceManager();
mController.setFooterPreferenceMixin(mFooterPreferenceMixin);
mController.displayPreference(mPreferenceScreen);
mController.updateState(mPreference);
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(1);
assertThat(mPreferenceScreen.getPreference(0).getTitle()).isEqualTo(TEST_DISCLOSURE);
assertThat(mPreference.getTitle()).isEqualTo(TEST_DISCLOSURE);
}
@Test
public void displayPreference_noDisclosure_shouldBeInvisible() {
public void updateState_noDisclosure_shouldBeInvisible() {
doReturn(null).when(mController).getDisclosure();
mController.displayPreference(mPreferenceScreen);
mController.updateState(mPreference);
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(0);
verify(mPreference, never()).setTitle(any());
}
}

View File

@@ -54,6 +54,7 @@ import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowAccountManager;
import com.android.settings.testutils.shadow.ShadowContentResolver;
import com.android.settings.testutils.shadow.ShadowDevicePolicyManager;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.widget.LayoutPreference;
@@ -64,6 +65,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@@ -113,8 +115,8 @@ public class RemoveAccountPreferenceControllerTest {
when(mAccountManager.getAuthenticatorTypesAsUser(anyInt()))
.thenReturn(new AuthenticatorDescription[0]);
when(mAccountManager.getAccountsAsUser(anyInt())).thenReturn(new Account[0]);
mController = new RemoveAccountPreferenceController(RuntimeEnvironment.application,
mFragment);
mController = new RemoveAccountPreferenceController(
Robolectric.setupActivity(Activity.class), mFragment);
}
@After
@@ -169,7 +171,8 @@ public class RemoveAccountPreferenceControllerTest {
}
@Test
@Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class})
@Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class,
ShadowFragment.class})
public void confirmRemove_shouldRemoveAccount()
throws AuthenticatorException, OperationCanceledException, IOException {
when(mFragment.isAdded()).thenReturn(true);
@@ -201,7 +204,8 @@ public class RemoveAccountPreferenceControllerTest {
}
@Test
@Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class})
@Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class,
ShadowFragment.class})
public void confirmRemove_activityGone_shouldSilentlyRemoveAccount()
throws AuthenticatorException, OperationCanceledException, IOException {
final Account account = new Account("Account11", "com.acct1");

View File

@@ -16,19 +16,12 @@
package com.android.settings.accounts;
import static com.android.settings.accounts.TopLevelAccountEntryPreferenceControllerTest
.ShadowAuthenticationHelper.LABELS;
import static com.android.settings.accounts.TopLevelAccountEntryPreferenceControllerTest
.ShadowAuthenticationHelper.TYPES;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.UserHandle;
import android.text.TextUtils;
import com.android.settings.R;
import com.android.settingslib.accounts.AuthenticatorHelper;
import com.android.settings.testutils.shadow.ShadowAuthenticationHelper;
import org.junit.After;
import org.junit.Before;
@@ -37,21 +30,22 @@ import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {TopLevelAccountEntryPreferenceControllerTest.ShadowAuthenticationHelper.class})
@Config(shadows = {ShadowAuthenticationHelper.class})
public class TopLevelAccountEntryPreferenceControllerTest {
private TopLevelAccountEntryPreferenceController mController;
private Context mContext;
private String[] LABELS;
private String[] TYPES;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new TopLevelAccountEntryPreferenceController(mContext, "test_key");
LABELS = ShadowAuthenticationHelper.getLabels();
TYPES = ShadowAuthenticationHelper.getTypes();
}
@After
@@ -60,7 +54,6 @@ public class TopLevelAccountEntryPreferenceControllerTest {
}
@Test
public void updateSummary_hasAccount_shouldDisplayUpTo3AccountTypes() {
assertThat(mController.getSummary())
.isEqualTo(LABELS[0] + ", " + LABELS[1] + ", and " + LABELS[2]);
@@ -83,44 +76,4 @@ public class TopLevelAccountEntryPreferenceControllerTest {
// should only show the 2 accounts with labels
assertThat(mController.getSummary()).isEqualTo(LABELS[0] + " and " + LABELS[1]);
}
@Implements(AuthenticatorHelper.class)
public static class ShadowAuthenticationHelper {
static final String[] TYPES = {"type1", "type2", "type3", "type4"};
static final String[] LABELS = {"LABEL1", "LABEL2", "LABEL3", "LABEL4"};
private static String[] sEnabledAccount = TYPES;
protected void __constructor__(Context context, UserHandle userHandle,
AuthenticatorHelper.OnAccountsUpdateListener listener) {
}
private static void setEnabledAccount(String[] enabledAccount) {
sEnabledAccount = enabledAccount;
}
@Resetter
public static void reset() {
sEnabledAccount = TYPES;
}
@Implementation
protected String[] getEnabledAccountTypes() {
return sEnabledAccount;
}
@Implementation
protected CharSequence getLabelForType(Context context, final String accountType) {
if (TextUtils.equals(accountType, TYPES[0])) {
return LABELS[0];
} else if (TextUtils.equals(accountType, TYPES[1])) {
return LABELS[1];
} else if (TextUtils.equals(accountType, TYPES[2])) {
return LABELS[2];
} else if (TextUtils.equals(accountType, TYPES[3])) {
return LABELS[3];
}
return null;
}
}
}

View File

@@ -39,6 +39,7 @@ import androidx.preference.PreferenceScreen;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowEntityHeaderController;
import com.android.settings.testutils.shadow.ShadowSettingsLibUtils;
import com.android.settings.widget.EntityHeaderController;
import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState;
@@ -58,7 +59,7 @@ import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowEntityHeaderController.class)
@Config(shadows = {ShadowEntityHeaderController.class, ShadowSettingsLibUtils.class})
public class AppInfoWithHeaderTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)

View File

@@ -16,8 +16,6 @@
package com.android.settings.applications;
import static com.android.settings.applications.AppPermissionsPreferenceController.NUM_PERMISSIONS_TO_SHOW;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
@@ -31,6 +29,8 @@ import android.content.pm.PackageManager.NameNotFoundException;
import androidx.preference.Preference;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -70,31 +70,67 @@ public class AppPermissionsPreferenceControllerTest {
}
@Test
public void updateSummary_noGrantedPermission_shouldSetNullSummary() {
public void updateSummary_noGrantedPermission_shouldSetNoPermissionGrantedSummary() {
doNothing().when(mController).queryPermissionSummary();
mController.updateState(mPreference);
mController.mNumPackageChecked = 2;
mController.mNumPackageChecked = 3;
mController.updateSummary(new ArrayList<>());
assertThat(mPreference.getSummary()).isNull();
assertThat(mPreference.getSummary()).isEqualTo(
mContext.getString(R.string.runtime_permissions_summary_no_permissions_granted));
}
@Test
public void updateSummary_hasPermissionGroups_shouldSetPermissionAsSummary() {
public void updateSummary_hasOnePermission_shouldSetPermissionAsSummary() {
doNothing().when(mController).queryPermissionSummary();
mController.updateState(mPreference);
final String permission = "location";
final ArrayList<CharSequence> labels = new ArrayList<>();
labels.add(permission);
final String summary = "Apps using " + permission;
mController.mNumPackageChecked = 2;
mController.mNumPackageChecked = 3;
mController.updateSummary(labels);
assertThat(mPreference.getSummary()).isEqualTo(summary);
}
@Test
public void updateSummary_hasThreePermissions_shouldShowThreePermissionAsSummary() {
doNothing().when(mController).queryPermissionSummary();
mController.updateState(mPreference);
mController.mNumPackageChecked = 3;
final List<CharSequence> labels = new ArrayList<>();
labels.add("Phone");
labels.add("SMS");
labels.add("Microphone");
mController.updateSummary(labels);
final String summary = "Apps using microphone, sms, and phone";
assertThat(mPreference.getSummary()).isEqualTo(summary);
}
@Test
public void updateSummary_hasFivePermissions_shouldShowThreePermissionsAndMoreAsSummary() {
doNothing().when(mController).queryPermissionSummary();
mController.updateState(mPreference);
mController.mNumPackageChecked = 3;
final List<CharSequence> labels = new ArrayList<>();
labels.add("Phone");
labels.add("SMS");
labels.add("Microphone");
labels.add("Contacts");
labels.add("Camera");
labels.add("Location");
mController.updateSummary(labels);
final String summary = "Apps using microphone, contacts, and sms, and more";
assertThat(mPreference.getSummary()).isEqualTo(summary);
}
@Test
public void updateSummary_notReachCallbackCount_shouldNotSetSummary() {
doNothing().when(mController).queryPermissionSummary();
@@ -107,29 +143,4 @@ public class AppPermissionsPreferenceControllerTest {
verify(mPreference, never()).setSummary(anyString());
}
@Test
public void updateSummary_hasFiveItems_shouldShowCertainNumItems() {
doNothing().when(mController).queryPermissionSummary();
mController.updateState(mPreference);
mController.mNumPackageChecked = 2;
mController.updateSummary(getPermissionGroupsSet());
final CharSequence summary = mPreference.getSummary();
final int items = summary.toString().split(",").length;
assertThat(items).isEqualTo(NUM_PERMISSIONS_TO_SHOW);
}
private List<CharSequence> getPermissionGroupsSet() {
final List<CharSequence> labels = new ArrayList<>();
labels.add("Phone");
labels.add("SMS");
labels.add("Microphone");
labels.add("Contacts");
labels.add("Camera");
labels.add("Location");
return labels;
}
}

View File

@@ -211,7 +211,12 @@ public class AppStateNotificationBridgeTest {
when(mSession.getAllApps()).thenReturn(apps);
mBridge.loadAllExtraInfo();
assertThat(apps.get(0).extraInfo).isNull();
// extra info should exist and blocked status should be populated
assertThat(apps.get(0).extraInfo).isNotNull();
verify(mBackend).getNotificationsBanned(PKG1, 0);
// but the recent/frequent counts should be 0 so they don't appear on those screens
assertThat(((NotificationsSentState) apps.get(0).extraInfo).avgSentDaily).isEqualTo(0);
assertThat(((NotificationsSentState) apps.get(0).extraInfo).lastSent).isEqualTo(0);
}
@Test

View File

@@ -16,9 +16,9 @@
package com.android.settings.applications;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
@@ -28,6 +28,10 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.ModuleInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.Button;
@@ -51,6 +55,8 @@ public class AppStorageSettingsTest {
private AppStorageSettings mSettings;
private Button mLeftButton;
private Button mRightButton;
@Mock
private PackageManager mPackageManager;
@Before
public void setUp() {
@@ -58,6 +64,8 @@ public class AppStorageSettingsTest {
mLeftButton = new Button(RuntimeEnvironment.application);
mRightButton = new Button(RuntimeEnvironment.application);
mSettings = spy(new AppStorageSettings());
mSettings.mPm = mPackageManager;
mSettings.mPackageName = "Package";
mSettings.mSizeController = mSizesController;
mButtonsPref = createMock();
mSettings.mButtonsPref = mButtonsPref;
@@ -77,7 +85,9 @@ public class AppStorageSettingsTest {
}
@Test
public void updateUiWithSize_noAppStats_shouldDisableClearButtons() {
public void updateUiWithSize_noAppStats_shouldDisableClearButtons()
throws PackageManager.NameNotFoundException {
mockMainlineModule(mSettings.mPackageName, false /* isMainlineModule */);
mSettings.updateUiWithSize(null);
verify(mSizesController).updateUi(nullable(Context.class));
@@ -86,12 +96,15 @@ public class AppStorageSettingsTest {
}
@Test
public void updateUiWithSize_hasDataAndCache_shouldEnableClearButtons() {
public void updateUiWithSize_hasDataAndCache_shouldEnableClearButtons()
throws PackageManager.NameNotFoundException {
final AppStorageStats stats = mock(AppStorageStats.class);
when(stats.getCacheBytes()).thenReturn(5000L);
when(stats.getDataBytes()).thenReturn(10000L);
doNothing().when(mSettings).handleClearCacheClick();
doNothing().when(mSettings).handleClearDataClick();
mockMainlineModule(mSettings.mPackageName, false /* isMainlineModule */);
mSettings.updateUiWithSize(stats);
verify(mButtonsPref).setButton1Enabled(true);
@@ -105,6 +118,22 @@ public class AppStorageSettingsTest {
verify(mSettings).handleClearCacheClick();
}
@Test
public void updateUiWithSize_mainlineModule_shouldDisableClearButtons()
throws PackageManager.NameNotFoundException {
final AppStorageStats stats = mock(AppStorageStats.class);
when(stats.getCacheBytes()).thenReturn(5000L);
when(stats.getDataBytes()).thenReturn(10000L);
doNothing().when(mSettings).handleClearCacheClick();
doNothing().when(mSettings).handleClearDataClick();
mockMainlineModule(mSettings.mPackageName, true /* isMainlineModule */);
mSettings.updateUiWithSize(stats);
verify(mButtonsPref).setButton1Enabled(false);
verify(mButtonsPref).setButton2Enabled(false);
}
private ActionButtonsPreference createMock() {
final ActionButtonsPreference pref = mock(ActionButtonsPreference.class);
when(pref.setButton1Text(anyInt())).thenReturn(pref);
@@ -121,5 +150,23 @@ public class AppStorageSettingsTest {
return pref;
}
private void mockMainlineModule(String packageName, boolean isMainlineModule)
throws PackageManager.NameNotFoundException {
final PackageInfo packageInfo = new PackageInfo();
final ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.sourceDir = "apex";
packageInfo.applicationInfo = applicationInfo;
if (isMainlineModule) {
when(mPackageManager.getModuleInfo(packageName, 0 /* flags */)).thenReturn(
new ModuleInfo());
} else {
when(mPackageManager.getPackageInfo(packageName, 0 /* flags */)).thenReturn(
packageInfo);
when(mPackageManager.getModuleInfo(packageName, 0 /* flags */)).thenThrow(
new PackageManager.NameNotFoundException());
}
}
}

View File

@@ -18,6 +18,7 @@ package com.android.settings.applications;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@@ -27,6 +28,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
@@ -36,7 +38,6 @@ import android.os.Build;
import android.os.UserHandle;
import android.os.UserManager;
import com.android.settings.R;
import com.android.settings.testutils.ApplicationTestUtils;
import com.android.settingslib.testutils.shadow.ShadowDefaultDialerManager;
import com.android.settingslib.testutils.shadow.ShadowSmsApplication;
@@ -165,7 +166,7 @@ public final class ApplicationFeatureProviderImplTest {
.thenReturn(PackageManager.INSTALL_REASON_POLICY);
mAppCount = -1;
mProvider.calculateNumberOfAppsWithAdminGrantedPermissions(new String[] {PERMISSION}, async,
mProvider.calculateNumberOfAppsWithAdminGrantedPermissions(new String[]{PERMISSION}, async,
(num) -> mAppCount = num);
if (async) {
ShadowApplication.runBackgroundTasks();
@@ -202,7 +203,7 @@ public final class ApplicationFeatureProviderImplTest {
.thenReturn(PackageManager.INSTALL_REASON_POLICY);
mAppList = null;
mProvider.listAppsWithAdminGrantedPermissions(new String[] {PERMISSION},
mProvider.listAppsWithAdminGrantedPermissions(new String[]{PERMISSION},
(list) -> mAppList = list);
assertThat(mAppList).isNotNull();
assertThat(mAppList.size()).isEqualTo(2);
@@ -251,10 +252,10 @@ public final class ApplicationFeatureProviderImplTest {
new ApplicationInfo(app2.activityInfo.applicationInfo)));
assertThat(mProvider.findPersistentPreferredActivities(MAIN_USER_ID,
new Intent[] {viewIntent, editIntent, sendIntent}))
new Intent[]{viewIntent, editIntent, sendIntent}))
.isEqualTo(expectedMainUserActivities);
assertThat(mProvider.findPersistentPreferredActivities(MANAGED_PROFILE_ID,
new Intent[] {viewIntent, editIntent, sendIntent}))
new Intent[]{viewIntent, editIntent, sendIntent}))
.isEqualTo(expectedManagedUserActivities);
}
@@ -282,6 +283,35 @@ public final class ApplicationFeatureProviderImplTest {
assertThat(keepEnabledPackages).containsAllIn(expectedPackages);
}
@Test
@Config(shadows = {ShadowSmsApplication.class, ShadowDefaultDialerManager.class})
public void getKeepEnabledPackages_hasEuiccComponent_shouldContainEuiccPackage() {
final String testDialer = "com.android.test.defaultdialer";
final String testSms = "com.android.test.defaultsms";
final String testLocationHistory = "com.android.test.location.history";
final String testEuicc = "com.android.test.euicc";
ShadowSmsApplication.setDefaultSmsApplication(new ComponentName(testSms, "receiver"));
ShadowDefaultDialerManager.setDefaultDialerApplication(testDialer);
final ComponentInfo componentInfo = new ComponentInfo();
componentInfo.packageName = testEuicc;
ApplicationFeatureProviderImpl spyProvider = spy(new ApplicationFeatureProviderImpl(
mContext, mPackageManager, mPackageManagerService, mDevicePolicyManager));
doReturn(componentInfo).when(spyProvider).findEuiccService(mPackageManager);
// Spy the real context to mock LocationManager.
Context spyContext = spy(RuntimeEnvironment.application);
when(mLocationManager.getExtraLocationControllerPackage()).thenReturn(testLocationHistory);
when(spyContext.getSystemService(Context.LOCATION_SERVICE)).thenReturn(mLocationManager);
ReflectionHelpers.setField(mProvider, "mContext", spyContext);
final Set<String> keepEnabledPackages = spyProvider.getKeepEnabledPackages();
assertThat(keepEnabledPackages).contains(testEuicc);
}
@Test
@Config(shadows = {ShadowSmsApplication.class, ShadowDefaultDialerManager.class})
public void getKeepEnabledPackages_shouldContainSettingsIntelligence() {

View File

@@ -0,0 +1,166 @@
/*
* Copyright (C) 2020 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.settings.applications;
import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.util.ArraySet;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settingslib.widget.FooterPreference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowUtils.class)
public class OpenSupportedLinksTest {
private static final String TEST_FOOTER_TITLE = "FooterTitle";
private static final String TEST_DOMAIN_LINK = "aaa.bbb.ccc";
private static final String TEST_SUMMARY = "TestSummary";
private static final String TEST_PACKAGE = "ssl.test.package.com";
@Mock
private PackageManager mPackageManager;
@Mock
private Resources mResources;
private Context mContext;
private TestFragment mSettings;
private FooterPreference mFooter;
private PreferenceCategory mCategory;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mSettings = spy(new TestFragment(mContext, mPackageManager));
mCategory = spy(new PreferenceCategory(mContext));
mFooter = new FooterPreference.Builder(mContext).setTitle(TEST_FOOTER_TITLE).build();
}
@After
public void tearDown() {
ShadowUtils.reset();
}
@Test
public void addLinksToFooter_noHandledDomains_returnDefaultFooterTitle() {
mSettings.addLinksToFooter(mFooter);
assertThat(mFooter.getTitle()).isEqualTo(TEST_FOOTER_TITLE);
}
@Test
public void addLinksToFooter_oneHandledDomains_returnDomainsFooterTitle() {
final ArraySet<String> domainLinks = new ArraySet<>();
domainLinks.add(TEST_DOMAIN_LINK);
ShadowUtils.setHandledDomains(domainLinks);
mSettings.addLinksToFooter(mFooter);
assertThat(mFooter.getTitle().toString()).contains(TEST_DOMAIN_LINK);
}
@Test
public void initRadioPreferencesGroup_statusAlways_allowOpenChecked() {
init(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
mSettings.initRadioPreferencesGroup();
assertThat(mSettings.mAllowOpening.isChecked()).isTrue();
assertThat(mSettings.mAskEveryTime.isChecked()).isFalse();
assertThat(mSettings.mNotAllowed.isChecked()).isFalse();
}
@Test
public void initRadioPreferencesGroup_statusAsk_askEveryTimeChecked() {
init(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
mSettings.initRadioPreferencesGroup();
assertThat(mSettings.mAllowOpening.isChecked()).isFalse();
assertThat(mSettings.mAskEveryTime.isChecked()).isTrue();
assertThat(mSettings.mNotAllowed.isChecked()).isFalse();
}
@Test
public void initRadioPreferencesGroup_statusNever_notAllowedChecked() {
init(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
mSettings.initRadioPreferencesGroup();
assertThat(mSettings.mAllowOpening.isChecked()).isFalse();
assertThat(mSettings.mAskEveryTime.isChecked()).isFalse();
assertThat(mSettings.mNotAllowed.isChecked()).isTrue();
}
@Test
public void getEntriesNo_oneHandledDomains_returnOne() {
initHandledDomains();
assertThat(mSettings.getEntriesNo()).isEqualTo(1);
}
private void init(int status) {
doReturn(status).when(mPackageManager).getIntentVerificationStatusAsUser(anyString(),
anyInt());
doReturn(mCategory).when(mSettings).findPreference(any(CharSequence.class));
doReturn(mResources).when(mSettings).getResources();
when(mResources.getQuantityString(anyInt(), anyInt(), anyInt())).thenReturn(TEST_SUMMARY);
doReturn(true).when(mCategory).addPreference(any(Preference.class));
}
public static class TestFragment extends OpenSupportedLinks {
private final Context mContext;
public TestFragment(Context context, PackageManager packageManager) {
mContext = context;
mPackageManager = packageManager;
mPackageName = TEST_PACKAGE;
}
}
private void initHandledDomains() {
final ArraySet<String> domainLinks = new ArraySet<>();
domainLinks.add(TEST_DOMAIN_LINK);
ShadowUtils.setHandledDomains(domainLinks);
}
}

View File

@@ -16,7 +16,7 @@
package com.android.settings.applications;
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.google.common.truth.Truth.assertThat;
@@ -83,7 +83,7 @@ public class SpecialAppAccessPreferenceControllerTest {
@Test
public void getAvailabilityState_unsearchable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test

View File

@@ -16,6 +16,8 @@
package com.android.settings.applications.appinfo;
import static com.android.settings.applications.appinfo.AppButtonsPreferenceController.KEY_REMOVE_TASK_WHEN_FINISHING;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
@@ -34,7 +36,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.ActivityManager;
import android.app.Application;
import android.app.admin.DevicePolicyManager;
import android.app.settings.SettingsEnums;
import android.content.Context;
@@ -117,6 +118,8 @@ public class AppButtonsPreferenceControllerTest {
private UserManager mUserManager;
@Mock
private PackageInfo mPackageInfo;
@Mock
private PreferenceScreen mScreen;
private Context mContext;
private Intent mUninstallIntent;
@@ -275,7 +278,8 @@ public class AppButtonsPreferenceControllerTest {
}
@Test
public void updateUninstallButton_isProfileOrDeviceOwner_setButtonDisable() {
public void updateUninstallButton_isSystemAndIsProfileOrDeviceOwner_setButtonDisable() {
doReturn(true).when(mController).isSystemPackage(any(), any(), any());
doReturn(true).when(mDpm).isDeviceOwnerAppOnAnyUser(anyString());
mController.updateUninstallButton();
@@ -283,6 +287,38 @@ public class AppButtonsPreferenceControllerTest {
verify(mButtonPrefs).setButton2Enabled(false);
}
@Test
public void updateUninstallButton_isSystemAndIsNotProfileOrDeviceOwner_setButtonEnabled() {
doReturn(true).when(mController).isSystemPackage(any(), any(), any());
doReturn(false).when(mDpm).isDeviceOwnerAppOnAnyUser(anyString());
mController.updateUninstallButton();
verify(mButtonPrefs).setButton2Enabled(true);
}
@Test
public void updateUninstallButton_isNotSystemAndIsProfileOrDeviceOwner_setButtonDisable() {
doReturn(false).when(mController).isSystemPackage(any(), any(), any());
doReturn(0).when(mDpm).getDeviceOwnerUserId();
doReturn(true).when(mDpm).isDeviceOwnerApp(anyString());
mController.updateUninstallButton();
verify(mButtonPrefs).setButton2Enabled(false);
}
@Test
public void updateUninstallButton_isNotSystemAndIsNotProfileOrDeviceOwner_setButtonEnabled() {
doReturn(false).when(mController).isSystemPackage(any(), any(), any());
doReturn(10).when(mDpm).getDeviceOwnerUserId();
doReturn(false).when(mDpm).isDeviceOwnerApp(anyString());
mController.updateUninstallButton();
verify(mButtonPrefs).setButton2Enabled(true);
}
@Test
public void updateUninstallButton_isDeviceProvisioningApp_setButtonDisable() {
doReturn(true).when(mDpm).isDeviceOwnerAppOnAnyUser(anyString());
@@ -439,6 +475,20 @@ public class AppButtonsPreferenceControllerTest {
assertThat(mController.refreshUi()).isFalse();
}
@Test
public void refreshUi_buttonPreferenceNull_shouldNotCrash()
throws PackageManager.NameNotFoundException {
doReturn(AppButtonsPreferenceController.AVAILABLE)
.when(mController).getAvailabilityStatus();
doReturn(mPackageInfo).when(mPackageManger).getPackageInfo(anyString(), anyInt());
doReturn(mButtonPrefs).when(mScreen).findPreference(anyString());
mController.displayPreference(mScreen);
mController.mButtonsPref = null;
// Should not crash in this method
assertThat(mController.refreshUi()).isTrue();
}
@Test
public void onPackageListChanged_available_shouldRefreshUi() {
doReturn(AppButtonsPreferenceController.AVAILABLE)
@@ -469,6 +519,43 @@ public class AppButtonsPreferenceControllerTest {
AppButtonsPreferenceController.DISABLED_FOR_USER);
}
@Test
public void handleActivityResult_onAppUninstall_removeTask() {
mController.handleActivityResult(REQUEST_UNINSTALL, 0, new Intent());
ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mSettingsActivity).finishPreferencePanel(anyInt(), argumentCaptor.capture());
final Intent i = argumentCaptor.getValue();
assertThat(i).isNotNull();
assertThat(i.getBooleanExtra(KEY_REMOVE_TASK_WHEN_FINISHING, false)).isTrue();
}
@Test
public void handleActivityResult_onAppNotUninstall_persistTask() {
mController.handleActivityResult(REQUEST_UNINSTALL + 1, 0, new Intent());
ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mSettingsActivity).finishPreferencePanel(anyInt(), argumentCaptor.capture());
final Intent i = argumentCaptor.getValue();
assertThat(i).isNotNull();
assertThat(i.getBooleanExtra(KEY_REMOVE_TASK_WHEN_FINISHING, false)).isFalse();
}
@Test
@Config(shadows = ShadowAppUtils.class)
public void isAvailable_nonMainlineModule_isTrue() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(shadows = ShadowAppUtils.class)
public void isAvailable_mainlineModule_isFalse() {
ShadowAppUtils.addMainlineModule(mController.mPackageName);
assertThat(mController.isAvailable()).isFalse();
}
/**
* The test fragment which implements
* {@link ButtonActionDialogFragment.AppButtonsDialogListener}
@@ -489,11 +576,19 @@ public class AppButtonsPreferenceControllerTest {
private ActionButtonsPreference createMock() {
final ActionButtonsPreference pref = mock(ActionButtonsPreference.class);
when(pref.setButton1Text(anyInt())).thenReturn(pref);
when(pref.setButton1Icon(anyInt())).thenReturn(pref);
when(pref.setButton1Enabled(anyBoolean())).thenReturn(pref);
when(pref.setButton1OnClickListener(any(View.OnClickListener.class))).thenReturn(pref);
when(pref.setButton2Text(anyInt())).thenReturn(pref);
when(pref.setButton2Icon(anyInt())).thenReturn(pref);
when(pref.setButton2Enabled(anyBoolean())).thenReturn(pref);
when(pref.setButton2Visible(anyBoolean())).thenReturn(pref);
when(pref.setButton2OnClickListener(any(View.OnClickListener.class))).thenReturn(pref);
when(pref.setButton3Text(anyInt())).thenReturn(pref);
when(pref.setButton3Icon(anyInt())).thenReturn(pref);
when(pref.setButton3Enabled(anyBoolean())).thenReturn(pref);
when(pref.setButton3OnClickListener(any(View.OnClickListener.class))).thenReturn(pref);
return pref;
}
@@ -515,16 +610,22 @@ public class AppButtonsPreferenceControllerTest {
public static class ShadowAppUtils {
public static Set<String> sSystemModules = new ArraySet<>();
public static Set<String> sMainlineModules = new ArraySet<>();
@Resetter
public static void reset() {
sSystemModules.clear();
sMainlineModules.clear();
}
public static void addHiddenModule(String pkg) {
sSystemModules.add(pkg);
}
public static void addMainlineModule(String pkg) {
sMainlineModules.add(pkg);
}
@Implementation
protected static boolean isInstant(ApplicationInfo info) {
return false;
@@ -534,5 +635,10 @@ public class AppButtonsPreferenceControllerTest {
protected static boolean isSystemModule(Context context, String packageName) {
return sSystemModules.contains(packageName);
}
@Implementation
protected static boolean isMainlineModule(PackageManager pm, String packageName) {
return sMainlineModules.contains(packageName);
}
}
}

View File

@@ -42,6 +42,7 @@ import androidx.lifecycle.LifecycleOwner;
import androidx.preference.PreferenceScreen;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowSettingsLibUtils;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.LayoutPreference;
@@ -54,8 +55,10 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowSettingsLibUtils.class)
public class AppHeaderViewPreferenceControllerTest {
@Mock

View File

@@ -35,7 +35,7 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.SettingsActivity;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.notification.AppNotificationSettings;
import com.android.settings.notification.app.AppNotificationSettings;
import com.android.settingslib.applications.ApplicationsState;
import org.junit.Before;

View File

@@ -32,6 +32,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ModuleInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
@@ -98,12 +99,15 @@ public class AppInstallerInfoPreferenceControllerTest {
}
@Test
public void getAvailabilityStatus_hasAppLabel_shouldReturnAvailable() {
public void getAvailabilityStatus_hasAppLabel_shouldReturnAvailable()
throws PackageManager.NameNotFoundException {
final String packageName = "Package1";
when(mUserManager.isManagedProfile()).thenReturn(false);
when(mAppInfo.loadLabel(mPackageManager)).thenReturn("Label1");
mController = new AppInstallerInfoPreferenceController(mContext, "test_key");
mController.setPackageName("Package1");
mController.setPackageName(packageName);
mController.setParentFragment(mFragment);
mockMainlineModule(packageName, false /* isMainlineModule */);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
@@ -148,4 +152,35 @@ public class AppInstallerInfoPreferenceControllerTest {
verify(mPreference, never()).setEnabled(false);
verify(mPreference).setIntent(any(Intent.class));
}
@Test
public void getAvailabilityStatus_isMainlineModule_shouldReturnDisabled()
throws PackageManager.NameNotFoundException {
final String packageName = "Package";
when(mUserManager.isManagedProfile()).thenReturn(false);
when(mAppInfo.loadLabel(mPackageManager)).thenReturn("Label");
mController.setPackageName(packageName);
mockMainlineModule(packageName, true /* isMainlineModule */);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.DISABLED_FOR_USER);
}
private void mockMainlineModule(String packageName, boolean isMainlineModule)
throws PackageManager.NameNotFoundException {
final PackageInfo packageInfo = new PackageInfo();
final ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.sourceDir = "apex";
packageInfo.applicationInfo = applicationInfo;
if (isMainlineModule) {
when(mPackageManager.getModuleInfo(packageName, 0 /* flags */)).thenReturn(
new ModuleInfo());
} else {
when(mPackageManager.getPackageInfo(packageName, 0 /* flags */)).thenReturn(
packageInfo);
when(mPackageManager.getModuleInfo(packageName, 0 /* flags */)).thenThrow(
new PackageManager.NameNotFoundException());
}
}
}

View File

@@ -35,7 +35,7 @@ import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.notification.AppNotificationSettings;
import com.android.settings.notification.app.AppNotificationSettings;
import com.android.settings.notification.NotificationBackend;
import com.android.settingslib.applications.ApplicationsState;

View File

@@ -19,6 +19,7 @@ package com.android.settings.applications.appinfo;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -26,8 +27,12 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
@@ -37,6 +42,8 @@ import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState.AppEntry;
import com.android.settingslib.applications.instantapps.InstantAppDataProvider;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -46,6 +53,8 @@ import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class AppOpenByDefaultPreferenceControllerTest {
@@ -55,6 +64,8 @@ public class AppOpenByDefaultPreferenceControllerTest {
private PreferenceScreen mScreen;
@Mock
private Preference mPreference;
@Mock
private PackageManager mPackageManager;
private Context mContext;
private AppOpenByDefaultPreferenceController mController;
@@ -62,10 +73,11 @@ public class AppOpenByDefaultPreferenceControllerTest {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application.getApplicationContext();
mContext = spy(RuntimeEnvironment.application.getApplicationContext());
mController = spy(new AppOpenByDefaultPreferenceController(mContext, "preferred_app"));
mController.setParentFragment(mFragment);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
}
@Test
@@ -146,13 +158,42 @@ public class AppOpenByDefaultPreferenceControllerTest {
}
@Test
public void updateState_notInstantApp_shouldShowPreferenceAndSetSummary() {
when(mFragment.getPackageInfo()).thenReturn(new PackageInfo());
public void updateState_isBrowserApp_shouldNotShowPreference() {
final PackageInfo packageInfo = new PackageInfo();
packageInfo.packageName = "com.package.test.browser";
when(mFragment.getPackageInfo()).thenReturn(packageInfo);
ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
(InstantAppDataProvider) (i -> false));
final ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.activityInfo = new ActivityInfo();
resolveInfo.handleAllWebDataURI = true;
final List<ResolveInfo> resolveInfos = ImmutableList.of(resolveInfo);
when(mPackageManager
.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(resolveInfos);
mController.updateState(mPreference);
verify(mPreference).setVisible(false);
}
@Test
public void updateState_notBrowserApp_notInstantApp_shouldShowPreferenceAndSetSummary() {
final PackageInfo packageInfo = new PackageInfo();
packageInfo.packageName = "com.package.test.browser";
when(mFragment.getPackageInfo()).thenReturn(packageInfo);
ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
(InstantAppDataProvider) (i -> false));
final ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.activityInfo = new ActivityInfo();
resolveInfo.handleAllWebDataURI = false;
final List<ResolveInfo> resolveInfos = ImmutableList.of(resolveInfo);
when(mPackageManager
.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(resolveInfos);
final AppEntry appEntry = mock(AppEntry.class);
appEntry.info = new ApplicationInfo();
when(mFragment.getAppEntry()).thenReturn(appEntry);
ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
(InstantAppDataProvider) (i -> false));
mController.updateState(mPreference);

View File

@@ -28,6 +28,7 @@ import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
@@ -43,6 +44,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
@@ -57,6 +59,8 @@ public class AppPermissionPreferenceControllerTest {
private PreferenceScreen mScreen;
@Mock
private Preference mPreference;
@Mock
private PackageManager mPackageManager;
private Context mContext;
private AppPermissionPreferenceController mController;
@@ -68,6 +72,7 @@ public class AppPermissionPreferenceControllerTest {
mController = new AppPermissionPreferenceController(mContext, "permission_settings");
mController.setPackageName("package1");
mController.setParentFragment(mFragment);
ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager);
when(mScreen.findPreference(any())).thenReturn(mPreference);
final String key = mController.getPreferenceKey();
@@ -75,10 +80,26 @@ public class AppPermissionPreferenceControllerTest {
when(mFragment.getActivity()).thenReturn(mActivity);
}
@Test
public void onStart_shouldAddPermissionsChangeListener() {
mController.onStart();
verify(mPackageManager).addOnPermissionsChangeListener(
any(PackageManager.OnPermissionsChangedListener.class));
}
@Test
public void onStop_shouldRemovePermissionsChangeListener() {
mController.onStop();
verify(mPackageManager).removeOnPermissionsChangeListener(
any(PackageManager.OnPermissionsChangedListener.class));
}
@Test
public void getAvailabilityStatus_isAlwaysAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(AppPermissionPreferenceController.AVAILABLE);
.isEqualTo(AppPermissionPreferenceController.AVAILABLE);
}
@Test

View File

@@ -85,8 +85,8 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
}
@Test
public void constructor_callsIsApplicationQualifiedForRole() {
verify(mRoleControllerManager).isApplicationQualifiedForRole(eq(TEST_ROLE_NAME), eq(
public void constructor_callsIsApplicationVisibleForRole() {
verify(mRoleControllerManager).isApplicationVisibleForRole(eq(TEST_ROLE_NAME), eq(
TEST_PACKAGE_NAME), any(Executor.class), any(Consumer.class));
}
@@ -108,7 +108,7 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
@Test
public void
getAvailabilityStatus_noCallbackForIsRoleNotVisible_shouldReturnUnsupported() {
setApplicationIsQualifiedForRole(true);
setApplicationIsVisibleForRole(true);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
DefaultAppShortcutPreferenceControllerBase.UNSUPPORTED_ON_DEVICE);
@@ -117,7 +117,7 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
@Test
public void getAvailabilityStatus_RoleIsNotVisible_shouldReturnUnsupported() {
setRoleIsVisible(false);
setApplicationIsQualifiedForRole(true);
setApplicationIsVisibleForRole(true);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
DefaultAppShortcutPreferenceControllerBase.UNSUPPORTED_ON_DEVICE);
@@ -125,7 +125,7 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
@Test
public void
getAvailabilityStatus_noCallbackForIsApplicationQualifiedForRole_shouldReturnUnsupported() {
getAvailabilityStatus_noCallbackForIsApplicationVisibleForRole_shouldReturnUnsupported() {
setRoleIsVisible(true);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
@@ -133,18 +133,18 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
}
@Test
public void getAvailabilityStatus_applicationIsNotQualifiedForRole_shouldReturnUnsupported() {
public void getAvailabilityStatus_applicationIsNotVisibleForRole_shouldReturnUnsupported() {
setRoleIsVisible(true);
setApplicationIsQualifiedForRole(false);
setApplicationIsVisibleForRole(false);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
DefaultAppShortcutPreferenceControllerBase.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_RoleVisibleAndApplicationQualified_shouldReturnAvailable() {
public void getAvailabilityStatus_RoleVisibleAndApplicationVisible_shouldReturnAvailable() {
setRoleIsVisible(true);
setApplicationIsQualifiedForRole(true);
setApplicationIsVisibleForRole(true);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
DefaultAppShortcutPreferenceControllerBase.AVAILABLE);
@@ -159,13 +159,13 @@ public class DefaultAppShortcutPreferenceControllerBaseTest {
callback.accept(visible);
}
private void setApplicationIsQualifiedForRole(boolean qualified) {
private void setApplicationIsVisibleForRole(boolean visible) {
final ArgumentCaptor<Consumer<Boolean>> callbackCaptor = ArgumentCaptor.forClass(
Consumer.class);
verify(mRoleControllerManager).isApplicationQualifiedForRole(eq(TEST_ROLE_NAME), eq(
verify(mRoleControllerManager).isApplicationVisibleForRole(eq(TEST_ROLE_NAME), eq(
TEST_PACKAGE_NAME), any(Executor.class), callbackCaptor.capture());
final Consumer<Boolean> callback = callbackCaptor.getValue();
callback.accept(qualified);
callback.accept(visible);
}
@Test

View File

@@ -0,0 +1,196 @@
/*
* Copyright (C) 2020 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.settings.applications.appinfo;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.app.AppOpsManager;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import androidx.preference.SwitchPreference;
import com.android.settings.applications.AppStateAppOpsBridge.PermissionState;
import com.android.settings.applications.AppStateManageExternalStorageBridge;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import java.util.HashMap;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowUserManager.class})
public class ManageExternalStorageDetailsTest {
@Mock
private AppOpsManager mAppOpsManager;
@Mock
private SwitchPreference mSwitchPref;
@Mock
private MetricsFeatureProvider mMetricsFeatureProvider;
@Mock
private AppStateManageExternalStorageBridge mBridge;
private ManageExternalStorageDetails mFragment;
private final HashMap<Integer, Integer> mUidToOpModeMap = new HashMap<>();
@Before
public void setUp() {
// Reset the global trackers
mUidToOpModeMap.clear();
//Start the mockin'
MockitoAnnotations.initMocks(this);
mFragment = new ManageExternalStorageDetails();
ReflectionHelpers.setField(mFragment, "mAppOpsManager", mAppOpsManager);
ReflectionHelpers.setField(mFragment, "mSwitchPref", mSwitchPref);
ReflectionHelpers.setField(mFragment, "mBridge", mBridge);
ReflectionHelpers.setField(mFragment, "mMetricsFeatureProvider",
mMetricsFeatureProvider);
mockAppOpsOperations();
}
@Test
public void onPreferenceChange_enableManageExternalStorage_shouldTriggerAppOpsManager() {
// Inject mock package details
final int mockUid = 23333;
final String mockPkgName = "com.mock.pkg.1";
PackageInfo pkgInfo = mock(PackageInfo.class);
pkgInfo.applicationInfo = new ApplicationInfo();
pkgInfo.applicationInfo.uid = mockUid;
ReflectionHelpers.setField(mFragment, "mPackageInfo", pkgInfo);
ReflectionHelpers.setField(mFragment, "mPackageName", mockPkgName);
// Set the initial state to be disabled
injectPermissionState(false);
// Simulate a preference change
mFragment.onPreferenceChange(mSwitchPref, /* newValue */ true);
// Verify that mAppOpsManager was called to allow the app-op
verify(mAppOpsManager, times(1))
.setUidMode(anyInt(), anyInt(), anyInt());
assertThat(mUidToOpModeMap).containsExactly(mockUid, AppOpsManager.MODE_ALLOWED);
// Verify the mSwitchPref was enabled
ArgumentCaptor<Boolean> acSetEnabled = ArgumentCaptor.forClass(Boolean.class);
verify(mSwitchPref, times(1)).setEnabled(acSetEnabled.capture());
assertThat(acSetEnabled.getAllValues()).containsExactly(true);
// Verify that mSwitchPref was toggled to on
ArgumentCaptor<Boolean> acSetChecked = ArgumentCaptor.forClass(Boolean.class);
verify(mSwitchPref, times(1)).setChecked(acSetChecked.capture());
assertThat(acSetChecked.getAllValues()).containsExactly(true);
}
@Test
public void onPreferenceChange_disableManageExternalStorage_shouldTriggerAppOpsManager() {
// Inject mock package details
final int mockUid = 24444;
final String mockPkgName = "com.mock.pkg.2";
PackageInfo pkgInfo = mock(PackageInfo.class);
pkgInfo.applicationInfo = new ApplicationInfo();
pkgInfo.applicationInfo.uid = mockUid;
ReflectionHelpers.setField(mFragment, "mPackageInfo", pkgInfo);
ReflectionHelpers.setField(mFragment, "mPackageName", mockPkgName);
// Set the initial state to be enabled
injectPermissionState(true);
// Simulate a preference change
mFragment.onPreferenceChange(mSwitchPref, /* newValue */ false);
// Verify that mAppOpsManager was called to deny the app-op
verify(mAppOpsManager, times(1))
.setUidMode(anyInt(), anyInt(), anyInt());
assertThat(mUidToOpModeMap).containsExactly(mockUid, AppOpsManager.MODE_ERRORED);
// Verify the mSwitchPref was enabled
ArgumentCaptor<Boolean> acSetEnabled = ArgumentCaptor.forClass(Boolean.class);
verify(mSwitchPref, times(1)).setEnabled(acSetEnabled.capture());
assertThat(acSetEnabled.getAllValues()).containsExactly(true);
// Verify that mSwitchPref was toggled to off
ArgumentCaptor<Boolean> acSetChecked = ArgumentCaptor.forClass(Boolean.class);
verify(mSwitchPref, times(1)).setChecked(acSetChecked.capture());
assertThat(acSetChecked.getAllValues()).containsExactly(false);
}
private void injectPermissionState(boolean enabled) {
PermissionState state = new PermissionState(null, null);
state.permissionDeclared = true;
state.appOpMode = enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_ERRORED;
ReflectionHelpers.setField(mFragment, "mPermissionState", state);
}
private void mockAppOpsOperations() {
Answer<Void> answerSetUidMode = invocation -> {
int code = invocation.getArgument(0);
int uid = invocation.getArgument(1);
int mode = invocation.getArgument(2);
if (code != AppOpsManager.OP_MANAGE_EXTERNAL_STORAGE) {
return null;
}
mUidToOpModeMap.put(uid, mode);
return null;
};
doAnswer(answerSetUidMode).when(mAppOpsManager)
.setUidMode(anyInt(), anyInt(), anyInt());
Answer<PermissionState> answerPermState = invocation -> {
String packageName = invocation.getArgument(0);
int uid = invocation.getArgument(1);
PermissionState res = new PermissionState(packageName, null);
res.permissionDeclared = false;
if (mUidToOpModeMap.containsKey(uid)) {
res.permissionDeclared = true;
res.appOpMode = mUidToOpModeMap.get(uid);
}
return res;
};
doAnswer(answerPermState).when(mBridge)
.getManageExternalStoragePermState(nullable(String.class), anyInt());
}
}

View File

@@ -119,8 +119,8 @@ public class TimeSpentInAppPreferenceControllerTest {
}
@Test
public void getSummary_shouldQueryAppFeatureProvider() {
mController.getSummary();
public void getSummaryTextInBackground_shouldQueryAppFeatureProvider() {
mController.getSummaryTextInBackground();
verify(mFeatureFactory.applicationFeatureProvider).getTimeSpentInApp(
nullable(String.class));

View File

@@ -31,15 +31,15 @@ import androidx.preference.PreferenceScreen;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.widget.RadioButtonPreference;
import com.android.settingslib.applications.DefaultAppInfo;
import com.android.settingslib.widget.RadioButtonPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@@ -49,20 +49,20 @@ import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class DefaultAppPickerFragmentTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private FragmentActivity mActivity;
@Mock
private PreferenceScreen mScreen;
@Mock
private UserManager mUserManager;
private FakeFeatureFactory mFeatureFactory;
private FragmentActivity mActivity;
private TestFragment mFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mFeatureFactory = FakeFeatureFactory.setupForTest();
mActivity = spy(Robolectric.buildActivity(FragmentActivity.class).get());
mFragment = spy(new TestFragment());
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);

View File

@@ -40,6 +40,7 @@ import androidx.fragment.app.FragmentActivity;
import androidx.preference.PreferenceScreen;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settings.testutils.shadow.ShadowSecureSettings;
import com.android.settingslib.applications.DefaultAppInfo;
@@ -133,6 +134,7 @@ public class DefaultAutofillPickerTest {
}
@Test
@Config(shadows = ShadowFragment.class)
public void mUserId_shouldDeriveUidFromManagedCaller() {
setupUserManager();
setupCaller();
@@ -145,6 +147,7 @@ public class DefaultAutofillPickerTest {
}
@Test
@Config(shadows = ShadowFragment.class)
public void mUserId_shouldDeriveUidFromMainCaller() {
setupUserManager();
setupCaller();
@@ -157,6 +160,7 @@ public class DefaultAutofillPickerTest {
}
@Test
@Config(shadows = ShadowFragment.class)
public void mUserId_shouldDeriveUidFromManagedClick() {
setupUserManager();
setupClick(/* forWork= */ true);
@@ -169,6 +173,7 @@ public class DefaultAutofillPickerTest {
}
@Test
@Config(shadows = ShadowFragment.class)
public void mUserId_shouldDeriveUidFromMainClick() {
setupUserManager();
setupClick(/* forWork= */ false);

View File

@@ -56,8 +56,12 @@ import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowAppUtils;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settings.widget.LoadingViewController;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.applications.ApplicationsState.AppEntry;
import com.android.settingslib.applications.ApplicationsState.AppFilter;
import org.junit.Before;
import org.junit.Test;
@@ -66,12 +70,14 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.fakes.RoboMenuItem;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowUserManager.class, ShadowAppUtils.class})
public class ManageApplicationsTest {
@Mock
@@ -99,6 +105,7 @@ public class ManageApplicationsTest {
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mContext.setTheme(R.style.Theme_AppCompat);
mAppReset = new RoboMenuItem(R.id.reset_app_preferences);
mSortRecent = new RoboMenuItem(R.id.sort_order_recent_notification);
mSortFrequent = new RoboMenuItem(R.id.sort_order_frequent_notification);
@@ -109,9 +116,12 @@ public class ManageApplicationsTest {
mFragment = spy(new ManageApplications());
when(mFragment.getContext()).thenReturn(mContext);
when(mFragment.getActivity()).thenReturn(mActivity);
ReflectionHelpers.setField(mFragment, "mUserManager",
mContext.getSystemService(UserManager.class));
when(mActivity.getResources()).thenReturn(mResources);
when(mActivity.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mActivity.getPackageManager()).thenReturn(mPackageManager);
when(mActivity.getLayoutInflater()).thenReturn(LayoutInflater.from(mContext));
}
@Test
@@ -366,6 +376,7 @@ public class ManageApplicationsTest {
appEntry.extraInfo = mock(AppFilterItem.class);
appList.add(appEntry);
ReflectionHelpers.setField(adapter, "mEntries", appList);
ReflectionHelpers.setField(adapter, "mContext", mContext);
adapter.onBindViewHolder(holder, 0);
// no crash? yay!
@@ -387,6 +398,7 @@ public class ManageApplicationsTest {
appEntry.info = mock(ApplicationInfo.class);
appList.add(appEntry);
ReflectionHelpers.setField(adapter, "mEntries", appList);
ReflectionHelpers.setField(adapter, "mContext", mContext);
adapter.onBindViewHolder(holder, 0);
verify(holder).updateSwitch(any(), anyBoolean(), anyBoolean());
@@ -406,6 +418,7 @@ public class ManageApplicationsTest {
appEntry.info = mock(ApplicationInfo.class);
appList.add(appEntry);
ReflectionHelpers.setField(adapter, "mEntries", appList);
ReflectionHelpers.setField(adapter, "mContext", mContext);
adapter.onBindViewHolder(holder, 0);
verify(holder, never()).updateSwitch(any(), anyBoolean(), anyBoolean());
@@ -494,6 +507,116 @@ public class ManageApplicationsTest {
assertThat(mFragment.mRecyclerView.getPaddingTop()).isEqualTo(0);
}
@Test
public void onSaveInstanceState_noSearchView_shouldNotSetBundleValue() {
final Bundle bundle = new Bundle();
ReflectionHelpers.setField(mFragment, "mResetAppsHelper", mock(ResetAppsHelper.class));
ReflectionHelpers.setField(mFragment, "mFilter", mock(AppFilterItem.class));
ReflectionHelpers.setField(mFragment, "mApplications",
mock(ManageApplications.ApplicationsAdapter.class));
mFragment.onSaveInstanceState(bundle);
assertThat(bundle.containsKey(ManageApplications.EXTRA_EXPAND_SEARCH_VIEW)).isFalse();
}
@Test
public void onSaveInstanceState_searchViewSet_shouldSetBundleValue() {
final SearchView searchView = mock(SearchView.class);
final Bundle bundle = new Bundle();
ReflectionHelpers.setField(mFragment, "mResetAppsHelper", mock(ResetAppsHelper.class));
ReflectionHelpers.setField(mFragment, "mFilter", mock(AppFilterItem.class));
ReflectionHelpers.setField(mFragment, "mApplications",
mock(ManageApplications.ApplicationsAdapter.class));
ReflectionHelpers.setField(mFragment, "mSearchView", searchView);
when(searchView.isIconified()).thenReturn(true);
mFragment.onSaveInstanceState(bundle);
assertThat(bundle.containsKey(ManageApplications.EXTRA_EXPAND_SEARCH_VIEW)).isTrue();
assertThat(bundle.getBoolean(ManageApplications.EXTRA_EXPAND_SEARCH_VIEW)).isFalse();
}
@Test
public void createHeader_batteryListType_hasCorrectItems() {
ReflectionHelpers.setField(mFragment, "mListType", ManageApplications.LIST_TYPE_HIGH_POWER);
ReflectionHelpers.setField(mFragment, "mRootView",
LayoutInflater.from(mContext).inflate(R.layout.manage_applications_apps, null));
mFragment.mRecyclerView = new RecyclerView(mContext);
final ManageApplications.ApplicationsAdapter adapter =
spy(new ManageApplications.ApplicationsAdapter(mState, mFragment,
AppFilterRegistry.getInstance().get(FILTER_APPS_ALL), new Bundle()));
ReflectionHelpers.setField(mFragment, "mApplications", adapter);
mFragment.createHeader();
assertThat(mFragment.mFilterAdapter.getCount()).isEqualTo(2);
assertThat(mFragment.mFilterAdapter.getItem(0)).isEqualTo(
mContext.getString(R.string.high_power_filter_on));
assertThat(mFragment.mFilterAdapter.getItem(1)).isEqualTo(
mContext.getString(R.string.filter_all_apps));
}
@Test
public void createHeader_notificationListType_hasCorrectItems() {
ReflectionHelpers.setField(mFragment, "mListType", LIST_TYPE_NOTIFICATION);
ReflectionHelpers.setField(mFragment, "mRootView",
LayoutInflater.from(mContext).inflate(R.layout.manage_applications_apps, null));
mFragment.mRecyclerView = new RecyclerView(mContext);
final ManageApplications.ApplicationsAdapter adapter =
spy(new ManageApplications.ApplicationsAdapter(mState, mFragment,
AppFilterRegistry.getInstance().get(FILTER_APPS_ALL), new Bundle()));
ReflectionHelpers.setField(mFragment, "mApplications", adapter);
mFragment.createHeader();
assertThat(mFragment.mFilterAdapter.getCount()).isEqualTo(3);
assertThat(mFragment.mFilterAdapter.getItem(0)).isEqualTo(
mContext.getString(R.string.sort_order_recent_notification));
assertThat(mFragment.mFilterAdapter.getItem(1)).isEqualTo(
mContext.getString(R.string.sort_order_frequent_notification));
assertThat(mFragment.mFilterAdapter.getItem(2)).isEqualTo(
mContext.getString(R.string.filter_notif_blocked_apps));
}
@Test
public void onItemSelected_powerWhiteApps_returnCorrectValue() {
ReflectionHelpers.setField(mFragment, "mListType", ManageApplications.LIST_TYPE_HIGH_POWER);
ReflectionHelpers.setField(mFragment, "mRootView",
LayoutInflater.from(mContext).inflate(R.layout.manage_applications_apps, null));
mFragment.mRecyclerView = new RecyclerView(mContext);
final ManageApplications.ApplicationsAdapter adapter =
spy(new ManageApplications.ApplicationsAdapter(mState, mFragment,
AppFilterRegistry.getInstance().get(FILTER_APPS_ALL), new Bundle()));
ReflectionHelpers.setField(mFragment, "mApplications", adapter);
mFragment.createHeader();
mFragment.onItemSelected(null, null, 0, 0);
AppFilter filter = ReflectionHelpers.getField(adapter, "mCompositeFilter");
assertThat(filter.filterApp(createPowerWhiteListApp(false))).isFalse();
assertThat(filter.filterApp(createPowerWhiteListApp(true))).isTrue();
}
@Test
public void onItemSelected_allApps_returnCorrectValue() {
ReflectionHelpers.setField(mFragment, "mListType", ManageApplications.LIST_TYPE_HIGH_POWER);
ReflectionHelpers.setField(mFragment, "mRootView",
LayoutInflater.from(mContext).inflate(R.layout.manage_applications_apps, null));
mFragment.mRecyclerView = new RecyclerView(mContext);
final ManageApplications.ApplicationsAdapter adapter =
spy(new ManageApplications.ApplicationsAdapter(mState, mFragment,
AppFilterRegistry.getInstance().get(FILTER_APPS_ALL), new Bundle()));
ReflectionHelpers.setField(mFragment, "mApplications", adapter);
mFragment.createHeader();
mFragment.onItemSelected(null, null, 1, 0);
AppFilter filter = ReflectionHelpers.getField(adapter, "mCompositeFilter");
assertThat(filter.filterApp(createPowerWhiteListApp(false))).isTrue();
assertThat(filter.filterApp(createPowerWhiteListApp(true))).isTrue();
}
private void setUpOptionMenus() {
when(mMenu.findItem(anyInt())).thenAnswer(invocation -> {
final Object[] args = invocation.getArguments();
@@ -511,13 +634,21 @@ public class ManageApplicationsTest {
});
}
private ArrayList<ApplicationsState.AppEntry> getTestAppList(String[] appNames) {
final ArrayList<ApplicationsState.AppEntry> appList = new ArrayList<>();
private ArrayList<AppEntry> getTestAppList(String[] appNames) {
final ArrayList<AppEntry> appList = new ArrayList<>();
for (String name : appNames) {
final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
final AppEntry appEntry = mock(AppEntry.class);
appEntry.label = name;
appList.add(appEntry);
}
return appList;
}
private AppEntry createPowerWhiteListApp(boolean isPowerWhiteListed) {
final ApplicationInfo info = new ApplicationInfo();
info.sourceDir = "abc";
final AppEntry entry = new AppEntry(mContext, info, 0);
entry.extraInfo = isPowerWhiteListed ? Boolean.TRUE : Boolean.FALSE;
return entry;
}
}

View File

@@ -61,7 +61,7 @@ public class MusicViewHolderControllerTest {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
final String fsUuid = new VolumeInfo("id", 0, null, "id").fsUuid;
mController = new MusicViewHolderController(mContext, mSource, fsUuid, new UserHandle(0));
mController = new MusicViewHolderController(mContext, mSource, fsUuid, UserHandle.of(-1));
View view = ApplicationViewHolder.newView(new FrameLayout(mContext));
mHolder = new ApplicationViewHolder(view);

View File

@@ -60,7 +60,7 @@ public class PhotosViewHolderControllerTest {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
final String fsUuid = new VolumeInfo("id", 0, null, "id").fsUuid;
mController = new PhotosViewHolderController(mContext, mSource, fsUuid, new UserHandle(0));
mController = new PhotosViewHolderController(mContext, mSource, fsUuid, UserHandle.of(-1));
final View view = ApplicationViewHolder.newView(new FrameLayout(mContext));
mHolder = new ApplicationViewHolder(view);

View File

@@ -76,4 +76,14 @@ public class DefaultPaymentSettingsPreferenceControllerTest {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void getAvailabilityStatus_NfcIsDisabled_shouldReturnDisabled() {
when(mPackageManager.hasSystemFeature(anyString())).thenReturn(true);
when(mUserManager.isAdminUser()).thenReturn(true);
when(mNfcAdapter.isEnabled()).thenReturn(false);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
DefaultPaymentSettingsPreferenceController.DISABLED_DEPENDENT_SETTING);
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (C) 2020 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.settings.applications.specialaccess;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
import android.content.Context;
import android.nfc.NfcAdapter;
import androidx.preference.Preference;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
@Ignore
public class PaymentSettingsEnablerTest {
private Context mContext;
private Preference mPreference;
private PaymentSettingsEnabler mEnabler;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mPreference = new Preference(mContext);
mEnabler = spy(new PaymentSettingsEnabler(mContext, mPreference));
}
@Test
public void handleNfcStateChanged_stateOff_shouldChangeSummaryAndDisablePreference() {
mEnabler.handleNfcStateChanged(NfcAdapter.STATE_OFF);
assertThat(mPreference.getSummary().toString()).contains(
mContext.getString(R.string.nfc_and_payment_settings_payment_off_nfc_off_summary));
assertThat(mPreference.isEnabled()).isFalse();
}
@Test
public void handleNfcStateChanged_stateOn_shouldClearSummaryAndEnablePreference() {
mEnabler.handleNfcStateChanged(NfcAdapter.STATE_ON);
assertThat(mPreference.getSummary()).isNull();
assertThat(mPreference.isEnabled()).isTrue();
}
}

View File

@@ -33,37 +33,26 @@ import android.os.UserHandle;
import androidx.lifecycle.LifecycleOwner;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.FooterPreferenceMixinCompat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class DeviceAdminListPreferenceControllerTest {
@Mock
private FooterPreferenceMixinCompat mFooterPreferenceMixin;
private Context mContext;
private DeviceAdminListPreferenceController mController;
private LifecycleOwner mLifecycleOwner;
private Lifecycle mLifecycle;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
final LifecycleOwner lifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(lifecycleOwner);
mController = spy(new DeviceAdminListPreferenceController(mContext, "test_key")
.setFooterPreferenceMixin(mFooterPreferenceMixin));
mLifecycle.addObserver(mController);
mLifecycle.addObserver(new DeviceAdminListPreferenceController(mContext, "test_key"));
}
@Test

View File

@@ -0,0 +1,67 @@
/*
* Copyright (C) 2020 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.settings.applications.specialaccess.interactacrossprofiles;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.Shadows.shadowOf;
import android.content.Context;
import android.content.pm.UserInfo;
import android.os.UserManager;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.core.BasePreferenceController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class InteractAcrossProfilesControllerTest {
private static final int PERSONAL_PROFILE_ID = 0;
private static final int WORK_PROFILE_ID = 10;
private final Context mContext = ApplicationProvider.getApplicationContext();
private final UserManager mUserManager = mContext.getSystemService(UserManager.class);
private final InteractAcrossProfilesController mController =
new InteractAcrossProfilesController(mContext, "test_key");
@Test
public void getAvailabilityStatus_multipleProfiles_returnsAvailable() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mUserManager).addProfile(
PERSONAL_PROFILE_ID,
WORK_PROFILE_ID,
"work-profile"/* profileName */,
UserInfo.FLAG_MANAGED_PROFILE);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_oneProfile_returnsDisabled() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
}
}

View File

@@ -0,0 +1,124 @@
/*
* Copyright (C) 2020 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.settings.applications.specialaccess.interactacrossprofiles;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.Shadows.shadowOf;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.CrossProfileApps;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.content.pm.UserInfo;
import android.os.UserManager;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class InteractAcrossProfilesDetailsTest {
private static final int PERSONAL_PROFILE_ID = 0;
private static final int WORK_PROFILE_ID = 10;
private static final int PACKAGE_UID = 0;
private static final String CROSS_PROFILE_PACKAGE_NAME = "crossProfilePackage";
public static final String INTERACT_ACROSS_PROFILES_PERMISSION =
"android.permission.INTERACT_ACROSS_PROFILES";
private final Context mContext = ApplicationProvider.getApplicationContext();
private final AppOpsManager mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
private final PackageManager mPackageManager = mContext.getPackageManager();
private final UserManager mUserManager = mContext.getSystemService(UserManager.class);
private final CrossProfileApps mCrossProfileApps = mContext.getSystemService(
CrossProfileApps.class);
@Test
public void getPreferenceSummary_appOpAllowed_returnsAllowed() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mUserManager).addProfile(
PERSONAL_PROFILE_ID, WORK_PROFILE_ID,
"work-profile"/* profileName */, UserInfo.FLAG_MANAGED_PROFILE);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, ImmutableList.of(CROSS_PROFILE_PACKAGE_NAME));
shadowOf(mPackageManager).setInstalledPackagesForUserId(
WORK_PROFILE_ID, ImmutableList.of(CROSS_PROFILE_PACKAGE_NAME));
shadowOf(mCrossProfileApps).addCrossProfilePackage(
CROSS_PROFILE_PACKAGE_NAME);
String appOp = AppOpsManager.permissionToOp(INTERACT_ACROSS_PROFILES_PERMISSION);
shadowOf(mAppOpsManager).setMode(
appOp, PACKAGE_UID, CROSS_PROFILE_PACKAGE_NAME, AppOpsManager.MODE_ALLOWED);
shadowOf(mPackageManager).addPermissionInfo(createCrossProfilesPermissionInfo());
assertThat(InteractAcrossProfilesDetails.getPreferenceSummary(
mContext, CROSS_PROFILE_PACKAGE_NAME))
.isEqualTo(mContext.getString(R.string.interact_across_profiles_summary_allowed));
}
@Test
public void getPreferenceSummary_appOpNotAllowed_returnsNotAllowed() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mUserManager).addProfile(
PERSONAL_PROFILE_ID, WORK_PROFILE_ID,
"work-profile"/* profileName */, UserInfo.FLAG_MANAGED_PROFILE);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, ImmutableList.of(CROSS_PROFILE_PACKAGE_NAME));
shadowOf(mPackageManager).setInstalledPackagesForUserId(
WORK_PROFILE_ID, ImmutableList.of(CROSS_PROFILE_PACKAGE_NAME));
shadowOf(mCrossProfileApps).addCrossProfilePackage(
CROSS_PROFILE_PACKAGE_NAME);
String appOp = AppOpsManager.permissionToOp(INTERACT_ACROSS_PROFILES_PERMISSION);
shadowOf(mAppOpsManager).setMode(
appOp, PACKAGE_UID, CROSS_PROFILE_PACKAGE_NAME, AppOpsManager.MODE_IGNORED);
shadowOf(mPackageManager).addPermissionInfo(createCrossProfilesPermissionInfo());
assertThat(InteractAcrossProfilesDetails.getPreferenceSummary(
mContext, CROSS_PROFILE_PACKAGE_NAME))
.isEqualTo(mContext.getString(
R.string.interact_across_profiles_summary_not_allowed));
}
@Test
public void getPreferenceSummary_noWorkProfile_returnsNotAllowed() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, ImmutableList.of(CROSS_PROFILE_PACKAGE_NAME));
assertThat(InteractAcrossProfilesDetails.getPreferenceSummary(
mContext, CROSS_PROFILE_PACKAGE_NAME))
.isEqualTo(mContext.getString(
R.string.interact_across_profiles_summary_not_allowed));
}
private PermissionInfo createCrossProfilesPermissionInfo() {
PermissionInfo permissionInfo = new PermissionInfo();
permissionInfo.name = INTERACT_ACROSS_PROFILES_PERMISSION;
permissionInfo.protectionLevel = PermissionInfo.PROTECTION_FLAG_APPOP;
return permissionInfo;
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) 2020 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.settings.applications.specialaccess.interactacrossprofiles;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.Shadows.shadowOf;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.core.BasePreferenceController;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class InteractAcrossProfilesPreferenceControllerTest {
private static final String CROSS_PROFILE_PACKAGE_NAME = "crossProfilePackage";
private static final String NOT_CROSS_PROFILE_PACKAGE_NAME = "notCrossProfilePackage";
public static final String INTERACT_ACROSS_PROFILES_PERMISSION =
"android.permission.INTERACT_ACROSS_PROFILES";
private static final int PROFILE_ID = 0;
private final Context mContext = ApplicationProvider.getApplicationContext();
private final PackageManager mPackageManager = mContext.getPackageManager();
private final InteractAcrossProfilesDetailsPreferenceController mController =
new InteractAcrossProfilesDetailsPreferenceController(mContext, "test_key");
@Test
public void getAvailabilityStatus_requestedCrossProfilePermission_returnsAvailable() {
mController.setPackageName(CROSS_PROFILE_PACKAGE_NAME);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PROFILE_ID, ImmutableList.of(CROSS_PROFILE_PACKAGE_NAME));
PackageInfo packageInfo = shadowOf(mPackageManager).getInternalMutablePackageInfo(
CROSS_PROFILE_PACKAGE_NAME);
packageInfo.requestedPermissions = new String[]{
INTERACT_ACROSS_PROFILES_PERMISSION};
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_notRequestedCrossProfilePermission_returnsDisabled() {
mController.setPackageName(NOT_CROSS_PROFILE_PACKAGE_NAME);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PROFILE_ID, ImmutableList.of(NOT_CROSS_PROFILE_PACKAGE_NAME));
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
}
@Test
public void getDetailFragmentClass_shouldReturnInteractAcrossProfilesDetails() {
assertThat(mController.getDetailFragmentClass())
.isEqualTo(InteractAcrossProfilesDetails.class);
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright (C) 2020 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.settings.applications.specialaccess.interactacrossprofiles;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertTrue;
import static org.robolectric.Shadows.shadowOf;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.CrossProfileApps;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.content.pm.UserInfo;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.Pair;
import androidx.test.core.app.ApplicationProvider;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowProcess;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class InteractAcrossProfilesSettingsTest {
private static final int PERSONAL_PROFILE_ID = 0;
private static final int WORK_PROFILE_ID = 10;
private static final int WORK_UID = UserHandle.PER_USER_RANGE * WORK_PROFILE_ID;
private static final int PACKAGE_UID = 0;
private static final String PERSONAL_CROSS_PROFILE_PACKAGE = "personalCrossProfilePackage";
private static final String PERSONAL_NON_CROSS_PROFILE_PACKAGE =
"personalNonCrossProfilePackage";
private static final String WORK_CROSS_PROFILE_PACKAGE = "workCrossProfilePackage";
private static final String WORK_NON_CROSS_PROFILE_PACKAGE =
"workNonCrossProfilePackage";
private static final List<String> PERSONAL_PROFILE_INSTALLED_PACKAGES =
ImmutableList.of(PERSONAL_CROSS_PROFILE_PACKAGE, PERSONAL_NON_CROSS_PROFILE_PACKAGE);
private static final List<String> WORK_PROFILE_INSTALLED_PACKAGES =
ImmutableList.of(WORK_CROSS_PROFILE_PACKAGE, WORK_NON_CROSS_PROFILE_PACKAGE);
public static final String INTERACT_ACROSS_PROFILES_PERMISSION =
"android.permission.INTERACT_ACROSS_PROFILES";
private final Context mContext = ApplicationProvider.getApplicationContext();
private final PackageManager mPackageManager = mContext.getPackageManager();
private final UserManager mUserManager = mContext.getSystemService(UserManager.class);
private final CrossProfileApps mCrossProfileApps =
mContext.getSystemService(CrossProfileApps.class);
private final AppOpsManager mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
@Test
public void collectConfigurableApps_fromPersonal_returnsCombinedPackages() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mUserManager).addProfile(
PERSONAL_PROFILE_ID, WORK_PROFILE_ID,
"work-profile"/* profileName */, UserInfo.FLAG_MANAGED_PROFILE);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, PERSONAL_PROFILE_INSTALLED_PACKAGES);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
WORK_PROFILE_ID, WORK_PROFILE_INSTALLED_PACKAGES);
installCrossProfilePackage(PERSONAL_PROFILE_ID, PERSONAL_CROSS_PROFILE_PACKAGE);
installCrossProfilePackage(WORK_PROFILE_ID, WORK_CROSS_PROFILE_PACKAGE);
List<Pair<ApplicationInfo, UserHandle>> apps =
InteractAcrossProfilesSettings.collectConfigurableApps(
mPackageManager, mUserManager, mCrossProfileApps);
assertThat(apps.size()).isEqualTo(2);
assertTrue(apps.stream().anyMatch(
app -> app.first.packageName.equals(PERSONAL_CROSS_PROFILE_PACKAGE)));
assertTrue(apps.stream().anyMatch(
app -> app.first.packageName.equals(WORK_CROSS_PROFILE_PACKAGE)));
}
@Test
public void collectConfigurableApps_fromWork_returnsCombinedPackages() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mUserManager).addProfile(
PERSONAL_PROFILE_ID, WORK_PROFILE_ID,
"work-profile"/* profileName */, UserInfo.FLAG_MANAGED_PROFILE);
ShadowProcess.setUid(WORK_UID);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, PERSONAL_PROFILE_INSTALLED_PACKAGES);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
WORK_PROFILE_ID, WORK_PROFILE_INSTALLED_PACKAGES);
installCrossProfilePackage(PERSONAL_PROFILE_ID, PERSONAL_CROSS_PROFILE_PACKAGE);
installCrossProfilePackage(WORK_PROFILE_ID, WORK_CROSS_PROFILE_PACKAGE);
List<Pair<ApplicationInfo, UserHandle>> apps =
InteractAcrossProfilesSettings.collectConfigurableApps(
mPackageManager, mUserManager, mCrossProfileApps);
assertThat(apps.size()).isEqualTo(2);
assertTrue(apps.stream().anyMatch(
app -> app.first.packageName.equals(PERSONAL_CROSS_PROFILE_PACKAGE)));
assertTrue(apps.stream().anyMatch(
app -> app.first.packageName.equals(WORK_CROSS_PROFILE_PACKAGE)));
}
@Test
public void collectConfigurableApps_onlyOneProfile_returnsEmpty() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, PERSONAL_PROFILE_INSTALLED_PACKAGES);
installCrossProfilePackage(PERSONAL_PROFILE_ID, PERSONAL_CROSS_PROFILE_PACKAGE);
List<Pair<ApplicationInfo, UserHandle>> apps =
InteractAcrossProfilesSettings.collectConfigurableApps(
mPackageManager, mUserManager, mCrossProfileApps);
assertThat(apps).isEmpty();
}
@Test
public void getNumberOfEnabledApps_returnsNumberOfEnabledApps() {
shadowOf(mUserManager).addUser(
PERSONAL_PROFILE_ID, "personal-profile"/* name */, 0/* flags */);
shadowOf(mUserManager).addProfile(
PERSONAL_PROFILE_ID, WORK_PROFILE_ID,
"work-profile"/* profileName */, UserInfo.FLAG_MANAGED_PROFILE);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
PERSONAL_PROFILE_ID, PERSONAL_PROFILE_INSTALLED_PACKAGES);
shadowOf(mPackageManager).setInstalledPackagesForUserId(
WORK_PROFILE_ID, WORK_PROFILE_INSTALLED_PACKAGES);
installCrossProfilePackage(PERSONAL_PROFILE_ID, PERSONAL_CROSS_PROFILE_PACKAGE);
installCrossProfilePackage(WORK_PROFILE_ID, WORK_CROSS_PROFILE_PACKAGE);
shadowOf(mCrossProfileApps).addCrossProfilePackage(PERSONAL_CROSS_PROFILE_PACKAGE);
String appOp = AppOpsManager.permissionToOp(INTERACT_ACROSS_PROFILES_PERMISSION);
shadowOf(mAppOpsManager).setMode(
appOp, PACKAGE_UID, PERSONAL_CROSS_PROFILE_PACKAGE, AppOpsManager.MODE_ALLOWED);
shadowOf(mAppOpsManager).setMode(
appOp, PACKAGE_UID, PERSONAL_NON_CROSS_PROFILE_PACKAGE, AppOpsManager.MODE_IGNORED);
shadowOf(mPackageManager).addPermissionInfo(createCrossProfilesPermissionInfo());
int numOfApps = InteractAcrossProfilesSettings.getNumberOfEnabledApps(
mContext, mPackageManager, mUserManager, mCrossProfileApps);
assertThat(numOfApps).isEqualTo(1);
}
private void installCrossProfilePackage(int profileId, String packageName) {
PackageInfo personalPackageInfo = shadowOf(mPackageManager).getInternalMutablePackageInfo(
packageName);
personalPackageInfo.requestedPermissions = new String[]{
INTERACT_ACROSS_PROFILES_PERMISSION};
}
private PermissionInfo createCrossProfilesPermissionInfo() {
PermissionInfo permissionInfo = new PermissionInfo();
permissionInfo.name = INTERACT_ACROSS_PROFILES_PERMISSION;
permissionInfo.protectionLevel = PermissionInfo.PROTECTION_FLAG_APPOP;
return permissionInfo;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2019 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.
@@ -11,13 +11,13 @@
* 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
* limitations under the License.
*/
package com.android.settings.notification;
package com.android.settings.applications.specialaccess.notificationaccess;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import android.content.Context;
@@ -30,30 +30,37 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class NotificationAccessSettingsTest {
public class NotificationAccessDetailsTest {
private Context mContext;
private FakeFeatureFactory mFeatureFactory;
private NotificationAccessSettings mFragment;
private NotificationAccessDetails mFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mFeatureFactory = FakeFeatureFactory.setupForTest();
mFragment = new NotificationAccessSettings();
mFragment = spy(new NotificationAccessDetails());
mContext = RuntimeEnvironment.application;
doReturn(mContext).when(mFragment).getContext();
}
@Test
public void logSpecialPermissionChange() {
mFragment.logSpecialPermissionChange(true, "app");
verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_NOTIVIEW_ALLOW),
eq("app"));
verify(mFeatureFactory.metricsFeatureProvider).action(
mContext,
MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_NOTIVIEW_ALLOW,
"app");
mFragment.logSpecialPermissionChange(false, "app");
verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_NOTIVIEW_DENY),
eq("app"));
verify(mFeatureFactory.metricsFeatureProvider).action(
mContext,
MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_NOTIVIEW_DENY,
"app");
}
}

View File

@@ -24,6 +24,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.preference.Preference;
@@ -46,6 +47,8 @@ public class PictureInPictureDetailPreferenceControllerTest {
private AppInfoDashboardFragment mFragment;
@Mock
private Preference mPreference;
@Mock
private PackageManager mManager;
private Context mContext;
private PictureInPictureDetailPreferenceController mController;
@@ -61,6 +64,8 @@ public class PictureInPictureDetailPreferenceControllerTest {
final String key = mController.getPreferenceKey();
when(mPreference.getKey()).thenReturn(key);
when(mContext.getPackageManager()).thenReturn(mManager);
when(mManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)).thenReturn(true);
}
@Test
@@ -79,6 +84,15 @@ public class PictureInPictureDetailPreferenceControllerTest {
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_noPictureInPictureFeature_shouldReturnUnSupported() {
when(mManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)).thenReturn(
false);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getDetailFragmentClass_shouldReturnPictureInPictureDetails() {
assertThat(mController.getDetailFragmentClass()).isEqualTo(PictureInPictureDetails.class);

View File

@@ -19,9 +19,9 @@ package com.android.settings.applications.specialaccess.premiumsms;
import static org.mockito.Mockito.verify;
import android.app.settings.SettingsEnums;
import android.telephony.SmsManager;
import com.android.internal.logging.nano.MetricsProto;
import com.android.internal.telephony.SmsUsageMonitor;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
@@ -47,31 +47,31 @@ public class PremiumSmsAccessTest {
@Test
public void logSpecialPermissionChange() {
mFragment.logSpecialPermissionChange(SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER,
mFragment.logSpecialPermissionChange(SmsManager.PREMIUM_SMS_CONSENT_ASK_USER,
"app");
verify(mFeatureFactory.metricsFeatureProvider).action(
SettingsEnums.PAGE_UNKNOWN,
MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_PREMIUM_SMS_ASK,
mFragment.getMetricsCategory(),
"app",
SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER);
SmsManager.PREMIUM_SMS_CONSENT_ASK_USER);
mFragment.logSpecialPermissionChange(SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW,
mFragment.logSpecialPermissionChange(SmsManager.PREMIUM_SMS_CONSENT_NEVER_ALLOW,
"app");
verify(mFeatureFactory.metricsFeatureProvider).action(
SettingsEnums.PAGE_UNKNOWN,
MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_PREMIUM_SMS_DENY,
mFragment.getMetricsCategory(),
"app",
SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW);
SmsManager.PREMIUM_SMS_CONSENT_NEVER_ALLOW);
mFragment.logSpecialPermissionChange(SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW,
mFragment.logSpecialPermissionChange(SmsManager.PREMIUM_SMS_CONSENT_ALWAYS_ALLOW,
"app");
verify(mFeatureFactory.metricsFeatureProvider).action(
SettingsEnums.PAGE_UNKNOWN,
MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_PREMIUM_SMS_ALWAYS_ALLOW,
mFragment.getMetricsCategory(),
"app",
SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW);
SmsManager.PREMIUM_SMS_CONSENT_ALWAYS_ALLOW);
}
}

View File

@@ -16,7 +16,7 @@
package com.android.settings.applications.specialaccess.premiumsms;
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.google.common.truth.Truth.assertThat;
@@ -47,7 +47,7 @@ public class PremiumSmsControllerTest {
@Test
public void getAvailability_byDefault_shouldBeShown() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test

View File

@@ -16,7 +16,7 @@
package com.android.settings.applications.specialaccess.vrlistener;
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
@@ -48,7 +48,7 @@ public class EnabledVrListenersControllerTest {
@Test
public void getAvailability_byDefault_unsearchable() {
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2019 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.settings.biometrics.face;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class FaceSettingsAttentionPreferenceControllerTest {
private Context mContext;
private FaceSettingsAttentionPreferenceController mController;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController = new FaceSettingsAttentionPreferenceController(mContext);
}
@Test
public void isSliceable_returnFalse() {
assertThat(mController.isSliceable()).isFalse();
}
}

View File

@@ -19,14 +19,20 @@ package com.android.settings.biometrics.face;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.face.FaceManager;
import android.os.UserManager;
import android.provider.Settings;
import androidx.preference.SwitchPreference;
import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
import com.android.settingslib.RestrictedSwitchPreference;
import org.junit.Before;
import org.junit.Test;
@@ -42,7 +48,10 @@ public class FaceSettingsLockscreenBypassPreferenceControllerTest {
@Mock
private FaceManager mFaceManager;
private SwitchPreference mPreference;
@Mock
private PackageManager mPackageManager;
@Mock
private RestrictedSwitchPreference mPreference;
@Mock
private UserManager mUserManager;
@@ -52,12 +61,15 @@ public class FaceSettingsLockscreenBypassPreferenceControllerTest {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mPreference = new SwitchPreference(mContext);
mContext = spy(RuntimeEnvironment.application);
when(mContext.getSystemService(eq(Context.FACE_SERVICE))).thenReturn(mFaceManager);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
mController = new FaceSettingsLockscreenBypassPreferenceController(mContext, "test_key");
mController = spy(new FaceSettingsLockscreenBypassPreferenceController(mContext,
"test_key"));
ReflectionHelpers.setField(mController, "mFaceManager", mFaceManager);
ReflectionHelpers.setField(mController, "mUserManager", mUserManager);
}
@Test
@@ -81,9 +93,21 @@ public class FaceSettingsLockscreenBypassPreferenceControllerTest {
boolean state = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD, defaultValue ? 1 : 0) != 0;
assertThat(mController.isChecked()).isFalse();
assertThat(mController.onPreferenceChange(mPreference, !state)).isTrue();
boolean newState = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.FACE_UNLOCK_DISMISSES_KEYGUARD, 0) != 0;
assertThat(newState).isEqualTo(!state);
}
@Test
public void preferenceDisabled_byAdmin() {
when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE)).thenReturn(true);
when(mFaceManager.isHardwareDetected()).thenReturn(true);
EnforcedAdmin admin = new EnforcedAdmin();
doReturn(admin).when(mController).getRestrictingAdmin();
mController.updateState(mPreference);
verify(mPreference).setDisabledByAdmin(admin);
}
}

View File

@@ -113,7 +113,6 @@ public class FaceStatusPreferenceControllerTest {
assertThat(mPreference.getSummary()).isEqualTo(
mContext.getString(R.string.security_settings_face_preference_summary_none));
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getOnPreferenceClickListener()).isNotNull();
}
@Test
@@ -129,6 +128,5 @@ public class FaceStatusPreferenceControllerTest {
assertThat(mPreference.getSummary()).isEqualTo(mContext.getResources()
.getString(R.string.security_settings_face_preference_summary));
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getOnPreferenceClickListener()).isNotNull();
}
}

View File

@@ -23,12 +23,12 @@ import static org.mockito.Mockito.verify;
import android.app.Dialog;
import android.hardware.fingerprint.Fingerprint;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.biometrics.fingerprint.FingerprintSettings.FingerprintSettingsFragment;
import com.android.settings.biometrics.fingerprint.FingerprintSettings
.FingerprintSettingsFragment.DeleteFingerprintDialog;
import com.android.settings.testutils.shadow.ShadowFragment;
import org.junit.Before;
import org.junit.Test;
@@ -37,10 +37,12 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadows.androidx.fragment.FragmentController;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowFragment.class)
@Config(shadows = DeleteFingerprintDialogTest.ShadowFragment.class)
public class DeleteFingerprintDialogTest {
@Mock
@@ -75,4 +77,19 @@ public class DeleteFingerprintDialogTest {
verify(mTarget, never()).deleteFingerPrint(mFingerprint);
}
@Implements(Fragment.class)
public static class ShadowFragment {
private Fragment mTargetFragment;
@Implementation
protected void setTargetFragment(Fragment fragment, int requestCode) {
mTargetFragment = fragment;
}
@Implementation
protected Fragment getTargetFragment() {
return mTargetFragment;
}
}
}

View File

@@ -115,7 +115,6 @@ public class FingerprintStatusPreferenceControllerTest {
assertThat(mPreference.getSummary()).isEqualTo(
mContext.getString(R.string.security_settings_fingerprint_preference_summary_none));
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getOnPreferenceClickListener()).isNotNull();
}
@Test
@@ -130,6 +129,5 @@ public class FingerprintStatusPreferenceControllerTest {
assertThat(mPreference.getSummary()).isEqualTo(mContext.getResources().getQuantityString(
R.plurals.security_settings_fingerprint_preference_summary, 1, 1));
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getOnPreferenceClickListener()).isNotNull();
}
}

View File

@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
@@ -58,6 +59,8 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
private static final int BATTERY_LEVEL_MAIN = 30;
private static final int BATTERY_LEVEL_LEFT = 25;
private static final int BATTERY_LEVEL_RIGHT = 45;
private static final int LOW_BATTERY_LEVEL = 15;
private static final int CASE_LOW_BATTERY_LEVEL = 19;
private static final String ICON_URI = "content://test.provider/icon.png";
private static final String MAC_ADDRESS = "04:52:C7:0B:D8:3C";
@@ -115,6 +118,7 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_CASE_BATTERY)).thenReturn(
String.valueOf(BATTERY_LEVEL_MAIN).getBytes());
when(mCachedDevice.isConnected()).thenReturn(true);
mController.refresh();
@@ -143,6 +147,37 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
assertThat(layout.findViewById(R.id.header_icon).getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void refresh_withLowBatteryAndUncharged_showAlertIcon() {
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_LEFT_BATTERY)).thenReturn(
String.valueOf(LOW_BATTERY_LEVEL).getBytes());
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_RIGHT_BATTERY)).thenReturn(
String.valueOf(LOW_BATTERY_LEVEL).getBytes());
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_CASE_BATTERY)).thenReturn(
String.valueOf(CASE_LOW_BATTERY_LEVEL).getBytes());
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING)).thenReturn(
String.valueOf(false).getBytes());
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_RIGHT_CHARGING)).thenReturn(
String.valueOf(true).getBytes());
when(mBluetoothDevice.getMetadata(
BluetoothDevice.METADATA_UNTETHERED_CASE_CHARGING)).thenReturn(
String.valueOf(false).getBytes());
when(mCachedDevice.isConnected()).thenReturn(true);
mController.refresh();
assertBatteryIcon(mLayoutPreference.findViewById(R.id.layout_left),
R.drawable.ic_battery_alert_24dp);
assertBatteryIcon(mLayoutPreference.findViewById(R.id.layout_right), /* resId= */-1);
assertBatteryIcon(mLayoutPreference.findViewById(R.id.layout_middle),
R.drawable.ic_battery_alert_24dp);
}
@Test
public void getAvailabilityStatus_untetheredHeadsetWithConfigOn_returnAvailable() {
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SETTINGS_UI,
@@ -210,11 +245,8 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
}
@Test
public void onStop_isAvailable_unregisterCallback() {
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SETTINGS_UI,
SettingsUIDeviceConfig.BT_ADVANCED_HEADER_ENABLED, "true", true);
when(mBluetoothDevice.getMetadata(BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET))
.thenReturn("true".getBytes());
public void onStop_isRegisterCallback_unregisterCallback() {
mController.mIsRegisterCallback = true;
mController.onStop();
@@ -234,9 +266,8 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
}
@Test
public void onStop_notAvailable_unregisterCallback() {
when(mBluetoothDevice.getMetadata(BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET))
.thenReturn("false".getBytes());
public void onStop_notRegisterCallback_unregisterCallback() {
mController.mIsRegisterCallback = false;
mController.onStop();
@@ -245,11 +276,7 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
}
@Test
public void onDestroy_isAvailable_recycleBitmap() {
DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SETTINGS_UI,
SettingsUIDeviceConfig.BT_ADVANCED_HEADER_ENABLED, "true", true);
when(mBluetoothDevice.getMetadata(BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET))
.thenReturn("true".getBytes());
public void onDestroy_recycleBitmap() {
mController.mIconCache.put(ICON_URI, mBitmap);
mController.onDestroy();
@@ -264,4 +291,10 @@ public class AdvancedBluetoothDetailsHeaderControllerTest {
com.android.settings.Utils.formatPercentage(batteryLevel));
}
private void assertBatteryIcon(LinearLayout linearLayout, int resId) {
final ImageView imageView = linearLayout.findViewById(R.id.bt_battery_icon);
assertThat(shadowOf(imageView.getDrawable()).getCreatedFromResId())
.isEqualTo(resId);
}
}

View File

@@ -91,7 +91,8 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
mBluetoothDeviceUpdater = spy(new AvailableMediaBluetoothDeviceUpdater(mContext,
mDashboardFragment, mDevicePreferenceCallback));
mBluetoothDeviceUpdater.setPrefContext(mContext);
mPreference = new BluetoothDevicePreference(mContext, mCachedBluetoothDevice, false);
mPreference = new BluetoothDevicePreference(mContext, mCachedBluetoothDevice, false,
BluetoothDevicePreference.SortType.TYPE_DEFAULT);
doNothing().when(mBluetoothDeviceUpdater).addPreference(any());
doNothing().when(mBluetoothDeviceUpdater).removePreference(any());
}

View File

@@ -15,6 +15,8 @@
*/
package com.android.settings.bluetooth;
import static com.android.settings.bluetooth.BluetoothDetailsMacAddressController.KEY_DEVICE_DETAILS_FOOTER;
import static com.google.common.truth.Truth.assertThat;
import com.android.settingslib.widget.FooterPreference;
@@ -25,22 +27,24 @@ import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class BluetoothDetailsMacAddressControllerTest extends BluetoothDetailsControllerTestBase {
private BluetoothDetailsMacAddressController mController;
private BluetoothDetailsMacAddressController mController;
@Override
public void setUp() {
super.setUp();
mController =
new BluetoothDetailsMacAddressController(mContext, mFragment, mCachedDevice,
mLifecycle);
setupDevice(mDeviceConfig);
mScreen.addPreference(new FooterPreference.Builder(mContext).setKey(
KEY_DEVICE_DETAILS_FOOTER).setTitle(KEY_DEVICE_DETAILS_FOOTER).build());
}
@Override
public void setUp() {
super.setUp();
mController =
new BluetoothDetailsMacAddressController(mContext, mFragment, mCachedDevice, mLifecycle);
setupDevice(mDeviceConfig);
}
@Test
public void macAddress() {
showScreen(mController);
FooterPreference footer =
(FooterPreference) mScreen.findPreference(mController.getPreferenceKey());
assertThat(footer.getTitle().toString()).endsWith(mDeviceConfig.getAddress());
}
@Test
public void macAddress() {
showScreen(mController);
FooterPreference footer =
(FooterPreference) mScreen.findPreference(mController.getPreferenceKey());
assertThat(footer.getTitle().toString()).endsWith(mDeviceConfig.getAddress());
}
}

View File

@@ -29,6 +29,7 @@ import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.SwitchPreference;
@@ -84,6 +85,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
mController = new BluetoothDetailsProfilesController(mContext, mFragment, mLocalManager,
mCachedDevice, mLifecycle);
mProfiles.setKey(mController.getPreferenceKey());
mController.mProfilesContainer = mProfiles;
mScreen.addPreference(mProfiles);
}
@@ -193,11 +195,14 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
private List<SwitchPreference> getProfileSwitches(boolean expectOnlyMConnectable) {
if (expectOnlyMConnectable) {
assertThat(mConnectableProfiles).isNotEmpty();
assertThat(mProfiles.getPreferenceCount()).isEqualTo(mConnectableProfiles.size());
assertThat(mProfiles.getPreferenceCount() - 1).isEqualTo(mConnectableProfiles.size());
}
List<SwitchPreference> result = new ArrayList<>();
for (int i = 0; i < mProfiles.getPreferenceCount(); i++) {
result.add((SwitchPreference)mProfiles.getPreference(i));
final Preference preference = mProfiles.getPreference(i);
if (preference instanceof SwitchPreference) {
result.add((SwitchPreference) preference);
}
}
return result;
}
@@ -236,7 +241,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
mController.onDeviceAttributesChanged();
// There should have been no new switches added.
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(3);
// Make sure both switches got disabled.
assertThat(switches.get(0).isEnabled()).isFalse();
@@ -258,7 +263,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
assertThat(mConnectableProfiles.get(0).isEnabled(mDevice)).isFalse();
// Make sure no new preferences were added.
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(3);
// Clicking the pref again should make the profile once again preferred.
pref.performClick();
@@ -266,7 +271,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
assertThat(mConnectableProfiles.get(0).isEnabled(mDevice)).isTrue();
// Make sure we still haven't gotten any new preferences added.
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(3);
}
@Test
@@ -295,7 +300,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
assertThat(pref.isChecked()).isTrue();
pref.performClick();
assertThat(mProfiles.getPreferenceCount()).isEqualTo(1);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mDevice.getPhonebookAccessPermission())
.isEqualTo(BluetoothDevice.ACCESS_REJECTED);
}
@@ -318,7 +323,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
assertThat(pref.isChecked()).isFalse();
pref.performClick();
assertThat(mProfiles.getPreferenceCount()).isEqualTo(1);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mDevice.getPhonebookAccessPermission())
.isEqualTo(BluetoothDevice.ACCESS_ALLOWED);
}
@@ -340,7 +345,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
assertThat(pref.isChecked()).isFalse();
pref.performClick();
assertThat(mProfiles.getPreferenceCount()).isEqualTo(1);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mDevice.getMessageAccessPermission()).isEqualTo(BluetoothDevice.ACCESS_ALLOWED);
}
@@ -386,7 +391,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
setupDevice(makeDefaultDeviceConfig());
addMockA2dpProfile(true, false, false);
showScreen(mController);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(1);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
SwitchPreference pref = (SwitchPreference) mProfiles.getPreference(0);
assertThat(pref.getKey())
.isNotEqualTo(BluetoothDetailsProfilesController.HIGH_QUALITY_AUDIO_PREF_TAG);
@@ -408,7 +413,7 @@ public class BluetoothDetailsProfilesControllerTest extends BluetoothDetailsCont
setupDevice(makeDefaultDeviceConfig());
A2dpProfile audioProfile = addMockA2dpProfile(true, true, true);
showScreen(mController);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
assertThat(mProfiles.getPreferenceCount()).isEqualTo(3);
// Disabling media audio should cause the high quality audio switch to disappear, but not
// the regular audio one.

View File

@@ -16,6 +16,8 @@
package com.android.settings.bluetooth;
import static android.bluetooth.BluetoothDevice.BOND_NONE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
@@ -126,4 +128,13 @@ public class BluetoothDeviceDetailsFragmentTest {
RemoteDeviceNameDialogFragment dialog = (RemoteDeviceNameDialogFragment) captor.getValue();
assertThat(dialog).isNotNull();
}
@Test
public void finishFragmentIfNecessary_deviceIsBondNone_finishFragment() {
when(mCachedDevice.getBondState()).thenReturn(BOND_NONE);
mFragment.finishFragmentIfNecessary();
verify(mFragment).finish();
}
}

View File

@@ -24,7 +24,6 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.UserManager;
@@ -48,19 +47,36 @@ import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowAlertDialogCompat.class})
public class BluetoothDevicePreferenceTest {
private static final boolean SHOW_DEVICES_WITHOUT_NAMES = true;
private static final String MAC_ADDRESS = "04:52:C7:0B:D8:3C";
private static final String MAC_ADDRESS_2 = "05:52:C7:0B:D8:3C";
private static final String MAC_ADDRESS_3 = "06:52:C7:0B:D8:3C";
private static final String MAC_ADDRESS_4 = "07:52:C7:0B:D8:3C";
private static final Comparator<BluetoothDevicePreference> COMPARATOR =
Comparator.naturalOrder();
private Context mContext;
@Mock
private CachedBluetoothDevice mCachedBluetoothDevice;
@Mock
private CachedBluetoothDevice mCachedDevice1;
@Mock
private CachedBluetoothDevice mCachedDevice2;
@Mock
private CachedBluetoothDevice mCachedDevice3;
private FakeFeatureFactory mFakeFeatureFactory;
private MetricsFeatureProvider mMetricsFeatureProvider;
private BluetoothDevicePreference mPreference;
private List<BluetoothDevicePreference> mPreferenceList = new ArrayList<>();
@Before
public void setUp() {
@@ -70,8 +86,11 @@ public class BluetoothDevicePreferenceTest {
mFakeFeatureFactory = FakeFeatureFactory.setupForTest();
mMetricsFeatureProvider = mFakeFeatureFactory.getMetricsFeatureProvider();
when(mCachedBluetoothDevice.getAddress()).thenReturn(MAC_ADDRESS);
when(mCachedDevice1.getAddress()).thenReturn(MAC_ADDRESS_2);
when(mCachedDevice2.getAddress()).thenReturn(MAC_ADDRESS_3);
when(mCachedDevice3.getAddress()).thenReturn(MAC_ADDRESS_4);
mPreference = new BluetoothDevicePreference(mContext, mCachedBluetoothDevice,
SHOW_DEVICES_WITHOUT_NAMES);
SHOW_DEVICES_WITHOUT_NAMES, BluetoothDevicePreference.SortType.TYPE_DEFAULT);
}
@Test
@@ -170,7 +189,8 @@ public class BluetoothDevicePreferenceTest {
doReturn(false).when(mCachedBluetoothDevice).hasHumanReadableName();
BluetoothDevicePreference preference =
new BluetoothDevicePreference(mContext, mCachedBluetoothDevice,
SHOW_DEVICES_WITHOUT_NAMES);
SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_DEFAULT);
assertThat(preference.isVisible()).isTrue();
}
@@ -179,7 +199,8 @@ public class BluetoothDevicePreferenceTest {
public void isVisible_hideDeviceWithoutNames_invisible() {
doReturn(false).when(mCachedBluetoothDevice).hasHumanReadableName();
BluetoothDevicePreference preference =
new BluetoothDevicePreference(mContext, mCachedBluetoothDevice, false);
new BluetoothDevicePreference(mContext, mCachedBluetoothDevice,
false, BluetoothDevicePreference.SortType.TYPE_DEFAULT);
assertThat(preference.isVisible()).isFalse();
}
@@ -190,4 +211,54 @@ public class BluetoothDevicePreferenceTest {
assertThat(mPreference.mNeedNotifyHierarchyChanged).isTrue();
}
@Test
public void compareTo_sortTypeFIFO() {
final BluetoothDevicePreference preference3 = new BluetoothDevicePreference(mContext,
mCachedDevice3, SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_FIFO);
final BluetoothDevicePreference preference2 = new BluetoothDevicePreference(mContext,
mCachedDevice2, SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_FIFO);
final BluetoothDevicePreference preference1 = new BluetoothDevicePreference(mContext,
mCachedDevice1, SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_FIFO);
mPreferenceList.add(preference1);
mPreferenceList.add(preference2);
mPreferenceList.add(preference3);
Collections.sort(mPreferenceList, COMPARATOR);
assertThat(mPreferenceList.get(0).getCachedDevice().getAddress())
.isEqualTo(preference3.getCachedDevice().getAddress());
assertThat(mPreferenceList.get(1).getCachedDevice().getAddress())
.isEqualTo(preference2.getCachedDevice().getAddress());
assertThat(mPreferenceList.get(2).getCachedDevice().getAddress())
.isEqualTo(preference1.getCachedDevice().getAddress());
}
@Test
public void compareTo_sortTypeDefault() {
final BluetoothDevicePreference preference3 = new BluetoothDevicePreference(mContext,
mCachedDevice3, SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_DEFAULT);
final BluetoothDevicePreference preference2 = new BluetoothDevicePreference(mContext,
mCachedDevice2, SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_DEFAULT);
final BluetoothDevicePreference preference1 = new BluetoothDevicePreference(mContext,
mCachedDevice1, SHOW_DEVICES_WITHOUT_NAMES,
BluetoothDevicePreference.SortType.TYPE_DEFAULT);
mPreferenceList.add(preference1);
mPreferenceList.add(preference2);
mPreferenceList.add(preference3);
Collections.sort(mPreferenceList, COMPARATOR);
assertThat(mPreferenceList.get(0).getCachedDevice().getAddress())
.isEqualTo(preference1.getCachedDevice().getAddress());
assertThat(mPreferenceList.get(1).getCachedDevice().getAddress())
.isEqualTo(preference2.getCachedDevice().getAddress());
assertThat(mPreferenceList.get(2).getCachedDevice().getAddress())
.isEqualTo(preference3.getCachedDevice().getAddress());
}
}

View File

@@ -82,7 +82,7 @@ public class BluetoothDeviceUpdaterTest {
private BluetoothDeviceUpdater mBluetoothDeviceUpdater;
private BluetoothDevicePreference mPreference;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private List<CachedBluetoothDevice> mCachedDevices = new ArrayList<CachedBluetoothDevice>();
private List<CachedBluetoothDevice> mCachedDevices = new ArrayList<>();
@Before
public void setUp() {
@@ -99,15 +99,21 @@ public class BluetoothDeviceUpdaterTest {
when(mCachedBluetoothDevice.getAddress()).thenReturn(MAC_ADDRESS);
when(mSubBluetoothDevice.getAddress()).thenReturn(SUB_MAC_ADDRESS);
mPreference = new BluetoothDevicePreference(mContext, mCachedBluetoothDevice, false);
mPreference = new BluetoothDevicePreference(mContext, mCachedBluetoothDevice,
false, BluetoothDevicePreference.SortType.TYPE_DEFAULT);
mBluetoothDeviceUpdater =
new BluetoothDeviceUpdater(mDashboardFragment, mDevicePreferenceCallback,
new BluetoothDeviceUpdater(mContext, mDashboardFragment, mDevicePreferenceCallback,
mLocalManager) {
@Override
public boolean isFilterMatched(CachedBluetoothDevice cachedBluetoothDevice) {
return true;
}
};
@Override
public boolean isFilterMatched(CachedBluetoothDevice cachedBluetoothDevice) {
return true;
}
@Override
protected String getPreferenceKey() {
return "test_bt";
}
};
mBluetoothDeviceUpdater.setPrefContext(mContext);
}

Some files were not shown because too many files have changed in this diff Show More