feat: SettingsLib验证通过-使用App module启用

This commit is contained in:
2024-12-09 16:04:49 +08:00
parent 1f18a59dab
commit a7f5c61005
1562 changed files with 181632 additions and 18 deletions

View File

@@ -0,0 +1,85 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.enterprise.ActionDisabledByAdminActivity.FRAGMENT_TAG;
import static com.google.common.truth.Truth.assertThat;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.Intent;
import androidx.fragment.app.FragmentManager;
import androidx.test.rule.ActivityTestRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
public class ActionDisabledByAdminActivityTest extends BaseEnterpriseTestCase {
private static final String RESTRICTION_STRING = "RESTRICTION_STRING";
private FragmentManager mFragmentManager;
private ActionDisabledByAdminDialogFragment mFragment;
@Rule
public ActivityTestRule<ActionDisabledByAdminActivity> mActivityTestRule =
new ActivityTestRule<>(ActionDisabledByAdminActivity.class, true, false);
@Before
public void setUp() throws Throwable {
MockitoAnnotations.initMocks(this);
mockNullEnforcedAdmin(RESTRICTION_STRING, 0);
mockNullEnforcedAdmin(RESTRICTION_STRING, mRealContext.getUserId());
}
@Test
public void onCreate_showDialog() {
mActivityTestRule.launchActivity(getIntent(false));
mFragmentManager = mActivityTestRule.getActivity().getSupportFragmentManager();
mFragment = (ActionDisabledByAdminDialogFragment)
mFragmentManager.findFragmentByTag(FRAGMENT_TAG);
assertThat(mFragment).isNotNull();
AlertDialog dialog = (AlertDialog) mFragment.getDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
}
@Test
public void onCreate_readsIntentRestriction() {
mActivityTestRule.launchActivity(getIntent(true));
mFragmentManager = mActivityTestRule.getActivity().getSupportFragmentManager();
mFragment = (ActionDisabledByAdminDialogFragment)
mFragmentManager.findFragmentByTag(FRAGMENT_TAG);
assertThat(mFragment).isNotNull();
assertThat(mFragment.mRestriction).isEqualTo(RESTRICTION_STRING);
}
private Intent getIntent(boolean hasRestrictionFlag) {
Intent intent = new Intent(mSpiedContext, ActionDisabledByAdminActivity.class);
if (hasRestrictionFlag) {
intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, RESTRICTION_STRING);
}
return intent;
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
public final class AdminGrantedCameraPermissionApplicationListPreferenceControllerTest extends
BaseAdminGrantedPermissionsApplicationListPreferenceControllerTestCase
<AdminGrantedCameraPermissionApplicationListPreferenceController> {
public AdminGrantedCameraPermissionApplicationListPreferenceControllerTest() {
super(EnterpriseUtils.CAMERA_PERMISSIONS);
}
@Override
protected AdminGrantedCameraPermissionApplicationListPreferenceController newController(
ApplicationFeatureProvider provider) {
return new AdminGrantedCameraPermissionApplicationListPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
public final class AdminGrantedCameraPermissionPreferenceControllerTest extends
BaseAdminGrantedPermissionsPreferenceControllerTestCase
<AdminGrantedCameraPermissionPreferenceController> {
public AdminGrantedCameraPermissionPreferenceControllerTest() {
super(EnterpriseUtils.CAMERA_PERMISSIONS);
}
@Override
protected AdminGrantedCameraPermissionPreferenceController newController(
ApplicationFeatureProvider provider) {
return new AdminGrantedCameraPermissionPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions, provider);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
public final class AdminGrantedLocationPermissionsApplicationListPreferenceControllerTest extends
BaseAdminGrantedPermissionsApplicationListPreferenceControllerTestCase
<AdminGrantedLocationPermissionsApplicationListPreferenceController> {
public AdminGrantedLocationPermissionsApplicationListPreferenceControllerTest() {
super(EnterpriseUtils.LOCATION_PERMISSIONS);
}
@Override
protected AdminGrantedLocationPermissionsApplicationListPreferenceController newController(
ApplicationFeatureProvider provider) {
return new AdminGrantedLocationPermissionsApplicationListPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
public final class AdminGrantedLocationPermissionsPreferenceControllerTest
extends BaseAdminGrantedPermissionsPreferenceControllerTestCase
<AdminGrantedLocationPermissionsPreferenceController> {
public AdminGrantedLocationPermissionsPreferenceControllerTest() {
super(EnterpriseUtils.LOCATION_PERMISSIONS);
}
@Override
protected AdminGrantedLocationPermissionsPreferenceController newController(
ApplicationFeatureProvider provider) {
return new AdminGrantedLocationPermissionsPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
public final class AdminGrantedMicrophonePermissionApplicationListPreferenceControllerTest extends
BaseAdminGrantedPermissionsApplicationListPreferenceControllerTestCase
<AdminGrantedMicrophonePermissionApplicationListPreferenceController> {
public AdminGrantedMicrophonePermissionApplicationListPreferenceControllerTest() {
super(EnterpriseUtils.MICROPHONE_PERMISSIONS);
}
@Override
protected AdminGrantedMicrophonePermissionApplicationListPreferenceController newController(
ApplicationFeatureProvider provider) {
return new AdminGrantedMicrophonePermissionApplicationListPreferenceController(
mSpiedContext, mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
public final class AdminGrantedMicrophonePermissionPreferenceControllerTest
extends BaseAdminGrantedPermissionsPreferenceControllerTestCase
<AdminGrantedMicrophonePermissionPreferenceController> {
public AdminGrantedMicrophonePermissionPreferenceControllerTest() {
super(EnterpriseUtils.MICROPHONE_PERMISSIONS);
}
@Override
protected AdminGrantedMicrophonePermissionPreferenceController newController(
ApplicationFeatureProvider provider) {
return new AdminGrantedMicrophonePermissionPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
}

View File

@@ -0,0 +1,171 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
import android.net.VpnManager;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class AlwaysOnVpnCurrentUserPreferenceControllerTest extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private AlwaysOnVpnCurrentUserPreferenceController mAlwaysOnVpnCurrentUserPreferenceController;
private Preference mPreference;
@Mock
private VpnManager mVpnManager;
@Before
public void setUp() {
when(mSpiedContext.getSystemService(VpnManager.class)).thenReturn(mVpnManager);
mockHasDeviceAdminFeature();
mPreference = new Preference(mSpiedContext);
mAlwaysOnVpnCurrentUserPreferenceController =
new AlwaysOnVpnCurrentUserPreferenceController(
mSpiedContext, mPreferenceKey, mFragmentController, mUxRestrictions);
}
@Test
public void testAlwaysOnVpnPackageSet_preferenceEnabled() {
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn("com.test");
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(), AVAILABLE);
}
@Test
public void testAlwaysOnVpnPackageSet_preferenceEnabled_zoneWrite() {
mAlwaysOnVpnCurrentUserPreferenceController.setAvailabilityStatusForZone("write");
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn("com.test");
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(), AVAILABLE);
}
@Test
public void testAlwaysOnVpnPackageSet_preferenceEnabled_zoneRead() {
mAlwaysOnVpnCurrentUserPreferenceController.setAvailabilityStatusForZone("read");
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn("com.test");
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testAlwaysOnVpnPackageSet_preferenceEnabled_zoneHidden() {
mAlwaysOnVpnCurrentUserPreferenceController.setAvailabilityStatusForZone("hidden");
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn("com.test");
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testAlwaysOnVpnPackageNotSet_preferenceDisabled() {
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn(null);
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testAlwaysOnVpnPackageNotSet_preferenceDisabled_zoneWrite() {
mAlwaysOnVpnCurrentUserPreferenceController.setAvailabilityStatusForZone("write");
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn(null);
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testAlwaysOnVpnPackageNotSet_preferenceDisabled_zoneRead() {
mAlwaysOnVpnCurrentUserPreferenceController.setAvailabilityStatusForZone("read");
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn(null);
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testAlwaysOnVpnPackageNotSet_preferenceDisabled_zoneHidden() {
mAlwaysOnVpnCurrentUserPreferenceController.setAvailabilityStatusForZone("hidden");
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn(null);
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mAlwaysOnVpnCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testNoCompMode_showsRegularTitle() {
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn("com.test");
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
assertThat(mPreference.getTitle()).isEqualTo(mRealContext.getResources()
.getString(R.string.enterprise_privacy_always_on_vpn_device));
}
@Test
public void testCompMode_showsPersonalProfileTitle() {
mockCompMode();
when(mVpnManager.getAlwaysOnVpnPackageForUser(anyInt())).thenReturn("com.test");
mAlwaysOnVpnCurrentUserPreferenceController.updateState(mPreference);
assertThat(mPreference.getTitle()).isEqualTo(mRealContext.getResources()
.getString(R.string.enterprise_privacy_always_on_vpn_personal));
}
}

View File

@@ -0,0 +1,257 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import android.content.pm.UserInfo;
import android.graphics.drawable.Drawable;
import android.util.ArrayMap;
import android.util.Log;
import androidx.preference.PreferenceGroup;
import androidx.test.annotation.UiThreadTest;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
import com.android.car.settingslib.applications.ApplicationFeatureProvider.ListOfAppsCallback;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
abstract class BaseAdminGrantedPermissionsApplicationListPreferenceControllerTestCase
<C extends BaseAdminGrantedPermissionsApplicationListPreferenceController>
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String TAG =
BaseAdminGrantedPermissionsApplicationListPreferenceControllerTestCase.class
.getSimpleName();
private static final UserInfo DEFAULT_USER_INFO = new UserInfo(42, "Groot", /* flags= */ 0);
private static final Map<CharSequence, Drawable> ICONS_BY_LABEL = new ArrayMap<>();
// Must be a spy to verify refreshUi() is called
private C mSpiedController;
protected final String[] mPermissions;
private DummyPreferenceGroup mPreferenceGroup;
BaseAdminGrantedPermissionsApplicationListPreferenceControllerTestCase(String... permissions) {
mPermissions = permissions;
}
@Before
@UiThreadTest // Needed to instantiate DummyPreferenceGroup
public void setExtraFixtures() {
mSpiedController = spy(newController(mApplicationFeatureProvider));
mPreferenceGroup = new DummyPreferenceGroup(mSpiedContext);
}
protected abstract C newController(ApplicationFeatureProvider provider);
@Test
public void testGetPreferenceType() {
assertWithMessage("preference type").that(mSpiedController.getPreferenceType())
.isEqualTo(PreferenceGroup.class);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted() {
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted_zoneWrite() {
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted_zoneRead() {
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted_zoneHidden() {
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted_zoneWrite() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted_zoneRead() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted_zoneHidden() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testUpdateState() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListAppsWithAdminGrantedPermissions();
mSpiedController.getAvailabilityStatus();
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
assertUiRefreshed(mSpiedController);
mSpiedController.updateState(mPreferenceGroup);
assertPreferenceGroupStateSet(mPreferenceGroup, "foo", "bar");
}
private ListOfAppsCallbackHolder mockListAppsWithAdminGrantedPermissions() {
ListOfAppsCallbackHolder callbackHolder = new ListOfAppsCallbackHolder();
doAnswer((inv) -> {
Log.d(TAG, "answering to " + inv);
ListOfAppsCallback callback = (ListOfAppsCallback) inv.getArguments()[1];
callbackHolder.setCallback(callback);
return null;
}).when(mApplicationFeatureProvider)
.listAppsWithAdminGrantedPermissions(eq(mPermissions), any());
return callbackHolder;
}
}

View File

@@ -0,0 +1,247 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import android.util.Log;
import androidx.preference.Preference;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
import com.android.car.settingslib.applications.ApplicationFeatureProvider.NumberOfAppsCallback;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
abstract class BaseAdminGrantedPermissionsPreferenceControllerTestCase
<C extends BaseAdminGrantedPermissionsPreferenceController> extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String TAG = BaseAdminGrantedPermissionsPreferenceControllerTestCase.class
.getSimpleName();
// Must be a spy to verify refreshUi() is called
private C mSpiedController;
protected final String[] mPermissions;
@Mock
private Preference mPreference;
BaseAdminGrantedPermissionsPreferenceControllerTestCase(String... permissions) {
mPermissions = permissions;
}
@Before
public void setController() {
mSpiedController = spy(newController(mApplicationFeatureProvider));
}
protected abstract C newController(ApplicationFeatureProvider provider);
@Test
public void testGetAvailabilityStatus_noPermissionsGranted() {
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted_zoneWrite() {
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted_zoneRead() {
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noPermissionsGranted_zoneHidden() {
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(42);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted_zoneWrite() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(42);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted_zoneRead() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(42);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_permissionsGranted_zoneHidden() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(42);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testUpdateState() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder =
mockCalculateNumberOfAppsWithAdminGrantedPermissions();
mSpiedController.getAvailabilityStatus();
callbackHolder.release(42);
assertUiRefreshed(mSpiedController);
mSpiedController.updateState(mPreference);
assertPreferenceStateSet(mPreference, 42);
}
private NumberOfAppsCallbackHolder mockCalculateNumberOfAppsWithAdminGrantedPermissions() {
NumberOfAppsCallbackHolder callbackHolder = new NumberOfAppsCallbackHolder();
doAnswer((inv) -> {
Log.d(TAG, "answering to " + inv);
NumberOfAppsCallback callback = (NumberOfAppsCallback) inv.getArguments()[2];
callbackHolder.setCallback(callback);
return null;
}).when(mApplicationFeatureProvider)
.calculateNumberOfAppsWithAdminGrantedPermissions(eq(mPermissions),
/* sync= */ eq(true), any());
return callbackHolder;
}
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static java.util.stream.Collectors.toList;
import android.car.drivingstate.CarUxRestrictions;
import android.content.Context;
import androidx.preference.Preference;
import androidx.preference.PreferenceGroup;
import com.android.car.settings.common.FragmentController;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
abstract class BaseEnterprisePreferenceControllerTestCase extends BaseEnterpriseTestCase {
protected final String mPreferenceKey = "Da Key";
protected final CarUxRestrictions mUxRestrictions = new CarUxRestrictions.Builder(
/* reqOpt= */ true, CarUxRestrictions.UX_RESTRICTIONS_FULLY_RESTRICTED, /* time= */ 0)
.build();
@Mock
protected FragmentController mFragmentController;
protected static final void assertPreferenceSummary(Preference preference, String summary) {
assertWithMessage("(preference %s).getSummary()", preference).that(preference.getSummary())
.isEqualTo(summary);
}
protected void verifyPreferenceTitles(DummyPreferenceGroup preferenceGroup,
CharSequence... titles) {
assertThat(preferenceGroup.getPreferences().stream()
.map(p -> p.getTitle()).collect(toList())).containsExactly(titles);
}
protected static final void verifyPreferenceVisibleSet(Preference preference, boolean visible) {
verify(preference).setVisible(visible);
}
protected static final void verifyPreferenceTitleSet(Preference preference,
CharSequence title) {
verify(preference).setTitle(title);
}
protected static final void verifyPreferenceTitleNeverSet(Preference preference) {
verify(preference, never()).setTitle(any());
}
protected static final void verifyPreferenceSummarySet(Preference preference,
CharSequence summary) {
verify(preference).setSummary(summary);
}
protected static final void verifyPreferenceSummarySet(Preference preference, int resId) {
verify(preference).setSummary(resId);
}
protected static final void verifyPreferenceSummaryNeverSet(Preference preference) {
verify(preference, never()).setSummary(any());
}
protected static final void verifyPreferenceIconSet(Preference preference) {
verify(preference).setIcon(notNull());
}
protected static final void verifyPreferenceIconNeverSet(Preference preference) {
verify(preference, never()).setIcon(notNull());
}
protected static final void verifyPreferenceDisabled(Preference preference) {
verify(preference).setEnabled(false);
}
protected static final void verifyPreferenceEnabled(Preference preference) {
verify(preference).setEnabled(true);
}
static final class DummyPreferenceGroup extends PreferenceGroup {
private final List<Preference> mList = new ArrayList<>();
DummyPreferenceGroup(Context context) {
super(context, null);
}
@Override public void removeAll() {
mList.clear();
}
@Override public boolean addPreference(Preference preference) {
mList.add(preference);
return true;
}
@Override public int getPreferenceCount() {
return mList.size();
}
@Override public Preference getPreference(int index) {
return mList.get(index);
}
public List<Preference> getPreferences() {
return mList;
}
}
}

View File

@@ -0,0 +1,195 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.annotation.Nullable;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.graphics.drawable.Drawable;
import android.util.ArrayMap;
import android.util.Log;
import androidx.preference.Preference;
import androidx.preference.PreferenceGroup;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceController;
import com.android.car.settings.testutils.TextDrawable;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
import com.android.car.settingslib.applications.ApplicationFeatureProvider.ListOfAppsCallback;
import com.android.car.settingslib.applications.ApplicationFeatureProvider.NumberOfAppsCallback;
import com.android.car.settingslib.applications.UserAppInfo;
import com.android.car.settingslib.enterprise.EnterpriseDefaultApps;
import com.android.car.settingslib.enterprise.EnterprisePrivacyFeatureProvider;
import com.android.internal.util.Preconditions;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
/**
* Base test for all controllers in the enterprise privacy / managed device info screen
*/
abstract class BaseEnterprisePrivacyPreferenceControllerTestCase
extends BaseEnterprisePreferenceControllerTestCase {
private static final String TAG = BaseEnterprisePrivacyPreferenceControllerTestCase.class
.getSimpleName();
private static final UserInfo DEFAULT_USER_INFO = new UserInfo(42, "Groot", /* flags= */ 0);
private static final Map<CharSequence, Drawable> ICONS_BY_LABEL = new ArrayMap<>();
@Mock
protected ApplicationFeatureProvider mApplicationFeatureProvider;
@Mock
protected EnterprisePrivacyFeatureProvider mEnterprisePrivacyFeatureProvider;
protected void verifyFindPersistentPreferredActivitiesCalledOnce() {
verify(mApplicationFeatureProvider, times(EnterpriseDefaultApps.values().length))
.findPersistentPreferredActivities(anyInt(), any());
}
protected ArgumentMatcher<Intent[]> matchesIntents(Intent[] intents) {
return (Intent[] actualIntents) -> {
if (actualIntents == null) {
return false;
}
if (actualIntents.length != intents.length) {
return false;
}
for (int i = 0; i < intents.length; i++) {
if (!intents[i].filterEquals(actualIntents[i])) {
return false;
}
}
return true;
};
}
protected void assertPreferenceStateSet(Preference preference, int count) {
String expectedSummary = mRealContext.getResources().getQuantityString(
R.plurals.enterprise_privacy_number_packages_lower_bound, count, count);
verifyPreferenceTitleNeverSet(preference);
verifyPreferenceSummarySet(preference, expectedSummary);
verifyPreferenceIconNeverSet(preference);
}
protected void assertPreferenceGroupStateSet(PreferenceGroup preferenceGroup,
CharSequence...appLabels) {
assertWithMessage("preference count")
.that(preferenceGroup.getPreferenceCount()).isEqualTo(appLabels.length);
for (int i = 0; i < appLabels.length; i++) {
Preference pref = preferenceGroup.getPreference(i);
CharSequence label = appLabels[i];
assertWithMessage("title at index %s", i).that(pref.getTitle()).isEqualTo(label);
Drawable icon = getIcon(label);
assertWithMessage("icon at index %s", i).that(pref.getIcon()).isEqualTo(icon);
assertWithMessage("order at index %s", i).that(pref.getOrder()).isEqualTo(i);
assertWithMessage("selectable at index %s", i).that(pref.isSelectable()).isFalse();
}
}
protected void expectUiRefreshed(PreferenceController controller) {
doNothing().when(controller).refreshUi();
}
protected void assertUiRefreshed(PreferenceController controller) {
verify(controller).refreshUi();
}
protected void assertUiNotRefreshed(PreferenceController controller) {
verify(controller, never()).refreshUi();
}
protected UserAppInfo newUserAppInfo(CharSequence label) {
ApplicationInfo appInfo = new ApplicationInfo() {
@Override
public CharSequence loadLabel(PackageManager pm) {
return label;
}
@Override
public Drawable loadIcon(PackageManager pm) {
return getIcon(label);
};
};
return new UserAppInfo(DEFAULT_USER_INFO, appInfo);
}
protected Drawable getIcon(CharSequence label) {
Drawable icon = ICONS_BY_LABEL.get(label);
if (icon != null) {
Log.d(TAG, "getIcon(" + label + "): returning existing icon " + icon);
return icon;
}
icon = new TextDrawable(label);
ICONS_BY_LABEL.put(label, icon);
Log.d(TAG, "getIcon(" + label + "): returning new icon " + icon);
return icon;
}
static final class ListOfAppsCallbackHolder {
@Nullable
private ApplicationFeatureProvider.ListOfAppsCallback mCallback;
void release(UserAppInfo... result) {
Preconditions.checkState(mCallback != null, "release() called before setCallback()");
Log.d(TAG, "setting result to " + Arrays.toString(result) + " and releasing latch on"
+ Thread.currentThread());
mCallback.onListOfAppsResult(Arrays.asList(result));
}
void setCallback(ListOfAppsCallback callback) {
Log.d(TAG, "setting callback to " + callback);
mCallback = Objects.requireNonNull(callback, "callback cannot be null");
}
}
static final class NumberOfAppsCallbackHolder {
@Nullable
private NumberOfAppsCallback mCallback;
void release(int result) {
Preconditions.checkState(mCallback != null, "release() called before setCallback()");
Log.d(TAG, "setting result to " + result + " and releasing latch on"
+ Thread.currentThread());
mCallback.onNumberOfAppsResult(result);
}
void setCallback(NumberOfAppsCallback callback) {
Log.d(TAG, "setting callback to " + callback);
mCallback = Objects.requireNonNull(callback, "callback cannot be null");
}
}
}

View File

@@ -0,0 +1,283 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.annotation.UserIdInt;
import android.app.AppOpsManager;
import android.app.admin.DeviceAdminInfo;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.os.IBinder;
import android.os.UserHandle;
import android.os.UserManager;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.dx.mockito.inline.extended.ExtendedMockito;
import com.android.settingslib.RestrictedLockUtilsInternal;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoSession;
import org.mockito.quality.Strictness;
import java.util.Arrays;
@RunWith(AndroidJUnit4.class)
public abstract class BaseEnterpriseTestCase {
protected static final UserHandle MY_USER_ID = UserHandle.of(UserHandle.myUserId());
protected final Context mRealContext = ApplicationProvider.getApplicationContext();
protected final Context mSpiedContext = spy(mRealContext);
protected final String mPackageName = mRealContext.getPackageName();
protected final PackageManager mRealPm = mRealContext.getPackageManager();
protected PackageManager mSpiedPm = spy(mRealPm);
protected final String mAppName = mRealContext.getApplicationInfo().loadLabel(mRealPm)
.toString();
protected final ComponentName mDefaultAdmin =
new ComponentName(mSpiedContext, DefaultDeviceAdminReceiver.class);
protected final ComponentName mFancyAdmin =
new ComponentName(mSpiedContext, FancyDeviceAdminReceiver.class);
protected ResolveInfo mDefaultResolveInfo;
protected ResolveInfo mFancyResolveInfo;
protected DeviceAdminInfo mDefaultDeviceAdminInfo;
protected DeviceAdminInfo mFancyDeviceAdminInfo;
@Mock
protected AppOpsManager mAppOpsMgr;
@Mock
protected DevicePolicyManager mDpm;
@Mock
protected UserManager mUm;
private MockitoSession mSession;
@Before
public final void setFixtures() throws Exception {
if (mSession != null) {
throw new IllegalStateException("Already set session - subclasses should NOT explicitly"
+ " call setFixtures()");
}
mSession = ExtendedMockito.mockitoSession()
.initMocks(this)
.spyStatic(UserManager.class)
.mockStatic(RestrictedLockUtilsInternal.class)
.strictness(Strictness.LENIENT)
.startMocking();
assertWithMessage("mDpm").that(mDpm).isNotNull();
assertWithMessage("mUm").that(mUm).isNotNull();
when(mSpiedContext.getSystemService(AppOpsManager.class)).thenReturn(mAppOpsMgr);
when(mSpiedContext.getSystemService(DevicePolicyManager.class)).thenReturn(mDpm);
when(mSpiedContext.getSystemService(PackageManager.class)).thenReturn(mSpiedPm);
when(mSpiedContext.getPackageManager()).thenReturn(mSpiedPm);
when(mSpiedContext.getSystemService(UserManager.class)).thenReturn(mUm);
doReturn(mUm).when(() -> UserManager.get(any()));
ActivityInfo defaultActivityInfo =
mRealPm.getReceiverInfo(mDefaultAdmin, PackageManager.GET_META_DATA);
mDefaultDeviceAdminInfo = new DeviceAdminInfo(mRealContext, defaultActivityInfo);
mDefaultResolveInfo = new ResolveInfo();
mDefaultResolveInfo.activityInfo = defaultActivityInfo;
ActivityInfo fancyActivityInfo =
mRealPm.getReceiverInfo(mFancyAdmin, PackageManager.GET_META_DATA);
mFancyDeviceAdminInfo = new DeviceAdminInfo(mRealContext, fancyActivityInfo);
mFancyResolveInfo = new ResolveInfo();
mFancyResolveInfo.activityInfo = fancyActivityInfo;
}
@After
public void tearDown() {
if (mSession != null) {
mSession.finishMocking();
mSession = null;
}
}
protected final void mockProfileOwner() {
mockActiveAdmin(mDefaultAdmin);
when(mDpm.getProfileOwner()).thenReturn(mDefaultAdmin);
}
protected final void mockProfileOwnerAsUser() {
when(mDpm.getProfileOwnerAsUser(MY_USER_ID)).thenReturn(mDefaultAdmin);
when(mDpm.getProfileOwnerAsUser(MY_USER_ID.getIdentifier())).thenReturn(mDefaultAdmin);
}
protected final void mockNoProfileOwnerAsUser() {
when(mDpm.getProfileOwnerAsUser(MY_USER_ID)).thenReturn(null);
when(mDpm.getProfileOwnerAsUser(MY_USER_ID.getIdentifier())).thenReturn(null);
}
protected final void mockDeviceOwner() {
when(mDpm.isDeviceManaged()).thenReturn(true);
mockActiveAdmin(mDefaultAdmin);
when(mDpm.isDeviceManaged()).thenReturn(true);
when(mDpm.getDeviceOwnerComponentOnCallingUser()).thenReturn(mDefaultAdmin);
when(mDpm.getDeviceOwnerComponentOnAnyUser()).thenReturn(mDefaultAdmin);
}
protected final void mockNoDeviceOwner() {
when(mDpm.getDeviceOwnerComponentOnCallingUser()).thenReturn(null);
when(mDpm.getDeviceOwnerComponentOnAnyUser()).thenReturn(null);
}
protected final void mockNotManaged() {
when(mDpm.isDeviceManaged()).thenReturn(false);
}
protected final void mockOrganizationName(String orgName) {
when(mDpm.getDeviceOwnerOrganizationName()).thenReturn(orgName);
}
protected final void mockFinancialDevice() {
when(mDpm.isDeviceManaged()).thenReturn(true);
when(mDpm.getDeviceOwnerType(mDefaultAdmin))
.thenReturn(DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED);
}
protected final void mockActiveAdmin(ComponentName componentName) {
when(mDpm.isAdminActive(componentName)).thenReturn(true);
}
protected final void mockInactiveAdmin(ComponentName componentName) {
when(mDpm.isAdminActive(componentName)).thenReturn(false);
}
protected final void mockGetActiveAdmins(ComponentName... componentNames) {
when(mDpm.getActiveAdmins()).thenReturn(Arrays.asList(componentNames));
}
protected final void mockQueryBroadcastReceivers(ResolveInfo... resolveInfoArray) {
// Need to use doReturn() instead of when() because mSpiedPm is a spy.
doReturn(Arrays.asList(resolveInfoArray))
.when(mSpiedPm).queryBroadcastReceivers(any(Intent.class), anyInt());
}
protected final void mockGetLongSupportMessageForUser(CharSequence message) {
when(mDpm.getLongSupportMessageForUser(eq(mDefaultAdmin), anyInt())).thenReturn(message);
}
protected final void mockRemovingAdmin(ComponentName admin, int userId) {
when(mDpm.isRemovingAdmin(admin, userId)).thenReturn(true);
}
protected final void mockGrantedPolicies(ComponentName admin, int ... policies) {
for (int policy: policies) {
when(mDpm.hasGrantedPolicy(admin, policy)).thenReturn(true);
}
}
protected final void mockHasDeviceAdminFeature() {
when(mSpiedPm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)).thenReturn(true);
}
protected final void mockNoDeviceAdminFeature() {
when(mSpiedPm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)).thenReturn(false);
}
protected final void mockSystemUser() {
when(mUm.isSystemUser()).thenReturn(true);
}
protected final void mockNonSystemUser() {
when(mUm.isSystemUser()).thenReturn(false);
}
protected final void mockNullEnforcedAdmin(String restriction, int userId) {
when(RestrictedLockUtilsInternal
.checkIfRestrictionEnforced(mSpiedContext, restriction, userId)).thenReturn(null);
}
protected final void mockGetLastBugreportTime(long time) {
when(mDpm.getLastBugReportRequestTime()).thenReturn(time);
}
protected final void mockCompMode() {
mockDeviceOwner();
UserInfo userInfo = new UserInfo(10, "UserAbc", null, 0,
UserManager.USER_TYPE_PROFILE_MANAGED);
when(mUm.getProfiles(anyInt())).thenReturn(Arrays.asList(userInfo));
}
protected final void mockGetLastNetworkLogRetrievalTime(long time) {
when(mDpm.getLastNetworkLogRetrievalTime()).thenReturn(time);
}
protected final void mockGetLastSecurityLogRetrievalTime(long time) {
when(mDpm.getLastSecurityLogRetrievalTime()).thenReturn(time);
}
protected final void mockIsCurrentInputMethodSetByOwner(boolean value) {
when(mDpm.isCurrentInputMethodSetByOwner()).thenReturn(value);
}
protected final void mockGetMaximumFailedPasswordsForWipe(@UserIdInt int userId, int max) {
when(mDpm.getMaximumFailedPasswordsForWipe(mDefaultAdmin, userId)).thenReturn(max);
}
protected final void verifyAdminActivated() {
verify(mDpm).setActiveAdmin(eq(mDefaultAdmin), anyBoolean());
}
protected final void verifyAdminNeverActivated() {
verify(mDpm, never()).setActiveAdmin(any(), anyBoolean());
}
protected final void verifyAdminDeactivated() {
verify(mDpm).removeActiveAdmin(mDefaultAdmin);
}
protected final void verifyAdminNeverDeactivated() {
verify(mDpm, never()).removeActiveAdmin(any());
}
protected final void verifyAppOpsMgrSetUserRestriction(int code, boolean restricted) {
verify(mAppOpsMgr).setUserRestriction(eq(code), eq(restricted), any(IBinder.class));
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import android.text.format.DateUtils;
import androidx.preference.Preference;
import com.android.car.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class BugReportsPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private BugReportsPreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setUp() throws Exception {
mController = new BugReportsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
}
@Test
public void testUpdateState_noBugreport() {
mockGetLastBugreportTime(-1);
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference, R.string.enterprise_privacy_none);
verifyPreferenceIconNeverSet(mPreference);
}
@Test
public void testUpdateState_withBugreport() {
long now = System.currentTimeMillis();
mockGetLastBugreportTime(now);
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
String formattedDate = DateUtils.formatDateTime(mRealContext, now,
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE);
verifyPreferenceSummarySet(mPreference, formattedDate);
verifyPreferenceIconNeverSet(mPreference);
}
}

View File

@@ -0,0 +1,194 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import android.net.ConnectivityManager;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.util.Collections;
public final class CaCertsCurrentUserPreferenceControllerTest extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private CaCertsCurrentUserPreferenceController mCaCertsCurrentUserPreferenceController;
private Preference mPreference;
@Mock
private ConnectivityManager mConnectivityManager;
@Before
public void setUp() {
when(mSpiedContext.getSystemService(ConnectivityManager.class))
.thenReturn(mConnectivityManager);
mPreference = new Preference(mSpiedContext);
mCaCertsCurrentUserPreferenceController = new CaCertsCurrentUserPreferenceController(
mSpiedContext, mPreferenceKey, mFragmentController, mUxRestrictions);
}
@Test
public void testNoInstalledCaCerts_preferenceDisabled() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(Collections.emptyList());
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertThat(mPreference.getSummary()).isEqualTo(
mRealContext.getResources().getQuantityString(
R.plurals.enterprise_privacy_number_ca_certs, 0, 0));
}
@Test
public void testNoInstalledCaCerts_preferenceDisabled_zoneWrite() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(Collections.emptyList());
mCaCertsCurrentUserPreferenceController.setAvailabilityStatusForZone("write");
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertThat(mPreference.getSummary()).isEqualTo(
mRealContext.getResources().getQuantityString(
R.plurals.enterprise_privacy_number_ca_certs, 0, 0));
}
@Test
public void testNoInstalledCaCerts_preferenceDisabled_zoneRead() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(Collections.emptyList());
mCaCertsCurrentUserPreferenceController.setAvailabilityStatusForZone("read");
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertThat(mPreference.getSummary()).isEqualTo(
mRealContext.getResources().getQuantityString(
R.plurals.enterprise_privacy_number_ca_certs, 0, 0));
}
@Test
public void testNoInstalledCaCerts_preferenceDisabled_zoneHidden() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(Collections.emptyList());
mCaCertsCurrentUserPreferenceController.setAvailabilityStatusForZone("hidden");
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertThat(mPreference.getSummary()).isEqualTo(
mRealContext.getResources().getQuantityString(
R.plurals.enterprise_privacy_number_ca_certs, 0, 0));
}
@Test
public void testInstalledCaCerts_preferenceEnabled() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(ImmutableList.of("cert1", "cert2"));
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(), AVAILABLE);
assertThat(mPreference.getSummary()).isEqualTo(mRealContext.getResources()
.getQuantityString(R.plurals.enterprise_privacy_number_ca_certs, 2, 2));
}
@Test
public void testInstalledCaCerts_preferenceEnabled_zoneWrite() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(ImmutableList.of("cert1", "cert2"));
mCaCertsCurrentUserPreferenceController.setAvailabilityStatusForZone("write");
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(), AVAILABLE);
assertThat(mPreference.getSummary()).isEqualTo(mRealContext.getResources()
.getQuantityString(R.plurals.enterprise_privacy_number_ca_certs, 2, 2));
}
@Test
public void testInstalledCaCerts_preferenceEnabled_zoneRead() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(ImmutableList.of("cert1", "cert2"));
mCaCertsCurrentUserPreferenceController.setAvailabilityStatusForZone("read");
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
assertThat(mPreference.getSummary()).isEqualTo(mRealContext.getResources()
.getQuantityString(R.plurals.enterprise_privacy_number_ca_certs, 2, 2));
}
@Test
public void testInstalledCaCerts_preferenceEnabled_zoneHidden() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(ImmutableList.of("cert1", "cert2"));
mCaCertsCurrentUserPreferenceController.setAvailabilityStatusForZone("hidden");
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mCaCertsCurrentUserPreferenceController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
assertThat(mPreference.getSummary()).isEqualTo(mRealContext.getResources()
.getQuantityString(R.plurals.enterprise_privacy_number_ca_certs, 2, 2));
}
@Test
public void testNoCompMode_showsRegularTitle() {
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(ImmutableList.of("cert1", "cert2"));
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
assertThat(mPreference.getTitle()).isEqualTo(mRealContext.getResources()
.getString(R.string.enterprise_privacy_ca_certs_device));
}
@Test
public void testCompMode_showsPersonalProfileTitle() {
mockCompMode();
when(mDpm.getOwnerInstalledCaCerts(any())).thenReturn(ImmutableList.of("cert1", "cert2"));
mCaCertsCurrentUserPreferenceController.updateState(mPreference);
assertThat(mPreference.getTitle()).isEqualTo(mRealContext.getResources()
.getString(R.string.enterprise_privacy_ca_certs_personal));
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import android.app.admin.DeviceAdminReceiver;
public final class DefaultDeviceAdminReceiver extends DeviceAdminReceiver {
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import androidx.test.annotation.UiThreadTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.car.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public final class DeviceAdminActivatedAppsPreferenceControllerTest
extends BaseEnterprisePreferenceControllerTestCase {
private DeviceAdminAppsPreferenceController mController;
private BaseEnterprisePreferenceControllerTestCase.DummyPreferenceGroup mPreferenceGroup;
@Before
@UiThreadTest
public void setUp() throws Exception {
mController = new DeviceAdminActivatedAppsPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mPreferenceGroup = new DummyPreferenceGroup(mSpiedContext);
}
@Test
public void testUpdateState_noBroadcastReceivers() {
mockQueryBroadcastReceivers();
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup,
mRealContext.getString(R.string.device_admin_apps_list_empty));
}
@Test
public void testUpdateState_noActivatedAdminApp() {
mockQueryBroadcastReceivers(mDefaultResolveInfo, mFancyResolveInfo);
mockInactiveAdmin(mDefaultAdmin);
mockInactiveAdmin(mFancyAdmin);
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup,
mRealContext.getString(R.string.device_admin_apps_list_empty));
}
@Test
public void testUpdateState_singleActivatedAdminApp() {
mockQueryBroadcastReceivers(mDefaultResolveInfo, mFancyResolveInfo);
mockInactiveAdmin(mDefaultAdmin);
mockActiveAdmin(mFancyAdmin);
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup, mFancyDeviceAdminInfo.loadLabel(mRealPm));
}
@Test
public void testUpdateState_multipleActivatedAdminApps() {
mockQueryBroadcastReceivers(mDefaultResolveInfo, mFancyResolveInfo);
mockActiveAdmin(mDefaultAdmin);
mockActiveAdmin(mFancyAdmin);
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup,
mDefaultDeviceAdminInfo.loadLabel(mRealPm),
mFancyDeviceAdminInfo.loadLabel(mRealPm));
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static android.car.test.mocks.AndroidMockitoHelper.syncCallOnMainThread;
import static com.google.common.truth.Truth.assertWithMessage;
import androidx.fragment.app.Fragment;
import org.junit.Test;
public final class DeviceAdminAddActivityTest extends BaseEnterpriseTestCase {
@Test
public void testGetFragment() throws Exception {
Fragment fragment = syncCallOnMainThread(() ->
// DeviceAdminAddActivity must be created in the main thread
new DeviceAdminAddActivity().getInitialFragment());
assertWithMessage("initial fragment class").that(fragment)
.isInstanceOf(DeviceAdminAddFragment.class);
}
}

View File

@@ -0,0 +1,352 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import androidx.preference.Preference;
import com.android.car.settings.common.PreferenceController;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class DeviceAdminAddExplanationPreferenceControllerTest extends
BaseEnterprisePreferenceControllerTestCase {
@Mock
private Preference mPreference;
private DeviceAdminAddExplanationPreferenceController mController;
@Before
public void setController() {
mController = new DeviceAdminAddExplanationPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mController.setDeviceAdmin(mDefaultDeviceAdminInfo);
}
@Test
public void testGetAvailabilityStatus_noAdmin() throws Exception {
DeviceAdminAddExplanationPreferenceController controller =
new DeviceAdminAddExplanationPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
mController.setExplanation("To conquer the universe");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneWrite() throws Exception {
DeviceAdminAddExplanationPreferenceController controller =
new DeviceAdminAddExplanationPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneRead() throws Exception {
DeviceAdminAddExplanationPreferenceController controller =
new DeviceAdminAddExplanationPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneHidden() throws Exception {
DeviceAdminAddExplanationPreferenceController controller =
new DeviceAdminAddExplanationPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_noReason() throws Exception {
mockDeviceOwner();
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_noReason_zoneWrite() throws Exception {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_noReason_zoneRead() throws Exception {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_noReason_zoneHidden() throws Exception {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_withReason() throws Exception {
mockDeviceOwner();
mController.setExplanation("To conquer the universe");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_withReason_zoneWrite() throws Exception {
mockDeviceOwner();
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_withReason_zoneRead() throws Exception {
mockDeviceOwner();
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_withReason_zoneHidden() throws Exception {
mockDeviceOwner();
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_noReason() throws Exception {
mockProfileOwner();
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_noReason_zoneWrite() throws Exception {
mockProfileOwner();
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_noReason_zoneRead() throws Exception {
mockProfileOwner();
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_noReason_zoneHidden() throws Exception {
mockProfileOwner();
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_withReason() throws Exception {
mockProfileOwner();
mController.setExplanation("To conquer the universe");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_withReason_zoneWrite() throws Exception {
mockProfileOwner();
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_withReason_zoneRead() throws Exception {
mockProfileOwner();
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_profileOwner_withReason_zoneHidden() throws Exception {
mockProfileOwner();
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetRealAvailabilityStatus_nullReason() throws Exception {
mController.setExplanation(null);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetRealAvailabilityStatus_nullReason_zoneWrite() throws Exception {
mController.setExplanation(null);
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetRealAvailabilityStatus_nullReason_zoneRead() throws Exception {
mController.setExplanation(null);
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetRealAvailabilityStatus_nullReason_zoneHidden() throws Exception {
mController.setExplanation(null);
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyReason() throws Exception {
mController.setExplanation("");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyReason_zoneWrite() throws Exception {
mController.setExplanation("");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyReason_zoneRead() throws Exception {
mController.setExplanation("");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyReason_zoneHidden() throws Exception {
mController.setExplanation("");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_validReason() throws Exception {
mController.setExplanation("To conquer the universe");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_validReason_zoneWrite() throws Exception {
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_validReason_zoneRead() throws Exception {
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_validReason_zoneHidden() throws Exception {
mController.setExplanation("To conquer the universe");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testUpdateState() throws Exception {
mController.setExplanation("To conquer the universe");
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference, "To conquer the universe");
verifyPreferenceSummaryNeverSet(mPreference);
verifyPreferenceIconNeverSet(mPreference);
}
}

View File

@@ -0,0 +1,541 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static android.app.admin.DeviceAdminInfo.USES_ENCRYPTED_STORAGE;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_FORCE_LOCK;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_RESET_PASSWORD;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_WATCH_LOGIN;
import static android.app.admin.DeviceAdminInfo.USES_POLICY_WIPE_DATA;
import static android.app.admin.DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN;
import static android.app.admin.DevicePolicyManager.EXTRA_ADD_EXPLANATION;
import static android.app.admin.DevicePolicyManager.EXTRA_DEVICE_ADMIN;
import static android.car.test.mocks.AndroidMockitoHelper.syncCallOnMainThread;
import static com.android.car.settings.enterprise.DeviceAdminAddActivity.EXTRA_DEVICE_ADMIN_PACKAGE_NAME;
import static com.android.car.settings.enterprise.DeviceAdminAddFragment.UNINSTALL_DEVICE_ADMIN_REQUEST_CODE;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.car.settings.R;
import com.android.car.settings.enterprise.DeviceAdminAddHeaderPreferenceController.ActivationListener;
import com.android.car.ui.toolbar.MenuItem;
import com.android.car.ui.toolbar.ToolbarController;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import java.util.Arrays;
public final class DeviceAdminAddFragmentTest extends BaseEnterpriseTestCase {
private static final String EXPLANATION = "To get to the other side";
private final Context mRealContext = ApplicationProvider.getApplicationContext();
private DeviceAdminAddFragment mRealFragment;
private DeviceAdminAddFragment mSpiedFragment;
@Mock
private ToolbarController mToolbarController;
@Mock
private FragmentActivity mActivity;
@Mock
private PreferenceScreen mPreferenceScreen;
@Mock
private DeviceAdminAddHeaderPreferenceController mHeaderController;
@Mock
private DeviceAdminAddExplanationPreferenceController mExplanationController;
@Mock
private DeviceAdminAddSupportPreferenceController mSupportController;
@Mock
private DeviceAdminAddWarningPreferenceController mWarningController;
@Mock
private DeviceAdminAddPoliciesPreferenceController mPoliciesController;
@Captor
private ArgumentCaptor<ActivationListener> mActivationListenerCaptor;
@Before
public void createFragments() throws Exception {
mRealFragment = syncCallOnMainThread(() -> new DeviceAdminAddFragment());
mSpiedFragment = spy(mRealFragment);
when(mExplanationController.setDeviceAdmin(any())).thenReturn(mExplanationController);
when(mHeaderController.setDeviceAdmin(any())).thenReturn(mHeaderController);
// Note: Must use doReturn (instead of when..doReturn() below because it's a spy
doReturn(mActivity).when(mSpiedFragment).requireActivity();
doReturn(mHeaderController).when(mSpiedFragment)
.use(eq(DeviceAdminAddHeaderPreferenceController.class), anyInt());
doReturn(mExplanationController).when(mSpiedFragment)
.use(eq(DeviceAdminAddExplanationPreferenceController.class), anyInt());
doReturn(mSupportController).when(mSpiedFragment)
.use(eq(DeviceAdminAddSupportPreferenceController.class), anyInt());
doReturn(mWarningController).when(mSpiedFragment)
.use(eq(DeviceAdminAddWarningPreferenceController.class), anyInt());
doReturn(mPoliciesController).when(mSpiedFragment)
.use(eq(DeviceAdminAddPoliciesPreferenceController.class), anyInt());
}
@Test
public void testGetPreferenceScreenResId() {
int resId = mRealFragment.getPreferenceScreenResId();
XmlResourceParser parser = mRealContext.getResources().getXml(resId);
assertWithMessage("xml with id %s", resId).that(parser).isNotNull();
}
@Test
public void testSetupToolbar_noIntent() {
mSpiedFragment.setToolbarTitle(mToolbarController);
verify(mToolbarController, never()).setTitle(anyInt());
}
@Test
public void testSetupToolbar_notFromActionAddDeviceAdmin() {
mockActivityIntent(new Intent());
mSpiedFragment.setToolbarTitle(mToolbarController);
verify(mToolbarController, never()).setTitle(anyInt());
}
@Test
public void testSetupToolbar_fromActionAddDeviceAdmin() {
mockActivityIntent(new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN));
mSpiedFragment.setToolbarTitle(mToolbarController);
verify(mToolbarController).setTitle(R.string.add_device_admin_msg);
}
@Test
public void testAttach_noIntent() {
mRealFragment.onAttach(mSpiedContext, mActivity);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_noExtra() {
mockActivityIntent(new Intent());
mRealFragment.onAttach(mSpiedContext, mActivity);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_adminExtra_adminNotFound() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN, new ComponentName("Guy", "Incognito")));
mRealFragment.onAttach(mSpiedContext, mActivity);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_adminExtra_ok_active() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockActiveAdmin(mDefaultAdmin);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verifyActivityNeverFinished();
verifyControllersUsed(mDefaultAdmin);
}
@Test
public void testAttach_addDeviceAdminAction_active() {
mockActivityIntent(new Intent(ACTION_ADD_DEVICE_ADMIN)
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockActiveAdmin(mDefaultAdmin);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verityActivityResultSet(Activity.RESULT_OK);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_addDeviceAdminAction_active_removing() {
mockActivityIntent(new Intent(ACTION_ADD_DEVICE_ADMIN)
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockActiveAdmin(mDefaultAdmin);
mockRemovingAdmin(mDefaultAdmin, mSpiedContext.getUserId());
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verityActivityResultNeverSet();
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_addDeviceAdminAction_active_noRefreshing() {
mockActivityIntent(new Intent(ACTION_ADD_DEVICE_ADMIN)
.putExtra(EXTRA_DEVICE_ADMIN, mFancyAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockActiveAdmin(mFancyAdmin);
// Grant all policies that mFancyAdmin has.
mockGrantedPolicies(mFancyAdmin, USES_POLICY_LIMIT_PASSWORD, USES_POLICY_WATCH_LOGIN,
USES_POLICY_RESET_PASSWORD, USES_POLICY_FORCE_LOCK, USES_POLICY_WIPE_DATA,
USES_POLICY_EXPIRE_PASSWORD, USES_ENCRYPTED_STORAGE);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verityActivityResultSet(Activity.RESULT_OK);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_addDeviceAdminAction_active_refreshing() {
mockActivityIntent(new Intent(ACTION_ADD_DEVICE_ADMIN)
.putExtra(EXTRA_DEVICE_ADMIN, mFancyAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockActiveAdmin(mFancyAdmin);
// Grant all policies that mFancyAdmin has besides USES_ENCRYPTED_STORAGE.
mockGrantedPolicies(mFancyAdmin, USES_POLICY_LIMIT_PASSWORD, USES_POLICY_WATCH_LOGIN,
USES_POLICY_RESET_PASSWORD, USES_POLICY_FORCE_LOCK, USES_POLICY_WIPE_DATA,
USES_POLICY_EXPIRE_PASSWORD);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verifyActivityNeverFinished();
verifyControllersUsed(mFancyAdmin);
}
@Test
public void testAttach_addDeviceAdminAction_inactive_userActivates() {
ActivationListener listener = attachActivityForResultTesting(ACTION_ADD_DEVICE_ADMIN);
listener.onChanged(true);
verityActivityResultSet(Activity.RESULT_OK);
verifyActivityNeverFinished();
}
@Test
public void testAttach_addDeviceAdminAction_inactive_userDeactivates() {
ActivationListener listener = attachActivityForResultTesting(ACTION_ADD_DEVICE_ADMIN);
listener.onChanged(false);
verityActivityResultSet(Activity.RESULT_CANCELED);
verifyActivityNeverFinished();
}
@Test
public void testAttach_inactive_notDeviceAdminAction() {
ActivationListener listener = attachActivityForResultTesting("ACTION_JACKSON");
listener.onChanged(true); // value doesn't matter
verityActivityResultNeverSet();
verifyActivityNeverFinished();
}
@Test
public void testAttach_adminExtra_ok_inactiveButValid() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockInactiveAdmin(mDefaultAdmin);
mockValidAdmin();
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verifyActivityNeverFinished();
verifyControllersUsed(mDefaultAdmin);
}
// TODO(b/202342351): add similar test for when new DeviceAdminInfo(context, ri) throws an
// exception (for example, when metadata is invalid).
@Test
public void testAttach_adminExtra_adminFoundButInvalid() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockInactiveAdmin(mDefaultAdmin);
// Don't need to mock pm
mRealFragment.onAttach(mSpiedContext, mActivity);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_packageExtra_adminNotFound() {
mockActivityIntent(new Intent().putExtra(EXTRA_DEVICE_ADMIN_PACKAGE_NAME, "D'OH!"));
mRealFragment.onAttach(mSpiedContext, mActivity);
verifyActivityFinished();
verifyControllersNeverUsed();
}
@Test
public void testAttach_packageExtra_ok() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN_PACKAGE_NAME, mPackageName)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockGetActiveAdmins(mDefaultAdmin);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verifyActivityNeverFinished();
verifyControllersUsed(mDefaultAdmin);
}
@Test
public void testAttach_adminExtra_doesNotShowUninstallButton() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockValidAdmin();
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verify(mSpiedFragment).setUninstallButton(any(Context.class), eq(false));
}
@Test
public void testAttach_packageExtra_showsUninstallButton() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN_PACKAGE_NAME, mPackageName)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockGetActiveAdmins(mDefaultAdmin);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verify(mSpiedFragment).setUninstallButton(any(Context.class), eq(true));
}
@Test
public void testSetUninstallButton_showButtonFalse() {
mRealFragment.setUninstallButton(mRealContext, false);
MenuItem button = mRealFragment.getToolbarMenuItems().get(0);
assertThat(button).isNotNull();
assertThat(button.getTitle().toString())
.isEqualTo(mRealContext.getString(R.string.deactivate_and_uninstall_device_admin));
assertThat(button.isEnabled()).isFalse();
assertThat(button.isVisible()).isFalse();
}
@Test
public void testSetUninstallButton_showButtonTrue() {
mRealFragment.setUninstallButton(mRealContext, true);
MenuItem button = mRealFragment.getToolbarMenuItems().get(0);
assertThat(button).isNotNull();
assertThat(button.getTitle().toString())
.isEqualTo(mRealContext.getString(R.string.deactivate_and_uninstall_device_admin));
assertThat(button.isEnabled()).isTrue();
assertThat(button.isVisible()).isTrue();
}
@Test
public void testUninstallOnClickListener_activeAdmin() {
mSpiedFragment.setDevicePolicyManager(mDpm);
mSpiedFragment.setPackageToUninstall(mPackageName, mDefaultAdmin);
mSpiedFragment.setUninstallButton(mSpiedContext, true);
mockActiveAdmin(mDefaultAdmin);
doNothing().when(mSpiedFragment).startActivityForResult(any(Intent.class), anyInt());
mSpiedFragment.getToolbarMenuItems().get(0).getOnClickListener().onClick(/* item= */ null);
ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(
Intent.class);
verify(mSpiedFragment).startActivityForResult(intentArgumentCaptor.capture(),
eq(UNINSTALL_DEVICE_ADMIN_REQUEST_CODE));
Intent intent = intentArgumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_UNINSTALL_PACKAGE);
assertThat(intent.getData().toString()).isEqualTo("package:" + mPackageName);
assertThat(intent.getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)).isTrue();
verify(mDpm).removeActiveAdmin(mDefaultAdmin);
}
@Test
public void testUninstallOnClickListener_inactiveAdmin() {
mSpiedFragment.setDevicePolicyManager(mDpm);
mSpiedFragment.setPackageToUninstall(mPackageName, mDefaultAdmin);
mSpiedFragment.setUninstallButton(mSpiedContext, true);
mockInactiveAdmin(mDefaultAdmin);
doNothing().when(mSpiedFragment).startActivityForResult(any(Intent.class), anyInt());
mSpiedFragment.getToolbarMenuItems().get(0).getOnClickListener().onClick(/* item= */ null);
ArgumentCaptor<Intent> intentArgumentCaptor = ArgumentCaptor.forClass(
Intent.class);
verify(mSpiedFragment).startActivityForResult(intentArgumentCaptor.capture(),
eq(UNINSTALL_DEVICE_ADMIN_REQUEST_CODE));
Intent intent = intentArgumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_UNINSTALL_PACKAGE);
assertThat(intent.getData().toString()).isEqualTo("package:" + mPackageName);
assertThat(intent.getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)).isTrue();
verify(mDpm, never()).removeActiveAdmin(mDefaultAdmin);
}
@Test
public void testOnActivityResult_resultOk() {
mSpiedFragment.onActivityResult(UNINSTALL_DEVICE_ADMIN_REQUEST_CODE, RESULT_OK, null);
verify(mActivity).setResult(RESULT_OK);
verify(mActivity).finish();
}
@Test
public void testOnActivityResult_resultNotOk() {
mSpiedFragment.onActivityResult(UNINSTALL_DEVICE_ADMIN_REQUEST_CODE, RESULT_CANCELED,
null);
verify(mActivity, never()).setResult(anyInt());
verify(mActivity, never()).finish();
}
@Test
public void testSetPreferenceScreenTitle() {
mockActivityIntent(new Intent()
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin)
.putExtra(EXTRA_ADD_EXPLANATION, EXPLANATION));
mockActiveAdmin(mDefaultAdmin);
mSpiedFragment.onAttach(mSpiedContext, mActivity);
mSpiedFragment.setPreferenceScreenTitle(mPreferenceScreen);
verify(mPreferenceScreen).setTitle((mDefaultDeviceAdminInfo.loadLabel(mRealPm)));
}
private ActivationListener attachActivityForResultTesting(String action) {
mockValidAdmin();
mockActivityIntent(new Intent(action)
.putExtra(EXTRA_DEVICE_ADMIN, mDefaultAdmin));
mSpiedFragment.onAttach(mSpiedContext, mActivity);
verify(mHeaderController).setActivationListener(mActivationListenerCaptor.capture());
return mActivationListenerCaptor.getValue();
}
private void mockActivityIntent(Intent intent) {
when(mActivity.getIntent()).thenReturn(intent);
}
private void mockValidAdmin() {
// TODO(b/202342351): use a custom matcher for
// DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED instead of any()
doReturn(Arrays.asList(mDefaultResolveInfo)).when(mSpiedPm).queryBroadcastReceivers(any(),
eq(PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS));
}
private void verifyActivityFinished() {
verify(mActivity).finish();
}
private void verifyActivityNeverFinished() {
verify(mActivity, never()).finish();
}
private void verityActivityResultSet(int result) {
verify(mActivity).setResult(result);
}
private void verityActivityResultNeverSet() {
verify(mActivity, never()).setResult(anyInt());
}
private void verifyControllersNeverUsed() {
verify(mSpiedFragment, never()).use(any(), anyInt());
}
private void verifyControllersUsed(ComponentName admin) {
verify(mSpiedFragment).use(DeviceAdminAddHeaderPreferenceController.class,
R.string.pk_device_admin_add_header);
verifySetDeviceAdmin(mHeaderController, admin);
verify(mHeaderController).setActivationListener(any());
verify(mSpiedFragment).use(DeviceAdminAddExplanationPreferenceController.class,
R.string.pk_device_admin_add_explanation);
verifySetDeviceAdmin(mExplanationController, admin);
verify(mExplanationController).setExplanation(EXPLANATION);
verify(mSpiedFragment).use(DeviceAdminAddSupportPreferenceController.class,
R.string.pk_device_admin_add_support);
verifySetDeviceAdmin(mSupportController, admin);
verify(mSpiedFragment).use(DeviceAdminAddWarningPreferenceController.class,
R.string.pk_device_admin_add_warning);
verifySetDeviceAdmin(mWarningController, admin);
verify(mSpiedFragment).use(DeviceAdminAddPoliciesPreferenceController.class,
R.string.pk_device_admin_add_policies);
verifySetDeviceAdmin(mPoliciesController, admin);
}
private void verifySetDeviceAdmin(BaseDeviceAdminAddPreferenceController<?> controller,
ComponentName admin) {
verify(controller).setDeviceAdmin(argThat(info->info.getComponent().equals(admin)));
}
}

View File

@@ -0,0 +1,288 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.app.AppOpsManager;
import androidx.preference.TwoStatePreference;
import com.android.car.settings.common.PreferenceController;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settings.enterprise.DeviceAdminAddHeaderPreferenceController.ActivationListener;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class DeviceAdminAddHeaderPreferenceControllerTest extends
BaseEnterprisePreferenceControllerTestCase {
private DeviceAdminAddHeaderPreferenceController mController;
@Mock
private TwoStatePreference mPreference;
@Mock
private ActivationListener mActivationListener;
@Before
public void setController() {
mController = new DeviceAdminAddHeaderPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mController.setDeviceAdmin(mDefaultDeviceAdminInfo);
}
@Test
public void testGetAvailabilityStatus_admin() throws Exception {
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_admin_zoneWrite() throws Exception {
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_admin_zoneRead() throws Exception {
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_admin_zoneHidden() throws Exception {
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin() throws Exception {
DeviceAdminAddHeaderPreferenceController controller =
new DeviceAdminAddHeaderPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneWrite() throws Exception {
DeviceAdminAddHeaderPreferenceController controller =
new DeviceAdminAddHeaderPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneRead() throws Exception {
DeviceAdminAddHeaderPreferenceController controller =
new DeviceAdminAddHeaderPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneHidden() throws Exception {
DeviceAdminAddHeaderPreferenceController controller =
new DeviceAdminAddHeaderPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testOnResumeInternal_inactiveAdmin() throws Exception {
mockInactiveAdmin(mDefaultAdmin);
mController.onResumeInternal(mPreference);
verifyPreferenceSetChecked(mPreference, false);
verifyPreferenceEnabled(mPreference);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
/* restricted= */ true);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_TOAST_WINDOW, /* restricted= */ true);
}
@Test
public void testOnResumeInternal_activeAdmin() throws Exception {
mockActiveAdmin(mDefaultAdmin);
mController.onResumeInternal(mPreference);
verifyPreferenceSetChecked(mPreference, true);
verifyPreferenceEnabled(mPreference);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
/* restricted= */ true);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_TOAST_WINDOW, /* restricted= */ true);
}
@Test
public void testOnResumeInternal_deviceOwner() throws Exception {
mockDeviceOwner();
mController.onResumeInternal(mPreference);
verifyPreferenceSetChecked(mPreference, true);
verifyPreferenceDisabled(mPreference);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
/* restricted= */ true);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_TOAST_WINDOW, /* restricted= */ true);
}
@Test
public void testOnPauseInternal() throws Exception {
mController.onPauseInternal(mPreference);
verifyPreferenceDisabled(mPreference);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
/* restricted= */ false);
verifyAppOpsMgrSetUserRestriction(AppOpsManager.OP_TOAST_WINDOW, /* restricted= */ false);
}
@Test
public void testUpdateState_activeAdminWithNoProperties() throws Exception {
mockActiveAdmin(mDefaultAdmin);
mController.updateState(mPreference);
verifyPreferenceSetChecked(mPreference, true);
verifyPreferenceEnabled(mPreference);
verifyPreferenceTitleSet(mPreference, mDefaultDeviceAdminInfo.loadLabel(mRealPm));
verifyPreferenceSummaryNeverSet(mPreference);
verifyPreferenceIconSet(mPreference);
}
@Test
public void testUpdateState_activeAdminWithAllProperties() throws Exception {
mController.setDeviceAdmin(mFancyDeviceAdminInfo);
mockActiveAdmin(mFancyAdmin);
mController.updateState(mPreference);
verifyPreferenceSetChecked(mPreference, true);
verifyPreferenceEnabled(mPreference);
verifyPreferenceTitleSet(mPreference, mFancyDeviceAdminInfo.loadLabel(mRealPm));
verifyPreferenceSummarySet(mPreference, mFancyDeviceAdminInfo.loadDescription(mRealPm));
verifyPreferenceIconSet(mPreference);
}
@Test
public void testUpdateStatus_inactiveAdmin() throws Exception {
mockInactiveAdmin(mDefaultAdmin);
mController.updateState(mPreference);
verifyPreferenceSetChecked(mPreference, false);
verifyPreferenceEnabled(mPreference);
verifyPreferenceTitleSet(mPreference, mDefaultDeviceAdminInfo.loadLabel(mRealPm));
}
@Test
public void testUpdateStatus_deviceOwner() throws Exception {
mockDeviceOwner();
mController.updateState(mPreference);
verifyPreferenceSetChecked(mPreference, true);
verifyPreferenceDisabled(mPreference);
verifyPreferenceTitleSet(mPreference, mDefaultDeviceAdminInfo.loadLabel(mRealPm));
}
@Test
public void testUpdateStatus_profileOwner() throws Exception {
mockProfileOwner();
mController.updateState(mPreference);
verifyPreferenceSetChecked(mPreference, true);
verifyPreferenceDisabled(mPreference);
verifyPreferenceTitleSet(mPreference, mDefaultDeviceAdminInfo.loadLabel(mRealPm));
}
@Test
public void testHandlePreferenceChanged_activateAdmin_withoutListener() {
mockInactiveAdmin(mDefaultAdmin);
mController.handlePreferenceChanged(mPreference, true);
verifyAdminNeverDeactivated();
verifyAdminActivated();
verifyActivationListenerNotCalled();
}
@Test
public void testHandlePreferenceChanged_activateAdmin_withListener() {
mockInactiveAdmin(mDefaultAdmin);
mController.setActivationListener(mActivationListener);
mController.handlePreferenceChanged(mPreference, true);
verifyAdminNeverDeactivated();
verifyAdminActivated();
verifyActivationListenerCalled(true);
}
@Test
public void testHandlePreferenceChanged_deactivateAdmin_withoutListener() {
mockActiveAdmin(mDefaultAdmin);
mController.handlePreferenceChanged(mPreference, false);
verifyAdminNeverActivated();
verifyAdminDeactivated();
verifyActivationListenerNotCalled();
}
@Test
public void testHandlePreferenceChanged_deactivateAdmin_withListener() {
mockActiveAdmin(mDefaultAdmin);
mController.setActivationListener(mActivationListener);
mController.handlePreferenceChanged(mPreference, false);
verifyAdminNeverActivated();
verifyAdminDeactivated();
verifyActivationListenerCalled(false);
}
private void verifyPreferenceSetChecked(TwoStatePreference preference, boolean isChecked) {
verify(preference).setChecked(isChecked);
}
private void verifyActivationListenerNotCalled() {
verify(mActivationListener, never()).onChanged(anyBoolean());
}
private void verifyActivationListenerCalled(boolean active) {
verify(mActivationListener).onChanged(active);
}
}

View File

@@ -0,0 +1,246 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.Mockito.verify;
import android.app.admin.DeviceAdminInfo.PolicyInfo;
import android.util.Log;
import androidx.preference.Preference;
import com.android.car.settings.common.PreferenceController;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import java.util.ArrayList;
public final class DeviceAdminAddPoliciesPreferenceControllerTest extends
BaseEnterprisePreferenceControllerTestCase {
private static final String TAG = DeviceAdminAddPoliciesPreferenceControllerTest.class
.getSimpleName();
private DeviceAdminAddPoliciesPreferenceController mController;
@Mock
private Preference mPreference;
@Captor
private ArgumentCaptor<CharSequence> mTitleCaptor;
@Before
public void setController() {
mController = new DeviceAdminAddPoliciesPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mController.setDeviceAdmin(mDefaultDeviceAdminInfo);
}
@Test
public void testGetPreferenceType() throws Exception {
assertWithMessage("preference type").that(mController.getPreferenceType())
.isEqualTo(Preference.class);
}
@Test
public void testGetAvailabilityStatus_noAdmin() throws Exception {
DeviceAdminAddPoliciesPreferenceController controller =
new DeviceAdminAddPoliciesPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneWrite() throws Exception {
DeviceAdminAddPoliciesPreferenceController controller =
new DeviceAdminAddPoliciesPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneRead() throws Exception {
DeviceAdminAddPoliciesPreferenceController controller =
new DeviceAdminAddPoliciesPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneHidden() throws Exception {
DeviceAdminAddPoliciesPreferenceController controller =
new DeviceAdminAddPoliciesPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner() throws Exception {
mockDeviceOwner();
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_zoneWrite() throws Exception {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_zoneRead() throws Exception {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_deviceOwner_zoneHidden() throws Exception {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_profileOwner() throws Exception {
mockProfileOwner();
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_zoneWrite() throws Exception {
mockProfileOwner();
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_zoneRead() throws Exception {
mockProfileOwner();
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_profileOwner_zoneHidden() throws Exception {
mockProfileOwner();
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_regularAdmin() throws Exception {
// Admin is neither PO nor DO
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_regularAdmin_zoneWrite() throws Exception {
// Admin is neither PO nor DO
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_regularAdmin_zoneRead() throws Exception {
// Admin is neither PO nor DO
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_regularAdmin_zoneHidden() throws Exception {
// Admin is neither PO nor DO
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testUpdateState_systemUser() throws Exception {
updateStateTest(/* isSystemUser= */ true);
}
@Test
public void testUpdateState_nonSystemUser() throws Exception {
updateStateTest(/* isSystemUser= */ false);
}
private void updateStateTest(boolean isSystemUser) {
// Arrange
if (isSystemUser) {
mockSystemUser();
} else {
mockNonSystemUser();
}
ArrayList<PolicyInfo> usedPolicies = mFancyDeviceAdminInfo.getUsedPolicies();
Log.d(TAG, "Admin policies: " + usedPolicies);
mController.setDeviceAdmin(mFancyDeviceAdminInfo);
// Act
mController.updateState(mPreference);
// Assert
verify(mPreference).setTitle(mTitleCaptor.capture());
Log.d(TAG, "Preference title: " + mTitleCaptor.getValue());
for (PolicyInfo policy : usedPolicies) {
CharSequence itemTitle = mRealContext
.getText(isSystemUser ? policy.label : policy.labelForSecondaryUsers);
assertWithMessage("policy item title")
.that(mTitleCaptor.getValue().toString()).contains(itemTitle);
}
}
}

View File

@@ -0,0 +1,199 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import androidx.preference.Preference;
import com.android.car.settings.common.PreferenceController;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class DeviceAdminAddSupportPreferenceControllerTest extends
BaseEnterprisePreferenceControllerTestCase {
@Mock
private Preference mPreference;
private DeviceAdminAddSupportPreferenceController mController;
@Before
public void setController() {
mController = new DeviceAdminAddSupportPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mController.setDeviceAdmin(mDefaultDeviceAdminInfo);
}
@Test
public void testGetAvailabilityStatus_noAdmin() throws Exception {
DeviceAdminAddSupportPreferenceController controller =
new DeviceAdminAddSupportPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneWrite() throws Exception {
DeviceAdminAddSupportPreferenceController controller =
new DeviceAdminAddSupportPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneRead() throws Exception {
DeviceAdminAddSupportPreferenceController controller =
new DeviceAdminAddSupportPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneHidden() throws Exception {
DeviceAdminAddSupportPreferenceController controller =
new DeviceAdminAddSupportPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_nullMessage() {
mockGetLongSupportMessageForUser(null);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_nullMessage_zoneWrite() {
mockGetLongSupportMessageForUser(null);
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_nullMessage_zoneRead() {
mockGetLongSupportMessageForUser(null);
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_nullMessage_zoneHidden() {
mockGetLongSupportMessageForUser(null);
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyMessage() {
mockGetLongSupportMessageForUser("");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyMessage_zoneWrite() {
mockGetLongSupportMessageForUser("");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyMessage_zoneRead() {
mockGetLongSupportMessageForUser("");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_emptyMessage_zoneHidden() {
mockGetLongSupportMessageForUser("");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_validMessage() {
mockGetLongSupportMessageForUser("WHAZZZZUP");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_validMessage_zoneWrite() {
mockGetLongSupportMessageForUser("WHAZZZZUP");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_validMessage_zoneRead() {
mockGetLongSupportMessageForUser("WHAZZZZUP");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_validMessage_zoneHidden() {
mockGetLongSupportMessageForUser("WHAZZZZUP");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testUpdateState() {
mockGetLongSupportMessageForUser("WHAZZZZUP");
mController.setSupportMessage();
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference, "WHAZZZZUP");
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import androidx.preference.Preference;
import com.android.car.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class DeviceAdminAddWarningPreferenceControllerTest extends
BaseEnterprisePreferenceControllerTestCase {
@Mock
private Preference mPreference;
private DeviceAdminAddWarningPreferenceController mController;
@Before
public void setController() {
mController = new DeviceAdminAddWarningPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mController.setDeviceAdmin(mDefaultDeviceAdminInfo);
}
@Test
public void testUpdateState_adminInactive() {
mockInactiveAdmin(mDefaultAdmin);
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference,
mRealContext.getString(R.string.device_admin_warning, mAppName));
}
@Test
public void testUpdateState_adminActive() {
mockActiveAdmin(mDefaultAdmin);
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference,
mRealContext.getString(R.string.device_admin_status, mAppName));
}
@Test
public void testUpdateState_profileOwner() {
mockProfileOwner();
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference,
mRealContext.getString(R.string.admin_profile_owner_user_message));
}
@Test
public void testUpdateState_deviceOwner() {
mockDeviceOwner();
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference,
mRealContext.getString(R.string.admin_device_owner_message));
}
@Test
public void testUpdateState_deviceOwner_financialDevice() {
mockDeviceOwner();
mockFinancialDevice();
mController.updateState(mPreference);
verifyPreferenceTitleSet(mPreference,
mRealContext.getString(R.string.admin_financed_message));
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import androidx.test.annotation.UiThreadTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.car.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public final class DeviceAdminDeactivatedAppsPreferenceControllerTest
extends BaseEnterprisePreferenceControllerTestCase {
private DeviceAdminAppsPreferenceController mController;
private BaseEnterprisePreferenceControllerTestCase.DummyPreferenceGroup mPreferenceGroup;
@Before
@UiThreadTest
public void setUp() throws Exception {
mController = new DeviceAdminDeactivatedAppsPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
mPreferenceGroup = new DummyPreferenceGroup(mSpiedContext);
}
@Test
public void testUpdateState_noBroadcastReceivers() {
mockQueryBroadcastReceivers();
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup,
mRealContext.getString(R.string.device_admin_apps_list_empty));
}
@Test
public void testUpdateState_noDeactivatedAdminApp() {
mockQueryBroadcastReceivers(mDefaultResolveInfo, mFancyResolveInfo);
mockActiveAdmin(mDefaultAdmin);
mockActiveAdmin(mFancyAdmin);
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup,
mRealContext.getString(R.string.device_admin_apps_list_empty));
}
@Test
public void testUpdateState_singleDeactivatedAdminApp() {
mockQueryBroadcastReceivers(mDefaultResolveInfo, mFancyResolveInfo);
mockActiveAdmin(mDefaultAdmin);
mockInactiveAdmin(mFancyAdmin);
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup, mFancyDeviceAdminInfo.loadLabel(mRealPm));
}
@Test
public void testUpdateState_multipleDeactivatedAdminApps() {
mockQueryBroadcastReceivers(mDefaultResolveInfo, mFancyResolveInfo);
mockInactiveAdmin(mDefaultAdmin);
mockInactiveAdmin(mFancyAdmin);
mController.updateState(mPreferenceGroup);
verifyPreferenceTitles(mPreferenceGroup,
mDefaultDeviceAdminInfo.loadLabel(mRealPm),
mFancyDeviceAdminInfo.loadLabel(mRealPm));
}
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.google.common.truth.Truth.assertThat;
import static org.testng.Assert.expectThrows;
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.car.settings.R;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class DeviceAdminStringProviderImplTest {
private final Context mContext = ApplicationProvider.getApplicationContext();
private final DeviceAdminStringProviderImpl mDeviceAdminStringProvider =
new DeviceAdminStringProviderImpl(mContext);
@Test
public void testDefaultDisabledByPolicyTitle() {
assertThat(mDeviceAdminStringProvider.getDefaultDisabledByPolicyTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title));
}
@Test
public void testDisallowAdjustVolumeTitle() {
assertThat(mDeviceAdminStringProvider.getDisallowAdjustVolumeTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_adjust_volume));
}
@Test
public void testDisallowOutgoingCallsTitle() {
assertThat(mDeviceAdminStringProvider.getDisallowOutgoingCallsTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_outgoing_calls));
}
@Test
public void testDisallowSmsTitle() {
assertThat(mDeviceAdminStringProvider.getDisallowSmsTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_sms));
}
@Test
public void testDisableCameraTitle() {
assertThat(mDeviceAdminStringProvider.getDisableCameraTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_camera));
}
@Test
public void testDisableScreenCaptureTitle() {
assertThat(mDeviceAdminStringProvider.getDisableScreenCaptureTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_screen_capture));
}
@Test
public void testSuspendPackagesTitle() {
assertThat(mDeviceAdminStringProvider.getSuspendPackagesTitle())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_suspend_packages));
}
@Test
public void testDefaultDisabledByPolicyContent() {
assertThat(mDeviceAdminStringProvider.getDefaultDisabledByPolicyContent())
.isEqualTo(mContext.getString(R.string.default_admin_support_msg));
}
@Test
public void testLearnMoreHelpPageUrl() {
assertThat(mDeviceAdminStringProvider.getLearnMoreHelpPageUrl())
.isEqualTo(mContext.getString(R.string.help_url_action_disabled_by_it_admin));
}
@Test
public void testDisabledByPolicyTitleForFinancedDevice() {
assertThat(mDeviceAdminStringProvider.getDisabledByPolicyTitleForFinancedDevice())
.isEqualTo(mContext.getString(R.string.disabled_by_policy_title_financed_device));
}
@Test
public void testDisabledBiometricsParentConsentTitle() {
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class,
() -> mDeviceAdminStringProvider.getDisabledBiometricsParentConsentTitle());
assertThat(e.getMessage()).contains("disabled_by_policy_title_biometric_parental_consent");
}
@Test
public void testDisabledBiometricsParentConsentContent() {
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class,
() -> mDeviceAdminStringProvider.getDisabledBiometricsParentConsentContent());
assertThat(e.getMessage())
.contains("disabled_by_policy_content_biometric_parental_consent");
}
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.google.common.truth.Truth.assertThat;
import android.car.drivingstate.CarUxRestrictions;
import com.android.car.admin.ui.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.ui.preference.CarUiFooterPreference;
import org.junit.Before;
import org.junit.Test;
public final class EnterpriseDisclosurePreferenceControllerTest extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String ORG_NAME = "My Org";
private EnterpriseDisclosurePreferenceController mEnterpriseDisclosurePreferenceController;
private CarUxRestrictions mCarUxRestrictions;
private CarUiFooterPreference mPreference;
@Before
public void setUp() {
mCarUxRestrictions = new CarUxRestrictions.Builder(/* reqOpt= */ true,
CarUxRestrictions.UX_RESTRICTIONS_BASELINE, /* timestamp= */ 0).build();
mPreference = new CarUiFooterPreference(mSpiedContext);
mockHasDeviceAdminFeature();
mEnterpriseDisclosurePreferenceController = new EnterpriseDisclosurePreferenceController(
mSpiedContext, mPreferenceKey, mFragmentController, mCarUxRestrictions);
}
@Test
public void testNoDeviceOwnerComponent_noDisclosure() {
mockNoDeviceOwner();
mEnterpriseDisclosurePreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mEnterpriseDisclosurePreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testNoDeviceOwnerComponent_noDisclosure_zoneWrite() {
mockNoDeviceOwner();
mEnterpriseDisclosurePreferenceController.setAvailabilityStatusForZone("write");
mEnterpriseDisclosurePreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mEnterpriseDisclosurePreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testNoDeviceOwnerComponent_noDisclosure_zoneRead() {
mockNoDeviceOwner();
mEnterpriseDisclosurePreferenceController.setAvailabilityStatusForZone("read");
mEnterpriseDisclosurePreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mEnterpriseDisclosurePreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testNoDeviceOwnerComponent_noDisclosure_zoneHidden() {
mockNoDeviceOwner();
mEnterpriseDisclosurePreferenceController.setAvailabilityStatusForZone("hidden");
mEnterpriseDisclosurePreferenceController.updateState(mPreference);
PreferenceControllerTestUtil.assertAvailability(
mEnterpriseDisclosurePreferenceController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testOrganizationNameAbsent_genericDisclosure() {
mockDeviceOwner();
mockOrganizationName(null);
mEnterpriseDisclosurePreferenceController.updateState(mPreference);
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getSummary().toString()).isEqualTo(mRealContext.getString(
R.string.car_admin_ui_managed_device_message_generic));
}
@Test
public void testOrganizationNamePresent_specificDisclosure() {
mockDeviceOwner();
mockOrganizationName(ORG_NAME);
mEnterpriseDisclosurePreferenceController.updateState(mPreference);
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getSummary().toString()).isEqualTo(mRealContext.getString(
R.string.car_admin_ui_managed_device_message_by_org, ORG_NAME));
}
}

View File

@@ -0,0 +1,241 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import android.util.Log;
import androidx.preference.PreferenceGroup;
import androidx.test.annotation.UiThreadTest;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
import com.android.car.settingslib.applications.ApplicationFeatureProvider.ListOfAppsCallback;
import org.junit.Before;
import org.junit.Test;
public class EnterpriseInstalledPackagesListPreferenceControllerTest extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String TAG = EnterpriseInstalledPackagesListPreferenceControllerTest.class
.getSimpleName();
// Must be a spy to verify refreshUi() is called
private EnterpriseInstalledPackagesListPreferenceController mSpiedController;
private DummyPreferenceGroup mPreferenceGroup;
@Before
@UiThreadTest // Needed to instantiate DummyPreferenceGroup
public void setExtraFixtures() {
mSpiedController = spy(newController(mApplicationFeatureProvider));
mPreferenceGroup = new DummyPreferenceGroup(mSpiedContext);
}
@Test
public void testGetPreferenceType() {
assertWithMessage("preference type").that(mSpiedController.getPreferenceType())
.isEqualTo(PreferenceGroup.class);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps() {
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps_zoneWrite() {
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps_zoneRead() {
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps_zoneHidden() {
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release();
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps_zoneWrite() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps_zoneRead() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps_zoneHidden() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testUpdateState() {
expectUiRefreshed(mSpiedController);
ListOfAppsCallbackHolder callbackHolder = mockListPolicyInstalledApps();
mSpiedController.getAvailabilityStatus();
callbackHolder.release(newUserAppInfo("foo"), newUserAppInfo("bar"));
assertUiRefreshed(mSpiedController);
mSpiedController.updateState(mPreferenceGroup);
assertPreferenceGroupStateSet(mPreferenceGroup, "foo", "bar");
}
private EnterpriseInstalledPackagesListPreferenceController newController(
ApplicationFeatureProvider provider) {
return new EnterpriseInstalledPackagesListPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
private ListOfAppsCallbackHolder mockListPolicyInstalledApps() {
ListOfAppsCallbackHolder callbackHolder = new ListOfAppsCallbackHolder();
doAnswer((inv) -> {
Log.d(TAG, "answering to " + inv);
ListOfAppsCallback callback = (ListOfAppsCallback) inv.getArguments()[0];
callbackHolder.setCallback(callback);
return null;
}).when(mApplicationFeatureProvider).listPolicyInstalledApps(any());
return callbackHolder;
}
}

View File

@@ -0,0 +1,235 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import android.util.Log;
import androidx.preference.Preference;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settingslib.applications.ApplicationFeatureProvider;
import com.android.car.settingslib.applications.ApplicationFeatureProvider.NumberOfAppsCallback;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public class EnterpriseInstalledPackagesPreferenceControllerTest extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String TAG = EnterpriseInstalledPackagesPreferenceControllerTest.class
.getSimpleName();
// Must be a spy to verify refreshUi() is called
private EnterpriseInstalledPackagesPreferenceController mSpiedController;
@Mock
private Preference mPreference;
@Before
public void setController() {
mSpiedController = spy(newController(mApplicationFeatureProvider));
}
@Test
public void testGetAvailabilityStatus_noInstalledApps() {
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps_zoneWrite() {
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps_zoneRead() {
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_noInstalledApps_zoneHidden() {
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(0);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
assertUiNotRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(3);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps_zoneWrite() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("write");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(3);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps_zoneRead() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("read");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(3);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
assertUiRefreshed(mSpiedController);
}
@Test
public void testGetAvailabilityStatus_withInstalledApps_zoneHidden() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.setAvailabilityStatusForZone("hidden");
// Assert initial state
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
// Unblock async call
callbackHolder.release(3);
// Assert post-callback result
PreferenceControllerTestUtil.assertAvailability(mSpiedController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
assertUiRefreshed(mSpiedController);
}
@Test
public void testUpdateState() {
expectUiRefreshed(mSpiedController);
NumberOfAppsCallbackHolder callbackHolder = mockCalculateNumberOfPolicyInstalledApps();
mSpiedController.getAvailabilityStatus();
callbackHolder.release(3);
assertUiRefreshed(mSpiedController);
mSpiedController.updateState(mPreference);
assertPreferenceStateSet(mPreference, 3);
}
private EnterpriseInstalledPackagesPreferenceController newController(
ApplicationFeatureProvider provider) {
return new EnterpriseInstalledPackagesPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, provider);
}
private NumberOfAppsCallbackHolder mockCalculateNumberOfPolicyInstalledApps() {
NumberOfAppsCallbackHolder callbackHolder = new NumberOfAppsCallbackHolder();
doAnswer((inv) -> {
Log.d(TAG, "answering to " + inv);
NumberOfAppsCallback callback = (NumberOfAppsCallback) inv.getArguments()[1];
callbackHolder.setCallback(callback);
return null;
}).when(mApplicationFeatureProvider)
.calculateNumberOfPolicyInstalledApps(/* async= */ eq(true), any());
return callbackHolder;
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static android.car.test.mocks.AndroidMockitoHelper.syncCallOnMainThread;
import static com.google.common.truth.Truth.assertWithMessage;
import androidx.fragment.app.Fragment;
import org.junit.Test;
public final class EnterprisePrivacySettingsActivityTest extends BaseEnterpriseTestCase {
@Test
public void testGetFragment() throws Exception {
Fragment fragment = syncCallOnMainThread(() ->
// EnterprisePrivacySettingsActivity must be created in the main thread
new EnterprisePrivacySettingsActivity().getInitialFragment());
assertWithMessage("initial fragment class").that(fragment)
.isInstanceOf(EnterprisePrivacySettingsFragment.class);
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static android.car.test.mocks.AndroidMockitoHelper.syncCallOnMainThread;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.content.res.XmlResourceParser;
import androidx.fragment.app.FragmentActivity;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class EnterprisePrivacySettingsFragmentTest extends BaseEnterpriseTestCase {
private EnterprisePrivacySettingsFragment mFragment;
@Mock
private FragmentActivity mFragmentActivity;
@Before
public void setFragment() throws Exception {
mFragment = syncCallOnMainThread(() -> new EnterprisePrivacySettingsFragment());
}
@Test
public void testGetPreferenceScreenResId() {
int resId = mFragment.getPreferenceScreenResId();
XmlResourceParser parser = mRealContext.getResources().getXml(resId);
assertWithMessage("xml with id %s", resId).that(parser).isNotNull();
}
@Test
public void testFinishActivityWhenDeviceOwnerIsNotSet() {
mockNotManaged();
mFragment.onAttach(mSpiedContext, mFragmentActivity);
verify(mFragmentActivity).finish();
}
@Test
public void testDoesNotFinishActivityWhenDeviceOwnerIsNotSet() {
mockDeviceOwner();
mFragment.onAttach(mSpiedContext, mFragmentActivity);
verify(mFragmentActivity, never()).finish();
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.UNSUPPORTED_ON_DEVICE;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class EnterprisePrivacySettingsPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private EnterprisePrivacySettingsPreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setController() {
mController = new EnterprisePrivacySettingsPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions);
}
@Test
public void testGetAvailabilityStatus_noFeature() {
mockNoDeviceAdminFeature();
// Must use new controller as availability is set on constructor
EnterprisePrivacySettingsPreferenceController controller =
new EnterprisePrivacySettingsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noFeature_zoneWrite() {
mockNoDeviceAdminFeature();
// Must use new controller as availability is set on constructor
EnterprisePrivacySettingsPreferenceController controller =
new EnterprisePrivacySettingsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noFeature_zoneRead() {
mockNoDeviceAdminFeature();
// Must use new controller as availability is set on constructor
EnterprisePrivacySettingsPreferenceController controller =
new EnterprisePrivacySettingsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noFeature_zoneHidden() {
mockNoDeviceAdminFeature();
// Must use new controller as availability is set on constructor
EnterprisePrivacySettingsPreferenceController controller =
new EnterprisePrivacySettingsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noDeviceOwner() {
mockNoDeviceOwner();
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noDeviceOwner_zoneWrite() {
mockNoDeviceOwner();
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noDeviceOwner_zoneRead() {
mockNoDeviceOwner();
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noDeviceOwner_zoneHidden() {
mockNoDeviceOwner();
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_withDeviceOwner() {
mockDeviceOwner();
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_withDeviceOwner_zoneWrite() {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_withDeviceOwner_zoneRead() {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_withDeviceOwner_zoneHidden() {
mockDeviceOwner();
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testuUdateState() {
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference,
R.string.enterprise_privacy_settings_summary_generic);
verifyPreferenceIconNeverSet(mPreference);
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static android.car.test.mocks.AndroidMockitoHelper.syncCallOnMainThread;
import static com.google.common.truth.Truth.assertWithMessage;
import android.content.res.XmlResourceParser;
import androidx.fragment.app.FragmentActivity;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class EnterpriseSetDefaultAppsListFragmentTest extends BaseEnterpriseTestCase {
private EnterpriseSetDefaultAppsListFragment mFragment;
@Mock
private FragmentActivity mFragmentActivity;
@Before
public void setFragment() throws Exception {
mFragment = syncCallOnMainThread(() -> new EnterpriseSetDefaultAppsListFragment());
}
@Test
public void testGetPreferenceScreenResId() {
int resId = mFragment.getPreferenceScreenResId();
XmlResourceParser parser = mRealContext.getResources().getXml(resId);
assertWithMessage("xml with id %s", resId).that(parser).isNotNull();
}
}

View File

@@ -0,0 +1,333 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.UserInfo;
import android.util.Log;
import androidx.preference.Preference;
import androidx.preference.PreferenceGroup;
import androidx.test.annotation.UiThreadTest;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settings.enterprise.BaseEnterprisePreferenceControllerTestCase.DummyPreferenceGroup;
import com.android.car.settingslib.applications.UserAppInfo;
import com.android.car.settingslib.enterprise.EnterpriseDefaultApps;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public final class EnterpriseSetDefaultAppsListPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String TAG = EnterpriseSetDefaultAppsListPreferenceControllerTest.class
.getSimpleName();
private UserInfo mMyUser;
private EnterpriseSetDefaultAppsListPreferenceController mController;
private DummyPreferenceGroup mPreferenceGroup;
@Before
@UiThreadTest // Needed to instantiate DummyPreferenceGroup
public void setUp() throws Exception {
mController = new EnterpriseSetDefaultAppsListPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, mApplicationFeatureProvider);
int userId = mSpiedContext.getUserId();
mMyUser = new UserInfo(mSpiedContext.getUserId(), "Mambo Number " + userId, /* flags= */ 0);
Log.d(TAG, "myUser: " + mMyUser.toFullString());
mPreferenceGroup = new DummyPreferenceGroup(mSpiedContext);
}
@Test
public void testGetPreferenceType() {
assertWithMessage("preference type").that(mController.getPreferenceType())
.isEqualTo(PreferenceGroup.class);
}
@Test
public void testGetAvailabilityStatus_none() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
// Don't need to mock anything
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_none_zoneWrite() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
// Don't need to mock anything
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_none_zoneRead() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
// Don't need to mock anything
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_none_zoneHidden() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
// Don't need to mock anything
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_one() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_one_zoneWrite() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_one_zoneRead() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_one_zoneHidden() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_cached() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testGetAvailabilityStatus_cached_zoneWrite() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testGetAvailabilityStatus_cached_zoneRead() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testGetAvailabilityStatus_cached_zoneHidden() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app");
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testUpdateState_allSingleApps() {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "app_4");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CALENDAR, "app_8");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CAMERA, "app_15");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CONTACTS, "app_16");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.EMAIL, "app_23");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.MAP, "app_42");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.PHONE, "app_108");
// Must call getAvailabilityStatus() to fetch the list
mController.getAvailabilityStatus();
mController.updateState(mPreferenceGroup);
List<Preference> prefs = mPreferenceGroup.getPreferences();
assertWithMessage("children preferences").that(prefs).hasSize(7);
// NOTE: must be called in the same order as the EnterpriseDefaultApp enums
assertPreference(prefs, 0, getSingleAppsTitle(R.string.default_browser_title), "app_4");
assertPreference(prefs, 1, getSingleAppsTitle(R.string.default_calendar_app_title),
"app_8");
assertPreference(prefs, 2, getMultipleAppsTitle(R.plurals.default_camera_app_title, 1),
"app_15");
assertPreference(prefs, 3, getSingleAppsTitle(R.string.default_contacts_app_title),
"app_16");
assertPreference(prefs, 4, getMultipleAppsTitle(R.plurals.default_email_app_title, 1),
"app_23");
assertPreference(prefs, 5, getSingleAppsTitle(R.string.default_map_app_title), "app_42");
assertPreference(prefs, 6, getMultipleAppsTitle(R.plurals.default_phone_app_title, 1),
"app_108");
}
@Test
public void testUpdateState_allMultipleApps() {
// NOTE: uses "s.." on apps that are single, and "m..." on apps that are multiple
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, "s1", "s2");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CALENDAR, "s1", "s2", "s3");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CAMERA, "m1", "m2");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CONTACTS, "s1", "s2", "s3", "s4");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.EMAIL, "m1", "m2", "m3");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.MAP, "s1", "s2", "s3", "s4");
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.PHONE, "m1", "m2", "m3", "m4");
// Must call getAvailabilityStatus() to fetch the list
mController.getAvailabilityStatus();
mController.updateState(mPreferenceGroup);
List<Preference> prefs = mPreferenceGroup.getPreferences();
assertWithMessage("children preferences").that(prefs).hasSize(7);
// NOTE: must be called in the same order as the EnterpriseDefaultApp enums
assertPreference(prefs, 0, getSingleAppsTitle(R.string.default_browser_title), "s1", "s2");
assertPreference(prefs, 1, getSingleAppsTitle(R.string.default_calendar_app_title), "s1",
"s2", "s3");
assertPreference(prefs, 2, getMultipleAppsTitle(R.plurals.default_camera_app_title, 2),
"m1", "m2");
assertPreference(prefs, 3, getSingleAppsTitle(R.string.default_contacts_app_title), "s1",
"s2", "s3", "s4");
assertPreference(prefs, 4, getMultipleAppsTitle(R.plurals.default_email_app_title, 3),
"m1", "m2", "m3");
assertPreference(prefs, 5, getSingleAppsTitle(R.string.default_map_app_title), "s1", "s2",
"s3", "s4");
assertPreference(prefs, 6, getMultipleAppsTitle(R.plurals.default_phone_app_title, 4),
"m1", "m2", "m3"); // caps at 3, so m4 is ignored
}
private void assertPreference(List<Preference> prefs, int index, CharSequence expectedTitle,
CharSequence... expectedApps) {
CharSequence expectedSummary = getSummary(expectedApps);
Preference pref = prefs.get(index);
Log.d(TAG, "assertPreference() at index #" + index + ": pref=" + pref
+ " expectedTitle: " + expectedTitle
+ " expectedSummary: " + expectedSummary);
assertWithMessage("title of preference #%s", index).that(pref.getTitle())
.isEqualTo(expectedTitle);
assertWithMessage("summary of preference #%s", index).that(pref.getSummary())
.isEqualTo(expectedSummary);
}
/**
* Gets the title for a default app type that can only have one app.
*/
private CharSequence getSingleAppsTitle(int resId) {
return mRealContext.getString(resId);
}
/**
* Gets the title for a default app type that can have multiple apps.
*/
private CharSequence getMultipleAppsTitle(int resId, int numberApps) {
return mRealContext.getResources().getQuantityString(resId, numberApps);
}
private CharSequence getSummary(CharSequence[] appNames) {
switch (appNames.length) {
case 1:
return appNames[0];
case 2:
return mRealContext.getString(R.string.app_names_concatenation_template_2,
appNames[0], appNames[1]);
default:
return mRealContext.getString(R.string.app_names_concatenation_template_3,
appNames[0], appNames[1], appNames[2]);
}
}
private void setEnterpriseSetDefaultApps(EnterpriseDefaultApps typeOfDefault,
String... appNames) {
Intent[] intents = typeOfDefault.getIntents();
int size = appNames.length;
List<UserAppInfo> apps = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
String appName = appNames[i];
ApplicationInfo appInfo = new ApplicationInfo();
appInfo.packageName = appName;
apps.add(new UserAppInfo(mMyUser, appInfo));
}
Log.d(TAG, "mocking " + size + " apps for " + typeOfDefault + ": " + apps);
when(mApplicationFeatureProvider.findPersistentPreferredActivities(eq(mMyUser.id),
argThat(matchesIntents(intents)))).thenReturn(apps);
}
}

View File

@@ -0,0 +1,230 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.UserInfo;
import android.util.Log;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.car.settingslib.applications.UserAppInfo;
import com.android.car.settingslib.enterprise.EnterpriseDefaultApps;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
public final class EnterpriseSetDefaultAppsPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private static final String TAG = EnterpriseSetDefaultAppsPreferenceControllerTest.class
.getSimpleName();
private UserInfo mMyUser;
private EnterpriseSetDefaultAppsPreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setUp() throws Exception {
mController = new EnterpriseSetDefaultAppsPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions, mApplicationFeatureProvider);
int userId = mSpiedContext.getUserId();
mMyUser = new UserInfo(mSpiedContext.getUserId(), "Mambo Number " + userId, /* flags= */ 0);
Log.d(TAG, "myUser: " + mMyUser.toFullString());
}
@Test
public void testGetAvailabilityStatus_none() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_none_zoneWrite() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_none_zoneRead() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_none_zoneHidden() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_one() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_one_zoneWrite() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_one_zoneRead() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_one_zoneHidden() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_cached() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testGetAvailabilityStatus_cached_zoneWrite() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
mController.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testGetAvailabilityStatus_cached_zoneRead() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
mController.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testGetAvailabilityStatus_cached_zoneHidden() throws Exception {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 1);
mController.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
verifyFindPersistentPreferredActivitiesCalledOnce();
}
@Test
public void testUpdateState() {
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER, 4);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CALENDAR, 8);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CAMERA, 15);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.CONTACTS, 16);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.EMAIL, 23);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.MAP, 42);
setEnterpriseSetDefaultApps(EnterpriseDefaultApps.PHONE, 108);
// Must call getAvailabilityStatus() to set the count
mController.getAvailabilityStatus();
mController.updateState(mPreference);
int count = EnterpriseDefaultApps.values().length;
String summary = mRealContext.getResources()
.getQuantityString(R.plurals.enterprise_privacy_number_packages, count, count);
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference, summary);
verifyPreferenceIconNeverSet(mPreference);
}
private void setEnterpriseSetDefaultApps(EnterpriseDefaultApps typeOfDefault, int number) {
Intent[] intents = typeOfDefault.getIntents();
ApplicationInfo appInfo = new ApplicationInfo();
appInfo.packageName = "app";
for (int i = 0; i < number; i++) {
List<UserAppInfo> apps = new ArrayList<>(number);
apps.add(new UserAppInfo(mMyUser, appInfo));
when(mApplicationFeatureProvider.findPersistentPreferredActivities(eq(mMyUser.id),
argThat(matchesIntents(intents)))).thenReturn(apps);
}
}
}

View File

@@ -0,0 +1,171 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.enterprise.EnterpriseUtils.getAdminWithinPackage;
import static com.android.car.settings.enterprise.EnterpriseUtils.getDeviceAdminInfo;
import static com.android.car.settings.enterprise.EnterpriseUtils.hasDeviceOwner;
import static com.android.car.settings.enterprise.EnterpriseUtils.hasUserRestrictionByDpm;
import static com.android.car.settings.enterprise.EnterpriseUtils.hasUserRestrictionByUm;
import static com.android.car.settings.enterprise.EnterpriseUtils.isAdminUser;
import static com.android.car.settings.enterprise.EnterpriseUtils.isDemoUser;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.when;
import android.app.admin.DeviceAdminInfo;
import android.content.ComponentName;
import android.os.UserManager;
import com.android.dx.mockito.inline.extended.ExtendedMockito;
import org.junit.Test;
public final class EnterpriseUtilsTest extends BaseEnterpriseTestCase {
private static final String TEST_RESTRICTION = "test_restriction";
@Test
public void testGetAdminWithinPackage_notFound() {
ComponentName admin = getAdminWithinPackage(mSpiedContext, mPackageName);
assertWithMessage("Admin for %s", mPackageName).that(admin).isNull();
}
@Test
public void testGetAdminWithinPackage_found() {
mockGetActiveAdmins(mDefaultAdmin);
ComponentName admin = getAdminWithinPackage(mSpiedContext, mPackageName);
assertWithMessage("Admin for %s", mPackageName).that(admin).isEqualTo(mDefaultAdmin);
}
@Test
public void testGetDeviceAdminInfo_notFound() {
ComponentName admin = new ComponentName("Bond", "James Bond");
DeviceAdminInfo info = getDeviceAdminInfo(mSpiedContext, admin);
assertWithMessage("Device admin for %s", admin).that(info).isNull();
}
@Test
public void testGetDeviceAdminInfo_found() {
DeviceAdminInfo info = getDeviceAdminInfo(mSpiedContext, mDefaultAdmin);
assertWithMessage("Device admin for %s", mDefaultAdmin).that(info).isNotNull();
assertWithMessage("Component for %s", info).that(info.getComponent())
.isEqualTo(mDefaultAdmin);
}
@Test
public void testIsDemoUser_notDemoMode_notDemoUser() {
ExtendedMockito.doReturn(false)
.when(() -> UserManager.isDeviceInDemoMode(mSpiedContext));
when(mUm.isDemoUser()).thenReturn(false);
assertThat(isDemoUser(mSpiedContext)).isFalse();
}
@Test
public void testIsDemoUser_notDemoMode_demoUser() {
ExtendedMockito.doReturn(false)
.when(() -> UserManager.isDeviceInDemoMode(mSpiedContext));
when(mUm.isDemoUser()).thenReturn(true);
assertThat(isDemoUser(mSpiedContext)).isFalse();
}
@Test
public void testIsDemoUser_demoMode_notDemoUser() {
ExtendedMockito.doReturn(false)
.when(() -> UserManager.isDeviceInDemoMode(mSpiedContext));
when(mUm.isDemoUser()).thenReturn(false);
assertThat(isDemoUser(mSpiedContext)).isFalse();
}
@Test
public void testIsDemoUser_demoMode_demoUser() {
ExtendedMockito.doReturn(true)
.when(() -> UserManager.isDeviceInDemoMode(mSpiedContext));
when(mUm.isDemoUser()).thenReturn(true);
assertThat(isDemoUser(mSpiedContext)).isTrue();
}
@Test
public void testIsAdminUser_true() {
when(mUm.isAdminUser()).thenReturn(true);
assertThat(isAdminUser(mSpiedContext)).isTrue();
}
@Test
public void testUserRestriction_notBaseRestricted_notUmRestricted() {
when(mUm.hasBaseUserRestriction(eq(TEST_RESTRICTION), any())).thenReturn(false);
when(mUm.hasUserRestriction(TEST_RESTRICTION)).thenReturn(false);
assertThat(hasUserRestrictionByUm(mSpiedContext, TEST_RESTRICTION)).isFalse();
assertThat(hasUserRestrictionByDpm(mSpiedContext, TEST_RESTRICTION)).isFalse();
}
@Test
public void testUserRestriction_baseRestricted_umRestricted() {
when(mUm.hasBaseUserRestriction(eq(TEST_RESTRICTION), any())).thenReturn(true);
assertThat(hasUserRestrictionByUm(mSpiedContext, TEST_RESTRICTION)).isTrue();
assertThat(hasUserRestrictionByDpm(mSpiedContext, TEST_RESTRICTION)).isFalse();
}
@Test
public void testUserRestriction_notBaseRestricted_umRestricted() {
when(mUm.hasBaseUserRestriction(eq(TEST_RESTRICTION), any())).thenReturn(false);
when(mUm.hasUserRestriction(TEST_RESTRICTION)).thenReturn(true);
assertThat(hasUserRestrictionByUm(mSpiedContext, TEST_RESTRICTION)).isFalse();
assertThat(hasUserRestrictionByDpm(mSpiedContext, TEST_RESTRICTION)).isTrue();
}
@Test
public void testHasDeviceOwner_unmanagedDevice() {
when(mDpm.isDeviceManaged()).thenReturn(false);
assertThat(hasDeviceOwner(mSpiedContext)).isFalse();
}
@Test
public void testHasDeviceOwner_managedDevice_noDeviceOwnerComponent() {
when(mDpm.isDeviceManaged()).thenReturn(true);
when(mDpm.getDeviceOwnerComponentOnAnyUser()).thenReturn(null);
assertThat(hasDeviceOwner(mSpiedContext)).isFalse();
}
@Test
public void testHasDeviceOwner() {
when(mDpm.isDeviceManaged()).thenReturn(true);
when(mDpm.getDeviceOwnerComponentOnAnyUser())
.thenReturn(new ComponentName("testPackage", "testClass"));
assertThat(hasDeviceOwner(mSpiedContext)).isTrue();
}
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static org.mockito.Mockito.when;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceController;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class FailedPasswordWipeCurrentUserPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private FailedPasswordWipeCurrentUserPreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setUp() throws Exception {
mController = new FailedPasswordWipeCurrentUserPreferenceController(mSpiedContext,
mPreferenceKey, mFragmentController, mUxRestrictions,
mEnterprisePrivacyFeatureProvider);
}
@Test
public void testGetAvailabilityStatus_maxNotSet() throws Exception {
mockGetMaximumFailedPasswordsForWipe(0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_maxNotSet_zoneWrite() throws Exception {
mController.setAvailabilityStatusForZone("write");
mockGetMaximumFailedPasswordsForWipe(0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_maxNotSet_zoneRead() throws Exception {
mController.setAvailabilityStatusForZone("read");
mockGetMaximumFailedPasswordsForWipe(0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_maxNotSet_zoneHidden() throws Exception {
mController.setAvailabilityStatusForZone("hidden");
mockGetMaximumFailedPasswordsForWipe(0);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGetAvailabilityStatus_maxSet() throws Exception {
mockGetMaximumFailedPasswordsForWipe(42);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_maxSet_zoneWrite() throws Exception {
mController.setAvailabilityStatusForZone("write");
mockGetMaximumFailedPasswordsForWipe(42);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_maxSet_zoneRead() throws Exception {
mController.setAvailabilityStatusForZone("read");
mockGetMaximumFailedPasswordsForWipe(42);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_maxSet_zoneHidden() throws Exception {
mController.setAvailabilityStatusForZone("hidden");
mockGetMaximumFailedPasswordsForWipe(42);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
PreferenceController.CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testUpdateState_set() {
mockGetMaximumFailedPasswordsForWipe(42);
mController.updateState(mPreference);
String expectedSummary = mRealContext.getResources().getQuantityString(
R.plurals.enterprise_privacy_number_failed_password_wipe, 42, 42);
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference, expectedSummary);
verifyPreferenceIconNeverSet(mPreference);
}
private void mockGetMaximumFailedPasswordsForWipe(int max) {
when(mEnterprisePrivacyFeatureProvider.getMaximumFailedPasswordsBeforeWipeInCurrentUser())
.thenReturn(max);
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import android.app.admin.DeviceAdminReceiver;
public final class FancyDeviceAdminReceiver extends DeviceAdminReceiver {
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static org.mockito.Mockito.when;
import android.net.ConnectivityManager;
import android.net.ProxyInfo;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class GlobalHttpProxyPreferenceControllerTest extends
BaseEnterprisePrivacyPreferenceControllerTestCase {
private GlobalHttpProxyPreferenceController mGlobalHttpProxyPreferenceController;
@Mock
private ConnectivityManager mConnectivityManager;
@Before
public void setUp() {
when(mSpiedContext.getSystemService(ConnectivityManager.class))
.thenReturn(mConnectivityManager);
mGlobalHttpProxyPreferenceController = new GlobalHttpProxyPreferenceController(
mSpiedContext, mPreferenceKey, mFragmentController, mUxRestrictions);
}
@Test
public void testGlobalProxyNotSet_disablesPreference() {
when(mConnectivityManager.getGlobalProxy()).thenReturn(
ProxyInfo.buildDirectProxy("test.com", 43));
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(), AVAILABLE);
}
@Test
public void testGlobalProxyNotSet_disablesPreference_zoneWrite() {
mGlobalHttpProxyPreferenceController.setAvailabilityStatusForZone("write");
when(mConnectivityManager.getGlobalProxy()).thenReturn(
ProxyInfo.buildDirectProxy("test.com", 43));
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(), AVAILABLE);
}
@Test
public void testGlobalProxyNotSet_disablesPreference_zoneRead() {
mGlobalHttpProxyPreferenceController.setAvailabilityStatusForZone("read");
when(mConnectivityManager.getGlobalProxy()).thenReturn(
ProxyInfo.buildDirectProxy("test.com", 43));
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGlobalProxyNotSet_disablesPreference_zoneHidden() {
mGlobalHttpProxyPreferenceController.setAvailabilityStatusForZone("hidden");
when(mConnectivityManager.getGlobalProxy()).thenReturn(
ProxyInfo.buildDirectProxy("test.com", 43));
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testGlobalProxySet_enablesPreference() {
when(mConnectivityManager.getGlobalProxy()).thenReturn(null);
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(), DISABLED_FOR_PROFILE);
}
@Test
public void testGlobalProxySet_enablesPreference_zoneWrite() {
mGlobalHttpProxyPreferenceController.setAvailabilityStatusForZone("write");
when(mConnectivityManager.getGlobalProxy()).thenReturn(null);
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(), DISABLED_FOR_PROFILE);
}
@Test
public void testGlobalProxySet_enablesPreference_zoneRead() {
mGlobalHttpProxyPreferenceController.setAvailabilityStatusForZone("read");
when(mConnectivityManager.getGlobalProxy()).thenReturn(null);
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(), DISABLED_FOR_PROFILE);
}
@Test
public void testGlobalProxySet_enablesPreference_zoneHidden() {
mGlobalHttpProxyPreferenceController.setAvailabilityStatusForZone("hidden");
when(mConnectivityManager.getGlobalProxy()).thenReturn(null);
PreferenceControllerTestUtil.assertAvailability(
mGlobalHttpProxyPreferenceController.getAvailabilityStatus(), DISABLED_FOR_PROFILE);
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static org.mockito.Mockito.when;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class ImePreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private ImePreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setUp() throws Exception {
mController = new ImePreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions, mEnterprisePrivacyFeatureProvider);
}
@Test
public void testGetgetAvailabilityStatus_notSet() {
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet(null);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetgetAvailabilityStatus_notSet_zoneWrite() {
mController.setAvailabilityStatusForZone("write");
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet(null);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetgetAvailabilityStatus_notSet_zoneRead() {
mController.setAvailabilityStatusForZone("read");
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet(null);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetgetAvailabilityStatus_notSet_zoneHidden() {
mController.setAvailabilityStatusForZone("hidden");
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet(null);
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetgetAvailabilityStatus_set() {
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet("Da Lablue");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetgetAvailabilityStatus_set_zoneWrite() {
mController.setAvailabilityStatusForZone("write");
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet("Da Lablue");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetgetAvailabilityStatus_set_zoneRead() {
mController.setAvailabilityStatusForZone("read");
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet("Da Lablue");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetgetAvailabilityStatus_set_zoneHidden() {
mController.setAvailabilityStatusForZone("hidden");
mockHasDeviceAdminFeature();
mockGetImeLabelIfOwnerSet("Da Lablue");
PreferenceControllerTestUtil.assertAvailability(mController.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testUpdateState_set() {
mockGetImeLabelIfOwnerSet("Da Lablue");
mController.updateState(mPreference);
String summary = mRealContext.getResources()
.getString(R.string.enterprise_privacy_input_method_name, "Da Lablue");
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference, summary);
verifyPreferenceIconNeverSet(mPreference);
}
private void mockGetImeLabelIfOwnerSet(String label) {
when(mEnterprisePrivacyFeatureProvider.getImeLabelIfOwnerSet()).thenReturn(label);
}
}

View File

@@ -0,0 +1,161 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.UNSUPPORTED_ON_DEVICE;
import android.content.ComponentName;
import androidx.preference.Preference;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import com.android.settingslib.utils.StringUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public final class ManageDeviceAdminPreferenceControllerTest
extends BaseEnterprisePreferenceControllerTestCase {
private Preference mPreference;
@Test
public void testUpdateState_noActiveAdminApps() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
mockGetActiveAdmins();
controller.updateState(mPreference);
assertPreferenceSummary(mPreference,
mRealContext.getString(R.string.number_of_device_admins_none));
}
@Test
public void testUpdateState_singleActiveAdminApp() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
mockGetActiveAdmins(ComponentName.createRelative("packageName", "className"));
controller.updateState(mPreference);
assertPreferenceSummary(mPreference,
StringUtil.getIcuPluralsString(mRealContext, 1, R.string.number_of_device_admins));
}
@Test
public void testUpdateState_multipleActiveAdminApps() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
mockGetActiveAdmins(ComponentName.createRelative("packageName1", "className1"),
ComponentName.createRelative("packageName2", "className2"));
controller.updateState(mPreference);
assertPreferenceSummary(mPreference,
StringUtil.getIcuPluralsString(mRealContext, 2, R.string.number_of_device_admins));
}
@Test
public void testGetAvailabilityStatus_deviceAdminDisabled() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureDisabled();
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_deviceAdminDisabled_zoneWrite() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureDisabled();
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_deviceAdminDisabled_zoneRead() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureDisabled();
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_deviceAdminDisabled_zoneHidden() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureDisabled();
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_deviceAdminEnabled() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceAdminEnabled_zoneWrite() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_deviceAdminEnabled_zoneRead() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_deviceAdminEnabled_zoneHidden() {
ManageDeviceAdminPreferenceController controller = newControllerWithFeatureEnabled();
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
private ManageDeviceAdminPreferenceController newControllerWithFeatureDisabled() {
mockNoDeviceAdminFeature();
return newController();
}
private ManageDeviceAdminPreferenceController newControllerWithFeatureEnabled() {
mockHasDeviceAdminFeature();
ManageDeviceAdminPreferenceController controller = newController();
return controller;
}
private ManageDeviceAdminPreferenceController newController() {
mPreference = new Preference(mSpiedContext);
return new ManageDeviceAdminPreferenceController(
mSpiedContext, mPreferenceKey, mFragmentController, mUxRestrictions);
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import android.text.format.DateUtils;
import androidx.preference.Preference;
import com.android.car.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class NetworkLogsPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private NetworkLogsPreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setUp() throws Exception {
mController = new NetworkLogsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
}
@Test
public void testUpdateState_noLogs() {
mockGetLastNetworkLogRetrievalTime(-1);
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference, R.string.enterprise_privacy_none);
verifyPreferenceIconNeverSet(mPreference);
}
@Test
public void testUpdateState_withLogs() {
long now = System.currentTimeMillis();
mockGetLastNetworkLogRetrievalTime(now);
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
String formattedDate = DateUtils.formatDateTime(mRealContext, now,
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE);
verifyPreferenceSummarySet(mPreference, formattedDate);
verifyPreferenceIconNeverSet(mPreference);
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import android.text.format.DateUtils;
import androidx.preference.Preference;
import com.android.car.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
public final class SecurityLogsPreferenceControllerTest
extends BaseEnterprisePrivacyPreferenceControllerTestCase {
private SecurityLogsPreferenceController mController;
@Mock
private Preference mPreference;
@Before
public void setUp() throws Exception {
mController = new SecurityLogsPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
}
@Test
public void testUpdateState_noLogs() {
mockGetLastSecurityLogRetrievalTime(-1);
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
verifyPreferenceSummarySet(mPreference, R.string.enterprise_privacy_none);
verifyPreferenceIconNeverSet(mPreference);
}
@Test
public void testUpdateState_withLogs() {
long now = System.currentTimeMillis();
mockGetLastSecurityLogRetrievalTime(now);
mController.updateState(mPreference);
verifyPreferenceTitleNeverSet(mPreference);
String formattedDate = DateUtils.formatDateTime(mRealContext, now,
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE);
verifyPreferenceSummarySet(mPreference, formattedDate);
verifyPreferenceIconNeverSet(mPreference);
}
}

View File

@@ -0,0 +1,334 @@
/*
* Copyright (C) 2021 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.car.settings.enterprise;
import static android.car.test.mocks.CarArgumentMatchers.intentFor;
import static com.android.car.settings.common.PreferenceController.AVAILABLE;
import static com.android.car.settings.common.PreferenceController.AVAILABLE_FOR_VIEWING;
import static com.android.car.settings.common.PreferenceController.CONDITIONALLY_UNAVAILABLE;
import static com.android.car.settings.common.PreferenceController.DISABLED_FOR_PROFILE;
import static com.android.car.settings.common.PreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.provider.Settings;
import androidx.preference.Preference;
import com.android.car.settings.R;
import com.android.car.settings.common.PreferenceControllerTestUtil;
import org.junit.Test;
import org.mockito.Mock;
import java.util.Arrays;
public final class WorkPolicyInfoPreferenceControllerTest
extends BaseEnterprisePreferenceControllerTestCase {
@Mock
private ResolveInfo mResolveInfo;
@Mock
private Preference mPreference;
@Test
public void testGetPreferenceType() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
assertWithMessage("preferenceType").that(controller.getPreferenceType())
.isEqualTo(Preference.class);
}
@Test
public void testGetAvailabilityStatus_noFeature() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureDisabled();
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noFeature_zoneWrite() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureDisabled();
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noFeature_zoneRead() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureDisabled();
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noFeature_zoneHidden() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureDisabled();
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
UNSUPPORTED_ON_DEVICE);
}
@Test
public void testGetAvailabilityStatus_noAdmin() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
// Don't need to mock anything else
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneWrite() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
// Don't need to mock anything else
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneRead() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
// Don't need to mock anything else
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_noAdmin_zoneHidden() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
// Don't need to mock anything else
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_adminWithoutReceiver() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
// Don't need to mock anything else
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_adminWithoutReceiver_zoneWrite() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
// Don't need to mock anything else
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_adminWithoutReceiver_zoneRead() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
// Don't need to mock anything else
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_adminWithoutReceiver_zoneHidden() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
// Don't need to mock anything else
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
DISABLED_FOR_PROFILE);
}
@Test
public void testGetAvailabilityStatus_adminWithReceiver() {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
mockHasIntent();
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_adminWithReceiver_zoneWrite() {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
mockHasIntent();
controller.setAvailabilityStatusForZone("write");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
AVAILABLE);
}
@Test
public void testGetAvailabilityStatus_adminWithReceiver_zoneRead() {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
mockHasIntent();
controller.setAvailabilityStatusForZone("read");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
AVAILABLE_FOR_VIEWING);
}
@Test
public void testGetAvailabilityStatus_adminWithReceiver_zoneHidden() {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
mockHasIntent();
controller.setAvailabilityStatusForZone("hidden");
PreferenceControllerTestUtil.assertAvailability(controller.getAvailabilityStatus(),
CONDITIONALLY_UNAVAILABLE);
}
@Test
public void testUpdateStatus_noFeature() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureDisabled();
// Don't need to mock anything else
controller.updateState(mPreference);
verifyPreferenceIntentNotSet();
verifyPreferenceTitleNotSet();
}
@Test
public void testUpdateStatus_noAdmin() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
// Don't need to mock anything else
controller.updateState(mPreference);
verifyPreferenceIntentNotSet();
}
@Test
public void testUpdateStatus_adminWithoutReceiver() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
// Don't need to mock anything else
controller.updateState(mPreference);
verifyPreferenceIntentNotSet();
verifyPreferenceTitleNotSet();
}
@Test
public void testUpdateStatus_adminWithReceiver() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
mockHasIntent();
controller.updateState(mPreference);
verifyPreferenceIntentSet();
verifyPreferenceTitleSet();
}
@Test
public void testUpdateStatus_adminWithReceiverButNoPackageInfo() throws Exception {
WorkPolicyInfoPreferenceController controller = newControllerWithFeatureEnabled();
mockProfileOwner();
mockHasIntent();
mockAppInfoMissing();
controller.updateState(mPreference);
verifyPreferenceIntentNotSet();
verifyPreferenceTitleNotSet();
}
// Must create new instances on demand as the feature check is done on constructor
private WorkPolicyInfoPreferenceController newControllerWithFeatureDisabled() {
mockNoDeviceAdminFeature();
return newController();
}
// Must create new instances on demand as the feature check is done on constructor
private WorkPolicyInfoPreferenceController newControllerWithFeatureEnabled() {
mockHasDeviceAdminFeature();
return newController();
}
private WorkPolicyInfoPreferenceController newController() {
return new WorkPolicyInfoPreferenceController(mSpiedContext, mPreferenceKey,
mFragmentController, mUxRestrictions);
}
private void mockHasIntent() {
// Must use doReturn() instead of when() because it's a spy
doReturn(Arrays.asList(mResolveInfo)).when(mSpiedPm)
.queryIntentActivities(showWorkPolicyInfoIntent(), eq(/* flags= */ 0));
}
private void mockAppInfoMissing() throws NameNotFoundException {
// Must use doThrow() instead of when() because it's a spy
doThrow(new NameNotFoundException("D'OH!")).when(mSpiedPm).getApplicationInfo(mPackageName,
/* flags= */ 0);
}
private Intent showWorkPolicyInfoIntent() {
return intentFor(Settings.ACTION_SHOW_WORK_POLICY_INFO, mDefaultAdmin.getPackageName());
}
private void verifyPreferenceIntentNotSet() {
verify(mPreference, never()).setIntent(any());
}
private void verifyPreferenceIntentSet() {
verify(mPreference).setIntent(showWorkPolicyInfoIntent());
}
private void verifyPreferenceTitleNotSet() {
verify(mPreference, never()).setTitle(any());
}
private void verifyPreferenceTitleSet() {
verify(mPreference).setTitle(mRealContext.getString(R.string.work_policy_privacy_settings,
mAppName));
}
}