fix: 引入Settings的Module

This commit is contained in:
2024-12-10 14:57:24 +08:00
parent ad8fc8731d
commit df105485bd
6934 changed files with 896168 additions and 2 deletions

View File

@@ -0,0 +1,247 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
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.app.admin.DevicePolicyManager;
import android.content.Context;
import android.os.UserManager;
import android.view.LayoutInflater;
import android.view.View;
import androidx.preference.PreferenceScreen;
import androidx.preference.PreferenceViewHolder;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settings.widget.GearPreference;
import org.junit.Before;
import org.junit.Ignore;
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)
@Ignore
public class ChangeScreenLockPreferenceControllerTest {
private static final int METRICS_CATEGORY = 1;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private UserManager mUserManager;
@Mock
private DevicePolicyManager mDevicePolicyManager;
@Mock
private PreferenceScreen mPreferenceScreen;
private Context mContext;
private FakeFeatureFactory mFeatureFactory;
private ChangeScreenLockPreferenceController mController;
private View mGearView;
private GearPreference mGearPreference;
private PreferenceViewHolder mPreferenceViewHolder;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application.getApplicationContext());
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
.thenReturn(mLockPatternUtils);
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
when(mContext.getSystemService(Context.DEVICE_POLICY_SERVICE))
.thenReturn(mDevicePolicyManager);
final SettingsPreferenceFragment host = mock(SettingsPreferenceFragment.class);
when(host.getMetricsCategory()).thenReturn(METRICS_CATEGORY);
mController = new ChangeScreenLockPreferenceController(mContext, host);
}
@Test
public void testDeviceAdministrators_byDefault_shouldBeShown() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(qualifiers = "mcc999")
public void testDeviceAdministrators_ifDisabled_shouldNotBeShown() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void updateState_notSecureDisableKeyguard_shouldNotShowGear() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(true);
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearView.getVisibility()).isEqualTo(View.GONE);
}
@Test
public void updateState_notSecureDisableKeyguard_summaryShouldShowOff() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(true);
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearPreference.getSummary())
.isEqualTo(mContext.getString(R.string.unlock_set_unlock_mode_off));
}
@Test
public void updateState_notSecureWithSwipeKeyguard_shouldNotShowGear() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearView.getVisibility()).isEqualTo(View.GONE);
}
@Test
public void updateState_notSecureWithSwipeKeyguard_summaryShouldShowSwipe() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearPreference.getSummary())
.isEqualTo(mContext.getString(R.string.unlock_set_unlock_mode_none));
}
@Test
public void updateState_secureWithPinKeyguard_shouldShowGear() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
doReturn(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX).when(mLockPatternUtils)
.getKeyguardStoredPasswordQuality(anyInt());
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearView.getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void updateState_secureWithPinKeyguard_summaryShouldShowPin() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
doReturn(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX).when(mLockPatternUtils)
.getKeyguardStoredPasswordQuality(anyInt());
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearPreference.getSummary())
.isEqualTo(mContext.getString(R.string.unlock_set_unlock_mode_pin));
}
@Test
public void updateState_secureWithPasswordKeyguard_shouldShowGear() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
doReturn(DevicePolicyManager.PASSWORD_QUALITY_COMPLEX).when(mLockPatternUtils)
.getKeyguardStoredPasswordQuality(anyInt());
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearView.getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void updateState_secureWithPasswordKeyguard_summaryShouldShowPassword() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
doReturn(DevicePolicyManager.PASSWORD_QUALITY_COMPLEX).when(mLockPatternUtils)
.getKeyguardStoredPasswordQuality(anyInt());
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearPreference.getSummary())
.isEqualTo(mContext.getString(R.string.unlock_set_unlock_mode_password));
}
@Test
public void updateState_secureWithPatternKeyguard_shouldShowGear() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
doReturn(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING).when(mLockPatternUtils)
.getKeyguardStoredPasswordQuality(anyInt());
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearView.getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void updateState_secureWithPatternKeyguard_summaryShouldShowPattern() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
doReturn(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING).when(mLockPatternUtils)
.getKeyguardStoredPasswordQuality(anyInt());
mockGearPreferenceAndViewHolder();
showPreference();
assertThat(mGearPreference.getSummary())
.isEqualTo(mContext.getString(R.string.unlock_set_unlock_mode_pattern));
}
private void mockGearPreferenceAndViewHolder() {
mGearPreference = new GearPreference(mContext, null);
mGearView = new View(mContext);
PreferenceViewHolder viewHolder = PreferenceViewHolder.createInstanceForTests(
LayoutInflater.from(mContext).inflate(
mGearPreference.getLayoutResource(), null, false));
mPreferenceViewHolder = spy(viewHolder);
doReturn(mGearView).when(mPreferenceViewHolder).findViewById(R.id.settings_button);
when(mPreferenceScreen.findPreference(anyString())).thenReturn(mGearPreference);
}
private void showPreference() {
mController.displayPreference(mPreferenceScreen);
mController.updateState(mGearPreference);
mGearPreference.onBindViewHolder(mPreferenceViewHolder);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (C) 2023 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.security;
import static com.android.internal.R.string.config_defaultContentProtectionService;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import android.content.ComponentName;
import android.content.Context;
import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.DeviceConfig;
import android.view.contentcapture.ContentCaptureManager;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
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 = {
ShadowDeviceConfig.class,
})
public class ContentProtectionPreferenceControllerTest {
private static final String PACKAGE_NAME = "com.test.package";
private static final ComponentName COMPONENT_NAME =
new ComponentName(PACKAGE_NAME, "TestClass");
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private Context mContext;
private String mConfigDefaultContentProtectionService = COMPONENT_NAME.flattenToString();
private ContentProtectionPreferenceController mController;
@Before
public void setUp() {
mContext = spy(RuntimeEnvironment.application);
mController = new ContentProtectionPreferenceController(mContext, "key");
}
@After
public void tearDown() {
ShadowDeviceConfig.reset();
}
@Test
public void isAvailable_isFalse() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_isTrue() {
doReturn(COMPONENT_NAME.flattenToString())
.when(mContext)
.getString(config_defaultContentProtectionService);
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
assertThat(mController.isAvailable()).isTrue();
}
}

View File

@@ -0,0 +1,179 @@
/*
* Copyright (C) 2023 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.security;
import static android.app.settings.SettingsEnums.CONTENT_PROTECTION_PREFERENCE;
import static com.android.internal.R.string.config_defaultContentProtectionService;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import android.content.ComponentName;
import android.content.Context;
import android.provider.DeviceConfig;
import android.provider.SearchIndexableResource;
import android.view.contentcapture.ContentCaptureManager;
import androidx.preference.PreferenceScreen;
import com.android.settings.R;
import com.android.settings.testutils.XmlTestUtils;
import com.android.settings.testutils.shadow.ShadowDashboardFragment;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
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.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowDashboardFragment.class,
ShadowUtils.class,
ShadowDeviceConfig.class,
})
public class ContentProtectionPreferenceFragmentTest {
private static final String PACKAGE_NAME = "com.test.package";
private static final ComponentName COMPONENT_NAME =
new ComponentName(PACKAGE_NAME, "TestClass");
private String mConfigDefaultContentProtectionService = COMPONENT_NAME.flattenToString();
private ContentProtectionPreferenceFragment mFragment;
private Context mContext;
private PreferenceScreen mScreen;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mFragment = spy(new ContentProtectionPreferenceFragment());
mScreen = spy(new PreferenceScreen(mContext, /* attrs= */ null));
doReturn(mContext).when(mFragment).getContext();
doReturn(mScreen).when(mFragment).getPreferenceScreen();
}
@After
public void tearDown() {
ShadowDeviceConfig.reset();
}
@Test
public void getMetricsCategory() {
assertThat(mFragment.getMetricsCategory()).isEqualTo(CONTENT_PROTECTION_PREFERENCE);
}
@Test
public void getPreferenceScreenResId() {
assertThat(mFragment.getPreferenceScreenResId())
.isEqualTo(R.layout.content_protection_preference_fragment);
}
@Test
public void getNonIndexableKeys_uiEnabled_existInXmlLayout() {
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
doReturn(mConfigDefaultContentProtectionService)
.when(mContext)
.getString(config_defaultContentProtectionService);
final List<String> nonIndexableKeys =
ContentProtectionPreferenceFragment.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(
mContext);
final List<String> allKeys =
XmlTestUtils.getKeysFromPreferenceXml(
mContext, R.layout.content_protection_preference_fragment);
final List<String> nonIndexableKeysExpected =
List.of(
"content_protection_preference_top_intro",
"content_protection_preference_subpage_illustration",
"content_protection_preference_user_consent_work_profile_switch");
assertThat(allKeys).containsAtLeastElementsIn(nonIndexableKeys);
assertThat(nonIndexableKeys).isEqualTo(nonIndexableKeysExpected);
}
@Test
public void getNonIndexableKeys_uiDisabled_notExisted() {
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"false",
/* makeDefault= */ false);
final List<String> nonIndexableKeys =
ContentProtectionPreferenceFragment.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(
mContext);
final List<String> allKeys =
XmlTestUtils.getKeysFromPreferenceXml(
mContext, R.layout.content_protection_preference_fragment);
assertThat(nonIndexableKeys).isEqualTo(allKeys);
}
@Test
public void searchIndexProvider_shouldIndexResource() {
final List<SearchIndexableResource> indexRes =
ContentProtectionPreferenceFragment.SEARCH_INDEX_DATA_PROVIDER
.getXmlResourcesToIndex(mContext, /* enabled= */ true);
assertThat(indexRes).isNotNull();
assertThat(indexRes).isNotEmpty();
assertThat(indexRes.get(0).xmlResId).isEqualTo(mFragment.getPreferenceScreenResId());
}
@Test
public void isPageSearchEnabled_uiDisabled_returnsFalse() {
boolean isSearchEnabled =
mFragment.SEARCH_INDEX_DATA_PROVIDER.isPageSearchEnabled(mContext);
assertThat(isSearchEnabled).isFalse();
}
@Test
public void isPageSearchEnabled_uiEnabled_returnsTrue() {
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
doReturn(mConfigDefaultContentProtectionService)
.when(mContext)
.getString(config_defaultContentProtectionService);
boolean isSearchEnabled =
mFragment.SEARCH_INDEX_DATA_PROVIDER.isPageSearchEnabled(mContext);
assertThat(isSearchEnabled).isTrue();
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright (C) 2023 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.security;
import static com.android.internal.R.string.config_defaultContentProtectionService;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import android.content.ComponentName;
import android.content.Context;
import android.provider.DeviceConfig;
import android.view.contentcapture.ContentCaptureManager;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
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.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowDeviceConfig.class,
})
public class ContentProtectionPreferenceUtilsTest {
private static final String PACKAGE_NAME = "com.test.package";
private static final ComponentName COMPONENT_NAME =
new ComponentName(PACKAGE_NAME, "TestClass");
private String mConfigDefaultContentProtectionService = COMPONENT_NAME.flattenToString();
@Mock private Context mMockContext;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@After
public void tearDown() {
ShadowDeviceConfig.reset();
}
@Test
public void isAvailable_bothEnabled_true() {
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
when(mMockContext.getString(config_defaultContentProtectionService))
.thenReturn(mConfigDefaultContentProtectionService);
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isTrue();
}
@Test
public void isAvailable_onlyUiEnabled_false() {
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isFalse();
}
@Test
public void isAvailable_onlyServiceEnabled_false() {
when(mMockContext.getString(config_defaultContentProtectionService))
.thenReturn(mConfigDefaultContentProtectionService);
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"false",
/* makeDefault= */ false);
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isFalse();
}
@Test
public void isAvailable_emptyComponentName_false() {
when(mMockContext.getString(config_defaultContentProtectionService))
.thenReturn("");
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isFalse();
}
@Test
public void isAvailable_blankComponentName_false() {
when(mMockContext.getString(config_defaultContentProtectionService))
.thenReturn(" ");
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"true",
/* makeDefault= */ false);
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isFalse();
}
@Test
public void isAvailable_invalidComponentName_false() {
when(mMockContext.getString(config_defaultContentProtectionService))
.thenReturn("invalid");
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isFalse();
}
@Test
public void isAvailable_bothDisabled_false() {
DeviceConfig.setProperty(
DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
ContentCaptureManager.DEVICE_CONFIG_PROPERTY_ENABLE_CONTENT_PROTECTION_RECEIVER,
"false",
/* makeDefault= */ false);
assertThat(ContentProtectionPreferenceUtils.isAvailable(mMockContext)).isFalse();
}
}

View File

