diff options
| author | 2020-11-02 15:08:22 +0000 | |
|---|---|---|
| committer | 2020-11-02 15:08:22 +0000 | |
| commit | 67dd9ce1301f431c4b4a213eabf028aba241c83c (patch) | |
| tree | bed9a5fb5369b8d2472981f9dcfef3180ba7ddd7 | |
| parent | 43526ef6a46b5e7259f08076141298a47237126d (diff) | |
| parent | fd65c456b53abc6f397587ff0fb993da3d8e6e3a (diff) | |
Merge "DevicePolicyManager unit test improvements:"
12 files changed, 1505 insertions, 1176 deletions
diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyConstantsTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyConstantsTest.java index be05245deea1..9660d6ba2f74 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyConstantsTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyConstantsTest.java @@ -15,33 +15,33 @@ */ package com.android.server.devicepolicy; -import android.test.AndroidTestCase; +import static com.google.common.truth.Truth.assertThat; + import android.test.suitebuilder.annotation.SmallTest; +import org.junit.Test; + /** * Test for {@link DevicePolicyConstants}. * - m FrameworksServicesTests && - adb install \ - -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && - adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyConstantsTest \ - -w com.android.frameworks.servicestests - - - -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner + * <p>Run this test with: + * + * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.DevicePolicyConstantsTest} */ @SmallTest -public class DevicePolicyConstantsTest extends AndroidTestCase { +public class DevicePolicyConstantsTest { private static final String TAG = "DevicePolicyConstantsTest"; + @Test public void testDefaultValues() throws Exception { final DevicePolicyConstants constants = DevicePolicyConstants.loadFromString(""); - assertEquals(1 * 60 * 60, constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_SEC); - assertEquals(24 * 60 * 60, constants.DAS_DIED_SERVICE_RECONNECT_MAX_BACKOFF_SEC); - assertEquals(2.0, constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_INCREASE); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_SEC).isEqualTo(1 * 60 * 60); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_MAX_BACKOFF_SEC).isEqualTo(24 * 60 * 60); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_INCREASE).isWithin(1.0e-10).of(2.0); } + @Test public void testCustomValues() throws Exception { final DevicePolicyConstants constants = DevicePolicyConstants.loadFromString( "das_died_service_reconnect_backoff_sec=10," @@ -49,11 +49,13 @@ public class DevicePolicyConstantsTest extends AndroidTestCase { + "das_died_service_reconnect_max_backoff_sec=15" ); - assertEquals(10, constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_SEC); - assertEquals(15, constants.DAS_DIED_SERVICE_RECONNECT_MAX_BACKOFF_SEC); - assertEquals(1.25, constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_INCREASE); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_SEC).isEqualTo(10); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_MAX_BACKOFF_SEC).isEqualTo(15); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_INCREASE).isWithin(1.0e-10) + .of(1.25); } + @Test public void testMinMax() throws Exception { final DevicePolicyConstants constants = DevicePolicyConstants.loadFromString( "das_died_service_reconnect_backoff_sec=3," @@ -61,8 +63,8 @@ public class DevicePolicyConstantsTest extends AndroidTestCase { + "das_died_service_reconnect_max_backoff_sec=1" ); - assertEquals(5, constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_SEC); - assertEquals(5, constants.DAS_DIED_SERVICE_RECONNECT_MAX_BACKOFF_SEC); - assertEquals(1.0, constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_INCREASE); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_SEC).isEqualTo(5); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_MAX_BACKOFF_SEC).isEqualTo(5); + assertThat(constants.DAS_DIED_SERVICE_RECONNECT_BACKOFF_INCREASE).isWithin(1.0e-10).of(1.0); } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyEventLoggerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyEventLoggerTest.java index b24bca8fc050..350b390a2130 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyEventLoggerTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyEventLoggerTest.java @@ -46,8 +46,8 @@ public class DevicePolicyEventLoggerTest { .setTimePeriod(1234L); assertThat(eventLogger.getEventId()).isEqualTo(5); assertThat(eventLogger.getBoolean()).isTrue(); - assertThat(eventLogger.getStringArray()) - .isEqualTo(new String[] {"string1", "string2", "string3"}); + assertThat(eventLogger.getStringArray()).asList() + .containsExactly("string1", "string2", "string3"); assertThat(eventLogger.getAdminPackageName()).isEqualTo("com.test.package"); assertThat(eventLogger.getInt()).isEqualTo(4321); assertThat(eventLogger.getTimePeriod()).isEqualTo(1234L); @@ -57,23 +57,22 @@ public class DevicePolicyEventLoggerTest { public void testStrings() { assertThat(DevicePolicyEventLogger .createEvent(0) - .setStrings("string1", "string2", "string3").getStringArray()) - .isEqualTo(new String[] {"string1", "string2", "string3"}); + .setStrings("string1", "string2", "string3").getStringArray()).asList() + .containsExactly("string1", "string2", "string3").inOrder(); assertThat(DevicePolicyEventLogger .createEvent(0) .setStrings("string1", new String[] {"string2", "string3"}).getStringArray()) - .isEqualTo(new String[] {"string1", "string2", "string3"}); + .asList().containsExactly("string1", "string2", "string3").inOrder(); assertThat(DevicePolicyEventLogger .createEvent(0) .setStrings("string1", "string2", new String[] {"string3"}).getStringArray()) - .isEqualTo(new String[] {"string1", "string2", "string3"}); - + .asList().containsExactly("string1", "string2", "string3").inOrder(); assertThat(DevicePolicyEventLogger .createEvent(0) - .setStrings((String) null).getStringArray()) - .isEqualTo(new String[] {null}); + .setStrings((String) null).getStringArray()).asList() + .containsExactly((String) null); assertThat(DevicePolicyEventLogger .createEvent(0) @@ -106,8 +105,8 @@ public class DevicePolicyEventLoggerTest { .createEvent(0); assertThat(eventLogger.getEventId()).isEqualTo(0); assertThat(eventLogger.getBoolean()).isFalse(); - assertThat(eventLogger.getStringArray()).isEqualTo(null); - assertThat(eventLogger.getAdminPackageName()).isEqualTo(null); + assertThat(eventLogger.getStringArray()).isNull(); + assertThat(eventLogger.getAdminPackageName()).isNull(); assertThat(eventLogger.getInt()).isEqualTo(0); assertThat(eventLogger.getTimePeriod()).isEqualTo(0L); } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java index 3167820f0a48..fa3f45c08202 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java @@ -20,7 +20,9 @@ import static android.os.UserHandle.USER_SYSTEM; import static com.android.server.devicepolicy.DpmTestUtils.writeInputStreamToFile; import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME; -import static org.junit.Assert.assertArrayEquals; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; @@ -43,17 +45,23 @@ import android.platform.test.annotations.Presubmit; import android.provider.Settings; import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; import com.android.frameworks.servicestests.R; import com.android.server.LocalServices; import com.android.server.SystemService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Set; @Presubmit +@RunWith(AndroidJUnit4.class) public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { private static final String USER_TYPE_EMPTY = ""; @@ -63,9 +71,8 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { private DpmMockContext mContext; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { mContext = getContext(); @@ -77,6 +84,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { .thenReturn(true); } + @Test public void testMigration() throws Exception { final File user10dir = getServices().addUser(10, 0, USER_TYPE_EMPTY); final File user11dir = getServices().addUser(11, 0, @@ -160,19 +168,19 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { mContext.binder.restoreCallingIdentity(ident); } - assertTrue(dpms.mOwners.hasDeviceOwner()); - assertFalse(dpms.mOwners.hasProfileOwner(USER_SYSTEM)); - assertTrue(dpms.mOwners.hasProfileOwner(10)); - assertTrue(dpms.mOwners.hasProfileOwner(11)); - assertFalse(dpms.mOwners.hasProfileOwner(12)); + assertThat(dpms.mOwners.hasDeviceOwner()).isTrue(); + assertThat(dpms.mOwners.hasProfileOwner(USER_SYSTEM)).isFalse(); + assertThat(dpms.mOwners.hasProfileOwner(10)).isTrue(); + assertThat(dpms.mOwners.hasProfileOwner(11)).isTrue(); + assertThat(dpms.mOwners.hasProfileOwner(12)).isFalse(); // Now all information should be migrated. - assertFalse(dpms.mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration( - USER_SYSTEM)); - assertFalse(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(12)); + assertThat(dpms.mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(USER_SYSTEM)) + .isFalse(); + assertThat(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(12)).isFalse(); // Check the new base restrictions. DpmTestUtils.assertRestrictions( @@ -221,6 +229,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { dpms.getProfileOwnerAdminLocked(11).ensureUserRestrictions()); } + @Test public void testMigration2_profileOwnerOnUser0() throws Exception { setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); @@ -271,13 +280,13 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { } finally { mContext.binder.restoreCallingIdentity(ident); } - assertFalse(dpms.mOwners.hasDeviceOwner()); - assertTrue(dpms.mOwners.hasProfileOwner(USER_SYSTEM)); + assertThat(dpms.mOwners.hasDeviceOwner()).isFalse(); + assertThat(dpms.mOwners.hasProfileOwner(USER_SYSTEM)).isTrue(); // Now all information should be migrated. - assertFalse(dpms.mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration( - USER_SYSTEM)); + assertThat(dpms.mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(dpms.mOwners.getProfileOwnerUserRestrictionsNeedsMigration(USER_SYSTEM)) + .isFalse(); // Check the new base restrictions. DpmTestUtils.assertRestrictions( @@ -297,6 +306,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { } // Test setting default restrictions for managed profile. + @Test public void testMigration3_managedProfileOwner() throws Exception { // Create a managed profile user. final File user10dir = getServices().addUser(10, 0, @@ -339,8 +349,8 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { mContext.binder.restoreCallingIdentity(ident); } - assertFalse(dpms.mOwners.hasDeviceOwner()); - assertTrue(dpms.mOwners.hasProfileOwner(10)); + assertThat(dpms.mOwners.hasDeviceOwner()).isFalse(); + assertThat(dpms.mOwners.hasProfileOwner(10)).isTrue(); // Check that default restrictions were applied. DpmTestUtils.assertRestrictions( @@ -352,11 +362,12 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { final Set<String> alreadySet = dpms.getProfileOwnerAdminLocked(10).defaultEnabledRestrictionsAlreadySet; - assertEquals(alreadySet.size(), 1); - assertTrue(alreadySet.contains(UserManager.DISALLOW_BLUETOOTH_SHARING)); + assertThat(alreadySet).hasSize(1); + assertThat(alreadySet.contains(UserManager.DISALLOW_BLUETOOTH_SHARING)).isTrue(); } @SmallTest + @Test public void testCompMigrationUnAffiliated_skipped() throws Exception { prepareAdmin1AsDo(); prepareAdminAnotherPackageAsPo(COPE_PROFILE_USER_ID); @@ -364,10 +375,11 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { final DevicePolicyManagerServiceTestable dpms = bootDpmsUp(); // DO should still be DO since no migration should happen. - assertTrue(dpms.mOwners.hasDeviceOwner()); + assertThat(dpms.mOwners.hasDeviceOwner()).isTrue(); } @SmallTest + @Test public void testCompMigrationAffiliated() throws Exception { prepareAdmin1AsDo(); prepareAdmin1AsPo(COPE_PROFILE_USER_ID, Build.VERSION_CODES.R); @@ -378,48 +390,54 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { final DevicePolicyManagerServiceTestable dpms = bootDpmsUp(); // DO should cease to be DO. - assertFalse(dpms.mOwners.hasDeviceOwner()); + assertThat(dpms.mOwners.hasDeviceOwner()).isFalse(); final DpmMockContext poContext = new DpmMockContext(getServices(), mRealTestContext); poContext.binder.callingUid = UserHandle.getUid(COPE_PROFILE_USER_ID, COPE_ADMIN1_APP_ID); runAsCaller(poContext, dpms, dpm -> { - assertEquals("Password history policy wasn't migrated to PO parent instance", - 33, dpm.getParentProfileInstance(admin1).getPasswordHistoryLength(admin1)); - assertEquals("Password history policy was put into non-parent PO instance", - 0, dpm.getPasswordHistoryLength(admin1)); - assertTrue("Screen capture restriction wasn't migrated to PO parent instance", - dpm.getParentProfileInstance(admin1).getScreenCaptureDisabled(admin1)); - - assertArrayEquals("Accounts with management disabled weren't migrated to PO parent", - new String[] {"com.google-primary"}, - dpm.getParentProfileInstance(admin1).getAccountTypesWithManagementDisabled()); - assertArrayEquals("Accounts with management disabled for profile were lost", - new String[] {"com.google-profile"}, - dpm.getAccountTypesWithManagementDisabled()); - - assertTrue("User restriction wasn't migrated to PO parent instance", - dpm.getParentProfileInstance(admin1).getUserRestrictions(admin1) - .containsKey(UserManager.DISALLOW_BLUETOOTH)); - assertFalse("User restriction was put into non-parent PO instance", - dpm.getUserRestrictions(admin1).containsKey(UserManager.DISALLOW_BLUETOOTH)); - - assertTrue("User restriction wasn't migrated to PO parent instance", - dpms.getProfileOwnerAdminLocked(COPE_PROFILE_USER_ID) - .getParentActiveAdmin() - .getEffectiveRestrictions() - .containsKey(UserManager.DISALLOW_CONFIG_DATE_TIME)); - assertFalse("User restriction was put into non-parent PO instance", - dpms.getProfileOwnerAdminLocked(COPE_PROFILE_USER_ID) - .getEffectiveRestrictions() - .containsKey(UserManager.DISALLOW_CONFIG_DATE_TIME)); - assertEquals("Personal apps suspension wasn't migrated", - DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED, - dpm.getPersonalAppsSuspendedReasons(admin1)); + assertWithMessage("Password history policy wasn't migrated to PO parent instance") + .that(dpm.getParentProfileInstance(admin1).getPasswordHistoryLength(admin1)) + .isEqualTo(33); + assertWithMessage("Password history policy was put into non-parent PO instance") + .that(dpm.getPasswordHistoryLength(admin1)).isEqualTo(0); + assertWithMessage("Screen capture restriction wasn't migrated to PO parent instance") + .that(dpm.getParentProfileInstance(admin1).getScreenCaptureDisabled(admin1)) + .isTrue(); + + assertWithMessage("Accounts with management disabled weren't migrated to PO parent") + .that(dpm.getParentProfileInstance(admin1) + .getAccountTypesWithManagementDisabled()).asList() + .containsExactly("com.google-primary"); + + assertWithMessage("Accounts with management disabled for profile were lost") + .that(dpm.getAccountTypesWithManagementDisabled()).asList() + .containsExactly("com.google-profile"); + + assertWithMessage("User restriction wasn't migrated to PO parent instance") + .that(dpm.getParentProfileInstance(admin1).getUserRestrictions(admin1).keySet()) + .contains(UserManager.DISALLOW_BLUETOOTH); + + assertWithMessage("User restriction was put into non-parent PO instance").that( + dpm.getUserRestrictions(admin1).keySet()) + .doesNotContain(UserManager.DISALLOW_BLUETOOTH); + + assertWithMessage("User restriction wasn't migrated to PO parent instance") + .that(dpms.getProfileOwnerAdminLocked(COPE_PROFILE_USER_ID) + .getParentActiveAdmin().getEffectiveRestrictions().keySet()) + .contains(UserManager.DISALLOW_CONFIG_DATE_TIME); + assertWithMessage("User restriction was put into non-parent PO instance") + .that(dpms.getProfileOwnerAdminLocked(COPE_PROFILE_USER_ID) + .getEffectiveRestrictions().keySet()) + .doesNotContain(UserManager.DISALLOW_CONFIG_DATE_TIME); + assertWithMessage("Personal apps suspension wasn't migrated") + .that(dpm.getPersonalAppsSuspendedReasons(admin1)) + .isEqualTo(DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED); }); } @SmallTest + @Test public void testCompMigration_keepSuspendedAppsWhenDpcIsRPlus() throws Exception { prepareAdmin1AsDo(); prepareAdmin1AsPo(COPE_PROFILE_USER_ID, Build.VERSION_CODES.R); @@ -445,13 +463,14 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { poContext.binder.callingUid = UserHandle.getUid(COPE_PROFILE_USER_ID, COPE_ADMIN1_APP_ID); runAsCaller(poContext, dpms, dpm -> { - assertEquals("Personal apps suspension wasn't migrated", - DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY, - dpm.getPersonalAppsSuspendedReasons(admin1)); + assertWithMessage("Personal apps suspension wasn't migrated") + .that(dpm.getPersonalAppsSuspendedReasons(admin1)) + .isEqualTo(DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY); }); } @SmallTest + @Test public void testCompMigration_unsuspendAppsWhenDpcNotRPlus() throws Exception { prepareAdmin1AsDo(); prepareAdmin1AsPo(COPE_PROFILE_USER_ID, Build.VERSION_CODES.Q); @@ -470,9 +489,9 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { poContext.binder.callingUid = UserHandle.getUid(COPE_PROFILE_USER_ID, COPE_ADMIN1_APP_ID); runAsCaller(poContext, dpms, dpm -> { - assertEquals("Personal apps weren't unsuspended", - DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED, - dpm.getPersonalAppsSuspendedReasons(admin1)); + assertWithMessage("Personal apps weren't unsuspended") + .that(dpm.getPersonalAppsSuspendedReasons(admin1)) + .isEqualTo(DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED); }); } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java index c4f7b9547277..8d7bc16fcf56 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java @@ -39,7 +39,9 @@ import static com.android.server.devicepolicy.DpmMockContext.CALLER_USER_HANDLE; import static com.android.server.testutils.TestUtils.assertExpectException; import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; +import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; @@ -89,13 +91,14 @@ import android.os.Bundle; import android.os.Process; import android.os.UserHandle; import android.os.UserManager; +import android.platform.test.annotations.FlakyTest; import android.platform.test.annotations.Presubmit; import android.provider.Settings; import android.security.KeyChain; import android.security.keystore.AttestationUtils; import android.telephony.TelephonyManager; import android.telephony.data.ApnSetting; -import android.test.MoreAsserts; +import android.test.MoreAsserts; // TODO(b/171932723): replace by Truth import android.util.ArraySet; import android.util.Pair; @@ -111,6 +114,9 @@ import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsLi import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.mockito.Mockito; import org.mockito.internal.util.collections.Sets; import org.mockito.stubbing.Answer; @@ -127,17 +133,11 @@ import java.util.concurrent.TimeUnit; /** * Tests for DevicePolicyManager( and DevicePolicyManagerService). - * You can run them via: - m FrameworksServicesTests && - adb install \ - -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && - adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \ - -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner - - (mmma frameworks/base/services/tests/servicestests/ for non-ninja build) * - * , or: - * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services + * <p>Run this test with: + * + * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.DevicePolicyManagerTest} + * */ @SmallTest @Presubmit @@ -205,9 +205,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { private static final String PROFILE_OFF_SUSPENSION_TEXT = "suspension_text"; private static final String PROFILE_OFF_SUSPENSION_SOON_TEXT = "suspension_tomorrow_text"; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { mContext = getContext(); mServiceContext = mContext; @@ -251,11 +250,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { return dpms.mTransferOwnershipMetadataManager; } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { flushTasks(dpms); getMockTransferMetadataManager().deleteMetadataFile(); - super.tearDown(); } private void initializeDpms() { @@ -336,14 +334,15 @@ public class DevicePolicyManagerTest extends DpmTestBase { // PO needs to be a DA. dpm.setActiveAdmin(admin, /*replace=*/ false); // Fire! - assertTrue(dpm.setProfileOwner(admin, "owner-name", CALLER_USER_HANDLE)); + assertThat(dpm.setProfileOwner(admin, "owner-name", CALLER_USER_HANDLE)).isTrue(); // Check - assertEquals(admin, dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE)); + assertThat(dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE)).isEqualTo(admin); }); mServiceContext.binder.restoreCallingIdentity(ident); } + @Test public void testHasNoFeature() throws Exception { when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) .thenReturn(false); @@ -352,9 +351,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { new DevicePolicyManagerServiceTestable(getServices(), mContext); // If the device has no DPMS feature, it shouldn't register the local service. - assertNull(LocalServices.getService(DevicePolicyManagerInternal.class)); + assertThat(LocalServices.getService(DevicePolicyManagerInternal.class)).isNull(); } + @Test public void testLoadAdminData() throws Exception { // Device owner in SYSTEM_USER setDeviceOwner(); @@ -365,7 +365,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { final int ANOTHER_UID = UserHandle.getUid(CALLER_USER_HANDLE, 1306); setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2); dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false, CALLER_USER_HANDLE); - assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActiveAsUser(adminAnotherPackage, CALLER_USER_HANDLE)).isTrue(); initializeDpms(); @@ -381,6 +381,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable(); } + @Test public void testLoadAdminData_noAdmins() throws Exception { final int ANOTHER_USER_ID = 15; getServices().addUser(ANOTHER_USER_ID, 0, ""); @@ -399,6 +400,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /** * Caller doesn't have proper permissions. */ + @Test public void testSetActiveAdmin_SecurityException() { // 1. Failure cases. @@ -422,6 +424,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * {@link DevicePolicyManager#getActiveAdmins} * {@link DevicePolicyManager#getActiveAdminsAsUser} */ + @Test public void testSetActiveAdmin() throws Exception { // 1. Make sure the caller has proper permissions. mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -456,9 +459,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { // TODO Verify other calls too. // Make sure it's active admin1. - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isAdminActive(admin2)); - assertFalse(dpm.isAdminActive(admin3)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isAdminActive(admin2)).isFalse(); + assertThat(dpm.isAdminActive(admin3)).isFalse(); // But not admin1 for a different user. @@ -466,8 +469,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { // (Because we're checking a different user's status from CALLER_USER_HANDLE.) mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE + 1)); - assertFalse(dpm.isAdminActiveAsUser(admin2, CALLER_USER_HANDLE + 1)); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE + 1)).isFalse(); + assertThat(dpm.isAdminActiveAsUser(admin2, CALLER_USER_HANDLE + 1)).isFalse(); mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); @@ -479,9 +482,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin2, /* replace =*/ false); // Now we have two admins. - assertTrue(dpm.isAdminActive(admin1)); - assertTrue(dpm.isAdminActive(admin2)); - assertFalse(dpm.isAdminActive(admin3)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isAdminActive(admin2)).isTrue(); + assertThat(dpm.isAdminActive(admin3)).isFalse(); // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called // again. (times(1) because it was previously called for admin1) @@ -508,9 +511,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { // 6. Test getActiveAdmins() List<ComponentName> admins = dpm.getActiveAdmins(); - assertEquals(2, admins.size()); - assertEquals(admin1, admins.get(0)); - assertEquals(admin2, admins.get(1)); + assertThat(admins.size()).isEqualTo(2); + assertThat(admins.get(0)).isEqualTo(admin1); + assertThat(admins.get(1)).isEqualTo(admin2); // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being // replaced @@ -519,12 +522,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Another user has no admins. mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL"); - assertEquals(0, DpmTestUtils.getListSizeAllowingNull( - dpm.getActiveAdminsAsUser(CALLER_USER_HANDLE + 1))); + assertThat(DpmTestUtils.getListSizeAllowingNull( + dpm.getActiveAdminsAsUser(CALLER_USER_HANDLE + 1))).isEqualTo(0); mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL"); } + @Test public void testSetActiveAdmin_multiUsers() throws Exception { final int ANOTHER_USER_ID = 100; @@ -544,12 +548,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isAdminActive(admin2)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isAdminActive(admin2)).isFalse(); mMockContext.binder.callingUid = ANOTHER_ADMIN_UID; - assertFalse(dpm.isAdminActive(admin1)); - assertTrue(dpm.isAdminActive(admin2)); + assertThat(dpm.isAdminActive(admin1)).isFalse(); + assertThat(dpm.isAdminActive(admin2)).isTrue(); } /** @@ -557,12 +561,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { * {@link DevicePolicyManager#setActiveAdmin} * with replace=false */ + @Test public void testSetActiveAdmin_twiceWithoutReplace() throws Exception { // 1. Make sure the caller has proper permissions. mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); // Add the same admin1 again without replace, which should throw. assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null, @@ -574,6 +579,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with * BIND_DEVICE_ADMIN. */ + @Test public void testSetActiveAdmin_permissionCheck() throws Exception { // 1. Make sure the caller has proper permissions. mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -581,13 +587,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertExpectException(IllegalArgumentException.class, /* messageRegex= */ permission.BIND_DEVICE_ADMIN, () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false)); - assertFalse(dpm.isAdminActive(adminNoPerm)); + assertThat(dpm.isAdminActive(adminNoPerm)).isFalse(); // Change the target API level to MNC. Now it can be set as DA. setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null, VERSION_CODES.M); dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false); - assertTrue(dpm.isAdminActive(adminNoPerm)); + assertThat(dpm.isAdminActive(adminNoPerm)).isTrue(); // TODO Test the "load from the file" case where DA will still be loaded even without // BIND_DEVICE_ADMIN and target API is N. @@ -597,6 +603,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * Test for: * {@link DevicePolicyManager#removeActiveAdmin} */ + @Test public void testRemoveActiveAdmin_SecurityException() { mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -604,9 +611,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); // Directly call the DPMS method with a different userid, which should fail. assertExpectException(SecurityException.class, /* messageRegex =*/ null, @@ -627,6 +634,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked * (because we can't send the remove broadcast). */ + @Test public void testRemoveActiveAdmin_userNotRunningOrLocked() { mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -636,9 +644,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); // 1. User not unlocked. setUserUnlocked(CALLER_USER_HANDLE, false); @@ -646,7 +654,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /* messageRegex= */ "User must be running and unlocked", () -> dpm.removeActiveAdmin(admin1)); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps( null, CALLER_USER_HANDLE); @@ -654,7 +662,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { setUserUnlocked(CALLER_USER_HANDLE, true); dpm.removeActiveAdmin(admin1); - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal).setActiveAdminApps( null, CALLER_USER_HANDLE); } @@ -663,6 +671,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * Test for: * {@link DevicePolicyManager#removeActiveAdmin} */ + @Test public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() { mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -670,8 +679,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); // Different user, but should work, because caller has proper permissions. mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); @@ -680,7 +689,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = 1234567; dpms.removeActiveAdmin(admin1, CALLER_USER_HANDLE); - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal).setActiveAdminApps( null, CALLER_USER_HANDLE); @@ -691,6 +700,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * Test for: * {@link DevicePolicyManager#removeActiveAdmin} */ + @Test public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() { // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later. mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -699,8 +709,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); // Broadcast from saveSettingsLocked(). verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( @@ -725,7 +735,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { isNull(String.class), isNull(Bundle.class)); - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal).setActiveAdminApps( null, CALLER_USER_HANDLE); @@ -738,6 +748,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // TODO Check other internal calls. } + @Test public void testRemoveActiveAdmin_multipleAdminsInUser() { // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later. mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -745,14 +756,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Add admin1. dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); // Add admin2. dpm.setActiveAdmin(admin2, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin2)); - assertFalse(dpm.isRemovingAdmin(admin2, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActive(admin2)).isTrue(); + assertThat(dpm.isRemovingAdmin(admin2, CALLER_USER_HANDLE)).isFalse(); // Broadcast from saveSettingsLocked(). verify(mContext.spiedContext, times(2)).sendBroadcastAsUser( @@ -777,7 +788,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { isNull(String.class), isNull(Bundle.class)); - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal).setActiveAdminApps( MockUtils.checkApps(admin2.getPackageName()), eq(CALLER_USER_HANDLE)); @@ -793,6 +804,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * Test for: * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)} */ + @Test public void testForceRemoveActiveAdmin() throws Exception { mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -802,7 +814,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /* appId= */ 10138, /* flags= */ ApplicationInfo.FLAG_TEST_ONLY); dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); // Calling from a non-shell uid should fail with a SecurityException mContext.binder.callingUid = 123456; @@ -815,7 +827,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); // Verify - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal).setActiveAdminApps( null, CALLER_USER_HANDLE); } @@ -825,6 +837,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * * Validates that when the password history length is set, it is persisted after rebooting */ + @Test public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception { int passwordHistoryLength = 2; @@ -842,13 +855,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Save password history length dpm.setPasswordHistoryLength(admin1, passwordHistoryLength); - assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength); + assertThat(passwordHistoryLength).isEqualTo(dpm.getPasswordHistoryLength(admin1)); initializeDpms(); reset(mContext.spiedContext); // Password history length should persist after rebooted - assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength); + assertThat(passwordHistoryLength).isEqualTo(dpm.getPasswordHistoryLength(admin1)); } /** @@ -858,6 +871,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in * addition to ones in the original user. */ + @Test public void testSetActivePasswordState_sendToProfiles() throws Exception { mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); @@ -893,6 +907,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not * its parent. */ + @Test public void testSetActivePasswordState_notSentToParent() throws Exception { mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); @@ -932,6 +947,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /** * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully. */ + @Test public void testSetDeviceOwner() throws Exception { setDeviceOwner(); @@ -944,7 +960,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // DO admin can't be deactivated. dpm.removeActiveAdmin(admin1); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); // TODO Test getDeviceOwnerName() too. To do so, we need to change // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. @@ -969,19 +985,19 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin1, /* replace =*/ false); // Fire! - assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); + assertThat(dpm.setDeviceOwner(admin1, "owner-name")).isTrue(); // getDeviceOwnerComponent should return the admin1 component. - assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); // Check various get APIs. checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true); // getDeviceOwnerComponent should *NOT* return the admin1 component for other users. mContext.binder.callingUid = DpmMockContext.CALLER_UID; - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -997,7 +1013,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED), MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); } private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) { @@ -1012,89 +1028,89 @@ public class DevicePolicyManagerTest extends DpmTestBase { // TODO Test getDeviceOwnerName() too. To do so, we need to change // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable. if (hasDeviceOwner) { - assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1); - assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); } else { - assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); - assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); } mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; if (hasDeviceOwner) { - assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1); - assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); } else { - assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); - assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); } mContext.binder.callingUid = DpmMockContext.CALLER_UID; // Still with MANAGE_USERS. - assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); if (hasDeviceOwner) { - assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); } else { - assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); } mContext.binder.callingUid = Process.SYSTEM_UID; mContext.callerPermissions.remove(permission.MANAGE_USERS); // System can still call "OnAnyUser" without MANAGE_USERS. if (hasDeviceOwner) { - assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1); - assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); } else { - assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); - assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(null); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); } mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; // Still no MANAGE_USERS. if (hasDeviceOwner) { - assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1); } else { - assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); } assertExpectException(SecurityException.class, /* messageRegex =*/ null, @@ -1108,9 +1124,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_UID; // Still no MANAGE_USERS. - assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isFalse(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(null); assertExpectException(SecurityException.class, /* messageRegex =*/ null, () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); @@ -1130,6 +1146,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /** * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist. */ + @Test public void testSetDeviceOwner_noSuchPackage() { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -1144,10 +1161,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"))); } + @Test public void testSetDeviceOwner_failures() throws Exception { // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner(). } + @Test public void testClearDeviceOwner() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -1164,20 +1183,20 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); + assertThat(dpm.setDeviceOwner(admin1, "owner-name")).isTrue(); // Verify internal calls. verify(getServices().iactivityManager, times(1)).updateDeviceOwner( eq(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER), MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true); - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM)).isFalse(); // Set up other mocks. when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle()); @@ -1196,7 +1215,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.clearDeviceOwnerApp(admin1.getPackageName()); // Now DO shouldn't be set. - assertNull(dpm.getDeviceOwnerComponentOnAnyUser()); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isNull(); verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER), eq(false), @@ -1209,7 +1228,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().usageStatsManagerInternal).setActiveAdminApps( null, UserHandle.USER_SYSTEM); - assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)); + assertThat(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM)).isFalse(); // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner // and once for clearing it. @@ -1219,6 +1238,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // TODO Check other calls. } + @Test public void testDeviceOwnerBackupActivateDeactivate() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -1227,7 +1247,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); + assertThat(dpm.setDeviceOwner(admin1, "owner-name")).isTrue(); verify(getServices().ibackupManager, times(1)).setBackupServiceActive( eq(UserHandle.USER_SYSTEM), eq(false)); @@ -1238,6 +1258,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(UserHandle.USER_SYSTEM), eq(true)); } + @Test public void testProfileOwnerBackupActivateDeactivate() throws Exception { setAsProfileOwner(admin1); @@ -1250,6 +1271,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(CALLER_USER_HANDLE), eq(true)); } + @Test public void testClearDeviceOwner_fromDifferentUser() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -1266,13 +1288,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); + assertThat(dpm.setDeviceOwner(admin1, "owner-name")).isTrue(); // Verify internal calls. verify(getServices().iactivityManager, times(1)).updateDeviceOwner( eq(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); // Now call clear from the secondary user, which should throw. mContext.binder.callingUid = DpmMockContext.CALLER_UID; @@ -1286,7 +1308,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.clearDeviceOwnerApp(admin1.getPackageName())); // DO shouldn't be removed. - assertTrue(dpm.isDeviceManaged()); + assertThat(dpm.isDeviceManaged()).isTrue(); } /** @@ -1294,6 +1316,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * * Validates that when the device owner is removed, the reset password token is cleared */ + @Test public void testClearDeviceOwner_clearResetPasswordToken() throws Exception { mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -1312,13 +1335,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM), nullable(EscrowTokenStateChangeCallback.class))) .thenReturn(handle); - assertTrue(dpm.setResetPasswordToken(admin1, token)); + assertThat(dpm.setResetPasswordToken(admin1, token)).isTrue(); // Assert reset password token is active when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM))) .thenReturn(true); - assertTrue(dpm.isResetPasswordTokenActive(admin1)); + assertThat(dpm.isResetPasswordTokenActive(admin1)).isTrue(); // Remove the device owner dpm.clearDeviceOwnerApp(admin1.getPackageName()); @@ -1328,12 +1351,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(UserHandle.USER_SYSTEM)); } + @Test public void testSetProfileOwner() throws Exception { setAsProfileOwner(admin1); // PO admin can't be deactivated. dpm.removeActiveAdmin(admin1); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); // Try setting DO on the same user, which should fail. setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); @@ -1347,13 +1371,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { }); } + @Test public void testClearProfileOwner() throws Exception { setAsProfileOwner(admin1); mContext.binder.callingUid = DpmMockContext.CALLER_UID; - assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isProfileOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isRemovingAdmin(admin1, CALLER_USER_HANDLE)).isFalse(); // First try when the user is locked, which should fail. when(getServices().userManager.isUserUnlocked(anyInt())) @@ -1367,16 +1392,18 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.clearProfileOwner(admin1); // Check - assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.isProfileOwnerApp(admin1.getPackageName())).isFalse(); + assertThat(dpm.isAdminActiveAsUser(admin1, CALLER_USER_HANDLE)).isFalse(); verify(getServices().usageStatsManagerInternal).setActiveAdminApps( null, CALLER_USER_HANDLE); } + @Test public void testSetProfileOwner_failures() throws Exception { // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner(). } + @Test public void testGetDeviceOwnerAdminLocked() throws Exception { checkDeviceOwnerWithMultipleDeviceAdmins(); } @@ -1421,13 +1448,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Set DO on the first non-system user. getServices().setUserRunning(CALLER_USER_HANDLE, true); - assertTrue(dpm.setDeviceOwner(admin2, "owner-name", CALLER_USER_HANDLE)); + assertThat(dpm.setDeviceOwner(admin2, "owner-name", CALLER_USER_HANDLE)).isTrue(); - assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); + assertThat(dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)).isEqualTo(admin2); // Then check getDeviceOwnerAdminLocked(). - assertEquals(admin2, getDeviceOwner().info.getComponent()); - assertEquals(DpmMockContext.CALLER_UID, getDeviceOwner().getUid()); + assertThat(getDeviceOwner().info.getComponent()).isEqualTo(admin2); + assertThat(getDeviceOwner().getUid()).isEqualTo(DpmMockContext.CALLER_UID); } /** @@ -1438,6 +1465,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * We didn't use to persist the DO component class name, but now we do, and the above method * finds the right component from a package name upon migration. */ + @Test public void testDeviceOwnerMigration() throws Exception { when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); checkDeviceOwnerWithMultipleDeviceAdmins(); @@ -1449,7 +1477,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpms.mOwners.writeDeviceOwner(); // Make sure the DO component name doesn't have a class name. - assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); + assertThat(dpms.getDeviceOwnerComponent(/* callingUserOnly= */ false).getClassName()) + .isEmpty(); // Then create a new DPMS to have it load the settings from files. when(getServices().userManager.getUserRestrictions(any(UserHandle.class))) @@ -1459,9 +1488,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Now the DO component name is a full name. // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the // DO. - assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); + assertThat(dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)).isEqualTo(admin1); } + @Test public void testSetGetApplicationRestriction() { setAsProfileOwner(admin1); mContext.packageName = admin1.getPackageName(); @@ -1480,20 +1510,20 @@ public class DevicePolicyManagerTest extends DpmTestBase { { Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1"); - assertNotNull(returned); - assertEquals(returned.size(), 1); - assertEquals(returned.get("KEY_STRING"), "Foo1"); + assertThat(returned).isNotNull(); + assertThat(returned.size()).isEqualTo(1); + assertThat("Foo1").isEqualTo(returned.get("KEY_STRING")); } { Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2"); - assertNotNull(returned); - assertEquals(returned.size(), 1); - assertEquals(returned.get("KEY_STRING"), "Foo2"); + assertThat(returned).isNotNull(); + assertThat(returned.size()).isEqualTo(1); + assertThat("Foo2").isEqualTo(returned.get("KEY_STRING")); } dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle()); - assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size()); + assertThat(dpm.getApplicationRestrictions(admin1, "pkg2").size()).isEqualTo(0); } /** @@ -1546,6 +1576,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { return uid; } + @Test public void testCertificateDisclosure() throws Exception { final int userId = CALLER_USER_HANDLE; final UserHandle user = UserHandle.of(userId); @@ -1571,7 +1602,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { .cancelAsUser(anyString(), anyInt(), eq(user)); // Given that we have four certificates installed, - when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts); + when(getServices().keyChainConnection.getService().getUserCaAliases()) + .thenReturn(fourCerts); // when two of them are approved (one of them approved twice hence no action), dpms.approveCaCert(fourCerts.getList().get(0), userId, true); dpms.approveCaCert(fourCerts.getList().get(1), userId, true); @@ -1586,6 +1618,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * Simple test for delegate set/get and general delegation. Tests verifying that delegated * privileges can acually be exercised by a delegate are not covered here. */ + @Test public void testDelegation() throws Exception { setAsProfileOwner(admin1); @@ -1606,17 +1639,18 @@ public class DevicePolicyManagerTest extends DpmTestBase { // DPMS correctly stores and retrieves the delegates DevicePolicyData policy = dpms.mUserData.get(userHandle); - assertEquals(2, policy.mDelegationMap.size()); + assertThat(policy.mDelegationMap.size()).isEqualTo(2); MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE), DELEGATION_CERT_INSTALL); MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE), DELEGATION_CERT_INSTALL); - assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1)); + assertThat(dpm.getCertInstallerPackage(admin1)).isEqualTo(CERT_DELEGATE); MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE), DELEGATION_APP_RESTRICTIONS); MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE), DELEGATION_APP_RESTRICTIONS); - assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1)); + assertThat(dpm.getApplicationRestrictionsManagingPackage(admin1)) + .isEqualTo(RESTRICTIONS_DELEGATE); // On calling install certificate APIs from an unauthorized process mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID; @@ -1658,6 +1692,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } } + @Test public void testApplicationRestrictionsManagingApp() throws Exception { setAsProfileOwner(admin1); @@ -1673,7 +1708,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // delegated that permission yet. mContext.binder.callingUid = DpmMockContext.CALLER_UID; mContext.packageName = admin1.getPackageName(); - assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); + assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isFalse(); final Bundle rest = new Bundle(); rest.putString("KEY_STRING", "Foo1"); assertExpectException(SecurityException.class, INVALID_CALLING_IDENTITY_MSG, @@ -1682,7 +1717,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Check via the profile owner that no restrictions were set. mContext.binder.callingUid = DpmMockContext.CALLER_UID; mContext.packageName = admin1.getPackageName(); - assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); + assertThat(dpm.getApplicationRestrictions(admin1, "pkg1").size()).isEqualTo(0); // Check the API does not allow setting a non-existent package assertExpectException(PackageManager.NameNotFoundException.class, @@ -1692,22 +1727,22 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Let appRestrictionsManagerPackage manage app restrictions dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage); - assertEquals(appRestrictionsManagerPackage, - dpm.getApplicationRestrictionsManagingPackage(admin1)); + assertThat(dpm.getApplicationRestrictionsManagingPackage(admin1)) + .isEqualTo(appRestrictionsManagerPackage); // Now that package should be able to set and retrieve app restrictions. mContext.binder.callingUid = appRestrictionsManagerUid; mContext.packageName = appRestrictionsManagerPackage; - assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage()); + assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isTrue(); dpm.setApplicationRestrictions(null, "pkg1", rest); Bundle returned = dpm.getApplicationRestrictions(null, "pkg1"); - assertEquals(1, returned.size(), 1); - assertEquals("Foo1", returned.get("KEY_STRING")); + assertThat(returned.size()).isEqualTo(1); + assertThat(returned.get("KEY_STRING")).isEqualTo("Foo1"); // The same app running on a separate user shouldn't be able to manage app restrictions. mContext.binder.callingUid = UserHandle.getUid( UserHandle.USER_SYSTEM, appRestrictionsManagerAppId); - assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); + assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isFalse(); assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex, () -> dpm.setApplicationRestrictions(null, "pkg1", rest)); @@ -1715,20 +1750,21 @@ public class DevicePolicyManagerTest extends DpmTestBase { // too. mContext.binder.callingUid = DpmMockContext.CALLER_UID; mContext.packageName = admin1.getPackageName(); - assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1")); + assertThat(dpm.getApplicationRestrictions(admin1, "pkg1")).isEqualTo(returned); dpm.setApplicationRestrictions(admin1, "pkg1", null); - assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size()); + assertThat(dpm.getApplicationRestrictions(admin1, "pkg1").size()).isEqualTo(0); // Removing the ability for the package to manage app restrictions. dpm.setApplicationRestrictionsManagingPackage(admin1, null); - assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1)); + assertThat(dpm.getApplicationRestrictionsManagingPackage(admin1)).isNull(); mContext.binder.callingUid = appRestrictionsManagerUid; mContext.packageName = appRestrictionsManagerPackage; - assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage()); + assertThat(dpm.isCallerApplicationRestrictionsManagingPackage()).isFalse(); assertExpectException(SecurityException.class, INVALID_CALLING_IDENTITY_MSG, () -> dpm.setApplicationRestrictions(null, "pkg1", null)); } + @Test public void testSetUserRestriction_asDo() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -1745,8 +1781,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Call. dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); - assertTrue(dpm.setDeviceOwner(admin1, "owner-name", - UserHandle.USER_SYSTEM)); + assertThat(dpm.setDeviceOwner(admin1, "owner-name", + UserHandle.USER_SYSTEM)).isTrue(); assertNoDeviceOwnerRestrictions(); reset(getServices().userManagerInternal); @@ -1859,6 +1895,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { return null; } + @Test public void testDaDisallowedPolicies_SecurityException() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL); @@ -1869,25 +1906,28 @@ public class DevicePolicyManagerTest extends DpmTestBase { boolean originalCameraDisabled = dpm.getCameraDisabled(admin1); assertExpectException(SecurityException.class, /* messageRegex= */ null, () -> dpm.setCameraDisabled(admin1, true)); - assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1)); + assertThat(dpm.getCameraDisabled(admin1)).isEqualTo(originalCameraDisabled); int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1); assertExpectException(SecurityException.class, /* messageRegex= */ null, () -> dpm.setKeyguardDisabledFeatures(admin1, DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL)); - assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1)); + assertThat(dpm.getKeyguardDisabledFeatures(admin1)) + .isEqualTo(originalKeyguardDisabledFeatures); long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1); assertExpectException(SecurityException.class, /* messageRegex= */ null, () -> dpm.setPasswordExpirationTimeout(admin1, 1234)); - assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1)); + assertThat(dpm.getPasswordExpirationTimeout(admin1)) + .isEqualTo(originalPasswordExpirationTimeout); int originalPasswordQuality = dpm.getPasswordQuality(admin1); assertExpectException(SecurityException.class, /* messageRegex= */ null, () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC)); - assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1)); + assertThat(dpm.getPasswordQuality(admin1)).isEqualTo(originalPasswordQuality); } + @Test public void testSetUserRestriction_asPo() { setAsProfileOwner(admin1); @@ -2023,6 +2063,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { UserManager.DISALLOW_UNMUTE_MICROPHONE ); + @Test public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception { final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID); @@ -2097,6 +2138,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); } + @Test public void testNoDefaultEnabledUserRestrictions() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -2112,8 +2154,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM); - assertTrue(dpm.setDeviceOwner(admin1, "owner-name", - UserHandle.USER_SYSTEM)); + assertThat(dpm.setDeviceOwner(admin1, "owner-name", + UserHandle.USER_SYSTEM)).isTrue(); assertNoDeviceOwnerRestrictions(); @@ -2132,6 +2174,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); } + @Test public void testSetFactoryResetProtectionPolicyWithDO() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -2156,6 +2199,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)); } + @Test public void testSetFactoryResetProtectionPolicyFailWithPO() throws Exception { setupProfileOwner(); @@ -2167,6 +2211,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.setFactoryResetProtectionPolicy(admin1, policy)); } + @Test public void testSetFactoryResetProtectionPolicyWithPOOfOrganizationOwnedDevice() throws Exception { setupProfileOwner(); @@ -2204,6 +2249,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)); } + @Test public void testGetFactoryResetProtectionPolicyWithFrpManagementAgent() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -2245,6 +2291,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertThat(actualAccounts).containsExactlyElementsIn(expectedAccounts); } + @Test public void testSetKeyguardDisabledFeaturesWithDO() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -2255,6 +2302,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA); } + @Test public void testSetKeyguardDisabledFeaturesWithPO() throws Exception { setupProfileOwner(); @@ -2264,6 +2312,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT); } + @Test public void testSetKeyguardDisabledFeaturesWithPOOfOrganizationOwnedDevice() throws Exception { final int MANAGED_PROFILE_USER_ID = CALLER_USER_HANDLE; @@ -2281,6 +2330,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA); } + @Test public void testSetApplicationHiddenWithDO() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -2304,6 +2354,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { UserHandle.USER_SYSTEM); } + @Test public void testSetApplicationHiddenWithPOOfOrganizationOwnedDevice() throws Exception { final int MANAGED_PROFILE_USER_ID = CALLER_USER_HANDLE; final int MANAGED_PROFILE_ADMIN_UID = @@ -2334,6 +2385,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false, UserHandle.USER_SYSTEM); } + @Test public void testGetMacAddress() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -2351,7 +2403,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // DO needs to be an DA. dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); // Test 2. Caller has DA, but not DO. assertExpectException(SecurityException.class, @@ -2359,7 +2411,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.getWifiMacAddress(admin1)); // Test 3. Caller has PO, but not DO. - assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); + assertThat(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)).isTrue(); assertExpectException(SecurityException.class, /* messageRegex= */ INVALID_CALLING_IDENTITY_MSG, () -> dpm.getWifiMacAddress(admin1)); @@ -2368,30 +2420,32 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.clearProfileOwner(admin1); dpm.setActiveAdmin(admin1, false); // Test 4, Caller is DO now. - assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); + assertThat(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)).isTrue(); // 4-1. But WifiManager is not ready. - assertNull(dpm.getWifiMacAddress(admin1)); + assertThat(dpm.getWifiMacAddress(admin1)).isNull(); // 4-2. When WifiManager returns an empty array, dpm should also output null. when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]); - assertNull(dpm.getWifiMacAddress(admin1)); + assertThat(dpm.getWifiMacAddress(admin1)).isNull(); // 4-3. With a real MAC address. final String[] macAddresses = new String[]{"11:22:33:44:55:66"}; when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses); - assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); + assertThat(dpm.getWifiMacAddress(admin1)).isEqualTo("11:22:33:44:55:66"); } + @Test public void testGetMacAddressByOrgOwnedPO() throws Exception { setupProfileOwner(); configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE); final String[] macAddresses = new String[]{"11:22:33:44:55:66"}; when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses); - assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); + assertThat(dpm.getWifiMacAddress(admin1)).isEqualTo("11:22:33:44:55:66"); } + @Test public void testReboot() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -2404,19 +2458,19 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Set admin1 as DA. dpm.setActiveAdmin(admin1, false); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); assertExpectException(SecurityException.class, /* messageRegex= */ INVALID_CALLING_IDENTITY_MSG, () -> dpm.reboot(admin1)); // Set admin1 as PO. - assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); + assertThat(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)).isTrue(); assertExpectException(SecurityException.class, /* messageRegex= */ INVALID_CALLING_IDENTITY_MSG, () -> dpm.reboot(admin1)); // Remove PO and add DO. dpm.clearProfileOwner(admin1); dpm.setActiveAdmin(admin1, false); - assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); + assertThat(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)).isTrue(); // admin1 is DO. // Set current call state of device to ringing. @@ -2432,10 +2486,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.reboot(admin1)); // Set current call state of device to idle. - when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); + when(getServices().telephonyManager.getCallState()) + .thenReturn(TelephonyManager.CALL_STATE_IDLE); dpm.reboot(admin1); } + @Test public void testSetGetSupportText() { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); dpm.setActiveAdmin(admin1, true); @@ -2444,11 +2500,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Null default support messages. { - assertNull(dpm.getLongSupportMessage(admin1)); - assertNull(dpm.getShortSupportMessage(admin1)); + assertThat(dpm.getLongSupportMessage(admin1)).isNull(); + assertThat(dpm.getShortSupportMessage(admin1)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertNull(dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE)); - assertNull(dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull(); + assertThat(dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull(); mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; } @@ -2473,46 +2529,46 @@ public class DevicePolicyManagerTest extends DpmTestBase { { final String supportText = "Some text to test with."; dpm.setShortSupportMessage(admin1, supportText); - assertEquals(supportText, dpm.getShortSupportMessage(admin1)); - assertNull(dpm.getLongSupportMessage(admin1)); - assertNull(dpm.getShortSupportMessage(admin2)); + assertThat(dpm.getShortSupportMessage(admin1)).isEqualTo(supportText); + assertThat(dpm.getLongSupportMessage(admin1)).isNull(); + assertThat(dpm.getShortSupportMessage(admin2)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1, - CALLER_USER_HANDLE)); - assertNull(dpm.getShortSupportMessageForUser(admin2, CALLER_USER_HANDLE)); - assertNull(dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.getShortSupportMessageForUser(admin1, + CALLER_USER_HANDLE)).isEqualTo(supportText); + assertThat(dpm.getShortSupportMessageForUser(admin2, CALLER_USER_HANDLE)).isNull(); + assertThat(dpm.getLongSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull(); mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; dpm.setShortSupportMessage(admin1, null); - assertNull(dpm.getShortSupportMessage(admin1)); + assertThat(dpm.getShortSupportMessage(admin1)).isNull(); } // Set/Get long returns what it sets and other admins text isn't changed. { final String supportText = "Some text to test with.\nWith more text."; dpm.setLongSupportMessage(admin1, supportText); - assertEquals(supportText, dpm.getLongSupportMessage(admin1)); - assertNull(dpm.getShortSupportMessage(admin1)); - assertNull(dpm.getLongSupportMessage(admin2)); + assertThat(dpm.getLongSupportMessage(admin1)).isEqualTo(supportText); + assertThat(dpm.getShortSupportMessage(admin1)).isNull(); + assertThat(dpm.getLongSupportMessage(admin2)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1, - CALLER_USER_HANDLE)); - assertNull(dpm.getLongSupportMessageForUser(admin2, CALLER_USER_HANDLE)); - assertNull(dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE)); + assertThat(dpm.getLongSupportMessageForUser(admin1, + CALLER_USER_HANDLE)).isEqualTo(supportText); + assertThat(dpm.getLongSupportMessageForUser(admin2, CALLER_USER_HANDLE)).isNull(); + assertThat(dpm.getShortSupportMessageForUser(admin1, CALLER_USER_HANDLE)).isNull(); mMockContext.binder.callingUid = DpmMockContext.CALLER_UID; dpm.setLongSupportMessage(admin1, null); - assertNull(dpm.getLongSupportMessage(admin1)); + assertThat(dpm.getLongSupportMessage(admin1)).isNull(); } } + @Test public void testSetGetMeteredDataDisabledPackages() throws Exception { setAsProfileOwner(admin1); - final ArrayList<String> emptyList = new ArrayList<>(); - assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1)); + assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEmpty(); // Setup final ArrayList<String> pkgsToRestrict = new ArrayList<>(); @@ -2525,8 +2581,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict); // Verify - assertEquals(emptyList, excludedPkgs); - assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1)); + assertThat(excludedPkgs).isEmpty(); + assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEqualTo(pkgsToRestrict); verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages( MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])), eq(CALLER_USER_HANDLE)); @@ -2536,17 +2592,18 @@ public class DevicePolicyManagerTest extends DpmTestBase { excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict); // Verify - assertEquals(emptyList, excludedPkgs); - assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1)); + assertThat(excludedPkgs).isEmpty(); + assertThat(dpm.getMeteredDataDisabledPackages(admin1)).isEqualTo(pkgsToRestrict); verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages( MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])), eq(CALLER_USER_HANDLE)); } + @Test public void testSetGetMeteredDataDisabledPackages_deviceAdmin() { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); dpm.setActiveAdmin(admin1, true); - assertTrue(dpm.isAdminActive(admin1)); + assertThat(dpm.isAdminActive(admin1)).isTrue(); mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS); assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG, @@ -2555,11 +2612,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.getMeteredDataDisabledPackages(admin1)); } + @Test public void testIsMeteredDataDisabledForUserPackage() throws Exception { setAsProfileOwner(admin1); // Setup - final ArrayList<String> emptyList = new ArrayList<>(); final ArrayList<String> pkgsToRestrict = new ArrayList<>(); final String package1 = "com.example.one"; final String package2 = "com.example.two"; @@ -2571,16 +2628,20 @@ public class DevicePolicyManagerTest extends DpmTestBase { List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict); // Verify - assertEquals(emptyList, excludedPkgs); + assertThat(excludedPkgs).isEmpty(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(package1 + "should be restricted", - dpm.isMeteredDataDisabledPackageForUser(admin1, package1, CALLER_USER_HANDLE)); - assertTrue(package2 + "should be restricted", - dpm.isMeteredDataDisabledPackageForUser(admin1, package2, CALLER_USER_HANDLE)); - assertFalse(package3 + "should not be restricted", - dpm.isMeteredDataDisabledPackageForUser(admin1, package3, CALLER_USER_HANDLE)); - } - + assertWithMessage("%s should be restricted", package1) + .that(dpm.isMeteredDataDisabledPackageForUser(admin1, package1, CALLER_USER_HANDLE)) + .isTrue(); + assertWithMessage("%s should be restricted", package2) + .that(dpm.isMeteredDataDisabledPackageForUser(admin1, package2, CALLER_USER_HANDLE)) + .isTrue(); + assertWithMessage("%s should not be restricted", package3) + .that(dpm.isMeteredDataDisabledPackageForUser(admin1, package3, CALLER_USER_HANDLE)) + .isFalse(); + } + + @Test public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception { setAsProfileOwner(admin1); assertExpectException(SecurityException.class, @@ -2597,6 +2658,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { clearDeviceOwner(); } + @Test public void testCreateAdminSupportIntent() throws Exception { // Setup device owner. mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -2604,11 +2666,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Nonexisting permission returns null Intent intent = dpm.createAdminSupportIntent("disallow_nothing"); - assertNull(intent); + assertThat(intent).isNull(); // Existing permission that is not set returns null intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME); - assertNull(intent); + assertThat(intent).isNull(); // Existing permission that is not set by device/profile owner returns null when(getServices().userManager.hasUserRestriction( @@ -2616,7 +2678,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(true); intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME); - assertNull(intent); + assertThat(intent).isNull(); // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource. doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList( @@ -2626,51 +2688,53 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(UserManager.DISALLOW_ADJUST_VOLUME), eq(UserHandle.of(UserHandle.myUserId()))); intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME); - assertNotNull(intent); - assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction()); - assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID), - intent.getIntExtra(Intent.EXTRA_USER_ID, -1)); - assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN)); - assertEquals(UserManager.DISALLOW_ADJUST_VOLUME, - intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)); + assertThat(intent).isNotNull(); + assertThat(intent.getAction()).isEqualTo(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); + assertThat(intent.getIntExtra(Intent.EXTRA_USER_ID, -1)) + .isEqualTo(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID)); + assertThat( + (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN)) + .isEqualTo(admin1); + assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)) + .isEqualTo(UserManager.DISALLOW_ADJUST_VOLUME); // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not // user restrictions // Camera is not disabled intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA); - assertNull(intent); + assertThat(intent).isNull(); // Camera is disabled dpm.setCameraDisabled(admin1, true); intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA); - assertNotNull(intent); - assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA, - intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)); + assertThat(intent).isNotNull(); + assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)) + .isEqualTo(DevicePolicyManager.POLICY_DISABLE_CAMERA); // Screen capture is not disabled intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE); - assertNull(intent); + assertThat(intent).isNull(); // Screen capture is disabled dpm.setScreenCaptureDisabled(admin1, true); intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE); - assertNotNull(intent); - assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE, - intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)); + assertThat(intent).isNotNull(); + assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)) + .isEqualTo(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE); // Same checks for different user mContext.binder.callingUid = DpmMockContext.CALLER_UID; // Camera should be disabled by device owner intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA); - assertNotNull(intent); - assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA, - intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)); - assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID), - intent.getIntExtra(Intent.EXTRA_USER_ID, -1)); + assertThat(intent).isNotNull(); + assertThat(intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION)) + .isEqualTo(DevicePolicyManager.POLICY_DISABLE_CAMERA); + assertThat(intent.getIntExtra(Intent.EXTRA_USER_ID, -1)) + .isEqualTo(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID)); // ScreenCapture should not be disabled by device owner intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE); - assertNull(intent); + assertThat(intent).isNull(); } /** @@ -2679,6 +2743,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * {@link DevicePolicyManager#getAffiliationIds} * {@link DevicePolicyManager#isAffiliatedUser} */ + @Test public void testUserAffiliation() throws Exception { mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -2686,20 +2751,20 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Check that the system user is unaffiliated. mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; - assertFalse(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isFalse(); // Set a device owner on the system user. Check that the system user becomes affiliated. setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin1, /* replace =*/ false); - assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); - assertTrue(dpm.isAffiliatedUser()); - assertTrue(dpm.getAffiliationIds(admin1).isEmpty()); + assertThat(dpm.setDeviceOwner(admin1, "owner-name")).isTrue(); + assertThat(dpm.isAffiliatedUser()).isTrue(); + assertThat(dpm.getAffiliationIds(admin1).isEmpty()).isTrue(); // Install a profile owner. Check that the test user is unaffiliated. mContext.binder.callingUid = DpmMockContext.CALLER_UID; setAsProfileOwner(admin2); - assertFalse(dpm.isAffiliatedUser()); - assertTrue(dpm.getAffiliationIds(admin2).isEmpty()); + assertThat(dpm.isAffiliatedUser()).isFalse(); + assertThat(dpm.getAffiliationIds(admin2).isEmpty()).isTrue(); // Have the profile owner specify a set of affiliation ids. Check that the test user remains // unaffiliated. @@ -2709,7 +2774,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { userAffiliationIds.add("blue"); dpm.setAffiliationIds(admin2, userAffiliationIds); MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue"); - assertFalse(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isFalse(); // Have the device owner specify a set of affiliation ids that do not intersect with those // specified by the profile owner. Check that the test user remains unaffiliated. @@ -2722,7 +2787,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { MoreAsserts.assertContentsInAnyOrder( dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta"); mContext.binder.callingUid = DpmMockContext.CALLER_UID; - assertFalse(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isFalse(); // Have the profile owner specify a set of affiliation ids that intersect with those // specified by the device owner. Check that the test user becomes affiliated. @@ -2730,33 +2795,36 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setAffiliationIds(admin2, userAffiliationIds); MoreAsserts.assertContentsInAnyOrder( dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow"); - assertTrue(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isTrue(); // Clear affiliation ids for the profile owner. The user becomes unaffiliated. dpm.setAffiliationIds(admin2, Collections.emptySet()); - assertTrue(dpm.getAffiliationIds(admin2).isEmpty()); - assertFalse(dpm.isAffiliatedUser()); + assertThat(dpm.getAffiliationIds(admin2).isEmpty()).isTrue(); + assertThat(dpm.isAffiliatedUser()).isFalse(); // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated dpm.setAffiliationIds(admin2, userAffiliationIds); - assertTrue(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isTrue(); dpm.clearProfileOwner(admin2); - assertFalse(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isFalse(); // Check that the system user remains affiliated. mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; - assertTrue(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isTrue(); // Clear the device owner - the user becomes unaffiliated. clearDeviceOwner(); - assertFalse(dpm.isAffiliatedUser()); + assertThat(dpm.isAffiliatedUser()).isFalse(); } + @Test public void testGetUserProvisioningState_defaultResult() { mContext.callerPermissions.add(permission.MANAGE_USERS); - assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); + assertThat(dpm.getUserProvisioningState()) + .isEqualTo(DevicePolicyManager.STATE_USER_UNMANAGED); } + @Test public void testSetUserProvisioningState_permission() throws Exception { setupProfileOwner(); @@ -2764,6 +2832,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_SETUP_FINALIZED); } + @Test public void testSetUserProvisioningState_unprivileged() throws Exception { setupProfileOwner(); assertExpectException(SecurityException.class, /* messageRegex =*/ null, @@ -2771,6 +2840,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { CALLER_USER_HANDLE)); } + @Test public void testSetUserProvisioningState_noManagement() { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -2778,9 +2848,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { /* messageRegex= */ "change provisioning state unless a .* owner is set", () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED, CALLER_USER_HANDLE)); - assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); + assertThat(dpm.getUserProvisioningState()) + .isEqualTo(DevicePolicyManager.STATE_USER_UNMANAGED); } + @Test public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -2790,6 +2862,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_SETUP_FINALIZED); } + @Test public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -2800,6 +2873,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_SETUP_FINALIZED); } + @Test public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -2808,6 +2882,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_SETUP_FINALIZED); } + @Test public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser() throws Exception { setupProfileOwner(); @@ -2817,6 +2892,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_PROFILE_FINALIZED); } + @Test public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile() throws Exception { setupProfileOwner(); @@ -2826,6 +2902,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_SETUP_FINALIZED); } + @Test public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception { setupProfileOwner(); @@ -2833,6 +2910,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_SETUP_FINALIZED); } + @Test public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception { setupProfileOwner(); @@ -2843,6 +2921,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.STATE_USER_UNMANAGED)); } + @Test public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState() throws Exception { setupProfileOwner(); @@ -2858,10 +2937,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); mContext.callerPermissions.add(permission.MANAGE_USERS); - assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState()); + assertThat(dpm.getUserProvisioningState()) + .isEqualTo(DevicePolicyManager.STATE_USER_UNMANAGED); for (int state : states) { dpm.setUserProvisioningState(state, userId); - assertEquals(state, dpm.getUserProvisioningState()); + assertThat(dpm.getUserProvisioningState()).isEqualTo(state); } } @@ -2870,7 +2950,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID); dpm.setActiveAdmin(admin1, false); - assertTrue(dpm.setProfileOwner(admin1, null, CALLER_USER_HANDLE)); + assertThat(dpm.setProfileOwner(admin1, null, CALLER_USER_HANDLE)).isTrue(); mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); } @@ -2880,7 +2960,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { setUpPackageManagerForAdmin(admin1, DpmMockContext.SYSTEM_UID); dpm.setActiveAdmin(admin1, false); - assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)); + assertThat(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM)).isTrue(); mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); } @@ -2890,11 +2970,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin1, false); - assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)); + assertThat(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM)).isTrue(); mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); } + @Test public void testSetMaximumTimeToLock() { mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -2956,6 +3037,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyStayOnWhilePluggedCleared(false); } + @Test public void testIsActiveSupervisionApp() throws Exception { when(mServiceContext.resources .getString(R.string.config_defaultSupervisionProfileOwnerComponent)) @@ -2968,11 +3050,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { final DevicePolicyManagerInternal dpmi = LocalServices.getService(DevicePolicyManagerInternal.class); - assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN)); + assertThat(dpmi.isActiveSupervisionApp(PROFILE_ADMIN)).isTrue(); } // Test if lock timeout on managed profile is handled correctly depending on whether profile // uses separate challenge. + @Test public void testSetMaximumTimeToLockProfile() throws Exception { final int PROFILE_USER = 15; final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436); @@ -3039,6 +3122,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM); } + @Test public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3055,8 +3139,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { getServices().buildMock.isDebuggable = false; dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE); + assertThat(MAX_MINUS_ONE_MINUTE).isEqualTo(dpm.getRequiredStrongAuthTimeout(admin1)); + assertThat(MAX_MINUS_ONE_MINUTE).isEqualTo(dpm.getRequiredStrongAuthTimeout(null)); verify(getServices().systemProperties, never()).getLong(anyString(), anyLong()); @@ -3067,45 +3151,47 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setRequiredStrongAuthTimeout(admin1, 0); // aggregation should be the default if unset by any admin - assertEquals(dpm.getRequiredStrongAuthTimeout(null), - DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); + assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) + .isEqualTo(dpm.getRequiredStrongAuthTimeout(null)); // admin not participating by default - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); + assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(0); //clamping from the top dpm.setRequiredStrongAuthTimeout(admin1, DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), - DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), - DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); + assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) + .isEqualTo(dpm.getRequiredStrongAuthTimeout(admin1)); + assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) + .isEqualTo(dpm.getRequiredStrongAuthTimeout(null)); // 0 means the admin is not participating, so default should be returned dpm.setRequiredStrongAuthTimeout(admin1, 0); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), - DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); + assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(0); + assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) + .isEqualTo(dpm.getRequiredStrongAuthTimeout(null)); // clamping from the bottom dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS); + assertThat(dpm.getRequiredStrongAuthTimeout(admin1)) + .isEqualTo(MINIMUM_STRONG_AUTH_TIMEOUT_MS); + assertThat(dpm.getRequiredStrongAuthTimeout(null)) + .isEqualTo(MINIMUM_STRONG_AUTH_TIMEOUT_MS); // values within range dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE); + assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(MIN_PLUS_ONE_MINUTE); + assertThat(dpm.getRequiredStrongAuthTimeout(null)).isEqualTo(MIN_PLUS_ONE_MINUTE); dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE); + assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(MAX_MINUS_ONE_MINUTE); + assertThat(dpm.getRequiredStrongAuthTimeout(null)).isEqualTo(MAX_MINUS_ONE_MINUTE); // reset to default dpm.setRequiredStrongAuthTimeout(admin1, 0); - assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0); - assertEquals(dpm.getRequiredStrongAuthTimeout(null), - DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS); + assertThat(dpm.getRequiredStrongAuthTimeout(admin1)).isEqualTo(0); + assertThat(DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) + .isEqualTo(dpm.getRequiredStrongAuthTimeout(null)); // negative value assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null, @@ -3130,8 +3216,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_DeviceAdminFeatureOff() throws Exception { when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) .thenReturn(false); - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(false); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(false); initializeDpms(); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) @@ -3141,6 +3227,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; } + @Test public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception { setup_DeviceAdminFeatureOff(); mContext.packageName = admin1.getPackageName(); @@ -3153,6 +3240,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); } + @Test public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception { setup_DeviceAdminFeatureOff(); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -3170,8 +3258,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_ManagedProfileFeatureOff() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(false); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(false); initializeDpms(); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) @@ -3181,6 +3269,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; } + @Test public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception { setup_ManagedProfileFeatureOff(); mContext.packageName = admin1.getPackageName(); @@ -3202,6 +3291,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); } + @Test public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception { setup_ManagedProfileFeatureOff(); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); @@ -3233,8 +3323,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(true); @@ -3244,6 +3334,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; } + @Test public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception { setup_nonSplitUser_firstBoot_primaryUser(); mContext.packageName = admin1.getPackageName(); @@ -3257,6 +3348,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false /* because of non-split user */); } + @Test public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser() throws Exception { setup_nonSplitUser_firstBoot_primaryUser(); @@ -3275,8 +3367,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(true); @@ -3302,6 +3394,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { true)).thenReturn(true); } + @Test public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception { setup_nonSplitUser_afterDeviceSetup_primaryUser(); @@ -3318,6 +3411,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false/* because of non-split user */); } + @Test public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception { setup_nonSplitUser_afterDeviceSetup_primaryUser(); @@ -3335,6 +3429,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT); } + @Test public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception { setup_nonSplitUser_withDo_primaryUser(); mContext.packageName = admin1.getPackageName(); @@ -3361,6 +3456,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); } + @Test public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem() throws Exception { setup_nonSplitUser_withDo_primaryUser(); @@ -3388,6 +3484,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); } + @Test public void testCheckCannotSetProfileOwnerWithDeviceOwner() throws Exception { setup_nonSplitUser_withDo_primaryUser(); final int managedProfileUserId = 18; @@ -3399,10 +3496,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); setUpPackageManagerForFakeAdmin(admin1, managedProfileAdminUid, admin1); dpm.setActiveAdmin(admin1, false, userId); - assertFalse(dpm.setProfileOwner(admin1, null, userId)); + assertThat(dpm.setProfileOwner(admin1, null, userId)).isFalse(); mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); } + @Test public void testCheckProvisioningPreCondition_nonSplitUser_attemptingComp() throws Exception { setup_nonSplitUser_withDo_primaryUser_ManagedProfile(); mContext.packageName = admin1.getPackageName(); @@ -3420,6 +3518,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID); } + @Test public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile() throws Exception { setup_nonSplitUser_withDo_primaryUser_ManagedProfile(); @@ -3449,8 +3548,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_firstBoot_systemUser() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(false); @@ -3459,6 +3558,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; } + @Test public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception { setup_splitUser_firstBoot_systemUser(); mContext.packageName = admin1.getPackageName(); @@ -3473,6 +3573,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false/* because calling uid is system user */); } + @Test public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser() throws Exception { setup_splitUser_firstBoot_systemUser(); @@ -3491,8 +3592,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(false); @@ -3501,6 +3602,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; } + @Test public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception { setup_splitUser_afterDeviceSetup_systemUser(); mContext.packageName = admin1.getPackageName(); @@ -3517,6 +3619,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false/* because calling uid is system user */); } + @Test public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser() throws Exception { setup_splitUser_afterDeviceSetup_systemUser(); @@ -3535,8 +3638,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_firstBoot_primaryUser() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); when(getServices().userManager.canAddMoreManagedProfiles(CALLER_USER_HANDLE, true)).thenReturn(true); @@ -3545,6 +3648,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_UID; } + @Test public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception { setup_splitUser_firstBoot_primaryUser(); mContext.packageName = admin1.getPackageName(); @@ -3557,6 +3661,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true); } + @Test public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser() throws Exception { setup_splitUser_firstBoot_primaryUser(); @@ -3575,8 +3680,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception { - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); when(getServices().userManager.canAddMoreManagedProfiles(CALLER_USER_HANDLE, true)).thenReturn(true); @@ -3585,6 +3690,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_UID; } + @Test public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser() throws Exception { setup_splitUser_afterDeviceSetup_primaryUser(); @@ -3601,6 +3707,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false/* because user setup completed */); } + @Test public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser() throws Exception { setup_splitUser_afterDeviceSetup_primaryUser(); @@ -3621,8 +3728,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception { setDeviceOwner(); - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(false); @@ -3631,6 +3738,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; } + @Test public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception { setup_provisionManagedProfileWithDeviceOwner_systemUser(); @@ -3640,6 +3748,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { false /* can't provision managed profile on system user */); } + @Test public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception { setup_provisionManagedProfileWithDeviceOwner_systemUser(); @@ -3651,8 +3760,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception { setDeviceOwner(); - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); when(getServices().userManager.getProfileParent(CALLER_USER_HANDLE)) .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); @@ -3663,6 +3772,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.ANOTHER_UID; } + @Test public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception { setup_provisionManagedProfileWithDeviceOwner_primaryUser(); @@ -3671,6 +3781,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); } + @Test public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception { setup_provisionManagedProfileWithDeviceOwner_primaryUser(); @@ -3684,8 +3795,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception { setDeviceOwner(); - when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) - .thenReturn(true); + when(getServices().ipackageManager + .hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)).thenReturn(true); when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); when(getServices().userManager.hasUserRestriction( eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), @@ -3700,6 +3811,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_UID; } + @Test public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception { setup_provisionManagedProfileCantRemoveUser_primaryUser(); @@ -3708,6 +3820,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); } + @Test public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception { setup_provisionManagedProfileCantRemoveUser_primaryUser(); @@ -3716,6 +3829,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE); } + @Test public void testCheckProvisioningPreCondition_permission() { // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted assertExpectException(SecurityException.class, /* messageRegex =*/ null, @@ -3723,12 +3837,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package")); } + @Test public void testForceUpdateUserSetupComplete_permission() { // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted assertExpectException(SecurityException.class, /* messageRegex =*/ null, () -> dpm.forceUpdateUserSetupComplete()); } + @Test public void testForceUpdateUserSetupComplete_systemUser() { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); // GIVEN calling from user 20 @@ -3737,6 +3853,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.forceUpdateUserSetupComplete()); } + @Test public void testForceUpdateUserSetupComplete_userbuild() { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -3753,14 +3870,15 @@ public class DevicePolicyManagerTest extends DpmTestBase { // GIVEN it's user build getServices().buildMock.isDebuggable = false; - assertTrue(dpms.hasUserSetupCompleted()); + assertThat(dpms.hasUserSetupCompleted()).isTrue(); dpm.forceUpdateUserSetupComplete(); // THEN the state in dpms is not changed - assertTrue(dpms.hasUserSetupCompleted()); + assertThat(dpms.hasUserSetupCompleted()).isTrue(); } + @Test public void testForceUpdateUserSetupComplete_userDebugbuild() { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -3777,12 +3895,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { // GIVEN it's userdebug build getServices().buildMock.isDebuggable = true; - assertTrue(dpms.hasUserSetupCompleted()); + assertThat(dpms.hasUserSetupCompleted()).isTrue(); dpm.forceUpdateUserSetupComplete(); // THEN the state in dpms is not changed - assertFalse(dpms.hasUserSetupCompleted()); + assertThat(dpms.hasUserSetupCompleted()).isFalse(); } private void clearDeviceOwner() throws Exception { @@ -3795,6 +3913,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { }); } + @Test public void testGetLastSecurityLogRetrievalTime() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3806,7 +3925,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(true); // No logs were retrieved so far. - assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(-1); // Enabling logging should not change the timestamp. dpm.setSecurityLoggingEnabled(admin1, true); @@ -3814,55 +3933,56 @@ public class DevicePolicyManagerTest extends DpmTestBase { .securityLogSetLoggingEnabledProperty(true); when(getServices().settings.securityLogGetLoggingEnabledProperty()) .thenReturn(true); - assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(-1); // Retrieving the logs should update the timestamp. final long beforeRetrieval = System.currentTimeMillis(); dpm.retrieveSecurityLogs(admin1); final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); final long afterRetrieval = System.currentTimeMillis(); - assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval); - assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval); + assertThat(firstSecurityLogRetrievalTime >= beforeRetrieval).isTrue(); + assertThat(firstSecurityLogRetrievalTime <= afterRetrieval).isTrue(); // Retrieving the pre-boot logs should update the timestamp. Thread.sleep(2); dpm.retrievePreRebootSecurityLogs(admin1); final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); - assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime); + assertThat(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime).isTrue(); // Checking the timestamp again should not change it. Thread.sleep(2); - assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(secondSecurityLogRetrievalTime); // Retrieving the logs again should update the timestamp. dpm.retrieveSecurityLogs(admin1); final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime(); - assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime); + assertThat(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime).isTrue(); // Disabling logging should not change the timestamp. Thread.sleep(2); dpm.setSecurityLoggingEnabled(admin1, false); - assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime); // Restarting the DPMS should not lose the timestamp. initializeDpms(); - assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime); // Any uid holding MANAGE_USERS permission can retrieve the timestamp. mContext.binder.callingUid = 1234567; mContext.callerPermissions.add(permission.MANAGE_USERS); - assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime); mContext.callerPermissions.remove(permission.MANAGE_USERS); // System can retrieve the timestamp. mContext.binder.clearCallingIdentity(); - assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(thirdSecurityLogRetrievalTime); // Removing the device owner should clear the timestamp. clearDeviceOwner(); - assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); + assertThat(dpm.getLastSecurityLogRetrievalTime()).isEqualTo(-1); } + @Test public void testSetConfiguredNetworksLockdownStateWithDO() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3875,6 +3995,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0); } + @Test public void testSetConfiguredNetworksLockdownStateWithPO() throws Exception { setupProfileOwner(); assertExpectException(SecurityException.class, null, @@ -3883,6 +4004,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0); } + @Test public void testSetConfiguredNetworksLockdownStateWithPOOfOrganizationOwnedDevice() throws Exception { setupProfileOwner(); @@ -3896,6 +4018,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0); } + @Test public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3903,6 +4026,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0")); } + @Test public void testSetSystemSettingWithDO() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3911,6 +4035,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM); } + @Test public void testSetSystemSettingWithPO() throws Exception { setupProfileOwner(); dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"); @@ -3918,6 +4043,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { Settings.System.SCREEN_BRIGHTNESS, "0", CALLER_USER_HANDLE); } + @Test public void testSetAutoTimeEnabledModifiesSetting() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3928,6 +4054,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0); } + @Test public void testSetAutoTimeEnabledWithPOOnUser0() throws Exception { mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; setupProfileOwnerOnUser0(); @@ -3938,6 +4065,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0); } + @Test public void testSetAutoTimeEnabledFailWithPONotOnUser0() throws Exception { setupProfileOwner(); assertExpectException(SecurityException.class, null, @@ -3945,6 +4073,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0); } + @Test public void testSetAutoTimeEnabledWithPOOfOrganizationOwnedDevice() throws Exception { setupProfileOwner(); configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE); @@ -3956,6 +4085,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0); } + @Test public void testSetAutoTimeZoneEnabledModifiesSetting() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -3966,6 +4096,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0); } + @Test public void testSetAutoTimeZoneEnabledWithPOOnUser0() throws Exception { mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; setupProfileOwnerOnUser0(); @@ -3976,6 +4107,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0); } + @Test public void testSetAutoTimeZoneEnabledFailWithPONotOnUser0() throws Exception { setupProfileOwner(); assertExpectException(SecurityException.class, null, @@ -3984,6 +4116,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { 0); } + @Test public void testSetAutoTimeZoneEnabledWithPOOfOrganizationOwnedDevice() throws Exception { setupProfileOwner(); configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE); @@ -3995,12 +4128,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0); } + @Test public void testIsOrganizationOwnedDevice() throws Exception { // Set up the user manager to return correct user info addManagedProfile(admin1, DpmMockContext.CALLER_UID, admin1); // Any caller should be able to call this method. - assertFalse(dpm.isOrganizationOwnedDeviceWithManagedProfile()); + assertThat(dpm.isOrganizationOwnedDeviceWithManagedProfile()).isFalse(); configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE); verify(getServices().userManager).setUserRestriction( @@ -4008,13 +4142,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(true), eq(UserHandle.of(UserHandle.USER_SYSTEM))); - assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile()); + assertThat(dpm.isOrganizationOwnedDeviceWithManagedProfile()).isTrue(); // A random caller from another user should also be able to get the right result. mContext.binder.callingUid = DpmMockContext.ANOTHER_UID; - assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile()); + assertThat(dpm.isOrganizationOwnedDeviceWithManagedProfile()).isTrue(); } + @Test public void testMarkOrganizationOwnedDevice_baseRestrictionsAdded() throws Exception { addManagedProfile(admin1, DpmMockContext.CALLER_UID, admin1); @@ -4044,6 +4179,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { parentDpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER)); } + @Test public void testSetTime() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -4051,11 +4187,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().alarmManager).setTime(0); } + @Test public void testSetTimeFailWithPO() throws Exception { setupProfileOwner(); assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0)); } + @Test public void testSetTimeWithPOOfOrganizationOwnedDevice() throws Exception { setupProfileOwner(); configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE); @@ -4063,14 +4201,16 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().alarmManager).setTime(0); } + @Test public void testSetTimeWithAutoTimeOn() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0)) .thenReturn(1); - assertFalse(dpm.setTime(admin1, 0)); + assertThat(dpm.setTime(admin1, 0)).isFalse(); } + @Test public void testSetTimeZone() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -4078,12 +4218,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().alarmManager).setTimeZone("Asia/Shanghai"); } + @Test public void testSetTimeZoneFailWithPO() throws Exception { setupProfileOwner(); assertExpectException(SecurityException.class, null, () -> dpm.setTimeZone(admin1, "Asia/Shanghai")); } + @Test public void testSetTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception { setupProfileOwner(); configureProfileOwnerOfOrgOwnedDevice(admin1, CALLER_USER_HANDLE); @@ -4091,14 +4233,16 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().alarmManager).setTimeZone("Asia/Shanghai"); } + @Test public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0)) .thenReturn(1); - assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai")); + assertThat(dpm.setTimeZone(admin1, "Asia/Shanghai")).isFalse(); } + @Test public void testGetLastBugReportRequestTime() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -4115,39 +4259,40 @@ public class DevicePolicyManagerTest extends DpmTestBase { getServices().removeUser(CALLER_USER_HANDLE); // No bug reports were requested so far. - assertEquals(-1, dpm.getLastBugReportRequestTime()); + assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(-1); // Requesting a bug report should update the timestamp. final long beforeRequest = System.currentTimeMillis(); dpm.requestBugreport(admin1); final long bugReportRequestTime = dpm.getLastBugReportRequestTime(); final long afterRequest = System.currentTimeMillis(); - assertTrue(bugReportRequestTime >= beforeRequest); - assertTrue(bugReportRequestTime <= afterRequest); + assertThat(bugReportRequestTime).isAtLeast(beforeRequest); + assertThat(bugReportRequestTime).isAtMost(afterRequest); // Checking the timestamp again should not change it. Thread.sleep(2); - assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); + assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime); // Restarting the DPMS should not lose the timestamp. initializeDpms(); - assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); + assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime); // Any uid holding MANAGE_USERS permission can retrieve the timestamp. mContext.binder.callingUid = 1234567; mContext.callerPermissions.add(permission.MANAGE_USERS); - assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); + assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime); mContext.callerPermissions.remove(permission.MANAGE_USERS); // System can retrieve the timestamp. mContext.binder.clearCallingIdentity(); - assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime()); + assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(bugReportRequestTime); // Removing the device owner should clear the timestamp. clearDeviceOwner(); - assertEquals(-1, dpm.getLastBugReportRequestTime()); + assertThat(dpm.getLastBugReportRequestTime()).isEqualTo(-1); } + @Test public void testGetLastNetworkLogRetrievalTime() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -4165,57 +4310,58 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(true); // No logs were retrieved so far. - assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1); // Attempting to retrieve logs without enabling logging should not change the timestamp. dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); - assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1); // Enabling logging should not change the timestamp. dpm.setNetworkLoggingEnabled(admin1, true); - assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1); // Retrieving the logs should update the timestamp. final long beforeRetrieval = System.currentTimeMillis(); dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); final long afterRetrieval = System.currentTimeMillis(); - assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval); - assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval); + assertThat(firstNetworkLogRetrievalTime >= beforeRetrieval).isTrue(); + assertThat(firstNetworkLogRetrievalTime <= afterRetrieval).isTrue(); // Checking the timestamp again should not change it. Thread.sleep(2); - assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(firstNetworkLogRetrievalTime); // Retrieving the logs again should update the timestamp. dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */); final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime(); - assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime); + assertThat(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime).isTrue(); // Disabling logging should not change the timestamp. Thread.sleep(2); dpm.setNetworkLoggingEnabled(admin1, false); - assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime); // Restarting the DPMS should not lose the timestamp. initializeDpms(); - assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime); // Any uid holding MANAGE_USERS permission can retrieve the timestamp. mContext.binder.callingUid = 1234567; mContext.callerPermissions.add(permission.MANAGE_USERS); - assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime); mContext.callerPermissions.remove(permission.MANAGE_USERS); // System can retrieve the timestamp. mContext.binder.clearCallingIdentity(); - assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(secondNetworkLogRetrievalTime); // Removing the device owner should clear the timestamp. clearDeviceOwner(); - assertEquals(-1, dpm.getLastNetworkLogRetrievalTime()); + assertThat(dpm.getLastNetworkLogRetrievalTime()).isEqualTo(-1); } + @Test public void testGetBindDeviceAdminTargetUsers() throws Exception { // Setup device owner. mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -4268,9 +4414,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setLockTaskPackages(who, packages); MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who)); for (String p : packages) { - assertTrue(dpm.isLockTaskPermitted(p)); + assertThat(dpm.isLockTaskPermitted(p)).isTrue(); } - assertFalse(dpm.isLockTaskPermitted("anotherPackage")); + assertThat(dpm.isLockTaskPermitted("anotherPackage")).isFalse(); // Test to see if set lock task features can be set dpm.setLockTaskFeatures(who, flags); verifyLockTaskState(userId, packages, flags); @@ -4283,11 +4429,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.setLockTaskPackages(who, packages)); assertExpectException(SecurityException.class, /* messageRegex =*/ null, () -> dpm.getLockTaskPackages(who)); - assertFalse(dpm.isLockTaskPermitted("doPackage1")); + assertThat(dpm.isLockTaskPermitted("doPackage1")).isFalse(); assertExpectException(SecurityException.class, /* messageRegex =*/ null, () -> dpm.setLockTaskFeatures(who, flags)); } + @Test public void testLockTaskPolicyForProfileOwner() throws Exception { // Setup a PO mContext.binder.callingUid = DpmMockContext.CALLER_UID; @@ -4315,9 +4462,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS | DevicePolicyManager.LOCK_TASK_FEATURE_HOME | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW; - verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags); + verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, + mpoFlags); } + @Test public void testLockTaskFeatures_IllegalArgumentException() throws Exception { // Setup a device owner. mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -4332,12 +4481,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.setLockTaskFeatures(admin1, flags)); } + @Test public void testSecondaryLockscreen_profileOwner() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_UID; // Initial state is disabled. - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of( - CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of( + CALLER_USER_HANDLE))).isFalse(); // Profile owner can set enabled state. setAsProfileOwner(admin1); @@ -4345,8 +4495,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { .getString(R.string.config_defaultSupervisionProfileOwnerComponent)) .thenReturn(admin1.flattenToString()); dpm.setSecondaryLockscreenEnabled(admin1, true); - assertTrue(dpm.isSecondaryLockscreenEnabled(UserHandle.of( - CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of( + CALLER_USER_HANDLE))).isTrue(); // Managed profile managed by different package is unaffiliated - cannot set enabled. final int managedProfileUserId = 15; @@ -4359,11 +4509,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.setSecondaryLockscreenEnabled(adminDifferentPackage, false)); } + @Test public void testSecondaryLockscreen_deviceOwner() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; // Initial state is disabled. - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM))) + .isFalse(); // Device owners can set enabled state. setupDeviceOwner(); @@ -4371,14 +4523,16 @@ public class DevicePolicyManagerTest extends DpmTestBase { .getString(R.string.config_defaultSupervisionProfileOwnerComponent)) .thenReturn(admin1.flattenToString()); dpm.setSecondaryLockscreenEnabled(admin1, true); - assertTrue(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM))) + .isTrue(); } + @Test public void testSecondaryLockscreen_nonOwner() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_UID; // Initial state is disabled. - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse(); // Non-DO/PO cannot set enabled state. when(mServiceContext.resources @@ -4386,9 +4540,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(admin1.flattenToString()); assertExpectException(SecurityException.class, /* messageRegex= */ null, () -> dpm.setSecondaryLockscreenEnabled(admin1, true)); - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse(); } + @Test public void testSecondaryLockscreen_nonSupervisionApp() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_UID; @@ -4403,13 +4558,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { eq(CALLER_USER_HANDLE)); // Initial state is disabled. - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse(); // Caller is Profile Owner, but no supervision app is configured. setAsProfileOwner(admin1); assertExpectException(SecurityException.class, "is not the default supervision component", () -> dpm.setSecondaryLockscreenEnabled(admin1, true)); - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse(); // Caller is Profile Owner, but is not the default configured supervision app. when(mServiceContext.resources @@ -4417,22 +4572,23 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(admin2.flattenToString()); assertExpectException(SecurityException.class, "is not the default supervision component", () -> dpm.setSecondaryLockscreenEnabled(admin1, true)); - assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))); + assertThat(dpm.isSecondaryLockscreenEnabled(UserHandle.of(CALLER_USER_HANDLE))).isFalse(); } + @Test public void testIsDeviceManaged() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); // The device owner itself, any uid holding MANAGE_USERS permission and the system can // find out that the device has a device owner. - assertTrue(dpm.isDeviceManaged()); + assertThat(dpm.isDeviceManaged()).isTrue(); mContext.binder.callingUid = 1234567; mContext.callerPermissions.add(permission.MANAGE_USERS); - assertTrue(dpm.isDeviceManaged()); + assertThat(dpm.isDeviceManaged()).isTrue(); mContext.callerPermissions.remove(permission.MANAGE_USERS); mContext.binder.clearCallingIdentity(); - assertTrue(dpm.isDeviceManaged()); + assertThat(dpm.isDeviceManaged()).isTrue(); clearDeviceOwner(); @@ -4440,12 +4596,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { // not have a device owner. mContext.binder.callingUid = 1234567; mContext.callerPermissions.add(permission.MANAGE_USERS); - assertFalse(dpm.isDeviceManaged()); + assertThat(dpm.isDeviceManaged()).isFalse(); mContext.callerPermissions.remove(permission.MANAGE_USERS); mContext.binder.clearCallingIdentity(); - assertFalse(dpm.isDeviceManaged()); + assertThat(dpm.isDeviceManaged()).isFalse(); } + @Test public void testDeviceOwnerOrganizationName() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -4453,23 +4610,24 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setOrganizationName(admin1, "organization"); // Device owner can retrieve organization managing the device. - assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); + assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo("organization"); // Any uid holding MANAGE_USERS permission can retrieve organization managing the device. mContext.binder.callingUid = 1234567; mContext.callerPermissions.add(permission.MANAGE_USERS); - assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); + assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo("organization"); mContext.callerPermissions.remove(permission.MANAGE_USERS); // System can retrieve organization managing the device. mContext.binder.clearCallingIdentity(); - assertEquals("organization", dpm.getDeviceOwnerOrganizationName()); + assertThat(dpm.getDeviceOwnerOrganizationName()).isEqualTo("organization"); // Removing the device owner clears the organization managing the device. clearDeviceOwner(); - assertNull(dpm.getDeviceOwnerOrganizationName()); + assertThat(dpm.getDeviceOwnerOrganizationName()).isNull(); } + @Test public void testWipeDataManagedProfile() throws Exception { final int MANAGED_PROFILE_USER_ID = 15; final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436); @@ -4489,6 +4647,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { MANAGED_PROFILE_USER_ID); } + @Test public void testWipeDataManagedProfileDisallowed() throws Exception { final int MANAGED_PROFILE_USER_ID = 15; final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436); @@ -4512,6 +4671,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.wipeData(0)); } + @Test public void testWipeDataDeviceOwner() throws Exception { setDeviceOwner(); when(getServices().userManager.getUserRestrictionSource( @@ -4527,6 +4687,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /*wipeEuicc=*/ eq(false)); } + @Test public void testWipeEuiccDataEnabled() throws Exception { setDeviceOwner(); when(getServices().userManager.getUserRestrictionSource( @@ -4542,6 +4703,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /*wipeEuicc=*/ eq(true)); } + @Test public void testWipeDataDeviceOwnerDisallowed() throws Exception { setDeviceOwner(); when(getServices().userManager.getUserRestrictionSource( @@ -4556,6 +4718,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.wipeData(0)); } + @Test public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception { final int MANAGED_PROFILE_USER_ID = 15; final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436); @@ -4588,6 +4751,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyZeroInteractions(getServices().recoverySystem); } + @Test public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed() throws Exception { final int MANAGED_PROFILE_USER_ID = 15; @@ -4621,6 +4785,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyZeroInteractions(getServices().recoverySystem); } + @Test public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception { setDeviceOwner(); when(getServices().userManager.getUserRestrictionSource( @@ -4643,6 +4808,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /*wipeEuicc=*/ eq(false)); } + @Test public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception { setDeviceOwner(); when(getServices().userManager.getUserRestrictionSource( @@ -4664,6 +4830,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { .removeUserEvenWhenDisallowed(anyInt()); } + @Test public void testMaximumFailedDevicePasswordAttemptsReachedOrgOwnedManagedProfile() throws Exception { final int MANAGED_PROFILE_USER_ID = 15; @@ -4679,16 +4846,16 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; dpm.setMaximumFailedPasswordsForWipe(admin1, 3); - assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(admin1)); - assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(null)); + assertThat(dpm.getMaximumFailedPasswordsForWipe(admin1)).isEqualTo(3); + assertThat(dpm.getMaximumFailedPasswordsForWipe(null)).isEqualTo(3); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); - assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM)); + assertThat(dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM)).isEqualTo(3); // Check that primary will be wiped as a result of failed primary user unlock attempts. - assertEquals(UserHandle.USER_SYSTEM, - dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM)); + assertThat(dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM)) + .isEqualTo(UserHandle.USER_SYSTEM); // Failed password attempts on the parent user are taken into account, as there isn't a // separate work challenge. @@ -4702,6 +4869,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /*wipeEuicc=*/ eq(false)); } + @Test public void testMaximumFailedProfilePasswordAttemptsReachedOrgOwnedManagedProfile() throws Exception { final int MANAGED_PROFILE_USER_ID = 15; @@ -4724,14 +4892,15 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN); - assertEquals(0, dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM)); - assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(null, MANAGED_PROFILE_USER_ID)); + assertThat(dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM)).isEqualTo(0); + assertThat(dpm.getMaximumFailedPasswordsForWipe(null, MANAGED_PROFILE_USER_ID)) + .isEqualTo(3); // Check that the policy is not affecting primary profile challenge. - assertEquals(UserHandle.USER_NULL, - dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM)); + assertThat(dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM)) + .isEqualTo(UserHandle.USER_NULL); // Check that primary will be wiped as a result of failed profile unlock attempts. - assertEquals(UserHandle.USER_SYSTEM, - dpm.getProfileWithMinimumFailedPasswordsForWipe(MANAGED_PROFILE_USER_ID)); + assertThat(dpm.getProfileWithMinimumFailedPasswordsForWipe(MANAGED_PROFILE_USER_ID)) + .isEqualTo(UserHandle.USER_SYSTEM); // Simulate three failed attempts at solving the separate challenge. dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID); @@ -4744,6 +4913,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /*wipeEuicc=*/ eq(false)); } + @Test public void testGetPermissionGrantState() throws Exception { final String permission = "some.permission"; final String app1 = "com.example.app1"; @@ -4766,10 +4936,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { // System can retrieve permission grant state. mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; mContext.packageName = "android"; - assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED, - dpm.getPermissionGrantState(null, app1, permission)); - assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT, - dpm.getPermissionGrantState(null, app2, permission)); + assertThat(dpm.getPermissionGrantState(null, app1, permission)) + .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + assertThat(dpm.getPermissionGrantState(null, app2, permission)) + .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); // A regular app cannot retrieve permission grant state. mContext.binder.callingUid = setupPackageInPackageManager(app1, 1); @@ -4781,12 +4951,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_UID; mContext.packageName = admin1.getPackageName(); setAsProfileOwner(admin1); - assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED, - dpm.getPermissionGrantState(admin1, app1, permission)); - assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT, - dpm.getPermissionGrantState(admin1, app2, permission)); + assertThat(dpm.getPermissionGrantState(admin1, app1, permission)) + .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED); + assertThat(dpm.getPermissionGrantState(admin1, app2, permission)) + .isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT); } + @Test public void testResetPasswordWithToken() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); @@ -4801,27 +4972,26 @@ public class DevicePolicyManagerTest extends DpmTestBase { when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM), nullable(EscrowTokenStateChangeCallback.class))) .thenReturn(handle); - assertTrue(dpm.setResetPasswordToken(admin1, token)); + assertThat(dpm.setResetPasswordToken(admin1, token)).isTrue(); // test password activation - when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM))) - .thenReturn(true); - assertTrue(dpm.isResetPasswordTokenActive(admin1)); + when(getServices().lockPatternUtils.isEscrowTokenActive(handle, UserHandle.USER_SYSTEM)) + .thenReturn(true); + assertThat(dpm.isResetPasswordTokenActive(admin1)).isTrue(); // test reset password with token when(getServices().lockPatternUtils.setLockCredentialWithToken( - eq(LockscreenCredential.createPassword(password)), - eq(handle), eq(token), - eq(UserHandle.USER_SYSTEM))) - .thenReturn(true); - assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0)); + LockscreenCredential.createPassword(password), handle, token, + UserHandle.USER_SYSTEM)).thenReturn(true); + assertThat(dpm.resetPasswordWithToken(admin1, password, token, 0)).isTrue(); // test removing a token - when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM))) + when(getServices().lockPatternUtils.removeEscrowToken(handle, UserHandle.USER_SYSTEM)) .thenReturn(true); - assertTrue(dpm.clearResetPasswordToken(admin1)); + assertThat(dpm.clearResetPasswordToken(admin1)).isTrue(); } + @Test public void testIsActivePasswordSufficient() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; mContext.packageName = admin1.getPackageName(); @@ -4841,11 +5011,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes()); setActivePasswordState(passwordMetricsNoSymbols); - assertTrue(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isTrue(); initializeDpms(); reset(mContext.spiedContext); - assertTrue(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isTrue(); // This call simulates the user entering the password for the first time after a reboot. // This causes password metrics to be reloaded into memory. Until this happens, @@ -4854,23 +5024,24 @@ public class DevicePolicyManagerTest extends DpmTestBase { // requirements. This is a known limitation of the current implementation of // isActivePasswordSufficient() - see b/34218769. setActivePasswordState(passwordMetricsNoSymbols); - assertTrue(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isTrue(); dpm.setPasswordMinimumSymbols(admin1, 1); // This assertion would fail if we had not called setActivePasswordState() again after // initializeDpms() - see previous comment. - assertFalse(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isFalse(); initializeDpms(); reset(mContext.spiedContext); - assertFalse(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isFalse(); PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes()); setActivePasswordState(passwordMetricsWithSymbols); - assertTrue(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isTrue(); } + @Test public void testIsActivePasswordSufficient_noLockScreen() throws Exception { // If there is no lock screen, the password is considered empty no matter what, because // it provides no security. @@ -4885,7 +5056,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE)); // If no password requirements are set, isActivePasswordSufficient should succeed. - assertTrue(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isTrue(); // Now set some password quality requirements. dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING); @@ -4900,9 +5071,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { MockUtils.checkUserHandle(userHandle)); // The active (nonexistent) password doesn't comply with the requirements. - assertFalse(dpm.isActivePasswordSufficient()); + assertThat(dpm.isActivePasswordSufficient()).isFalse(); } + @Test public void testIsPasswordSufficientAfterProfileUnification() throws Exception { final int managedProfileUserId = CALLER_USER_HANDLE; final int managedProfileAdminUid = @@ -4921,13 +5093,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Numeric password is compliant with current requirement (QUALITY_NUMERIC set explicitly // on the parent admin) - assertTrue(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM, - UserHandle.USER_NULL)); + assertThat(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM, + UserHandle.USER_NULL)).isTrue(); // Numeric password is not compliant if profile is to be unified: the profile has a // QUALITY_ALPHABETIC policy on itself which will be enforced on the password after // unification. - assertFalse(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM, - managedProfileUserId)); + assertThat(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM, + managedProfileUserId)).isFalse(); } private void setActivePasswordState(PasswordMetrics passwordMetrics) @@ -4961,6 +5133,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.restoreCallingIdentity(ident); } + @Test public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception { final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD; final Uri currentImeUri = Settings.Secure.getUriFor(currentIme); @@ -4976,70 +5149,71 @@ public class DevicePolicyManagerTest extends DpmTestBase { // First and second user set IMEs manually. mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Device owner changes IME for first user. mContext.binder.callingUid = deviceOwnerUid; - when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM)) - .thenReturn("ime1"); + when(getServices().settings.settingsSecureGetStringForUser(currentIme, + UserHandle.USER_SYSTEM)).thenReturn("ime1"); dpm.setSecureSetting(admin1, currentIme, "ime2"); verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2", UserHandle.USER_SYSTEM); reset(getServices().settings); dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM); mContext.binder.callingUid = firstUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Second user changes IME manually. dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE); mContext.binder.callingUid = firstUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // First user changes IME manually. dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Device owner changes IME for first user again. mContext.binder.callingUid = deviceOwnerUid; - when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM)) - .thenReturn("ime2"); + when(getServices().settings.settingsSecureGetStringForUser(currentIme, + UserHandle.USER_SYSTEM)).thenReturn("ime2"); dpm.setSecureSetting(admin1, currentIme, "ime3"); verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3", UserHandle.USER_SYSTEM); dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM); mContext.binder.callingUid = firstUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Restarting the DPMS should not lose information. initializeDpms(); mContext.binder.callingUid = firstUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Device owner can find out whether it set the current IME itself. mContext.binder.callingUid = deviceOwnerUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); // Removing the device owner should clear the information that it set the current IME. clearDeviceOwner(); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); } + @Test public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception { final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD; final Uri currentImeUri = Settings.Secure.getUriFor(currentIme); @@ -5055,9 +5229,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { // First and second user set IMEs manually. mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Profile owner changes IME for second user. mContext.binder.callingUid = profileOwnerUid; @@ -5069,23 +5243,23 @@ public class DevicePolicyManagerTest extends DpmTestBase { reset(getServices().settings); dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); // First user changes IME manually. dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); // Second user changes IME manually. dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); // Profile owner changes IME for second user again. mContext.binder.callingUid = profileOwnerUid; @@ -5096,29 +5270,30 @@ public class DevicePolicyManagerTest extends DpmTestBase { CALLER_USER_HANDLE); dpms.notifyChangeToContentObserver(currentImeUri, CALLER_USER_HANDLE); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); // Restarting the DPMS should not lose information. initializeDpms(); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); // Profile owner can find out whether it set the current IME itself. mContext.binder.callingUid = profileOwnerUid; - assertTrue(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isTrue(); // Removing the profile owner should clear the information that it set the current IME. dpm.clearProfileOwner(admin1); mContext.binder.callingUid = firstUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); mContext.binder.callingUid = secondUserSystemUid; - assertFalse(dpm.isCurrentInputMethodSetByOwner()); + assertThat(dpm.isCurrentInputMethodSetByOwner()).isFalse(); } + @Test public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo() throws Exception { // Set up a device owner. @@ -5127,6 +5302,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid); } + @Test public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser() throws Exception { // Set up a profile owner. @@ -5141,23 +5317,24 @@ public class DevicePolicyManagerTest extends DpmTestBase { final int userId = UserHandle.getUserId(adminUid); final String packageName = "some.package"; - assertFalse(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.singletonList(packageName))); - assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1)); + assertThat(dpms.setPermittedCrossProfileNotificationListeners( + admin1, Collections.singletonList(packageName))).isFalse(); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId)); + assertThat(dpms.isNotificationListenerServicePermitted(packageName, userId)).isTrue(); // Attempt to set to empty list (which means no listener is allowlisted) mContext.binder.callingUid = adminUid; - assertFalse(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.emptyList())); - assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1)); + assertThat(dpms.setPermittedCrossProfileNotificationListeners( + admin1, Collections.emptyList())).isFalse(); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId)); + assertThat(dpms.isNotificationListenerServicePermitted(packageName, userId)).isTrue(); } + @Test public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception { // Set up a managed profile final int MANAGED_PROFILE_USER_ID = 15; @@ -5171,8 +5348,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user. /*appId=*/ 12345, /*flags=*/ 0); - assertTrue(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.singletonList(permittedListener))); + assertThat(dpms.setPermittedCrossProfileNotificationListeners( + admin1, Collections.singletonList(permittedListener))).isTrue(); // isNotificationListenerServicePermitted should throw if not called from System. assertExpectException(SecurityException.class, /* messageRegex= */ null, @@ -5180,10 +5357,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { permittedListener, MANAGED_PROFILE_USER_ID)); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted( - permittedListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + permittedListener, MANAGED_PROFILE_USER_ID)).isTrue(); } + @Test public void testSetPermittedCrossProfileNotificationListeners_managedProfile() throws Exception { // Set up a managed profile @@ -5212,63 +5390,64 @@ public class DevicePolicyManagerTest extends DpmTestBase { ++appId, ApplicationInfo.FLAG_SYSTEM); // By default all packages are allowed - assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1)); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted( - permittedListener, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - notPermittedListener, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + permittedListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + notPermittedListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, MANAGED_PROFILE_USER_ID)).isTrue(); // Setting only one package in the allowlist mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; - assertTrue(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.singletonList(permittedListener))); + assertThat(dpms.setPermittedCrossProfileNotificationListeners( + admin1, Collections.singletonList(permittedListener))).isTrue(); final List<String> permittedListeners = dpms.getPermittedCrossProfileNotificationListeners(admin1); - assertEquals(1, permittedListeners.size()); - assertEquals(permittedListener, permittedListeners.get(0)); + assertThat(permittedListeners.size()).isEqualTo(1); + assertThat(permittedListeners.get(0)).isEqualTo(permittedListener); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted( - permittedListener, MANAGED_PROFILE_USER_ID)); - assertFalse(dpms.isNotificationListenerServicePermitted( - notPermittedListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + permittedListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + notPermittedListener, MANAGED_PROFILE_USER_ID)).isFalse(); // System packages are always allowed (even if not in the allowlist) - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, MANAGED_PROFILE_USER_ID)).isTrue(); // Setting an empty allowlist - only system listeners allowed mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; - assertTrue(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.emptyList())); - assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size()); + assertThat(dpms.setPermittedCrossProfileNotificationListeners( + admin1, Collections.emptyList())).isTrue(); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1).size()).isEqualTo(0); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertFalse(dpms.isNotificationListenerServicePermitted( - permittedListener, MANAGED_PROFILE_USER_ID)); - assertFalse(dpms.isNotificationListenerServicePermitted( - notPermittedListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + permittedListener, MANAGED_PROFILE_USER_ID)).isFalse(); + assertThat(dpms.isNotificationListenerServicePermitted( + notPermittedListener, MANAGED_PROFILE_USER_ID)).isFalse(); // System packages are always allowed (even if not in the allowlist) - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, MANAGED_PROFILE_USER_ID)).isTrue(); // Setting a null allowlist - all listeners allowed mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; - assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null)); - assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1)); + assertThat(dpms.setPermittedCrossProfileNotificationListeners(admin1, null)).isTrue(); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted( - permittedListener, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - notPermittedListener, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, MANAGED_PROFILE_USER_ID)); + assertThat(dpms.isNotificationListenerServicePermitted( + permittedListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + notPermittedListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, MANAGED_PROFILE_USER_ID)).isTrue(); } + @Test public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile() throws Exception { // Set up a managed profile @@ -5291,36 +5470,37 @@ public class DevicePolicyManagerTest extends DpmTestBase { ++appId, ApplicationInfo.FLAG_SYSTEM); // By default all packages are allowed (for all profiles) - assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1)); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1)).isNull(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue(dpms.isNotificationListenerServicePermitted( - nonSystemPackage, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - nonSystemPackage, UserHandle.USER_SYSTEM)); - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, UserHandle.USER_SYSTEM)); + assertThat(dpms.isNotificationListenerServicePermitted( + nonSystemPackage, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + nonSystemPackage, UserHandle.USER_SYSTEM)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, UserHandle.USER_SYSTEM)).isTrue(); // Setting an empty allowlist - only system listeners allowed in managed profile, but // all allowed in primary profile mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; - assertTrue(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.emptyList())); - assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size()); + assertThat(dpms.setPermittedCrossProfileNotificationListeners( + admin1, Collections.emptyList())).isTrue(); + assertThat(dpms.getPermittedCrossProfileNotificationListeners(admin1).size()).isEqualTo(0); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertFalse(dpms.isNotificationListenerServicePermitted( - nonSystemPackage, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, MANAGED_PROFILE_USER_ID)); - assertTrue(dpms.isNotificationListenerServicePermitted( - nonSystemPackage, UserHandle.USER_SYSTEM)); - assertTrue(dpms.isNotificationListenerServicePermitted( - systemListener, UserHandle.USER_SYSTEM)); + assertThat(dpms.isNotificationListenerServicePermitted( + nonSystemPackage, MANAGED_PROFILE_USER_ID)).isFalse(); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, MANAGED_PROFILE_USER_ID)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + nonSystemPackage, UserHandle.USER_SYSTEM)).isTrue(); + assertThat(dpms.isNotificationListenerServicePermitted( + systemListener, UserHandle.USER_SYSTEM)).isTrue(); } + @Test public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception { mServiceContext.packageName = mRealTestContext.getPackageName(); mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; @@ -5330,6 +5510,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context); } + @Test public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception { mServiceContext.packageName = mRealTestContext.getPackageName(); mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; @@ -5340,6 +5521,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context); } + @Test public void testGetOwnerInstalledCaCertsForDelegate() throws Exception { mServiceContext.packageName = mRealTestContext.getPackageName(); mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; @@ -5359,6 +5541,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller); } + @Test public void testDisallowSharingIntoProfileSetRestriction() { when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package)) .thenReturn("com.android.managedprovisioning"); @@ -5371,6 +5554,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyDataSharingChangedBroadcast(); } + @Test public void testDisallowSharingIntoProfileClearRestriction() { when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package)) .thenReturn("com.android.managedprovisioning"); @@ -5383,6 +5567,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { verifyDataSharingChangedBroadcast(); } + @Test public void testDisallowSharingIntoProfileUnchanged() { RestrictionsListener listener = new RestrictionsListener(mContext); listener.onUserRestrictionsChanged(CALLER_USER_HANDLE, new Bundle(), new Bundle()); @@ -5399,6 +5584,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); } + @Test public void testOverrideApnAPIsFailWithPO() throws Exception { setupProfileOwner(); ApnSetting apn = (new ApnSetting.Builder()) @@ -5446,13 +5632,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { runAsCaller(callerContext, dpms, (dpm) -> { when(getServices().keyChainConnection.getService().installCaCertificate(caCert)) .thenReturn(alias); - assertTrue(dpm.installCaCert(caller, caCert)); + assertThat(dpm.installCaCert(caller, caCert)).isTrue(); when(getServices().keyChainConnection.getService().getUserCaAliases()) .thenReturn(asSlice(new String[] {alias})); }); - getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED) - .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()), + getServices().injectBroadcast(mServiceContext, + new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED) + .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()), callerUser.getIdentifier()); flushTasks(dpms); @@ -5461,25 +5648,27 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Device Owner / Profile Owner can find out which CA certs were installed by itself. runAsCaller(admin1Context, dpms, (dpm) -> { final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser); - assertEquals(Collections.singletonList(alias), installedCaCerts); + assertThat(installedCaCerts).isEqualTo(Collections.singletonList(alias)); ownerInstalledCaCerts.addAll(installedCaCerts); }); // Restarting the DPMS should not lose information. initializeDpms(); - runAsCaller(admin1Context, dpms, (dpm) -> - assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser))); + runAsCaller(admin1Context, dpms, + (dpm) -> assertThat(dpm.getOwnerInstalledCaCerts(callerUser)) + .isEqualTo(ownerInstalledCaCerts)); // System can find out which CA certs were installed by the Device Owner / Profile Owner. runAsCaller(serviceContext, dpms, (dpm) -> { - assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)); + assertThat(dpm.getOwnerInstalledCaCerts(callerUser)).isEqualTo(ownerInstalledCaCerts); // Remove the CA cert. reset(getServices().keyChainConnection.getService()); }); - getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED) - .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()), + getServices().injectBroadcast(mServiceContext, + new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED) + .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()), callerUser.getIdentifier()); flushTasks(dpms); @@ -5516,14 +5705,15 @@ public class DevicePolicyManagerTest extends DpmTestBase { runAsCaller(callerContext, dpms, (dpm) -> { when(getServices().keyChainConnection.getService().installCaCertificate(caCert)) .thenReturn(alias); - assertTrue(dpm.installCaCert(callerName, caCert)); + assertThat(dpm.installCaCert(callerName, caCert)).isTrue(); }); // Fake the CA cert as having been installed when(getServices().keyChainConnection.getService().getUserCaAliases()) .thenReturn(asSlice(new String[] {alias})); - getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED) - .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()), + getServices().injectBroadcast(mServiceContext, + new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED) + .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()), callerUser.getIdentifier()); flushTasks(dpms); @@ -5532,8 +5722,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { runAsCaller(serviceContext, dpms, (dpm) -> { final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser); - assertNotNull(ownerInstalledCaCerts); - assertTrue(ownerInstalledCaCerts.isEmpty()); + assertThat(ownerInstalledCaCerts).isNotNull(); + assertThat(ownerInstalledCaCerts.isEmpty()).isTrue(); }); } @@ -5541,9 +5731,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags); Arrays.sort(gotFlags); Arrays.sort(expectedFlags); - assertTrue(Arrays.equals(expectedFlags, gotFlags)); + assertThat(Arrays.equals(expectedFlags, gotFlags)).isTrue(); } + @Test public void testTranslationOfIdAttestationFlag() { int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID}; int[] correspondingAttUtilsTypes = new int[]{ @@ -5551,7 +5742,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { AttestationUtils.ID_TYPE_MEID}; // Test translation of zero flags - assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0)); + assertThat(DevicePolicyManagerService.translateIdAttestationFlags(0)).isNull(); // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but // non-null array @@ -5578,39 +5769,41 @@ public class DevicePolicyManagerTest extends DpmTestBase { AttestationUtils.ID_TYPE_MEID}); } + @Test public void testRevertDeviceOwnership_noMetadataFile() throws Exception { setDeviceOwner(); initializeDpms(); - assertFalse(getMockTransferMetadataManager().metadataFileExists()); - assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM)); - assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM)); - } - - // @FlakyTest(bugId = 148934649) - // public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception { - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), - // getDeviceOwnerPoliciesFile()); - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated), - // getDeviceOwnerFile()); - // assertDeviceOwnershipRevertedWithFakeTransferMetadata(); - // } - - // @FlakyTest(bugId = 148934649) - // public void testRevertDeviceOwnership_deviceNotMigrated() - // throws Exception { - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), - // getDeviceOwnerPoliciesFile()); - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated), - // getDeviceOwnerFile()); - // assertDeviceOwnershipRevertedWithFakeTransferMetadata(); - // } - - public void testRevertDeviceOwnership_adminAndDeviceNotMigrated() - throws Exception { + assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse(); + assertThat(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM)).isTrue(); + assertThat(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM)).isTrue(); + } + + @FlakyTest(bugId = 148934649) + @Test + public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception { + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), + getDeviceOwnerPoliciesFile()); + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated), + getDeviceOwnerFile()); + assertDeviceOwnershipRevertedWithFakeTransferMetadata(); + } + + @FlakyTest(bugId = 148934649) + @Test + public void testRevertDeviceOwnership_deviceNotMigrated() throws Exception { + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), + getDeviceOwnerPoliciesFile()); + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated), + getDeviceOwnerFile()); + assertDeviceOwnershipRevertedWithFakeTransferMetadata(); + } + + @Test + public void testRevertDeviceOwnership_adminAndDeviceNotMigrated() throws Exception { DpmTestUtils.writeInputStreamToFile( getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated), getDeviceOwnerPoliciesFile()); @@ -5620,40 +5813,44 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertDeviceOwnershipRevertedWithFakeTransferMetadata(); } + @Test public void testRevertProfileOwnership_noMetadataFile() throws Exception { setupProfileOwner(); initializeDpms(); - assertFalse(getMockTransferMetadataManager().metadataFileExists()); - assertTrue(dpms.isProfileOwner(admin1, CALLER_USER_HANDLE)); - assertTrue(dpms.isAdminActive(admin1, CALLER_USER_HANDLE)); - } - - // @FlakyTest(bugId = 148934649) - // public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception { - // getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0, - // UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM); - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), - // getProfileOwnerPoliciesFile()); - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated), - // getProfileOwnerFile()); - // assertProfileOwnershipRevertedWithFakeTransferMetadata(); - // } - - // @FlakyTest(bugId = 148934649) - // public void testRevertProfileOwnership_profileNotMigrated() throws Exception { - // getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0, - // UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM); - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), - // getProfileOwnerPoliciesFile()); - // DpmTestUtils.writeInputStreamToFile( - // getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated), - // getProfileOwnerFile()); - // assertProfileOwnershipRevertedWithFakeTransferMetadata(); - // } + assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse(); + assertThat(dpms.isProfileOwner(admin1, CALLER_USER_HANDLE)).isTrue(); + assertThat(dpms.isAdminActive(admin1, CALLER_USER_HANDLE)).isTrue(); + } + + @FlakyTest(bugId = 148934649) + @Test + public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception { + getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0, + UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM); + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), + getProfileOwnerPoliciesFile()); + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated), + getProfileOwnerFile()); + assertProfileOwnershipRevertedWithFakeTransferMetadata(); + } + @FlakyTest(bugId = 148934649) + @Test + public void testRevertProfileOwnership_profileNotMigrated() throws Exception { + getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0, + UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM); + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated), + getProfileOwnerPoliciesFile()); + DpmTestUtils.writeInputStreamToFile( + getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated), + getProfileOwnerFile()); + assertProfileOwnershipRevertedWithFakeTransferMetadata(); + } + + @Test public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception { getServices().addUser(CALLER_USER_HANDLE, 0, UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM); @@ -5666,6 +5863,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProfileOwnershipRevertedWithFakeTransferMetadata(); } + @Test public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception { setupProfileOwner(); configureContextForAccess(mContext, false); @@ -5674,6 +5872,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin2)); } + @Test public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception { setupProfileOwner(); configureContextForAccess(mContext, false); @@ -5682,6 +5881,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1)); } + @Test public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception { setupProfileOwner(); @@ -5700,6 +5900,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(UserHandle.SYSTEM); } + @Test public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception { setupProfileOwner(); @@ -5719,6 +5920,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } } + @Test public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller() throws Exception { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -5741,6 +5943,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpms.getCallerIdentity(admin2))); } + @Test public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller() throws Exception { configureContextForAccess(mContext, false); @@ -5781,6 +5984,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } } + @Test public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception { setupProfileOwner(); markDelegatedCertInstallerAsInstalled(); @@ -5800,6 +6004,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpms.getCallerIdentity(null, DpmMockContext.DELEGATE_PACKAGE_NAME))); } + @Test public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions() throws Exception { setupProfileOwner(); @@ -5821,6 +6026,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { }); } + @Test public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() { mContext.binder.callingUid = DpmMockContext.CALLER_UID; when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn( @@ -5830,9 +6036,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { parentDpm.getPasswordComplexity(); - assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity()); + assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE); } + @Test public void testGetPasswordComplexity_illegalStateExceptionIfLocked() { mContext.binder.callingUid = DpmMockContext.CALLER_UID; when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn( @@ -5841,6 +6048,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity()); } + @Test public void testGetPasswordComplexity_securityExceptionWithoutPermissions() { mContext.binder.callingUid = DpmMockContext.CALLER_UID; when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn( @@ -5850,6 +6058,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } + @Test public void testGetPasswordComplexity_currentUserNoPassword() { mContext.binder.callingUid = DpmMockContext.CALLER_UID; when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn( @@ -5859,9 +6068,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { when(getServices().userManager.getCredentialOwnerProfile(CALLER_USER_HANDLE)) .thenReturn(CALLER_USER_HANDLE); - assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity()); + assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_NONE); } + @Test public void testGetPasswordComplexity_currentUserHasPassword() { mContext.binder.callingUid = DpmMockContext.CALLER_UID; when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn( @@ -5874,9 +6084,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { .getUserPasswordMetrics(CALLER_USER_HANDLE)) .thenReturn(computeForPassword("asdf".getBytes())); - assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity()); + assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_MEDIUM); } + @Test public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() { mContext.binder.callingUid = DpmMockContext.CALLER_UID; when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn( @@ -5896,23 +6107,25 @@ public class DevicePolicyManagerTest extends DpmTestBase { .getUserPasswordMetrics(parentUser.id)) .thenReturn(computeForPassword("parentUser".getBytes())); - assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity()); + assertThat(dpm.getPasswordComplexity()).isEqualTo(PASSWORD_COMPLEXITY_HIGH); } + @Test public void testCrossProfileCalendarPackages_initiallyEmpty() { setAsProfileOwner(admin1); final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1); assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet()); } + @Test public void testCrossProfileCalendarPackages_reopenDpms() { setAsProfileOwner(admin1); dpm.setCrossProfileCalendarPackages(admin1, null); Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1); - assertTrue(packages == null); + assertThat(packages == null).isTrue(); initializeDpms(); packages = dpm.getCrossProfileCalendarPackages(admin1); - assertTrue(packages == null); + assertThat(packages == null).isTrue(); dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet()); packages = dpm.getCrossProfileCalendarPackages(admin1); @@ -5932,21 +6145,22 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) { - assertTrue(expected != null); - assertTrue(actual != null); - assertTrue(expected.containsAll(actual)); - assertTrue(actual.containsAll(expected)); + assertThat(expected).isNotNull(); + assertThat(actual).isNotNull(); + assertThat(actual).containsExactlyElementsIn(expected); } + @Test public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() { setAsProfileOwner(admin1); dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet()); when(getServices().settings.settingsSecureGetIntForUser( Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, CALLER_USER_HANDLE)).thenReturn(1); - assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE")); + assertThat(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE")).isFalse(); } + @Test public void testIsPackageAllowedToAccessCalendar_settingOff() { final String testPackage = "TEST_PACKAGE"; setAsProfileOwner(admin1); @@ -5954,9 +6168,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { when(getServices().settings.settingsSecureGetIntForUser( Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, CALLER_USER_HANDLE)).thenReturn(0); - assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage)); + assertThat(dpm.isPackageAllowedToAccessCalendar(testPackage)).isFalse(); } + @Test public void testIsPackageAllowedToAccessCalendar_bothAllowed() { final String testPackage = "TEST_PACKAGE"; setAsProfileOwner(admin1); @@ -5964,9 +6179,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { when(getServices().settings.settingsSecureGetIntForUser( Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, CALLER_USER_HANDLE)).thenReturn(1); - assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage)); + assertThat(dpm.isPackageAllowedToAccessCalendar(testPackage)).isTrue(); } + @Test public void testSetUserControlDisabledPackages_asDO() throws Exception { final List<String> testPackages = new ArrayList<>(); testPackages.add("package_1"); @@ -5979,9 +6195,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { verify(getServices().packageManagerInternal).setDeviceOwnerProtectedPackages(testPackages); - assertEquals(testPackages, dpm.getUserControlDisabledPackages(admin1)); + assertThat(dpm.getUserControlDisabledPackages(admin1)).isEqualTo(testPackages); } + @Test public void testSetUserControlDisabledPackages_failingAsPO() throws Exception { final List<String> testPackages = new ArrayList<>(); testPackages.add("package_1"); @@ -6008,28 +6225,32 @@ public class DevicePolicyManagerTest extends DpmTestBase { mServiceContext.binder.restoreCallingIdentity(ident); } + @Test public void testGetCrossProfilePackages_notSet_returnsEmpty() { setAsProfileOwner(admin1); - assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty()); + assertThat(dpm.getCrossProfilePackages(admin1).isEmpty()).isTrue(); } + @Test public void testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() { setAsProfileOwner(admin1); initializeDpms(); - assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty()); + assertThat(dpm.getCrossProfilePackages(admin1).isEmpty()).isTrue(); } + @Test public void testGetCrossProfilePackages_whenSet_returnsEqual() { setAsProfileOwner(admin1); Set<String> packages = Collections.singleton("TEST_PACKAGE"); dpm.setCrossProfilePackages(admin1, packages); - assertEquals(packages, dpm.getCrossProfilePackages(admin1)); + assertThat(dpm.getCrossProfilePackages(admin1)).isEqualTo(packages); } + @Test public void testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual() { setAsProfileOwner(admin1); Set<String> packages = Collections.singleton("TEST_PACKAGE"); @@ -6037,9 +6258,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setCrossProfilePackages(admin1, packages); initializeDpms(); - assertEquals(packages, dpm.getCrossProfilePackages(admin1)); + assertThat(dpm.getCrossProfilePackages(admin1)).isEqualTo(packages); } + @Test public void testGetAllCrossProfilePackages_notSet_returnsEmpty() throws Exception { addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1); mContext.packageName = admin1.getPackageName(); @@ -6047,9 +6269,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { setCrossProfileAppsList(); setVendorCrossProfileAppsList(); - assertTrue(dpm.getAllCrossProfilePackages().isEmpty()); + assertThat(dpm.getAllCrossProfilePackages().isEmpty()).isTrue(); } + @Test public void testGetAllCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() throws Exception { addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1); @@ -6059,9 +6282,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { setVendorCrossProfileAppsList(); initializeDpms(); - assertTrue(dpm.getAllCrossProfilePackages().isEmpty()); + assertThat(dpm.getAllCrossProfilePackages().isEmpty()).isTrue(); } + @Test public void testGetAllCrossProfilePackages_whenSet_returnsCombinedSet() throws Exception { addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1); final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE"); @@ -6071,13 +6295,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE"); setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE"); - assertEquals(Sets.newSet( - "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", - "TEST_VENDOR_DEFAULT_PACKAGE"), - dpm.getAllCrossProfilePackages()); - + assertThat(dpm.getAllCrossProfilePackages()).containsExactly( + "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", + "TEST_VENDOR_DEFAULT_PACKAGE"); } + @Test public void testGetAllCrossProfilePackages_whenSet_dpmsReinitialized_returnsCombinedSet() throws Exception { addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1); @@ -6089,12 +6312,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE"); initializeDpms(); - assertEquals(Sets.newSet( + assertThat(dpm.getAllCrossProfilePackages()).containsExactly( "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", - "TEST_VENDOR_DEFAULT_PACKAGE"), - dpm.getAllCrossProfilePackages()); + "TEST_VENDOR_DEFAULT_PACKAGE"); } + @Test public void testGetDefaultCrossProfilePackages_noPackagesSet_returnsEmpty() { setCrossProfileAppsList(); setVendorCrossProfileAppsList(); @@ -6102,27 +6325,29 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertThat(dpm.getDefaultCrossProfilePackages()).isEmpty(); } + @Test public void testGetDefaultCrossProfilePackages_packagesSet_returnsCombinedSet() { setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE"); setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE"); - assertThat(dpm.getDefaultCrossProfilePackages()).isEqualTo(Sets.newSet( - "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", "TEST_VENDOR_DEFAULT_PACKAGE" - )); + assertThat(dpm.getDefaultCrossProfilePackages()).containsExactly( + "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", "TEST_VENDOR_DEFAULT_PACKAGE"); } + @Test public void testSetCommonCriteriaMode_asDeviceOwner() throws Exception { setDeviceOwner(); - assertFalse(dpm.isCommonCriteriaModeEnabled(admin1)); - assertFalse(dpm.isCommonCriteriaModeEnabled(null)); + assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isFalse(); + assertThat(dpm.isCommonCriteriaModeEnabled(null)).isFalse(); dpm.setCommonCriteriaModeEnabled(admin1, true); - assertTrue(dpm.isCommonCriteriaModeEnabled(admin1)); - assertTrue(dpm.isCommonCriteriaModeEnabled(null)); + assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isTrue(); + assertThat(dpm.isCommonCriteriaModeEnabled(null)).isTrue(); } + @Test public void testSetCommonCriteriaMode_asPoOfOrgOwnedDevice() throws Exception { final int managedProfileUserId = 15; final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436); @@ -6130,15 +6355,16 @@ public class DevicePolicyManagerTest extends DpmTestBase { configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId); mContext.binder.callingUid = managedProfileAdminUid; - assertFalse(dpm.isCommonCriteriaModeEnabled(admin1)); - assertFalse(dpm.isCommonCriteriaModeEnabled(null)); + assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isFalse(); + assertThat(dpm.isCommonCriteriaModeEnabled(null)).isFalse(); dpm.setCommonCriteriaModeEnabled(admin1, true); - assertTrue(dpm.isCommonCriteriaModeEnabled(admin1)); - assertTrue(dpm.isCommonCriteriaModeEnabled(null)); + assertThat(dpm.isCommonCriteriaModeEnabled(admin1)).isTrue(); + assertThat(dpm.isCommonCriteriaModeEnabled(null)).isTrue(); } + @Test public void testCanProfileOwnerResetPasswordWhenLocked_nonDirectBootAwarePo() throws Exception { setDeviceEncryptionPerUser(); @@ -6146,30 +6372,33 @@ public class DevicePolicyManagerTest extends DpmTestBase { setupPasswordResetToken(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertFalse("po is not direct boot aware", - dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)); + assertWithMessage("po is not direct boot aware") + .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isFalse(); } + @Test public void testCanProfileOwnerResetPasswordWhenLocked_noActiveToken() throws Exception { setDeviceEncryptionPerUser(); setupProfileOwner(); makeAdmin1DirectBootAware(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertFalse("po doesn't have an active password reset token", - dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)); + assertWithMessage("po doesn't have an active password reset token") + .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isFalse(); } + @Test public void testCanProfileOwnerResetPasswordWhenLocked_nonFbeDevice() throws Exception { setupProfileOwner(); makeAdmin1DirectBootAware(); setupPasswordResetToken(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertFalse("device is not FBE", - dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)); + assertWithMessage("device is not FBE") + .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isFalse(); } + @Test public void testCanProfileOwnerResetPasswordWhenLocked() throws Exception { setDeviceEncryptionPerUser(); setupProfileOwner(); @@ -6177,8 +6406,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { setupPasswordResetToken(); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - assertTrue("direct boot aware po with active password reset token", - dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)); + assertWithMessage("direct boot aware po with active password reset token") + .that(dpm.canProfileOwnerResetPasswordWhenLocked(CALLER_USER_HANDLE)).isTrue(); } private void setupPasswordResetToken() { @@ -6196,7 +6425,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { .isEscrowTokenActive(eq(handle), eq(CALLER_USER_HANDLE))) .thenReturn(true); - assertTrue("failed to activate token", dpm.isResetPasswordTokenActive(admin1)); + assertWithMessage("failed to activate token").that(dpm.isResetPasswordTokenActive(admin1)) + .isTrue(); } private void makeAdmin1DirectBootAware() @@ -6231,6 +6461,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { .thenReturn(packages); } + @Test public void testSetAccountTypesWithManagementDisabledOnManagedProfile() throws Exception { setupProfileOwner(); @@ -6249,6 +6480,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty(); } + @Test public void testSetAccountTypesWithManagementDisabledOnOrgOwnedManagedProfile() throws Exception { final int managedProfileUserId = 15; @@ -6284,6 +6516,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * Tests the case when the user doesn't turn the profile on in time, verifies that the user is * warned with a notification and then the apps get suspended. */ + @Test public void testMaximumProfileTimeOff_profileOffTimeExceeded() throws Exception { prepareMocksForSetMaximumProfileTimeOff(); @@ -6346,6 +6579,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /** * Tests the case when the user turns the profile back on long before the deadline (> 1 day). */ + @Test public void testMaximumProfileTimeOff_turnOnBeforeWarning() throws Exception { prepareMocksForSetMaximumProfileTimeOff(); @@ -6366,6 +6600,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /** * Tests the case when the user turns the profile back on after the warning notification. */ + @Test public void testMaximumProfileTimeOff_turnOnAfterWarning() throws Exception { prepareMocksForSetMaximumProfileTimeOff(); @@ -6395,6 +6630,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { /** * Tests the case when the user turns the profile back on when the apps are already suspended. */ + @Test public void testMaximumProfileTimeOff_turnOnAfterDeadline() throws Exception { prepareMocksForSetMaximumProfileTimeOff(); @@ -6482,7 +6718,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private static Matcher<Notification> hasExtra(String... extras) { - assertEquals("Odd number of extra key-values", 0, extras.length % 2); + assertWithMessage("Odd number of extra key-values").that(extras.length % 2).isEqualTo(0); return new BaseMatcher<Notification>() { @Override public boolean matches(Object item) { @@ -6520,17 +6756,17 @@ public class DevicePolicyManagerTest extends DpmTestBase { // To simulate a reboot, we just reinitialize dpms and call systemReady initializeDpms(); - assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); - assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName())); - assertFalse(dpm.isAdminActive(adminAnotherPackage)); - assertTrue(dpm.isAdminActive(admin1)); - assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser()); + assertThat(dpm.isDeviceOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName())).isFalse(); + assertThat(dpm.isAdminActive(adminAnotherPackage)).isFalse(); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnCallingUser()).isEqualTo(admin1); - assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())); - assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); - assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId()); - assertFalse(getMockTransferMetadataManager().metadataFileExists()); + assertThat(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName())).isTrue(); + assertThat(dpm.getDeviceOwnerComponentOnAnyUser()).isEqualTo(admin1); + assertThat(dpm.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); + assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse(); mServiceContext.binder.restoreCallingIdentity(ident); } @@ -6547,12 +6783,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { // To simulate a reboot, we just reinitialize dpms and call systemReady initializeDpms(); - assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName())); - assertTrue(dpm.isAdminActive(admin1)); - assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName())); - assertFalse(dpm.isAdminActive(adminAnotherPackage)); - assertEquals(dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE), admin1); - assertFalse(getMockTransferMetadataManager().metadataFileExists()); + assertThat(dpm.isProfileOwnerApp(admin1.getPackageName())).isTrue(); + assertThat(dpm.isAdminActive(admin1)).isTrue(); + assertThat(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName())).isFalse(); + assertThat(dpm.isAdminActive(adminAnotherPackage)).isFalse(); + assertThat(admin1).isEqualTo(dpm.getProfileOwnerAsUser(CALLER_USER_HANDLE)); + assertThat(getMockTransferMetadataManager().metadataFileExists()).isFalse(); } private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) { @@ -6597,8 +6833,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void assertProvisioningAllowed(String action, boolean expected) { - assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected, - dpm.isProvisioningAllowed(action)); + assertWithMessage("isProvisioningAllowed(%s) returning unexpected result", action) + .that(dpm.isProvisioningAllowed(action)).isEqualTo(expected); } private void assertProvisioningAllowed(String action, boolean expected, String packageName, @@ -6622,9 +6858,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void assertCheckProvisioningPreCondition( String action, String packageName, int provisioningCondition) { - assertEquals("checkProvisioningPreCondition(" - + action + ", " + packageName + ") returning unexpected result", - provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName)); + assertWithMessage("checkProvisioningPreCondition(%s, %s) returning unexpected result", + action, packageName).that(dpm.checkProvisioningPreCondition(action, packageName)) + .isEqualTo(provisioningCondition); } /** @@ -6642,7 +6878,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin); dpm.setActiveAdmin(admin, false, userId); - assertTrue(dpm.setProfileOwner(admin, null, userId)); + assertThat(dpm.setProfileOwner(admin, null, userId)).isTrue(); mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS); } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DpmTestBase.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DpmTestBase.java index 41d54e9010d3..81570a10fc13 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DpmTestBase.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DpmTestBase.java @@ -16,6 +16,8 @@ package com.android.server.devicepolicy; +import static com.google.common.truth.Truth.assertThat; + import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -35,18 +37,28 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.UserHandle; -import android.test.AndroidTestCase; + +import androidx.test.InstrumentationRegistry; + +import org.junit.Before; import java.io.InputStream; import java.util.List; -public abstract class DpmTestBase extends AndroidTestCase { +/** + * Temporary copy of DpmTestBase using JUnit 4 - once all tests extend it, it should be renamed + * back to DpmTestBase (with the temporary methods removed. + * + */ +public abstract class DpmTestBase { + public static final String TAG = "DpmTest"; - protected Context mRealTestContext; + protected final Context mRealTestContext = InstrumentationRegistry.getTargetContext(); protected DpmMockContext mMockContext; private MockSystemServices mServices; + // Attributes below are public so they don't need to be prefixed with m public ComponentName admin1; public ComponentName admin2; public ComponentName admin3; @@ -54,12 +66,8 @@ public abstract class DpmTestBase extends AndroidTestCase { public ComponentName adminNoPerm; public ComponentName delegateCertInstaller; - @Override - protected void setUp() throws Exception { - super.setUp(); - - mRealTestContext = super.getContext(); - + @Before + public void setFixtures() throws Exception { mServices = new MockSystemServices(mRealTestContext, "test-data"); mMockContext = new DpmMockContext(mServices, mRealTestContext); @@ -74,8 +82,7 @@ public abstract class DpmTestBase extends AndroidTestCase { mockSystemPropertiesToReturnDefault(); } - @Override - public DpmMockContext getContext() { + protected DpmMockContext getContext() { return mMockContext; } @@ -136,20 +143,15 @@ public abstract class DpmTestBase extends AndroidTestCase { final PackageInfo pi = DpmTestUtils.cloneParcelable( mRealTestContext.getPackageManager().getPackageInfo( mRealTestContext.getPackageName(), 0)); - assertTrue(pi.applicationInfo.flags != 0); + assertThat(pi.applicationInfo.flags).isNotEqualTo(0); if (ai != null) { pi.applicationInfo = ai; } - doReturn(pi).when(mServices.ipackageManager).getPackageInfo( - eq(packageName), - eq(0), - eq(userId)); + doReturn(pi).when(mServices.ipackageManager).getPackageInfo(packageName, 0, userId); - doReturn(ai.uid).when(mServices.packageManager).getPackageUidAsUser( - eq(packageName), - eq(userId)); + doReturn(ai.uid).when(mServices.packageManager).getPackageUidAsUser(packageName, userId); } protected void markDelegatedCertInstallerAsInstalled() throws Exception { @@ -230,8 +232,8 @@ public abstract class DpmTestBase extends AndroidTestCase { mRealTestContext.getPackageManager().queryBroadcastReceivers( resolveIntent, PackageManager.GET_META_DATA); - assertNotNull(realResolveInfo); - assertEquals(1, realResolveInfo.size()); + assertThat(realResolveInfo).isNotNull(); + assertThat(realResolveInfo).hasSize(1); // We need to change AI, so set a clone. realResolveInfo.set(0, DpmTestUtils.cloneParcelable(realResolveInfo.get(0))); diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/FactoryResetProtectionPolicyTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/FactoryResetProtectionPolicyTest.java index e8818a3f4940..3aa5a80d814f 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/FactoryResetProtectionPolicyTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/FactoryResetProtectionPolicyTest.java @@ -16,8 +16,8 @@ package com.android.server.devicepolicy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static com.google.common.truth.Truth.assertThat; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -100,7 +100,7 @@ public class FactoryResetProtectionPolicyTest { ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new InputStreamReader(inStream)); - assertEquals(XmlPullParser.START_TAG, parser.next()); + assertThat(parser.next()).isEqualTo(XmlPullParser.START_TAG); assertPoliciesAreEqual(policy, policy.readFromXml(parser)); } @@ -114,7 +114,7 @@ public class FactoryResetProtectionPolicyTest { parser.setInput(new InputStreamReader(inStream)); // If deserialization fails, then null is returned. - assertNull(policy.readFromXml(parser)); + assertThat(policy.readFromXml(parser)).isNull(); } private ByteArrayOutputStream serialize(FactoryResetProtectionPolicy policy) @@ -133,17 +133,17 @@ public class FactoryResetProtectionPolicyTest { private void assertPoliciesAreEqual(FactoryResetProtectionPolicy expectedPolicy, FactoryResetProtectionPolicy actualPolicy) { - assertEquals(expectedPolicy.isFactoryResetProtectionEnabled(), - actualPolicy.isFactoryResetProtectionEnabled()); + assertThat(actualPolicy.isFactoryResetProtectionEnabled()) + .isEqualTo(expectedPolicy.isFactoryResetProtectionEnabled()); assertAccountsAreEqual(expectedPolicy.getFactoryResetProtectionAccounts(), actualPolicy.getFactoryResetProtectionAccounts()); } private void assertAccountsAreEqual(List<String> expectedAccounts, List<String> actualAccounts) { - assertEquals(expectedAccounts.size(), actualAccounts.size()); + assertThat(actualAccounts.size()).isEqualTo(expectedAccounts.size()); for (int i = 0; i < expectedAccounts.size(); i++) { - assertEquals(expectedAccounts.get(i), actualAccounts.get(i)); + assertThat(actualAccounts.get(i)).isEqualTo(expectedAccounts.get(i)); } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/NetworkEventTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/NetworkEventTest.java index c698312eedec..7506dd45ad82 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/NetworkEventTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/NetworkEventTest.java @@ -17,6 +17,9 @@ package com.android.server.devicepolicy; import static com.android.server.devicepolicy.NetworkLoggingHandler.LOG_NETWORK_EVENT_MSG; +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.doNothing; import static org.mockito.Mockito.spy; @@ -37,8 +40,9 @@ import android.os.test.TestLooper; import android.test.suitebuilder.annotation.SmallTest; import com.android.server.LocalServices; -import com.android.server.SystemService; +import org.junit.Before; +import org.junit.Test; import org.mockito.ArgumentCaptor; import java.util.List; @@ -50,9 +54,8 @@ public class NetworkEventTest extends DpmTestBase { private DpmMockContext mSpiedDpmMockContext; private DevicePolicyManagerServiceTestable mDpmTestable; - @Override - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { mSpiedDpmMockContext = spy(mMockContext); mSpiedDpmMockContext.callerPermissions.add( android.Manifest.permission.MANAGE_DEVICE_ADMINS); @@ -64,6 +67,7 @@ public class NetworkEventTest extends DpmTestBase { mDpmTestable.setActiveAdmin(admin1, true, DpmMockContext.CALLER_USER_HANDLE); } + @Test public void testNetworkEventId_monotonicallyIncreasing() throws Exception { // GIVEN the handler has not processed any events. long startingId = 0; @@ -72,17 +76,20 @@ public class NetworkEventTest extends DpmTestBase { List<NetworkEvent> events = fillHandlerWithFullBatchOfEvents(startingId); // THEN the events are in a batch. - assertTrue("Batch not at the returned token.", - events != null && events.size() == MAX_EVENTS_PER_BATCH); + assertWithMessage("Batch not at the returned token.").that(events).isNotNull(); + assertWithMessage("Batch not at the returned token.").that(events) + .hasSize(MAX_EVENTS_PER_BATCH); + // THEN event ids are monotonically increasing. long expectedId = startingId; for (int i = 0; i < MAX_EVENTS_PER_BATCH; i++) { - assertEquals("At index " + i + ", the event has the wrong id.", expectedId, - events.get(i).getId()); + assertWithMessage("At index %s, the event has the wrong id.", i) + .that(events.get(i).getId()).isEqualTo(expectedId); expectedId++; } } + @Test public void testNetworkEventId_wrapsAround() throws Exception { // GIVEN the handler has almost processed Long.MAX_VALUE events. int gap = 5; @@ -92,24 +99,25 @@ public class NetworkEventTest extends DpmTestBase { List<NetworkEvent> events = fillHandlerWithFullBatchOfEvents(startingId); // THEN the events are in a batch. - assertTrue("Batch not at the returned token.", - events != null && events.size() == MAX_EVENTS_PER_BATCH); + assertWithMessage("Batch not at the returned token.").that(events).isNotNull(); + assertWithMessage("Batch not at the returned token.").that(events) + .hasSize(MAX_EVENTS_PER_BATCH); // THEN event ids are monotonically increasing. long expectedId = startingId; for (int i = 0; i < gap; i++) { - assertEquals("At index " + i + ", the event has the wrong id.", expectedId, - events.get(i).getId()); + assertWithMessage("At index %s, the event has the wrong id.", i) + .that(events.get(i).getId()).isEqualTo(expectedId); expectedId++; } // THEN event ids are reset when the id reaches the maximum possible value. - assertEquals("Event was not assigned the maximum id value.", Long.MAX_VALUE, - events.get(gap).getId()); - assertEquals("Event id was not reset.", 0, events.get(gap + 1).getId()); + assertWithMessage("Event was not assigned the maximum id value.") + .that(events.get(gap).getId()).isEqualTo(Long.MAX_VALUE); + assertWithMessage("Event id was not reset.").that(events.get(gap + 1).getId()).isEqualTo(0); // THEN event ids are monotonically increasing. expectedId = 0; for (int i = gap + 1; i < MAX_EVENTS_PER_BATCH; i++) { - assertEquals("At index " + i + ", the event has the wrong id.", expectedId, - events.get(i).getId()); + assertWithMessage("At index %s, the event has the wrong id.", i) + .that(events.get(i).getId()).isEqualTo(expectedId); expectedId++; } } @@ -134,8 +142,8 @@ public class NetworkEventTest extends DpmTestBase { ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(mSpiedDpmMockContext).sendBroadcastAsUser(intentCaptor.capture(), any(UserHandle.class)); - assertEquals(intentCaptor.getValue().getAction(), - DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE); + assertThat(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE) + .isEqualTo(intentCaptor.getValue().getAction()); long token = intentCaptor.getValue().getExtras().getLong( DeviceAdminReceiver.EXTRA_NETWORK_LOGS_TOKEN, 0); return handler.retrieveFullLogBatch(token); @@ -144,6 +152,7 @@ public class NetworkEventTest extends DpmTestBase { /** * Test parceling and unparceling of a ConnectEvent. */ + @Test public void testConnectEventParceling() { ConnectEvent event = new ConnectEvent("127.0.0.1", 80, "com.android.whateverdude", 100000); event.setId(5L); @@ -152,16 +161,17 @@ public class NetworkEventTest extends DpmTestBase { p.setDataPosition(0); ConnectEvent unparceledEvent = p.readParcelable(NetworkEventTest.class.getClassLoader()); p.recycle(); - assertEquals(event.getInetAddress(), unparceledEvent.getInetAddress()); - assertEquals(event.getPort(), unparceledEvent.getPort()); - assertEquals(event.getPackageName(), unparceledEvent.getPackageName()); - assertEquals(event.getTimestamp(), unparceledEvent.getTimestamp()); - assertEquals(event.getId(), unparceledEvent.getId()); + assertThat(unparceledEvent.getInetAddress()).isEqualTo(event.getInetAddress()); + assertThat(unparceledEvent.getPort()).isEqualTo(event.getPort()); + assertThat(unparceledEvent.getPackageName()).isEqualTo(event.getPackageName()); + assertThat(unparceledEvent.getTimestamp()).isEqualTo(event.getTimestamp()); + assertThat(unparceledEvent.getId()).isEqualTo(event.getId()); } /** * Test parceling and unparceling of a DnsEvent. */ + @Test public void testDnsEventParceling() { DnsEvent event = new DnsEvent("d.android.com", new String[]{"192.168.0.1", "127.0.0.1"}, 2, "com.android.whateverdude", 100000); @@ -171,13 +181,15 @@ public class NetworkEventTest extends DpmTestBase { p.setDataPosition(0); DnsEvent unparceledEvent = p.readParcelable(NetworkEventTest.class.getClassLoader()); p.recycle(); - assertEquals(event.getHostname(), unparceledEvent.getHostname()); - assertEquals(event.getInetAddresses().get(0), unparceledEvent.getInetAddresses().get(0)); - assertEquals(event.getInetAddresses().get(1), unparceledEvent.getInetAddresses().get(1)); - assertEquals(event.getTotalResolvedAddressCount(), - unparceledEvent.getTotalResolvedAddressCount()); - assertEquals(event.getPackageName(), unparceledEvent.getPackageName()); - assertEquals(event.getTimestamp(), unparceledEvent.getTimestamp()); - assertEquals(event.getId(), unparceledEvent.getId()); + assertThat(unparceledEvent.getHostname()).isEqualTo(event.getHostname()); + assertThat(unparceledEvent.getInetAddresses().get(0)) + .isEqualTo(event.getInetAddresses().get(0)); + assertThat(unparceledEvent.getInetAddresses().get(1)) + .isEqualTo(event.getInetAddresses().get(1)); + assertThat(unparceledEvent.getTotalResolvedAddressCount()) + .isEqualTo(event.getTotalResolvedAddressCount()); + assertThat(unparceledEvent.getPackageName()).isEqualTo(event.getPackageName()); + assertThat(unparceledEvent.getTimestamp()).isEqualTo(event.getTimestamp()); + assertThat(unparceledEvent.getId()).isEqualTo(event.getId()); } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/OverlayPackagesProviderTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/OverlayPackagesProviderTest.java index a3cc915b3eba..24e226a64917 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/OverlayPackagesProviderTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/OverlayPackagesProviderTest.java @@ -20,6 +20,9 @@ import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEV import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE; import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; @@ -32,16 +35,17 @@ import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.res.Resources; -import android.test.AndroidTestCase; import android.test.mock.MockPackageManager; import android.view.inputmethod.InputMethodInfo; import androidx.test.InstrumentationRegistry; +import androidx.test.runner.AndroidJUnit4; import com.android.internal.R; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -51,18 +55,23 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -public class OverlayPackagesProviderTest extends AndroidTestCase { +/** + * Run this test with: + * + * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.OwnersTest} + * + */ +@RunWith(AndroidJUnit4.class) +public class OverlayPackagesProviderTest { private static final String TEST_DPC_PACKAGE_NAME = "dpc.package.name"; private static final ComponentName TEST_MDM_COMPONENT_NAME = new ComponentName( TEST_DPC_PACKAGE_NAME, "pc.package.name.DeviceAdmin"); private static final int TEST_USER_ID = 123; - private @Mock - Resources mResources; - @Mock - private OverlayPackagesProvider.Injector mInjector; - private @Mock - Context mTestContext; + private @Mock Resources mResources; + + private @Mock OverlayPackagesProvider.Injector mInjector; + private @Mock Context mTestContext; private Resources mRealResources; private FakePackageManager mPackageManager; @@ -256,12 +265,12 @@ public class OverlayPackagesProviderTest extends AndroidTestCase { ArrayList<String> required = getStringArrayInRealResources(requiredId); ArrayList<String> disallowed = getStringArrayInRealResources(disallowedId); required.retainAll(disallowed); - assertTrue(required.isEmpty()); + assertThat(required.isEmpty()).isTrue(); } private void verifyAppsAreNonRequired(String action, String... appArray) { - assertEquals(setFromArray(appArray), - mHelper.getNonRequiredApps(TEST_MDM_COMPONENT_NAME, TEST_USER_ID, action)); + assertThat(mHelper.getNonRequiredApps(TEST_MDM_COMPONENT_NAME, TEST_USER_ID, action)) + .containsExactlyElementsIn(setFromArray(appArray)); } private void setRequiredAppsManagedDevice(String... apps) { @@ -348,19 +357,19 @@ public class OverlayPackagesProviderTest extends AndroidTestCase { class FakePackageManager extends MockPackageManager { @Override public List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent, int flags, int userId) { - assertTrue("Expected an intent with action ACTION_MAIN", - Intent.ACTION_MAIN.equals(intent.getAction())); - assertEquals("Expected an intent with category CATEGORY_LAUNCHER", - setFromArray(Intent.CATEGORY_LAUNCHER), intent.getCategories()); - assertTrue("Expected the flag MATCH_UNINSTALLED_PACKAGES", - (flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0); - assertTrue("Expected the flag MATCH_DISABLED_COMPONENTS", - (flags & PackageManager.MATCH_DISABLED_COMPONENTS) != 0); - assertTrue("Expected the flag MATCH_DIRECT_BOOT_AWARE", - (flags & PackageManager.MATCH_DIRECT_BOOT_AWARE) != 0); - assertTrue("Expected the flag MATCH_DIRECT_BOOT_UNAWARE", - (flags & PackageManager.MATCH_DIRECT_BOOT_UNAWARE) != 0); - assertEquals(userId, TEST_USER_ID); + assertWithMessage("Expected an intent with action ACTION_MAIN") + .that(Intent.ACTION_MAIN.equals(intent.getAction())).isTrue(); + assertWithMessage("Expected an intent with category CATEGORY_LAUNCHER") + .that(intent.getCategories()).containsExactly(Intent.CATEGORY_LAUNCHER); + assertWithMessage("Expected the flag MATCH_UNINSTALLED_PACKAGES") + .that((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES)).isNotEqualTo(0); + assertWithMessage("Expected the flag MATCH_DISABLED_COMPONENTS") + .that((flags & PackageManager.MATCH_DISABLED_COMPONENTS)).isNotEqualTo(0); + assertWithMessage("Expected the flag MATCH_DIRECT_BOOT_AWARE") + .that((flags & PackageManager.MATCH_DIRECT_BOOT_AWARE)).isNotEqualTo(0); + assertWithMessage("Expected the flag MATCH_DIRECT_BOOT_UNAWARE") + .that((flags & PackageManager.MATCH_DIRECT_BOOT_UNAWARE)).isNotEqualTo(0); + assertThat(TEST_USER_ID).isEqualTo(userId); List<ResolveInfo> result = new ArrayList<>(); if (mSystemAppsWithLauncher == null) { return result; diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java index 5899bb0e94fe..bfe183cc608b 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java @@ -16,25 +16,32 @@ package com.android.server.devicepolicy; +import static com.google.common.truth.Truth.assertThat; + import android.content.ComponentName; import android.os.UserHandle; import android.test.suitebuilder.annotation.SmallTest; +import androidx.test.runner.AndroidJUnit4; + import com.android.server.devicepolicy.DevicePolicyManagerServiceTestable.OwnersTestable; +import org.junit.Test; +import org.junit.runner.RunWith; + /** * Tests for the DeviceOwner object that saves & loads device and policy owner information. - * run this test with: - m FrameworksServicesTests && - adb install \ - -r out/target/product/hammerhead/data/app/FrameworksServicesTests/FrameworksServicesTests.apk && - adb shell am instrument -e class com.android.server.devicepolicy.OwnersTest \ - -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner - - (mmma frameworks/base/services/tests/servicestests/ for non-ninja build) + * + * <p>Run this test with: + * + * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.OwnersTest} + * */ @SmallTest +@RunWith(AndroidJUnit4.class) public class OwnersTest extends DpmTestBase { + + @Test public void testUpgrade01() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -48,26 +55,26 @@ public class OwnersTest extends DpmTestBase { owners.load(); // The legacy file should be removed. - assertFalse(owners.getLegacyConfigFile().exists()); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); // File was empty, so no new files should be created. - assertFalse(owners.getDeviceOwnerFile().exists()); - - assertFalse(owners.getProfileOwnerFile(10).exists()); - assertFalse(owners.getProfileOwnerFile(11).exists()); - assertFalse(owners.getProfileOwnerFile(20).exists()); - assertFalse(owners.getProfileOwnerFile(21).exists()); - - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); - assertNull(owners.getSystemUpdatePolicy()); - assertEquals(0, owners.getProfileOwnerKeys().size()); - - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerFile().exists()).isFalse(); + + assertThat(owners.getProfileOwnerFile(10).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(11).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(20).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(21).exists()).isFalse(); + + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); + + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } // Then re-read and check. @@ -75,19 +82,20 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); - assertNull(owners.getSystemUpdatePolicy()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } } + @Test public void testUpgrade02() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -101,28 +109,28 @@ public class OwnersTest extends DpmTestBase { owners.load(); // The legacy file should be removed. - assertFalse(owners.getLegacyConfigFile().exists()); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); - assertTrue(owners.getDeviceOwnerFile().exists()); // TODO Check content + assertThat(owners.getDeviceOwnerFile().exists()).isTrue(); // TODO Check content - assertFalse(owners.getProfileOwnerFile(10).exists()); - assertFalse(owners.getProfileOwnerFile(11).exists()); - assertFalse(owners.getProfileOwnerFile(20).exists()); - assertFalse(owners.getProfileOwnerFile(21).exists()); + assertThat(owners.getProfileOwnerFile(10).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(11).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(20).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(21).exists()).isFalse(); - assertTrue(owners.hasDeviceOwner()); - assertEquals(null, owners.getDeviceOwnerName()); - assertEquals("com.google.android.testdpc", owners.getDeviceOwnerPackageName()); - assertEquals(UserHandle.USER_SYSTEM, owners.getDeviceOwnerUserId()); + assertThat(owners.hasDeviceOwner()).isTrue(); + assertThat(owners.getDeviceOwnerName()).isEqualTo(null); + assertThat(owners.getDeviceOwnerPackageName()).isEqualTo("com.google.android.testdpc"); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); - assertNull(owners.getSystemUpdatePolicy()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertTrue(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } // Then re-read and check. @@ -130,22 +138,23 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertTrue(owners.hasDeviceOwner()); - assertEquals(null, owners.getDeviceOwnerName()); - assertEquals("com.google.android.testdpc", owners.getDeviceOwnerPackageName()); - assertEquals(UserHandle.USER_SYSTEM, owners.getDeviceOwnerUserId()); + assertThat(owners.hasDeviceOwner()).isTrue(); + assertThat(owners.getDeviceOwnerName()).isEqualTo(null); + assertThat(owners.getDeviceOwnerPackageName()).isEqualTo("com.google.android.testdpc"); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); - assertNull(owners.getSystemUpdatePolicy()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertTrue(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } } + @Test public void testUpgrade03() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -159,36 +168,36 @@ public class OwnersTest extends DpmTestBase { owners.load(); // The legacy file should be removed. - assertFalse(owners.getLegacyConfigFile().exists()); - - assertFalse(owners.getDeviceOwnerFile().exists()); - - assertTrue(owners.getProfileOwnerFile(10).exists()); - assertTrue(owners.getProfileOwnerFile(11).exists()); - assertFalse(owners.getProfileOwnerFile(20).exists()); - assertFalse(owners.getProfileOwnerFile(21).exists()); - - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); - assertNull(owners.getSystemUpdatePolicy()); - - assertEquals(2, owners.getProfileOwnerKeys().size()); - assertEquals(new ComponentName("com.google.android.testdpc", - "com.google.android.testdpc.DeviceAdminReceiver0"), - owners.getProfileOwnerComponent(10)); - assertEquals("0", owners.getProfileOwnerName(10)); - assertEquals("com.google.android.testdpc", owners.getProfileOwnerPackage(10)); - - assertEquals(new ComponentName("com.google.android.testdpc1", ""), - owners.getProfileOwnerComponent(11)); - assertEquals("1", owners.getProfileOwnerName(11)); - assertEquals("com.google.android.testdpc1", owners.getProfileOwnerPackage(11)); - - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); + + assertThat(owners.getDeviceOwnerFile().exists()).isFalse(); + + assertThat(owners.getProfileOwnerFile(10).exists()).isTrue(); + assertThat(owners.getProfileOwnerFile(11).exists()).isTrue(); + assertThat(owners.getProfileOwnerFile(20).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(21).exists()).isFalse(); + + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + + assertThat(owners.getProfileOwnerKeys()).hasSize(2); + assertThat(owners.getProfileOwnerComponent(10)) + .isEqualTo(new ComponentName("com.google.android.testdpc", + "com.google.android.testdpc.DeviceAdminReceiver0")); + assertThat(owners.getProfileOwnerName(10)).isEqualTo("0"); + assertThat(owners.getProfileOwnerPackage(10)).isEqualTo("com.google.android.testdpc"); + + assertThat(owners.getProfileOwnerComponent(11)) + .isEqualTo(new ComponentName("com.google.android.testdpc1", "")); + assertThat(owners.getProfileOwnerName(11)).isEqualTo("1"); + assertThat(owners.getProfileOwnerPackage(11)).isEqualTo("com.google.android.testdpc1"); + + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } // Then re-read and check. @@ -196,27 +205,27 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); - assertNull(owners.getSystemUpdatePolicy()); - - assertEquals(2, owners.getProfileOwnerKeys().size()); - assertEquals(new ComponentName("com.google.android.testdpc", - "com.google.android.testdpc.DeviceAdminReceiver0"), - owners.getProfileOwnerComponent(10)); - assertEquals("0", owners.getProfileOwnerName(10)); - assertEquals("com.google.android.testdpc", owners.getProfileOwnerPackage(10)); - - assertEquals(new ComponentName("com.google.android.testdpc1", ""), - owners.getProfileOwnerComponent(11)); - assertEquals("1", owners.getProfileOwnerName(11)); - assertEquals("com.google.android.testdpc1", owners.getProfileOwnerPackage(11)); - - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + + assertThat(owners.getProfileOwnerKeys()).hasSize(2); + assertThat(owners.getProfileOwnerComponent(10)) + .isEqualTo(new ComponentName("com.google.android.testdpc", + "com.google.android.testdpc.DeviceAdminReceiver0")); + assertThat(owners.getProfileOwnerName(10)).isEqualTo("0"); + assertThat(owners.getProfileOwnerPackage(10)).isEqualTo("com.google.android.testdpc"); + + assertThat(owners.getProfileOwnerComponent(11)) + .isEqualTo(new ComponentName("com.google.android.testdpc1", "")); + assertThat(owners.getProfileOwnerName(11)).isEqualTo("1"); + assertThat(owners.getProfileOwnerPackage(11)).isEqualTo("com.google.android.testdpc1"); + + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } } @@ -224,6 +233,7 @@ public class OwnersTest extends DpmTestBase { * Note this also tests {@link Owners#setDeviceOwnerUserRestrictionsMigrated()} * and {@link Owners#setProfileOwnerUserRestrictionsMigrated(int)}. */ + @Test public void testUpgrade04() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -237,40 +247,40 @@ public class OwnersTest extends DpmTestBase { owners.load(); // The legacy file should be removed. - assertFalse(owners.getLegacyConfigFile().exists()); - - assertTrue(owners.getDeviceOwnerFile().exists()); - - assertTrue(owners.getProfileOwnerFile(10).exists()); - assertTrue(owners.getProfileOwnerFile(11).exists()); - assertFalse(owners.getProfileOwnerFile(20).exists()); - assertFalse(owners.getProfileOwnerFile(21).exists()); - - assertTrue(owners.hasDeviceOwner()); - assertEquals(null, owners.getDeviceOwnerName()); - assertEquals("com.google.android.testdpc", owners.getDeviceOwnerPackageName()); - assertEquals(UserHandle.USER_SYSTEM, owners.getDeviceOwnerUserId()); - - assertNotNull(owners.getSystemUpdatePolicy()); - assertEquals(5, owners.getSystemUpdatePolicy().getPolicyType()); - - assertEquals(2, owners.getProfileOwnerKeys().size()); - assertEquals(new ComponentName("com.google.android.testdpc", - "com.google.android.testdpc.DeviceAdminReceiver0"), - owners.getProfileOwnerComponent(10)); - assertEquals("0", owners.getProfileOwnerName(10)); - assertEquals("com.google.android.testdpc", owners.getProfileOwnerPackage(10)); - - assertEquals(new ComponentName("com.google.android.testdpc1", ""), - owners.getProfileOwnerComponent(11)); - assertEquals("1", owners.getProfileOwnerName(11)); - assertEquals("com.google.android.testdpc1", owners.getProfileOwnerPackage(11)); - - assertTrue(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); + + assertThat(owners.getDeviceOwnerFile().exists()).isTrue(); + + assertThat(owners.getProfileOwnerFile(10).exists()).isTrue(); + assertThat(owners.getProfileOwnerFile(11).exists()).isTrue(); + assertThat(owners.getProfileOwnerFile(20).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(21).exists()).isFalse(); + + assertThat(owners.hasDeviceOwner()).isTrue(); + assertThat(owners.getDeviceOwnerName()).isEqualTo(null); + assertThat(owners.getDeviceOwnerPackageName()).isEqualTo("com.google.android.testdpc"); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); + + assertThat(owners.getSystemUpdatePolicy()).isNotNull(); + assertThat(owners.getSystemUpdatePolicy().getPolicyType()).isEqualTo(5); + + assertThat(owners.getProfileOwnerKeys()).hasSize(2); + assertThat(owners.getProfileOwnerComponent(10)) + .isEqualTo(new ComponentName("com.google.android.testdpc", + "com.google.android.testdpc.DeviceAdminReceiver0")); + assertThat(owners.getProfileOwnerName(10)).isEqualTo("0"); + assertThat(owners.getProfileOwnerPackage(10)).isEqualTo("com.google.android.testdpc"); + + assertThat(owners.getProfileOwnerComponent(11)) + .isEqualTo(new ComponentName("com.google.android.testdpc1", "")); + assertThat(owners.getProfileOwnerName(11)).isEqualTo("1"); + assertThat(owners.getProfileOwnerPackage(11)).isEqualTo("com.google.android.testdpc1"); + + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } // Then re-read and check. @@ -278,31 +288,31 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertTrue(owners.hasDeviceOwner()); - assertEquals(null, owners.getDeviceOwnerName()); - assertEquals("com.google.android.testdpc", owners.getDeviceOwnerPackageName()); - assertEquals(UserHandle.USER_SYSTEM, owners.getDeviceOwnerUserId()); + assertThat(owners.hasDeviceOwner()).isTrue(); + assertThat(owners.getDeviceOwnerName()).isEqualTo(null); + assertThat(owners.getDeviceOwnerPackageName()).isEqualTo("com.google.android.testdpc"); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_SYSTEM); - assertNotNull(owners.getSystemUpdatePolicy()); - assertEquals(5, owners.getSystemUpdatePolicy().getPolicyType()); + assertThat(owners.getSystemUpdatePolicy()).isNotNull(); + assertThat(owners.getSystemUpdatePolicy().getPolicyType()).isEqualTo(5); - assertEquals(2, owners.getProfileOwnerKeys().size()); - assertEquals(new ComponentName("com.google.android.testdpc", - "com.google.android.testdpc.DeviceAdminReceiver0"), - owners.getProfileOwnerComponent(10)); - assertEquals("0", owners.getProfileOwnerName(10)); - assertEquals("com.google.android.testdpc", owners.getProfileOwnerPackage(10)); + assertThat(owners.getProfileOwnerKeys()).hasSize(2); + assertThat(owners.getProfileOwnerComponent(10)) + .isEqualTo(new ComponentName("com.google.android.testdpc", + "com.google.android.testdpc.DeviceAdminReceiver0")); + assertThat(owners.getProfileOwnerName(10)).isEqualTo("0"); + assertThat(owners.getProfileOwnerPackage(10)).isEqualTo("com.google.android.testdpc"); - assertEquals(new ComponentName("com.google.android.testdpc1", ""), - owners.getProfileOwnerComponent(11)); - assertEquals("1", owners.getProfileOwnerName(11)); - assertEquals("com.google.android.testdpc1", owners.getProfileOwnerPackage(11)); + assertThat(owners.getProfileOwnerComponent(11)) + .isEqualTo(new ComponentName("com.google.android.testdpc1", "")); + assertThat(owners.getProfileOwnerName(11)).isEqualTo("1"); + assertThat(owners.getProfileOwnerPackage(11)).isEqualTo("com.google.android.testdpc1"); - assertTrue(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); owners.setDeviceOwnerUserRestrictionsMigrated(); } @@ -311,11 +321,11 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); owners.setProfileOwnerUserRestrictionsMigrated(11); } @@ -324,16 +334,17 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertTrue(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isTrue(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); owners.setProfileOwnerUserRestrictionsMigrated(11); } } + @Test public void testUpgrade05() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -347,27 +358,27 @@ public class OwnersTest extends DpmTestBase { owners.load(); // The legacy file should be removed. - assertFalse(owners.getLegacyConfigFile().exists()); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); // Note device initializer is no longer supported. No need to write the DO file. - assertFalse(owners.getDeviceOwnerFile().exists()); + assertThat(owners.getDeviceOwnerFile().exists()).isFalse(); - assertFalse(owners.getProfileOwnerFile(10).exists()); - assertFalse(owners.getProfileOwnerFile(11).exists()); - assertFalse(owners.getProfileOwnerFile(20).exists()); + assertThat(owners.getProfileOwnerFile(10).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(11).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(20).exists()).isFalse(); - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); - assertNull(owners.getSystemUpdatePolicy()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } // Then re-read and check. @@ -375,21 +386,22 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); - assertNull(owners.getSystemUpdatePolicy()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.getSystemUpdatePolicy()).isNull(); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } } + @Test public void testUpgrade06() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -403,26 +415,26 @@ public class OwnersTest extends DpmTestBase { owners.load(); // The legacy file should be removed. - assertFalse(owners.getLegacyConfigFile().exists()); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); - assertTrue(owners.getDeviceOwnerFile().exists()); + assertThat(owners.getDeviceOwnerFile().exists()).isTrue(); - assertFalse(owners.getProfileOwnerFile(10).exists()); - assertFalse(owners.getProfileOwnerFile(11).exists()); - assertFalse(owners.getProfileOwnerFile(20).exists()); + assertThat(owners.getProfileOwnerFile(10).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(11).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(20).exists()).isFalse(); - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertNotNull(owners.getSystemUpdatePolicy()); - assertEquals(5, owners.getSystemUpdatePolicy().getPolicyType()); + assertThat(owners.getSystemUpdatePolicy()).isNotNull(); + assertThat(owners.getSystemUpdatePolicy().getPolicyType()).isEqualTo(5); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } // Then re-read and check. @@ -430,21 +442,22 @@ public class OwnersTest extends DpmTestBase { final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); - assertFalse(owners.hasDeviceOwner()); - assertEquals(UserHandle.USER_NULL, owners.getDeviceOwnerUserId()); - assertEquals(0, owners.getProfileOwnerKeys().size()); + assertThat(owners.hasDeviceOwner()).isFalse(); + assertThat(owners.getDeviceOwnerUserId()).isEqualTo(UserHandle.USER_NULL); + assertThat(owners.getProfileOwnerKeys()).isEmpty(); - assertNotNull(owners.getSystemUpdatePolicy()); - assertEquals(5, owners.getSystemUpdatePolicy().getPolicyType()); + assertThat(owners.getSystemUpdatePolicy()).isNotNull(); + assertThat(owners.getSystemUpdatePolicy().getPolicyType()).isEqualTo(5); - assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)); - assertFalse(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)); + assertThat(owners.getDeviceOwnerUserRestrictionsNeedsMigration()).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(10)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(11)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(20)).isFalse(); + assertThat(owners.getProfileOwnerUserRestrictionsNeedsMigration(21)).isFalse(); } } + @Test public void testRemoveExistingFiles() throws Exception { getServices().addUsers(10, 11, 20, 21); @@ -456,11 +469,11 @@ public class OwnersTest extends DpmTestBase { owners.load(); - assertFalse(owners.getLegacyConfigFile().exists()); + assertThat(owners.getLegacyConfigFile().exists()).isFalse(); - assertTrue(owners.getDeviceOwnerFile().exists()); - assertTrue(owners.getProfileOwnerFile(10).exists()); - assertTrue(owners.getProfileOwnerFile(11).exists()); + assertThat(owners.getDeviceOwnerFile().exists()).isTrue(); + assertThat(owners.getProfileOwnerFile(10).exists()).isTrue(); + assertThat(owners.getProfileOwnerFile(11).exists()).isTrue(); // Then clear all information and save. owners.clearDeviceOwner(); @@ -475,8 +488,8 @@ public class OwnersTest extends DpmTestBase { owners.writeProfileOwner(21); // Now all files should be removed. - assertFalse(owners.getDeviceOwnerFile().exists()); - assertFalse(owners.getProfileOwnerFile(10).exists()); - assertFalse(owners.getProfileOwnerFile(11).exists()); + assertThat(owners.getDeviceOwnerFile().exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(10).exists()).isFalse(); + assertThat(owners.getProfileOwnerFile(11).exists()).isFalse(); } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/SecurityEventTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/SecurityEventTest.java index 8dcf21f9fe77..6cefaebbff7a 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/SecurityEventTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/SecurityEventTest.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.android.server.devicepolicy; import static android.app.admin.SecurityLog.TAG_ADB_SHELL_CMD; @@ -11,6 +26,8 @@ import static android.app.admin.SecurityLog.TAG_KEY_INTEGRITY_VIOLATION; import static android.app.admin.SecurityLog.TAG_MEDIA_MOUNT; import static android.app.admin.SecurityLog.TAG_MEDIA_UNMOUNT; +import static com.google.common.truth.Truth.assertThat; + import android.app.admin.SecurityLog.SecurityEvent; import android.os.Parcel; import android.os.UserHandle; @@ -18,21 +35,37 @@ import android.text.TextUtils; import android.util.EventLog; import android.util.EventLog.Event; +import androidx.test.runner.AndroidJUnit4; + import junit.framework.AssertionFailedError; +import org.junit.Test; +import org.junit.runner.RunWith; + import java.util.ArrayList; import java.util.List; +/** + * Tests for the DeviceOwner object that saves & loads device and policy owner information. + * + * <p>Run this test with: + * + * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.SecurityEventTest} + * + */ +@RunWith(AndroidJUnit4.class) public class SecurityEventTest extends DpmTestBase { + @Test public void testSecurityEventId() throws Exception { SecurityEvent event = createEvent(() -> { EventLog.writeEvent(TAG_ADB_SHELL_CMD, 0); }, TAG_ADB_SHELL_CMD); event.setId(20); - assertEquals(20, event.getId()); + assertThat(event.getId()).isEqualTo(20); } + @Test public void testSecurityEventParceling() throws Exception { // GIVEN an event. SecurityEvent event = createEvent(() -> { @@ -45,12 +78,13 @@ public class SecurityEventTest extends DpmTestBase { SecurityEvent unparceledEvent = p.readParcelable(SecurityEventTest.class.getClassLoader()); p.recycle(); // THEN the event state is preserved. - assertEquals(event.getTag(), unparceledEvent.getTag()); - assertEquals(event.getData(), unparceledEvent.getData()); - assertEquals(event.getTimeNanos(), unparceledEvent.getTimeNanos()); - assertEquals(event.getId(), unparceledEvent.getId()); + assertThat(unparceledEvent.getTag()).isEqualTo(event.getTag()); + assertThat(unparceledEvent.getData()).isEqualTo(event.getData()); + assertThat(unparceledEvent.getTimeNanos()).isEqualTo(event.getTimeNanos()); + assertThat(unparceledEvent.getId()).isEqualTo(event.getId()); } + @Test public void testSecurityEventRedaction() throws Exception { SecurityEvent event; @@ -58,75 +92,75 @@ public class SecurityEventTest extends DpmTestBase { event = createEvent(() -> { EventLog.writeEvent(TAG_ADB_SHELL_CMD, "command"); }, TAG_ADB_SHELL_CMD); - assertFalse(TextUtils.isEmpty((String) event.getData())); + assertThat(TextUtils.isEmpty((String) event.getData())).isFalse(); // TAG_MEDIA_MOUNT will have the volume label redacted (second data) event = createEvent(() -> { EventLog.writeEvent(TAG_MEDIA_MOUNT, new Object[] {"path", "label"}); }, TAG_MEDIA_MOUNT); - assertFalse(TextUtils.isEmpty(event.getStringData(1))); - assertTrue(TextUtils.isEmpty(event.redact(0).getStringData(1))); + assertThat(TextUtils.isEmpty(event.getStringData(1))).isFalse(); + assertThat(TextUtils.isEmpty(event.redact(0).getStringData(1))).isTrue(); // TAG_MEDIA_UNMOUNT will have the volume label redacted (second data) event = createEvent(() -> { EventLog.writeEvent(TAG_MEDIA_UNMOUNT, new Object[] {"path", "label"}); }, TAG_MEDIA_UNMOUNT); - assertFalse(TextUtils.isEmpty(event.getStringData(1))); - assertTrue(TextUtils.isEmpty(event.redact(0).getStringData(1))); + assertThat(TextUtils.isEmpty(event.getStringData(1))).isFalse(); + assertThat(TextUtils.isEmpty(event.redact(0).getStringData(1))).isTrue(); // TAG_APP_PROCESS_START will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_APP_PROCESS_START, new Object[] {"process", 12345L, UserHandle.getUid(10, 123), 456, "seinfo", "hash"}); }, TAG_APP_PROCESS_START); - assertNotNull(event.redact(10)); - assertNull(event.redact(11)); + assertThat(event.redact(10)).isNotNull(); + assertThat(event.redact(11)).isNull(); // TAG_CERT_AUTHORITY_INSTALLED will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_CERT_AUTHORITY_INSTALLED, new Object[] {1, "subject", 10}); }, TAG_CERT_AUTHORITY_INSTALLED); - assertNotNull(event.redact(10)); - assertNull(event.redact(11)); + assertThat(event.redact(10)).isNotNull(); + assertThat(event.redact(11)).isNull(); // TAG_CERT_AUTHORITY_REMOVED will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_CERT_AUTHORITY_REMOVED, new Object[] {1, "subject", 20}); }, TAG_CERT_AUTHORITY_REMOVED); - assertNotNull(event.redact(20)); - assertNull(event.redact(0)); + assertThat(event.redact(20)).isNotNull(); + assertThat(event.redact(0)).isNull(); // TAG_KEY_GENERATED will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_KEY_GENERATED, new Object[] {1, "alias", UserHandle.getUid(0, 123)}); }, TAG_KEY_GENERATED); - assertNotNull(event.redact(0)); - assertNull(event.redact(10)); + assertThat(event.redact(0)).isNotNull(); + assertThat(event.redact(10)).isNull(); // TAG_KEY_IMPORT will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_KEY_IMPORT, new Object[] {1, "alias", UserHandle.getUid(1, 123)}); }, TAG_KEY_IMPORT); - assertNotNull(event.redact(1)); - assertNull(event.redact(10)); + assertThat(event.redact(1)).isNotNull(); + assertThat(event.redact(10)).isNull(); // TAG_KEY_DESTRUCTION will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_KEY_DESTRUCTION, new Object[] {1, "alias", UserHandle.getUid(2, 123)}); }, TAG_KEY_DESTRUCTION); - assertNotNull(event.redact(2)); - assertNull(event.redact(10)); + assertThat(event.redact(2)).isNotNull(); + assertThat(event.redact(10)).isNull(); // TAG_KEY_INTEGRITY_VIOLATION will be fully redacted if user does not match event = createEvent(() -> { EventLog.writeEvent(TAG_KEY_INTEGRITY_VIOLATION, new Object[] {"alias", UserHandle.getUid(2, 123)}); }, TAG_KEY_INTEGRITY_VIOLATION); - assertNotNull(event.redact(2)); - assertNull(event.redact(10)); + assertThat(event.redact(2)).isNotNull(); + assertThat(event.redact(10)).isNull(); } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/SystemUpdatePolicyTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/SystemUpdatePolicyTest.java index e51859b5c829..0a9aad771ff0 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/SystemUpdatePolicyTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/SystemUpdatePolicyTest.java @@ -21,8 +21,9 @@ import static android.app.admin.SystemUpdatePolicy.ValidationFailedException.ERR import static android.app.admin.SystemUpdatePolicy.ValidationFailedException.ERROR_NEW_FREEZE_PERIOD_TOO_CLOSE; import static android.app.admin.SystemUpdatePolicy.ValidationFailedException.ERROR_NEW_FREEZE_PERIOD_TOO_LONG; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + import static org.junit.Assert.fail; import android.app.admin.FreezePeriod; @@ -53,10 +54,12 @@ import java.util.concurrent.TimeUnit; /** * Unit tests for {@link android.app.admin.SystemUpdatePolicy}. - * Throughout this test, we use "MM-DD" format to denote dates without year. * - * atest com.android.server.devicepolicy.SystemUpdatePolicyTest - * runtest -c com.android.server.devicepolicy.SystemUpdatePolicyTest frameworks-services + * <p>NOTE: Throughout this test, we use {@code "MM-DD"} format to denote dates without year. + * + * <p>Run this test with: + * + * {@code atest FrameworksServicesTests:com.android.server.devicepolicy.SystemUpdatePolicyTest} */ @RunWith(AndroidJUnit4.class) public final class SystemUpdatePolicyTest { @@ -224,37 +227,37 @@ public final class SystemUpdatePolicyTest { @Test public void testDistanceWithoutLeapYear() { - assertEquals(364, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 12, 31), LocalDate.of(2016, 1, 1))); - assertEquals(365, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2017, 1, 1), LocalDate.of(2016, 1, 1))); - assertEquals(365, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2017, 2, 28), LocalDate.of(2016, 2, 29))); - assertEquals(-365, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 1, 1), LocalDate.of(2017, 1, 1))); - assertEquals(1, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 3, 1), LocalDate.of(2016, 2, 29))); - assertEquals(1, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 3, 1), LocalDate.of(2016, 2, 28))); - assertEquals(0, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 2, 29), LocalDate.of(2016, 2, 28))); - assertEquals(0, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 2, 28), LocalDate.of(2016, 2, 28))); - - assertEquals(59, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2016, 3, 1), LocalDate.of(2016, 1, 1))); - assertEquals(59, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2017, 3, 1), LocalDate.of(2017, 1, 1))); - - assertEquals(365 * 40, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2040, 1, 1), LocalDate.of(2000, 1, 1))); - - assertEquals(365 * 2, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2019, 3, 1), LocalDate.of(2017, 3, 1))); - assertEquals(365 * 2, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2018, 3, 1), LocalDate.of(2016, 3, 1))); - assertEquals(365 * 2, FreezePeriod.distanceWithoutLeapYear( - LocalDate.of(2017, 3, 1), LocalDate.of(2015, 3, 1))); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 12, 31), LocalDate.of(2016, 1, 1))).isEqualTo(364); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2017, 1, 1), LocalDate.of(2016, 1, 1))).isEqualTo(365); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2017, 2, 28), LocalDate.of(2016, 2, 29))).isEqualTo(365); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 1, 1), LocalDate.of(2017, 1, 1))).isEqualTo(-365); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 3, 1), LocalDate.of(2016, 2, 29))).isEqualTo(1); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 3, 1), LocalDate.of(2016, 2, 28))).isEqualTo(1); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 2, 29), LocalDate.of(2016, 2, 28))).isEqualTo(0); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 2, 28), LocalDate.of(2016, 2, 28))).isEqualTo(0); + + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2016, 3, 1), LocalDate.of(2016, 1, 1))).isEqualTo(59); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2017, 3, 1), LocalDate.of(2017, 1, 1))).isEqualTo(59); + + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2040, 1, 1), LocalDate.of(2000, 1, 1))).isEqualTo(365 * 40); + + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2019, 3, 1), LocalDate.of(2017, 3, 1))).isEqualTo(365 * 2); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2018, 3, 1), LocalDate.of(2016, 3, 1))).isEqualTo(365 * 2); + assertThat(FreezePeriod.distanceWithoutLeapYear( + LocalDate.of(2017, 3, 1), LocalDate.of(2015, 3, 1))).isEqualTo(365 * 2); } @@ -395,8 +398,8 @@ public final class SystemUpdatePolicyTest { private void assertInstallationOption(int expectedType, long expectedTime, long now, SystemUpdatePolicy p) { - assertEquals(expectedType, p.getInstallationOptionAt(now).getType()); - assertEquals(expectedTime, p.getInstallationOptionAt(now).getEffectiveTime()); + assertThat(p.getInstallationOptionAt(now).getType()).isEqualTo(expectedType); + assertThat(p.getInstallationOptionAt(now).getEffectiveTime()).isEqualTo(expectedTime); } private void testFreezePeriodsSucceeds(String...dates) throws Exception { @@ -410,8 +413,8 @@ public final class SystemUpdatePolicyTest { setFreezePeriods(p, dates); fail("Invalid periods (" + expectedError + ") not flagged: " + String.join(" ", dates)); } catch (SystemUpdatePolicy.ValidationFailedException e) { - assertTrue("Exception not expected: " + e.getMessage(), - e.getErrorCode() == expectedError); + assertWithMessage("Exception not expected: %s", e.getMessage()).that(e.getErrorCode()) + .isEqualTo(expectedError); } } @@ -426,8 +429,8 @@ public final class SystemUpdatePolicyTest { createPrevFreezePeriod(prevStart, prevEnd, now, dates); fail("Invalid period (" + expectedError + ") not flagged: " + String.join(" ", dates)); } catch (SystemUpdatePolicy.ValidationFailedException e) { - assertTrue("Exception not expected: " + e.getMessage(), - e.getErrorCode() == expectedError); + assertWithMessage("Exception not expected: %s", e.getMessage()).that(e.getErrorCode()) + .isEqualTo(expectedError); } } @@ -480,7 +483,7 @@ public final class SystemUpdatePolicyTest { ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); XmlPullParser parser = Xml.newPullParser(); parser.setInput(new InputStreamReader(inStream)); - assertEquals(XmlPullParser.START_TAG, parser.next()); + assertThat(parser.next()).isEqualTo(XmlPullParser.START_TAG); checkFreezePeriods(SystemUpdatePolicy.restoreFromXml(parser), expectedPeriods); } @@ -488,8 +491,8 @@ public final class SystemUpdatePolicyTest { List<FreezePeriod> expectedPeriods) { int i = 0; for (FreezePeriod period : policy.getFreezePeriods()) { - assertEquals(expectedPeriods.get(i).getStart(), period.getStart()); - assertEquals(expectedPeriods.get(i).getEnd(), period.getEnd()); + assertThat(period.getStart()).isEqualTo(expectedPeriods.get(i).getStart()); + assertThat(period.getEnd()).isEqualTo(expectedPeriods.get(i).getEnd()); i++; } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/TransferOwnershipMetadataManagerTest.java b/services/tests/servicestests/src/com/android/server/devicepolicy/TransferOwnershipMetadataManagerTest.java index 2005dd901ad1..07ea85535f50 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/TransferOwnershipMetadataManagerTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/TransferOwnershipMetadataManagerTest.java @@ -25,14 +25,13 @@ import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.T import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.TAG_TARGET_COMPONENT; import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.TAG_USER_ID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import android.os.Environment; -import androidx.test.runner.AndroidJUnit4; import android.util.Log; +import androidx.test.runner.AndroidJUnit4; + import com.android.server.devicepolicy.TransferOwnershipMetadataManager.Injector; import com.android.server.devicepolicy.TransferOwnershipMetadataManager.Metadata; @@ -51,12 +50,14 @@ import java.nio.file.Paths; /** * Unit tests for {@link TransferOwnershipMetadataManager}. * - * bit FrameworksServicesTests:com.android.server.devicepolicy.TransferOwnershipMetadataManagerTest - * runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/devicepolicy/TransferOwnershipMetadataManagerTest.java -* */ - + * <p>Run this test with: + * + * <pre><code> + atest FrameworksServicesTests:com.android.server.devicepolicy.TransferOwnershipMetadataManagerTest + * </code></pre> + */ @RunWith(AndroidJUnit4.class) -public class TransferOwnershipMetadataManagerTest { +public final class TransferOwnershipMetadataManagerTest { private final static String TAG = TransferOwnershipMetadataManagerTest.class.getName(); private final static String SOURCE_COMPONENT = "com.dummy.admin.package/com.dummy.admin.package.SourceClassName"; @@ -77,28 +78,27 @@ public class TransferOwnershipMetadataManagerTest { @Test public void testSave() { TransferOwnershipMetadataManager paramsManager = getOwnerTransferParams(); - assertTrue(paramsManager.saveMetadataFile(TEST_PARAMS)); - assertTrue(paramsManager.metadataFileExists()); + assertThat(paramsManager.saveMetadataFile(TEST_PARAMS)).isTrue(); + assertThat(paramsManager.metadataFileExists()).isTrue(); } @Test public void testFileContentValid() { TransferOwnershipMetadataManager paramsManager = getOwnerTransferParams(); - assertTrue(paramsManager.saveMetadataFile(TEST_PARAMS)); + assertThat(paramsManager.saveMetadataFile(TEST_PARAMS)).isTrue(); Path path = Paths.get(new File(mMockInjector.getOwnerTransferMetadataDir(), OWNER_TRANSFER_METADATA_XML).getAbsolutePath()); try { String contents = new String(Files.readAllBytes(path), Charset.forName("UTF-8")); - assertEquals( - "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n" - + "<" + TAG_USER_ID + ">" + USER_ID + "</" + TAG_USER_ID + ">\n" - + "<" + TAG_SOURCE_COMPONENT + ">" + SOURCE_COMPONENT + "</" - + TAG_SOURCE_COMPONENT + ">\n" - + "<" + TAG_TARGET_COMPONENT + ">" + TARGET_COMPONENT + "</" - + TAG_TARGET_COMPONENT + ">\n" - + "<" + TAG_ADMIN_TYPE + ">" + ADMIN_TYPE_DEVICE_OWNER + "</" - + TAG_ADMIN_TYPE + ">\n", - contents); + assertThat(contents).isEqualTo( + "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n" + + "<" + TAG_USER_ID + ">" + USER_ID + "</" + TAG_USER_ID + ">\n" + + "<" + TAG_SOURCE_COMPONENT + ">" + SOURCE_COMPONENT + "</" + + TAG_SOURCE_COMPONENT + ">\n" + + "<" + TAG_TARGET_COMPONENT + ">" + TARGET_COMPONENT + "</" + + TAG_TARGET_COMPONENT + ">\n" + + "<" + TAG_ADMIN_TYPE + ">" + ADMIN_TYPE_DEVICE_OWNER + "</" + + TAG_ADMIN_TYPE + ">\n"); } catch (IOException e) { e.printStackTrace(); } @@ -124,7 +124,7 @@ public class TransferOwnershipMetadataManagerTest { Log.d(TAG, "testLoad: failed to get canonical file"); } paramsManager.saveMetadataFile(TEST_PARAMS); - assertEquals(TEST_PARAMS, paramsManager.loadMetadataFile()); + assertThat(paramsManager.loadMetadataFile()).isEqualTo(TEST_PARAMS); } @Test @@ -132,7 +132,7 @@ public class TransferOwnershipMetadataManagerTest { TransferOwnershipMetadataManager paramsManager = getOwnerTransferParams(); paramsManager.saveMetadataFile(TEST_PARAMS); paramsManager.deleteMetadataFile(); - assertFalse(paramsManager.metadataFileExists()); + assertThat(paramsManager.metadataFileExists()).isFalse(); } @After |