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