@@ -0,0 +1,212 @@
/*
* Copyright (C) 2023 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.security;
import static com.android.settings.security.ContentProtectionTogglePreferenceController.KEY_CONTENT_PROTECTION_PREFERENCE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
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.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settings.widget.SettingsMainSwitchPreference;
import com.android.settingslib.RestrictedLockUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowUtils.class,
})
public class ContentProtectionTogglePreferenceControllerTest {
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock private PreferenceScreen mMockScreen;
private RestrictedLockUtils.EnforcedAdmin mAdmin;
private SettingsMainSwitchPreference mSwitchPreference;
private final Context mContext = ApplicationProvider.getApplicationContext();
private ContentProtectionTogglePreferenceController mController;
private int mSettingBackupValue;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mController = new TestContentProtectionTogglePreferenceController();
mSwitchPreference = new SettingsMainSwitchPreference(mContext);
when(mMockScreen.findPreference(mController.getPreferenceKey()))
.thenReturn(mSwitchPreference);
mSettingBackupValue = getContentProtectionGlobalSetting();
Settings.Global.putInt(mContext.getContentResolver(), KEY_CONTENT_PROTECTION_PREFERENCE, 0);
}
@After
public void tearDown() {
Settings.Global.putInt(
mContext.getContentResolver(),
KEY_CONTENT_PROTECTION_PREFERENCE,
mSettingBackupValue);
ShadowUtils.reset();
}
@Test
public void isAvailable_alwaysAvailable() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void displayPreference() {
setUpFullyManagedMode();
SettingsMainSwitchPreference mockSwitchPreference =
mock(SettingsMainSwitchPreference.class);
when(mMockScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController = new TestContentProtectionTogglePreferenceController();
mController.displayPreference(mMockScreen);
assertThat(mockSwitchPreference).isNotNull();
}
@Test
public void updateState_notFullyManagedMode_enabled() {
SettingsMainSwitchPreference mockSwitchPreference =
mock(SettingsMainSwitchPreference.class);
when(mMockScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController = new TestContentProtectionTogglePreferenceController();
mController.displayPreference(mMockScreen);
mController.updateState(mockSwitchPreference);
verify(mockSwitchPreference, never()).setDisabledByAdmin(any());
}
@Test
public void updateState_fullyManagedMode_disabled() {
setUpFullyManagedMode();
SettingsMainSwitchPreference mockSwitchPreference =
mock(SettingsMainSwitchPreference.class);
when(mMockScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController = new TestContentProtectionTogglePreferenceController();
mController.displayPreference(mMockScreen);
mController.updateState(mockSwitchPreference);
verify(mockSwitchPreference).setDisabledByAdmin(mAdmin);
}
@Test
public void isChecked_settingTurnOn() {
Settings.Global.putInt(mContext.getContentResolver(), KEY_CONTENT_PROTECTION_PREFERENCE, 1);
assertThat(mController.isChecked()).isTrue();
}
@Test
public void isChecked_fullyManagedMode_settingTurnOff() {
setUpFullyManagedMode();
Settings.Global.putInt(mContext.getContentResolver(), KEY_CONTENT_PROTECTION_PREFERENCE, 1);
SettingsMainSwitchPreference mockSwitchPreference =
mock(SettingsMainSwitchPreference.class);
when(mMockScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController = new TestContentProtectionTogglePreferenceController();
mController.displayPreference(mMockScreen);
mController.updateState(mockSwitchPreference);
assertThat(mController.isChecked()).isFalse();
}
@Test
public void isChecked_settingTurnOff() {
Settings.Global.putInt(
mContext.getContentResolver(), KEY_CONTENT_PROTECTION_PREFERENCE, -1);
assertThat(mController.isChecked()).isFalse();
assertThat(getContentProtectionGlobalSetting()).isEqualTo(-1);
}
@Test
public void isChecked_settingDefaultOn() {
assertThat(mController.isChecked()).isTrue();
assertThat(getContentProtectionGlobalSetting()).isEqualTo(0);
}
@Test
public void onSwitchChanged_switchChecked_manuallyEnabled() {
mController.setChecked(false);
mController.onCheckedChanged(/* switchView= */ null, /* isChecked= */ true);
assertThat(getContentProtectionGlobalSetting()).isEqualTo(1);
}
@Test
public void onSwitchChanged_switchUnchecked_manuallyDisabled() {
mController.onCheckedChanged(/* switchView= */ null, /* isChecked= */ false);
assertThat(getContentProtectionGlobalSetting()).isEqualTo(-1);
}
private int getContentProtectionGlobalSetting() {
return Settings.Global.getInt(
mContext.getContentResolver(), KEY_CONTENT_PROTECTION_PREFERENCE, 0);
}
private void setUpFullyManagedMode() {
mAdmin = new RestrictedLockUtils.EnforcedAdmin();
}
private class TestContentProtectionTogglePreferenceController
extends ContentProtectionTogglePreferenceController {
TestContentProtectionTogglePreferenceController() {
super(ContentProtectionTogglePreferenceControllerTest.this.mContext, "key");
}
@Override
protected RestrictedLockUtils.EnforcedAdmin getEnforcedAdmin() {
return mAdmin;
}
}
}

View File

@@ -0,0 +1,163 @@
/*
* Copyright (C) 2023 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.security;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
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.os.UserHandle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.RestrictedSwitchPreference;
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;
@RunWith(RobolectricTestRunner.class)
public class ContentProtectionWorkSwitchControllerTest {
private static final UserHandle TEST_USER_HANDLE = UserHandle.of(10);
private final Context mContext = ApplicationProvider.getApplicationContext();
@Mock private PreferenceScreen mMockPreferenceScreen;
private ContentProtectionWorkSwitchController mController;
private UserHandle mManagedProfileUserHandle;
private RestrictedLockUtils.EnforcedAdmin mEnforcedAdmin;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mController = new TestContentProtectionWorkSwitchController();
}
@Test
public void isAvailable_managedProfile_available() {
mManagedProfileUserHandle = TEST_USER_HANDLE;
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_noManagedProfile_notAvailable() {
mManagedProfileUserHandle = null;
assertThat(mController.getAvailabilityStatus()).isEqualTo(CONDITIONALLY_UNAVAILABLE);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isChecked_noManagedProfile_alwaysOff() {
mManagedProfileUserHandle = null;
assertThat(mController.isChecked()).isFalse();
}
@Test
public void isChecked_managedProfile_alwaysOff() {
mManagedProfileUserHandle = TEST_USER_HANDLE;
assertThat(mController.isChecked()).isFalse();
}
@Test
public void setChecked_alwaysFalse() {
assertThat(mController.setChecked(true)).isFalse();
assertThat(mController.setChecked(false)).isFalse();
}
@Test
public void displayPreference_managedProfile_disabled() {
mManagedProfileUserHandle = TEST_USER_HANDLE;
mEnforcedAdmin = new RestrictedLockUtils.EnforcedAdmin();
RestrictedSwitchPreference mockSwitchPreference = mock(RestrictedSwitchPreference.class);
when(mMockPreferenceScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController.displayPreference(mMockPreferenceScreen);
assertThat(mController.isAvailable()).isTrue();
verify(mockSwitchPreference).setDisabledByAdmin(mEnforcedAdmin);
}
@Test
public void displayPreference_noManagedProfile_notDisabled() {
mManagedProfileUserHandle = null;
mEnforcedAdmin = new RestrictedLockUtils.EnforcedAdmin();
RestrictedSwitchPreference mockSwitchPreference = mock(RestrictedSwitchPreference.class);
when(mMockPreferenceScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController.displayPreference(mMockPreferenceScreen);
assertThat(mController.isAvailable()).isFalse();
verify(mockSwitchPreference, never()).setDisabledByAdmin(any());
}
@Test
public void displayPreference_noEnforcedAdmin_notDisabled() {
mManagedProfileUserHandle = null;
mEnforcedAdmin = null;
RestrictedSwitchPreference mockSwitchPreference = mock(RestrictedSwitchPreference.class);
when(mMockPreferenceScreen.findPreference(any())).thenReturn(mockSwitchPreference);
when(mockSwitchPreference.getKey()).thenReturn(mController.getPreferenceKey());
mController.displayPreference(mMockPreferenceScreen);
assertThat(mController.isAvailable()).isFalse();
verify(mockSwitchPreference, never()).setDisabledByAdmin(any());
}
private class TestContentProtectionWorkSwitchController
extends ContentProtectionWorkSwitchController {
TestContentProtectionWorkSwitchController() {
super(ContentProtectionWorkSwitchControllerTest.this.mContext, "key");
}
@Override
@Nullable
protected UserHandle getManagedProfile() {
return mManagedProfileUserHandle;
}
@Override
@Nullable
protected RestrictedLockUtils.EnforcedAdmin getEnforcedAdmin(
@NonNull UserHandle managedProfile) {
return mEnforcedAdmin;
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import android.content.Context;
import androidx.preference.Preference;
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.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class CredentialManagementAppControllerTest {
@Mock
private Preference mPreference;
private Context mContext;
private CredentialManagementAppPreferenceController mController;
private static final String PREF_KEY_CREDENTIAL_MANAGEMENT_APP = "certificate_management_app";
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new CredentialManagementAppPreferenceController(
mContext, PREF_KEY_CREDENTIAL_MANAGEMENT_APP);
}
@Test
public void getAvailable_shouldAlwaysReturnTrue() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void getAvailabilityStatus_shouldAlwaysReturnAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void displayPreference_noCredentialManagementApp_shouldDisablePreference() {
mController.displayPreference(mPreference);
verify(mPreference).setEnabled(false);
verify(mPreference).setSummary(R.string.no_certificate_management_app);
}
}

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.security;
import static android.app.settings.SettingsEnums.CREDENTIAL_MANAGEMENT_APP;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import android.content.Context;
import android.provider.SearchIndexableResource;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowDashboardFragment;
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 org.robolectric.annotation.Config;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowDashboardFragment.class)
public class CredentialManagementAppFragmentTest {
private CredentialManagementAppFragment mFragment;
private Context mContext;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mFragment = spy(new CredentialManagementAppFragment());
doReturn(mContext).when(mFragment).getContext();
}
@Test
public void searchIndexProvider_shouldIndexResource() {
final List<SearchIndexableResource> indexRes =
CredentialManagementAppFragment.SEARCH_INDEX_DATA_PROVIDER
.getXmlResourcesToIndex(mContext, true /* enabled */);
assertThat(indexRes).isNotNull();
assertThat(indexRes.get(0).xmlResId).isEqualTo(R.xml.credential_management_app_fragment);
}
@Test
public void getMetricsCategory_shouldReturnInstallCertificateFromStorage() {
assertThat(mFragment.getMetricsCategory()).isEqualTo(CREDENTIAL_MANAGEMENT_APP);
}
}

View File

@@ -0,0 +1,86 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.os.Bundle;
import android.os.UserManager;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
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.ShadowApplication;
import org.robolectric.shadows.androidx.fragment.FragmentController;
@RunWith(RobolectricTestRunner.class)
public class EncryptionAndCredentialTest {
@Mock
private UserManager mUserManager;
@Mock
private DevicePolicyManager mDevicePolicyManager;
private Context mContext;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowApplication application = ShadowApplication.getInstance();
application.setSystemService(Context.DEVICE_POLICY_SERVICE, mDevicePolicyManager);
application.setSystemService(Context.USER_SERVICE, mUserManager);
mContext = RuntimeEnvironment.application;
}
@Test
public void getMetricsCategory_shouldReturnEncryptionAndCredential() {
EncryptionAndCredential fragment = new EncryptionAndCredential();
assertThat(fragment.getMetricsCategory()).isEqualTo(MetricsEvent.ENCRYPTION_AND_CREDENTIAL);
}
@Test
public void isSelectable_encryptionPreferenceStatus_isNotSelectable() {
final PreferenceFragmentCompat fragment =
FragmentController.of(new TestFragment(), new Bundle())
.create()
.start()
.resume()
.get();
final Preference preference =
fragment.findPreference("encryption_and_credentials_encryption_status");
assertThat(preference.isSelectable()).isFalse();
}
public static class TestFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(com.android.settings.R.xml.encryption_and_credential);
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* 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.security;
import static com.android.settings.security.EncryptionStatusPreferenceController
.PREF_KEY_ENCRYPTION_DETAIL_PAGE;
import static com.android.settings.security.EncryptionStatusPreferenceController
.PREF_KEY_ENCRYPTION_SECURITY_PAGE;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import androidx.preference.Preference;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowLockPatternUtils;
import com.android.settings.testutils.shadow.ShadowUserManager;
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 = {ShadowLockPatternUtils.class, ShadowUserManager.class})
public class EncryptionStatusPreferenceControllerTest {
private Context mContext;
private EncryptionStatusPreferenceController mController;
private Preference mPreference;
private ShadowUserManager mShadowUserManager;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mController =
new EncryptionStatusPreferenceController(mContext, PREF_KEY_ENCRYPTION_DETAIL_PAGE);
mShadowUserManager = ShadowUserManager.getShadow();
mPreference = new Preference(mContext);
}
@Test
@Config(qualifiers = "mcc999")
public void isAvailable_notVisible_false() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
@Config(qualifiers = "mcc999")
public void isAvailable_notVisible_butNotDetailPage_true() {
mController = new EncryptionStatusPreferenceController(mContext,
PREF_KEY_ENCRYPTION_SECURITY_PAGE);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void updateSummary_encrypted_shouldSayEncrypted() {
ShadowLockPatternUtils.setDeviceEncryptionEnabled(true);
mController.updateState(mPreference);
assertThat(mPreference.getFragment()).isNull();
assertThat(mPreference.getSummary())
.isEqualTo(mContext.getText(R.string.encrypted_summary));
}
@Test
public void updateSummary_unencrypted_shouldSayUnencrypted() {
ShadowLockPatternUtils.setDeviceEncryptionEnabled(false);
mController.updateState(mPreference);
final CharSequence summary = mContext.getText(R.string.not_encrypted_summary);
assertThat(mPreference.getSummary()).isEqualTo(summary);
assertThat(mController.getPreferenceKey()).isNotEqualTo(PREF_KEY_ENCRYPTION_SECURITY_PAGE);
assertThat(mPreference.getFragment()).isNull();
}
@Test
public void updateSummary_unencrypted_securityPage_shouldSayUnencrypted() {
mController =
new EncryptionStatusPreferenceController(mContext,
PREF_KEY_ENCRYPTION_SECURITY_PAGE);
ShadowLockPatternUtils.setDeviceEncryptionEnabled(false);
mController.updateState(mPreference);
final CharSequence summary = mContext.getText(R.string.not_encrypted_summary);
assertThat(mPreference.getSummary()).isEqualTo(summary);
assertThat(mPreference.getFragment()).isNull();
}
}

