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 be1d07bbec0be..c5fb0bde579fd 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceMigrationTest.java @@ -47,14 +47,14 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { mContext = getContext(); - when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) + when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) .thenReturn(true); } public void testMigration() throws Exception { - final File user10dir = mMockContext.addUser(10, 0); - final File user11dir = mMockContext.addUser(11, UserInfo.FLAG_MANAGED_PROFILE); - mMockContext.addUser(12, 0); + final File user10dir = getServices().addUser(10, 0); + final File user11dir = getServices().addUser(11, UserInfo.FLAG_MANAGED_PROFILE); + getServices().addUser(12, 0); setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); setUpPackageManagerForAdmin(admin2, UserHandle.getUid(10, 123)); @@ -62,12 +62,12 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { // Create the legacy owners & policies file. DpmTestUtils.writeToFile( - (new File(mContext.dataDir, OwnersTestable.LEGACY_FILE)).getAbsoluteFile(), + (new File(getServices().dataDir, OwnersTestable.LEGACY_FILE)).getAbsoluteFile(), DpmTestUtils.readAsset(mRealTestContext, "DevicePolicyManagerServiceMigrationTest/legacy_device_owner.xml")); DpmTestUtils.writeToFile( - (new File(mContext.systemUserDataDir, "device_policies.xml")).getAbsoluteFile(), + (new File(getServices().systemUserDataDir, "device_policies.xml")).getAbsoluteFile(), DpmTestUtils.readAsset(mRealTestContext, "DevicePolicyManagerServiceMigrationTest/legacy_device_policies.xml")); @@ -81,12 +81,12 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { "DevicePolicyManagerServiceMigrationTest/legacy_device_policies_11.xml")); // Set up UserManager - when(mMockContext.userManagerInternal.getBaseUserRestrictions( + when(getServices().userManagerInternal.getBaseUserRestrictions( eq(UserHandle.USER_SYSTEM))).thenReturn(DpmTestUtils.newRestrictions( UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_RECORD_AUDIO)); - when(mMockContext.userManagerInternal.getBaseUserRestrictions( + when(getServices().userManagerInternal.getBaseUserRestrictions( eq(10))).thenReturn(DpmTestUtils.newRestrictions( UserManager.DISALLOW_REMOVE_USER, UserManager.DISALLOW_ADD_USER, @@ -95,7 +95,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { UserManager.DISALLOW_WALLPAPER, UserManager.DISALLOW_RECORD_AUDIO)); - when(mMockContext.userManagerInternal.getBaseUserRestrictions( + when(getServices().userManagerInternal.getBaseUserRestrictions( eq(11))).thenReturn(DpmTestUtils.newRestrictions( UserManager.DISALLOW_REMOVE_USER, UserManager.DISALLOW_ADD_USER, @@ -113,7 +113,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { newBaseRestrictions.put(userId, bundle); return null; - }).when(mContext.userManagerInternal).setBaseUserRestrictionsByDpmsForMigration( + }).when(getServices().userManagerInternal).setBaseUserRestrictionsByDpmsForMigration( anyInt(), any(Bundle.class)); // Initialize DPM/DPMS and let it migrate the persisted information. @@ -125,7 +125,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { try { LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); - dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); + dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext); dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); @@ -200,17 +200,17 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { // Create the legacy owners & policies file. DpmTestUtils.writeToFile( - (new File(mContext.dataDir, OwnersTestable.LEGACY_FILE)).getAbsoluteFile(), + (new File(getServices().dataDir, OwnersTestable.LEGACY_FILE)).getAbsoluteFile(), DpmTestUtils.readAsset(mRealTestContext, "DevicePolicyManagerServiceMigrationTest2/legacy_device_owner.xml")); DpmTestUtils.writeToFile( - (new File(mContext.systemUserDataDir, "device_policies.xml")).getAbsoluteFile(), + (new File(getServices().systemUserDataDir, "device_policies.xml")).getAbsoluteFile(), DpmTestUtils.readAsset(mRealTestContext, "DevicePolicyManagerServiceMigrationTest2/legacy_device_policies.xml")); // Set up UserManager - when(mMockContext.userManagerInternal.getBaseUserRestrictions( + when(getServices().userManagerInternal.getBaseUserRestrictions( eq(UserHandle.USER_SYSTEM))).thenReturn(DpmTestUtils.newRestrictions( UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_RECORD_AUDIO, @@ -226,7 +226,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { newBaseRestrictions.put(userId, bundle); return null; - }).when(mContext.userManagerInternal).setBaseUserRestrictionsByDpmsForMigration( + }).when(getServices().userManagerInternal).setBaseUserRestrictionsByDpmsForMigration( anyInt(), any(Bundle.class)); // Initialize DPM/DPMS and let it migrate the persisted information. @@ -238,7 +238,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { try { LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); - dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); + dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext); dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); @@ -273,18 +273,18 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { // Test setting default restrictions for managed profile. public void testMigration3_managedProfileOwner() throws Exception { // Create a managed profile user. - final File user10dir = mMockContext.addUser(10, UserInfo.FLAG_MANAGED_PROFILE); + final File user10dir = getServices().addUser(10, UserInfo.FLAG_MANAGED_PROFILE); // Profile owner package for managed profile user. setUpPackageManagerForAdmin(admin1, UserHandle.getUid(10, 123)); // Set up fake UserManager to make it look like a managed profile. - when(mMockContext.userManager.isManagedProfile(eq(10))).thenReturn(true); + when(getServices().userManager.isManagedProfile(eq(10))).thenReturn(true); // Set up fake Settings to make it look like INSTALL_NON_MARKET_APPS was reversed. - when(mMockContext.settings.settingsSecureGetIntForUser( + when(getServices().settings.settingsSecureGetIntForUser( eq(Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED), eq(0), eq(10))).thenReturn(1); // Write policy and owners files. DpmTestUtils.writeToFile( - (new File(mContext.systemUserDataDir, "device_policies.xml")).getAbsoluteFile(), + (new File(getServices().systemUserDataDir, "device_policies.xml")).getAbsoluteFile(), DpmTestUtils.readAsset(mRealTestContext, "DevicePolicyManagerServiceMigrationTest3/system_device_policies.xml")); DpmTestUtils.writeToFile( @@ -304,7 +304,7 @@ public class DevicePolicyManagerServiceMigrationTest extends DpmTestBase { try { LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); - dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); + dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext); dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java index b870d9404181e..a33153e074962 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerServiceTestable.java @@ -61,11 +61,12 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi private final File mDeviceOwnerFile; private final File mUsersDataDir; - public OwnersTestable(DpmMockContext context) { - super(context.userManager, context.userManagerInternal, context.packageManagerInternal); - mLegacyFile = new File(context.dataDir, LEGACY_FILE); - mDeviceOwnerFile = new File(context.dataDir, DEVICE_OWNER_FILE); - mUsersDataDir = new File(context.dataDir, "users"); + public OwnersTestable(MockSystemServices services) { + super(services.userManager, services.userManagerInternal, + services.packageManagerInternal); + mLegacyFile = new File(services.dataDir, LEGACY_FILE); + mDeviceOwnerFile = new File(services.dataDir, DEVICE_OWNER_FILE); + mUsersDataDir = new File(services.dataDir, "users"); } @Override @@ -88,8 +89,8 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi public final DpmMockContext context; private final MockInjector mMockInjector; - public DevicePolicyManagerServiceTestable(DpmMockContext context, File dataDir) { - this(new MockInjector(context, dataDir)); + public DevicePolicyManagerServiceTestable(MockSystemServices services, DpmMockContext context) { + this(new MockInjector(services, context)); } private DevicePolicyManagerServiceTestable(MockInjector injector) { @@ -100,15 +101,13 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi public void notifyChangeToContentObserver(Uri uri, int userHandle) { - ContentObserver co = mMockInjector.mContentObservers - .get(new Pair(uri, userHandle)); + ContentObserver co = mMockInjector.mContentObservers.get(new Pair<>(uri, userHandle)); if (co != null) { co.onChange(false, uri, userHandle); // notify synchronously } // Notify USER_ALL observer too. - co = mMockInjector.mContentObservers - .get(new Pair(uri, UserHandle.USER_ALL)); + co = mMockInjector.mContentObservers.get(new Pair<>(uri, UserHandle.USER_ALL)); if (co != null) { co.onChange(false, uri, userHandle); // notify synchronously } @@ -118,76 +117,75 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi private static class MockInjector extends Injector { public final DpmMockContext context; - - public final File dataDir; + private final MockSystemServices services; // Key is a pair of uri and userId private final Map, ContentObserver> mContentObservers = new ArrayMap<>(); - private MockInjector(DpmMockContext context, File dataDir) { + private MockInjector(MockSystemServices services, DpmMockContext context) { super(context); + this.services = services; this.context = context; - this.dataDir = dataDir; } @Override Owners newOwners() { - return new OwnersTestable(context); + return new OwnersTestable(services); } @Override UserManager getUserManager() { - return context.userManager; + return services.userManager; } @Override UserManagerInternal getUserManagerInternal() { - return context.userManagerInternal; + return services.userManagerInternal; } @Override PackageManagerInternal getPackageManagerInternal() { - return context.packageManagerInternal; + return services.packageManagerInternal; } @Override PowerManagerInternal getPowerManagerInternal() { - return context.powerManagerInternal; + return services.powerManagerInternal; } @Override NotificationManager getNotificationManager() { - return context.notificationManager; + return services.notificationManager; } @Override IIpConnectivityMetrics getIIpConnectivityMetrics() { - return context.iipConnectivityMetrics; + return services.iipConnectivityMetrics; } @Override IWindowManager getIWindowManager() { - return context.iwindowManager; + return services.iwindowManager; } @Override IActivityManager getIActivityManager() { - return context.iactivityManager; + return services.iactivityManager; } @Override IPackageManager getIPackageManager() { - return context.ipackageManager; + return services.ipackageManager; } @Override IBackupManager getIBackupManager() { - return context.ibackupManager; + return services.ibackupManager; } @Override IAudioService getIAudioService() { - return context.iaudioService; + return services.iaudioService; } @Override @@ -197,32 +195,32 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi @Override LockPatternUtils newLockPatternUtils() { - return context.lockPatternUtils; + return services.lockPatternUtils; } @Override boolean storageManagerIsFileBasedEncryptionEnabled() { - return context.storageManager.isFileBasedEncryptionEnabled(); + return services.storageManager.isFileBasedEncryptionEnabled(); } @Override boolean storageManagerIsNonDefaultBlockEncrypted() { - return context.storageManager.isNonDefaultBlockEncrypted(); + return services.storageManager.isNonDefaultBlockEncrypted(); } @Override boolean storageManagerIsEncrypted() { - return context.storageManager.isEncrypted(); + return services.storageManager.isEncrypted(); } @Override boolean storageManagerIsEncryptable() { - return context.storageManager.isEncryptable(); + return services.storageManager.isEncryptable(); } @Override String getDevicePolicyFilePathForSystemUser() { - return context.systemUserDataDir.getAbsolutePath() + "/"; + return services.systemUserDataDir.getAbsolutePath() + "/"; } @Override @@ -257,53 +255,53 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi @Override File environmentGetUserSystemDirectory(int userId) { - return context.environment.getUserSystemDirectory(userId); + return services.environment.getUserSystemDirectory(userId); } @Override void powerManagerGoToSleep(long time, int reason, int flags) { - context.powerManager.goToSleep(time, reason, flags); + services.powerManager.goToSleep(time, reason, flags); } @Override void powerManagerReboot(String reason) { - context.powerManager.reboot(reason); + services.powerManager.reboot(reason); } @Override void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force) throws IOException { - context.recoverySystem.rebootWipeUserData(shutdown, reason, force); + services.recoverySystem.rebootWipeUserData(shutdown, reason, force); } @Override boolean systemPropertiesGetBoolean(String key, boolean def) { - return context.systemProperties.getBoolean(key, def); + return services.systemProperties.getBoolean(key, def); } @Override long systemPropertiesGetLong(String key, long def) { - return context.systemProperties.getLong(key, def); + return services.systemProperties.getLong(key, def); } @Override String systemPropertiesGet(String key, String def) { - return context.systemProperties.get(key, def); + return services.systemProperties.get(key, def); } @Override String systemPropertiesGet(String key) { - return context.systemProperties.get(key); + return services.systemProperties.get(key); } @Override void systemPropertiesSet(String key, String value) { - context.systemProperties.set(key, value); + services.systemProperties.set(key, value); } @Override boolean userManagerIsSplitSystemUser() { - return context.userManagerForMock.isSplitSystemUser(); + return services.userManagerForMock.isSplitSystemUser(); } @Override @@ -320,87 +318,87 @@ public class DevicePolicyManagerServiceTestable extends DevicePolicyManagerServi @Override int settingsSecureGetIntForUser(String name, int def, int userHandle) { - return context.settings.settingsSecureGetIntForUser(name, def, userHandle); + return services.settings.settingsSecureGetIntForUser(name, def, userHandle); } @Override String settingsSecureGetStringForUser(String name, int userHandle) { - return context.settings.settingsSecureGetStringForUser(name, userHandle); + return services.settings.settingsSecureGetStringForUser(name, userHandle); } @Override void settingsSecurePutIntForUser(String name, int value, int userHandle) { - context.settings.settingsSecurePutIntForUser(name, value, userHandle); + services.settings.settingsSecurePutIntForUser(name, value, userHandle); } @Override void settingsSecurePutStringForUser(String name, String value, int userHandle) { - context.settings.settingsSecurePutStringForUser(name, value, userHandle); + services.settings.settingsSecurePutStringForUser(name, value, userHandle); } @Override void settingsGlobalPutStringForUser(String name, String value, int userHandle) { - context.settings.settingsGlobalPutStringForUser(name, value, userHandle); + services.settings.settingsGlobalPutStringForUser(name, value, userHandle); } @Override void settingsSecurePutInt(String name, int value) { - context.settings.settingsSecurePutInt(name, value); + services.settings.settingsSecurePutInt(name, value); } @Override void settingsGlobalPutInt(String name, int value) { - context.settings.settingsGlobalPutInt(name, value); + services.settings.settingsGlobalPutInt(name, value); } @Override void settingsSecurePutString(String name, String value) { - context.settings.settingsSecurePutString(name, value); + services.settings.settingsSecurePutString(name, value); } @Override void settingsGlobalPutString(String name, String value) { - context.settings.settingsGlobalPutString(name, value); + services.settings.settingsGlobalPutString(name, value); } @Override int settingsGlobalGetInt(String name, int def) { - return context.settings.settingsGlobalGetInt(name, def); + return services.settings.settingsGlobalGetInt(name, def); } @Override String settingsGlobalGetString(String name) { - return context.settings.settingsGlobalGetString(name); + return services.settings.settingsGlobalGetString(name); } @Override void securityLogSetLoggingEnabledProperty(boolean enabled) { - context.settings.securityLogSetLoggingEnabledProperty(enabled); + services.settings.securityLogSetLoggingEnabledProperty(enabled); } @Override boolean securityLogGetLoggingEnabledProperty() { - return context.settings.securityLogGetLoggingEnabledProperty(); + return services.settings.securityLogGetLoggingEnabledProperty(); } @Override boolean securityLogIsLoggingEnabled() { - return context.settings.securityLogIsLoggingEnabled(); + return services.settings.securityLogIsLoggingEnabled(); } @Override TelephonyManager getTelephonyManager() { - return context.telephonyManager; + return services.telephonyManager; } @Override boolean isBuildDebuggable() { - return context.buildMock.isDebuggable; + return services.buildMock.isDebuggable; } @Override KeyChain.KeyChainConnection keyChainBindAsUser(UserHandle user) { - return context.keyChainConnection; + return services.keyChainConnection; } } } 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 fb74d056f9a0d..88fb992a6855e 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DevicePolicyManagerTest.java @@ -15,42 +15,56 @@ */ package com.android.server.devicepolicy; +import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; +import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY; import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY; import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isNull; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.nullable; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + import android.Manifest.permission; import android.app.Activity; import android.app.Notification; -import android.app.NotificationManager; import android.app.admin.DeviceAdminReceiver; import android.app.admin.DevicePolicyManager; import android.app.admin.DevicePolicyManagerInternal; import android.app.admin.PasswordMetrics; import android.content.BroadcastReceiver; import android.content.ComponentName; -import android.content.Context; import android.content.Intent; -import android.content.ServiceConnection; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.StringParceledListSlice; -import android.content.res.Resources; -import android.graphics.Color; -import android.net.IIpConnectivityMetrics; -import android.net.Uri; import android.content.pm.UserInfo; +import android.graphics.Color; +import android.net.Uri; import android.net.wifi.WifiInfo; import android.os.Build.VERSION_CODES; import android.os.Bundle; -import android.os.IBinder; import android.os.Process; import android.os.UserHandle; import android.os.UserManager; -import android.os.UserManagerInternal; import android.provider.Settings; -import android.security.IKeyChainService; import android.security.KeyChain; import android.telephony.TelephonyManager; import android.test.MoreAsserts; @@ -78,30 +92,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; -import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; -import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNull; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.nullable; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.hamcrest.MockitoHamcrest.argThat; - /** * Tests for DevicePolicyManager( and DevicePolicyManagerService). * You can run them via: @@ -122,7 +112,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL); + // TODO replace all instances of this with explicit {@link #mServiceContext}. + @Deprecated private DpmMockContext mContext; + + private DpmMockContext mServiceContext; + private DpmMockContext mAdmin1Context; public DevicePolicyManager dpm; public DevicePolicyManagerServiceTestable dpms; @@ -159,11 +154,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { super.setUp(); mContext = getContext(); - when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) + mServiceContext = mContext; + mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID; + when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) .thenReturn(true); // By default, pretend all users are running and unlocked. - when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); + when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true); initializeDpms(); @@ -172,6 +169,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID); setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID); + mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext); + mAdmin1Context.packageName = admin1.getPackageName(); + mAdmin1Context.applicationInfo = new ApplicationInfo(); + mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID; + setUpUserManager(); } @@ -184,18 +186,15 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void initializeDpms() { // Need clearCallingIdentity() to pass permission checks. final long ident = mContext.binder.clearCallingIdentity(); - try { - LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); + LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); - dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir); + dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext); + dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); + dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); - dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY); - dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED); + dpm = new DevicePolicyManagerTestable(mContext, dpms); - dpm = new DevicePolicyManagerTestable(mContext, dpms); - } finally { - mContext.binder.restoreCallingIdentity(ident); - } + mContext.binder.restoreCallingIdentity(ident); } private void setUpUserManager() { @@ -214,7 +213,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { return null; } - }).when(mContext.userManager).setApplicationRestrictions( + }).when(getServices().userManager).setApplicationRestrictions( anyString(), nullable(Bundle.class), any(UserHandle.class)); // UM.getApplicationRestrictions() will read from appRestrictions. @@ -226,33 +225,36 @@ public class DevicePolicyManagerTest extends DpmTestBase { return appRestrictions.get(Pair.create(pkg, user)); } - }).when(mContext.userManager).getApplicationRestrictions( + }).when(getServices().userManager).getApplicationRestrictions( anyString(), any(UserHandle.class)); // Add the first secondary user. - mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0); + getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0); } private void setAsProfileOwner(ComponentName admin) { - mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); - mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); + final long ident = mServiceContext.binder.clearCallingIdentity(); - // PO needs to be an DA. - dpm.setActiveAdmin(admin, /* replace =*/ false); + mServiceContext.binder.callingUid = + UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID); + runAsCaller(mServiceContext, dpms, dpm -> { + // PO needs to be a DA. + dpm.setActiveAdmin(admin, /*replace=*/ false); + // Fire! + assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); + // Check + assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE)); + }); - // Fire! - assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); - - // Check - assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE)); + mServiceContext.binder.restoreCallingIdentity(ident); } public void testHasNoFeature() throws Exception { - when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) + when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN))) .thenReturn(false); LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); - new DevicePolicyManagerServiceTestable(mContext, dataDir); + new DevicePolicyManagerServiceTestable(getServices(), mContext); // If the device has no DPMS feature, it shouldn't register the local service. assertNull(LocalServices.getService(DevicePolicyManagerInternal.class)); @@ -308,7 +310,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED), MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE)); - verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( + verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting( eq(admin1.getPackageName()), eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), eq(PackageManager.DONT_KILL_APP), @@ -347,7 +349,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called // again. (times(1) because it was previously called for admin1) - verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting( + verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting( eq(admin1.getPackageName()), eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT), eq(PackageManager.DONT_KILL_APP), @@ -386,7 +388,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { final int ANOTHER_USER_ID = 100; final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456); - mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. + getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user. // Set up pacakge manager for the other user. setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID); @@ -509,7 +511,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); // 1. User not unlocked. - when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) + when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) .thenReturn(false); try { dpm.removeActiveAdmin(admin1); @@ -522,7 +524,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); // 2. User unlocked. - when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) + when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE))) .thenReturn(true); dpm.removeActiveAdmin(admin1); @@ -657,7 +659,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Setup device owner. mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; mContext.packageName = admin1.getPackageName(); - doReturn(true).when(mContext.lockPatternUtils) + doReturn(true).when(getServices().lockPatternUtils) .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID); setupDeviceOwner(); @@ -740,11 +742,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; // Verify internal calls. - verify(mContext.iactivityManager, times(1)).updateDeviceOwner( + verify(getServices().iactivityManager, times(1)).updateDeviceOwner( eq(admin1.getPackageName())); // TODO We should check if the caller has called clearCallerIdentity(). - verify(mContext.ibackupManager, times(1)).setBackupServiceActive( + verify(getServices().ibackupManager, times(1)).setBackupServiceActive( eq(UserHandle.USER_SYSTEM), eq(false)); verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( @@ -949,28 +951,27 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); // Verify internal calls. - verify(mContext.iactivityManager, times(1)).updateDeviceOwner( + verify(getServices().iactivityManager, times(1)).updateDeviceOwner( eq(admin1.getPackageName())); assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); - when(mContext.userManager.hasUserRestriction(eq(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)); // Set up other mocks. - when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle()); + when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle()); // Now call clear. - doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser( - eq(admin1.getPackageName()), - anyInt()); + doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager). + getPackageUidAsUser(eq(admin1.getPackageName()), anyInt()); // But first pretend the user is locked. Then it should fail. - when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false); + when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false); try { dpm.clearDeviceOwnerApp(admin1.getPackageName()); fail("Didn't throw IllegalStateException"); @@ -979,18 +980,18 @@ public class DevicePolicyManagerTest extends DpmTestBase { "User must be running and unlocked", expected.getMessage()); } - when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true); - reset(mContext.userManagerInternal); + when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true); + reset(getServices().userManagerInternal); dpm.clearDeviceOwnerApp(admin1.getPackageName()); // Now DO shouldn't be set. assertNull(dpm.getDeviceOwnerComponentOnAnyUser()); - verify(mContext.userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER), + verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER), eq(false), MockUtils.checkUserHandle(UserHandle.USER_SYSTEM)); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), eq(null), eq(true), eq(CAMERA_NOT_DISABLED)); @@ -1024,7 +1025,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertTrue(dpm.setDeviceOwner(admin1, "owner-name")); // Verify internal calls. - verify(mContext.iactivityManager, times(1)).updateDeviceOwner( + verify(getServices().iactivityManager, times(1)).updateDeviceOwner( eq(admin1.getPackageName())); assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser()); @@ -1033,7 +1034,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_UID; // Now call clear. - doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser( + doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser( eq(admin1.getPackageName()), anyInt()); try { @@ -1056,14 +1057,17 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Try setting DO on the same user, which should fail. setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID); - dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); - try { - dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); - fail("IllegalStateException not thrown"); - } catch (IllegalStateException expected) { - assertTrue("Message was: " + expected.getMessage(), - expected.getMessage().contains("already has a profile owner")); - } + mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; + runAsCaller(mServiceContext, dpms, dpm -> { + dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE); + try { + dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE); + fail("IllegalStateException not thrown"); + } catch (IllegalStateException expected) { + assertTrue("Message was: " + expected.getMessage(), + expected.getMessage().contains("already has a profile owner")); + } + }); } public void testClearProfileOwner() throws Exception { @@ -1075,7 +1079,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE)); // First try when the user is locked, which should fail. - when(mContext.userManager.isUserUnlocked(anyInt())) + when(getServices().userManager.isUserUnlocked(anyInt())) .thenReturn(false); try { dpm.clearProfileOwner(admin1); @@ -1085,7 +1089,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { "User must be running and unlocked", expected.getMessage()); } // Clear, really. - when(mContext.userManager.isUserUnlocked(anyInt())) + when(getServices().userManager.isUserUnlocked(anyInt())) .thenReturn(true); dpm.clearProfileOwner(admin1); @@ -1110,7 +1114,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { final int ANOTHER_USER_ID = 100; final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456); - mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user. + getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user. mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS); mContext.callerPermissions.add(permission.MANAGE_USERS); @@ -1119,7 +1123,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); // Make sure the admin packge is installed to each user. setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID); @@ -1141,7 +1145,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID); // Set DO on the first non-system user. - mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); + getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true); assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE)); assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false)); @@ -1160,7 +1164,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { * finds the right component from a package name upon migration. */ public void testDeviceOwnerMigration() throws Exception { - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); checkDeviceOwnerWithMultipleDeviceAdmins(); // Overwrite the device owner setting and clears the clas name. @@ -1173,7 +1177,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName()); // Then create a new DPMS to have it load the settings from files. - when(mContext.userManager.getUserRestrictions(any(UserHandle.class))) + when(getServices().userManager.getUserRestrictions(any(UserHandle.class))) .thenReturn(new Bundle()); initializeDpms(); @@ -1227,8 +1231,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { */ private int setupPackageInPackageManager(final String packageName, final int appId) throws Exception { - return setupPackageInPackageManager( - packageName, DpmMockContext.CALLER_USER_HANDLE, appId, + return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId, ApplicationInfo.FLAG_HAS_CODE); } @@ -1241,31 +1244,29 @@ public class DevicePolicyManagerTest extends DpmTestBase { * @param flags flags to set in the ApplicationInfo for this package * @return the UID of the package as known by the mock package manager */ - private int setupPackageInPackageManager( - final String packageName, int userId, final int appId, int flags) - throws Exception { - // Make the PackageManager return the package instead of throwing a NameNotFoundException + private int setupPackageInPackageManager(final String packageName, int userId, final int appId, + int flags) throws Exception { + final int uid = UserHandle.getUid(userId, appId); + // Make the PackageManager return the package instead of throwing NameNotFoundException final PackageInfo pi = new PackageInfo(); pi.applicationInfo = new ApplicationInfo(); pi.applicationInfo.flags = flags; - doReturn(pi).when(mContext.ipackageManager).getPackageInfo( + doReturn(pi).when(getServices().ipackageManager).getPackageInfo( eq(packageName), anyInt(), eq(userId)); - doReturn(pi.applicationInfo).when(mContext.ipackageManager).getApplicationInfo( + doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo( eq(packageName), anyInt(), eq(userId)); - // Setup application UID with the PackageManager - final int uid = UserHandle.getUid(userId, appId); - doReturn(uid).when(mContext.packageManager).getPackageUidAsUser( + doReturn(uid).when(getServices().packageManager).getPackageUidAsUser( eq(packageName), eq(userId)); // Associate packageName to uid - doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid)); + doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid)); doReturn(new String[]{packageName}) - .when(mContext.ipackageManager).getPackagesForUid(eq(uid)); + .when(getServices().ipackageManager).getPackagesForUid(eq(uid)); return uid; } @@ -1276,7 +1277,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.applicationInfo = new ApplicationInfo(); mContext.callerPermissions.add(permission.MANAGE_USERS); mContext.packageName = "com.android.frameworks.servicestests"; - mContext.addPackageContext(user, mContext); + getServices().addPackageContext(user, mContext); when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE); StringParceledListSlice oneCert = asSlice(new String[] {"1"}); @@ -1286,20 +1287,20 @@ public class DevicePolicyManagerTest extends DpmTestBase { doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2)); // Given that we have exactly one certificate installed, - when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert); + when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert); // when that certificate is approved, dpms.approveCaCert(oneCert.getList().get(0), userId, true); // a notification should not be shown. - verify(mContext.notificationManager, timeout(1000)) + verify(getServices().notificationManager, timeout(1000)) .cancelAsUser(anyString(), anyInt(), eq(user)); // Given that we have four certificates installed, - when(mContext.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); // a notification should be shown saying that there are two certificates left to approve. - verify(mContext.notificationManager, timeout(1000)) + verify(getServices().notificationManager, timeout(1000)) .notifyAsUser(anyString(), anyInt(), argThat( new BaseMatcher() { @Override @@ -1528,35 +1529,35 @@ public class DevicePolicyManagerTest extends DpmTestBase { DpmTestUtils.newRestrictions(defaultRestrictions), dpm.getUserRestrictions(admin1) ); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(defaultRestrictions), eq(true) /* isDeviceOwner */, eq(CAMERA_NOT_DISABLED) ); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); for (String restriction : defaultRestrictions) { dpm.clearUserRestriction(admin1, restriction); } assertNoDeviceOwnerRestrictions(); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS, UserManager.DISALLOW_ADD_USER), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); DpmTestUtils.assertRestrictions( DpmTestUtils.newRestrictions( @@ -1570,11 +1571,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); DpmTestUtils.assertRestrictions( DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), @@ -1586,71 +1587,71 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); assertNoDeviceOwnerRestrictions(); // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when // DO sets them, the scope is global. dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, UserManager.DISALLOW_UNMUTE_MICROPHONE), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); // More tests. dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, UserManager.DISALLOW_ADD_USER), eq(true), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.setCameraDisabled(admin1, true); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), // DISALLOW_CAMERA will be applied to both local and global. MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, UserManager.DISALLOW_ADD_USER), eq(true), eq(CAMERA_DISABLED_GLOBALLY)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied // locally. dpm.setCameraDisabled(admin1, false); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID); dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM); dpm.setCameraDisabled(admin2, true); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN, UserManager.DISALLOW_ADD_USER), eq(true), eq(CAMERA_DISABLED_LOCALLY)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); // TODO Make sure restrictions are written to the file. } @@ -1664,19 +1665,19 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(DpmMockContext.CALLER_USER_HANDLE), MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES), eq(false), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(DpmMockContext.CALLER_USER_HANDLE), MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserManager.DISALLOW_OUTGOING_CALLS), eq(false), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); DpmTestUtils.assertRestrictions( DpmTestUtils.newRestrictions( @@ -1695,11 +1696,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(DpmMockContext.CALLER_USER_HANDLE), MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS), eq(false), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); DpmTestUtils.assertRestrictions( DpmTestUtils.newRestrictions( @@ -1716,11 +1717,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { ); dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(DpmMockContext.CALLER_USER_HANDLE), MockUtils.checkUserRestrictions(), eq(false), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); DpmTestUtils.assertRestrictions( DpmTestUtils.newRestrictions(), @@ -1735,22 +1736,22 @@ public class DevicePolicyManagerTest extends DpmTestBase { // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even // though when DO sets them they'll be applied globally. dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(DpmMockContext.CALLER_USER_HANDLE), MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, UserManager.DISALLOW_UNMUTE_MICROPHONE), eq(false), eq(CAMERA_NOT_DISABLED)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); dpm.setCameraDisabled(admin1, true); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(DpmMockContext.CALLER_USER_HANDLE), MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME, UserManager.DISALLOW_UNMUTE_MICROPHONE), eq(false), eq(CAMERA_DISABLED_LOCALLY)); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); // TODO Make sure restrictions are written to the file. } @@ -1786,13 +1787,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { DpmTestUtils.newRestrictions(defaultRestrictions), dpm.getUserRestrictions(admin1) ); - verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(defaultRestrictions), eq(true) /* isDeviceOwner */, eq(CAMERA_NOT_DISABLED) ); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); for (String restriction : defaultRestrictions) { dpm.clearUserRestriction(admin1, restriction); @@ -1801,7 +1802,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertNoDeviceOwnerRestrictions(); // Initialize DPMS again and check that the user restriction wasn't enabled again. - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); initializeDpms(); assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); assertNotNull(dpms.getDeviceOwnerAdminLocked()); @@ -1816,7 +1817,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { UserRestrictionsUtils .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction); try { - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); initializeDpms(); assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName())); assertNotNull(dpms.getDeviceOwnerAdminLocked()); @@ -1829,13 +1830,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { DpmTestUtils.newRestrictions(newDefaultEnabledRestriction), dpm.getUserRestrictions(admin1) ); - verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions( + verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions( eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(newDefaultEnabledRestriction), eq(true) /* isDeviceOwner */, eq(CAMERA_NOT_DISABLED) ); - reset(mContext.userManagerInternal); + reset(getServices().userManagerInternal); // Remove the restriction. dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction); @@ -1912,13 +1913,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertNull(dpm.getWifiMacAddress(admin1)); // 4-2. Returns WifiInfo, but with the default MAC. - when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); + when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo()); assertNull(dpm.getWifiMacAddress(admin1)); // 4-3. With a real MAC address. final WifiInfo wi = new WifiInfo(); wi.setMacAddress("11:22:33:44:55:66"); - when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi); + when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi); assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1)); } @@ -1958,7 +1959,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // admin1 is DO. // Set current call state of device to ringing. - when(mContext.telephonyManager.getCallState()) + when(getServices().telephonyManager.getCallState()) .thenReturn(TelephonyManager.CALL_STATE_RINGING); try { dpm.reboot(admin1); @@ -1968,7 +1969,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } // Set current call state of device to dialing/active. - when(mContext.telephonyManager.getCallState()) + when(getServices().telephonyManager.getCallState()) .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK); try { dpm.reboot(admin1); @@ -1978,7 +1979,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } // Set current call state of device to idle. - when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); + when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE); dpm.reboot(admin1); } @@ -2087,7 +2088,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertNull(intent); // Existing permission that is not set by device/profile owner returns null - when(mContext.userManager.hasUserRestriction( + when(getServices().userManager.hasUserRestriction( eq(UserManager.DISALLOW_ADJUST_VOLUME), eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(true); @@ -2095,7 +2096,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertNull(intent); // Permission that is set by device owner returns correct intent - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( eq(UserManager.DISALLOW_ADJUST_VOLUME), eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); @@ -2385,52 +2386,52 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.setActiveAdmin(admin1, /* replace =*/ false); dpm.setActiveAdmin(admin2, /* replace =*/ false); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin1, 0); verifyScreenTimeoutCall(null, false); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin1, 1); verifyScreenTimeoutCall(1, true); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin2, 10); verifyScreenTimeoutCall(null, false); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin1, 5); verifyScreenTimeoutCall(5, true); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin2, 4); verifyScreenTimeoutCall(4, true); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin1, 0); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE); verifyScreenTimeoutCall(Integer.MAX_VALUE, true); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1); verifyScreenTimeoutCall(Integer.MAX_VALUE, true); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); dpm.setMaximumTimeToLock(admin2, 10); verifyScreenTimeoutCall(10, true); - reset(mMockContext.powerManagerInternal); - reset(mMockContext.settings); + reset(getServices().powerManagerInternal); + reset(getServices().settings); // There's no restriction; shold be set to MAX. dpm.setMaximumTimeToLock(admin2, 0); @@ -2450,25 +2451,20 @@ public class DevicePolicyManagerTest extends DpmTestBase { // verify that the minimum timeout cannot be modified on user builds (system property is // not being read) - mContext.buildMock.isDebuggable = false; + 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); - verify(mContext.systemProperties, never()).getLong(anyString(), anyLong()); + verify(getServices().systemProperties, never()).getLong(anyString(), anyLong()); // restore to the debuggable build state - mContext.buildMock.isDebuggable = true; + getServices().buildMock.isDebuggable = true; // Always return the default (second arg) when getting system property for long type - when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer( - new Answer() { - @Override - public Long answer(InvocationOnMock invocation) throws Throwable { - return (Long) invocation.getArguments()[1]; - } - } + when(getServices().systemProperties.getLong(anyString(), anyLong())).thenAnswer( + invocation -> invocation.getArguments()[1] ); // reset to default (0 means the admin is not participating, so default should be returned) @@ -2526,10 +2522,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void verifyScreenTimeoutCall(Integer expectedTimeout, boolean shouldStayOnWhilePluggedInBeCleared) { if (expectedTimeout == null) { - verify(mMockContext.powerManagerInternal, times(0)) + verify(getServices().powerManagerInternal, times(0)) .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt()); } else { - verify(mMockContext.powerManagerInternal, times(1)) + verify(getServices().powerManagerInternal, times(1)) .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout)); } // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw @@ -2537,13 +2533,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_DeviceAdminFeatureOff() throws Exception { - when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) + when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) .thenReturn(false); - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(false); initializeDpms(); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(true); setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); @@ -2576,11 +2572,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_ManagedProfileFeatureOff() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(false); initializeDpms(); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(true); setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); @@ -2598,7 +2594,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false); // Test again when split user is on - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true); assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false); assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE, @@ -2620,7 +2616,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED); // Test again when split user is on - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, DevicePolicyManager.CODE_OK); assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, @@ -2633,10 +2629,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(true); setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); @@ -2671,10 +2667,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(true); setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); @@ -2692,9 +2688,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { final int MANAGED_PROFILE_USER_ID = 18; final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308); addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, false /* we can't remove a managed profile */)).thenReturn(false); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)).thenReturn(true); } @@ -2756,11 +2752,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); // The DO should be allowed to initiate provisioning if it set the restriction itself, but // other packages should be forbidden. - when(mContext.userManager.hasUserRestriction( + when(getServices().userManager.hasUserRestriction( eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(true); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); @@ -2782,11 +2778,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); // The DO should not be allowed to initiate provisioning if the restriction is set by // another entity. - when(mContext.userManager.hasUserRestriction( + when(getServices().userManager.hasUserRestriction( eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(true); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE), eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid)))) .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); @@ -2824,11 +2820,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { setup_nonSplitUser_withDo_primaryUser_ManagedProfile(); mContext.packageName = admin1.getPackageName(); mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS); - when(mContext.userManager.hasUserRestriction( + when(getServices().userManager.hasUserRestriction( eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), eq(UserHandle.SYSTEM))) .thenReturn(true); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), eq(UserHandle.SYSTEM))) .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); @@ -2848,10 +2844,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_firstBoot_systemUser() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(false); setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM); @@ -2887,10 +2883,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(false); setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); @@ -2927,10 +2923,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_firstBoot_primaryUser() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, true)).thenReturn(true); setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); @@ -2964,10 +2960,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception { - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, true)).thenReturn(true); setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE); @@ -3006,10 +3002,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception { setDeviceOwner(); - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true)) .thenReturn(false); setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM); @@ -3036,10 +3032,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception { setDeviceOwner(); - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, true)).thenReturn(true); setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); @@ -3067,16 +3063,16 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception { setDeviceOwner(); - when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) + when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0)) .thenReturn(true); - when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true); - when(mContext.userManager.hasUserRestriction( + when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true); + when(getServices().userManager.hasUserRestriction( eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))) .thenReturn(true); - when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, + when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, false /* we can't remove a managed profile */)).thenReturn(false); - when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, + when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE, true)).thenReturn(true); setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE); @@ -3144,7 +3140,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); // GIVEN it's user build - mContext.buildMock.isDebuggable = false; + getServices().buildMock.isDebuggable = false; assertTrue(dpms.hasUserSetupCompleted()); @@ -3169,7 +3165,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpms.mUserData.put(UserHandle.USER_SYSTEM, userData); // GIVEN it's userdebug build - mContext.buildMock.isDebuggable = true; + getServices().buildMock.isDebuggable = true; assertTrue(dpms.hasUserSetupCompleted()); @@ -3180,12 +3176,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void clearDeviceOwner() throws Exception { - final long ident = mContext.binder.clearCallingIdentity(); - mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; - doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager) + doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager) .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt()); - dpm.clearDeviceOwnerApp(admin1.getPackageName()); - mContext.binder.restoreCallingIdentity(ident); + + mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; + runAsCaller(mAdmin1Context, dpms, dpm -> { + dpm.clearDeviceOwnerApp(admin1.getPackageName()); + }); } public void testGetLastSecurityLogRetrievalTime() throws Exception { @@ -3194,7 +3191,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the // feature is disabled because there are non-affiliated secondary users. - mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE); + getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE); when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs)) .thenReturn(true); @@ -3203,9 +3200,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Enabling logging should not change the timestamp. dpm.setSecurityLoggingEnabled(admin1, true); - verify(mContext.settings) + verify(getServices().settings) .securityLogSetLoggingEnabledProperty(true); - when(mContext.settings.securityLogGetLoggingEnabledProperty()) + when(getServices().settings.securityLogGetLoggingEnabledProperty()) .thenReturn(true); assertEquals(-1, dpm.getLastSecurityLogRetrievalTime()); @@ -3269,7 +3266,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the // feature is disabled because there are non-affiliated secondary users. - mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE); + getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE); // No bug reports were requested so far. assertEquals(-1, dpm.getLastBugReportRequestTime()); @@ -3317,8 +3314,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the // feature is disabled because there are non-affiliated secondary users. - mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE); - when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject())) + getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE); + when(getServices().iipConnectivityMetrics.registerNetdEventCallback(anyObject())) .thenReturn(true); // No logs were retrieved so far. @@ -3389,7 +3386,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Add a secondary user, it should never talk with. final int ANOTHER_USER_ID = 36; - mContext.addUser(ANOTHER_USER_ID, 0); + getServices().addUser(ANOTHER_USER_ID, 0); // Since the managed profile is not affiliated, they should not be allowed to talk to each // other. @@ -3470,7 +3467,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setupDeviceOwner(); // Lock task packages are updated when loading user data. - verify(mContext.iactivityManager) + verify(getServices().iactivityManager) .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0])); // Set up a managed profile managed by different package (package name shouldn't matter) @@ -3479,7 +3476,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { final ComponentName adminDifferentPackage = new ComponentName("another.package", "whatever.class"); addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2); - verify(mContext.iactivityManager) + verify(getServices().iactivityManager) .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0])); // The DO can still set lock task packages @@ -3489,7 +3486,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1)); assertTrue(dpm.isLockTaskPermitted("doPackage1")); assertFalse(dpm.isLockTaskPermitted("anotherPackage")); - verify(mContext.iactivityManager) + verify(getServices().iactivityManager) .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages)); // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages. @@ -3520,14 +3517,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage)); assertTrue(dpm.isLockTaskPermitted("poPackage1")); assertFalse(dpm.isLockTaskPermitted("doPackage2")); - verify(mContext.iactivityManager) + verify(getServices().iactivityManager) .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages)); // Unaffiliate the profile, lock task mode no longer available on the profile. dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet()); assertFalse(dpm.isLockTaskPermitted("poPackage1")); // Lock task packages cleared when loading user data and when the user becomes unaffiliated. - verify(mContext.iactivityManager, times(2)) + verify(getServices().iactivityManager, times(2)) .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0])); mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; @@ -3591,11 +3588,11 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; // Even if the caller is the managed profile, the current user is the user 0 - when(mContext.iactivityManager.getCurrentUser()) + when(getServices().iactivityManager.getCurrentUser()) .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); dpm.wipeData(0); - verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed( + verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed( MANAGED_PROFILE_USER_ID); } @@ -3605,10 +3602,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); // Even if the caller is the managed profile, the current user is the user 0 - when(mContext.iactivityManager.getCurrentUser()) + when(getServices().iactivityManager.getCurrentUser()) .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, UserHandle.of(MANAGED_PROFILE_USER_ID))) .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); @@ -3624,19 +3621,19 @@ public class DevicePolicyManagerTest extends DpmTestBase { public void testWipeDataDeviceOwner() throws Exception { setDeviceOwner(); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_FACTORY_RESET, UserHandle.SYSTEM)) .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); dpm.wipeData(0); - verify(mContext.recoverySystem).rebootWipeUserData( + verify(getServices().recoverySystem).rebootWipeUserData( /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true)); } public void testWipeDataDeviceOwnerDisallowed() throws Exception { setDeviceOwner(); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_FACTORY_RESET, UserHandle.SYSTEM)) .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); @@ -3655,10 +3652,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); // Even if the caller is the managed profile, the current user is the user 0 - when(mContext.iactivityManager.getCurrentUser()) + when(getServices().iactivityManager.getCurrentUser()) .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, UserHandle.of(MANAGED_PROFILE_USER_ID))) .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER); @@ -3676,9 +3673,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because // both the user restriction and the policy were set by the PO. - verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed( + verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed( MANAGED_PROFILE_USER_ID); - verifyZeroInteractions(mContext.recoverySystem); + verifyZeroInteractions(getServices().recoverySystem); } public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed() @@ -3688,10 +3685,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1); // Even if the caller is the managed profile, the current user is the user 0 - when(mContext.iactivityManager.getCurrentUser()) + when(getServices().iactivityManager.getCurrentUser()) .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0)); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, UserHandle.of(MANAGED_PROFILE_USER_ID))) .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); @@ -3709,14 +3706,14 @@ public class DevicePolicyManagerTest extends DpmTestBase { // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is // not wiped. - verify(mContext.userManagerInternal, never()) + verify(getServices().userManagerInternal, never()) .removeUserEvenWhenDisallowed(anyInt()); - verifyZeroInteractions(mContext.recoverySystem); + verifyZeroInteractions(getServices().recoverySystem); } public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception { setDeviceOwner(); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_FACTORY_RESET, UserHandle.SYSTEM)) .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER); @@ -3731,13 +3728,13 @@ public class DevicePolicyManagerTest extends DpmTestBase { // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the // user restriction and the policy were set by the DO. - verify(mContext.recoverySystem).rebootWipeUserData( + verify(getServices().recoverySystem).rebootWipeUserData( /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true)); } public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception { setDeviceOwner(); - when(mContext.userManager.getUserRestrictionSource( + when(getServices().userManager.getUserRestrictionSource( UserManager.DISALLOW_FACTORY_RESET, UserHandle.SYSTEM)) .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM); @@ -3751,8 +3748,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM); // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped. - verifyZeroInteractions(mContext.recoverySystem); - verify(mContext.userManagerInternal, never()) + verifyZeroInteractions(getServices().recoverySystem); + verify(getServices().userManagerInternal, never()) .removeUserEvenWhenDisallowed(anyInt()); } @@ -3761,18 +3758,18 @@ public class DevicePolicyManagerTest extends DpmTestBase { final String app1 = "com.example.app1"; final String app2 = "com.example.app2"; - when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt())) + when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt())) .thenReturn(PackageManager.PERMISSION_GRANTED); - doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager) + doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager) .getPermissionFlags(permission, app1, UserHandle.SYSTEM); - when(mContext.packageManager.getPermissionFlags(permission, app1, + when(getServices().packageManager.getPermissionFlags(permission, app1, UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))) .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED); - when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt())) + when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt())) .thenReturn(PackageManager.PERMISSION_DENIED); - doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2, + doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2, UserHandle.SYSTEM); - when(mContext.packageManager.getPermissionFlags(permission, app2, + when(getServices().packageManager.getPermissionFlags(permission, app2, UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0); // System can retrieve permission grant state. @@ -3815,24 +3812,24 @@ public class DevicePolicyManagerTest extends DpmTestBase { final byte[] token = new byte[32]; final long handle = 123456; final String password = "password"; - when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM))) + when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM))) .thenReturn(handle); assertTrue(dpm.setResetPasswordToken(admin1, token)); // test password activation - when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM))) + when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM))) .thenReturn(true); assertTrue(dpm.isResetPasswordTokenActive(admin1)); // test reset password with token - when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password), + when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password), eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token), eq(UserHandle.USER_SYSTEM))) .thenReturn(true); assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0)); // test removing a token - when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM))) + when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM))) .thenReturn(true); assertTrue(dpm.clearResetPasswordToken(admin1)); } @@ -3892,23 +3889,27 @@ public class DevicePolicyManagerTest extends DpmTestBase { assertTrue(dpm.isActivePasswordSufficient()); } - private void setActivePasswordState(PasswordMetrics passwordMetrics) { - int userHandle = UserHandle.getUserId(mContext.binder.callingUid); + private void setActivePasswordState(PasswordMetrics passwordMetrics) + throws Exception { + final int userHandle = UserHandle.getUserId(mContext.binder.callingUid); final long ident = mContext.binder.clearCallingIdentity(); - try { - dpm.setActivePasswordState(passwordMetrics, userHandle); - dpm.reportPasswordChanged(userHandle); - final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED); - intent.setComponent(admin1); - intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid)); + dpm.setActivePasswordState(passwordMetrics, userHandle); + dpm.reportPasswordChanged(userHandle); - verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( - MockUtils.checkIntent(intent), - MockUtils.checkUserHandle(userHandle)); - } finally { - mContext.binder.restoreCallingIdentity(ident); - } + final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED); + intent.setComponent(admin1); + intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid)); + + verify(mContext.spiedContext, times(1)).sendBroadcastAsUser( + MockUtils.checkIntent(intent), + MockUtils.checkUserHandle(userHandle)); + + // CertificateMonitor.updateInstalledCertificates is called on the background thread, + // let it finish with system uid, otherwise it will throw and crash. + flushTasks(); + + mContext.binder.restoreCallingIdentity(ident); } public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception { @@ -3932,12 +3933,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Device owner changes IME for first user. mContext.binder.callingUid = deviceOwnerUid; - when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM)) + when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM)) .thenReturn("ime1"); dpm.setSecureSetting(admin1, currentIme, "ime2"); - verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2", + verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2", UserHandle.USER_SYSTEM); - reset(mContext.settings); + reset(getServices().settings); dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM); mContext.binder.callingUid = firstUserSystemUid; assertTrue(dpm.isCurrentInputMethodSetByOwner()); @@ -3960,10 +3961,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Device owner changes IME for first user again. mContext.binder.callingUid = deviceOwnerUid; - when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM)) + when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM)) .thenReturn("ime2"); dpm.setSecureSetting(admin1, currentIme, "ime3"); - verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3", + verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3", UserHandle.USER_SYSTEM); dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM); mContext.binder.callingUid = firstUserSystemUid; @@ -4011,12 +4012,12 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Profile owner changes IME for second user. mContext.binder.callingUid = profileOwnerUid; - when(mContext.settings.settingsSecureGetStringForUser(currentIme, + when(getServices().settings.settingsSecureGetStringForUser(currentIme, DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1"); dpm.setSecureSetting(admin1, currentIme, "ime2"); - verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2", + verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2", DpmMockContext.CALLER_USER_HANDLE); - reset(mContext.settings); + reset(getServices().settings); dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE); mContext.binder.callingUid = firstUserSystemUid; assertFalse(dpm.isCurrentInputMethodSetByOwner()); @@ -4039,10 +4040,10 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Profile owner changes IME for second user again. mContext.binder.callingUid = profileOwnerUid; - when(mContext.settings.settingsSecureGetStringForUser(currentIme, + when(getServices().settings.settingsSecureGetStringForUser(currentIme, DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2"); dpm.setSecureSetting(admin1, currentIme, "ime3"); - verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3", + verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3", DpmMockContext.CALLER_USER_HANDLE); dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE); mContext.binder.callingUid = firstUserSystemUid; @@ -4101,7 +4102,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Attempt to set to empty list (which means no listener is whitelisted) mContext.binder.callingUid = adminUid; assertFalse(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.emptyList())); + admin1, Collections.emptyList())); assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1)); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; @@ -4178,7 +4179,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; assertTrue(dpms.setPermittedCrossProfileNotificationListeners( admin1, Collections.singletonList(permittedListener))); - List permittedListeners = + final List permittedListeners = dpms.getPermittedCrossProfileNotificationListeners(admin1); assertEquals(1, permittedListeners.size()); assertEquals(permittedListener, permittedListeners.get(0)); @@ -4195,7 +4196,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // Setting an empty whitelist - only system listeners allowed mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; assertTrue(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.emptyList())); + admin1, Collections.emptyList())); assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size()); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; @@ -4259,7 +4260,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { // all allowed in primary profile mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID; assertTrue(dpms.setPermittedCrossProfileNotificationListeners( - admin1, Collections.emptyList())); + admin1, Collections.emptyList())); assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size()); mContext.binder.callingUid = DpmMockContext.SYSTEM_UID; @@ -4274,39 +4275,38 @@ public class DevicePolicyManagerTest extends DpmTestBase { } public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception { - mContext.packageName = mRealTestContext.getPackageName(); + mServiceContext.packageName = mRealTestContext.getPackageName(); + mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; + mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; setDeviceOwner(); - final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller"); - caller.packageName = admin1.getPackageName(); - caller.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID; - - verifyCanGetOwnerInstalledCaCerts(admin1, caller); + verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context); } public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception { - mContext.packageName = mRealTestContext.getPackageName(); + mServiceContext.packageName = mRealTestContext.getPackageName(); + mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; + mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID; setAsProfileOwner(admin1); - final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller"); - caller.packageName = admin1.getPackageName(); - caller.binder.callingUid = DpmMockContext.CALLER_UID; - - verifyCanGetOwnerInstalledCaCerts(admin1, caller); - verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, caller); + verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context); + verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context); } public void testGetOwnerInstalledCaCertsForDelegate() throws Exception { - mContext.packageName = mRealTestContext.getPackageName(); + mServiceContext.packageName = mRealTestContext.getPackageName(); + mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; + mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID; setAsProfileOwner(admin1); - final String delegate = "com.example.delegate"; - final int delegateUid = setupPackageInPackageManager(delegate, 20988); - dpm.setCertInstallerPackage(admin1, delegate); + final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext); + caller.packageName = "com.example.delegate"; + caller.binder.callingUid = setupPackageInPackageManager(caller.packageName, + DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE); - final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller"); - caller.packageName = delegate; - caller.binder.callingUid = delegateUid; + // Make caller a delegated cert installer. + runAsCaller(mAdmin1Context, dpms, + dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName)); verifyCanGetOwnerInstalledCaCerts(null, caller); verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller); @@ -4318,13 +4318,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { final byte[] caCert = TEST_CA.getBytes(); // device admin (used for posting the tls notification) - final DpmMockContext admin1Context; + DpmMockContext admin1Context = mAdmin1Context; if (admin1.getPackageName().equals(callerContext.getPackageName())) { admin1Context = callerContext; - } else { - admin1Context = new DpmMockContext(mRealTestContext, "test-admin"); - admin1Context.packageName = admin1.getPackageName(); - admin1Context.applicationInfo = new ApplicationInfo(); } when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE); @@ -4335,21 +4331,21 @@ public class DevicePolicyManagerTest extends DpmTestBase { // system_server final DpmMockContext serviceContext = mContext; serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - serviceContext.addPackageContext(callerUser, admin1Context); - serviceContext.addPackageContext(callerUser, callerContext); + getServices().addPackageContext(callerUser, admin1Context); + getServices().addPackageContext(callerUser, callerContext); // Install a CA cert. runAsCaller(callerContext, dpms, (dpm) -> { - when(mContext.keyChainConnection.getService().installCaCertificate(caCert)) + when(getServices().keyChainConnection.getService().installCaCertificate(caCert)) .thenReturn(alias); assertTrue(dpm.installCaCert(caller, caCert)); - when(mContext.keyChainConnection.getService().getUserCaAliases()) + when(getServices().keyChainConnection.getService().getUserCaAliases()) .thenReturn(asSlice(new String[] {alias})); - }); - serviceContext.injectBroadcast(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(); final List ownerInstalledCaCerts = new ArrayList<>(); @@ -4357,26 +4353,26 @@ 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 installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser); - assertEquals(Arrays.asList(alias), installedCaCerts); + assertEquals(Collections.singletonList(alias), installedCaCerts); ownerInstalledCaCerts.addAll(installedCaCerts); }); // Restarting the DPMS should not lose information. initializeDpms(); - runAsCaller(admin1Context, dpms, (dpm) -> { - assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)); - }); + runAsCaller(admin1Context, dpms, (dpm) -> + assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser))); // System can find out which CA certs were installed by the Device Owner / Profile Owner. runAsCaller(serviceContext, dpms, (dpm) -> { assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)); // Remove the CA cert. - reset(mContext.keyChainConnection.getService()); + reset(getServices().keyChainConnection.getService()); }); - serviceContext.injectBroadcast(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(); // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile @@ -4392,13 +4388,9 @@ public class DevicePolicyManagerTest extends DpmTestBase { final byte[] caCert = TEST_CA.getBytes(); // device admin (used for posting the tls notification) - final DpmMockContext admin1Context; + DpmMockContext admin1Context = mAdmin1Context; if (admin1.getPackageName().equals(callerContext.getPackageName())) { admin1Context = callerContext; - } else { - admin1Context = new DpmMockContext(mRealTestContext, "test-admin"); - admin1Context.packageName = admin1.getPackageName(); - admin1Context.applicationInfo = new ApplicationInfo(); } when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE); @@ -4409,27 +4401,26 @@ public class DevicePolicyManagerTest extends DpmTestBase { // system_server final DpmMockContext serviceContext = mContext; serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID; - serviceContext.addPackageContext(callerUser, admin1Context); - serviceContext.addPackageContext(callerUser, callerContext); + getServices().addPackageContext(callerUser, admin1Context); + getServices().addPackageContext(callerUser, callerContext); // Install a CA cert as caller runAsCaller(callerContext, dpms, (dpm) -> { - when(mContext.keyChainConnection.getService().installCaCertificate(caCert)) + when(getServices().keyChainConnection.getService().installCaCertificate(caCert)) .thenReturn(alias); assertTrue(dpm.installCaCert(callerName, caCert)); }); // Fake the CA cert as having been installed - when(serviceContext.keyChainConnection.getService().getUserCaAliases()) + when(getServices().keyChainConnection.getService().getUserCaAliases()) .thenReturn(asSlice(new String[] {alias})); - serviceContext.injectBroadcast(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(); // Removing the Profile Owner should clear the information on which CA certs were installed - runAsCaller(admin1Context, dpms, (dpm) -> { - dpm.clearProfileOwner(admin1); - }); + runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1)); runAsCaller(serviceContext, dpms, (dpm) -> { final List ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser); @@ -4439,7 +4430,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { } private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) { - when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, + when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, userhandle)).thenReturn(isUserSetupComplete ? 1 : 0); dpms.notifyChangeToContentObserver( Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle); @@ -4452,8 +4443,8 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void assertProvisioningAllowed(String action, boolean expected, String packageName, int uid) { - String previousPackageName = mContext.packageName; - int previousUid = mMockContext.binder.callingUid; + final String previousPackageName = mContext.packageName; + final int previousUid = mMockContext.binder.callingUid; // Call assertProvisioningAllowed with the packageName / uid passed as arguments. mContext.packageName = packageName; @@ -4486,7 +4477,7 @@ public class DevicePolicyManagerTest extends DpmTestBase { private void addManagedProfile( ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception { final int userId = UserHandle.getUserId(adminUid); - mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM); + getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM); mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS); setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin); dpm.setActiveAdmin(admin, false, userId); @@ -4507,6 +4498,6 @@ public class DevicePolicyManagerTest extends DpmTestBase { // We can't let exceptions happen on the background thread. Throw them here if they happen // so they still cause the test to fail despite being suppressed. - mContext.rethrowBackgroundBroadcastExceptions(); + getServices().rethrowBackgroundBroadcastExceptions(); } } diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java b/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java index 87106ec7b9180..408ee9c933a9b 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/DpmMockContext.java @@ -16,61 +16,27 @@ package com.android.server.devicepolicy; -import android.accounts.Account; -import android.accounts.AccountManager; -import android.app.AlarmManager; -import android.app.IActivityManager; -import android.app.NotificationManager; -import android.app.backup.IBackupManager; +import static org.mockito.Mockito.mock; + import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; -import android.content.pm.IPackageManager; import android.content.pm.PackageManager; -import android.content.pm.PackageManagerInternal; -import android.content.pm.UserInfo; import android.content.res.Resources; -import android.media.IAudioService; -import android.net.IIpConnectivityMetrics; -import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; -import android.os.PowerManager.WakeLock; -import android.os.PowerManagerInternal; import android.os.UserHandle; -import android.os.UserManager; -import android.os.UserManagerInternal; -import android.security.KeyChain; -import android.telephony.TelephonyManager; -import android.test.mock.MockContentResolver; import android.test.mock.MockContext; import android.util.ArrayMap; -import android.util.Pair; -import android.view.IWindowManager; - -import com.android.internal.widget.LockPatternUtils; import org.junit.Assert; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; - -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; /** * Context used throughout DPMS tests. @@ -107,9 +73,10 @@ public class DpmMockContext extends MockContext { public static final int SYSTEM_PID = 11111; public static final String ANOTHER_PACKAGE_NAME = "com.another.package.name"; - public static final int ANOTHER_UID = UserHandle.getUid(UserHandle.USER_SYSTEM, 18434); + private final MockSystemServices mMockSystemServices; + public static class MockBinder { public int callingUid = CALLER_UID; public int callingPid = CALLER_PID; @@ -144,130 +111,7 @@ public class DpmMockContext extends MockContext { } } - public static class EnvironmentForMock { - public File getUserSystemDirectory(int userId) { - return null; - } - } - - public static class BuildMock { - public boolean isDebuggable = true; - } - - public static class PowerManagerForMock { - public WakeLock newWakeLock(int levelAndFlags, String tag) { - return null; - } - - public void goToSleep(long time, int reason, int flags) { - } - - public void reboot(String reason) { - } - } - - public static class RecoverySystemForMock { - public void rebootWipeUserData( - boolean shutdown, String reason, boolean force) throws IOException { - } - } - - public static class SystemPropertiesForMock { - public boolean getBoolean(String key, boolean def) { - return false; - } - - public long getLong(String key, long def) { - return 0; - } - - public String get(String key, String def) { - return null; - } - - public String get(String key) { - return null; - } - - public void set(String key, String value) { - } - } - - public static class UserManagerForMock { - public boolean isSplitSystemUser() { - return false; - } - } - - public static class SettingsForMock { - public int settingsSecureGetIntForUser(String name, int def, int userHandle) { - return 0; - } - - public String settingsSecureGetStringForUser(String name, int userHandle) { - return null; - } - - public void settingsSecurePutIntForUser(String name, int value, int userHandle) { - } - - public void settingsSecurePutStringForUser(String name, String value, int userHandle) { - } - - public void settingsGlobalPutStringForUser(String name, String value, int userHandle) { - } - - public void settingsSecurePutInt(String name, int value) { - } - - public void settingsGlobalPutInt(String name, int value) { - } - - public void settingsSecurePutString(String name, String value) { - } - - public void settingsGlobalPutString(String name, String value) { - } - - public int settingsGlobalGetInt(String name, int value) { - return 0; - } - - public String settingsGlobalGetString(String name) { - return ""; - } - - public void securityLogSetLoggingEnabledProperty(boolean enabled) { - } - - public boolean securityLogGetLoggingEnabledProperty() { - return false; - } - - public boolean securityLogIsLoggingEnabled() { - return false; - } - } - - public static class StorageManagerForMock { - public boolean isFileBasedEncryptionEnabled() { - return false; - } - - public boolean isNonDefaultBlockEncrypted() { - return false; - } - - public boolean isEncrypted() { - return false; - } - - public boolean isEncryptable() { - return false; - } - } - - public final Context realTestContext; + private final Context realTestContext; /** * Use this instance to verify unimplemented methods such as {@link #sendBroadcast}. @@ -276,39 +120,8 @@ public class DpmMockContext extends MockContext { */ public final Context spiedContext; - public final File dataDir; - public final File systemUserDataDir; - public final MockBinder binder; - public final EnvironmentForMock environment; public final Resources resources; - public final SystemPropertiesForMock systemProperties; - public final UserManager userManager; - public final UserManagerInternal userManagerInternal; - public final PackageManagerInternal packageManagerInternal; - public final UserManagerForMock userManagerForMock; - public final PowerManagerForMock powerManager; - public final PowerManagerInternal powerManagerInternal; - public final RecoverySystemForMock recoverySystem; - public final NotificationManager notificationManager; - public final IIpConnectivityMetrics iipConnectivityMetrics; - public final IWindowManager iwindowManager; - public final IActivityManager iactivityManager; - public final IPackageManager ipackageManager; - public final IBackupManager ibackupManager; - public final IAudioService iaudioService; - public final LockPatternUtils lockPatternUtils; - public final StorageManagerForMock storageManager; - public final WifiManager wifiManager; - public final SettingsForMock settings; - public final MockContentResolver contentResolver; - public final TelephonyManager telephonyManager; - public final AccountManager accountManager; - public final AlarmManager alarmManager; - public final KeyChain.KeyChainConnection keyChainConnection; - - /** Note this is a partial mock, not a real mock. */ - public final PackageManager packageManager; /** TODO: Migrate everything to use {@link #permissions} to avoid confusion. */ @Deprecated @@ -317,246 +130,17 @@ public class DpmMockContext extends MockContext { /** Less confusing alias for {@link #callerPermissions}. */ public final List permissions = callerPermissions; - private final ArrayList mUserInfos = new ArrayList<>(); - - public final BuildMock buildMock = new BuildMock(); - - /** Optional mapping of other user contexts for {@link #createPackageContextAsUser} to return */ - public final Map, Context> userPackageContexts = new ArrayMap<>(); - public String packageName = null; public ApplicationInfo applicationInfo = null; - // We have to keep track of broadcast receivers registered for a given intent ourselves as the - // DPM unit tests mock out the package manager and PackageManager.queryBroadcastReceivers() does - // not work. - private class BroadcastReceiverRegistration { - public final BroadcastReceiver receiver; - public final IntentFilter filter; - public final Handler scheduler; - - // Exceptions thrown in a background thread kill the whole test. Save them instead. - public final AtomicReference backgroundException = new AtomicReference<>(); - - public BroadcastReceiverRegistration(BroadcastReceiver receiver, IntentFilter filter, - Handler scheduler) { - this.receiver = receiver; - this.filter = filter; - this.scheduler = scheduler; - } - - public void sendBroadcastIfApplicable(int userId, Intent intent) { - final BroadcastReceiver.PendingResult result = new BroadcastReceiver.PendingResult( - 0 /* resultCode */, null /* resultData */, null /* resultExtras */, - 0 /* type */, false /* ordered */, false /* sticky */, null /* token */, userId, - 0 /* flags */); - if (filter.match(null, intent, false, "DpmMockContext") > 0) { - final Runnable send = () -> { - receiver.setPendingResult(result); - receiver.onReceive(DpmMockContext.this, intent); - }; - if (scheduler != null) { - scheduler.post(() -> { - try { - send.run(); - } catch (Exception e) { - backgroundException.compareAndSet(null, e); - } - }); - } else { - send.run(); - } - } - } - } - private List mBroadcastReceivers = new ArrayList<>(); - - public DpmMockContext(Context realTestContext, String name) { - this(realTestContext, new File(realTestContext.getCacheDir(), name)); - } - - public DpmMockContext(Context context, File dataDir) { + public DpmMockContext(MockSystemServices mockSystemServices, Context context) { + mMockSystemServices = mockSystemServices; realTestContext = context; - this.dataDir = dataDir; - DpmTestUtils.clearDir(dataDir); - binder = new MockBinder(); - environment = mock(EnvironmentForMock.class); resources = mock(Resources.class); - systemProperties = mock(SystemPropertiesForMock.class); - userManager = mock(UserManager.class); - userManagerInternal = mock(UserManagerInternal.class); - userManagerForMock = mock(UserManagerForMock.class); - packageManagerInternal = mock(PackageManagerInternal.class); - powerManager = mock(PowerManagerForMock.class); - powerManagerInternal = mock(PowerManagerInternal.class); - recoverySystem = mock(RecoverySystemForMock.class); - notificationManager = mock(NotificationManager.class); - iipConnectivityMetrics = mock(IIpConnectivityMetrics.class); - iwindowManager = mock(IWindowManager.class); - iactivityManager = mock(IActivityManager.class); - ipackageManager = mock(IPackageManager.class); - ibackupManager = mock(IBackupManager.class); - iaudioService = mock(IAudioService.class); - lockPatternUtils = mock(LockPatternUtils.class); - storageManager = mock(StorageManagerForMock.class); - wifiManager = mock(WifiManager.class); - settings = mock(SettingsForMock.class); - telephonyManager = mock(TelephonyManager.class); - accountManager = mock(AccountManager.class); - alarmManager = mock(AlarmManager.class); - keyChainConnection = mock(KeyChain.KeyChainConnection.class, RETURNS_DEEP_STUBS); - - // Package manager is huge, so we use a partial mock instead. - packageManager = spy(context.getPackageManager()); - spiedContext = mock(Context.class); - - contentResolver = new MockContentResolver(); - - // Add the system user with a fake profile group already set up (this can happen in the real - // world if a managed profile is added and then removed). - systemUserDataDir = - addUser(UserHandle.USER_SYSTEM, UserInfo.FLAG_PRIMARY, UserHandle.USER_SYSTEM); - - // System user is always running. - setUserRunning(UserHandle.USER_SYSTEM, true); - } - - public File addUser(int userId, int flags) { - return addUser(userId, flags, UserInfo.NO_PROFILE_GROUP_ID); - } - - public File addUser(int userId, int flags, int profileGroupId) { - // Set up (default) UserInfo for CALLER_USER_HANDLE. - final UserInfo uh = new UserInfo(userId, "user" + userId, flags); - uh.profileGroupId = profileGroupId; - when(userManager.getUserInfo(eq(userId))).thenReturn(uh); - - mUserInfos.add(uh); - when(userManager.getUsers()).thenReturn(mUserInfos); - when(userManager.getUsers(anyBoolean())).thenReturn(mUserInfos); - when(userManager.isUserRunning(eq(new UserHandle(userId)))).thenReturn(true); - when(userManager.getUserInfo(anyInt())).thenAnswer( - new Answer() { - @Override - public UserInfo answer(InvocationOnMock invocation) throws Throwable { - final int userId = (int) invocation.getArguments()[0]; - return getUserInfo(userId); - } - } - ); - when(userManager.getProfiles(anyInt())).thenAnswer( - new Answer>() { - @Override - public List answer(InvocationOnMock invocation) throws Throwable { - final int userId = (int) invocation.getArguments()[0]; - return getProfiles(userId); - } - } - ); - when(userManager.getProfileIdsWithDisabled(anyInt())).thenAnswer( - new Answer() { - @Override - public int[] answer(InvocationOnMock invocation) throws Throwable { - final int userId = (int) invocation.getArguments()[0]; - List profiles = getProfiles(userId); - return profiles.stream() - .mapToInt(profile -> profile.id) - .toArray(); - } - } - ); - when(accountManager.getAccountsAsUser(anyInt())).thenReturn(new Account[0]); - - // Create a data directory. - final File dir = new File(dataDir, "users/" + userId); - DpmTestUtils.clearDir(dir); - - when(environment.getUserSystemDirectory(eq(userId))).thenReturn(dir); - return dir; - } - - public void removeUser(int userId) { - for (int i = 0; i < mUserInfos.size(); i++) { - if (mUserInfos.get(i).id == userId) { - mUserInfos.remove(i); - break; - } - } - when(userManager.getUserInfo(eq(userId))).thenReturn(null); - - when(userManager.isUserRunning(eq(new UserHandle(userId)))).thenReturn(false); - } - - private UserInfo getUserInfo(int userId) { - for (UserInfo ui : mUserInfos) { - if (ui.id == userId) { - return ui; - } - } - return null; - } - - private List getProfiles(int userId) { - final ArrayList ret = new ArrayList(); - UserInfo parent = null; - for (UserInfo ui : mUserInfos) { - if (ui.id == userId) { - parent = ui; - break; - } - } - if (parent == null) { - return ret; - } - for (UserInfo ui : mUserInfos) { - if (ui == parent - || ui.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID - && ui.profileGroupId == parent.profileGroupId) { - ret.add(ui); - } - } - return ret; - } - - /** - * Add multiple users at once. They'll all have flag 0. - */ - public void addUsers(int... userIds) { - for (int userId : userIds) { - addUser(userId, 0); - } - } - - public void setUserRunning(int userId, boolean isRunning) { - when(userManager.isUserRunning(MockUtils.checkUserHandle(userId))) - .thenReturn(isRunning); - } - - public void injectBroadcast(final Intent intent) { - final int userId = UserHandle.getUserId(binder.getCallingUid()); - for (final BroadcastReceiverRegistration receiver : mBroadcastReceivers) { - receiver.sendBroadcastIfApplicable(userId, intent); - } - } - - public void rethrowBackgroundBroadcastExceptions() throws Exception { - for (final BroadcastReceiverRegistration receiver : mBroadcastReceivers) { - final Exception e = receiver.backgroundException.getAndSet(null); - if (e != null) { - throw e; - } - } - } - - public void addPackageContext(UserHandle user, Context context) { - if (context.getPackageName() == null) { - throw new NullPointerException("getPackageName() == null"); - } - userPackageContexts.put(new Pair<>(user, context.getPackageName()), context); } @Override @@ -589,15 +173,15 @@ public class DpmMockContext extends MockContext { public Object getSystemService(String name) { switch (name) { case Context.ALARM_SERVICE: - return alarmManager; + return mMockSystemServices.alarmManager; case Context.USER_SERVICE: - return userManager; + return mMockSystemServices.userManager; case Context.POWER_SERVICE: - return powerManager; + return mMockSystemServices.powerManager; case Context.WIFI_SERVICE: - return wifiManager; + return mMockSystemServices.wifiManager; case Context.ACCOUNT_SERVICE: - return accountManager; + return mMockSystemServices.accountManager; } throw new UnsupportedOperationException(); } @@ -609,22 +193,21 @@ public class DpmMockContext extends MockContext { @Override public PackageManager getPackageManager() { - return packageManager; + return mMockSystemServices.packageManager; } @Override public void enforceCallingOrSelfPermission(String permission, String message) { - if (binder.getCallingUid() == SYSTEM_UID) { + if (UserHandle.isSameApp(binder.getCallingUid(), SYSTEM_UID)) { return; // Assume system has all permissions. } - List permissions = binder.callingPermissions.get(binder.getCallingUid()); if (permissions == null) { // TODO: delete the following line. to do this without breaking any tests, first it's // necessary to remove all tests that set it directly. permissions = callerPermissions; -// throw new UnsupportedOperationException( -// "Caller UID " + binder.getCallingUid() + " doesn't exist"); + // throw new UnsupportedOperationException( + // "Caller UID " + binder.getCallingUid() + " doesn't exist"); } if (!permissions.contains(permission)) { throw new SecurityException("Caller doesn't have " + permission + " : " + message); @@ -773,44 +356,40 @@ public class DpmMockContext extends MockContext { @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { - mBroadcastReceivers.add(new BroadcastReceiverRegistration(receiver, filter, null)); + mMockSystemServices.registerReceiver(receiver, filter, null); return spiedContext.registerReceiver(receiver, filter); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { - mBroadcastReceivers.add(new BroadcastReceiverRegistration(receiver, filter, scheduler)); + mMockSystemServices.registerReceiver(receiver, filter, scheduler); return spiedContext.registerReceiver(receiver, filter, broadcastPermission, scheduler); } @Override public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler) { - mBroadcastReceivers.add(new BroadcastReceiverRegistration(receiver, filter, scheduler)); + mMockSystemServices.registerReceiver(receiver, filter, scheduler); return spiedContext.registerReceiverAsUser(receiver, user, filter, broadcastPermission, scheduler); } @Override public void unregisterReceiver(BroadcastReceiver receiver) { - mBroadcastReceivers.removeIf(r -> r.receiver == receiver); + mMockSystemServices.unregisterReceiver(receiver); spiedContext.unregisterReceiver(receiver); } @Override public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) throws PackageManager.NameNotFoundException { - final Pair key = new Pair<>(user, packageName); - if (userPackageContexts.containsKey(key)) { - return userPackageContexts.get(key); - } - throw new UnsupportedOperationException("No package " + packageName + " for user " + user); + return mMockSystemServices.createPackageContextAsUser(packageName, flags, user); } @Override public ContentResolver getContentResolver() { - return contentResolver; + return mMockSystemServices.contentResolver; } @Override 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 5d68edd6f66b4..e0ea5734d3b84 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,10 @@ package com.android.server.devicepolicy; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; + import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; @@ -28,20 +32,14 @@ import android.content.pm.ResolveInfo; import android.os.UserHandle; import android.test.AndroidTestCase; -import java.io.File; import java.util.List; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doReturn; - public abstract class DpmTestBase extends AndroidTestCase { public static final String TAG = "DpmTest"; protected Context mRealTestContext; protected DpmMockContext mMockContext; - - public File dataDir; + private MockSystemServices mServices; public ComponentName admin1; public ComponentName admin2; @@ -55,8 +53,8 @@ public abstract class DpmTestBase extends AndroidTestCase { mRealTestContext = super.getContext(); - mMockContext = new DpmMockContext( - mRealTestContext, new File(mRealTestContext.getCacheDir(), "test-data")); + mServices = new MockSystemServices(mRealTestContext, "test-data"); + mMockContext = new DpmMockContext(mServices, mRealTestContext); admin1 = new ComponentName(mRealTestContext, DummyDeviceAdmins.Admin1.class); admin2 = new ComponentName(mRealTestContext, DummyDeviceAdmins.Admin2.class); @@ -71,12 +69,16 @@ public abstract class DpmTestBase extends AndroidTestCase { return mMockContext; } + public MockSystemServices getServices() { + return mServices; + } + protected interface DpmRunnable { - public void run(DevicePolicyManager dpm) throws Exception; + void run(DevicePolicyManager dpm) throws Exception; } /** - * Simulate an RPC from {@param caller} to the service context ({@link #mContext}). + * Simulate an RPC from {@param caller} to the service context ({@link #mMockContext}). * * The caller sees its own context. The server also sees its own separate context, with the * appropriate calling UID and calling permissions fields already set up. @@ -85,12 +87,15 @@ public abstract class DpmTestBase extends AndroidTestCase { DpmRunnable action) { final DpmMockContext serviceContext = mMockContext; + // Save calling UID and PID before clearing identity so we don't run into aliasing issues. + final int callingUid = caller.binder.callingUid; + final int callingPid = caller.binder.callingPid; + final long origId = serviceContext.binder.clearCallingIdentity(); try { - serviceContext.binder.callingUid = caller.binder.callingUid; - serviceContext.binder.callingPid = caller.binder.callingPid; - serviceContext.binder.callingPermissions.put(caller.binder.callingUid, - caller.permissions); + serviceContext.binder.callingUid = callingUid; + serviceContext.binder.callingPid = callingPid; + serviceContext.binder.callingPermissions.put(callingUid, caller.permissions); action.run(new DevicePolicyManagerTestable(caller, dpms)); } catch (Exception e) { throw new AssertionError(e); @@ -99,7 +104,7 @@ public abstract class DpmTestBase extends AndroidTestCase { } } - protected void markPackageAsInstalled(String packageName, ApplicationInfo ai, int userId) + private void markPackageAsInstalled(String packageName, ApplicationInfo ai, int userId) throws Exception { final PackageInfo pi = DpmTestUtils.cloneParcelable( mRealTestContext.getPackageManager().getPackageInfo( @@ -110,12 +115,12 @@ public abstract class DpmTestBase extends AndroidTestCase { pi.applicationInfo = ai; } - doReturn(pi).when(mMockContext.ipackageManager).getPackageInfo( + doReturn(pi).when(mServices.ipackageManager).getPackageInfo( eq(packageName), eq(0), eq(userId)); - doReturn(ai.uid).when(mMockContext.packageManager).getPackageUidAsUser( + doReturn(ai.uid).when(mServices.packageManager).getPackageUidAsUser( eq(packageName), eq(userId)); } @@ -151,7 +156,7 @@ public abstract class DpmTestBase extends AndroidTestCase { * @param copyFromAdmin package information for {@code admin} will be built based on this * component's information. */ - protected void setUpPackageManagerForFakeAdmin(ComponentName admin, int packageUid, + private void setUpPackageManagerForFakeAdmin(ComponentName admin, int packageUid, Integer enabledSetting, Integer appTargetSdk, ComponentName copyFromAdmin) throws Exception { @@ -171,7 +176,7 @@ public abstract class DpmTestBase extends AndroidTestCase { ai.packageName = admin.getPackageName(); ai.name = admin.getClassName(); - doReturn(ai).when(mMockContext.ipackageManager).getApplicationInfo( + doReturn(ai).when(mServices.ipackageManager).getApplicationInfo( eq(admin.getPackageName()), anyInt(), eq(UserHandle.getUserId(packageUid))); @@ -198,12 +203,12 @@ public abstract class DpmTestBase extends AndroidTestCase { // Note we don't set up queryBroadcastReceivers. We don't use it in DPMS. - doReturn(aci).when(mMockContext.ipackageManager).getReceiverInfo( + doReturn(aci).when(mServices.ipackageManager).getReceiverInfo( eq(admin), anyInt(), eq(UserHandle.getUserId(packageUid))); - doReturn(new String[] {admin.getPackageName()}).when(mMockContext.ipackageManager) + doReturn(new String[] {admin.getPackageName()}).when(mServices.ipackageManager) .getPackagesForUid(eq(packageUid)); // Set up getPackageInfo(). markPackageAsInstalled(admin.getPackageName(), ai, UserHandle.getUserId(packageUid)); diff --git a/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java new file mode 100644 index 0000000000000..ed8de05176318 --- /dev/null +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/MockSystemServices.java @@ -0,0 +1,459 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.server.devicepolicy; + +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.app.AlarmManager; +import android.app.IActivityManager; +import android.app.NotificationManager; +import android.app.backup.IBackupManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.IPackageManager; +import android.content.pm.PackageManager; +import android.content.pm.PackageManagerInternal; +import android.content.pm.UserInfo; +import android.media.IAudioService; +import android.net.IIpConnectivityMetrics; +import android.net.wifi.WifiManager; +import android.os.Handler; +import android.os.PowerManager; +import android.os.PowerManagerInternal; +import android.os.UserHandle; +import android.os.UserManager; +import android.os.UserManagerInternal; +import android.security.KeyChain; +import android.telephony.TelephonyManager; +import android.test.mock.MockContentResolver; +import android.util.ArrayMap; +import android.util.Pair; +import android.view.IWindowManager; + +import com.android.internal.widget.LockPatternUtils; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +/** + * System services mocks and some other data that are shared by all contexts during the test. + */ +public class MockSystemServices { + public final File systemUserDataDir; + public final EnvironmentForMock environment; + public final SystemPropertiesForMock systemProperties; + public final UserManager userManager; + public final UserManagerInternal userManagerInternal; + public final PackageManagerInternal packageManagerInternal; + public final UserManagerForMock userManagerForMock; + public final PowerManagerForMock powerManager; + public final PowerManagerInternal powerManagerInternal; + public final RecoverySystemForMock recoverySystem; + public final NotificationManager notificationManager; + public final IIpConnectivityMetrics iipConnectivityMetrics; + public final IWindowManager iwindowManager; + public final IActivityManager iactivityManager; + public final IPackageManager ipackageManager; + public final IBackupManager ibackupManager; + public final IAudioService iaudioService; + public final LockPatternUtils lockPatternUtils; + public final StorageManagerForMock storageManager; + public final WifiManager wifiManager; + public final SettingsForMock settings; + public final MockContentResolver contentResolver; + public final TelephonyManager telephonyManager; + public final AccountManager accountManager; + public final AlarmManager alarmManager; + public final KeyChain.KeyChainConnection keyChainConnection; + /** Note this is a partial mock, not a real mock. */ + public final PackageManager packageManager; + public final BuildMock buildMock = new BuildMock(); + public final File dataDir; + + public MockSystemServices(Context realContext, String name) { + dataDir = new File(realContext.getCacheDir(), name); + DpmTestUtils.clearDir(dataDir); + + environment = mock(EnvironmentForMock.class); + systemProperties = mock(SystemPropertiesForMock.class); + userManager = mock(UserManager.class); + userManagerInternal = mock(UserManagerInternal.class); + userManagerForMock = mock(UserManagerForMock.class); + packageManagerInternal = mock(PackageManagerInternal.class); + powerManager = mock(PowerManagerForMock.class); + powerManagerInternal = mock(PowerManagerInternal.class); + recoverySystem = mock(RecoverySystemForMock.class); + notificationManager = mock(NotificationManager.class); + iipConnectivityMetrics = mock(IIpConnectivityMetrics.class); + iwindowManager = mock(IWindowManager.class); + iactivityManager = mock(IActivityManager.class); + ipackageManager = mock(IPackageManager.class); + ibackupManager = mock(IBackupManager.class); + iaudioService = mock(IAudioService.class); + lockPatternUtils = mock(LockPatternUtils.class); + storageManager = mock(StorageManagerForMock.class); + wifiManager = mock(WifiManager.class); + settings = mock(SettingsForMock.class); + telephonyManager = mock(TelephonyManager.class); + accountManager = mock(AccountManager.class); + alarmManager = mock(AlarmManager.class); + keyChainConnection = mock(KeyChain.KeyChainConnection.class, RETURNS_DEEP_STUBS); + + // Package manager is huge, so we use a partial mock instead. + packageManager = spy(realContext.getPackageManager()); + + contentResolver = new MockContentResolver(); + + // Add the system user with a fake profile group already set up (this can happen in the real + // world if a managed profile is added and then removed). + systemUserDataDir = + addUser(UserHandle.USER_SYSTEM, UserInfo.FLAG_PRIMARY, UserHandle.USER_SYSTEM); + + // System user is always running. + setUserRunning(UserHandle.USER_SYSTEM, true); + } + + /** Optional mapping of other user contexts for {@link #createPackageContextAsUser} to return */ + private final Map, Context> userPackageContexts = new ArrayMap<>(); + + private final ArrayList mUserInfos = new ArrayList<>(); + + private final List mBroadcastReceivers = new ArrayList<>(); + + public void registerReceiver( + BroadcastReceiver receiver, IntentFilter filter, Handler scheduler) { + mBroadcastReceivers.add(new BroadcastReceiverRegistration(receiver, filter, scheduler)); + } + + public void unregisterReceiver(BroadcastReceiver receiver) { + mBroadcastReceivers.removeIf(r -> r.receiver == receiver); + } + + public File addUser(int userId, int flags) { + return addUser(userId, flags, UserInfo.NO_PROFILE_GROUP_ID); + } + + public File addUser(int userId, int flags, int profileGroupId) { + // Set up (default) UserInfo for CALLER_USER_HANDLE. + final UserInfo uh = new UserInfo(userId, "user" + userId, flags); + uh.profileGroupId = profileGroupId; + when(userManager.getUserInfo(eq(userId))).thenReturn(uh); + + mUserInfos.add(uh); + when(userManager.getUsers()).thenReturn(mUserInfos); + when(userManager.getUsers(anyBoolean())).thenReturn(mUserInfos); + when(userManager.isUserRunning(eq(new UserHandle(userId)))).thenReturn(true); + when(userManager.getUserInfo(anyInt())).thenAnswer( + invocation -> { + final int userId1 = (int) invocation.getArguments()[0]; + return getUserInfo(userId1); + } + ); + when(userManager.getProfiles(anyInt())).thenAnswer( + invocation -> { + final int userId12 = (int) invocation.getArguments()[0]; + return getProfiles(userId12); + } + ); + when(userManager.getProfileIdsWithDisabled(anyInt())).thenAnswer( + invocation -> { + final int userId13 = (int) invocation.getArguments()[0]; + List profiles = getProfiles(userId13); + return profiles.stream() + .mapToInt(profile -> profile.id) + .toArray(); + } + ); + when(accountManager.getAccountsAsUser(anyInt())).thenReturn(new Account[0]); + + // Create a data directory. + final File dir = new File(dataDir, "users/" + userId); + DpmTestUtils.clearDir(dir); + + when(environment.getUserSystemDirectory(eq(userId))).thenReturn(dir); + return dir; + } + + public void removeUser(int userId) { + for (int i = 0; i < mUserInfos.size(); i++) { + if (mUserInfos.get(i).id == userId) { + mUserInfos.remove(i); + break; + } + } + when(userManager.getUserInfo(eq(userId))).thenReturn(null); + + when(userManager.isUserRunning(eq(new UserHandle(userId)))).thenReturn(false); + } + + private UserInfo getUserInfo(int userId) { + for (final UserInfo ui : mUserInfos) { + if (ui.id == userId) { + return ui; + } + } + return null; + } + + private List getProfiles(int userId) { + final ArrayList ret = new ArrayList<>(); + UserInfo parent = null; + for (final UserInfo ui : mUserInfos) { + if (ui.id == userId) { + parent = ui; + break; + } + } + if (parent == null) { + return ret; + } + for (final UserInfo ui : mUserInfos) { + if (ui == parent + || ui.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID + && ui.profileGroupId == parent.profileGroupId) { + ret.add(ui); + } + } + return ret; + } + + /** + * Add multiple users at once. They'll all have flag 0. + */ + public void addUsers(int... userIds) { + for (final int userId : userIds) { + addUser(userId, 0); + } + } + + public void setUserRunning(int userId, boolean isRunning) { + when(userManager.isUserRunning(MockUtils.checkUserHandle(userId))) + .thenReturn(isRunning); + } + + public void injectBroadcast(Context context, final Intent intent, int userId) { + //final int userId = UserHandle.getUserId(binder.getCallingUid()); + for (final BroadcastReceiverRegistration receiver : mBroadcastReceivers) { + receiver.sendBroadcastIfApplicable(context, userId, intent); + } + } + + public void rethrowBackgroundBroadcastExceptions() throws Exception { + for (final BroadcastReceiverRegistration receiver : mBroadcastReceivers) { + final Exception e = receiver.backgroundException.getAndSet(null); + if (e != null) { + throw e; + } + } + } + + public void addPackageContext(UserHandle user, Context context) { + if (context.getPackageName() == null) { + throw new NullPointerException("getPackageName() == null"); + } + userPackageContexts.put(new Pair<>(user, context.getPackageName()), context); + } + + public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) + throws PackageManager.NameNotFoundException { + final Pair key = new Pair<>(user, packageName); + if (userPackageContexts.containsKey(key)) { + return userPackageContexts.get(key); + } + throw new UnsupportedOperationException("No package " + packageName + " for user " + user); + } + + + public static class EnvironmentForMock { + public File getUserSystemDirectory(int userId) { + return null; + } + } + + public static class BuildMock { + public boolean isDebuggable = true; + } + + public static class PowerManagerForMock { + public PowerManager.WakeLock newWakeLock(int levelAndFlags, String tag) { + return null; + } + + public void goToSleep(long time, int reason, int flags) { + } + + public void reboot(String reason) { + } + } + + public static class RecoverySystemForMock { + public void rebootWipeUserData( + boolean shutdown, String reason, boolean force) throws IOException { + } + } + + public static class SystemPropertiesForMock { + public boolean getBoolean(String key, boolean def) { + return false; + } + + public long getLong(String key, long def) { + return 0; + } + + public String get(String key, String def) { + return null; + } + + public String get(String key) { + return null; + } + + public void set(String key, String value) { + } + } + + public static class UserManagerForMock { + public boolean isSplitSystemUser() { + return false; + } + } + + public static class SettingsForMock { + public int settingsSecureGetIntForUser(String name, int def, int userHandle) { + return 0; + } + + public String settingsSecureGetStringForUser(String name, int userHandle) { + return null; + } + + public void settingsSecurePutIntForUser(String name, int value, int userHandle) { + } + + public void settingsSecurePutStringForUser(String name, String value, int userHandle) { + } + + public void settingsGlobalPutStringForUser(String name, String value, int userHandle) { + } + + public void settingsSecurePutInt(String name, int value) { + } + + public void settingsGlobalPutInt(String name, int value) { + } + + public void settingsSecurePutString(String name, String value) { + } + + public void settingsGlobalPutString(String name, String value) { + } + + public int settingsGlobalGetInt(String name, int value) { + return 0; + } + + public String settingsGlobalGetString(String name) { + return ""; + } + + public void securityLogSetLoggingEnabledProperty(boolean enabled) { + } + + public boolean securityLogGetLoggingEnabledProperty() { + return false; + } + + public boolean securityLogIsLoggingEnabled() { + return false; + } + } + + public static class StorageManagerForMock { + public boolean isFileBasedEncryptionEnabled() { + return false; + } + + public boolean isNonDefaultBlockEncrypted() { + return false; + } + + public boolean isEncrypted() { + return false; + } + + public boolean isEncryptable() { + return false; + } + } + + // We have to keep track of broadcast receivers registered for a given intent ourselves as the + // DPM unit tests mock out the package manager and PackageManager.queryBroadcastReceivers() does + // not work. + private static class BroadcastReceiverRegistration { + public final BroadcastReceiver receiver; + public final IntentFilter filter; + public final Handler scheduler; + + // Exceptions thrown in a background thread kill the whole test. Save them instead. + public final AtomicReference backgroundException = new AtomicReference<>(); + + public BroadcastReceiverRegistration(BroadcastReceiver receiver, IntentFilter filter, + Handler scheduler) { + this.receiver = receiver; + this.filter = filter; + this.scheduler = scheduler; + } + + public void sendBroadcastIfApplicable(Context context, int userId, Intent intent) { + final BroadcastReceiver.PendingResult result = new BroadcastReceiver.PendingResult( + 0 /* resultCode */, null /* resultData */, null /* resultExtras */, + 0 /* type */, false /* ordered */, false /* sticky */, null /* token */, userId, + 0 /* flags */); + if (filter.match(null, intent, false, "DpmMockContext") > 0) { + final Runnable send = () -> { + receiver.setPendingResult(result); + receiver.onReceive(context, intent); + }; + if (scheduler != null) { + scheduler.post(() -> { + try { + send.run(); + } catch (Exception e) { + backgroundException.compareAndSet(null, e); + } + }); + } else { + send.run(); + } + } + } + } +} 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 423c4d5431a8b..909a8357e5948 100644 --- a/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java +++ b/services/tests/servicestests/src/com/android/server/devicepolicy/OwnersTest.java @@ -34,11 +34,11 @@ import android.os.UserHandle; */ public class OwnersTest extends DpmTestBase { public void testUpgrade01() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); // First, migrate. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(), DpmTestUtils.readAsset(mRealTestContext, "OwnersTest/test01/input.xml")); @@ -70,7 +70,7 @@ public class OwnersTest extends DpmTestBase { // Then re-read and check. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertFalse(owners.hasDeviceOwner()); @@ -87,11 +87,11 @@ public class OwnersTest extends DpmTestBase { } public void testUpgrade02() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); // First, migrate. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(), DpmTestUtils.readAsset(mRealTestContext, "OwnersTest/test02/input.xml")); @@ -125,7 +125,7 @@ public class OwnersTest extends DpmTestBase { // Then re-read and check. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertTrue(owners.hasDeviceOwner()); @@ -145,11 +145,11 @@ public class OwnersTest extends DpmTestBase { } public void testUpgrade03() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); // First, migrate. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(), DpmTestUtils.readAsset(mRealTestContext, "OwnersTest/test03/input.xml")); @@ -191,7 +191,7 @@ public class OwnersTest extends DpmTestBase { // Then re-read and check. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertFalse(owners.hasDeviceOwner()); @@ -223,11 +223,11 @@ public class OwnersTest extends DpmTestBase { * and {@link Owners#setProfileOwnerUserRestrictionsMigrated(int)}. */ public void testUpgrade04() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); // First, migrate. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(), DpmTestUtils.readAsset(mRealTestContext, "OwnersTest/test04/input.xml")); @@ -273,7 +273,7 @@ public class OwnersTest extends DpmTestBase { // Then re-read and check. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertTrue(owners.hasDeviceOwner()); @@ -306,7 +306,7 @@ public class OwnersTest extends DpmTestBase { } { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); @@ -319,7 +319,7 @@ public class OwnersTest extends DpmTestBase { } { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertFalse(owners.getDeviceOwnerUserRestrictionsNeedsMigration()); @@ -333,11 +333,11 @@ public class OwnersTest extends DpmTestBase { } public void testUpgrade05() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); // First, migrate. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(), DpmTestUtils.readAsset(mRealTestContext, "OwnersTest/test05/input.xml")); @@ -370,7 +370,7 @@ public class OwnersTest extends DpmTestBase { // Then re-read and check. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertFalse(owners.hasDeviceOwner()); @@ -389,11 +389,11 @@ public class OwnersTest extends DpmTestBase { } public void testUpgrade06() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); // First, migrate. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(), DpmTestUtils.readAsset(mRealTestContext, "OwnersTest/test06/input.xml")); @@ -425,7 +425,7 @@ public class OwnersTest extends DpmTestBase { // Then re-read and check. { - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); owners.load(); assertFalse(owners.hasDeviceOwner()); @@ -444,9 +444,9 @@ public class OwnersTest extends DpmTestBase { } public void testRemoveExistingFiles() throws Exception { - getContext().addUsers(10, 11, 20, 21); + getServices().addUsers(10, 11, 20, 21); - final OwnersTestable owners = new OwnersTestable(getContext()); + final OwnersTestable owners = new OwnersTestable(getServices()); // First, migrate to create new-style config files. DpmTestUtils.writeToFile(owners.getLegacyConfigFileWithTestOverride(),