1 /* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.accounts; 18 19 import static android.database.sqlite.SQLiteDatabase.deleteDatabase; 20 21 import static org.mockito.Matchers.any; 22 import static org.mockito.Matchers.anyBoolean; 23 import static org.mockito.Matchers.anyInt; 24 import static org.mockito.Matchers.anyString; 25 import static org.mockito.Matchers.eq; 26 import static org.mockito.Mockito.atLeast; 27 import static org.mockito.Mockito.never; 28 import static org.mockito.Mockito.nullable; 29 import static org.mockito.Mockito.verify; 30 import static org.mockito.Mockito.when; 31 32 import android.accounts.Account; 33 import android.accounts.AccountManager; 34 import android.accounts.AccountManagerInternal; 35 import android.accounts.CantAddAccountActivity; 36 import android.accounts.IAccountManagerResponse; 37 import android.app.AppOpsManager; 38 import android.app.INotificationManager; 39 import android.app.admin.DevicePolicyManager; 40 import android.app.admin.DevicePolicyManagerInternal; 41 import android.content.BroadcastReceiver; 42 import android.content.Context; 43 import android.content.Intent; 44 import android.content.IntentFilter; 45 import android.content.ServiceConnection; 46 import android.content.pm.ActivityInfo; 47 import android.content.pm.ApplicationInfo; 48 import android.content.pm.PackageInfo; 49 import android.content.pm.PackageManager; 50 import android.content.pm.PackageManagerInternal; 51 import android.content.pm.ResolveInfo; 52 import android.content.pm.Signature; 53 import android.content.pm.UserInfo; 54 import android.database.Cursor; 55 import android.database.DatabaseErrorHandler; 56 import android.database.sqlite.SQLiteDatabase; 57 import android.os.Bundle; 58 import android.os.Handler; 59 import android.os.IBinder; 60 import android.os.Looper; 61 import android.os.RemoteException; 62 import android.os.SystemClock; 63 import android.os.UserHandle; 64 import android.os.UserManager; 65 import android.test.AndroidTestCase; 66 import android.test.mock.MockContext; 67 import android.test.suitebuilder.annotation.SmallTest; 68 import android.util.Log; 69 70 import com.android.server.LocalServices; 71 72 import org.mockito.ArgumentCaptor; 73 import org.mockito.Captor; 74 import org.mockito.Mock; 75 import org.mockito.MockitoAnnotations; 76 77 import java.io.File; 78 import java.security.GeneralSecurityException; 79 import java.util.ArrayList; 80 import java.util.Arrays; 81 import java.util.Collections; 82 import java.util.Comparator; 83 import java.util.HashMap; 84 import java.util.List; 85 import java.util.concurrent.CountDownLatch; 86 import java.util.concurrent.CyclicBarrier; 87 import java.util.concurrent.ExecutorService; 88 import java.util.concurrent.Executors; 89 import java.util.concurrent.TimeUnit; 90 import java.util.concurrent.atomic.AtomicLong; 91 92 /** 93 * Tests for {@link AccountManagerService}. 94 * <p>Run with:<pre> 95 * mmma -j40 frameworks/base/services/tests/servicestests 96 * adb install -r ${OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk 97 * adb shell am instrument -w -e package com.android.server.accounts \ 98 * com.android.frameworks.servicestests\ 99 * /androidx.test.runner.AndroidJUnitRunner 100 * </pre> 101 */ 102 public class AccountManagerServiceTest extends AndroidTestCase { 103 private static final String TAG = AccountManagerServiceTest.class.getSimpleName(); 104 private static final long ONE_DAY_IN_MILLISECOND = 86400000; 105 106 @Mock private Context mMockContext; 107 @Mock private AppOpsManager mMockAppOpsManager; 108 @Mock private UserManager mMockUserManager; 109 @Mock private PackageManager mMockPackageManager; 110 @Mock private DevicePolicyManagerInternal mMockDevicePolicyManagerInternal; 111 @Mock private DevicePolicyManager mMockDevicePolicyManager; 112 @Mock private IAccountManagerResponse mMockAccountManagerResponse; 113 @Mock private IBinder mMockBinder; 114 @Mock private INotificationManager mMockNotificationManager; 115 @Mock private PackageManagerInternal mMockPackageManagerInternal; 116 117 @Captor private ArgumentCaptor<Intent> mIntentCaptor; 118 @Captor private ArgumentCaptor<Bundle> mBundleCaptor; 119 private int mVisibleAccountsChangedBroadcasts; 120 private int mLoginAccountsChangedBroadcasts; 121 private int mAccountRemovedBroadcasts; 122 123 private static final int LATCH_TIMEOUT_MS = 500; 124 private static final String PREN_DB = "pren.db"; 125 private static final String DE_DB = "de.db"; 126 private static final String CE_DB = "ce.db"; 127 private PackageInfo mPackageInfo; 128 private AccountManagerService mAms; 129 private TestInjector mTestInjector; 130 131 @Override setUp()132 protected void setUp() throws Exception { 133 MockitoAnnotations.initMocks(this); 134 135 when(mMockPackageManager.checkSignatures(anyInt(), anyInt())) 136 .thenReturn(PackageManager.SIGNATURE_MATCH); 137 final UserInfo ui = new UserInfo(UserHandle.USER_SYSTEM, "user0", 0); 138 when(mMockUserManager.getUserInfo(eq(ui.id))).thenReturn(ui); 139 when(mMockContext.createPackageContextAsUser( 140 anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext); 141 when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); 142 143 mPackageInfo = new PackageInfo(); 144 mPackageInfo.signatures = new Signature[1]; 145 mPackageInfo.signatures[0] = new Signature(new byte[] {'a', 'b', 'c', 'd'}); 146 mPackageInfo.applicationInfo = new ApplicationInfo(); 147 mPackageInfo.applicationInfo.privateFlags = ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 148 when(mMockPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(mPackageInfo); 149 when(mMockContext.getSystemService(Context.APP_OPS_SERVICE)).thenReturn(mMockAppOpsManager); 150 when(mMockContext.getSystemService(Context.USER_SERVICE)).thenReturn(mMockUserManager); 151 when(mMockContext.getSystemServiceName(AppOpsManager.class)).thenReturn( 152 Context.APP_OPS_SERVICE); 153 when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn( 154 PackageManager.PERMISSION_GRANTED); 155 Bundle bundle = new Bundle(); 156 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 157 when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn( 158 mMockDevicePolicyManager); 159 when(mMockAccountManagerResponse.asBinder()).thenReturn(mMockBinder); 160 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 161 .thenReturn(true); 162 LocalServices.addService(PackageManagerInternal.class, mMockPackageManagerInternal); 163 164 Context realTestContext = getContext(); 165 MyMockContext mockContext = new MyMockContext(realTestContext, mMockContext); 166 setContext(mockContext); 167 mTestInjector = new TestInjector(realTestContext, mockContext, mMockNotificationManager); 168 mAms = new AccountManagerService(mTestInjector); 169 } 170 171 @Override tearDown()172 protected void tearDown() throws Exception { 173 // Let async logging tasks finish, otherwise they may crash due to db being removed 174 CountDownLatch cdl = new CountDownLatch(1); 175 mAms.mHandler.post(() -> { 176 deleteDatabase(new File(mTestInjector.getCeDatabaseName(UserHandle.USER_SYSTEM))); 177 deleteDatabase(new File(mTestInjector.getDeDatabaseName(UserHandle.USER_SYSTEM))); 178 deleteDatabase(new File(mTestInjector.getPreNDatabaseName(UserHandle.USER_SYSTEM))); 179 cdl.countDown(); 180 }); 181 cdl.await(1, TimeUnit.SECONDS); 182 LocalServices.removeServiceForTest(PackageManagerInternal.class); 183 super.tearDown(); 184 } 185 186 class AccountSorter implements Comparator<Account> { compare(Account object1, Account object2)187 public int compare(Account object1, Account object2) { 188 if (object1 == object2) return 0; 189 if (object1 == null) return 1; 190 if (object2 == null) return -1; 191 int result = object1.type.compareTo(object2.type); 192 if (result != 0) return result; 193 return object1.name.compareTo(object2.name); 194 } 195 } 196 197 @SmallTest testCheckAddAccount()198 public void testCheckAddAccount() throws Exception { 199 unlockSystemUser(); 200 Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 201 Account a21 = new Account("account2", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 202 Account a31 = new Account("account3", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 203 Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 204 Account a22 = new Account("account2", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 205 Account a32 = new Account("account3", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 206 mAms.addAccountExplicitly(a11, "p11", null); 207 mAms.addAccountExplicitly(a12, "p12", null); 208 mAms.addAccountExplicitly(a21, "p21", null); 209 mAms.addAccountExplicitly(a22, "p22", null); 210 mAms.addAccountExplicitly(a31, "p31", null); 211 mAms.addAccountExplicitly(a32, "p32", null); 212 213 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 214 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 215 Account[] accounts = mAms.getAccountsAsUser(null, 216 UserHandle.getCallingUserId(), mContext.getOpPackageName()); 217 Arrays.sort(accounts, new AccountSorter()); 218 assertEquals(6, accounts.length); 219 assertEquals(a11, accounts[0]); 220 assertEquals(a21, accounts[1]); 221 assertEquals(a31, accounts[2]); 222 assertEquals(a12, accounts[3]); 223 assertEquals(a22, accounts[4]); 224 assertEquals(a32, accounts[5]); 225 226 accounts = mAms.getAccountsAsUser(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 227 UserHandle.getCallingUserId(), mContext.getOpPackageName()); 228 Arrays.sort(accounts, new AccountSorter()); 229 assertEquals(3, accounts.length); 230 assertEquals(a11, accounts[0]); 231 assertEquals(a21, accounts[1]); 232 assertEquals(a31, accounts[2]); 233 234 mAms.removeAccountInternal(a21); 235 236 accounts = mAms.getAccountsAsUser(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 237 UserHandle.getCallingUserId(), mContext.getOpPackageName()); 238 Arrays.sort(accounts, new AccountSorter()); 239 assertEquals(2, accounts.length); 240 assertEquals(a11, accounts[0]); 241 assertEquals(a31, accounts[1]); 242 } 243 244 @SmallTest testPasswords()245 public void testPasswords() throws Exception { 246 unlockSystemUser(); 247 Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 248 Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 249 mAms.addAccountExplicitly(a11, "p11", null); 250 mAms.addAccountExplicitly(a12, "p12", null); 251 252 assertEquals("p11", mAms.getPassword(a11)); 253 assertEquals("p12", mAms.getPassword(a12)); 254 255 mAms.setPassword(a11, "p11b"); 256 257 assertEquals("p11b", mAms.getPassword(a11)); 258 assertEquals("p12", mAms.getPassword(a12)); 259 } 260 261 @SmallTest testUserdata()262 public void testUserdata() throws Exception { 263 unlockSystemUser(); 264 Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 265 Bundle u11 = new Bundle(); 266 u11.putString("a", "a_a11"); 267 u11.putString("b", "b_a11"); 268 u11.putString("c", "c_a11"); 269 Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 270 Bundle u12 = new Bundle(); 271 u12.putString("a", "a_a12"); 272 u12.putString("b", "b_a12"); 273 u12.putString("c", "c_a12"); 274 mAms.addAccountExplicitly(a11, "p11", u11); 275 mAms.addAccountExplicitly(a12, "p12", u12); 276 277 assertEquals("a_a11", mAms.getUserData(a11, "a")); 278 assertEquals("b_a11", mAms.getUserData(a11, "b")); 279 assertEquals("c_a11", mAms.getUserData(a11, "c")); 280 assertEquals("a_a12", mAms.getUserData(a12, "a")); 281 assertEquals("b_a12", mAms.getUserData(a12, "b")); 282 assertEquals("c_a12", mAms.getUserData(a12, "c")); 283 284 mAms.setUserData(a11, "b", "b_a11b"); 285 mAms.setUserData(a12, "c", null); 286 287 assertEquals("a_a11", mAms.getUserData(a11, "a")); 288 assertEquals("b_a11b", mAms.getUserData(a11, "b")); 289 assertEquals("c_a11", mAms.getUserData(a11, "c")); 290 assertEquals("a_a12", mAms.getUserData(a12, "a")); 291 assertEquals("b_a12", mAms.getUserData(a12, "b")); 292 assertNull(mAms.getUserData(a12, "c")); 293 } 294 295 @SmallTest testAuthtokens()296 public void testAuthtokens() throws Exception { 297 unlockSystemUser(); 298 Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 299 Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 300 mAms.addAccountExplicitly(a11, "p11", null); 301 mAms.addAccountExplicitly(a12, "p12", null); 302 303 mAms.setAuthToken(a11, "att1", "a11_att1"); 304 mAms.setAuthToken(a11, "att2", "a11_att2"); 305 mAms.setAuthToken(a11, "att3", "a11_att3"); 306 mAms.setAuthToken(a12, "att1", "a12_att1"); 307 mAms.setAuthToken(a12, "att2", "a12_att2"); 308 mAms.setAuthToken(a12, "att3", "a12_att3"); 309 310 assertEquals("a11_att1", mAms.peekAuthToken(a11, "att1")); 311 assertEquals("a11_att2", mAms.peekAuthToken(a11, "att2")); 312 assertEquals("a11_att3", mAms.peekAuthToken(a11, "att3")); 313 assertEquals("a12_att1", mAms.peekAuthToken(a12, "att1")); 314 assertEquals("a12_att2", mAms.peekAuthToken(a12, "att2")); 315 assertEquals("a12_att3", mAms.peekAuthToken(a12, "att3")); 316 317 mAms.setAuthToken(a11, "att3", "a11_att3b"); 318 mAms.invalidateAuthToken(a12.type, "a12_att2"); 319 320 assertEquals("a11_att1", mAms.peekAuthToken(a11, "att1")); 321 assertEquals("a11_att2", mAms.peekAuthToken(a11, "att2")); 322 assertEquals("a11_att3b", mAms.peekAuthToken(a11, "att3")); 323 assertEquals("a12_att1", mAms.peekAuthToken(a12, "att1")); 324 assertNull(mAms.peekAuthToken(a12, "att2")); 325 assertEquals("a12_att3", mAms.peekAuthToken(a12, "att3")); 326 327 assertNull(mAms.peekAuthToken(a12, "att2")); 328 } 329 330 @SmallTest testRemovedAccountSync()331 public void testRemovedAccountSync() throws Exception { 332 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 333 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 334 unlockSystemUser(); 335 Account a1 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 336 Account a2 = new Account("account2", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2); 337 mAms.addAccountExplicitly(a1, "p1", null); 338 mAms.addAccountExplicitly(a2, "p2", null); 339 340 Context originalContext = ((MyMockContext)getContext()).mTestContext; 341 // create a separate instance of AMS. It initially assumes that user0 is locked 342 AccountManagerService ams2 = new AccountManagerService(mTestInjector); 343 344 // Verify that account can be removed when user is locked 345 ams2.removeAccountInternal(a1); 346 Account[] accounts = ams2.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName()); 347 assertEquals(1, accounts.length); 348 assertEquals("Only a2 should be returned", a2, accounts[0]); 349 350 // Verify that CE db file is unchanged and still has 2 accounts 351 String ceDatabaseName = mTestInjector.getCeDatabaseName(UserHandle.USER_SYSTEM); 352 int accountsNumber = readNumberOfAccountsFromDbFile(originalContext, ceDatabaseName); 353 assertEquals("CE database should still have 2 accounts", 2, accountsNumber); 354 355 // Unlock the user and verify that db has been updated 356 ams2.onUserUnlocked(newIntentForUser(UserHandle.USER_SYSTEM)); 357 accounts = ams2.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName()); 358 assertEquals(1, accounts.length); 359 assertEquals("Only a2 should be returned", a2, accounts[0]); 360 accountsNumber = readNumberOfAccountsFromDbFile(originalContext, ceDatabaseName); 361 assertEquals("CE database should now have 1 account", 1, accountsNumber); 362 } 363 364 @SmallTest testPreNDatabaseMigration()365 public void testPreNDatabaseMigration() throws Exception { 366 String preNDatabaseName = mTestInjector.getPreNDatabaseName(UserHandle.USER_SYSTEM); 367 Context originalContext = ((MyMockContext) getContext()).mTestContext; 368 PreNTestDatabaseHelper.createV4Database(originalContext, preNDatabaseName); 369 // Assert that database was created with 1 account 370 int n = readNumberOfAccountsFromDbFile(originalContext, preNDatabaseName); 371 assertEquals("pre-N database should have 1 account", 1, n); 372 373 // Start testing 374 unlockSystemUser(); 375 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 376 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 377 Account[] accounts = mAms.getAccountsAsUser(null, UserHandle.getCallingUserId(), 378 mContext.getOpPackageName()); 379 assertEquals("1 account should be migrated", 1, accounts.length); 380 assertEquals(PreNTestDatabaseHelper.ACCOUNT_NAME, accounts[0].name); 381 assertEquals(PreNTestDatabaseHelper.ACCOUNT_PASSWORD, mAms.getPassword(accounts[0])); 382 assertEquals("Authtoken should be migrated", 383 PreNTestDatabaseHelper.TOKEN_STRING, 384 mAms.peekAuthToken(accounts[0], PreNTestDatabaseHelper.TOKEN_TYPE)); 385 386 assertFalse("pre-N database file should be removed but was found at " + preNDatabaseName, 387 new File(preNDatabaseName).exists()); 388 389 // Verify that ce/de files are present 390 String deDatabaseName = mTestInjector.getDeDatabaseName(UserHandle.USER_SYSTEM); 391 String ceDatabaseName = mTestInjector.getCeDatabaseName(UserHandle.USER_SYSTEM); 392 assertTrue("DE database file should be created at " + deDatabaseName, 393 new File(deDatabaseName).exists()); 394 assertTrue("CE database file should be created at " + ceDatabaseName, 395 new File(ceDatabaseName).exists()); 396 } 397 398 @SmallTest testStartAddAccountSessionWithNullResponse()399 public void testStartAddAccountSessionWithNullResponse() throws Exception { 400 unlockSystemUser(); 401 try { 402 mAms.startAddAccountSession( 403 null, // response 404 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 405 "authTokenType", 406 null, // requiredFeatures 407 true, // expectActivityLaunch 408 null); // optionsIn 409 fail("IllegalArgumentException expected. But no exception was thrown."); 410 } catch (IllegalArgumentException e) { 411 // IllegalArgumentException is expected. 412 } 413 } 414 415 @SmallTest testStartAddAccountSessionWithNullAccountType()416 public void testStartAddAccountSessionWithNullAccountType() throws Exception { 417 unlockSystemUser(); 418 try { 419 mAms.startAddAccountSession( 420 mMockAccountManagerResponse, // response 421 null, // accountType 422 "authTokenType", 423 null, // requiredFeatures 424 true, // expectActivityLaunch 425 null); // optionsIn 426 fail("IllegalArgumentException expected. But no exception was thrown."); 427 } catch (IllegalArgumentException e) { 428 // IllegalArgumentException is expected. 429 } 430 } 431 432 @SmallTest testStartAddAccountSessionUserCannotModifyAccountNoDPM()433 public void testStartAddAccountSessionUserCannotModifyAccountNoDPM() throws Exception { 434 unlockSystemUser(); 435 Bundle bundle = new Bundle(); 436 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 437 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 438 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 439 440 mAms.startAddAccountSession( 441 mMockAccountManagerResponse, // response 442 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 443 "authTokenType", 444 null, // requiredFeatures 445 true, // expectActivityLaunch 446 null); // optionsIn 447 verify(mMockAccountManagerResponse).onError( 448 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 449 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 450 451 // verify the intent for default CantAddAccountActivity is sent. 452 Intent intent = mIntentCaptor.getValue(); 453 assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName()); 454 assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0), 455 AccountManager.ERROR_CODE_USER_RESTRICTED); 456 } 457 458 @SmallTest testStartAddAccountSessionUserCannotModifyAccountWithDPM()459 public void testStartAddAccountSessionUserCannotModifyAccountWithDPM() throws Exception { 460 unlockSystemUser(); 461 Bundle bundle = new Bundle(); 462 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 463 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 464 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 465 LocalServices.addService( 466 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal); 467 when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent( 468 anyInt(), anyString())).thenReturn(new Intent()); 469 when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent( 470 anyInt(), anyBoolean())).thenReturn(new Intent()); 471 472 mAms.startAddAccountSession( 473 mMockAccountManagerResponse, // response 474 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 475 "authTokenType", 476 null, // requiredFeatures 477 true, // expectActivityLaunch 478 null); // optionsIn 479 480 verify(mMockAccountManagerResponse).onError( 481 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 482 verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM)); 483 verify(mMockDevicePolicyManagerInternal).createUserRestrictionSupportIntent( 484 anyInt(), anyString()); 485 } 486 487 @SmallTest testStartAddAccountSessionUserCannotModifyAccountForTypeNoDPM()488 public void testStartAddAccountSessionUserCannotModifyAccountForTypeNoDPM() throws Exception { 489 unlockSystemUser(); 490 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 491 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 492 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 493 494 mAms.startAddAccountSession( 495 mMockAccountManagerResponse, // response 496 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 497 "authTokenType", 498 null, // requiredFeatures 499 true, // expectActivityLaunch 500 null); // optionsIn 501 502 verify(mMockAccountManagerResponse).onError( 503 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 504 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 505 506 // verify the intent for default CantAddAccountActivity is sent. 507 Intent intent = mIntentCaptor.getValue(); 508 assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName()); 509 assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0), 510 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE); 511 } 512 513 @SmallTest testStartAddAccountSessionUserCannotModifyAccountForTypeWithDPM()514 public void testStartAddAccountSessionUserCannotModifyAccountForTypeWithDPM() throws Exception { 515 unlockSystemUser(); 516 when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn( 517 mMockDevicePolicyManager); 518 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 519 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 520 521 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 522 LocalServices.addService( 523 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal); 524 when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent( 525 anyInt(), anyString())).thenReturn(new Intent()); 526 when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent( 527 anyInt(), anyBoolean())).thenReturn(new Intent()); 528 529 mAms.startAddAccountSession( 530 mMockAccountManagerResponse, // response 531 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 532 "authTokenType", 533 null, // requiredFeatures 534 true, // expectActivityLaunch 535 null); // optionsIn 536 537 verify(mMockAccountManagerResponse).onError( 538 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 539 verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM)); 540 verify(mMockDevicePolicyManagerInternal).createShowAdminSupportIntent( 541 anyInt(), anyBoolean()); 542 } 543 544 @SmallTest testStartAddAccountSessionSuccessWithoutPasswordForwarding()545 public void testStartAddAccountSessionSuccessWithoutPasswordForwarding() throws Exception { 546 unlockSystemUser(); 547 when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn( 548 PackageManager.PERMISSION_DENIED); 549 550 final CountDownLatch latch = new CountDownLatch(1); 551 Response response = new Response(latch, mMockAccountManagerResponse); 552 Bundle options = createOptionsWithAccountName( 553 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS); 554 mAms.startAddAccountSession( 555 response, // response 556 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 557 "authTokenType", 558 null, // requiredFeatures 559 false, // expectActivityLaunch 560 options); // optionsIn 561 waitForLatch(latch); 562 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 563 Bundle result = mBundleCaptor.getValue(); 564 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE); 565 assertNotNull(sessionBundle); 566 // Assert that session bundle is encrypted and hence data not visible. 567 assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1)); 568 // Assert password is not returned 569 assertNull(result.getString(AccountManager.KEY_PASSWORD)); 570 assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null)); 571 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN, 572 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN)); 573 } 574 575 @SmallTest testStartAddAccountSessionSuccessWithPasswordForwarding()576 public void testStartAddAccountSessionSuccessWithPasswordForwarding() throws Exception { 577 unlockSystemUser(); 578 when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn( 579 PackageManager.PERMISSION_GRANTED); 580 581 final CountDownLatch latch = new CountDownLatch(1); 582 Response response = new Response(latch, mMockAccountManagerResponse); 583 Bundle options = createOptionsWithAccountName( 584 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS); 585 mAms.startAddAccountSession( 586 response, // response 587 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 588 "authTokenType", 589 null, // requiredFeatures 590 false, // expectActivityLaunch 591 options); // optionsIn 592 593 waitForLatch(latch); 594 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 595 Bundle result = mBundleCaptor.getValue(); 596 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE); 597 assertNotNull(sessionBundle); 598 // Assert that session bundle is encrypted and hence data not visible. 599 assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1)); 600 // Assert password is returned 601 assertEquals(result.getString(AccountManager.KEY_PASSWORD), 602 AccountManagerServiceTestFixtures.ACCOUNT_PASSWORD); 603 assertNull(result.getString(AccountManager.KEY_AUTHTOKEN)); 604 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN, 605 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN)); 606 } 607 608 @SmallTest testStartAddAccountSessionReturnWithInvalidIntent()609 public void testStartAddAccountSessionReturnWithInvalidIntent() throws Exception { 610 unlockSystemUser(); 611 ResolveInfo resolveInfo = new ResolveInfo(); 612 resolveInfo.activityInfo = new ActivityInfo(); 613 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 614 when(mMockPackageManager.resolveActivityAsUser( 615 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 616 when(mMockPackageManager.checkSignatures( 617 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 618 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 619 .thenReturn(false); 620 621 final CountDownLatch latch = new CountDownLatch(1); 622 Response response = new Response(latch, mMockAccountManagerResponse); 623 Bundle options = createOptionsWithAccountName( 624 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE); 625 626 mAms.startAddAccountSession( 627 response, // response 628 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 629 "authTokenType", 630 null, // requiredFeatures 631 true, // expectActivityLaunch 632 options); // optionsIn 633 waitForLatch(latch); 634 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 635 verify(mMockAccountManagerResponse).onError( 636 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 637 } 638 639 @SmallTest testStartAddAccountSessionReturnWithValidIntent()640 public void testStartAddAccountSessionReturnWithValidIntent() throws Exception { 641 unlockSystemUser(); 642 ResolveInfo resolveInfo = new ResolveInfo(); 643 resolveInfo.activityInfo = new ActivityInfo(); 644 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 645 when(mMockPackageManager.resolveActivityAsUser( 646 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 647 when(mMockPackageManager.checkSignatures( 648 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 649 650 final CountDownLatch latch = new CountDownLatch(1); 651 Response response = new Response(latch, mMockAccountManagerResponse); 652 Bundle options = createOptionsWithAccountName( 653 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE); 654 655 mAms.startAddAccountSession( 656 response, // response 657 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 658 "authTokenType", 659 null, // requiredFeatures 660 true, // expectActivityLaunch 661 options); // optionsIn 662 waitForLatch(latch); 663 664 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 665 Bundle result = mBundleCaptor.getValue(); 666 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 667 assertNotNull(intent); 668 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 669 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 670 } 671 672 @SmallTest testStartAddAccountSessionError()673 public void testStartAddAccountSessionError() throws Exception { 674 unlockSystemUser(); 675 Bundle options = createOptionsWithAccountName( 676 AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR); 677 options.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_INVALID_RESPONSE); 678 options.putString(AccountManager.KEY_ERROR_MESSAGE, 679 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 680 681 final CountDownLatch latch = new CountDownLatch(1); 682 Response response = new Response(latch, mMockAccountManagerResponse); 683 mAms.startAddAccountSession( 684 response, // response 685 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 686 "authTokenType", 687 null, // requiredFeatures 688 false, // expectActivityLaunch 689 options); // optionsIn 690 691 waitForLatch(latch); 692 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 693 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 694 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 695 } 696 697 @SmallTest testStartUpdateCredentialsSessionWithNullResponse()698 public void testStartUpdateCredentialsSessionWithNullResponse() throws Exception { 699 unlockSystemUser(); 700 try { 701 mAms.startUpdateCredentialsSession( 702 null, // response 703 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 704 "authTokenType", 705 true, // expectActivityLaunch 706 null); // optionsIn 707 fail("IllegalArgumentException expected. But no exception was thrown."); 708 } catch (IllegalArgumentException e) { 709 // IllegalArgumentException is expected. 710 } 711 } 712 713 @SmallTest testStartUpdateCredentialsSessionWithNullAccount()714 public void testStartUpdateCredentialsSessionWithNullAccount() throws Exception { 715 unlockSystemUser(); 716 try { 717 mAms.startUpdateCredentialsSession( 718 mMockAccountManagerResponse, // response 719 null, 720 "authTokenType", 721 true, // expectActivityLaunch 722 null); // optionsIn 723 fail("IllegalArgumentException expected. But no exception was thrown."); 724 } catch (IllegalArgumentException e) { 725 // IllegalArgumentException is expected. 726 } 727 } 728 729 @SmallTest testStartUpdateCredentialsSessionSuccessWithoutPasswordForwarding()730 public void testStartUpdateCredentialsSessionSuccessWithoutPasswordForwarding() 731 throws Exception { 732 unlockSystemUser(); 733 when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn( 734 PackageManager.PERMISSION_DENIED); 735 736 final CountDownLatch latch = new CountDownLatch(1); 737 Response response = new Response(latch, mMockAccountManagerResponse); 738 Bundle options = createOptionsWithAccountName( 739 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS); 740 mAms.startUpdateCredentialsSession( 741 response, // response 742 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 743 "authTokenType", 744 false, // expectActivityLaunch 745 options); // optionsIn 746 waitForLatch(latch); 747 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 748 Bundle result = mBundleCaptor.getValue(); 749 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE); 750 assertNotNull(sessionBundle); 751 // Assert that session bundle is encrypted and hence data not visible. 752 assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1)); 753 // Assert password is not returned 754 assertNull(result.getString(AccountManager.KEY_PASSWORD)); 755 assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null)); 756 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN, 757 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN)); 758 } 759 760 @SmallTest testStartUpdateCredentialsSessionSuccessWithPasswordForwarding()761 public void testStartUpdateCredentialsSessionSuccessWithPasswordForwarding() throws Exception { 762 unlockSystemUser(); 763 when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn( 764 PackageManager.PERMISSION_GRANTED); 765 766 final CountDownLatch latch = new CountDownLatch(1); 767 Response response = new Response(latch, mMockAccountManagerResponse); 768 Bundle options = createOptionsWithAccountName( 769 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS); 770 mAms.startUpdateCredentialsSession( 771 response, // response 772 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 773 "authTokenType", 774 false, // expectActivityLaunch 775 options); // optionsIn 776 777 waitForLatch(latch); 778 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 779 Bundle result = mBundleCaptor.getValue(); 780 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE); 781 assertNotNull(sessionBundle); 782 // Assert that session bundle is encrypted and hence data not visible. 783 assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1)); 784 // Assert password is returned 785 assertEquals(result.getString(AccountManager.KEY_PASSWORD), 786 AccountManagerServiceTestFixtures.ACCOUNT_PASSWORD); 787 assertNull(result.getString(AccountManager.KEY_AUTHTOKEN)); 788 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN, 789 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN)); 790 } 791 792 @SmallTest testStartUpdateCredentialsSessionReturnWithInvalidIntent()793 public void testStartUpdateCredentialsSessionReturnWithInvalidIntent() throws Exception { 794 unlockSystemUser(); 795 ResolveInfo resolveInfo = new ResolveInfo(); 796 resolveInfo.activityInfo = new ActivityInfo(); 797 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 798 when(mMockPackageManager.resolveActivityAsUser( 799 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 800 when(mMockPackageManager.checkSignatures( 801 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 802 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 803 .thenReturn(false); 804 805 final CountDownLatch latch = new CountDownLatch(1); 806 Response response = new Response(latch, mMockAccountManagerResponse); 807 Bundle options = createOptionsWithAccountName( 808 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE); 809 810 mAms.startUpdateCredentialsSession( 811 response, // response 812 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 813 "authTokenType", 814 true, // expectActivityLaunch 815 options); // optionsIn 816 817 waitForLatch(latch); 818 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 819 verify(mMockAccountManagerResponse).onError( 820 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 821 } 822 823 @SmallTest testStartUpdateCredentialsSessionReturnWithValidIntent()824 public void testStartUpdateCredentialsSessionReturnWithValidIntent() throws Exception { 825 unlockSystemUser(); 826 ResolveInfo resolveInfo = new ResolveInfo(); 827 resolveInfo.activityInfo = new ActivityInfo(); 828 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 829 when(mMockPackageManager.resolveActivityAsUser( 830 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 831 when(mMockPackageManager.checkSignatures( 832 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 833 834 final CountDownLatch latch = new CountDownLatch(1); 835 Response response = new Response(latch, mMockAccountManagerResponse); 836 Bundle options = createOptionsWithAccountName( 837 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE); 838 839 mAms.startUpdateCredentialsSession( 840 response, // response 841 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 842 "authTokenType", 843 true, // expectActivityLaunch 844 options); // optionsIn 845 846 waitForLatch(latch); 847 848 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 849 Bundle result = mBundleCaptor.getValue(); 850 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 851 assertNotNull(intent); 852 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 853 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 854 } 855 856 @SmallTest testStartUpdateCredentialsSessionError()857 public void testStartUpdateCredentialsSessionError() throws Exception { 858 unlockSystemUser(); 859 Bundle options = createOptionsWithAccountName( 860 AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR); 861 options.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_INVALID_RESPONSE); 862 options.putString(AccountManager.KEY_ERROR_MESSAGE, 863 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 864 865 final CountDownLatch latch = new CountDownLatch(1); 866 Response response = new Response(latch, mMockAccountManagerResponse); 867 868 mAms.startUpdateCredentialsSession( 869 response, // response 870 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, 871 "authTokenType", 872 true, // expectActivityLaunch 873 options); // optionsIn 874 875 waitForLatch(latch); 876 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 877 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 878 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 879 } 880 881 @SmallTest testFinishSessionAsUserWithNullResponse()882 public void testFinishSessionAsUserWithNullResponse() throws Exception { 883 unlockSystemUser(); 884 try { 885 mAms.finishSessionAsUser( 886 null, // response 887 createEncryptedSessionBundle( 888 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 889 false, // expectActivityLaunch 890 createAppBundle(), // appInfo 891 UserHandle.USER_SYSTEM); 892 fail("IllegalArgumentException expected. But no exception was thrown."); 893 } catch (IllegalArgumentException e) { 894 // IllegalArgumentException is expected. 895 } 896 } 897 898 @SmallTest testFinishSessionAsUserWithNullSessionBundle()899 public void testFinishSessionAsUserWithNullSessionBundle() throws Exception { 900 unlockSystemUser(); 901 try { 902 mAms.finishSessionAsUser( 903 mMockAccountManagerResponse, // response 904 null, // sessionBundle 905 false, // expectActivityLaunch 906 createAppBundle(), // appInfo 907 UserHandle.USER_SYSTEM); 908 fail("IllegalArgumentException expected. But no exception was thrown."); 909 } catch (IllegalArgumentException e) { 910 // IllegalArgumentException is expected. 911 } 912 } 913 914 @SmallTest testFinishSessionAsUserUserCannotModifyAccountNoDPM()915 public void testFinishSessionAsUserUserCannotModifyAccountNoDPM() throws Exception { 916 unlockSystemUser(); 917 Bundle bundle = new Bundle(); 918 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 919 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 920 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 921 922 mAms.finishSessionAsUser( 923 mMockAccountManagerResponse, // response 924 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 925 false, // expectActivityLaunch 926 createAppBundle(), // appInfo 927 2); // fake user id 928 929 verify(mMockAccountManagerResponse).onError( 930 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 931 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.of(2))); 932 933 // verify the intent for default CantAddAccountActivity is sent. 934 Intent intent = mIntentCaptor.getValue(); 935 assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName()); 936 assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0), 937 AccountManager.ERROR_CODE_USER_RESTRICTED); 938 } 939 940 @SmallTest testFinishSessionAsUserUserCannotModifyAccountWithDPM()941 public void testFinishSessionAsUserUserCannotModifyAccountWithDPM() throws Exception { 942 unlockSystemUser(); 943 Bundle bundle = new Bundle(); 944 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 945 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 946 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 947 LocalServices.addService( 948 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal); 949 when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent( 950 anyInt(), anyString())).thenReturn(new Intent()); 951 when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent( 952 anyInt(), anyBoolean())).thenReturn(new Intent()); 953 954 mAms.finishSessionAsUser( 955 mMockAccountManagerResponse, // response 956 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 957 false, // expectActivityLaunch 958 createAppBundle(), // appInfo 959 2); // fake user id 960 961 verify(mMockAccountManagerResponse).onError( 962 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 963 verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.of(2))); 964 verify(mMockDevicePolicyManagerInternal).createUserRestrictionSupportIntent( 965 anyInt(), anyString()); 966 } 967 968 @SmallTest testFinishSessionAsUserWithBadSessionBundle()969 public void testFinishSessionAsUserWithBadSessionBundle() throws Exception { 970 unlockSystemUser(); 971 972 Bundle badSessionBundle = new Bundle(); 973 badSessionBundle.putString("any", "any"); 974 mAms.finishSessionAsUser( 975 mMockAccountManagerResponse, // response 976 badSessionBundle, // sessionBundle 977 false, // expectActivityLaunch 978 createAppBundle(), // appInfo 979 2); // fake user id 980 981 verify(mMockAccountManagerResponse).onError( 982 eq(AccountManager.ERROR_CODE_BAD_REQUEST), anyString()); 983 } 984 985 @SmallTest testFinishSessionAsUserWithBadAccountType()986 public void testFinishSessionAsUserWithBadAccountType() throws Exception { 987 unlockSystemUser(); 988 989 mAms.finishSessionAsUser( 990 mMockAccountManagerResponse, // response 991 createEncryptedSessionBundleWithNoAccountType( 992 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 993 false, // expectActivityLaunch 994 createAppBundle(), // appInfo 995 2); // fake user id 996 997 verify(mMockAccountManagerResponse).onError( 998 eq(AccountManager.ERROR_CODE_BAD_ARGUMENTS), anyString()); 999 } 1000 1001 @SmallTest testFinishSessionAsUserUserCannotModifyAccountForTypeNoDPM()1002 public void testFinishSessionAsUserUserCannotModifyAccountForTypeNoDPM() throws Exception { 1003 unlockSystemUser(); 1004 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 1005 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 1006 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 1007 1008 mAms.finishSessionAsUser( 1009 mMockAccountManagerResponse, // response 1010 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 1011 false, // expectActivityLaunch 1012 createAppBundle(), // appInfo 1013 2); // fake user id 1014 1015 verify(mMockAccountManagerResponse).onError( 1016 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 1017 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.of(2))); 1018 1019 // verify the intent for default CantAddAccountActivity is sent. 1020 Intent intent = mIntentCaptor.getValue(); 1021 assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName()); 1022 assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0), 1023 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE); 1024 } 1025 1026 @SmallTest testFinishSessionAsUserUserCannotModifyAccountForTypeWithDPM()1027 public void testFinishSessionAsUserUserCannotModifyAccountForTypeWithDPM() throws Exception { 1028 unlockSystemUser(); 1029 when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn( 1030 mMockDevicePolicyManager); 1031 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 1032 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 1033 1034 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 1035 LocalServices.addService( 1036 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal); 1037 when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent( 1038 anyInt(), anyString())).thenReturn(new Intent()); 1039 when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent( 1040 anyInt(), anyBoolean())).thenReturn(new Intent()); 1041 1042 mAms.finishSessionAsUser( 1043 mMockAccountManagerResponse, // response 1044 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 1045 false, // expectActivityLaunch 1046 createAppBundle(), // appInfo 1047 2); // fake user id 1048 1049 verify(mMockAccountManagerResponse).onError( 1050 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 1051 verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.of(2))); 1052 verify(mMockDevicePolicyManagerInternal).createShowAdminSupportIntent( 1053 anyInt(), anyBoolean()); 1054 } 1055 1056 @SmallTest testFinishSessionAsUserSuccess()1057 public void testFinishSessionAsUserSuccess() throws Exception { 1058 unlockSystemUser(); 1059 final CountDownLatch latch = new CountDownLatch(1); 1060 Response response = new Response(latch, mMockAccountManagerResponse); 1061 mAms.finishSessionAsUser( 1062 response, // response 1063 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 1064 false, // expectActivityLaunch 1065 createAppBundle(), // appInfo 1066 UserHandle.USER_SYSTEM); 1067 1068 waitForLatch(latch); 1069 // Verify notification is cancelled 1070 verify(mMockNotificationManager).cancelNotificationWithTag(anyString(), 1071 anyString(), nullable(String.class), anyInt(), anyInt()); 1072 1073 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1074 Bundle result = mBundleCaptor.getValue(); 1075 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE); 1076 assertNotNull(sessionBundle); 1077 // Assert that session bundle is decrypted and hence data is visible. 1078 assertEquals(AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1, 1079 sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1)); 1080 // Assert finishSessionAsUser added calling uid and pid into the sessionBundle 1081 assertTrue(sessionBundle.containsKey(AccountManager.KEY_CALLER_UID)); 1082 assertTrue(sessionBundle.containsKey(AccountManager.KEY_CALLER_PID)); 1083 assertEquals(sessionBundle.getString( 1084 AccountManager.KEY_ANDROID_PACKAGE_NAME), "APCT.package"); 1085 1086 // Verify response data 1087 assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null)); 1088 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME, 1089 result.getString(AccountManager.KEY_ACCOUNT_NAME)); 1090 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 1091 result.getString(AccountManager.KEY_ACCOUNT_TYPE)); 1092 } 1093 1094 @SmallTest testFinishSessionAsUserReturnWithInvalidIntent()1095 public void testFinishSessionAsUserReturnWithInvalidIntent() throws Exception { 1096 unlockSystemUser(); 1097 ResolveInfo resolveInfo = new ResolveInfo(); 1098 resolveInfo.activityInfo = new ActivityInfo(); 1099 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 1100 when(mMockPackageManager.resolveActivityAsUser( 1101 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 1102 when(mMockPackageManager.checkSignatures( 1103 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 1104 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 1105 .thenReturn(false); 1106 1107 final CountDownLatch latch = new CountDownLatch(1); 1108 Response response = new Response(latch, mMockAccountManagerResponse); 1109 1110 mAms.finishSessionAsUser( 1111 response, // response 1112 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE), 1113 true, // expectActivityLaunch 1114 createAppBundle(), // appInfo 1115 UserHandle.USER_SYSTEM); 1116 1117 waitForLatch(latch); 1118 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1119 verify(mMockAccountManagerResponse).onError( 1120 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 1121 } 1122 1123 @SmallTest testFinishSessionAsUserReturnWithValidIntent()1124 public void testFinishSessionAsUserReturnWithValidIntent() throws Exception { 1125 unlockSystemUser(); 1126 ResolveInfo resolveInfo = new ResolveInfo(); 1127 resolveInfo.activityInfo = new ActivityInfo(); 1128 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 1129 when(mMockPackageManager.resolveActivityAsUser( 1130 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 1131 when(mMockPackageManager.checkSignatures( 1132 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 1133 1134 final CountDownLatch latch = new CountDownLatch(1); 1135 Response response = new Response(latch, mMockAccountManagerResponse); 1136 1137 mAms.finishSessionAsUser( 1138 response, // response 1139 createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE), 1140 true, // expectActivityLaunch 1141 createAppBundle(), // appInfo 1142 UserHandle.USER_SYSTEM); 1143 1144 waitForLatch(latch); 1145 1146 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1147 Bundle result = mBundleCaptor.getValue(); 1148 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 1149 assertNotNull(intent); 1150 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 1151 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 1152 } 1153 1154 @SmallTest testFinishSessionAsUserError()1155 public void testFinishSessionAsUserError() throws Exception { 1156 unlockSystemUser(); 1157 Bundle sessionBundle = createEncryptedSessionBundleWithError( 1158 AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR); 1159 1160 final CountDownLatch latch = new CountDownLatch(1); 1161 Response response = new Response(latch, mMockAccountManagerResponse); 1162 1163 mAms.finishSessionAsUser( 1164 response, // response 1165 sessionBundle, 1166 false, // expectActivityLaunch 1167 createAppBundle(), // appInfo 1168 UserHandle.USER_SYSTEM); 1169 1170 waitForLatch(latch); 1171 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 1172 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 1173 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1174 } 1175 1176 @SmallTest testIsCredentialsUpdatedSuggestedWithNullResponse()1177 public void testIsCredentialsUpdatedSuggestedWithNullResponse() throws Exception { 1178 unlockSystemUser(); 1179 try { 1180 mAms.isCredentialsUpdateSuggested( 1181 null, // response 1182 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1183 AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN); 1184 fail("IllegalArgumentException expected. But no exception was thrown."); 1185 } catch (IllegalArgumentException e) { 1186 // IllegalArgumentException is expected. 1187 } 1188 } 1189 1190 @SmallTest testIsCredentialsUpdatedSuggestedWithNullAccount()1191 public void testIsCredentialsUpdatedSuggestedWithNullAccount() throws Exception { 1192 unlockSystemUser(); 1193 try { 1194 mAms.isCredentialsUpdateSuggested( 1195 mMockAccountManagerResponse, 1196 null, // account 1197 AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN); 1198 fail("IllegalArgumentException expected. But no exception was thrown."); 1199 } catch (IllegalArgumentException e) { 1200 // IllegalArgumentException is expected. 1201 } 1202 } 1203 1204 @SmallTest testIsCredentialsUpdatedSuggestedWithEmptyStatusToken()1205 public void testIsCredentialsUpdatedSuggestedWithEmptyStatusToken() throws Exception { 1206 unlockSystemUser(); 1207 try { 1208 mAms.isCredentialsUpdateSuggested( 1209 mMockAccountManagerResponse, 1210 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1211 null); 1212 fail("IllegalArgumentException expected. But no exception was thrown."); 1213 } catch (IllegalArgumentException e) { 1214 // IllegalArgumentException is expected. 1215 } 1216 } 1217 1218 @SmallTest testIsCredentialsUpdatedSuggestedError()1219 public void testIsCredentialsUpdatedSuggestedError() throws Exception { 1220 unlockSystemUser(); 1221 final CountDownLatch latch = new CountDownLatch(1); 1222 Response response = new Response(latch, mMockAccountManagerResponse); 1223 1224 mAms.isCredentialsUpdateSuggested( 1225 response, 1226 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, 1227 AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN); 1228 1229 waitForLatch(latch); 1230 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 1231 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 1232 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1233 } 1234 1235 @SmallTest testIsCredentialsUpdatedSuggestedSuccess()1236 public void testIsCredentialsUpdatedSuggestedSuccess() throws Exception { 1237 unlockSystemUser(); 1238 final CountDownLatch latch = new CountDownLatch(1); 1239 Response response = new Response(latch, mMockAccountManagerResponse); 1240 1241 mAms.isCredentialsUpdateSuggested( 1242 response, 1243 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1244 AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN); 1245 1246 waitForLatch(latch); 1247 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1248 Bundle result = mBundleCaptor.getValue(); 1249 boolean needUpdate = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT); 1250 assertTrue(needUpdate); 1251 } 1252 1253 @SmallTest testHasFeaturesWithNullResponse()1254 public void testHasFeaturesWithNullResponse() throws Exception { 1255 unlockSystemUser(); 1256 try { 1257 mAms.hasFeatures( 1258 null, // response 1259 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1260 new String[] {"feature1", "feature2"}, // features 1261 "testPackage"); // opPackageName 1262 fail("IllegalArgumentException expected. But no exception was thrown."); 1263 } catch (IllegalArgumentException e) { 1264 // IllegalArgumentException is expected. 1265 } 1266 } 1267 1268 @SmallTest testHasFeaturesWithNullAccount()1269 public void testHasFeaturesWithNullAccount() throws Exception { 1270 unlockSystemUser(); 1271 try { 1272 mAms.hasFeatures( 1273 mMockAccountManagerResponse, // response 1274 null, // account 1275 new String[] {"feature1", "feature2"}, // features 1276 "testPackage"); // opPackageName 1277 fail("IllegalArgumentException expected. But no exception was thrown."); 1278 } catch (IllegalArgumentException e) { 1279 // IllegalArgumentException is expected. 1280 } 1281 } 1282 1283 @SmallTest testHasFeaturesWithNullFeature()1284 public void testHasFeaturesWithNullFeature() throws Exception { 1285 unlockSystemUser(); 1286 try { 1287 mAms.hasFeatures( 1288 mMockAccountManagerResponse, // response 1289 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, // account 1290 null, // features 1291 "testPackage"); // opPackageName 1292 fail("IllegalArgumentException expected. But no exception was thrown."); 1293 } catch (IllegalArgumentException e) { 1294 // IllegalArgumentException is expected. 1295 } 1296 } 1297 1298 @SmallTest testHasFeaturesReturnNullResult()1299 public void testHasFeaturesReturnNullResult() throws Exception { 1300 unlockSystemUser(); 1301 final CountDownLatch latch = new CountDownLatch(1); 1302 Response response = new Response(latch, mMockAccountManagerResponse); 1303 mAms.hasFeatures( 1304 response, // response 1305 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, // account 1306 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, // features 1307 "testPackage"); // opPackageName 1308 waitForLatch(latch); 1309 verify(mMockAccountManagerResponse).onError( 1310 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 1311 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1312 } 1313 1314 @SmallTest testHasFeaturesSuccess()1315 public void testHasFeaturesSuccess() throws Exception { 1316 unlockSystemUser(); 1317 final CountDownLatch latch = new CountDownLatch(1); 1318 Response response = new Response(latch, mMockAccountManagerResponse); 1319 mAms.hasFeatures( 1320 response, // response 1321 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, // account 1322 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, // features 1323 "testPackage"); // opPackageName 1324 waitForLatch(latch); 1325 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1326 Bundle result = mBundleCaptor.getValue(); 1327 boolean hasFeatures = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT); 1328 assertTrue(hasFeatures); 1329 } 1330 1331 @SmallTest testRemoveAccountAsUserWithNullResponse()1332 public void testRemoveAccountAsUserWithNullResponse() throws Exception { 1333 unlockSystemUser(); 1334 try { 1335 mAms.removeAccountAsUser( 1336 null, // response 1337 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1338 true, // expectActivityLaunch 1339 UserHandle.USER_SYSTEM); 1340 fail("IllegalArgumentException expected. But no exception was thrown."); 1341 } catch (IllegalArgumentException e) { 1342 // IllegalArgumentException is expected. 1343 } 1344 } 1345 1346 @SmallTest testRemoveAccountAsUserWithNullAccount()1347 public void testRemoveAccountAsUserWithNullAccount() throws Exception { 1348 unlockSystemUser(); 1349 try { 1350 mAms.removeAccountAsUser( 1351 mMockAccountManagerResponse, // response 1352 null, // account 1353 true, // expectActivityLaunch 1354 UserHandle.USER_SYSTEM); 1355 fail("IllegalArgumentException expected. But no exception was thrown."); 1356 } catch (IllegalArgumentException e) { 1357 // IllegalArgumentException is expected. 1358 } 1359 } 1360 1361 @SmallTest testRemoveAccountAsUserAccountNotManagedByCaller()1362 public void testRemoveAccountAsUserAccountNotManagedByCaller() throws Exception { 1363 unlockSystemUser(); 1364 when(mMockPackageManager.checkSignatures(anyInt(), anyInt())) 1365 .thenReturn(PackageManager.SIGNATURE_NO_MATCH); 1366 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 1367 .thenReturn(false); 1368 try { 1369 mAms.removeAccountAsUser( 1370 mMockAccountManagerResponse, // response 1371 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1372 true, // expectActivityLaunch 1373 UserHandle.USER_SYSTEM); 1374 fail("SecurityException expected. But no exception was thrown."); 1375 } catch (SecurityException e) { 1376 // SecurityException is expected. 1377 } 1378 } 1379 1380 @SmallTest testRemoveAccountAsUserUserCannotModifyAccount()1381 public void testRemoveAccountAsUserUserCannotModifyAccount() throws Exception { 1382 unlockSystemUser(); 1383 Bundle bundle = new Bundle(); 1384 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 1385 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 1386 1387 final CountDownLatch latch = new CountDownLatch(1); 1388 Response response = new Response(latch, mMockAccountManagerResponse); 1389 1390 mAms.removeAccountAsUser( 1391 response, // response 1392 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1393 true, // expectActivityLaunch 1394 UserHandle.USER_SYSTEM); 1395 waitForLatch(latch); 1396 verify(mMockAccountManagerResponse).onError( 1397 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 1398 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1399 } 1400 1401 @SmallTest testRemoveAccountAsUserUserCannotModifyAccountType()1402 public void testRemoveAccountAsUserUserCannotModifyAccountType() throws Exception { 1403 unlockSystemUser(); 1404 when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn( 1405 mMockDevicePolicyManager); 1406 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 1407 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 1408 1409 final CountDownLatch latch = new CountDownLatch(1); 1410 Response response = new Response(latch, mMockAccountManagerResponse); 1411 1412 mAms.removeAccountAsUser( 1413 response, // response 1414 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1415 true, // expectActivityLaunch 1416 UserHandle.USER_SYSTEM); 1417 waitForLatch(latch); 1418 verify(mMockAccountManagerResponse).onError( 1419 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 1420 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1421 } 1422 1423 @SmallTest testRemoveAccountAsUserRemovalAllowed()1424 public void testRemoveAccountAsUserRemovalAllowed() throws Exception { 1425 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 1426 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1427 1428 unlockSystemUser(); 1429 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p1", null); 1430 Account[] addedAccounts = 1431 mAms.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName()); 1432 assertEquals(1, addedAccounts.length); 1433 1434 final CountDownLatch latch = new CountDownLatch(1); 1435 Response response = new Response(latch, mMockAccountManagerResponse); 1436 1437 mAms.removeAccountAsUser( 1438 response, // response 1439 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1440 true, // expectActivityLaunch 1441 UserHandle.USER_SYSTEM); 1442 waitForLatch(latch); 1443 1444 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1445 Bundle result = mBundleCaptor.getValue(); 1446 boolean allowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT); 1447 assertTrue(allowed); 1448 Account[] accounts = mAms.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName()); 1449 assertEquals(0, accounts.length); 1450 } 1451 1452 @SmallTest testRemoveAccountAsUserRemovalNotAllowed()1453 public void testRemoveAccountAsUserRemovalNotAllowed() throws Exception { 1454 unlockSystemUser(); 1455 1456 final CountDownLatch latch = new CountDownLatch(1); 1457 Response response = new Response(latch, mMockAccountManagerResponse); 1458 1459 mAms.removeAccountAsUser( 1460 response, // response 1461 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, 1462 true, // expectActivityLaunch 1463 UserHandle.USER_SYSTEM); 1464 waitForLatch(latch); 1465 1466 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1467 Bundle result = mBundleCaptor.getValue(); 1468 boolean allowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT); 1469 assertFalse(allowed); 1470 } 1471 1472 @SmallTest testRemoveAccountAsUserReturnWithValidIntent()1473 public void testRemoveAccountAsUserReturnWithValidIntent() throws Exception { 1474 unlockSystemUser(); 1475 ResolveInfo resolveInfo = new ResolveInfo(); 1476 resolveInfo.activityInfo = new ActivityInfo(); 1477 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 1478 when(mMockPackageManager.resolveActivityAsUser( 1479 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 1480 when(mMockPackageManager.checkSignatures( 1481 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 1482 1483 final CountDownLatch latch = new CountDownLatch(1); 1484 Response response = new Response(latch, mMockAccountManagerResponse); 1485 1486 mAms.removeAccountAsUser( 1487 response, // response 1488 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 1489 true, // expectActivityLaunch 1490 UserHandle.USER_SYSTEM); 1491 waitForLatch(latch); 1492 1493 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1494 Bundle result = mBundleCaptor.getValue(); 1495 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 1496 assertNotNull(intent); 1497 } 1498 1499 @SmallTest testGetAccountsByTypeForPackageWhenTypeIsNull()1500 public void testGetAccountsByTypeForPackageWhenTypeIsNull() throws Exception { 1501 unlockSystemUser(); 1502 HashMap<String, Integer> visibility1 = new HashMap<>(); 1503 visibility1.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE, 1504 AccountManager.VISIBILITY_USER_MANAGED_VISIBLE); 1505 1506 HashMap<String, Integer> visibility2 = new HashMap<>(); 1507 visibility2.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE, 1508 AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE); 1509 1510 mAms.addAccountExplicitlyWithVisibility( 1511 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "P11", null, visibility1); 1512 mAms.addAccountExplicitlyWithVisibility( 1513 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "P12", null, visibility2); 1514 1515 Account[] accounts = mAms.getAccountsByTypeForPackage( 1516 null, "otherPackageName", 1517 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 1518 // Only get the USER_MANAGED_NOT_VISIBLE account. 1519 assertEquals(1, accounts.length); 1520 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, accounts[0].name); 1521 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, accounts[0].type); 1522 } 1523 1524 @SmallTest testGetAuthTokenLabelWithNullAccountType()1525 public void testGetAuthTokenLabelWithNullAccountType() throws Exception { 1526 unlockSystemUser(); 1527 try { 1528 mAms.getAuthTokenLabel( 1529 mMockAccountManagerResponse, // response 1530 null, // accountType 1531 "authTokenType"); 1532 fail("IllegalArgumentException expected. But no exception was thrown."); 1533 } catch (IllegalArgumentException e) { 1534 // IllegalArgumentException is expected. 1535 } 1536 } 1537 1538 @SmallTest testGetAuthTokenLabelWithNullAuthTokenType()1539 public void testGetAuthTokenLabelWithNullAuthTokenType() throws Exception { 1540 unlockSystemUser(); 1541 try { 1542 mAms.getAuthTokenLabel( 1543 mMockAccountManagerResponse, // response 1544 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1545 null); // authTokenType 1546 fail("IllegalArgumentException expected. But no exception was thrown."); 1547 } catch (IllegalArgumentException e) { 1548 // IllegalArgumentException is expected. 1549 } 1550 } 1551 1552 @SmallTest testGetAuthTokenWithNullResponse()1553 public void testGetAuthTokenWithNullResponse() throws Exception { 1554 unlockSystemUser(); 1555 try { 1556 mAms.getAuthToken( 1557 null, // response 1558 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1559 "authTokenType", // authTokenType 1560 true, // notifyOnAuthFailure 1561 true, // expectActivityLaunch 1562 createGetAuthTokenOptions()); 1563 fail("IllegalArgumentException expected. But no exception was thrown."); 1564 } catch (IllegalArgumentException e) { 1565 // IllegalArgumentException is expected. 1566 } 1567 } 1568 1569 @SmallTest testGetAuthTokenWithNullAccount()1570 public void testGetAuthTokenWithNullAccount() throws Exception { 1571 unlockSystemUser(); 1572 final CountDownLatch latch = new CountDownLatch(1); 1573 Response response = new Response(latch, mMockAccountManagerResponse); 1574 mAms.getAuthToken( 1575 response, // response 1576 null, // account 1577 "authTokenType", // authTokenType 1578 true, // notifyOnAuthFailure 1579 true, // expectActivityLaunch 1580 createGetAuthTokenOptions()); 1581 waitForLatch(latch); 1582 1583 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1584 verify(mMockAccountManagerResponse).onError( 1585 eq(AccountManager.ERROR_CODE_BAD_ARGUMENTS), anyString()); 1586 } 1587 1588 @SmallTest testGetAuthTokenWithNullAuthTokenType()1589 public void testGetAuthTokenWithNullAuthTokenType() throws Exception { 1590 unlockSystemUser(); 1591 final CountDownLatch latch = new CountDownLatch(1); 1592 Response response = new Response(latch, mMockAccountManagerResponse); 1593 mAms.getAuthToken( 1594 response, // response 1595 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1596 null, // authTokenType 1597 true, // notifyOnAuthFailure 1598 true, // expectActivityLaunch 1599 createGetAuthTokenOptions()); 1600 waitForLatch(latch); 1601 1602 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1603 verify(mMockAccountManagerResponse).onError( 1604 eq(AccountManager.ERROR_CODE_BAD_ARGUMENTS), anyString()); 1605 } 1606 1607 @SmallTest testGetAuthTokenWithInvalidPackage()1608 public void testGetAuthTokenWithInvalidPackage() throws Exception { 1609 unlockSystemUser(); 1610 String[] list = new String[]{"test"}; 1611 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1612 try { 1613 mAms.getAuthToken( 1614 mMockAccountManagerResponse, // response 1615 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1616 "authTokenType", // authTokenType 1617 true, // notifyOnAuthFailure 1618 true, // expectActivityLaunch 1619 createGetAuthTokenOptions()); 1620 fail("SecurityException expected. But no exception was thrown."); 1621 } catch (SecurityException e) { 1622 // SecurityException is expected. 1623 } 1624 } 1625 1626 @SmallTest testGetAuthTokenFromInternal()1627 public void testGetAuthTokenFromInternal() throws Exception { 1628 unlockSystemUser(); 1629 when(mMockContext.createPackageContextAsUser( 1630 anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext); 1631 when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); 1632 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 1633 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1634 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 1635 1636 mAms.setAuthToken(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1637 "authTokenType", AccountManagerServiceTestFixtures.AUTH_TOKEN); 1638 final CountDownLatch latch = new CountDownLatch(1); 1639 Response response = new Response(latch, mMockAccountManagerResponse); 1640 mAms.getAuthToken( 1641 response, // response 1642 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1643 "authTokenType", // authTokenType 1644 true, // notifyOnAuthFailure 1645 true, // expectActivityLaunch 1646 createGetAuthTokenOptions()); 1647 waitForLatch(latch); 1648 1649 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1650 Bundle result = mBundleCaptor.getValue(); 1651 assertEquals(result.getString(AccountManager.KEY_AUTHTOKEN), 1652 AccountManagerServiceTestFixtures.AUTH_TOKEN); 1653 assertEquals(result.getString(AccountManager.KEY_ACCOUNT_NAME), 1654 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS); 1655 assertEquals(result.getString(AccountManager.KEY_ACCOUNT_TYPE), 1656 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 1657 } 1658 1659 @SmallTest testGetAuthTokenSuccess()1660 public void testGetAuthTokenSuccess() throws Exception { 1661 unlockSystemUser(); 1662 when(mMockContext.createPackageContextAsUser( 1663 anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext); 1664 when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); 1665 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 1666 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1667 1668 final CountDownLatch latch = new CountDownLatch(1); 1669 Response response = new Response(latch, mMockAccountManagerResponse); 1670 mAms.getAuthToken( 1671 response, // response 1672 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 1673 "authTokenType", // authTokenType 1674 true, // notifyOnAuthFailure 1675 false, // expectActivityLaunch 1676 createGetAuthTokenOptions()); 1677 waitForLatch(latch); 1678 1679 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1680 Bundle result = mBundleCaptor.getValue(); 1681 assertEquals(result.getString(AccountManager.KEY_AUTHTOKEN), 1682 AccountManagerServiceTestFixtures.AUTH_TOKEN); 1683 assertEquals(result.getString(AccountManager.KEY_ACCOUNT_NAME), 1684 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS); 1685 assertEquals(result.getString(AccountManager.KEY_ACCOUNT_TYPE), 1686 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 1687 } 1688 1689 @SmallTest testGetAuthTokenReturnWithInvalidIntent()1690 public void testGetAuthTokenReturnWithInvalidIntent() throws Exception { 1691 unlockSystemUser(); 1692 when(mMockContext.createPackageContextAsUser( 1693 anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext); 1694 when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); 1695 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 1696 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1697 ResolveInfo resolveInfo = new ResolveInfo(); 1698 resolveInfo.activityInfo = new ActivityInfo(); 1699 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 1700 when(mMockPackageManager.resolveActivityAsUser( 1701 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 1702 when(mMockPackageManager.checkSignatures( 1703 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 1704 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 1705 .thenReturn(false); 1706 1707 final CountDownLatch latch = new CountDownLatch(1); 1708 Response response = new Response(latch, mMockAccountManagerResponse); 1709 mAms.getAuthToken( 1710 response, // response 1711 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 1712 "authTokenType", // authTokenType 1713 true, // notifyOnAuthFailure 1714 false, // expectActivityLaunch 1715 createGetAuthTokenOptions()); 1716 waitForLatch(latch); 1717 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1718 verify(mMockAccountManagerResponse).onError( 1719 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 1720 } 1721 1722 @SmallTest testGetAuthTokenReturnWithValidIntent()1723 public void testGetAuthTokenReturnWithValidIntent() throws Exception { 1724 unlockSystemUser(); 1725 when(mMockContext.createPackageContextAsUser( 1726 anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext); 1727 when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); 1728 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 1729 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1730 1731 ResolveInfo resolveInfo = new ResolveInfo(); 1732 resolveInfo.activityInfo = new ActivityInfo(); 1733 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 1734 when(mMockPackageManager.resolveActivityAsUser( 1735 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 1736 when(mMockPackageManager.checkSignatures( 1737 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 1738 1739 final CountDownLatch latch = new CountDownLatch(1); 1740 Response response = new Response(latch, mMockAccountManagerResponse); 1741 mAms.getAuthToken( 1742 response, // response 1743 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 1744 "authTokenType", // authTokenType 1745 false, // notifyOnAuthFailure 1746 true, // expectActivityLaunch 1747 createGetAuthTokenOptions()); 1748 waitForLatch(latch); 1749 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1750 Bundle result = mBundleCaptor.getValue(); 1751 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 1752 assertNotNull(intent); 1753 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 1754 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 1755 } 1756 1757 @SmallTest testGetAuthTokenError()1758 public void testGetAuthTokenError() throws Exception { 1759 unlockSystemUser(); 1760 when(mMockContext.createPackageContextAsUser( 1761 anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext); 1762 when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); 1763 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 1764 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 1765 final CountDownLatch latch = new CountDownLatch(1); 1766 Response response = new Response(latch, mMockAccountManagerResponse); 1767 mAms.getAuthToken( 1768 response, // response 1769 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, 1770 "authTokenType", // authTokenType 1771 true, // notifyOnAuthFailure 1772 false, // expectActivityLaunch 1773 createGetAuthTokenOptions()); 1774 waitForLatch(latch); 1775 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 1776 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 1777 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1778 1779 } 1780 1781 @SmallTest testAddAccountAsUserWithNullResponse()1782 public void testAddAccountAsUserWithNullResponse() throws Exception { 1783 unlockSystemUser(); 1784 try { 1785 mAms.addAccountAsUser( 1786 null, // response 1787 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 1788 "authTokenType", 1789 null, // requiredFeatures 1790 true, // expectActivityLaunch 1791 null, // optionsIn 1792 UserHandle.USER_SYSTEM); 1793 fail("IllegalArgumentException expected. But no exception was thrown."); 1794 } catch (IllegalArgumentException e) { 1795 // IllegalArgumentException is expected. 1796 } 1797 } 1798 1799 @SmallTest testAddAccountAsUserWithNullAccountType()1800 public void testAddAccountAsUserWithNullAccountType() throws Exception { 1801 unlockSystemUser(); 1802 try { 1803 mAms.addAccountAsUser( 1804 mMockAccountManagerResponse, // response 1805 null, // accountType 1806 "authTokenType", 1807 null, // requiredFeatures 1808 true, // expectActivityLaunch 1809 null, // optionsIn 1810 UserHandle.USER_SYSTEM); 1811 fail("IllegalArgumentException expected. But no exception was thrown."); 1812 } catch (IllegalArgumentException e) { 1813 // IllegalArgumentException is expected. 1814 } 1815 } 1816 1817 @SmallTest testAddAccountAsUserUserCannotModifyAccountNoDPM()1818 public void testAddAccountAsUserUserCannotModifyAccountNoDPM() throws Exception { 1819 unlockSystemUser(); 1820 Bundle bundle = new Bundle(); 1821 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 1822 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 1823 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 1824 1825 mAms.addAccountAsUser( 1826 mMockAccountManagerResponse, // response 1827 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1828 "authTokenType", 1829 null, // requiredFeatures 1830 true, // expectActivityLaunch 1831 null, // optionsIn 1832 UserHandle.USER_SYSTEM); 1833 verify(mMockAccountManagerResponse).onError( 1834 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 1835 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 1836 1837 // verify the intent for default CantAddAccountActivity is sent. 1838 Intent intent = mIntentCaptor.getValue(); 1839 assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName()); 1840 assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0), 1841 AccountManager.ERROR_CODE_USER_RESTRICTED); 1842 } 1843 1844 @SmallTest testAddAccountAsUserUserCannotModifyAccountWithDPM()1845 public void testAddAccountAsUserUserCannotModifyAccountWithDPM() throws Exception { 1846 unlockSystemUser(); 1847 Bundle bundle = new Bundle(); 1848 bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true); 1849 when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle); 1850 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 1851 LocalServices.addService( 1852 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal); 1853 when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent( 1854 anyInt(), anyString())).thenReturn(new Intent()); 1855 when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent( 1856 anyInt(), anyBoolean())).thenReturn(new Intent()); 1857 1858 mAms.addAccountAsUser( 1859 mMockAccountManagerResponse, // response 1860 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1861 "authTokenType", 1862 null, // requiredFeatures 1863 true, // expectActivityLaunch 1864 null, // optionsIn 1865 UserHandle.USER_SYSTEM); 1866 1867 verify(mMockAccountManagerResponse).onError( 1868 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString()); 1869 verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM)); 1870 verify(mMockDevicePolicyManagerInternal).createUserRestrictionSupportIntent( 1871 anyInt(), anyString()); 1872 } 1873 1874 @SmallTest testAddAccountAsUserUserCannotModifyAccountForTypeNoDPM()1875 public void testAddAccountAsUserUserCannotModifyAccountForTypeNoDPM() throws Exception { 1876 unlockSystemUser(); 1877 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 1878 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 1879 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 1880 1881 mAms.addAccountAsUser( 1882 mMockAccountManagerResponse, // response 1883 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1884 "authTokenType", 1885 null, // requiredFeatures 1886 true, // expectActivityLaunch 1887 null, // optionsIn 1888 UserHandle.USER_SYSTEM); 1889 1890 verify(mMockAccountManagerResponse).onError( 1891 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 1892 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 1893 1894 // verify the intent for default CantAddAccountActivity is sent. 1895 Intent intent = mIntentCaptor.getValue(); 1896 assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName()); 1897 assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0), 1898 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE); 1899 } 1900 1901 @SmallTest testAddAccountAsUserUserCannotModifyAccountForTypeWithDPM()1902 public void testAddAccountAsUserUserCannotModifyAccountForTypeWithDPM() throws Exception { 1903 unlockSystemUser(); 1904 when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn( 1905 mMockDevicePolicyManager); 1906 when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt())) 1907 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"}); 1908 1909 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class); 1910 LocalServices.addService( 1911 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal); 1912 when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent( 1913 anyInt(), anyString())).thenReturn(new Intent()); 1914 when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent( 1915 anyInt(), anyBoolean())).thenReturn(new Intent()); 1916 1917 mAms.addAccountAsUser( 1918 mMockAccountManagerResponse, // response 1919 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1920 "authTokenType", 1921 null, // requiredFeatures 1922 true, // expectActivityLaunch 1923 null, // optionsIn 1924 UserHandle.USER_SYSTEM); 1925 1926 verify(mMockAccountManagerResponse).onError( 1927 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString()); 1928 verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM)); 1929 verify(mMockDevicePolicyManagerInternal).createShowAdminSupportIntent( 1930 anyInt(), anyBoolean()); 1931 } 1932 1933 @SmallTest testAddAccountAsUserSuccess()1934 public void testAddAccountAsUserSuccess() throws Exception { 1935 unlockSystemUser(); 1936 final CountDownLatch latch = new CountDownLatch(1); 1937 Response response = new Response(latch, mMockAccountManagerResponse); 1938 mAms.addAccountAsUser( 1939 response, // response 1940 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1941 "authTokenType", 1942 null, // requiredFeatures 1943 true, // expectActivityLaunch 1944 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS), 1945 UserHandle.USER_SYSTEM); 1946 waitForLatch(latch); 1947 // Verify notification is cancelled 1948 verify(mMockNotificationManager).cancelNotificationWithTag(anyString(), 1949 anyString(), nullable(String.class), anyInt(), anyInt()); 1950 1951 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 1952 Bundle result = mBundleCaptor.getValue(); 1953 // Verify response data 1954 assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null)); 1955 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, 1956 result.getString(AccountManager.KEY_ACCOUNT_NAME)); 1957 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 1958 result.getString(AccountManager.KEY_ACCOUNT_TYPE)); 1959 1960 Bundle optionBundle = result.getParcelable( 1961 AccountManagerServiceTestFixtures.KEY_OPTIONS_BUNDLE); 1962 // Assert addAccountAsUser added calling uid and pid into the option bundle 1963 assertTrue(optionBundle.containsKey(AccountManager.KEY_CALLER_UID)); 1964 assertTrue(optionBundle.containsKey(AccountManager.KEY_CALLER_PID)); 1965 } 1966 1967 @SmallTest testAddAccountAsUserReturnWithInvalidIntent()1968 public void testAddAccountAsUserReturnWithInvalidIntent() throws Exception { 1969 unlockSystemUser(); 1970 ResolveInfo resolveInfo = new ResolveInfo(); 1971 resolveInfo.activityInfo = new ActivityInfo(); 1972 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 1973 when(mMockPackageManager.resolveActivityAsUser( 1974 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 1975 when(mMockPackageManager.checkSignatures( 1976 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 1977 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 1978 .thenReturn(false); 1979 1980 final CountDownLatch latch = new CountDownLatch(1); 1981 Response response = new Response(latch, mMockAccountManagerResponse); 1982 mAms.addAccountAsUser( 1983 response, // response 1984 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 1985 "authTokenType", 1986 null, // requiredFeatures 1987 true, // expectActivityLaunch 1988 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE), 1989 UserHandle.USER_SYSTEM); 1990 1991 waitForLatch(latch); 1992 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 1993 verify(mMockAccountManagerResponse).onError( 1994 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 1995 } 1996 1997 @SmallTest testAddAccountAsUserReturnWithValidIntent()1998 public void testAddAccountAsUserReturnWithValidIntent() throws Exception { 1999 unlockSystemUser(); 2000 ResolveInfo resolveInfo = new ResolveInfo(); 2001 resolveInfo.activityInfo = new ActivityInfo(); 2002 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 2003 when(mMockPackageManager.resolveActivityAsUser( 2004 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 2005 when(mMockPackageManager.checkSignatures( 2006 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 2007 2008 final CountDownLatch latch = new CountDownLatch(1); 2009 Response response = new Response(latch, mMockAccountManagerResponse); 2010 2011 mAms.addAccountAsUser( 2012 response, // response 2013 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 2014 "authTokenType", 2015 null, // requiredFeatures 2016 true, // expectActivityLaunch 2017 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE), 2018 UserHandle.USER_SYSTEM); 2019 2020 waitForLatch(latch); 2021 2022 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2023 Bundle result = mBundleCaptor.getValue(); 2024 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 2025 assertNotNull(intent); 2026 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 2027 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 2028 } 2029 2030 @SmallTest testAddAccountAsUserError()2031 public void testAddAccountAsUserError() throws Exception { 2032 unlockSystemUser(); 2033 2034 final CountDownLatch latch = new CountDownLatch(1); 2035 Response response = new Response(latch, mMockAccountManagerResponse); 2036 2037 mAms.addAccountAsUser( 2038 response, // response 2039 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 2040 "authTokenType", 2041 null, // requiredFeatures 2042 true, // expectActivityLaunch 2043 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR), 2044 UserHandle.USER_SYSTEM); 2045 2046 waitForLatch(latch); 2047 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 2048 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 2049 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 2050 } 2051 2052 @SmallTest testConfirmCredentialsAsUserWithNullResponse()2053 public void testConfirmCredentialsAsUserWithNullResponse() throws Exception { 2054 unlockSystemUser(); 2055 try { 2056 mAms.confirmCredentialsAsUser( 2057 null, // response 2058 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 2059 new Bundle(), // options 2060 false, // expectActivityLaunch 2061 UserHandle.USER_SYSTEM); 2062 fail("IllegalArgumentException expected. But no exception was thrown."); 2063 } catch (IllegalArgumentException e) { 2064 // IllegalArgumentException is expected. 2065 } 2066 } 2067 2068 @SmallTest testConfirmCredentialsAsUserWithNullAccount()2069 public void testConfirmCredentialsAsUserWithNullAccount() throws Exception { 2070 unlockSystemUser(); 2071 try { 2072 mAms.confirmCredentialsAsUser( 2073 mMockAccountManagerResponse, // response 2074 null, // account 2075 new Bundle(), // options 2076 false, // expectActivityLaunch 2077 UserHandle.USER_SYSTEM); 2078 fail("IllegalArgumentException expected. But no exception was thrown."); 2079 } catch (IllegalArgumentException e) { 2080 // IllegalArgumentException is expected. 2081 } 2082 } 2083 2084 @SmallTest testConfirmCredentialsAsUserSuccess()2085 public void testConfirmCredentialsAsUserSuccess() throws Exception { 2086 unlockSystemUser(); 2087 final CountDownLatch latch = new CountDownLatch(1); 2088 Response response = new Response(latch, mMockAccountManagerResponse); 2089 mAms.confirmCredentialsAsUser( 2090 response, // response 2091 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 2092 new Bundle(), // options 2093 true, // expectActivityLaunch 2094 UserHandle.USER_SYSTEM); 2095 waitForLatch(latch); 2096 2097 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2098 Bundle result = mBundleCaptor.getValue(); 2099 // Verify response data 2100 assertTrue(result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)); 2101 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, 2102 result.getString(AccountManager.KEY_ACCOUNT_NAME)); 2103 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2104 result.getString(AccountManager.KEY_ACCOUNT_TYPE)); 2105 } 2106 2107 @SmallTest testConfirmCredentialsAsUserReturnWithInvalidIntent()2108 public void testConfirmCredentialsAsUserReturnWithInvalidIntent() throws Exception { 2109 unlockSystemUser(); 2110 ResolveInfo resolveInfo = new ResolveInfo(); 2111 resolveInfo.activityInfo = new ActivityInfo(); 2112 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 2113 when(mMockPackageManager.resolveActivityAsUser( 2114 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 2115 when(mMockPackageManager.checkSignatures( 2116 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 2117 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 2118 .thenReturn(false); 2119 2120 final CountDownLatch latch = new CountDownLatch(1); 2121 Response response = new Response(latch, mMockAccountManagerResponse); 2122 mAms.confirmCredentialsAsUser( 2123 response, // response 2124 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 2125 new Bundle(), // options 2126 true, // expectActivityLaunch 2127 UserHandle.USER_SYSTEM); 2128 waitForLatch(latch); 2129 2130 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 2131 verify(mMockAccountManagerResponse).onError( 2132 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 2133 } 2134 2135 @SmallTest testConfirmCredentialsAsUserReturnWithValidIntent()2136 public void testConfirmCredentialsAsUserReturnWithValidIntent() throws Exception { 2137 unlockSystemUser(); 2138 ResolveInfo resolveInfo = new ResolveInfo(); 2139 resolveInfo.activityInfo = new ActivityInfo(); 2140 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 2141 when(mMockPackageManager.resolveActivityAsUser( 2142 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 2143 when(mMockPackageManager.checkSignatures( 2144 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 2145 2146 final CountDownLatch latch = new CountDownLatch(1); 2147 Response response = new Response(latch, mMockAccountManagerResponse); 2148 2149 mAms.confirmCredentialsAsUser( 2150 response, // response 2151 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 2152 new Bundle(), // options 2153 true, // expectActivityLaunch 2154 UserHandle.USER_SYSTEM); 2155 2156 waitForLatch(latch); 2157 2158 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2159 Bundle result = mBundleCaptor.getValue(); 2160 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 2161 assertNotNull(intent); 2162 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 2163 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 2164 } 2165 2166 @SmallTest testConfirmCredentialsAsUserError()2167 public void testConfirmCredentialsAsUserError() throws Exception { 2168 unlockSystemUser(); 2169 2170 final CountDownLatch latch = new CountDownLatch(1); 2171 Response response = new Response(latch, mMockAccountManagerResponse); 2172 2173 mAms.confirmCredentialsAsUser( 2174 response, // response 2175 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, 2176 new Bundle(), // options 2177 true, // expectActivityLaunch 2178 UserHandle.USER_SYSTEM); 2179 2180 waitForLatch(latch); 2181 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 2182 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 2183 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 2184 } 2185 2186 @SmallTest testUpdateCredentialsWithNullResponse()2187 public void testUpdateCredentialsWithNullResponse() throws Exception { 2188 unlockSystemUser(); 2189 try { 2190 mAms.updateCredentials( 2191 null, // response 2192 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 2193 "authTokenType", 2194 false, // expectActivityLaunch 2195 new Bundle()); // options 2196 fail("IllegalArgumentException expected. But no exception was thrown."); 2197 } catch (IllegalArgumentException e) { 2198 // IllegalArgumentException is expected. 2199 } 2200 } 2201 2202 @SmallTest testUpdateCredentialsWithNullAccount()2203 public void testUpdateCredentialsWithNullAccount() throws Exception { 2204 unlockSystemUser(); 2205 try { 2206 mAms.updateCredentials( 2207 mMockAccountManagerResponse, // response 2208 null, // account 2209 "authTokenType", 2210 false, // expectActivityLaunch 2211 new Bundle()); // options 2212 fail("IllegalArgumentException expected. But no exception was thrown."); 2213 } catch (IllegalArgumentException e) { 2214 // IllegalArgumentException is expected. 2215 } 2216 } 2217 2218 @SmallTest testUpdateCredentialsSuccess()2219 public void testUpdateCredentialsSuccess() throws Exception { 2220 unlockSystemUser(); 2221 final CountDownLatch latch = new CountDownLatch(1); 2222 Response response = new Response(latch, mMockAccountManagerResponse); 2223 2224 mAms.updateCredentials( 2225 response, // response 2226 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, 2227 "authTokenType", 2228 false, // expectActivityLaunch 2229 new Bundle()); // options 2230 2231 waitForLatch(latch); 2232 2233 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2234 Bundle result = mBundleCaptor.getValue(); 2235 // Verify response data 2236 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, 2237 result.getString(AccountManager.KEY_ACCOUNT_NAME)); 2238 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2239 result.getString(AccountManager.KEY_ACCOUNT_TYPE)); 2240 } 2241 2242 @SmallTest testUpdateCredentialsReturnWithInvalidIntent()2243 public void testUpdateCredentialsReturnWithInvalidIntent() throws Exception { 2244 unlockSystemUser(); 2245 ResolveInfo resolveInfo = new ResolveInfo(); 2246 resolveInfo.activityInfo = new ActivityInfo(); 2247 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 2248 when(mMockPackageManager.resolveActivityAsUser( 2249 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 2250 when(mMockPackageManager.checkSignatures( 2251 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH); 2252 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 2253 .thenReturn(false); 2254 2255 final CountDownLatch latch = new CountDownLatch(1); 2256 Response response = new Response(latch, mMockAccountManagerResponse); 2257 2258 mAms.updateCredentials( 2259 response, // response 2260 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 2261 "authTokenType", 2262 true, // expectActivityLaunch 2263 new Bundle()); // options 2264 2265 waitForLatch(latch); 2266 2267 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 2268 verify(mMockAccountManagerResponse).onError( 2269 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 2270 } 2271 2272 @SmallTest testUpdateCredentialsReturnWithValidIntent()2273 public void testUpdateCredentialsReturnWithValidIntent() throws Exception { 2274 unlockSystemUser(); 2275 ResolveInfo resolveInfo = new ResolveInfo(); 2276 resolveInfo.activityInfo = new ActivityInfo(); 2277 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 2278 when(mMockPackageManager.resolveActivityAsUser( 2279 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo); 2280 when(mMockPackageManager.checkSignatures( 2281 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH); 2282 2283 final CountDownLatch latch = new CountDownLatch(1); 2284 Response response = new Response(latch, mMockAccountManagerResponse); 2285 2286 mAms.updateCredentials( 2287 response, // response 2288 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, 2289 "authTokenType", 2290 true, // expectActivityLaunch 2291 new Bundle()); // options 2292 2293 waitForLatch(latch); 2294 2295 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2296 Bundle result = mBundleCaptor.getValue(); 2297 Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 2298 assertNotNull(intent); 2299 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT)); 2300 assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK)); 2301 } 2302 2303 @SmallTest testUpdateCredentialsError()2304 public void testUpdateCredentialsError() throws Exception { 2305 unlockSystemUser(); 2306 2307 final CountDownLatch latch = new CountDownLatch(1); 2308 Response response = new Response(latch, mMockAccountManagerResponse); 2309 2310 mAms.updateCredentials( 2311 response, // response 2312 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, 2313 "authTokenType", 2314 false, // expectActivityLaunch 2315 new Bundle()); // options 2316 2317 waitForLatch(latch); 2318 verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, 2319 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 2320 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 2321 } 2322 2323 @SmallTest testEditPropertiesWithNullResponse()2324 public void testEditPropertiesWithNullResponse() throws Exception { 2325 unlockSystemUser(); 2326 try { 2327 mAms.editProperties( 2328 null, // response 2329 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2330 false); // expectActivityLaunch 2331 fail("IllegalArgumentException expected. But no exception was thrown."); 2332 } catch (IllegalArgumentException e) { 2333 // IllegalArgumentException is expected. 2334 } 2335 } 2336 2337 @SmallTest testEditPropertiesWithNullAccountType()2338 public void testEditPropertiesWithNullAccountType() throws Exception { 2339 unlockSystemUser(); 2340 try { 2341 mAms.editProperties( 2342 mMockAccountManagerResponse, // response 2343 null, // accountType 2344 false); // expectActivityLaunch 2345 fail("IllegalArgumentException expected. But no exception was thrown."); 2346 } catch (IllegalArgumentException e) { 2347 // IllegalArgumentException is expected. 2348 } 2349 } 2350 2351 @SmallTest testEditPropertiesAccountNotManagedByCaller()2352 public void testEditPropertiesAccountNotManagedByCaller() throws Exception { 2353 unlockSystemUser(); 2354 when(mMockPackageManager.checkSignatures(anyInt(), anyInt())) 2355 .thenReturn(PackageManager.SIGNATURE_NO_MATCH); 2356 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 2357 .thenReturn(false); 2358 try { 2359 mAms.editProperties( 2360 mMockAccountManagerResponse, // response 2361 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2362 false); // expectActivityLaunch 2363 fail("SecurityException expected. But no exception was thrown."); 2364 } catch (SecurityException e) { 2365 // SecurityException is expected. 2366 } 2367 } 2368 2369 @SmallTest testEditPropertiesSuccess()2370 public void testEditPropertiesSuccess() throws Exception { 2371 unlockSystemUser(); 2372 final CountDownLatch latch = new CountDownLatch(1); 2373 Response response = new Response(latch, mMockAccountManagerResponse); 2374 2375 mAms.editProperties( 2376 response, // response 2377 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2378 false); // expectActivityLaunch 2379 2380 waitForLatch(latch); 2381 2382 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2383 Bundle result = mBundleCaptor.getValue(); 2384 // Verify response data 2385 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, 2386 result.getString(AccountManager.KEY_ACCOUNT_NAME)); 2387 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2388 result.getString(AccountManager.KEY_ACCOUNT_TYPE)); 2389 } 2390 2391 @SmallTest testGetAccountByTypeAndFeaturesWithNullResponse()2392 public void testGetAccountByTypeAndFeaturesWithNullResponse() throws Exception { 2393 unlockSystemUser(); 2394 try { 2395 mAms.getAccountByTypeAndFeatures( 2396 null, // response 2397 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2398 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2399 "testpackage"); // opPackageName 2400 fail("IllegalArgumentException expected. But no exception was thrown."); 2401 } catch (IllegalArgumentException e) { 2402 // IllegalArgumentException is expected. 2403 } 2404 } 2405 2406 @SmallTest testGetAccountByTypeAndFeaturesWithNullAccountType()2407 public void testGetAccountByTypeAndFeaturesWithNullAccountType() throws Exception { 2408 unlockSystemUser(); 2409 try { 2410 mAms.getAccountByTypeAndFeatures( 2411 mMockAccountManagerResponse, // response 2412 null, // accountType 2413 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2414 "testpackage"); // opPackageName 2415 fail("IllegalArgumentException expected. But no exception was thrown."); 2416 } catch (IllegalArgumentException e) { 2417 // IllegalArgumentException is expected. 2418 } 2419 } 2420 2421 @SmallTest testGetAccountByTypeAndFeaturesWithNoFeaturesAndNoAccount()2422 public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndNoAccount() throws Exception { 2423 unlockSystemUser(); 2424 mAms.getAccountByTypeAndFeatures( 2425 mMockAccountManagerResponse, 2426 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2427 null, 2428 "testpackage"); 2429 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2430 Bundle result = mBundleCaptor.getValue(); 2431 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); 2432 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE); 2433 assertEquals(null, accountName); 2434 assertEquals(null, accountType); 2435 } 2436 2437 @SmallTest testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneVisibleAccount()2438 public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneVisibleAccount() 2439 throws Exception { 2440 unlockSystemUser(); 2441 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2442 mAms.getAccountByTypeAndFeatures( 2443 mMockAccountManagerResponse, 2444 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2445 null, 2446 "testpackage"); 2447 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2448 Bundle result = mBundleCaptor.getValue(); 2449 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); 2450 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE); 2451 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, accountName); 2452 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, accountType); 2453 } 2454 2455 @SmallTest testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneNotVisibleAccount()2456 public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneNotVisibleAccount() 2457 throws Exception { 2458 unlockSystemUser(); 2459 HashMap<String, Integer> visibility = new HashMap<>(); 2460 visibility.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE, 2461 AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE); 2462 mAms.addAccountExplicitlyWithVisibility( 2463 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility); 2464 mAms.getAccountByTypeAndFeatures( 2465 mMockAccountManagerResponse, 2466 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2467 null, 2468 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 2469 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 2470 Intent intent = mIntentCaptor.getValue(); 2471 Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS); 2472 assertEquals(1, accounts.length); 2473 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]); 2474 } 2475 2476 @SmallTest testGetAccountByTypeAndFeaturesWithNoFeaturesAndTwoAccounts()2477 public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndTwoAccounts() throws Exception { 2478 unlockSystemUser(); 2479 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2480 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null); 2481 2482 mAms.getAccountByTypeAndFeatures( 2483 mMockAccountManagerResponse, 2484 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2485 null, 2486 "testpackage"); 2487 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 2488 Intent intent = mIntentCaptor.getValue(); 2489 Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS); 2490 assertEquals(2, accounts.length); 2491 if (accounts[0].equals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS)) { 2492 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]); 2493 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, accounts[1]); 2494 } else { 2495 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, accounts[0]); 2496 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[1]); 2497 } 2498 } 2499 2500 @SmallTest testGetAccountByTypeAndFeaturesWithFeaturesAndNoAccount()2501 public void testGetAccountByTypeAndFeaturesWithFeaturesAndNoAccount() throws Exception { 2502 unlockSystemUser(); 2503 final CountDownLatch latch = new CountDownLatch(1); 2504 mAms.getAccountByTypeAndFeatures( 2505 mMockAccountManagerResponse, 2506 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2507 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2508 "testpackage"); 2509 waitForLatch(latch); 2510 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2511 Bundle result = mBundleCaptor.getValue(); 2512 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); 2513 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE); 2514 assertEquals(null, accountName); 2515 assertEquals(null, accountType); 2516 } 2517 2518 @SmallTest testGetAccountByTypeAndFeaturesWithFeaturesAndNoQualifiedAccount()2519 public void testGetAccountByTypeAndFeaturesWithFeaturesAndNoQualifiedAccount() 2520 throws Exception { 2521 unlockSystemUser(); 2522 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null); 2523 final CountDownLatch latch = new CountDownLatch(1); 2524 mAms.getAccountByTypeAndFeatures( 2525 mMockAccountManagerResponse, 2526 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2527 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2528 "testpackage"); 2529 waitForLatch(latch); 2530 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2531 Bundle result = mBundleCaptor.getValue(); 2532 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); 2533 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE); 2534 assertEquals(null, accountName); 2535 assertEquals(null, accountType); 2536 } 2537 2538 @SmallTest testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedAccount()2539 public void testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedAccount() 2540 throws Exception { 2541 unlockSystemUser(); 2542 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2543 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null); 2544 final CountDownLatch latch = new CountDownLatch(1); 2545 mAms.getAccountByTypeAndFeatures( 2546 mMockAccountManagerResponse, 2547 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2548 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2549 "testpackage"); 2550 waitForLatch(latch); 2551 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2552 Bundle result = mBundleCaptor.getValue(); 2553 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); 2554 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE); 2555 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, accountName); 2556 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, accountType); 2557 } 2558 2559 @SmallTest testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedNotVisibleAccount()2560 public void testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedNotVisibleAccount() 2561 throws Exception { 2562 unlockSystemUser(); 2563 HashMap<String, Integer> visibility = new HashMap<>(); 2564 visibility.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE, 2565 AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE); 2566 mAms.addAccountExplicitlyWithVisibility( 2567 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility); 2568 final CountDownLatch latch = new CountDownLatch(1); 2569 mAms.getAccountByTypeAndFeatures( 2570 mMockAccountManagerResponse, 2571 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2572 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2573 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 2574 waitForLatch(latch); 2575 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 2576 Intent intent = mIntentCaptor.getValue(); 2577 Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS); 2578 assertEquals(1, accounts.length); 2579 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]); 2580 } 2581 2582 @SmallTest testGetAccountByTypeAndFeaturesWithFeaturesAndTwoQualifiedAccount()2583 public void testGetAccountByTypeAndFeaturesWithFeaturesAndTwoQualifiedAccount() 2584 throws Exception { 2585 unlockSystemUser(); 2586 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2587 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_2, "p12", null); 2588 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p13", null); 2589 final CountDownLatch latch = new CountDownLatch(1); 2590 mAms.getAccountByTypeAndFeatures( 2591 mMockAccountManagerResponse, 2592 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2593 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2594 "testpackage"); 2595 waitForLatch(latch); 2596 verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM)); 2597 Intent intent = mIntentCaptor.getValue(); 2598 Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS); 2599 assertEquals(2, accounts.length); 2600 if (accounts[0].equals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS)) { 2601 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]); 2602 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_2, accounts[1]); 2603 } else { 2604 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_2, accounts[0]); 2605 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[1]); 2606 } 2607 } 2608 2609 @SmallTest testGetAccountsByFeaturesWithNullResponse()2610 public void testGetAccountsByFeaturesWithNullResponse() throws Exception { 2611 unlockSystemUser(); 2612 try { 2613 mAms.getAccountsByFeatures( 2614 null, // response 2615 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, 2616 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2617 "testpackage"); // opPackageName 2618 fail("IllegalArgumentException expected. But no exception was thrown."); 2619 } catch (IllegalArgumentException e) { 2620 // IllegalArgumentException is expected. 2621 } 2622 } 2623 2624 @SmallTest testGetAccountsByFeaturesWithNullAccountType()2625 public void testGetAccountsByFeaturesWithNullAccountType() throws Exception { 2626 unlockSystemUser(); 2627 try { 2628 mAms.getAccountsByFeatures( 2629 mMockAccountManagerResponse, // response 2630 null, // accountType 2631 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2632 "testpackage"); // opPackageName 2633 fail("IllegalArgumentException expected. But no exception was thrown."); 2634 } catch (IllegalArgumentException e) { 2635 // IllegalArgumentException is expected. 2636 } 2637 } 2638 2639 @SmallTest testGetAccountsByFeaturesAccountNotVisible()2640 public void testGetAccountsByFeaturesAccountNotVisible() throws Exception { 2641 unlockSystemUser(); 2642 2643 when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn( 2644 PackageManager.PERMISSION_DENIED); 2645 when(mMockPackageManager.checkSignatures(anyInt(), anyInt())) 2646 .thenReturn(PackageManager.SIGNATURE_NO_MATCH); 2647 when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt())) 2648 .thenReturn(false); 2649 2650 final CountDownLatch latch = new CountDownLatch(1); 2651 Response response = new Response(latch, mMockAccountManagerResponse); 2652 mAms.getAccountsByFeatures( 2653 response, // response 2654 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 2655 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2656 "testpackage"); // opPackageName 2657 waitForLatch(latch); 2658 2659 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2660 Bundle result = mBundleCaptor.getValue(); 2661 Account[] accounts = (Account[]) result.getParcelableArray(AccountManager.KEY_ACCOUNTS); 2662 assertTrue(accounts.length == 0); 2663 } 2664 2665 @SmallTest testGetAccountsByFeaturesNullFeatureReturnsAllAccounts()2666 public void testGetAccountsByFeaturesNullFeatureReturnsAllAccounts() throws Exception { 2667 unlockSystemUser(); 2668 2669 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2670 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null); 2671 2672 final CountDownLatch latch = new CountDownLatch(1); 2673 Response response = new Response(latch, mMockAccountManagerResponse); 2674 mAms.getAccountsByFeatures( 2675 response, // response 2676 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 2677 null, // features 2678 "testpackage"); // opPackageName 2679 waitForLatch(latch); 2680 2681 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2682 Bundle result = mBundleCaptor.getValue(); 2683 Account[] accounts = (Account[]) result.getParcelableArray(AccountManager.KEY_ACCOUNTS); 2684 Arrays.sort(accounts, new AccountSorter()); 2685 assertEquals(2, accounts.length); 2686 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, accounts[0]); 2687 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[1]); 2688 } 2689 2690 @SmallTest testGetAccountsByFeaturesReturnsAccountsWithFeaturesOnly()2691 public void testGetAccountsByFeaturesReturnsAccountsWithFeaturesOnly() throws Exception { 2692 unlockSystemUser(); 2693 2694 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2695 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null); 2696 2697 final CountDownLatch latch = new CountDownLatch(1); 2698 Response response = new Response(latch, mMockAccountManagerResponse); 2699 mAms.getAccountsByFeatures( 2700 response, // response 2701 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 2702 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2703 "testpackage"); // opPackageName 2704 waitForLatch(latch); 2705 2706 verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture()); 2707 Bundle result = mBundleCaptor.getValue(); 2708 Account[] accounts = (Account[]) result.getParcelableArray(AccountManager.KEY_ACCOUNTS); 2709 assertEquals(1, accounts.length); 2710 assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]); 2711 } 2712 2713 @SmallTest testGetAccountsByFeaturesError()2714 public void testGetAccountsByFeaturesError() throws Exception { 2715 unlockSystemUser(); 2716 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2717 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_ERROR, "p12", null); 2718 2719 final CountDownLatch latch = new CountDownLatch(1); 2720 Response response = new Response(latch, mMockAccountManagerResponse); 2721 mAms.getAccountsByFeatures( 2722 response, // response 2723 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType 2724 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, 2725 "testpackage"); // opPackageName 2726 waitForLatch(latch); 2727 2728 verify(mMockAccountManagerResponse).onError( 2729 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString()); 2730 verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class)); 2731 } 2732 2733 @SmallTest testRegisterAccountListener()2734 public void testRegisterAccountListener() throws Exception { 2735 unlockSystemUser(); 2736 mAms.registerAccountListener( 2737 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2738 "testpackage"); // opPackageName 2739 2740 mAms.registerAccountListener( 2741 null, //accountTypes 2742 "testpackage"); // opPackageName 2743 2744 // Check that two previously registered receivers can be unregistered successfully. 2745 mAms.unregisterAccountListener( 2746 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2747 "testpackage"); // opPackageName 2748 2749 mAms.unregisterAccountListener( 2750 null, //accountTypes 2751 "testpackage"); // opPackageName 2752 } 2753 2754 @SmallTest testRegisterAccountListenerAndAddAccount()2755 public void testRegisterAccountListenerAndAddAccount() throws Exception { 2756 unlockSystemUser(); 2757 mAms.registerAccountListener( 2758 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2759 "testpackage"); // opPackageName 2760 2761 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2762 // Notification about new account 2763 updateBroadcastCounters(2); 2764 assertEquals(mVisibleAccountsChangedBroadcasts, 1); 2765 assertEquals(mLoginAccountsChangedBroadcasts, 1); 2766 } 2767 2768 @SmallTest testRegisterAccountListenerAndAddAccountOfDifferentType()2769 public void testRegisterAccountListenerAndAddAccountOfDifferentType() throws Exception { 2770 unlockSystemUser(); 2771 mAms.registerAccountListener( 2772 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2}, 2773 "testpackage"); // opPackageName 2774 2775 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2776 mAms.addAccountExplicitly( 2777 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p11", null); 2778 // Notification about new account 2779 2780 updateBroadcastCounters(2); 2781 assertEquals(mVisibleAccountsChangedBroadcasts, 0); // broadcast was not sent 2782 assertEquals(mLoginAccountsChangedBroadcasts, 2); 2783 } 2784 2785 @SmallTest testRegisterAccountListenerWithAddingTwoAccounts()2786 public void testRegisterAccountListenerWithAddingTwoAccounts() throws Exception { 2787 unlockSystemUser(); 2788 2789 HashMap<String, Integer> visibility = new HashMap<>(); 2790 visibility.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE, 2791 AccountManager.VISIBILITY_USER_MANAGED_VISIBLE); 2792 2793 mAms.registerAccountListener( 2794 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2795 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 2796 mAms.addAccountExplicitlyWithVisibility( 2797 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility); 2798 mAms.unregisterAccountListener( 2799 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2800 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 2801 2802 addAccountRemovedReceiver(AccountManagerServiceTestFixtures.CALLER_PACKAGE); 2803 mAms.addAccountExplicitlyWithVisibility( 2804 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p11", null, visibility); 2805 2806 updateBroadcastCounters(3); 2807 assertEquals(mVisibleAccountsChangedBroadcasts, 1); 2808 assertEquals(mLoginAccountsChangedBroadcasts, 2); 2809 assertEquals(mAccountRemovedBroadcasts, 0); 2810 2811 mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS); 2812 mAms.registerAccountListener( null /* accountTypes */, 2813 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 2814 mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE); 2815 2816 updateBroadcastCounters(8); 2817 assertEquals(mVisibleAccountsChangedBroadcasts, 2); 2818 assertEquals(mLoginAccountsChangedBroadcasts, 4); 2819 assertEquals(mAccountRemovedBroadcasts, 2); 2820 } 2821 2822 @SmallTest testRegisterAccountListenerForThreePackages()2823 public void testRegisterAccountListenerForThreePackages() throws Exception { 2824 unlockSystemUser(); 2825 2826 addAccountRemovedReceiver("testpackage1"); 2827 HashMap<String, Integer> visibility = new HashMap<>(); 2828 visibility.put("testpackage1", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE); 2829 visibility.put("testpackage2", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE); 2830 visibility.put("testpackage3", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE); 2831 2832 mAms.registerAccountListener( 2833 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2834 "testpackage1"); // opPackageName 2835 mAms.registerAccountListener( 2836 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2837 "testpackage2"); // opPackageName 2838 mAms.registerAccountListener( 2839 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2840 "testpackage3"); // opPackageName 2841 mAms.addAccountExplicitlyWithVisibility( 2842 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility); 2843 updateBroadcastCounters(4); 2844 assertEquals(mVisibleAccountsChangedBroadcasts, 3); 2845 assertEquals(mLoginAccountsChangedBroadcasts, 1); 2846 2847 mAms.unregisterAccountListener( 2848 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2849 "testpackage3"); // opPackageName 2850 // Remove account with 2 active listeners. 2851 mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS); 2852 updateBroadcastCounters(8); 2853 assertEquals(mVisibleAccountsChangedBroadcasts, 5); 2854 assertEquals(mLoginAccountsChangedBroadcasts, 2); // 3 add, 2 remove 2855 assertEquals(mAccountRemovedBroadcasts, 1); 2856 2857 // Add account of another type. 2858 mAms.addAccountExplicitly( 2859 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_TYPE_2, "p11", null); 2860 2861 updateBroadcastCounters(8); 2862 assertEquals(mVisibleAccountsChangedBroadcasts, 5); 2863 assertEquals(mLoginAccountsChangedBroadcasts, 3); 2864 assertEquals(mAccountRemovedBroadcasts, 1); 2865 } 2866 2867 @SmallTest testRegisterAccountListenerForAddingAccountWithVisibility()2868 public void testRegisterAccountListenerForAddingAccountWithVisibility() throws Exception { 2869 unlockSystemUser(); 2870 2871 HashMap<String, Integer> visibility = new HashMap<>(); 2872 visibility.put("testpackage1", AccountManager.VISIBILITY_NOT_VISIBLE); 2873 visibility.put("testpackage2", AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE); 2874 visibility.put("testpackage3", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE); 2875 2876 addAccountRemovedReceiver("testpackage1"); 2877 mAms.registerAccountListener( 2878 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2879 "testpackage1"); // opPackageName 2880 mAms.registerAccountListener( 2881 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2882 "testpackage2"); // opPackageName 2883 mAms.registerAccountListener( 2884 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2885 "testpackage3"); // opPackageName 2886 mAms.addAccountExplicitlyWithVisibility( 2887 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility); 2888 2889 updateBroadcastCounters(2); 2890 assertEquals(mVisibleAccountsChangedBroadcasts, 1); 2891 assertEquals(mLoginAccountsChangedBroadcasts, 1); 2892 2893 mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS); 2894 2895 updateBroadcastCounters(4); 2896 assertEquals(mVisibleAccountsChangedBroadcasts, 2); 2897 assertEquals(mLoginAccountsChangedBroadcasts, 2); 2898 assertEquals(mAccountRemovedBroadcasts, 0); // account was never visible. 2899 } 2900 2901 @SmallTest testRegisterAccountListenerCredentialsUpdate()2902 public void testRegisterAccountListenerCredentialsUpdate() throws Exception { 2903 unlockSystemUser(); 2904 mAms.registerAccountListener( 2905 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2906 "testpackage"); // opPackageName 2907 mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null); 2908 mAms.setPassword(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "pwd"); 2909 updateBroadcastCounters(4); 2910 assertEquals(mVisibleAccountsChangedBroadcasts, 2); 2911 assertEquals(mLoginAccountsChangedBroadcasts, 2); 2912 } 2913 2914 @SmallTest testUnregisterAccountListenerNotRegistered()2915 public void testUnregisterAccountListenerNotRegistered() throws Exception { 2916 unlockSystemUser(); 2917 try { 2918 mAms.unregisterAccountListener( 2919 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1}, 2920 "testpackage"); // opPackageName 2921 fail("IllegalArgumentException expected. But no exception was thrown."); 2922 } catch (IllegalArgumentException e) { 2923 // IllegalArgumentException is expected. 2924 } 2925 } 2926 updateBroadcastCounters(int expectedBroadcasts)2927 private void updateBroadcastCounters (int expectedBroadcasts){ 2928 mVisibleAccountsChangedBroadcasts = 0; 2929 mLoginAccountsChangedBroadcasts = 0; 2930 mAccountRemovedBroadcasts = 0; 2931 ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class); 2932 verify(mMockContext, atLeast(expectedBroadcasts)).sendBroadcastAsUser(captor.capture(), 2933 any(UserHandle.class)); 2934 for (Intent intent : captor.getAllValues()) { 2935 if (AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED.equals(intent.getAction())) { 2936 mVisibleAccountsChangedBroadcasts++; 2937 } else if (AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION.equals(intent.getAction())) { 2938 mLoginAccountsChangedBroadcasts++; 2939 } else if (AccountManager.ACTION_ACCOUNT_REMOVED.equals(intent.getAction())) { 2940 mAccountRemovedBroadcasts++; 2941 } 2942 } 2943 } 2944 addAccountRemovedReceiver(String packageName)2945 private void addAccountRemovedReceiver(String packageName) { 2946 ResolveInfo resolveInfo = new ResolveInfo(); 2947 resolveInfo.activityInfo = new ActivityInfo(); 2948 resolveInfo.activityInfo.applicationInfo = new ApplicationInfo(); 2949 resolveInfo.activityInfo.applicationInfo.packageName = packageName; 2950 2951 List<ResolveInfo> accountRemovedReceivers = new ArrayList<>(); 2952 accountRemovedReceivers.add(resolveInfo); 2953 when(mMockPackageManager.queryBroadcastReceiversAsUser(any(Intent.class), anyInt(), 2954 anyInt())).thenReturn(accountRemovedReceivers); 2955 } 2956 2957 @SmallTest testConcurrencyReadWrite()2958 public void testConcurrencyReadWrite() throws Exception { 2959 // Test 2 threads calling getAccounts and 1 thread setAuthToken 2960 unlockSystemUser(); 2961 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 2962 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 2963 2964 Account a1 = new Account("account1", 2965 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 2966 mAms.addAccountExplicitly(a1, "p1", null); 2967 List<String> errors = Collections.synchronizedList(new ArrayList<>()); 2968 int readerCount = 2; 2969 ExecutorService es = Executors.newFixedThreadPool(readerCount + 1); 2970 AtomicLong readTotalTime = new AtomicLong(0); 2971 AtomicLong writeTotalTime = new AtomicLong(0); 2972 final CyclicBarrier cyclicBarrier = new CyclicBarrier(readerCount + 1); 2973 2974 final int loopSize = 20; 2975 for (int t = 0; t < readerCount; t++) { 2976 es.submit(() -> { 2977 for (int i = 0; i < loopSize; i++) { 2978 String logPrefix = Thread.currentThread().getName() + " " + i; 2979 waitForCyclicBarrier(cyclicBarrier); 2980 cyclicBarrier.reset(); 2981 SystemClock.sleep(1); // Ensure that writer wins 2982 Log.d(TAG, logPrefix + " getAccounts started"); 2983 long ti = System.currentTimeMillis(); 2984 try { 2985 Account[] accounts = mAms.getAccountsAsUser(null, 2986 UserHandle.getCallingUserId(), mContext.getOpPackageName()); 2987 if (accounts == null || accounts.length != 1 2988 || !AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1.equals( 2989 accounts[0].type)) { 2990 String msg = logPrefix + ": Unexpected accounts: " + Arrays 2991 .toString(accounts); 2992 Log.e(TAG, " " + msg); 2993 errors.add(msg); 2994 } 2995 Log.d(TAG, logPrefix + " getAccounts done"); 2996 } catch (Exception e) { 2997 String msg = logPrefix + ": getAccounts failed " + e; 2998 Log.e(TAG, msg, e); 2999 errors.add(msg); 3000 } 3001 ti = System.currentTimeMillis() - ti; 3002 readTotalTime.addAndGet(ti); 3003 } 3004 }); 3005 } 3006 3007 es.submit(() -> { 3008 for (int i = 0; i < loopSize; i++) { 3009 String logPrefix = Thread.currentThread().getName() + " " + i; 3010 waitForCyclicBarrier(cyclicBarrier); 3011 long ti = System.currentTimeMillis(); 3012 Log.d(TAG, logPrefix + " setAuthToken started"); 3013 try { 3014 mAms.setAuthToken(a1, "t1", "v" + i); 3015 Log.d(TAG, logPrefix + " setAuthToken done"); 3016 } catch (Exception e) { 3017 errors.add(logPrefix + ": setAuthToken failed: " + e); 3018 } 3019 ti = System.currentTimeMillis() - ti; 3020 writeTotalTime.addAndGet(ti); 3021 } 3022 }); 3023 es.shutdown(); 3024 assertTrue("Time-out waiting for jobs to finish", 3025 es.awaitTermination(10, TimeUnit.SECONDS)); 3026 es.shutdownNow(); 3027 assertTrue("Errors: " + errors, errors.isEmpty()); 3028 Log.i(TAG, "testConcurrencyReadWrite: readTotalTime=" + readTotalTime + " avg=" 3029 + (readTotalTime.doubleValue() / readerCount / loopSize)); 3030 Log.i(TAG, "testConcurrencyReadWrite: writeTotalTime=" + writeTotalTime + " avg=" 3031 + (writeTotalTime.doubleValue() / loopSize)); 3032 } 3033 3034 @SmallTest testConcurrencyRead()3035 public void testConcurrencyRead() throws Exception { 3036 // Test 2 threads calling getAccounts 3037 unlockSystemUser(); 3038 String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE}; 3039 when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list); 3040 3041 Account a1 = new Account("account1", 3042 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 3043 mAms.addAccountExplicitly(a1, "p1", null); 3044 List<String> errors = Collections.synchronizedList(new ArrayList<>()); 3045 int readerCount = 2; 3046 ExecutorService es = Executors.newFixedThreadPool(readerCount + 1); 3047 AtomicLong readTotalTime = new AtomicLong(0); 3048 3049 final int loopSize = 20; 3050 for (int t = 0; t < readerCount; t++) { 3051 es.submit(() -> { 3052 for (int i = 0; i < loopSize; i++) { 3053 String logPrefix = Thread.currentThread().getName() + " " + i; 3054 Log.d(TAG, logPrefix + " getAccounts started"); 3055 long ti = System.currentTimeMillis(); 3056 try { 3057 Account[] accounts = mAms.getAccountsAsUser(null, 3058 UserHandle.getCallingUserId(), mContext.getOpPackageName()); 3059 if (accounts == null || accounts.length != 1 3060 || !AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1.equals( 3061 accounts[0].type)) { 3062 String msg = logPrefix + ": Unexpected accounts: " + Arrays 3063 .toString(accounts); 3064 Log.e(TAG, " " + msg); 3065 errors.add(msg); 3066 } 3067 Log.d(TAG, logPrefix + " getAccounts done"); 3068 } catch (Exception e) { 3069 String msg = logPrefix + ": getAccounts failed " + e; 3070 Log.e(TAG, msg, e); 3071 errors.add(msg); 3072 } 3073 ti = System.currentTimeMillis() - ti; 3074 readTotalTime.addAndGet(ti); 3075 } 3076 }); 3077 } 3078 es.shutdown(); 3079 assertTrue("Time-out waiting for jobs to finish", 3080 es.awaitTermination(10, TimeUnit.SECONDS)); 3081 es.shutdownNow(); 3082 assertTrue("Errors: " + errors, errors.isEmpty()); 3083 Log.i(TAG, "testConcurrencyRead: readTotalTime=" + readTotalTime + " avg=" 3084 + (readTotalTime.doubleValue() / readerCount / loopSize)); 3085 } 3086 waitForCyclicBarrier(CyclicBarrier cyclicBarrier)3087 private void waitForCyclicBarrier(CyclicBarrier cyclicBarrier) { 3088 try { 3089 cyclicBarrier.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS); 3090 } catch (Exception e) { 3091 throw new IllegalStateException("Should not throw " + e, e); 3092 } 3093 } 3094 waitForLatch(CountDownLatch latch)3095 private void waitForLatch(CountDownLatch latch) { 3096 try { 3097 latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS); 3098 } catch (InterruptedException e) { 3099 throw new IllegalStateException("Should not throw an InterruptedException", e); 3100 } 3101 } 3102 createAddAccountOptions(String accountName)3103 private Bundle createAddAccountOptions(String accountName) { 3104 Bundle options = new Bundle(); 3105 options.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName); 3106 return options; 3107 } 3108 createGetAuthTokenOptions()3109 private Bundle createGetAuthTokenOptions() { 3110 Bundle options = new Bundle(); 3111 options.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, 3112 AccountManagerServiceTestFixtures.CALLER_PACKAGE); 3113 options.putLong(AccountManagerServiceTestFixtures.KEY_TOKEN_EXPIRY, 3114 System.currentTimeMillis() + ONE_DAY_IN_MILLISECOND); 3115 return options; 3116 } 3117 encryptBundleWithCryptoHelper(Bundle sessionBundle)3118 private Bundle encryptBundleWithCryptoHelper(Bundle sessionBundle) { 3119 Bundle encryptedBundle = null; 3120 try { 3121 CryptoHelper cryptoHelper = CryptoHelper.getInstance(); 3122 encryptedBundle = cryptoHelper.encryptBundle(sessionBundle); 3123 } catch (GeneralSecurityException e) { 3124 throw new IllegalStateException("Failed to encrypt session bundle.", e); 3125 } 3126 return encryptedBundle; 3127 } 3128 createEncryptedSessionBundle(final String accountName)3129 private Bundle createEncryptedSessionBundle(final String accountName) { 3130 Bundle sessionBundle = new Bundle(); 3131 sessionBundle.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName); 3132 sessionBundle.putString( 3133 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1, 3134 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1); 3135 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, 3136 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 3137 sessionBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.session.package"); 3138 return encryptBundleWithCryptoHelper(sessionBundle); 3139 } 3140 createEncryptedSessionBundleWithError(final String accountName)3141 private Bundle createEncryptedSessionBundleWithError(final String accountName) { 3142 Bundle sessionBundle = new Bundle(); 3143 sessionBundle.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName); 3144 sessionBundle.putString( 3145 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1, 3146 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1); 3147 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, 3148 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 3149 sessionBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.session.package"); 3150 sessionBundle.putInt( 3151 AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_INVALID_RESPONSE); 3152 sessionBundle.putString(AccountManager.KEY_ERROR_MESSAGE, 3153 AccountManagerServiceTestFixtures.ERROR_MESSAGE); 3154 return encryptBundleWithCryptoHelper(sessionBundle); 3155 } 3156 createEncryptedSessionBundleWithNoAccountType(final String accountName)3157 private Bundle createEncryptedSessionBundleWithNoAccountType(final String accountName) { 3158 Bundle sessionBundle = new Bundle(); 3159 sessionBundle.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName); 3160 sessionBundle.putString( 3161 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1, 3162 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1); 3163 sessionBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.session.package"); 3164 return encryptBundleWithCryptoHelper(sessionBundle); 3165 } 3166 createAppBundle()3167 private Bundle createAppBundle() { 3168 Bundle appBundle = new Bundle(); 3169 appBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.package"); 3170 return appBundle; 3171 } 3172 createOptionsWithAccountName(final String accountName)3173 private Bundle createOptionsWithAccountName(final String accountName) { 3174 Bundle sessionBundle = new Bundle(); 3175 sessionBundle.putString( 3176 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1, 3177 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1); 3178 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, 3179 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1); 3180 Bundle options = new Bundle(); 3181 options.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName); 3182 options.putBundle(AccountManagerServiceTestFixtures.KEY_ACCOUNT_SESSION_BUNDLE, 3183 sessionBundle); 3184 options.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_PASSWORD, 3185 AccountManagerServiceTestFixtures.ACCOUNT_PASSWORD); 3186 return options; 3187 } 3188 readNumberOfAccountsFromDbFile(Context context, String dbName)3189 private int readNumberOfAccountsFromDbFile(Context context, String dbName) { 3190 SQLiteDatabase ceDb = context.openOrCreateDatabase(dbName, 0, null); 3191 try (Cursor cursor = ceDb.rawQuery("SELECT count(*) FROM accounts", null)) { 3192 assertTrue(cursor.moveToNext()); 3193 return cursor.getInt(0); 3194 } 3195 } 3196 unlockSystemUser()3197 private void unlockSystemUser() { 3198 mAms.onUserUnlocked(newIntentForUser(UserHandle.USER_SYSTEM)); 3199 } 3200 newIntentForUser(int userId)3201 private static Intent newIntentForUser(int userId) { 3202 Intent intent = new Intent(); 3203 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 3204 return intent; 3205 } 3206 3207 static class MyMockContext extends MockContext { 3208 private Context mTestContext; 3209 private Context mMockContext; 3210 MyMockContext(Context testContext, Context mockContext)3211 MyMockContext(Context testContext, Context mockContext) { 3212 this.mTestContext = testContext; 3213 this.mMockContext = mockContext; 3214 } 3215 3216 @Override checkCallingOrSelfPermission(final String permission)3217 public int checkCallingOrSelfPermission(final String permission) { 3218 return mMockContext.checkCallingOrSelfPermission(permission); 3219 } 3220 3221 @Override bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user)3222 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, 3223 UserHandle user) { 3224 return mTestContext.bindServiceAsUser(service, conn, flags, user); 3225 } 3226 3227 @Override unbindService(ServiceConnection conn)3228 public void unbindService(ServiceConnection conn) { 3229 mTestContext.unbindService(conn); 3230 } 3231 3232 @Override getPackageManager()3233 public PackageManager getPackageManager() { 3234 return mMockContext.getPackageManager(); 3235 } 3236 3237 @Override getPackageName()3238 public String getPackageName() { 3239 return mTestContext.getPackageName(); 3240 } 3241 3242 @Override getSystemService(String name)3243 public Object getSystemService(String name) { 3244 return mMockContext.getSystemService(name); 3245 } 3246 3247 @Override getSystemServiceName(Class<?> serviceClass)3248 public String getSystemServiceName(Class<?> serviceClass) { 3249 return mMockContext.getSystemServiceName(serviceClass); 3250 } 3251 3252 @Override startActivityAsUser(Intent intent, UserHandle user)3253 public void startActivityAsUser(Intent intent, UserHandle user) { 3254 mMockContext.startActivityAsUser(intent, user); 3255 } 3256 3257 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter)3258 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 3259 return mMockContext.registerReceiver(receiver, filter); 3260 } 3261 3262 @Override registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler)3263 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, 3264 IntentFilter filter, String broadcastPermission, Handler scheduler) { 3265 return mMockContext.registerReceiverAsUser( 3266 receiver, user, filter, broadcastPermission, scheduler); 3267 } 3268 3269 @Override openOrCreateDatabase(String file, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)3270 public SQLiteDatabase openOrCreateDatabase(String file, int mode, 3271 SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { 3272 return mTestContext.openOrCreateDatabase(file, mode, factory,errorHandler); 3273 } 3274 3275 @Override getDatabasePath(String name)3276 public File getDatabasePath(String name) { 3277 return mTestContext.getDatabasePath(name); 3278 } 3279 3280 @Override sendBroadcastAsUser(Intent intent, UserHandle user)3281 public void sendBroadcastAsUser(Intent intent, UserHandle user) { 3282 mMockContext.sendBroadcastAsUser(intent, user); 3283 } 3284 3285 @Override getOpPackageName()3286 public String getOpPackageName() { 3287 return mMockContext.getOpPackageName(); 3288 } 3289 3290 @Override createPackageContextAsUser(String packageName, int flags, UserHandle user)3291 public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) 3292 throws PackageManager.NameNotFoundException { 3293 return mMockContext.createPackageContextAsUser(packageName, flags, user); 3294 } 3295 } 3296 3297 static class TestAccountAuthenticatorCache extends AccountAuthenticatorCache { TestAccountAuthenticatorCache(Context realContext)3298 public TestAccountAuthenticatorCache(Context realContext) { 3299 super(realContext); 3300 } 3301 3302 @Override getUserSystemDirectory(int userId)3303 protected File getUserSystemDirectory(int userId) { 3304 return new File(mContext.getCacheDir(), "authenticator"); 3305 } 3306 } 3307 3308 static class TestInjector extends AccountManagerService.Injector { 3309 private Context mRealContext; 3310 private INotificationManager mMockNotificationManager; TestInjector(Context realContext, Context mockContext, INotificationManager mockNotificationManager)3311 TestInjector(Context realContext, 3312 Context mockContext, 3313 INotificationManager mockNotificationManager) { 3314 super(mockContext); 3315 mRealContext = realContext; 3316 mMockNotificationManager = mockNotificationManager; 3317 } 3318 3319 @Override getMessageHandlerLooper()3320 Looper getMessageHandlerLooper() { 3321 return Looper.getMainLooper(); 3322 } 3323 3324 @Override addLocalService(AccountManagerInternal service)3325 void addLocalService(AccountManagerInternal service) { 3326 } 3327 3328 @Override getAccountAuthenticatorCache()3329 IAccountAuthenticatorCache getAccountAuthenticatorCache() { 3330 return new TestAccountAuthenticatorCache(mRealContext); 3331 } 3332 3333 @Override getCeDatabaseName(int userId)3334 protected String getCeDatabaseName(int userId) { 3335 return new File(mRealContext.getCacheDir(), CE_DB).getPath(); 3336 } 3337 3338 @Override getDeDatabaseName(int userId)3339 protected String getDeDatabaseName(int userId) { 3340 return new File(mRealContext.getCacheDir(), DE_DB).getPath(); 3341 } 3342 3343 @Override getPreNDatabaseName(int userId)3344 String getPreNDatabaseName(int userId) { 3345 return new File(mRealContext.getCacheDir(), PREN_DB).getPath(); 3346 } 3347 3348 @Override getNotificationManager()3349 INotificationManager getNotificationManager() { 3350 return mMockNotificationManager; 3351 } 3352 } 3353 3354 class Response extends IAccountManagerResponse.Stub { 3355 private CountDownLatch mLatch; 3356 private IAccountManagerResponse mMockResponse; Response(CountDownLatch latch, IAccountManagerResponse mockResponse)3357 public Response(CountDownLatch latch, IAccountManagerResponse mockResponse) { 3358 mLatch = latch; 3359 mMockResponse = mockResponse; 3360 } 3361 3362 @Override onResult(Bundle bundle)3363 public void onResult(Bundle bundle) { 3364 try { 3365 mMockResponse.onResult(bundle); 3366 } catch (RemoteException e) { 3367 } 3368 mLatch.countDown(); 3369 } 3370 3371 @Override onError(int code, String message)3372 public void onError(int code, String message) { 3373 try { 3374 mMockResponse.onError(code, message); 3375 } catch (RemoteException e) { 3376 } 3377 mLatch.countDown(); 3378 } 3379 } 3380 } 3381