View File

@@ -0,0 +1,86 @@
/*
* 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.security;
import static com.android.settings.security.InstallCertificateFromStorage.SEARCH_INDEX_DATA_PROVIDER;
import static com.google.common.truth.Truth.assertThat;
import android.app.admin.DevicePolicyManager;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.os.UserManager;
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.ShadowApplication;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class InstallCertificateFromStorageTest {
@Mock
private UserManager mUserManager;
@Mock
private DevicePolicyManager mDevicePolicyManager;
private Context mContext;
private List<String> mTestKeys;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowApplication application = ShadowApplication.getInstance();
application.setSystemService(Context.DEVICE_POLICY_SERVICE, mDevicePolicyManager);
application.setSystemService(Context.USER_SERVICE, mUserManager);
mContext = RuntimeEnvironment.application;
setUpTestKeys();
}
private void setUpTestKeys() {
mTestKeys = new ArrayList<>();
mTestKeys.add("certificate_types");
mTestKeys.add("install_ca_certificate");
mTestKeys.add("install_user_certificate");
mTestKeys.add("install_wifi_certificate");
}
@Test
public void getMetricsCategory_shouldReturnInstallCertificateFromStorage() {
InstallCertificateFromStorage fragment = new InstallCertificateFromStorage();
assertThat(fragment.getMetricsCategory()).isEqualTo(
SettingsEnums.INSTALL_CERTIFICATE_FROM_STORAGE);
}
@Test
public void getNonIndexableKeys_existInXmlLayout() {
final List<String> nonIndexableKeys =
SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
assertThat(nonIndexableKeys).containsAtLeastElementsIn(mTestKeys);
}
}

View File

@@ -0,0 +1,99 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.os.UserManager;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.internal.widget.LockPatternUtils;
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.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication;
@RunWith(RobolectricTestRunner.class)
public class LockUnificationPreferenceControllerTest {
private static final int FAKE_PROFILE_USER_ID = 1234;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private UserManager mUm;
@Mock
private PreferenceScreen mScreen;
@Mock
private SecuritySettings mHost;
private Context mContext;
private LockUnificationPreferenceController mController;
private Preference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {FAKE_PROFILE_USER_ID});
final FakeFeatureFactory featureFactory = FakeFeatureFactory.setupForTest();
when(featureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
.thenReturn(mLockPatternUtils);
}
private void init() {
mController = new LockUnificationPreferenceController(mContext, mHost);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
mPreference = new Preference(mContext);
}
@Test
public void isAvailable_noProfile_false() {
when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[0]);
init();
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void getPreferenceKey_byDefault_returnsDefaultValue() {
init();
assertThat(mController.getPreferenceKey()).isEqualTo("unification");
}
@Test
public void getPreferenceKey_whenGivenValue_returnsGivenValue() {
mController = new LockUnificationPreferenceController(mContext, mHost, "key");
assertThat(mController.getPreferenceKey()).isEqualTo("key");
}
}

View File

@@ -0,0 +1,149 @@
/*
* 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.security;
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 android.content.Context;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.display.AmbientDisplayAlwaysOnPreferenceController;
import com.android.settings.display.AmbientDisplayNotificationsPreferenceController;
import com.android.settings.gestures.DoubleTapScreenPreferenceController;
import com.android.settings.gestures.PickupGesturePreferenceController;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.XmlTestUtils;
import com.android.settings.testutils.shadow.ShadowLockPatternUtils;
import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settingslib.core.AbstractPreferenceController;
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 java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowUtils.class, ShadowLockPatternUtils.class})
public class LockscreenDashboardFragmentTest {
@Mock
private LockPatternUtils mLockPatternUtils;
private FakeFeatureFactory mFeatureFactory;
private TestFragment mTestFragment;
private Context mContext;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(any(Context.class)))
.thenReturn(mLockPatternUtils);
mContext = RuntimeEnvironment.application;
mTestFragment = spy(new TestFragment());
doReturn(mContext).when(mTestFragment).getContext();
}
@Test
public void containsNotificationSettingsForPrimaryUserAndWorkProfile() {
List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(RuntimeEnvironment.application,
mTestFragment.getPreferenceScreenResId());
assertThat(keys).containsAtLeast(LockscreenDashboardFragment.KEY_LOCK_SCREEN_NOTIFICATON,
LockscreenDashboardFragment.KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE,
LockscreenDashboardFragment.KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE_HEADER);
}
@Test
public void onAttach_alwaysOn_shouldInvokeSetters() {
final AmbientDisplayAlwaysOnPreferenceController controller = spy(
new AmbientDisplayAlwaysOnPreferenceController(mContext, "key"));
doReturn(controller).when(mTestFragment).use(
AmbientDisplayAlwaysOnPreferenceController.class);
mTestFragment.onAttach(mContext);
verify(controller).setConfig(any());
}
@Test
public void onAttach_notifications_shouldInvokeSetters() {
final AmbientDisplayNotificationsPreferenceController controller = spy(
new AmbientDisplayNotificationsPreferenceController(mContext, "key"));
doReturn(controller).when(mTestFragment).use(
AmbientDisplayNotificationsPreferenceController.class);
mTestFragment.onAttach(mContext);
verify(controller).setConfig(any());
}
@Test
public void onAttach_doubleTap_shouldInvokeSetters() {
final DoubleTapScreenPreferenceController controller = spy(
new DoubleTapScreenPreferenceController(mContext, "key"));
doReturn(controller).when(mTestFragment).use(DoubleTapScreenPreferenceController.class);
mTestFragment.onAttach(mContext);
verify(controller).setConfig(any());
}
@Test
public void onAttach_pickUp_shouldInvokeSetters() {
final PickupGesturePreferenceController controller = spy(
new PickupGesturePreferenceController(mContext, "key"));
doReturn(controller).when(mTestFragment).use(PickupGesturePreferenceController.class);
mTestFragment.onAttach(mContext);
verify(controller).setConfig(any());
}
@Test
public void isPageSearchable_notLocked_shouldBeSearchable() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(true);
assertThat(LockscreenDashboardFragment.SEARCH_INDEX_DATA_PROVIDER
.getNonIndexableKeys(mContext))
.doesNotContain("security_lockscreen_settings_screen");
}
@Test
public void controlsSettings() {
mTestFragment.onAttach(mContext);
assertThat(mTestFragment.mControlsContentObserver).isNotNull();
mTestFragment.onDetach();
assertThat(mTestFragment.mControlsContentObserver).isNull();
}
public static class TestFragment extends LockscreenDashboardFragment {
@Override
protected <T extends AbstractPreferenceController> T use(Class<T> clazz) {
return super.use(clazz);
}
}
}

View File

@@ -0,0 +1,189 @@
/*
* Copyright (C) 2022 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.os.SystemProperties;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowSystemProperties;
@RunWith(RobolectricTestRunner.class)
public class MemtagHelperTest {
private final String mMemtagProperty = "arm64.memtag.bootctl";
private final String mMemtagSupportedProperty = "ro.arm64.memtag.bootctl_settings_toggle";
@Test
public void isChecked_empty_isFalse() {
ShadowSystemProperties.override(mMemtagProperty, "");
assertThat(MemtagHelper.isChecked()).isFalse();
}
@Test
public void isChecked_memtag_isTrue() {
ShadowSystemProperties.override(mMemtagProperty, "memtag");
assertThat(MemtagHelper.isChecked()).isTrue();
}
@Test
public void isChecked_memtagAndKernel_isTrue() {
ShadowSystemProperties.override(mMemtagProperty, "memtag,memtag-kernel");
assertThat(MemtagHelper.isChecked()).isTrue();
}
@Test
public void isChecked_kernel_isFalse() {
ShadowSystemProperties.override(mMemtagProperty, "memtag-kernel");
assertThat(MemtagHelper.isChecked()).isFalse();
}
@Test
public void isChecked_kernelAndMemtag_isTrue() {
ShadowSystemProperties.override(mMemtagProperty, "memtag-kernel,memtag");
assertThat(MemtagHelper.isChecked()).isTrue();
}
@Test
public void SetChecked_true_isMemtag() {
MemtagHelper.setChecked(true);
assertThat(SystemProperties.get(mMemtagProperty)).isEqualTo("memtag");
}
@Test
public void SetChecked_false_isNone() {
MemtagHelper.setChecked(false);
assertThat(SystemProperties.get(mMemtagProperty)).isEqualTo("none");
}
@Test
public void getAvailabilityStatus_isForcedOff_isDISABLED_DEPENDENT_SETTING() {
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "force_off");
ShadowSystemProperties.override(mMemtagSupportedProperty, "true");
assertThat(MemtagHelper.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_DEPENDENT_SETTING);
}
@Test
public void getAvailabilityStatus_isForcedOn_isDISABLED_DEPENDENT_SETTING() {
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "force_on");
ShadowSystemProperties.override(mMemtagSupportedProperty, "true");
assertThat(MemtagHelper.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_DEPENDENT_SETTING);
}
@Test
public void getAvailabilityStatus_isUnsupported_isUNSUPPORTED_ON_DEVICE() {
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "");
ShadowSystemProperties.override(mMemtagSupportedProperty, "false");
assertThat(MemtagHelper.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_isSupported_isAVAILABLE() {
ShadowSystemProperties.override(mMemtagSupportedProperty, "true");
assertThat(MemtagHelper.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void IsOn_zygoteSupportsMemoryTagging_isTrue() {
ZygoteShadow.setSupportsMemoryTagging(true);
assertThat(MemtagHelper.isOn()).isTrue();
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void IsOn_noZygoteSupportsMemoryTagging_isFalse() {
ZygoteShadow.setSupportsMemoryTagging(false);
assertThat(MemtagHelper.isOn()).isFalse();
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void getSummary_memtagAndZygoteSupportsMemoryTagging_memtag_on() {
ZygoteShadow.setSupportsMemoryTagging(true);
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "");
ShadowSystemProperties.override(mMemtagProperty, "memtag");
assertThat(MemtagHelper.getSummary()).isEqualTo(R.string.memtag_on);
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void getSummary_noMemtagAndZygoteSupportsMemoryTagging_memtag_off_pending() {
ZygoteShadow.setSupportsMemoryTagging(true);
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "");
ShadowSystemProperties.override(mMemtagProperty, "");
assertThat(MemtagHelper.getSummary()).isEqualTo(R.string.memtag_off_pending);
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void getSummary_noMemtagAndNoZygoteSupportsMemoryTagging_memtag_off() {
ZygoteShadow.setSupportsMemoryTagging(false);
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "");
ShadowSystemProperties.override(mMemtagProperty, "");
assertThat(MemtagHelper.getSummary()).isEqualTo(R.string.memtag_off);
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void getSummary_memtagAndNoZygoteSupportsMemoryTagging_memtag_on_pending() {
ZygoteShadow.setSupportsMemoryTagging(false);
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "");
ShadowSystemProperties.override(mMemtagProperty, "memtag");
assertThat(MemtagHelper.getSummary()).isEqualTo(R.string.memtag_on_pending);
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void getSummary_forceOffOverride_memtag_force_off() {
ZygoteShadow.setSupportsMemoryTagging(false);
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "force_off");
ShadowSystemProperties.override(mMemtagProperty, "memtag");
assertThat(MemtagHelper.getSummary()).isEqualTo(R.string.memtag_force_off);
}
@Test
@Config(shadows = {ZygoteShadow.class})
public void getSummary_forceOffOverride_memtag_force_on() {
ZygoteShadow.setSupportsMemoryTagging(false);
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "force_on");
ShadowSystemProperties.override(mMemtagProperty, "memtag");
assertThat(MemtagHelper.getSummary()).isEqualTo(R.string.memtag_force_on);
}
@Test
public void isForcedOn_forceOnOverride_isTrue() {
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "force_on");
assertThat(MemtagHelper.isForcedOn()).isTrue();
}
@Test
public void isForcedOff_forceOffOverride_isTrue() {
ShadowSystemProperties.override(MemtagHelper.DEVICE_CONFIG_PROP, "force_off");
assertThat(MemtagHelper.isForcedOff()).isTrue();
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2022 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import com.android.settings.testutils.shadow.ShadowRestrictedLockUtilsInternal;
import com.android.settingslib.RestrictedPreference;
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.shadows.ShadowSystemProperties;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowRestrictedLockUtilsInternal.class})
public class MemtagPagePreferenceControllerTest {
private final String mMemtagSupportedProperty = "ro.arm64.memtag.bootctl_supported";
private MemtagPagePreferenceController mController;
private Context mContext;
private static final String FRAGMENT_TAG = "memtag_page";
@Before
public void setUp() {
ShadowSystemProperties.override(mMemtagSupportedProperty, "true");
mContext = RuntimeEnvironment.application;
mController = new MemtagPagePreferenceController(mContext, FRAGMENT_TAG);
}
@Test
public void displayPreference_disabledByAdmin_disablesPreference() {
ShadowRestrictedLockUtilsInternal.setMteIsDisabled(true);
RestrictedPreference preference = new RestrictedPreference(mContext);
preference.setKey(mController.getPreferenceKey());
PreferenceScreen screen = new PreferenceManager(mContext).createPreferenceScreen(mContext);
screen.addPreference(preference);
mController.displayPreference(screen);
assertThat(preference.isDisabledByAdmin()).isTrue();
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2022 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.app.settings.SettingsEnums;
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;
@RunWith(RobolectricTestRunner.class)
public class MemtagPageTest {
private MemtagPage mMemtagPage;
private Context mContext;
@Before
public void setUp() {
mMemtagPage = new MemtagPage();
mContext = RuntimeEnvironment.application;
}
@Test
public void getMetricsCategory_isSETTINGS_MEMTAG_CATEGORY() {
assertThat(mMemtagPage.getMetricsCategory())
.isEqualTo(SettingsEnums.SETTINGS_MEMTAG_CATEGORY);
}
@Test
public void getPreferenceScreenResId_isMemtag_page() {
assertThat(mMemtagPage.getPreferenceScreenResId()).isEqualTo(R.xml.memtag_page);
}
@Test
public void SEARCH_INDEX_DATA_PROVIDERgetPreferenceControllers_isNotEmpty() {
assertThat(MemtagPage.SEARCH_INDEX_DATA_PROVIDER.getPreferenceControllers(mContext))
.isNotEmpty();
}
}

View File

@@ -0,0 +1,158 @@
/*
* Copyright (C) 2022 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.security;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist;
import static androidx.test.espresso.matcher.RootMatchers.isDialog;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
import com.android.settings.testutils.shadow.ShadowRestrictedLockUtilsInternal;
import com.android.settingslib.RestrictedSwitchPreference;
import com.android.settingslib.testutils.shadow.ShadowInteractionJankMonitor;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowSystemProperties;
@Ignore("b/313564061")
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ZygoteShadow.class,
ShadowDeviceConfig.class,
ShadowInteractionJankMonitor.class,
ShadowRestrictedLockUtilsInternal.class
})
public class MemtagPreferenceControllerTest {
private final String mMemtagSupportedProperty = "ro.arm64.memtag.bootctl_supported";
@Rule
public ActivityScenarioRule<TestActivity> mActivityScenario =
new ActivityScenarioRule<>(TestActivity.class);
private MemtagPage mMemtagPage;
private MemtagPreferenceController mController;
private Context mContext;
private TestActivity mActivity;
private static final String FRAGMENT_TAG = "memtag_page";
@Before
public void setUp() {
ShadowSystemProperties.override(mMemtagSupportedProperty, "true");
mContext = ApplicationProvider.getApplicationContext();
mMemtagPage = new MemtagPage();
System.out.println("Activity: " + mActivity);
mActivityScenario.getScenario().onActivity(a -> {
a.getSupportFragmentManager()
.beginTransaction()
.add(TestActivity.CONTAINER_VIEW_ID, mMemtagPage)
.commitNow();
mController = new MemtagPreferenceController(a, FRAGMENT_TAG);
mController.setFragment(mMemtagPage);
});
System.out.println("Committed");
}
@Test
public void getSliceHighlightMenuRes_isMenu_key_security() {
assertThat(mController.getSliceHighlightMenuRes()).isEqualTo(R.string.menu_key_security);
}
@Test
public void setChecked_isChecked_updatesSummary() {
ZygoteShadow.setSupportsMemoryTagging(true);
mController.setChecked(true);
assertThat(mController.getSummary())
.isEqualTo(mContext.getResources().getString(R.string.memtag_on));
}
@Test
public void setChecked_isUnchecked_updatesSummary() {
ZygoteShadow.setSupportsMemoryTagging(false);
mController.setChecked(false);
assertThat(mController.getSummary())
.isEqualTo(mContext.getResources().getString(R.string.memtag_off));
}
@Test
public void setChecked_isCheckedPending_updatesSummary() {
ZygoteShadow.setSupportsMemoryTagging(false);
mController.setChecked(true);
assertThat(mController.getSummary())
.isEqualTo(mContext.getResources().getString(R.string.memtag_on_pending));
}
@Test
public void setChecked_isUncheckedPending_updatesSummary() {
ZygoteShadow.setSupportsMemoryTagging(true);
mController.setChecked(false);
assertThat(mController.getSummary())
.isEqualTo(mContext.getResources().getString(R.string.memtag_off_pending));
}
@Test
public void setChecked_isCheckedPending_showsDialog() {
ZygoteShadow.setSupportsMemoryTagging(false);
mController.setChecked(true);
onView(withText(R.string.memtag_reboot_title)).inRoot(isDialog());
}
@Test
public void setChecked_isUncheckedPending_showsDialog() {
ZygoteShadow.setSupportsMemoryTagging(true);
mController.setChecked(false);
onView(withText(R.string.memtag_reboot_title)).inRoot(isDialog());
}
@Test
public void setChecked_isChecked_doesNotShowDialog() {
ZygoteShadow.setSupportsMemoryTagging(false);
mController.setChecked(false);
onView(withText(R.string.memtag_reboot_title)).inRoot(isDialog()).check(doesNotExist());
}
@Test
public void setChecked_isUnchecked_doesNotShowDialog() {
ZygoteShadow.setSupportsMemoryTagging(true);
mController.setChecked(true);
onView(withText(R.string.memtag_reboot_title)).inRoot(isDialog()).check(doesNotExist());
}
@Test
public void updateState_disabledByAdmin_disablesPreference() {
ShadowRestrictedLockUtilsInternal.setMteIsDisabled(true);
RestrictedSwitchPreference preference = new RestrictedSwitchPreference(mContext);
mController.updateState(preference);
assertThat(preference.isDisabledByAdmin()).isTrue();
}
}

View File

@@ -0,0 +1,201 @@
/*
* 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.security;
import static com.android.settings.security.OwnerInfoPreferenceController.KEY_OWNER_INFO;
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.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.users.OwnerInfoSettings;
import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
import com.android.settingslib.RestrictedPreference;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.core.lifecycle.ObservablePreferenceFragment;
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;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {
com.android.settings.testutils.shadow.ShadowFragment.class,
})
public class OwnerInfoPreferenceControllerTest {
@Mock
private ObservablePreferenceFragment mFragment;
@Mock
private PreferenceScreen mScreen;
@Mock
private PreferenceManager mPreferenceManager;
@Mock
private FragmentManager mFragmentManager;
@Mock
private FragmentTransaction mFragmentTransaction;
@Mock
private RestrictedPreference mPreference;
@Mock
private LockPatternUtils mLockPatternUtils;
private Context mContext;
private OwnerInfoPreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
when(mFragment.isAdded()).thenReturn(true);
when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
when(mFragment.getPreferenceManager()).thenReturn(mPreferenceManager);
when(mPreference.getContext()).thenReturn(mContext);
when(mFragment.getFragmentManager()).thenReturn(mFragmentManager);
when(mFragment.getSettingsLifecycle()).thenReturn(mock(Lifecycle.class));
when(mFragmentManager.beginTransaction()).thenReturn(mFragmentTransaction);
mController = spy(new OwnerInfoPreferenceController(mContext, mFragment));
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
ReflectionHelpers.setField(mController, "mLockPatternUtils", mLockPatternUtils);
}
@Test
public void isAvailable_shouldReturnTrue() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void onResume_shouldUpdateEnableState() {
mController.onResume();
verify(mController).updateEnableState();
}
@Test
public void onResume_shouldUpdateSummary() {
mController.onResume();
verify(mController).updateSummary();
}
@Test
public void updateSummary_deviceOwnerInfoEnabled_shouldSetDeviceOwnerInfoSummary() {
final String deviceOwnerInfo = "Test Device Owner Info";
doReturn(true).when(mController).isDeviceOwnerInfoEnabled();
doReturn(deviceOwnerInfo).when(mController).getDeviceOwnerInfo();
mController.displayPreference(mScreen);
mController.updateSummary();
verify(mPreference).setSummary(deviceOwnerInfo);
}
@Test
public void updateSummary_ownerInfoEnabled_shouldSetOwnerInfoSummary() {
final String ownerInfo = "Test Owner Info";
doReturn(false).when(mController).isDeviceOwnerInfoEnabled();
doReturn(true).when(mController).isOwnerInfoEnabled();
doReturn(ownerInfo).when(mController).getOwnerInfo();
mController.displayPreference(mScreen);
mController.updateSummary();
verify(mPreference).setSummary(ownerInfo);
}
@Test
public void updateSummary_ownerInfoDisabled_shouldSetDefaultSummary() {
doReturn(false).when(mController).isDeviceOwnerInfoEnabled();
doReturn(false).when(mController).isOwnerInfoEnabled();
mController.displayPreference(mScreen);
mController.updateSummary();
verify(mPreference).setSummary(mContext.getString(
com.android.settings.R.string.owner_info_settings_summary));
}
@Test
public void updateEnableState_deviceOwnerInfoEnabled_shouldSetDisabledByAdmin() {
doReturn(true).when(mController).isDeviceOwnerInfoEnabled();
doReturn(mock(EnforcedAdmin.class)).when(mController).getDeviceOwner();
mController.displayPreference(mScreen);
mController.updateEnableState();
verify(mPreference).setDisabledByAdmin(any(EnforcedAdmin.class));
}
@Test
public void updateEnableState_lockScreenDisabled_shouldDisablePreference() {
doReturn(false).when(mController).isDeviceOwnerInfoEnabled();
doReturn(true).when(mLockPatternUtils).isLockScreenDisabled(anyInt());
mController.displayPreference(mScreen);
mController.updateEnableState();
verify(mPreference).setEnabled(false);
}
@Test
public void updateEnableState_lockScreenEnabled_shouldEnablePreference() {
doReturn(false).when(mController).isDeviceOwnerInfoEnabled();
doReturn(false).when(mLockPatternUtils).isLockScreenDisabled(anyInt());
mController.displayPreference(mScreen);
mController.updateEnableState();
verify(mPreference).setEnabled(true);
}
@Test
public void handlePreferenceTreeClick_shouldLaunchOwnerInfoSettings() {
final RestrictedPreference preference = new RestrictedPreference(mContext);
preference.setKey(KEY_OWNER_INFO);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(preference);
doReturn(false).when(mController).isDeviceOwnerInfoEnabled();
doReturn(false).when(mLockPatternUtils).isLockScreenDisabled(anyInt());
mController.displayPreference(mScreen);
mController.updateEnableState();
mController.handlePreferenceTreeClick(preference);
verify(mFragment.getFragmentManager().beginTransaction())
.add(any(OwnerInfoSettings.class), anyString());
}
}

View File

@@ -0,0 +1,183 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
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.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.UserHandle;
import android.security.AppUriAuthenticationPolicy;
import android.security.Credentials;
import android.security.IKeyChainService;
import android.security.KeyChain;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
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;
@RunWith(RobolectricTestRunner.class)
public class RequestManageCredentialsTest {
private static final AppUriAuthenticationPolicy AUTHENTICATION_POLICY =
new AppUriAuthenticationPolicy.Builder()
.addAppAndUriMapping("com.android.test", Uri.parse("test.com"), "testAlias")
.build();
private RequestManageCredentials mActivity;
@Mock
private DevicePolicyManager mDevicePolicyManager;
@Mock
private KeyChain.KeyChainConnection mKeyChainConnection;
@Mock
private IKeyChainService mKeyChainService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void onCreate_intentActionNotManageCredentials_finishActivity()
throws Exception {
final Intent intent = new Intent(Credentials.ACTION_MANAGE_CREDENTIALS + "_bad");
intent.putExtra(KeyChain.EXTRA_AUTHENTICATION_POLICY, AUTHENTICATION_POLICY);
setupActivityWithAction(intent);
when(mDevicePolicyManager.getDeviceOwnerUser()).thenReturn(null);
when(mDevicePolicyManager.getProfileOwner()).thenReturn(null);
when(mActivity.getLaunchedFromPackage()).thenReturn("com.example.credapp");
mActivity.onCreate(null);
assertThat(mActivity).isNotNull();
assertThat(mActivity.isFinishing()).isTrue();
}
@Test
public void onCreate_noAuthenticationPolicy_finishActivity()
throws Exception {
final Intent intent = new Intent(Credentials.ACTION_MANAGE_CREDENTIALS);
setupActivityWithAction(intent);
when(mDevicePolicyManager.getDeviceOwnerUser()).thenReturn(null);
when(mDevicePolicyManager.getProfileOwner()).thenReturn(null);
when(mActivity.getLaunchedFromPackage()).thenReturn("com.example.credapp");
mActivity.onCreate(null);
assertThat(mActivity).isNotNull();
assertThat(mActivity.isFinishing()).isTrue();
}
@Test
public void onCreate_invalidAuthenticationPolicy_finishActivity()
throws Exception {
final Intent intent = new Intent(Credentials.ACTION_MANAGE_CREDENTIALS);
intent.putExtra(KeyChain.EXTRA_AUTHENTICATION_POLICY, "Invalid policy");
setupActivityWithAction(intent);
when(mDevicePolicyManager.getDeviceOwnerUser()).thenReturn(null);
when(mDevicePolicyManager.getProfileOwner()).thenReturn(null);
when(mActivity.getLaunchedFromPackage()).thenReturn("com.example.credapp");
mActivity.onCreate(null);
assertThat(mActivity).isNotNull();
assertThat(mActivity.isFinishing()).isTrue();
}
@Test
public void onCreate_runOnManagedProfile_finishActivity()
throws Exception {
final Intent intent = new Intent(Credentials.ACTION_MANAGE_CREDENTIALS);
intent.putExtra(KeyChain.EXTRA_AUTHENTICATION_POLICY, AUTHENTICATION_POLICY);
setupActivityWithAction(intent);
when(mDevicePolicyManager.getDeviceOwnerUser()).thenReturn(null);
when(mDevicePolicyManager.getProfileOwner()).thenReturn(new ComponentName("pkg", "cls"));
when(mActivity.getLaunchedFromPackage()).thenReturn("com.example.credapp");
mActivity.onCreate(null);
assertThat(mActivity).isNotNull();
assertThat(mActivity.isFinishing()).isTrue();
}
@Test
public void onCreate_runOnManagedDevice_finishActivity()
throws Exception {
final Intent intent = new Intent(Credentials.ACTION_MANAGE_CREDENTIALS);
intent.putExtra(KeyChain.EXTRA_AUTHENTICATION_POLICY, AUTHENTICATION_POLICY);
setupActivityWithAction(intent);
when(mDevicePolicyManager.getDeviceOwnerUser()).thenReturn(UserHandle.SYSTEM);
when(mDevicePolicyManager.getProfileOwner()).thenReturn(null);
when(mActivity.getLaunchedFromPackage()).thenReturn("com.example.credapp");
mActivity.onCreate(null);
assertThat(mActivity).isNotNull();
assertThat(mActivity.isFinishing()).isTrue();
}
@Test
public void onCreate_authenticationPolicyProvided_startActivity() throws Exception {
final Intent intent = new Intent(Credentials.ACTION_MANAGE_CREDENTIALS);
intent.putExtra(KeyChain.EXTRA_AUTHENTICATION_POLICY, AUTHENTICATION_POLICY);
setupActivityWithAction(intent);
when(mDevicePolicyManager.getDeviceOwnerUser()).thenReturn(null);
when(mDevicePolicyManager.getProfileOwner()).thenReturn(null);
when(mActivity.getLaunchedFromPackage()).thenReturn("com.example.credapp");
mActivity.onCreate(null);
assertThat(mActivity).isNotNull();
assertThat(mActivity.isFinishing()).isFalse();
assertThat((RecyclerView) mActivity.findViewById(R.id.apps_list)).isNotNull();
assertThat((LinearLayout) mActivity.findViewById(R.id.button_panel)).isNotNull();
assertThat((Button) mActivity.findViewById(R.id.allow_button)).isNotNull();
assertThat((Button) mActivity.findViewById(R.id.dont_allow_button)).isNotNull();
}
private void setupActivityWithAction(Intent intent) throws Exception {
mActivity = spy(Robolectric.buildActivity(RequestManageCredentials.class, intent).get());
doReturn(mKeyChainConnection).when(mActivity).getKeyChainConnection(eq(mActivity), any());
doReturn(mDevicePolicyManager).when(mActivity).getSystemService(DevicePolicyManager.class);
when(mKeyChainConnection.getService()).thenReturn(mKeyChainService);
}
}

View File

@@ -0,0 +1,89 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import android.os.UserManager;
import androidx.lifecycle.LifecycleOwner;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.core.lifecycle.Lifecycle;
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 = ShadowUserManager.class)
public class RestrictedEncryptionPreferenceControllerTest {
private Context mContext;
private ShadowUserManager mUserManager;
private InstallCertificatePreferenceController mInstallCertificatePreferenceController;
private ResetCredentialsPreferenceController mResetCredentialsPreferenceController;
private UserCredentialsPreferenceController mUserCredentialsPreferenceController;
private InstallCaCertificatePreferenceController mInstallCaCertificatePreferenceController;
private InstallUserCertificatePreferenceController mInstallUserCertificatePreferenceController;
private InstallWifiCertificatePreferenceController mInstallWifiCertificatePreferenceController;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
mInstallCertificatePreferenceController =
new InstallCertificatePreferenceController(mContext);
mResetCredentialsPreferenceController =
new ResetCredentialsPreferenceController(mContext, mLifecycle);
mUserCredentialsPreferenceController =
new UserCredentialsPreferenceController(mContext);
mInstallCaCertificatePreferenceController =
new InstallCaCertificatePreferenceController(mContext);
mInstallUserCertificatePreferenceController =
new InstallUserCertificatePreferenceController(mContext);
mInstallWifiCertificatePreferenceController =
new InstallWifiCertificatePreferenceController(mContext);
mUserManager = ShadowUserManager.getShadow();
}
@Test
public void isAvailable_noRestriction_shouldReturnTrue() {
assertThat(mInstallCertificatePreferenceController.isAvailable()).isTrue();
assertThat(mResetCredentialsPreferenceController.isAvailable()).isTrue();
assertThat(mUserCredentialsPreferenceController.isAvailable()).isTrue();
assertThat(mInstallCaCertificatePreferenceController.isAvailable()).isTrue();
assertThat(mInstallUserCertificatePreferenceController.isAvailable()).isTrue();
assertThat(mInstallWifiCertificatePreferenceController.isAvailable()).isTrue();
}
@Test
public void isAvailable_hasRestriction_shouldReturnFalse() {
mUserManager.addBaseUserRestriction(UserManager.DISALLOW_CONFIG_CREDENTIALS);
assertThat(mInstallCertificatePreferenceController.isAvailable()).isFalse();
assertThat(mResetCredentialsPreferenceController.isAvailable()).isFalse();
assertThat(mUserCredentialsPreferenceController.isAvailable()).isFalse();
}
}

View File

@@ -0,0 +1,99 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.Preference;
import com.android.settings.R;
import org.junit.After;
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 org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
public class ScreenPinningPreferenceControllerTest {
private Context mContext;
private ScreenPinningPreferenceController mController;
private Preference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new ScreenPinningPreferenceController(mContext, "key");
mPreference = new Preference(mContext);
mPreference.setKey(mController.getPreferenceKey());
}
@After
public void tearDown() {
final ContentResolver contentResolver = mContext.getContentResolver();
Settings.System.putInt(contentResolver, Settings.System.LOCK_TO_APP_ENABLED, 0);
}
@Test
public void isAvailable_byDefault_isTrue() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(qualifiers = "mcc999")
public void isAvailable_whenNotVisible_isFalse() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void updateState_isOff_shouldDisableOffSummary() {
final ContentResolver contentResolver = mContext.getContentResolver();
Settings.System.putInt(contentResolver, Settings.System.LOCK_TO_APP_ENABLED, 0);
mController.updateState(mPreference);
assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.switch_off_text));
}
@Test
public void updateState_isOn_shouldDisableOnSummary() {
final ContentResolver contentResolver = mContext.getContentResolver();
Settings.System.putInt(contentResolver, Settings.System.LOCK_TO_APP_ENABLED, 1);
mController.updateState(mPreference);
assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.switch_on_text));
}
@Test
public void getPreferenceKey_whenGivenValue_returnsGivenValue() {
mController = new ScreenPinningPreferenceController(mContext, "key");
assertThat(mController.getPreferenceKey()).isEqualTo("key");
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (C) 2024 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.security;
import static com.google.common.truth.Truth.assertThat;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.os.UserHandle;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowLockPatternUtils;
import com.android.settingslib.search.SearchIndexableRaw;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowLockPatternUtils.class)
public class ScreenPinningSettingsTest {
private Context mContext;
@Before
public void setUp() {
mContext = ApplicationProvider.getApplicationContext();
}
@After
public void tearDown() {
ShadowLockPatternUtils.reset();
}
@Test
public void getDynamicRawDataToIndex_numericPassword_shouldIndexUnlockPinTitle() {
ShadowLockPatternUtils.setKeyguardStoredPasswordQuality(
DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
final List<SearchIndexableRaw> indexRaws =
ScreenPinningSettings.SEARCH_INDEX_DATA_PROVIDER.getDynamicRawDataToIndex(
mContext, /* enabled= */ true);
assertThat(indexRaws.size()).isEqualTo(1);
assertThat(indexRaws.get(0).title).isEqualTo(
mContext.getString(R.string.screen_pinning_unlock_pin));
}
@Test
public void getDynamicRawDataToIndex_alphabeticPassword_shouldIndexUnlockPasswordTitle() {
ShadowLockPatternUtils.setKeyguardStoredPasswordQuality(
DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
final List<SearchIndexableRaw> indexRaws =
ScreenPinningSettings.SEARCH_INDEX_DATA_PROVIDER.getDynamicRawDataToIndex(
mContext, /* enabled= */ true);
assertThat(indexRaws.size()).isEqualTo(1);
assertThat(indexRaws.get(0).title).isEqualTo(
mContext.getString(R.string.screen_pinning_unlock_password));
}
@Test
public void getDynamicRawDataToIndex_patternPassword_shouldIndexUnlockPatternTitle() {
ShadowLockPatternUtils.setKeyguardStoredPasswordQuality(
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
ShadowLockPatternUtils.setIsLockPatternEnabled(
UserHandle.myUserId(), /* isLockPatternEnabled= */ true);
final List<SearchIndexableRaw> indexRaws =
ScreenPinningSettings.SEARCH_INDEX_DATA_PROVIDER.getDynamicRawDataToIndex(
mContext, /* enabled= */ true);
assertThat(indexRaws.size()).isEqualTo(1);
assertThat(indexRaws.get(0).title).isEqualTo(
mContext.getString(R.string.screen_pinning_unlock_pattern));
}
@Test
public void getDynamicRawDataToIndex_nonePassword_shouldIndexUnlockNoneTitle() {
ShadowLockPatternUtils.setKeyguardStoredPasswordQuality(
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
final List<SearchIndexableRaw> indexRaws =
ScreenPinningSettings.SEARCH_INDEX_DATA_PROVIDER.getDynamicRawDataToIndex(
mContext, /* enabled= */ true);
assertThat(indexRaws.size()).isEqualTo(1);
assertThat(indexRaws.get(0).title).isEqualTo(
mContext.getString(R.string.screen_pinning_unlock_none));
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.security;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.security.trustagent.TrustAgentManager;
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 SecurityFeatureProviderImplTest {
private Context mContext;
private SecurityFeatureProviderImpl mImpl;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mImpl = new SecurityFeatureProviderImpl();
}
@Test
public void getTrustAgentManager_shouldReturnCache() {
final TrustAgentManager m1 = mImpl.getTrustAgentManager();
final TrustAgentManager m2 = mImpl.getTrustAgentManager();
assertThat(m1).isSameInstanceAs(m2);
}
@Test
public void getLockPatternUtils_shouldReturnCache() {
final LockPatternUtils l1 = mImpl.getLockPatternUtils(mContext);
final LockPatternUtils l2 = mImpl.getLockPatternUtils(mContext);
assertThat(l1).isSameInstanceAs(l2);
}
}

View File

@@ -0,0 +1,98 @@
/*
* 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.security;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
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)
public class ShowPasswordPreferenceControllerTest {
@Mock
private PreferenceScreen mScreen;
private Context mContext;
private ShowPasswordPreferenceController mController;
private Preference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new ShowPasswordPreferenceController(mContext);
mPreference = new Preference(mContext);
mPreference.setKey(mController.getPreferenceKey());
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
}
@Test
public void isAvailable_byDefault_isTrue() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(qualifiers = "mcc999")
public void isAvailable_whenNotVisible_isFalse() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isChecked_settingIsOff_false() {
final ContentResolver contentResolver = mContext.getContentResolver();
Settings.System.putInt(contentResolver, Settings.System.TEXT_SHOW_PASSWORD, 0);
assertThat(mController.isChecked()).isFalse();
}
@Test
public void isChecked_settingIsOn_true() {
final ContentResolver contentResolver = mContext.getContentResolver();
Settings.System.putInt(contentResolver, Settings.System.TEXT_SHOW_PASSWORD, 1);
assertThat(mController.isChecked()).isTrue();
}
@Test
public void changePref_turnOn_shouldChangeSettingTo1() {
mController.onPreferenceChange(mPreference, true);
assertThat(mController.isChecked()).isTrue();
}
@Test
public void changePref_turnOff_shouldChangeSettingTo0() {
mController.onPreferenceChange(mPreference, false);
assertThat(mController.isChecked()).isFalse();
}
}

View File

@@ -0,0 +1,189 @@
/*
* 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.security;
import static android.telephony.TelephonyManager.SIM_STATE_READY;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.res.Resources;
import android.os.PersistableBundle;
import android.os.UserManager;
import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
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.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class SimLockPreferenceControllerTest {
@Mock
private SubscriptionManager mSubscriptionManager;
@Mock
private CarrierConfigManager mCarrierManager;
@Mock
private UserManager mUserManager;
@Mock
private TelephonyManager mTelephonyManager;
@Mock
private PreferenceScreen mScreen;
private SimLockPreferenceController mController;
private Preference mPreference;
private Context mContext;
private Resources mResources;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE,
mSubscriptionManager);
when(mSubscriptionManager.createForAllUserProfiles()).thenReturn(mSubscriptionManager);
shadowApplication.setSystemService(Context.CARRIER_CONFIG_SERVICE, mCarrierManager);
shadowApplication.setSystemService(Context.USER_SERVICE, mUserManager);
shadowApplication.setSystemService(Context.TELEPHONY_SERVICE, mTelephonyManager);
mContext = spy(RuntimeEnvironment.application);
mResources = spy(mContext.getResources());
when(mContext.getResources()).thenReturn(mResources);
mController = new SimLockPreferenceController(mContext, "key");
mPreference = new Preference(mContext);
mPreference.setKey(mController.getPreferenceKey());
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
}
@Test
public void isAvailable_notShowSimUi_false() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(false);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void isAvailable_notAdmin_false() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(true);
when(mUserManager.isAdminUser()).thenReturn(false);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
}
@Test
public void isAvailable_simIccNotReady_false() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(true);
when(mUserManager.isAdminUser()).thenReturn(true);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
}
@Test
public void isAvailable_carrierConfigDisabled_false() {
when(mUserManager.isAdminUser()).thenReturn(true);
setupMockIcc();
final PersistableBundle pb = new PersistableBundle();
pb.putBoolean(CarrierConfigManager.KEY_HIDE_SIM_LOCK_SETTINGS_BOOL, true);
when(mCarrierManager.getConfigForSubId(anyInt())).thenReturn(pb);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
}
@Test
public void isAvailable_true() {
when(mUserManager.isAdminUser()).thenReturn(true);
setupMockIcc();
final PersistableBundle pb = new PersistableBundle();
when(mCarrierManager.getConfigForSubId(anyInt())).thenReturn(pb);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void displayPreference_simReady_enablePreference() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(true);
mController.displayPreference(mScreen);
assertThat(mPreference.isEnabled()).isFalse();
}
@Test
public void displayPreference_simNotReady_disablePreference() {
setupMockSimReady();
mController.displayPreference(mScreen);
assertThat(mPreference.isEnabled()).isTrue();
}
@Test
public void getPreferenceKey_whenGivenValue_returnsGivenValue() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(true);
mController = new SimLockPreferenceController(mContext, "key");
assertThat(mController.getPreferenceKey()).isEqualTo("key");
}
private void setupMockIcc() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(true);
final List<SubscriptionInfo> subscriptionInfoList = new ArrayList<>();
SubscriptionInfo info = mock(SubscriptionInfo.class);
subscriptionInfoList.add(info);
when(mTelephonyManager.createForSubscriptionId(anyInt())).thenReturn(mTelephonyManager);
when(mTelephonyManager.hasIccCard()).thenReturn(true);
when(mSubscriptionManager.getActiveSubscriptionInfoList())
.thenReturn(subscriptionInfoList);
}
private void setupMockSimReady() {
when(mResources.getBoolean(R.bool.config_show_sim_info)).thenReturn(true);
final List<SubscriptionInfo> subscriptionInfoList = new ArrayList<>();
SubscriptionInfo info = mock(SubscriptionInfo.class);
subscriptionInfoList.add(info);
when(mTelephonyManager.getSimState(anyInt())).thenReturn(SIM_STATE_READY);
when(mSubscriptionManager.getActiveSubscriptionInfoList())
.thenReturn(subscriptionInfoList);
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2022 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.security;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentContainerView;
public final class TestActivity extends FragmentActivity {
static final int CONTAINER_VIEW_ID = 1234;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
FragmentContainerView contentView = new FragmentContainerView(this);
contentView.setId(CONTAINER_VIEW_ID);
setContentView(contentView);
}
}

View File

@@ -0,0 +1,135 @@
/*
* 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.security;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
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.anyInt;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.hardware.fingerprint.FingerprintManager;
import android.os.UserManager;
import androidx.lifecycle.LifecycleOwner;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.testutils.FakeFeatureFactory;
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.shadows.ShadowApplication;
import java.util.Arrays;
@RunWith(RobolectricTestRunner.class)
public class VisiblePatternProfilePreferenceControllerTest {
private static final int FAKE_PROFILE_USER_ID = 1234;
@Mock
private PackageManager mPackageManager;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private FingerprintManager mFingerprintManager;
@Mock
private UserManager mUm;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private FakeFeatureFactory mFeatureFactory;
private Context mContext;
private VisiblePatternProfilePreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)).thenReturn(true);
final ShadowApplication application = ShadowApplication.getInstance();
application.setSystemService(Context.FINGERPRINT_SERVICE, mFingerprintManager);
application.setSystemService(Context.USER_SERVICE, mUm);
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
.thenReturn(mLockPatternUtils);
when(mUm.getProfiles(anyInt())).thenReturn(Arrays.asList(new UserInfo(
FAKE_PROFILE_USER_ID, "", UserInfo.FLAG_MANAGED_PROFILE | UserInfo.FLAG_PROFILE)));
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
mController = new VisiblePatternProfilePreferenceController(mContext, mLifecycle);
}
@Test
public void getAvailabilityStatus_notSecure_DISABLED() {
when(mLockPatternUtils.isSecure(FAKE_PROFILE_USER_ID)).thenReturn(false);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(FAKE_PROFILE_USER_ID))
.thenReturn(PASSWORD_QUALITY_UNSPECIFIED);
assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
}
@Test
public void getAvailabilityStatus_secureWithPassword_DISABLED() {
when(mLockPatternUtils.isSecure(FAKE_PROFILE_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(FAKE_PROFILE_USER_ID))
.thenReturn(PASSWORD_QUALITY_ALPHABETIC);
assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
}
@Test
public void getAvailabilityStatus_secureWithPattern_AVAILABLE() {
when(mLockPatternUtils.isSecure(FAKE_PROFILE_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(FAKE_PROFILE_USER_ID))
.thenReturn(PASSWORD_QUALITY_SOMETHING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getPreferenceKey_byDefault_returnsDefaultValue() {
assertThat(mController.getPreferenceKey()).isEqualTo("visiblepattern_profile");
}
@Test
public void getPreferenceKey_whenGivenValue_returnsGivenValue() {
mController = new VisiblePatternProfilePreferenceController(mContext, mLifecycle, "key");
assertThat(mController.getPreferenceKey()).isEqualTo("key");
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2022 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.security;
import com.android.internal.os.Zygote;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
@Implements(Zygote.class)
public class ZygoteShadow {
private static boolean sSupportsMemoryTagging;
public static void setSupportsMemoryTagging(boolean value) {
sSupportsMemoryTagging = value;
}
@Implementation
public static boolean nativeSupportsMemoryTagging() {
return sSupportsMemoryTagging;
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (C) 2023 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.security.screenlock;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.preference.SwitchPreference;
import androidx.test.core.app.ApplicationProvider;
import com.android.internal.widget.LockPatternUtils;
import com.android.settingslib.core.lifecycle.ObservablePreferenceFragment;
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;
@RunWith(RobolectricTestRunner.class)
public class AutoPinConfirmPreferenceControllerTest {
private static final Integer TEST_USER_ID = 1;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private ObservablePreferenceFragment mParentFragment;
private AutoPinConfirmPreferenceController mController;
private SwitchPreference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Context context = ApplicationProvider.getApplicationContext();
mController =
new AutoPinConfirmPreferenceController(context, TEST_USER_ID, mLockPatternUtils,
mParentFragment);
mPreference = new SwitchPreference(context);
}
@Test
public void isAvailable_featureEnabledAndLockSetToNone_shouldReturnFalse() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_featureEnabledAndLockSetToPassword_shouldReturnFalse() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID))
.thenReturn(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_featureEnabledAndLockSetToPIN_lengthLessThanSix_shouldReturnFalse() {
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID))
.thenReturn(LockPatternUtils.CREDENTIAL_TYPE_PIN);
when(mLockPatternUtils.getPinLength(TEST_USER_ID)).thenReturn(5);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_featureEnabledAndLockSetToPIN_lengthMoreThanEqSix_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID))
.thenReturn(LockPatternUtils.CREDENTIAL_TYPE_PIN);
when(mLockPatternUtils.getPinLength(TEST_USER_ID)).thenReturn(6);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void updateState_ChangingSettingState_shouldSetPreferenceToAppropriateCheckedState() {
// When auto_pin_confirm setting is disabled, switchPreference is unchecked
when(mLockPatternUtils.isAutoPinConfirmEnabled(TEST_USER_ID)).thenReturn(false);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
// When auto_pin_confirm setting is enabled, switchPreference is checked
when(mLockPatternUtils.isAutoPinConfirmEnabled(TEST_USER_ID)).thenReturn(true);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
}
}

View File

@@ -0,0 +1,135 @@
/*
* 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.security.screenlock;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
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;
import static org.mockito.Mockito.when;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.display.TimeoutListPreference;
import com.android.settings.security.trustagent.TrustAgentManager;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowDevicePolicyManager;
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 java.util.Collections;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowDevicePolicyManager.class)
public class LockAfterTimeoutPreferenceControllerTest {
private static final int TEST_USER_ID = 0;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private TrustAgentManager mTrustAgentManager;
@Mock
private TimeoutListPreference mPreference;
private Context mContext;
private LockAfterTimeoutPreferenceController mController;
private FakeFeatureFactory mFeatureFactory;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
.thenReturn(mTrustAgentManager);
mController = new LockAfterTimeoutPreferenceController(
mContext, TEST_USER_ID, mLockPatternUtils);
}
@Test
public void isAvailable_lockSetToPattern_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(TEST_USER_ID))
.thenReturn(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToPin_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(TEST_USER_ID))
.thenReturn(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToPassword_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(TEST_USER_ID))
.thenReturn(DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToNone_shouldReturnFalse() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(false);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void testUpdateStateWithAdminTimeouts() {
final int userId = UserHandle.myUserId();
final long adminTimeout = 10000;
final int displayTimeout = 5000;
final UserManager um = mock(UserManager.class);
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(um);
when(um.getProfiles(userId)).thenReturn(Collections.emptyList());
// Fake list of timeout values.
when(mPreference.getEntries()).thenReturn(new CharSequence[] {"10"});
when(mPreference.getEntryValues()).thenReturn(new CharSequence[] {"10000"});
Settings.System.putInt(mContext.getContentResolver(), SCREEN_OFF_TIMEOUT, displayTimeout);
ShadowDevicePolicyManager.getShadow().setMaximumTimeToLock(userId, adminTimeout);
mController.updateState(mPreference);
verify(mPreference).removeUnusableTimeouts(adminTimeout - displayTimeout, null);
}
}

View File

@@ -0,0 +1,145 @@
/*
* 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.security.screenlock;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
import static androidx.lifecycle.Lifecycle.Event.ON_RESUME;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.os.UserManager;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.testutils.FakeFeatureFactory;
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.shadows.ShadowApplication;
@RunWith(RobolectricTestRunner.class)
public class LockScreenPreferenceControllerTest {
private static final int FAKE_PROFILE_USER_ID = 1234;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private UserManager mUm;
@Mock
private PreferenceScreen mScreen;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private FakeFeatureFactory mFeatureFactory;
private Context mContext;
private LockScreenPreferenceController mController;
private Preference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
.thenReturn(mLockPatternUtils);
when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {FAKE_PROFILE_USER_ID});
mPreference = new Preference(mContext);
when(mScreen.findPreference(anyString())).thenReturn(mPreference);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
mController = new LockScreenPreferenceController(mContext, "Test_key");
}
@Test
public void getAvailabilityStatus_notSecure_lockscreenDisabled_AVAILABLE() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(true);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_notSecure_lockscreenEnabled_AVAILABLE() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_secure_hasLockScreen_AVAILABLE() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
.thenReturn(PASSWORD_QUALITY_ALPHABETIC);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_secure_noLockScreen_AVAILABLE() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
.thenReturn(PASSWORD_QUALITY_UNSPECIFIED);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void onResume_available_shouldShow() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
.thenReturn(PASSWORD_QUALITY_ALPHABETIC);
mController.displayPreference(mScreen);
mLifecycle.handleLifecycleEvent(ON_RESUME);
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void onResume_unavailable_shouldShow() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
.thenReturn(PASSWORD_QUALITY_UNSPECIFIED);
mController.displayPreference(mScreen);
mLifecycle.handleLifecycleEvent(ON_RESUME);
assertThat(mPreference.isVisible()).isTrue();
}
}

View File

@@ -0,0 +1,98 @@
/*
* 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.security.screenlock;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.preference.SwitchPreference;
import com.android.internal.widget.LockPatternUtils;
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 PatternVisiblePreferenceControllerTest {
private static final int TEST_USER_ID = 0;
@Mock
private LockPatternUtils mLockPatternUtils;
private Context mContext;
private PatternVisiblePreferenceController mController;
private SwitchPreference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController =
new PatternVisiblePreferenceController(mContext, TEST_USER_ID, mLockPatternUtils);
mPreference = new SwitchPreference(mContext);
}
@Test
public void isAvailable_lockSetToPattern_shouldReturnTrue() {
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID))
.thenReturn(LockPatternUtils.CREDENTIAL_TYPE_PATTERN);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToPin_shouldReturnFalse() {
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID)).thenReturn(
LockPatternUtils.CREDENTIAL_TYPE_PIN);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_lockSetToNone_shouldReturnFalse() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(false);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void updateState_shouldSetPref() {
when(mLockPatternUtils.isVisiblePatternEnabled(TEST_USER_ID)).thenReturn(true);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
when(mLockPatternUtils.isVisiblePatternEnabled(TEST_USER_ID)).thenReturn(false);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void onPreferenceChange_shouldUpdateLockPatternUtils() {
mController.onPreferenceChange(mPreference, true /* newValue */);
verify(mLockPatternUtils).setVisiblePatternEnabled(true, TEST_USER_ID);
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (C) 2023 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.security.screenlock;
import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD_OR_PIN;
import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PATTERN;
import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PIN;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.preference.SwitchPreference;
import com.android.internal.widget.LockPatternUtils;
import org.junit.Before;
import org.junit.Ignore;
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 PinPrivacyPreferenceControllerTest {
private static final int TEST_USER_ID = 0;
@Mock
private LockPatternUtils mLockPatternUtils;
private Context mContext;
private PinPrivacyPreferenceController mController;
private SwitchPreference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController =
new PinPrivacyPreferenceController(mContext, TEST_USER_ID, mLockPatternUtils);
mPreference = new SwitchPreference(mContext);
}
@Test
public void isAvailable_lockSetToPin_shouldReturnTrue() {
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID)).thenReturn(
CREDENTIAL_TYPE_PIN);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToOther_shouldReturnFalse() {
when(mLockPatternUtils.getCredentialTypeForUser(TEST_USER_ID)).thenReturn(
CREDENTIAL_TYPE_PATTERN);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void updateState_shouldSetPref() {
when(mLockPatternUtils.isPinEnhancedPrivacyEnabled(TEST_USER_ID)).thenReturn(true);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void updateState_shouldSetPref_false() {
when(mLockPatternUtils.isPinEnhancedPrivacyEnabled(TEST_USER_ID)).thenReturn(false);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void onPreferenceChange_shouldUpdateLockPatternUtils() {
mController.onPreferenceChange(mPreference, true);
verify(mLockPatternUtils).setPinEnhancedPrivacyEnabled(true, TEST_USER_ID);
}
@Test
public void getPreferenceKey_returnsConst() {
assertThat(mController.getPreferenceKey().equals("enhancedPinPrivacy")).isTrue();
}
}

View File

@@ -0,0 +1,131 @@
/*
* 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.security.screenlock;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import androidx.preference.SwitchPreference;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.security.trustagent.TrustAgentManager;
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.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class PowerButtonInstantLockPreferenceControllerTest {
private static final int TEST_USER_ID = 0;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private TrustAgentManager mTrustAgentManager;
private Context mContext;
private PowerButtonInstantLockPreferenceController mController;
private SwitchPreference mPreference;
private FakeFeatureFactory mFeatureFactory;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
.thenReturn(mTrustAgentManager);
mPreference = new SwitchPreference(mContext);
mController = new PowerButtonInstantLockPreferenceController(
mContext, TEST_USER_ID, mLockPatternUtils);
}
@Test
public void isAvailable_lockSetToPattern_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(TEST_USER_ID))
.thenReturn(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToPin_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(TEST_USER_ID))
.thenReturn(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToPassword_shouldReturnTrue() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(true);
when(mLockPatternUtils.getKeyguardStoredPasswordQuality(TEST_USER_ID))
.thenReturn(DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_lockSetToNone_shouldReturnFalse() {
when(mLockPatternUtils.isSecure(TEST_USER_ID)).thenReturn(false);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void updateState_shouldSetPref() {
final String fakeTrustAgent = "trust_agent";
when(mTrustAgentManager.getActiveTrustAgentLabel(mContext, mLockPatternUtils))
.thenReturn(fakeTrustAgent);
when(mLockPatternUtils.getPowerButtonInstantlyLocks(TEST_USER_ID)).thenReturn(true);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
assertThat(mPreference.getSummary()).isEqualTo(mContext.getString(
R.string.lockpattern_settings_power_button_instantly_locks_summary,
fakeTrustAgent));
when(mTrustAgentManager.getActiveTrustAgentLabel(mContext, mLockPatternUtils))
.thenReturn(null);
when(mLockPatternUtils.getPowerButtonInstantlyLocks(TEST_USER_ID)).thenReturn(false);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
assertThat(mPreference.getSummary()).isEqualTo(mContext.getString(
com.android.settingslib.R.string.summary_empty));
}
@Test
public void onPreferenceChange_shouldUpdateLockPatternUtils() {
mController.onPreferenceChange(mPreference, true /* newValue */);
verify(mLockPatternUtils).setPowerButtonInstantlyLocks(true, TEST_USER_ID);
}
}

View File

@@ -0,0 +1,69 @@
/*
* 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.security.screenlock;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
import com.android.settings.security.OwnerInfoPreferenceController;
import com.android.settingslib.core.AbstractPreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RunWith(RobolectricTestRunner.class)
public class ScreenLockSettingsTest {
private ScreenLockSettings mSettings;
@Before
public void setUp() {
mSettings = new ScreenLockSettings();
}
@Test
public void verifyConstants() {
assertThat(mSettings.getMetricsCategory())
.isEqualTo(MetricsProto.MetricsEvent.SCREEN_LOCK_SETTINGS);
assertThat(mSettings.getPreferenceScreenResId()).isEqualTo(R.xml.screen_lock_settings);
}
@Test
public void onOwnerInfoUpdated_shouldUpdateOwnerInfoController() {
final Map<Class, List<AbstractPreferenceController>> preferenceControllers =
ReflectionHelpers.getField(mSettings, "mPreferenceControllers");
final OwnerInfoPreferenceController controller = mock(OwnerInfoPreferenceController.class);
List<AbstractPreferenceController> controllerList = new ArrayList<>();
controllerList.add(controller);
preferenceControllers.put(OwnerInfoPreferenceController.class, controllerList);
mSettings.onOwnerInfoUpdated();
verify(controller).updateSummary();
}
}

View File

@@ -0,0 +1,128 @@
/*
* 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.security.trustagent;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
import android.content.Context;
import androidx.preference.Preference;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.security.trustagent.TrustAgentManager.TrustAgentComponentInfo;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.utils.StringUtil;
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 java.util.ArrayList;
import java.util.Collections;
@RunWith(RobolectricTestRunner.class)
public class ManageTrustAgentsPreferenceControllerTest {
@Mock
private TrustAgentManager mTrustAgentManager;
@Mock
private LockPatternUtils mLockPatternUtils;
private FakeFeatureFactory mFeatureFactory;
private Context mContext;
private ManageTrustAgentsPreferenceController mController;
private Preference mPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
.thenReturn(mLockPatternUtils);
when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
.thenReturn(mTrustAgentManager);
mController = new ManageTrustAgentsPreferenceController(mContext, "key");
mPreference = new Preference(mContext);
mPreference.setKey(mController.getPreferenceKey());
}
@Test
public void isAvailable_byDefault_isTrue() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(qualifiers = "mcc999")
public void isAvailable_whenNotVisible_isFalse() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void updateState_isNotSecure_shouldDisablePreference() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
mController.updateState(mPreference);
assertThat(mPreference.isEnabled()).isFalse();
assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.disabled_because_no_backup_security));
}
@Test
public void updateState_isSecure_noTrustAgent_shouldShowGenericSummary() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.thenReturn(new ArrayList<>());
mController.updateState(mPreference);
assertThat(mPreference.isEnabled()).isTrue();
assertThat(mPreference.getSummary())
.isEqualTo(mContext.getString(R.string.manage_trust_agents_summary));
}
@Test
public void updateState_isSecure_hasTrustAgent_shouldShowDetailedSummary() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.thenReturn(Collections.singletonList(new TrustAgentComponentInfo()));
mController.updateState(mPreference);
assertThat(mPreference.isEnabled()).isTrue();
assertThat(mPreference.getSummary())
.isEqualTo(StringUtil.getIcuPluralsString(mContext, 1,
R.string.manage_trust_agents_summary_on));
}
@Test
public void getPreferenceKey_whenGivenValue_returnsGivenValue() {
mController = new ManageTrustAgentsPreferenceController(mContext, "key");
assertThat(mController.getPreferenceKey()).isEqualTo("key");
}
}

View File

@@ -0,0 +1,211 @@
/*
* 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.security.trustagent;
import static com.android.settings.security.trustagent.TrustAgentListPreferenceController.PREF_KEY_SECURITY_CATEGORY;
import static com.android.settings.security.trustagent.TrustAgentListPreferenceController.PREF_KEY_TRUST_AGENT;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
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.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.security.SecuritySettings;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.core.lifecycle.Lifecycle;
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.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class TrustAgentListPreferenceControllerTest {
@Mock
private TrustAgentManager mTrustAgentManager;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private PreferenceScreen mScreen;
@Mock
private PreferenceCategory mCategory;
@Mock
private SecuritySettings mFragment;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private FakeFeatureFactory mFeatureFactory;
private Activity mActivity;
private TrustAgentListPreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mActivity = Robolectric.buildActivity(Activity.class).get();
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(any(Context.class)))
.thenReturn(mLockPatternUtils);
when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
.thenReturn(mTrustAgentManager);
when(mCategory.getKey()).thenReturn(PREF_KEY_SECURITY_CATEGORY);
when(mCategory.getContext()).thenReturn(mActivity);
when(mScreen.findPreference(PREF_KEY_SECURITY_CATEGORY)).thenReturn(mCategory);
mController = new TrustAgentListPreferenceController(mActivity, mFragment, mLifecycle);
}
@Test
public void testConstants() {
assertThat(mController.isAvailable()).isTrue();
assertThat(mController.getPreferenceKey()).isEqualTo(PREF_KEY_TRUST_AGENT);
assertThat(mController).isInstanceOf(PreferenceControllerMixin.class);
}
@Test
@Config(qualifiers = "mcc999")
public void isAvailable_whenNotVisible_isFalse() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void onResume_shouldClearOldAgents() {
final Preference oldAgent = new Preference(mActivity);
oldAgent.setKey(PREF_KEY_TRUST_AGENT + 0);
when(mCategory.findPreference(PREF_KEY_TRUST_AGENT + 0))
.thenReturn(oldAgent)
.thenReturn(null);
final List<TrustAgentManager.TrustAgentComponentInfo> agents = new ArrayList<>();
final TrustAgentManager.TrustAgentComponentInfo agent =
mock(TrustAgentManager.TrustAgentComponentInfo.class);
agent.title = "Test_title";
agent.summary = "test summary";
agent.componentName = new ComponentName("pkg", "agent");
agent.admin = null;
agents.add(agent);
when(mTrustAgentManager.getActiveTrustAgents(mActivity, mLockPatternUtils))
.thenReturn(agents);
mController.displayPreference(mScreen);
mController.onResume();
verify(mCategory).removePreference(oldAgent);
}
@Test
public void onResume_shouldAddNewAgents() {
final List<TrustAgentManager.TrustAgentComponentInfo> agents = new ArrayList<>();
final TrustAgentManager.TrustAgentComponentInfo agent =
mock(TrustAgentManager.TrustAgentComponentInfo.class);
agent.title = "Test_title";
agent.summary = "test summary";
agent.componentName = new ComponentName("pkg", "agent");
agent.admin = null;
agents.add(agent);
when(mTrustAgentManager.getActiveTrustAgents(mActivity, mLockPatternUtils))
.thenReturn(agents);
mController.displayPreference(mScreen);
mController.onResume();
verify(mCategory, atLeastOnce()).addPreference(any(Preference.class));
}
@Test
@Config(qualifiers = "mcc999")
public void onResume_ifNotAvailable_shouldNotAddNewAgents() {
final List<TrustAgentManager.TrustAgentComponentInfo> agents = new ArrayList<>();
final TrustAgentManager.TrustAgentComponentInfo agent =
mock(TrustAgentManager.TrustAgentComponentInfo.class);
agent.title = "Test_title";
agent.summary = "test summary";
agent.componentName = new ComponentName("pkg", "agent");
agent.admin = null;
agents.add(agent);
when(mTrustAgentManager.getActiveTrustAgents(mActivity, mLockPatternUtils))
.thenReturn(agents);
mController.displayPreference(mScreen);
mController.onResume();
verify(mCategory, never()).addPreference(any(Preference.class));
}
@Test
public void onResume_controllerShouldHasKey() {
final List<TrustAgentManager.TrustAgentComponentInfo> agents = new ArrayList<>();
final TrustAgentManager.TrustAgentComponentInfo agent =
mock(TrustAgentManager.TrustAgentComponentInfo.class);
agent.title = "Test_title";
agent.summary = "test summary";
agent.componentName = new ComponentName("pkg", "agent");
agent.admin = null;
agents.add(agent);
when(mTrustAgentManager.getActiveTrustAgents(mActivity, mLockPatternUtils))
.thenReturn(agents);
final String key = PREF_KEY_TRUST_AGENT + 0;
mController.displayPreference(mScreen);
mController.onResume();
assertThat(mController.mTrustAgentsKeyList).containsExactly(key);
}
@Test
public void updateDynamicRawDataToIndex_shouldIndexAgents() {
final List<TrustAgentManager.TrustAgentComponentInfo> agents = new ArrayList<>();
final TrustAgentManager.TrustAgentComponentInfo agent =
mock(TrustAgentManager.TrustAgentComponentInfo.class);
agent.title = "Test_title";
agent.summary = "test summary";
agent.componentName = new ComponentName("pkg", "agent");
agent.admin = null;
agents.add(agent);
when(mTrustAgentManager.getActiveTrustAgents(mActivity, mLockPatternUtils))
.thenReturn(agents);
final List<SearchIndexableRaw> indexRaws = new ArrayList<>();
mController.updateDynamicRawDataToIndex(indexRaws);
assertThat(indexRaws).hasSize(1);
}
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.security.trustagent;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.when;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.os.UserManager;
import android.service.trust.TrustAgentService;
import com.android.internal.widget.LockPatternUtils;
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.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class TrustAgentManagerTest {
private static final String CANNED_PACKAGE_NAME = "com.test.package";
private static final String CANNED_CLASS_NAME = "TestTrustAgent";
private static final String CANNED_TRUST_AGENT_TITLE = "TestTrustAgentTitle";
@Mock
private PackageManager mPackageManager;
@Mock
private Context mContext;
@Mock
private DevicePolicyManager mDevicePolicyManager;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private UserManager mUserManager;
@Mock
private UserInfo mUserInfo;
@Mock
private XmlResourceParser mXmlResourceParser;
@Mock
private Resources mResources;
@Mock
private TypedArray mTypedArray;
private TrustAgentManager mTrustAgentManager;
@Before
public void setUp() throws NameNotFoundException {
MockitoAnnotations.initMocks(this);
mTrustAgentManager = new TrustAgentManager();
when(mContext.getSystemService(DevicePolicyManager.class))
.thenReturn(mDevicePolicyManager);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mContext.getSystemService(Context.USER_SERVICE))
.thenReturn(mUserManager);
when(mResources.obtainAttributes(any(), any())).thenReturn(mTypedArray);
when(mPackageManager.getResourcesForApplication(any(ApplicationInfo.class)))
.thenReturn(mResources);
when(mPackageManager.getXml(any(), anyInt(), any())).thenReturn(mXmlResourceParser);
when(mUserManager.getUserInfo(anyInt())).thenReturn(mUserInfo);
}
@Test
public void shouldProvideTrust_doesProvideTrustWithPermission() {
when(mPackageManager.checkPermission(TrustAgentManager.PERMISSION_PROVIDE_AGENT,
CANNED_PACKAGE_NAME)).thenReturn(PackageManager.PERMISSION_GRANTED);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.packageName = CANNED_PACKAGE_NAME;
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
assertThat(mTrustAgentManager.shouldProvideTrust(resolveInfo, mPackageManager)).isTrue();
}
@Test
public void shouldProvideTrust_doesNotProvideTrustWithoutPermission() {
when(mPackageManager.checkPermission(TrustAgentManager.PERMISSION_PROVIDE_AGENT,
CANNED_PACKAGE_NAME)).thenReturn(PackageManager.PERMISSION_DENIED);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.packageName = CANNED_PACKAGE_NAME;
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
assertThat(mTrustAgentManager.shouldProvideTrust(resolveInfo, mPackageManager)).isFalse();
}
@Test
public void getAllActiveTrustAgentsAndComponentSet_returnsTrustAgents()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(true);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.isNotEmpty();
}
@Test
public void getActiveTrustAgentsAndComponentSet_componentSet_returnsTrustAgents()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(true);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, true))
.isNotEmpty();
}
@Test
public void getAllActiveTrustAgentsAndComponentNotSet_returnsTrustAgents()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(false);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.isNotEmpty();
}
@Test
public void getActiveTrustAgentsAndComponentSet_returnsEmpty()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(false);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, true))
.isEmpty();
}
private void setUpGetActiveTrustAgents(boolean hasSettingsActivity)
throws XmlPullParserException, IOException {
String settingsActivity =
hasSettingsActivity ? CANNED_PACKAGE_NAME + "." + CANNED_CLASS_NAME : "";
when(mXmlResourceParser.next()).thenReturn(XmlPullParser.START_TAG);
when(mXmlResourceParser.getName()).thenReturn("trust-agent");
List<ResolveInfo> resolveInfos =
Collections.singletonList(createResolveInfo(hasSettingsActivity));
List<ComponentName> enabledTrustAgents =
Collections.singletonList(
new ComponentName(CANNED_PACKAGE_NAME, CANNED_CLASS_NAME));
when(mPackageManager.queryIntentServices(any(), anyInt())).thenReturn(resolveInfos);
when(mLockPatternUtils.getEnabledTrustAgents(anyInt())).thenReturn(enabledTrustAgents);
when(mUserInfo.isManagedProfile()).thenReturn(false);
when(mUserManager.getProfiles(anyInt())).thenReturn(null);
when(mPackageManager.checkPermission(TrustAgentManager.PERMISSION_PROVIDE_AGENT,
CANNED_PACKAGE_NAME)).thenReturn(PackageManager.PERMISSION_GRANTED);
when(mTypedArray.getString(com.android.internal.R.styleable.TrustAgent_title))
.thenReturn(CANNED_TRUST_AGENT_TITLE);
when(mTypedArray.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity))
.thenReturn(settingsActivity);
}
private ResolveInfo createResolveInfo(boolean hasSettingsActivity) {
ServiceInfo serviceInfo = new ServiceInfo();
Bundle metaData = new Bundle();
metaData.putInt(TrustAgentService.TRUST_AGENT_META_DATA, 1);
serviceInfo.packageName = CANNED_PACKAGE_NAME;
serviceInfo.name = CANNED_CLASS_NAME;
serviceInfo.metaData = metaData;
serviceInfo.applicationInfo = new ApplicationInfo();
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
return resolveInfo;
}
}

View File

@@ -0,0 +1,241 @@
/*
* 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.security.trustagent;
import static com.google.common.truth.Truth.assertThat;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.service.trust.TrustAgentService;
import android.text.TextUtils;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.testutils.shadow.ShadowDevicePolicyManager;
import com.android.settings.testutils.shadow.ShadowLockPatternUtils;
import com.android.settings.testutils.shadow.ShadowRestrictedLockUtilsInternal;
import com.android.settingslib.RestrictedSwitchPreference;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowApplicationPackageManager;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {
ShadowLockPatternUtils.class,
ShadowRestrictedLockUtilsInternal.class,
ShadowDevicePolicyManager.class,
ShadowApplicationPackageManager.class,
TrustAgentsPreferenceControllerTest.ShadowTrustAgentManager.class
})
public class TrustAgentsPreferenceControllerTest {
private static final Intent TEST_INTENT =
new Intent(TrustAgentService.SERVICE_INTERFACE);
private Context mContext;
private ShadowApplicationPackageManager mPackageManager;
private TrustAgentsPreferenceController mController;
private PreferenceManager mPreferenceManager;
private PreferenceScreen mPreferenceScreen;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mPackageManager = (ShadowApplicationPackageManager) Shadows.shadowOf(
mContext.getPackageManager());
mController = new TrustAgentsPreferenceController(mContext, "pref_key");
mPreferenceManager = new PreferenceManager(mContext);
mPreferenceScreen = mPreferenceManager.createPreferenceScreen(mContext);
mPreferenceScreen.setKey("pref_key");
}
@After
public void tearDown() {
ShadowTrustAgentManager.clearPermissionGrantedList();
}
@Test
public void getAvailabilityStatus_byDefault_shouldBeShown() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void onStart_noTrustAgent_shouldNotAddPreference() {
final List<ResolveInfo> availableAgents = createFakeAvailableAgents();
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
mController.displayPreference(mPreferenceScreen);
mController.onStart();
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(0);
}
@Ignore("b/313612480")
@Test
public void
onStart_hasAUninstalledTrustAgent_shouldRemoveOnePreferenceAndLeaveTwoPreferences() {
final List<ResolveInfo> availableAgents = createFakeAvailableAgents();
final ResolveInfo uninstalledTrustAgent = availableAgents.get(0);
for (ResolveInfo rInfo : availableAgents) {
ShadowTrustAgentManager.grantPermissionToResolveInfo(rInfo);
}
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
mController.displayPreference(mPreferenceScreen);
mController.onStart();
availableAgents.remove(uninstalledTrustAgent);
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
mController.onStart();
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(2);
}
@Ignore("b/313612480")
@Test
public void onStart_hasANewTrustAgent_shouldAddOnePreferenceAndHaveFourPreferences() {
final List<ResolveInfo> availableAgents = createFakeAvailableAgents();
final ComponentName newComponentName = new ComponentName("test.data.packageD", "clzDDD");
final ResolveInfo newTrustAgent = createFakeResolveInfo(newComponentName);
for (ResolveInfo rInfo : availableAgents) {
ShadowTrustAgentManager.grantPermissionToResolveInfo(rInfo);
}
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
mController.displayPreference(mPreferenceScreen);
mController.onStart();
availableAgents.add(newTrustAgent);
ShadowTrustAgentManager.grantPermissionToResolveInfo(newTrustAgent);
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
mController.onStart();
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(4);
}
@Ignore("b/313612480")
@Test
public void onStart_hasUnrestrictedTrustAgent_shouldAddThreeChangeablePreferences() {
ShadowRestrictedLockUtilsInternal.setKeyguardDisabledFeatures(0);
final List<ResolveInfo> availableAgents = createFakeAvailableAgents();
for (ResolveInfo rInfo : availableAgents) {
ShadowTrustAgentManager.grantPermissionToResolveInfo(rInfo);
}
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
mController.displayPreference(mPreferenceScreen);
mController.onStart();
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(3);
for (int i = 0; i < mPreferenceScreen.getPreferenceCount(); i++) {
RestrictedSwitchPreference preference =
(RestrictedSwitchPreference) mPreferenceScreen.getPreference(i);
assertThat(preference.isDisabledByAdmin()).isFalse();
}
}
@Ignore("b/313612480")
@Test
public void onStart_hasRestrictedTructAgent_shouldAddThreeUnchangeablePreferences() {
final List<ResolveInfo> availableAgents = createFakeAvailableAgents();
for (ResolveInfo rInfo : availableAgents) {
ShadowTrustAgentManager.grantPermissionToResolveInfo(rInfo);
}
mPackageManager.setResolveInfosForIntent(TEST_INTENT, availableAgents);
ShadowRestrictedLockUtilsInternal.setKeyguardDisabledFeatures(
DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS);
mController.displayPreference(mPreferenceScreen);
mController.onStart();
assertThat(mPreferenceScreen.getPreferenceCount()).isEqualTo(3);
for (int i = 0; i < mPreferenceScreen.getPreferenceCount(); i++) {
RestrictedSwitchPreference preference =
(RestrictedSwitchPreference) mPreferenceScreen.getPreference(i);
assertThat(preference.isDisabledByAdmin()).isTrue();
}
}
private List<ResolveInfo> createFakeAvailableAgents() {
final List<ComponentName> componentNames = new ArrayList<>();
componentNames.add(new ComponentName("test.data.packageA", "clzAAA"));
componentNames.add(new ComponentName("test.data.packageB", "clzBBB"));
componentNames.add(new ComponentName("test.data.packageC", "clzCCC"));
final List<ResolveInfo> result = new ArrayList<>();
for (ComponentName cn : componentNames) {
final ResolveInfo ri = createFakeResolveInfo(cn);
result.add(ri);
}
return result;
}
private ResolveInfo createFakeResolveInfo(ComponentName cn) {
final ResolveInfo ri = new ResolveInfo();
ri.serviceInfo = new ServiceInfo();
ri.serviceInfo.packageName = cn.getPackageName();
ri.serviceInfo.name = cn.getClassName();
ri.serviceInfo.applicationInfo = new ApplicationInfo();
ri.serviceInfo.applicationInfo.packageName = cn.getPackageName();
ri.serviceInfo.applicationInfo.name = cn.getClassName();
return ri;
}
@Implements(TrustAgentManager.class)
public static class ShadowTrustAgentManager {
private final static List<ResolveInfo> sPermissionGrantedList = new ArrayList<>();
@Implementation
protected boolean shouldProvideTrust(ResolveInfo resolveInfo, PackageManager pm) {
for (ResolveInfo info : sPermissionGrantedList) {
if (info.serviceInfo.equals(resolveInfo.serviceInfo)) {
return true;
}
}
return false;
}
private static void grantPermissionToResolveInfo(ResolveInfo rInfo) {
sPermissionGrantedList.add(rInfo);
}
private static void clearPermissionGrantedList() {
sPermissionGrantedList.clear();
}
}
}