1 package org.robolectric.shadows; 2 3 import static android.Manifest.permission.READ_CALENDAR; 4 import static android.Manifest.permission.READ_CONTACTS; 5 import static android.Manifest.permission.READ_SMS; 6 import static android.Manifest.permission.SUSPEND_APPS; 7 import static android.Manifest.permission.WRITE_CALENDAR; 8 import static android.content.pm.ApplicationInfo.FLAG_ALLOW_BACKUP; 9 import static android.content.pm.ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA; 10 import static android.content.pm.ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING; 11 import static android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE; 12 import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE; 13 import static android.content.pm.ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS; 14 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS; 15 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS; 16 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES; 17 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS; 18 import static android.content.pm.ApplicationInfo.FLAG_VM_SAFE_MODE; 19 import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED; 20 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 21 import static android.content.pm.PackageManager.EXTRA_VERIFICATION_ID; 22 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 23 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 24 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 25 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 26 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 27 import static android.content.pm.PackageManager.PERMISSION_DENIED; 28 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 29 import static android.content.pm.PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 30 import static android.content.pm.PackageManager.SIGNATURE_MATCH; 31 import static android.content.pm.PackageManager.SIGNATURE_NEITHER_SIGNED; 32 import static android.content.pm.PackageManager.SIGNATURE_NO_MATCH; 33 import static android.content.pm.PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 34 import static android.content.pm.PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 35 import static android.content.pm.PackageManager.VERIFICATION_ALLOW; 36 import static android.content.pm.PackageManager.VERIFICATION_REJECT; 37 import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1; 38 import static android.os.Build.VERSION_CODES.M; 39 import static android.os.Build.VERSION_CODES.N; 40 import static android.os.Build.VERSION_CODES.N_MR1; 41 import static android.os.Build.VERSION_CODES.O; 42 import static android.os.Build.VERSION_CODES.P; 43 import static android.os.Build.VERSION_CODES.Q; 44 import static android.os.Build.VERSION_CODES.S; 45 import static android.os.Build.VERSION_CODES.TIRAMISU; 46 import static com.google.common.collect.ImmutableList.toImmutableList; 47 import static com.google.common.truth.Truth.assertThat; 48 import static com.google.common.truth.Truth.assertWithMessage; 49 import static org.junit.Assert.assertEquals; 50 import static org.junit.Assert.assertThrows; 51 import static org.junit.Assert.fail; 52 import static org.mockito.Mockito.doReturn; 53 import static org.mockito.Mockito.eq; 54 import static org.mockito.Mockito.mock; 55 import static org.mockito.Mockito.times; 56 import static org.mockito.Mockito.verify; 57 import static org.mockito.Mockito.verifyNoMoreInteractions; 58 import static org.robolectric.Robolectric.setupActivity; 59 import static org.robolectric.Shadows.shadowOf; 60 import static org.robolectric.shadows.ShadowLooper.shadowMainLooper; 61 62 import android.Manifest; 63 import android.Manifest.permission_group; 64 import android.app.Activity; 65 import android.app.Application; 66 import android.app.admin.DevicePolicyManager; 67 import android.content.BroadcastReceiver; 68 import android.content.ComponentName; 69 import android.content.Context; 70 import android.content.Intent; 71 import android.content.IntentFilter; 72 import android.content.pm.ActivityInfo; 73 import android.content.pm.ApplicationInfo; 74 import android.content.pm.ChangedPackages; 75 import android.content.pm.FeatureInfo; 76 import android.content.pm.IPackageDeleteObserver; 77 import android.content.pm.IPackageStatsObserver; 78 import android.content.pm.InstallSourceInfo; 79 import android.content.pm.ModuleInfo; 80 import android.content.pm.PackageInfo; 81 import android.content.pm.PackageInstaller; 82 import android.content.pm.PackageManager; 83 import android.content.pm.PackageManager.ApplicationInfoFlags; 84 import android.content.pm.PackageManager.ComponentEnabledSetting; 85 import android.content.pm.PackageManager.NameNotFoundException; 86 import android.content.pm.PackageManager.OnPermissionsChangedListener; 87 import android.content.pm.PackageManager.PackageInfoFlags; 88 import android.content.pm.PackageManager.ResolveInfoFlags; 89 import android.content.pm.PackageParser.Package; 90 import android.content.pm.PackageParser.PermissionGroup; 91 import android.content.pm.PackageStats; 92 import android.content.pm.PathPermission; 93 import android.content.pm.PermissionGroupInfo; 94 import android.content.pm.PermissionInfo; 95 import android.content.pm.ProviderInfo; 96 import android.content.pm.ResolveInfo; 97 import android.content.pm.ServiceInfo; 98 import android.content.pm.Signature; 99 import android.content.pm.SigningInfo; 100 import android.content.pm.SuspendDialogInfo; 101 import android.content.res.XmlResourceParser; 102 import android.graphics.Color; 103 import android.graphics.drawable.BitmapDrawable; 104 import android.graphics.drawable.Drawable; 105 import android.net.Uri; 106 import android.os.Build.VERSION; 107 import android.os.Build.VERSION_CODES; 108 import android.os.Bundle; 109 import android.os.PersistableBundle; 110 import android.os.Process; 111 import android.provider.DocumentsContract; 112 import android.telecom.TelecomManager; 113 import androidx.test.core.app.ApplicationProvider; 114 import androidx.test.core.content.pm.ApplicationInfoBuilder; 115 import androidx.test.core.content.pm.PackageInfoBuilder; 116 import androidx.test.ext.junit.runners.AndroidJUnit4; 117 import com.google.common.collect.ImmutableList; 118 import java.io.ByteArrayInputStream; 119 import java.io.File; 120 import java.util.ArrayList; 121 import java.util.Arrays; 122 import java.util.Iterator; 123 import java.util.List; 124 import org.junit.After; 125 import org.junit.Assert; 126 import org.junit.Before; 127 import org.junit.Rule; 128 import org.junit.Test; 129 import org.junit.rules.TemporaryFolder; 130 import org.junit.runner.RunWith; 131 import org.mockito.ArgumentCaptor; 132 import org.mockito.Mockito; 133 import org.robolectric.R; 134 import org.robolectric.RuntimeEnvironment; 135 import org.robolectric.annotation.Config; 136 import org.robolectric.annotation.GetInstallerPackageNameMode; 137 import org.robolectric.annotation.GetInstallerPackageNameMode.Mode; 138 import org.robolectric.shadow.api.Shadow; 139 import org.robolectric.shadows.ShadowPackageManager.PackageSetting; 140 import org.robolectric.shadows.ShadowPackageManager.ResolveInfoComparator; 141 import org.robolectric.util.ReflectionHelpers; 142 import org.robolectric.util.ReflectionHelpers.ClassParameter; 143 import org.robolectric.util.TestUtil; 144 145 @RunWith(AndroidJUnit4.class) 146 public class ShadowPackageManagerTest { 147 148 private static final String TEST_PACKAGE_NAME = "com.some.other.package"; 149 private static final String TEST_PACKAGE_LABEL = "My Little App"; 150 private static final String TEST_APP_PATH = "/values/app/application.apk"; 151 private static final String TEST_PACKAGE2_NAME = "com.a.second.package"; 152 private static final String TEST_PACKAGE2_LABEL = "A Second App"; 153 private static final String TEST_APP2_PATH = "/values/app/application2.apk"; 154 private static final Object USER_ID = 1; 155 private static final String REAL_TEST_APP_ASSET_PATH = "assets/exampleapp.apk"; 156 private static final String REAL_TEST_APP_PACKAGE_NAME = "org.robolectric.exampleapp"; 157 private static final String TEST_PACKAGE3_NAME = "com.a.third.package"; 158 private static final int TEST_PACKAGE_VERSION_CODE = 10000; 159 public static final int INSTALL_VERIFICATION_ID = 1234; 160 public static final String INITIATING_PACKAGE_NAME = "initiating.package"; 161 public static final String INSTALLING_PACKAGE_NAME = "installing.package"; 162 public static final String ORIGINATING_PACKAGE_NAME = "originating.package"; 163 public static final String UPDATE_OWNER_PACKAGE_NAME = "update.owner.package"; 164 165 @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); 166 private Context context; 167 private PackageManager packageManager; 168 169 private final ArgumentCaptor<PackageStats> packageStatsCaptor = 170 ArgumentCaptor.forClass(PackageStats.class); 171 172 @Before setUp()173 public void setUp() { 174 context = ApplicationProvider.getApplicationContext(); 175 packageManager = context.getPackageManager(); 176 } 177 178 @After tearDown()179 public void tearDown() { 180 ShadowPackageManager.reset(); 181 } 182 183 @Test packageInstallerCreateSession()184 public void packageInstallerCreateSession() throws Exception { 185 PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller(); 186 int sessionId = packageInstaller.createSession(createSessionParams("packageName")); 187 188 PackageInstaller.SessionInfo sessionInfo = packageInstaller.getSessionInfo(sessionId); 189 assertThat(sessionInfo.isActive()).isTrue(); 190 191 assertThat(sessionInfo.appPackageName).isEqualTo("packageName"); 192 193 packageInstaller.abandonSession(sessionId); 194 195 assertThat(packageInstaller.getSessionInfo(sessionId)).isNull(); 196 } 197 198 @Test packageInstallerOpenSession()199 public void packageInstallerOpenSession() throws Exception { 200 PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller(); 201 int sessionId = packageInstaller.createSession(createSessionParams("packageName")); 202 203 PackageInstaller.Session session = packageInstaller.openSession(sessionId); 204 205 assertThat(session).isNotNull(); 206 } 207 createSessionParams(String appPackageName)208 private static PackageInstaller.SessionParams createSessionParams(String appPackageName) { 209 PackageInstaller.SessionParams params = 210 new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL); 211 params.setAppPackageName(appPackageName); 212 return params; 213 } 214 215 @Test packageInstallerAndGetPackageArchiveInfo()216 public void packageInstallerAndGetPackageArchiveInfo() { 217 shadowOf(packageManager).installPackage(generateTestPackageInfo()); 218 verifyTestPackageInfo(packageManager.getPackageArchiveInfo(TEST_APP_PATH, 0)); 219 } 220 221 @Test packageInstallerAndGetPackageInfo()222 public void packageInstallerAndGetPackageInfo() throws NameNotFoundException { 223 shadowOf(packageManager).installPackage(generateTestPackageInfo()); 224 verifyTestPackageInfo(packageManager.getPackageInfo(TEST_PACKAGE_NAME, 0)); 225 } 226 227 @Config(minSdk = TIRAMISU) 228 @Test packageInstallerAndGetPackageInfo_T()229 public void packageInstallerAndGetPackageInfo_T() throws NameNotFoundException { 230 shadowOf(packageManager).installPackage(generateTestPackageInfo()); 231 verifyTestPackageInfo(packageManager.getPackageInfo(TEST_PACKAGE_NAME, PackageInfoFlags.of(0))); 232 } 233 234 @Test applicationFlags()235 public void applicationFlags() throws Exception { 236 int flags = packageManager.getApplicationInfo("org.robolectric", 0).flags; 237 assertThat((flags & FLAG_ALLOW_BACKUP)).isEqualTo(FLAG_ALLOW_BACKUP); 238 assertThat((flags & FLAG_ALLOW_CLEAR_USER_DATA)).isEqualTo(FLAG_ALLOW_CLEAR_USER_DATA); 239 assertThat((flags & FLAG_ALLOW_TASK_REPARENTING)).isEqualTo(FLAG_ALLOW_TASK_REPARENTING); 240 assertThat((flags & FLAG_DEBUGGABLE)).isEqualTo(FLAG_DEBUGGABLE); 241 assertThat((flags & FLAG_HAS_CODE)).isEqualTo(FLAG_HAS_CODE); 242 assertThat((flags & FLAG_RESIZEABLE_FOR_SCREENS)).isEqualTo(FLAG_RESIZEABLE_FOR_SCREENS); 243 assertThat((flags & FLAG_SUPPORTS_LARGE_SCREENS)).isEqualTo(FLAG_SUPPORTS_LARGE_SCREENS); 244 assertThat((flags & FLAG_SUPPORTS_NORMAL_SCREENS)).isEqualTo(FLAG_SUPPORTS_NORMAL_SCREENS); 245 assertThat((flags & FLAG_SUPPORTS_SCREEN_DENSITIES)).isEqualTo(FLAG_SUPPORTS_SCREEN_DENSITIES); 246 assertThat((flags & FLAG_SUPPORTS_SMALL_SCREENS)).isEqualTo(FLAG_SUPPORTS_SMALL_SCREENS); 247 assertThat((flags & FLAG_VM_SAFE_MODE)).isEqualTo(FLAG_VM_SAFE_MODE); 248 } 249 250 /** 251 * Tests the permission grants of this test package. 252 * 253 * <p>These grants are defined in the test package's AndroidManifest.xml. 254 */ 255 @Test testCheckPermission_thisPackage()256 public void testCheckPermission_thisPackage() { 257 String thisPackage = context.getPackageName(); 258 assertEquals( 259 PERMISSION_GRANTED, 260 packageManager.checkPermission("android.permission.INTERNET", thisPackage)); 261 assertEquals( 262 PERMISSION_GRANTED, 263 packageManager.checkPermission("android.permission.SYSTEM_ALERT_WINDOW", thisPackage)); 264 assertEquals( 265 PERMISSION_GRANTED, 266 packageManager.checkPermission("android.permission.GET_TASKS", thisPackage)); 267 268 assertEquals( 269 PERMISSION_DENIED, 270 packageManager.checkPermission("android.permission.ACCESS_FINE_LOCATION", thisPackage)); 271 assertEquals( 272 PERMISSION_DENIED, 273 packageManager.checkPermission( 274 "android.permission.ACCESS_FINE_LOCATION", "random-package")); 275 } 276 277 /** 278 * Tests the permission grants of other packages. These packages are added to the PackageManager 279 * by calling {@link ShadowPackageManager#addPackage}. 280 */ 281 @Test testCheckPermission_otherPackages()282 public void testCheckPermission_otherPackages() { 283 PackageInfo packageInfo = new PackageInfo(); 284 packageInfo.packageName = TEST_PACKAGE_NAME; 285 packageInfo.requestedPermissions = 286 new String[] {"android.permission.INTERNET", "android.permission.SEND_SMS"}; 287 // Grant one of the permissions. 288 packageInfo.requestedPermissionsFlags = 289 new int[] {REQUESTED_PERMISSION_GRANTED, 0 /* this permission isn't granted */}; 290 shadowOf(packageManager).installPackage(packageInfo); 291 292 assertEquals( 293 PERMISSION_GRANTED, 294 packageManager.checkPermission("android.permission.INTERNET", TEST_PACKAGE_NAME)); 295 assertEquals( 296 PERMISSION_DENIED, 297 packageManager.checkPermission("android.permission.SEND_SMS", TEST_PACKAGE_NAME)); 298 assertEquals( 299 PERMISSION_DENIED, 300 packageManager.checkPermission("android.permission.READ_SMS", TEST_PACKAGE_NAME)); 301 } 302 303 /** 304 * Tests the permission grants of other packages. These packages are added to the PackageManager 305 * by calling {@link ShadowPackageManager#addPackage}. 306 */ 307 @Test testCheckPermission_otherPackages_grantedByDefault()308 public void testCheckPermission_otherPackages_grantedByDefault() { 309 PackageInfo packageInfo = new PackageInfo(); 310 packageInfo.packageName = TEST_PACKAGE_NAME; 311 packageInfo.requestedPermissions = 312 new String[] {"android.permission.INTERNET", "android.permission.SEND_SMS"}; 313 shadowOf(packageManager).installPackage(packageInfo); 314 315 // Because we didn't specify permission grant state in the PackageInfo object, all requested 316 // permissions are automatically granted. See ShadowPackageManager.grantPermissionsByDefault() 317 // for the explanation. 318 assertEquals( 319 PERMISSION_GRANTED, 320 packageManager.checkPermission("android.permission.INTERNET", TEST_PACKAGE_NAME)); 321 assertEquals( 322 PERMISSION_GRANTED, 323 packageManager.checkPermission("android.permission.SEND_SMS", TEST_PACKAGE_NAME)); 324 assertEquals( 325 PERMISSION_DENIED, 326 packageManager.checkPermission("android.permission.READ_SMS", TEST_PACKAGE_NAME)); 327 } 328 329 @Test 330 @Config(minSdk = M) testGrantRuntimePermission()331 public void testGrantRuntimePermission() { 332 PackageInfo packageInfo = new PackageInfo(); 333 packageInfo.packageName = TEST_PACKAGE_NAME; 334 packageInfo.requestedPermissions = 335 new String[] {"android.permission.SEND_SMS", "android.permission.READ_SMS"}; 336 packageInfo.requestedPermissionsFlags = new int[] {0, 0}; // Not granted by default 337 packageInfo.applicationInfo = new ApplicationInfo(); 338 packageInfo.applicationInfo.uid = 12345; 339 shadowOf(packageManager).installPackage(packageInfo); 340 341 OnPermissionsChangedListener listener = mock(OnPermissionsChangedListener.class); 342 packageManager.addOnPermissionsChangeListener(listener); 343 344 packageManager.grantRuntimePermission( 345 TEST_PACKAGE_NAME, "android.permission.SEND_SMS", Process.myUserHandle()); 346 347 verify(listener, times(1)).onPermissionsChanged(12345); 348 assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(REQUESTED_PERMISSION_GRANTED); 349 assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(0); 350 351 packageManager.grantRuntimePermission( 352 TEST_PACKAGE_NAME, "android.permission.READ_SMS", Process.myUserHandle()); 353 354 verify(listener, times(2)).onPermissionsChanged(12345); 355 assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(REQUESTED_PERMISSION_GRANTED); 356 assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(REQUESTED_PERMISSION_GRANTED); 357 } 358 359 @Test 360 @Config(minSdk = M) testGrantRuntimePermission_packageNotFound()361 public void testGrantRuntimePermission_packageNotFound() { 362 try { 363 packageManager.grantRuntimePermission( 364 "com.unknown.package", "android.permission.SEND_SMS", Process.myUserHandle()); 365 fail("Exception expected"); 366 } catch (SecurityException expected) { 367 } 368 } 369 370 @Test 371 @Config(minSdk = M) testGrantRuntimePermission_doesntRequestPermission()372 public void testGrantRuntimePermission_doesntRequestPermission() { 373 PackageInfo packageInfo = new PackageInfo(); 374 packageInfo.packageName = TEST_PACKAGE_NAME; 375 packageInfo.requestedPermissions = 376 new String[] {"android.permission.SEND_SMS", "android.permission.READ_SMS"}; 377 packageInfo.requestedPermissionsFlags = new int[] {0, 0}; // Not granted by default 378 shadowOf(packageManager).installPackage(packageInfo); 379 380 try { 381 packageManager.grantRuntimePermission( 382 // This permission is not granted to the package. 383 TEST_PACKAGE_NAME, "android.permission.RECEIVE_SMS", Process.myUserHandle()); 384 fail("Exception expected"); 385 } catch (SecurityException expected) { 386 } 387 } 388 389 @Test 390 @Config(minSdk = M) testRevokeRuntimePermission()391 public void testRevokeRuntimePermission() { 392 PackageInfo packageInfo = new PackageInfo(); 393 packageInfo.packageName = TEST_PACKAGE_NAME; 394 packageInfo.requestedPermissions = 395 new String[] {"android.permission.SEND_SMS", "android.permission.READ_SMS"}; 396 packageInfo.requestedPermissionsFlags = 397 new int[] {REQUESTED_PERMISSION_GRANTED, REQUESTED_PERMISSION_GRANTED}; 398 packageInfo.applicationInfo = new ApplicationInfo(); 399 packageInfo.applicationInfo.uid = 12345; 400 shadowOf(packageManager).installPackage(packageInfo); 401 402 OnPermissionsChangedListener listener = mock(OnPermissionsChangedListener.class); 403 packageManager.addOnPermissionsChangeListener(listener); 404 405 packageManager.revokeRuntimePermission( 406 TEST_PACKAGE_NAME, "android.permission.SEND_SMS", Process.myUserHandle()); 407 408 verify(listener, times(1)).onPermissionsChanged(12345); 409 assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(0); 410 assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(REQUESTED_PERMISSION_GRANTED); 411 412 packageManager.revokeRuntimePermission( 413 TEST_PACKAGE_NAME, "android.permission.READ_SMS", Process.myUserHandle()); 414 415 verify(listener, times(2)).onPermissionsChanged(12345); 416 assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(0); 417 assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(0); 418 } 419 420 @Test 421 @Config(minSdk = M) getPermissionFlags_whenNoPackagePermissionFlagsProvided_returnsZero()422 public void getPermissionFlags_whenNoPackagePermissionFlagsProvided_returnsZero() { 423 // Don't add any permission flags 424 int flags = 425 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 426 427 assertThat(flags).isEqualTo(0); 428 } 429 430 @Test 431 @Config(minSdk = M) getPermissionFlags_whenPackagePermissionFlagsProvided_returnsPermissionFlags()432 public void getPermissionFlags_whenPackagePermissionFlagsProvided_returnsPermissionFlags() { 433 // Add the SYSTEM_FIXED permission flag 434 packageManager.updatePermissionFlags( 435 READ_SMS, 436 TEST_PACKAGE_NAME, 437 FLAG_PERMISSION_SYSTEM_FIXED, 438 FLAG_PERMISSION_SYSTEM_FIXED, 439 Process.myUserHandle()); 440 441 int flags = 442 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 443 444 assertThat(flags).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 445 } 446 447 @Test 448 @Config(minSdk = M) getPermissionFlags_whenPackagePermissionFlagsProvidedForDiffPermission_returnsZero()449 public void getPermissionFlags_whenPackagePermissionFlagsProvidedForDiffPermission_returnsZero() { 450 // Add the SYSTEM_FIXED permission flag to the READ_SMS permission 451 packageManager.updatePermissionFlags( 452 READ_SMS, 453 TEST_PACKAGE_NAME, 454 FLAG_PERMISSION_SYSTEM_FIXED, 455 FLAG_PERMISSION_SYSTEM_FIXED, 456 Process.myUserHandle()); 457 458 int flags = 459 packageManager.getPermissionFlags(READ_CONTACTS, TEST_PACKAGE_NAME, Process.myUserHandle()); 460 461 assertThat(flags).isEqualTo(0); 462 } 463 464 @Test 465 @Config(minSdk = M) getPermissionFlags_whenPermissionFlagsProvidedForDifferentPackage_returnsZero()466 public void getPermissionFlags_whenPermissionFlagsProvidedForDifferentPackage_returnsZero() { 467 // Add the SYSTEM_FIXED permission flag to the READ_SMS permission for TEST_PACKAGE_NAME 468 packageManager.updatePermissionFlags( 469 READ_SMS, 470 TEST_PACKAGE_NAME, 471 FLAG_PERMISSION_SYSTEM_FIXED, 472 FLAG_PERMISSION_SYSTEM_FIXED, 473 Process.myUserHandle()); 474 475 int flags = 476 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE2_NAME, Process.myUserHandle()); 477 478 assertThat(flags).isEqualTo(0); 479 } 480 481 @Test 482 @Config(minSdk = M) updatePermissionFlags_whenNoFlagMaskProvided_doesNotUpdateFlags()483 public void updatePermissionFlags_whenNoFlagMaskProvided_doesNotUpdateFlags() { 484 // Check that we have no permission flags set beforehand 485 int oldFlags = 486 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 487 assertThat(oldFlags).isEqualTo(0); 488 489 packageManager.updatePermissionFlags( 490 READ_SMS, 491 TEST_PACKAGE_NAME, 492 /* flagMask= */ 0, 493 FLAG_PERMISSION_SYSTEM_FIXED, 494 Process.myUserHandle()); 495 496 int newFlags = 497 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 498 assertThat(newFlags).isEqualTo(0); 499 } 500 501 @Test 502 @Config(minSdk = M) updatePermissionFlags_whenPackageHasOnePermissionFlagTurnedOn_updatesFlagToBeOn()503 public void updatePermissionFlags_whenPackageHasOnePermissionFlagTurnedOn_updatesFlagToBeOn() { 504 // Check that we have no permission flags set beforehand 505 int oldFlags = 506 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 507 assertThat(oldFlags).isEqualTo(0); 508 509 packageManager.updatePermissionFlags( 510 READ_SMS, 511 TEST_PACKAGE_NAME, 512 FLAG_PERMISSION_SYSTEM_FIXED, 513 FLAG_PERMISSION_SYSTEM_FIXED, 514 Process.myUserHandle()); 515 516 int newFlags = 517 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 518 assertThat(newFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 519 } 520 521 @Test 522 @Config(minSdk = M) updatePermissionFlags_whenPackageHasOnePermissionFlagTurnedOff_updatesFlagToBeOff()523 public void updatePermissionFlags_whenPackageHasOnePermissionFlagTurnedOff_updatesFlagToBeOff() { 524 // Check that we have one permission flag set beforehand 525 packageManager.updatePermissionFlags( 526 READ_SMS, 527 TEST_PACKAGE_NAME, 528 FLAG_PERMISSION_SYSTEM_FIXED, 529 FLAG_PERMISSION_SYSTEM_FIXED, 530 Process.myUserHandle()); 531 int oldFlags = 532 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 533 assertThat(oldFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 534 535 packageManager.updatePermissionFlags( 536 READ_SMS, 537 TEST_PACKAGE_NAME, 538 FLAG_PERMISSION_SYSTEM_FIXED, 539 /* flagValues= */ 0, 540 Process.myUserHandle()); 541 542 int newFlags = 543 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 544 assertThat(newFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(0); 545 } 546 547 @Test 548 @Config(minSdk = M) 549 public void updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOn_updatesFlagsToBeOn()550 updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOn_updatesFlagsToBeOn() { 551 // Check that we have no permission flags set beforehand 552 int oldFlags = 553 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 554 assertThat(oldFlags).isEqualTo(0); 555 556 packageManager.updatePermissionFlags( 557 READ_SMS, 558 TEST_PACKAGE_NAME, 559 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 560 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 561 Process.myUserHandle()); 562 563 int newFlags = 564 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 565 assertThat(newFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 566 assertThat(newFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 567 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 568 } 569 570 @Test 571 @Config(minSdk = M) 572 public void updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOff_updatesFlagsToBeOff()573 updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOff_updatesFlagsToBeOff() { 574 // Check that we have one permission flag set beforehand 575 packageManager.updatePermissionFlags( 576 READ_SMS, 577 TEST_PACKAGE_NAME, 578 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 579 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 580 Process.myUserHandle()); 581 int oldFlags = 582 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 583 assertThat(oldFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 584 assertThat(oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 585 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 586 587 packageManager.updatePermissionFlags( 588 READ_SMS, 589 TEST_PACKAGE_NAME, 590 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 591 /* flagValues= */ 0, 592 Process.myUserHandle()); 593 594 int newFlags = 595 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 596 assertThat(newFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(0); 597 assertThat(newFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT).isEqualTo(0); 598 } 599 600 @Test 601 @Config(minSdk = M) 602 public void updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOn_turnOneFlagOff_onlyAffectsOneFlag()603 updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOn_turnOneFlagOff_onlyAffectsOneFlag() { 604 // Check that we have one permission flag set beforehand 605 packageManager.updatePermissionFlags( 606 READ_SMS, 607 TEST_PACKAGE_NAME, 608 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 609 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 610 Process.myUserHandle()); 611 int oldFlags = 612 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 613 assertThat(oldFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 614 assertThat(oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 615 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 616 617 packageManager.updatePermissionFlags( 618 READ_SMS, 619 TEST_PACKAGE_NAME, 620 FLAG_PERMISSION_SYSTEM_FIXED, 621 /* flagValues= */ 0, 622 Process.myUserHandle()); 623 624 int newFlags = 625 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 626 assertThat(newFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(0); 627 // The GRANTED_BY_DEFAULT flag should be untouched 628 assertThat(newFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 629 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 630 } 631 632 @Test 633 @Config(minSdk = M) 634 public void updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOn_turnDiffFlagOn_doesNotAffectOtherFlags()635 updatePermissionFlags_whenPackageHasMultiplePermissionFlagsTurnedOn_turnDiffFlagOn_doesNotAffectOtherFlags() { 636 // Check that we have one permission flag set beforehand 637 packageManager.updatePermissionFlags( 638 READ_SMS, 639 TEST_PACKAGE_NAME, 640 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 641 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 642 Process.myUserHandle()); 643 int oldFlags = 644 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 645 assertThat(oldFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 646 assertThat(oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 647 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 648 649 packageManager.updatePermissionFlags( 650 READ_SMS, 651 TEST_PACKAGE_NAME, 652 FLAG_PERMISSION_USER_FIXED, 653 FLAG_PERMISSION_USER_FIXED, 654 Process.myUserHandle()); 655 656 int newFlags = 657 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 658 // The SYSTEM_FIXED and GRANTED_BY_DEFAULT flags should not be affected 659 assertThat(newFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 660 assertThat(newFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 661 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 662 assertThat(newFlags & FLAG_PERMISSION_USER_FIXED).isEqualTo(FLAG_PERMISSION_USER_FIXED); 663 } 664 665 @Test 666 @Config(minSdk = M) updatePermissionFlags_forDifferentPermission_doesNotAffectOriginalPermissionFlags()667 public void updatePermissionFlags_forDifferentPermission_doesNotAffectOriginalPermissionFlags() { 668 // Check that we have one permission flag set beforehand 669 packageManager.updatePermissionFlags( 670 READ_SMS, 671 TEST_PACKAGE_NAME, 672 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 673 FLAG_PERMISSION_SYSTEM_FIXED | FLAG_PERMISSION_GRANTED_BY_DEFAULT, 674 Process.myUserHandle()); 675 int oldSmsFlags = 676 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 677 assertThat(oldSmsFlags & FLAG_PERMISSION_SYSTEM_FIXED).isEqualTo(FLAG_PERMISSION_SYSTEM_FIXED); 678 assertThat(oldSmsFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) 679 .isEqualTo(FLAG_PERMISSION_GRANTED_BY_DEFAULT); 680 681 packageManager.updatePermissionFlags( 682 READ_CONTACTS, 683 TEST_PACKAGE_NAME, 684 FLAG_PERMISSION_USER_FIXED, 685 FLAG_PERMISSION_USER_FIXED, 686 Process.myUserHandle()); 687 688 int newSmsFlags = 689 packageManager.getPermissionFlags(READ_SMS, TEST_PACKAGE_NAME, Process.myUserHandle()); 690 // Check we haven't changed the permission flags of the READ_SMS permission 691 assertThat(oldSmsFlags).isEqualTo(newSmsFlags); 692 int contactsFlags = 693 packageManager.getPermissionFlags(READ_CONTACTS, TEST_PACKAGE_NAME, Process.myUserHandle()); 694 assertThat(contactsFlags & FLAG_PERMISSION_USER_FIXED).isEqualTo(FLAG_PERMISSION_USER_FIXED); 695 } 696 697 @Test testQueryBroadcastReceiverSucceeds()698 public void testQueryBroadcastReceiverSucceeds() { 699 Intent intent = new Intent("org.robolectric.ACTION_RECEIVER_PERMISSION_PACKAGE"); 700 intent.setPackage(context.getPackageName()); 701 702 List<ResolveInfo> receiverInfos = 703 packageManager.queryBroadcastReceivers(intent, PackageManager.GET_RESOLVED_FILTER); 704 assertThat(receiverInfos).isNotEmpty(); 705 assertThat(receiverInfos.get(0).activityInfo.name) 706 .isEqualTo("org.robolectric.ConfigTestReceiverPermissionsAndActions"); 707 assertThat(receiverInfos.get(0).activityInfo.permission) 708 .isEqualTo("org.robolectric.CUSTOM_PERM"); 709 assertThat(receiverInfos.get(0).filter.getAction(0)) 710 .isEqualTo("org.robolectric.ACTION_RECEIVER_PERMISSION_PACKAGE"); 711 } 712 713 @Test testQueryBroadcastReceiverFailsForMissingPackageName()714 public void testQueryBroadcastReceiverFailsForMissingPackageName() { 715 Intent intent = new Intent("org.robolectric.ACTION_ONE_MORE_PACKAGE"); 716 List<ResolveInfo> receiverInfos = 717 packageManager.queryBroadcastReceivers(intent, PackageManager.GET_RESOLVED_FILTER); 718 assertThat(receiverInfos).isEmpty(); 719 } 720 721 @Test testQueryBroadcastReceiver_matchAllWithoutIntentFilter()722 public void testQueryBroadcastReceiver_matchAllWithoutIntentFilter() { 723 Intent intent = new Intent(); 724 intent.setPackage(context.getPackageName()); 725 List<ResolveInfo> receiverInfos = 726 packageManager.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); 727 assertThat(receiverInfos).hasSize(7); 728 729 for (ResolveInfo receiverInfo : receiverInfos) { 730 assertThat(receiverInfo.activityInfo.name) 731 .isNotEqualTo("com.bar.ReceiverWithoutIntentFilter"); 732 } 733 } 734 735 @Test testGetPackageInfo_ForReceiversSucceeds()736 public void testGetPackageInfo_ForReceiversSucceeds() throws Exception { 737 PackageInfo receiverInfos = 738 packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_RECEIVERS); 739 740 assertThat(receiverInfos.receivers).isNotEmpty(); 741 assertThat(receiverInfos.receivers[0].name) 742 .isEqualTo("org.robolectric.ConfigTestReceiver.InnerReceiver"); 743 assertThat(receiverInfos.receivers[0].permission).isEqualTo("com.ignored.PERM"); 744 } 745 746 private static class ActivityWithConfigChanges extends Activity {} 747 748 @Test getActivityMetaData_configChanges()749 public void getActivityMetaData_configChanges() throws Exception { 750 Activity activity = setupActivity(ShadowPackageManagerTest.ActivityWithConfigChanges.class); 751 752 ActivityInfo activityInfo = 753 activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0); 754 755 int configChanges = activityInfo.configChanges; 756 assertThat(configChanges & ActivityInfo.CONFIG_SCREEN_LAYOUT) 757 .isEqualTo(ActivityInfo.CONFIG_SCREEN_LAYOUT); 758 assertThat(configChanges & ActivityInfo.CONFIG_ORIENTATION) 759 .isEqualTo(ActivityInfo.CONFIG_ORIENTATION); 760 761 // Spot check a few other possible values that shouldn't be in the flags. 762 assertThat(configChanges & ActivityInfo.CONFIG_FONT_SCALE).isEqualTo(0); 763 assertThat(configChanges & ActivityInfo.CONFIG_SCREEN_SIZE).isEqualTo(0); 764 } 765 766 /** MCC + MNC are always present in config changes since Oreo. */ 767 @Test 768 @Config(minSdk = O) getActivityMetaData_configChangesAlwaysIncludesMccAndMnc()769 public void getActivityMetaData_configChangesAlwaysIncludesMccAndMnc() throws Exception { 770 Activity activity = setupActivity(ShadowPackageManagerTest.ActivityWithConfigChanges.class); 771 772 ActivityInfo activityInfo = 773 activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0); 774 775 int configChanges = activityInfo.configChanges; 776 assertThat(configChanges & ActivityInfo.CONFIG_MCC).isEqualTo(ActivityInfo.CONFIG_MCC); 777 assertThat(configChanges & ActivityInfo.CONFIG_MNC).isEqualTo(ActivityInfo.CONFIG_MNC); 778 } 779 780 @Test getPermissionInfo_fromPlatform()781 public void getPermissionInfo_fromPlatform() throws Exception { 782 PermissionInfo permission = packageManager.getPermissionInfo(READ_CONTACTS, 0); 783 784 assertThat(permission.labelRes).isEqualTo(0); 785 assertThat(permission.descriptionRes).isEqualTo(0); 786 assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_DANGEROUS); 787 assertThat(permission.group).isEqualTo(permission_group.CONTACTS); 788 } 789 790 @Test getPermissionInfo_fromManifest()791 public void getPermissionInfo_fromManifest() throws Exception { 792 PermissionInfo permission = 793 packageManager.getPermissionInfo("org.robolectric.permission_with_minimal_fields", 0); 794 795 assertThat(permission.labelRes).isEqualTo(0); 796 assertThat(permission.descriptionRes).isEqualTo(0); 797 assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_NORMAL); 798 } 799 800 @Test getPermissionInfo_addedPermission()801 public void getPermissionInfo_addedPermission() throws Exception { 802 PermissionInfo permissionInfo = new PermissionInfo(); 803 permissionInfo.name = "manually_added_permission"; 804 shadowOf(packageManager).addPermissionInfo(permissionInfo); 805 806 PermissionInfo permission = packageManager.getPermissionInfo("manually_added_permission", 0); 807 808 assertThat(permission.name).isEqualTo("manually_added_permission"); 809 } 810 811 @Test getPermissionInfo_overriddenPlatformPermission()812 public void getPermissionInfo_overriddenPlatformPermission() throws Exception { 813 PermissionInfo permissionInfo = new PermissionInfo(); 814 permissionInfo.name = READ_CONTACTS; 815 permissionInfo.group = "my_other_permission_group"; 816 shadowOf(packageManager).addPermissionInfo(permissionInfo); 817 818 PermissionInfo permission = packageManager.getPermissionInfo(READ_CONTACTS, 0); 819 820 assertThat(permission.labelRes).isEqualTo(0); 821 assertThat(permission.descriptionRes).isEqualTo(0); 822 assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_NORMAL); 823 assertThat(permission.group).isEqualTo("my_other_permission_group"); 824 } 825 826 @Test getPermissionGroupInfo_fromPlatform()827 public void getPermissionGroupInfo_fromPlatform() throws Exception { 828 PermissionGroupInfo permissionGroupInfo = 829 packageManager.getPermissionGroupInfo(permission_group.CALENDAR, 0); 830 831 assertThat(permissionGroupInfo.name).isEqualTo(permission_group.CALENDAR); 832 assertThat(permissionGroupInfo.priority).isEqualTo(200); 833 } 834 835 @Test getPermissionGroupInfo_fromManifest()836 public void getPermissionGroupInfo_fromManifest() throws Exception { 837 PermissionGroupInfo permissionGroupInfo = 838 packageManager.getPermissionGroupInfo("org.robolectric.package_permission_group", 0); 839 840 assertThat(permissionGroupInfo.name).isEqualTo("org.robolectric.package_permission_group"); 841 assertThat(permissionGroupInfo.priority).isEqualTo(0); 842 } 843 844 @Test getPermissionGroupInfo_extraPermissionGroup()845 public void getPermissionGroupInfo_extraPermissionGroup() throws Exception { 846 PermissionGroupInfo extraPermissionGroupInfo = new PermissionGroupInfo(); 847 extraPermissionGroupInfo.name = "my_other_permission_group"; 848 extraPermissionGroupInfo.priority = 42; 849 shadowOf(packageManager).addPermissionGroupInfo(extraPermissionGroupInfo); 850 851 PermissionGroupInfo permissionGroupInfo = 852 packageManager.getPermissionGroupInfo("my_other_permission_group", 0); 853 854 assertThat(permissionGroupInfo.name).isEqualTo("my_other_permission_group"); 855 assertThat(permissionGroupInfo.priority).isEqualTo(42); 856 } 857 858 @Test getPermissionGroupInfo_overriddenPlatformPermissionGroup()859 public void getPermissionGroupInfo_overriddenPlatformPermissionGroup() throws Exception { 860 PermissionGroupInfo extraPermissionGroupInfo = new PermissionGroupInfo(); 861 extraPermissionGroupInfo.name = permission_group.CALENDAR; 862 extraPermissionGroupInfo.priority = 42; 863 shadowOf(packageManager).addPermissionGroupInfo(extraPermissionGroupInfo); 864 865 PermissionGroupInfo permissionGroupInfo = 866 packageManager.getPermissionGroupInfo(permission_group.CALENDAR, 0); 867 868 assertThat(permissionGroupInfo.name).isEqualTo(permission_group.CALENDAR); 869 assertThat(permissionGroupInfo.priority).isEqualTo(42); 870 } 871 872 @Test 873 @Config(minSdk = S) getGroupOfPlatformPermission_fromManifest()874 public void getGroupOfPlatformPermission_fromManifest() throws Exception { 875 String[] permissionGroupArg = new String[1]; 876 877 packageManager.getGroupOfPlatformPermission( 878 "org.robolectric.some_permission", 879 context.getMainExecutor(), 880 (group) -> { 881 permissionGroupArg[0] = group; 882 }); 883 shadowMainLooper().idle(); 884 885 assertThat(permissionGroupArg[0]).isNull(); 886 } 887 888 @Test 889 @Config(minSdk = S) getGroupOfPlatformPermission_fromExtraPermissions()890 public void getGroupOfPlatformPermission_fromExtraPermissions() throws Exception { 891 String permissionName = "some_other_permission"; 892 String permissionGroupName = "some_other_permission_group"; 893 PermissionInfo permissionInfo = new PermissionInfo(); 894 permissionInfo.name = permissionName; 895 permissionInfo.group = permissionGroupName; 896 shadowOf(packageManager).addPermissionInfo(permissionInfo); 897 String[] permissionGroupArg = new String[1]; 898 899 packageManager.getGroupOfPlatformPermission( 900 permissionName, 901 context.getMainExecutor(), 902 (group) -> { 903 permissionGroupArg[0] = group; 904 }); 905 shadowMainLooper().idle(); 906 907 assertThat(permissionGroupArg[0]).isNull(); 908 } 909 910 @Test 911 @Config(minSdk = S) getGroupOfPlatformPermission_fromExtraPermissionsPlatformPrefix()912 public void getGroupOfPlatformPermission_fromExtraPermissionsPlatformPrefix() throws Exception { 913 String permissionName = "android.permission.some_other_permission"; 914 String permissionGroupName = "some_other_permission_group"; 915 PermissionInfo permissionInfo = new PermissionInfo(); 916 permissionInfo.name = permissionName; 917 permissionInfo.group = permissionGroupName; 918 shadowOf(packageManager).addPermissionInfo(permissionInfo); 919 String[] permissionGroupArg = new String[1]; 920 921 packageManager.getGroupOfPlatformPermission( 922 permissionName, 923 context.getMainExecutor(), 924 (group) -> { 925 permissionGroupArg[0] = group; 926 }); 927 shadowMainLooper().idle(); 928 929 assertThat(permissionGroupArg[0]).isEqualTo(permissionGroupName); 930 } 931 932 @Test 933 @Config(minSdk = S) getGroupOfPlatformPermission_unknown()934 public void getGroupOfPlatformPermission_unknown() throws Exception { 935 String[] permissionGroupArg = new String[1]; 936 937 packageManager.getGroupOfPlatformPermission( 938 "unknown_permission", 939 context.getMainExecutor(), 940 (group) -> { 941 permissionGroupArg[0] = group; 942 }); 943 shadowMainLooper().idle(); 944 945 assertThat(permissionGroupArg[0]).isNull(); 946 } 947 948 @Test 949 @Config(minSdk = S) getGroupOfPlatformPermission_fromPlatform()950 public void getGroupOfPlatformPermission_fromPlatform() throws Exception { 951 String[] permissionGroupArg = new String[1]; 952 953 packageManager.getGroupOfPlatformPermission( 954 READ_CONTACTS, 955 context.getMainExecutor(), 956 (group) -> { 957 permissionGroupArg[0] = group; 958 }); 959 shadowMainLooper().idle(); 960 961 assertThat(permissionGroupArg[0]).isEqualTo(permission_group.CONTACTS); 962 } 963 964 @Test 965 @Config(minSdk = S) getGroupOfPlatformPermission_overriddenPlatformPermission()966 public void getGroupOfPlatformPermission_overriddenPlatformPermission() throws Exception { 967 PermissionInfo permissionInfo = new PermissionInfo(); 968 permissionInfo.name = READ_CONTACTS; 969 permissionInfo.group = permission_group.CALENDAR; 970 shadowOf(packageManager).addPermissionInfo(permissionInfo); 971 String[] permissionGroupArg = new String[1]; 972 973 packageManager.getGroupOfPlatformPermission( 974 READ_CONTACTS, 975 context.getMainExecutor(), 976 (group) -> { 977 permissionGroupArg[0] = group; 978 }); 979 shadowMainLooper().idle(); 980 981 assertThat(permissionGroupArg[0]).isEqualTo(permission_group.CALENDAR); 982 } 983 984 @Test 985 @Config(minSdk = S) getPlatformPermissionsForGroup_fromManifest()986 public void getPlatformPermissionsForGroup_fromManifest() throws Exception { 987 List<List<String>> permissionsArg = new ArrayList<>(); 988 989 packageManager.getPlatformPermissionsForGroup( 990 "my_permission_group", 991 context.getMainExecutor(), 992 (permissions) -> { 993 permissionsArg.add(permissions); 994 }); 995 shadowMainLooper().idle(); 996 997 assertThat(permissionsArg).hasSize(1); 998 assertThat(permissionsArg.get(0)).isEmpty(); 999 } 1000 1001 @Test 1002 @Config(minSdk = S) getPlatformPermissionsForGroup_fromExtraPermissions()1003 public void getPlatformPermissionsForGroup_fromExtraPermissions() throws Exception { 1004 String permissionName1 = "some_other_permission"; 1005 String permissionName2 = "android.permission.my_calendar_permission"; 1006 String permissionGroupName = permission_group.CALENDAR; 1007 PermissionInfo permissionInfo1 = new PermissionInfo(); 1008 permissionInfo1.name = permissionName1; 1009 permissionInfo1.group = permissionGroupName; 1010 shadowOf(packageManager).addPermissionInfo(permissionInfo1); 1011 PermissionInfo permissionInfo2 = new PermissionInfo(); 1012 permissionInfo2.name = permissionName2; 1013 permissionInfo2.group = permissionGroupName; 1014 shadowOf(packageManager).addPermissionInfo(permissionInfo2); 1015 List<List<String>> permissionsArg = new ArrayList<>(); 1016 1017 packageManager.getPlatformPermissionsForGroup( 1018 permissionGroupName, 1019 context.getMainExecutor(), 1020 (permissions) -> { 1021 permissionsArg.add(permissions); 1022 }); 1023 shadowMainLooper().idle(); 1024 1025 assertThat(permissionsArg).hasSize(1); 1026 assertThat(permissionsArg.get(0)).doesNotContain(permissionName1); 1027 assertThat(permissionsArg.get(0)).contains(permissionName2); 1028 } 1029 1030 @Test 1031 @Config(minSdk = S) getPlatformPermissionsForGroup_unknown()1032 public void getPlatformPermissionsForGroup_unknown() throws Exception { 1033 List<List<String>> permissionsArg = new ArrayList<>(); 1034 1035 packageManager.getPlatformPermissionsForGroup( 1036 "unknown_permission_group", 1037 context.getMainExecutor(), 1038 (permissions) -> { 1039 permissionsArg.add(permissions); 1040 }); 1041 shadowMainLooper().idle(); 1042 1043 assertThat(permissionsArg).hasSize(1); 1044 assertThat(permissionsArg.get(0)).isEmpty(); 1045 } 1046 1047 @Test 1048 @Config(minSdk = S) getPlatformPermissionsForGroup_fromPlatform()1049 public void getPlatformPermissionsForGroup_fromPlatform() throws Exception { 1050 List<List<String>> permissionsArg = new ArrayList<>(); 1051 1052 packageManager.getPlatformPermissionsForGroup( 1053 permission_group.CALENDAR, 1054 context.getMainExecutor(), 1055 (permissions) -> { 1056 permissionsArg.add(permissions); 1057 }); 1058 shadowMainLooper().idle(); 1059 1060 assertThat(permissionsArg).hasSize(1); 1061 assertThat(permissionsArg.get(0)).containsExactly(READ_CALENDAR, WRITE_CALENDAR); 1062 } 1063 1064 @Test 1065 @Config(minSdk = S) getPlatformPermissionsForGroup_overriddenPlatformPermission()1066 public void getPlatformPermissionsForGroup_overriddenPlatformPermission() throws Exception { 1067 PermissionInfo permissionInfo = new PermissionInfo(); 1068 permissionInfo.name = READ_CONTACTS; 1069 permissionInfo.group = permission_group.CALENDAR; 1070 shadowOf(packageManager).addPermissionInfo(permissionInfo); 1071 List<List<String>> permissionsArg = new ArrayList<>(); 1072 1073 packageManager.getPlatformPermissionsForGroup( 1074 permission_group.CALENDAR, 1075 context.getMainExecutor(), 1076 (permissions) -> { 1077 permissionsArg.add(permissions); 1078 }); 1079 shadowMainLooper().idle(); 1080 1081 assertThat(permissionsArg).hasSize(1); 1082 assertThat(permissionsArg.get(0)).containsExactly(READ_CALENDAR, READ_CONTACTS, WRITE_CALENDAR); 1083 } 1084 1085 @Test getAllPermissionGroups_fromPlatformAndManifest()1086 public void getAllPermissionGroups_fromPlatformAndManifest() { 1087 List<PermissionGroupInfo> allPermissionGroups = packageManager.getAllPermissionGroups(0); 1088 1089 assertThat(allPermissionGroups.stream().map(info -> info.name).collect(toImmutableList())) 1090 .containsExactly( 1091 permission_group.CALENDAR, 1092 permission_group.CONTACTS, 1093 "org.robolectric.package_permission_group"); 1094 } 1095 1096 @Test getAllPermissionGroups_duplicateInExtraPermissions()1097 public void getAllPermissionGroups_duplicateInExtraPermissions() { 1098 PermissionGroupInfo overriddenPermission = new PermissionGroupInfo(); 1099 overriddenPermission.name = "org.robolectric.package_permission_group"; 1100 shadowOf(packageManager).addPermissionGroupInfo(overriddenPermission); 1101 PermissionGroupInfo newCameraPermission = new PermissionGroupInfo(); 1102 newCameraPermission.name = "org.robolectric.package_permission_other_group"; 1103 shadowOf(packageManager).addPermissionGroupInfo(newCameraPermission); 1104 1105 List<PermissionGroupInfo> allPermissionGroups = packageManager.getAllPermissionGroups(0); 1106 1107 assertThat(allPermissionGroups.stream().map(info -> info.name).collect(toImmutableList())) 1108 .containsExactly( 1109 permission_group.CALENDAR, 1110 permission_group.CONTACTS, 1111 "org.robolectric.package_permission_group", 1112 "org.robolectric.package_permission_other_group"); 1113 } 1114 1115 @Test getAllPermissionGroups_duplicatePermission()1116 public void getAllPermissionGroups_duplicatePermission() { 1117 // Package 1 1118 Package pkg1 = new Package(TEST_PACKAGE_NAME); 1119 ApplicationInfo appInfo1 = pkg1.applicationInfo; 1120 appInfo1.flags = ApplicationInfo.FLAG_INSTALLED; 1121 appInfo1.packageName = TEST_PACKAGE_NAME; 1122 appInfo1.sourceDir = TEST_APP_PATH; 1123 appInfo1.name = TEST_PACKAGE_LABEL; 1124 PermissionGroupInfo pgiApp1Group1 = new PermissionGroupInfo(); 1125 pgiApp1Group1.name = "org.robolectric.package_permission_other_group1"; 1126 PermissionGroup pgApp1Group1 = new PermissionGroup(pkg1, pgiApp1Group1); 1127 pkg1.permissionGroups.add(pgApp1Group1); 1128 PermissionGroupInfo pgiApp1Group2 = new PermissionGroupInfo(); 1129 pgiApp1Group2.name = "org.robolectric.package_permission_other_group2"; 1130 PermissionGroup pgApp1Group2 = new PermissionGroup(pkg1, pgiApp1Group2); 1131 pkg1.permissionGroups.add(pgApp1Group2); 1132 shadowOf(packageManager).addPackageInternal(pkg1); 1133 1134 // Package 2, contains one permission group that is the same 1135 Package pkg2 = new Package(TEST_PACKAGE2_NAME); 1136 ApplicationInfo appInfo2 = pkg2.applicationInfo; 1137 appInfo2.flags = ApplicationInfo.FLAG_INSTALLED; 1138 appInfo2.packageName = TEST_PACKAGE2_NAME; 1139 appInfo2.sourceDir = TEST_APP2_PATH; 1140 appInfo2.name = TEST_PACKAGE2_LABEL; 1141 PermissionGroupInfo pgiApp2Group1 = new PermissionGroupInfo(); 1142 pgiApp2Group1.name = "org.robolectric.package_permission_other_group1"; 1143 PermissionGroup pgApp2Group1 = new PermissionGroup(pkg2, pgiApp2Group1); 1144 pkg2.permissionGroups.add(pgApp2Group1); 1145 PermissionGroupInfo pgiApp2Group2 = new PermissionGroupInfo(); 1146 pgiApp2Group2.name = "org.robolectric.package_permission_other_group3"; 1147 PermissionGroup pgApp2Group2 = new PermissionGroup(pkg2, pgiApp2Group2); 1148 pkg2.permissionGroups.add(pgApp2Group2); 1149 shadowOf(packageManager).addPackageInternal(pkg2); 1150 1151 List<PermissionGroupInfo> allPermissionGroups = packageManager.getAllPermissionGroups(0); 1152 1153 // Make sure that the duplicate permission group does not show up in the list 1154 assertThat(allPermissionGroups.stream().map(info -> info.name).collect(toImmutableList())) 1155 .containsExactly( 1156 permission_group.CALENDAR, 1157 permission_group.CONTACTS, 1158 "org.robolectric.package_permission_group", 1159 "org.robolectric.package_permission_other_group1", 1160 "org.robolectric.package_permission_other_group2", 1161 "org.robolectric.package_permission_other_group3"); 1162 } 1163 1164 @Test getPackageArchiveInfo()1165 public void getPackageArchiveInfo() { 1166 ApplicationInfo appInfo = new ApplicationInfo(); 1167 appInfo.flags = ApplicationInfo.FLAG_INSTALLED; 1168 appInfo.packageName = TEST_PACKAGE_NAME; 1169 appInfo.sourceDir = TEST_APP_PATH; 1170 appInfo.name = TEST_PACKAGE_LABEL; 1171 1172 PackageInfo packageInfo = new PackageInfo(); 1173 packageInfo.packageName = TEST_PACKAGE_NAME; 1174 packageInfo.applicationInfo = appInfo; 1175 shadowOf(packageManager).installPackage(packageInfo); 1176 1177 PackageInfo packageInfoResult = packageManager.getPackageArchiveInfo(TEST_APP_PATH, 0); 1178 assertThat(packageInfoResult).isNotNull(); 1179 ApplicationInfo applicationInfo = packageInfoResult.applicationInfo; 1180 assertThat(applicationInfo).isInstanceOf(ApplicationInfo.class); 1181 assertThat(applicationInfo.packageName).isEqualTo(TEST_PACKAGE_NAME); 1182 assertThat(applicationInfo.sourceDir).isEqualTo(TEST_APP_PATH); 1183 } 1184 1185 @Test getPackageArchiveInfo_ApkNotInstalled()1186 public void getPackageArchiveInfo_ApkNotInstalled() { 1187 File testApk = TestUtil.resourcesBaseDir().resolve(REAL_TEST_APP_ASSET_PATH).toFile(); 1188 1189 PackageInfo packageInfo = packageManager.getPackageArchiveInfo(testApk.getAbsolutePath(), 0); 1190 1191 String resourcesMode = System.getProperty("robolectric.resourcesMode"); 1192 if (resourcesMode != null && resourcesMode.equals("legacy")) { 1193 assertThat(packageInfo).isNull(); 1194 } else { 1195 assertThat(packageInfo).isNotNull(); 1196 ApplicationInfo applicationInfo = packageInfo.applicationInfo; 1197 assertThat(applicationInfo.packageName).isEqualTo(REAL_TEST_APP_PACKAGE_NAME); 1198 1199 // double-check that Robolectric doesn't consider this package to be installed 1200 try { 1201 packageManager.getPackageInfo(packageInfo.packageName, 0); 1202 Assert.fail("Package not expected to be installed."); 1203 } catch (NameNotFoundException e) { 1204 // expected exception 1205 } 1206 } 1207 } 1208 1209 @Test getApplicationInfo_thisApplication()1210 public void getApplicationInfo_thisApplication() throws Exception { 1211 ApplicationInfo info = packageManager.getApplicationInfo(context.getPackageName(), 0); 1212 assertThat(info).isNotNull(); 1213 assertThat(info.packageName).isEqualTo(context.getPackageName()); 1214 assertThat(info.processName).isEqualTo(info.packageName); 1215 } 1216 1217 @Test 1218 @Config(minSdk = TIRAMISU) getApplicationInfo_thisApplication_withApplicationInfoFlags()1219 public void getApplicationInfo_thisApplication_withApplicationInfoFlags() throws Exception { 1220 ApplicationInfo info = 1221 packageManager.getApplicationInfo(context.getPackageName(), ApplicationInfoFlags.of(0)); 1222 assertThat(info).isNotNull(); 1223 assertThat(info.packageName).isEqualTo(context.getPackageName()); 1224 assertThat(info.processName).isEqualTo(info.packageName); 1225 } 1226 1227 @Test getApplicationInfo_uninstalledApplication_includeUninstalled()1228 public void getApplicationInfo_uninstalledApplication_includeUninstalled() throws Exception { 1229 shadowOf(packageManager).deletePackage(context.getPackageName()); 1230 1231 ApplicationInfo info = 1232 packageManager.getApplicationInfo(context.getPackageName(), MATCH_UNINSTALLED_PACKAGES); 1233 assertThat(info).isNotNull(); 1234 assertThat(info.packageName).isEqualTo(context.getPackageName()); 1235 } 1236 1237 @Test 1238 @Config(minSdk = TIRAMISU) 1239 public void getApplicationInfo_uninstalledApplication_includeUninstalled_withApplicationInfoFlags()1240 getApplicationInfo_uninstalledApplication_includeUninstalled_withApplicationInfoFlags() 1241 throws Exception { 1242 shadowOf(packageManager).deletePackage(context.getPackageName()); 1243 1244 ApplicationInfo info = 1245 packageManager.getApplicationInfo( 1246 context.getPackageName(), ApplicationInfoFlags.of(MATCH_UNINSTALLED_PACKAGES)); 1247 assertThat(info).isNotNull(); 1248 assertThat(info.packageName).isEqualTo(context.getPackageName()); 1249 } 1250 1251 @Test getApplicationInfo_uninstalledApplication_dontIncludeUninstalled()1252 public void getApplicationInfo_uninstalledApplication_dontIncludeUninstalled() { 1253 shadowOf(packageManager).deletePackage(context.getPackageName()); 1254 1255 try { 1256 packageManager.getApplicationInfo(context.getPackageName(), 0); 1257 fail("PackageManager.NameNotFoundException not thrown"); 1258 } catch (PackageManager.NameNotFoundException e) { 1259 // expected 1260 } 1261 } 1262 1263 @Test 1264 @Config(minSdk = TIRAMISU) 1265 public void getApplicationInfo_uninstalledApplication_dontIncludeUninstalled_withApplicationInfoFlags()1266 getApplicationInfo_uninstalledApplication_dontIncludeUninstalled_withApplicationInfoFlags() { 1267 shadowOf(packageManager).deletePackage(context.getPackageName()); 1268 1269 try { 1270 packageManager.getApplicationInfo(context.getPackageName(), ApplicationInfoFlags.of(0)); 1271 fail("PackageManager.NameNotFoundException not thrown"); 1272 } catch (PackageManager.NameNotFoundException e) { 1273 // expected 1274 } 1275 } 1276 1277 @Test(expected = PackageManager.NameNotFoundException.class) getApplicationInfo_whenUnknown_shouldThrowNameNotFoundException()1278 public void getApplicationInfo_whenUnknown_shouldThrowNameNotFoundException() throws Exception { 1279 try { 1280 packageManager.getApplicationInfo("unknown_package", 0); 1281 fail("should have thrown NameNotFoundException"); 1282 } catch (PackageManager.NameNotFoundException e) { 1283 assertThat(e.getMessage()).contains("unknown_package"); 1284 throw e; 1285 } 1286 } 1287 1288 @Test(expected = PackageManager.NameNotFoundException.class) 1289 @Config(minSdk = TIRAMISU) 1290 public void getApplicationInfo_whenUnknown_shouldThrowNameNotFoundException_withApplicationInfoFlags()1291 getApplicationInfo_whenUnknown_shouldThrowNameNotFoundException_withApplicationInfoFlags() 1292 throws Exception { 1293 try { 1294 packageManager.getApplicationInfo("unknown_package", ApplicationInfoFlags.of(0)); 1295 fail("should have thrown NameNotFoundException"); 1296 } catch (PackageManager.NameNotFoundException e) { 1297 assertThat(e.getMessage()).contains("unknown_package"); 1298 throw e; 1299 } 1300 } 1301 1302 @Test getApplicationInfo_nullPackage_shouldThrowNameNotFoundException()1303 public void getApplicationInfo_nullPackage_shouldThrowNameNotFoundException() { 1304 assertThrows( 1305 PackageManager.NameNotFoundException.class, 1306 () -> packageManager.getApplicationInfo(null, 0)); 1307 } 1308 1309 @Test getApplicationInfo_otherApplication()1310 public void getApplicationInfo_otherApplication() throws Exception { 1311 PackageInfo packageInfo = new PackageInfo(); 1312 packageInfo.packageName = TEST_PACKAGE_NAME; 1313 packageInfo.applicationInfo = new ApplicationInfo(); 1314 packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME; 1315 packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL; 1316 shadowOf(packageManager).installPackage(packageInfo); 1317 1318 ApplicationInfo info = packageManager.getApplicationInfo(TEST_PACKAGE_NAME, 0); 1319 assertThat(info).isNotNull(); 1320 assertThat(info.packageName).isEqualTo(TEST_PACKAGE_NAME); 1321 assertThat(packageManager.getApplicationLabel(info).toString()).isEqualTo(TEST_PACKAGE_LABEL); 1322 } 1323 1324 @Test 1325 @Config(minSdk = TIRAMISU) getApplicationInfo_otherApplication_withApplicationInfoFlags()1326 public void getApplicationInfo_otherApplication_withApplicationInfoFlags() throws Exception { 1327 PackageInfo packageInfo = new PackageInfo(); 1328 packageInfo.packageName = TEST_PACKAGE_NAME; 1329 packageInfo.applicationInfo = new ApplicationInfo(); 1330 packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME; 1331 packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL; 1332 shadowOf(packageManager).installPackage(packageInfo); 1333 1334 ApplicationInfo info = 1335 packageManager.getApplicationInfo(TEST_PACKAGE_NAME, ApplicationInfoFlags.of(0)); 1336 assertThat(info).isNotNull(); 1337 assertThat(info.packageName).isEqualTo(TEST_PACKAGE_NAME); 1338 assertThat(packageManager.getApplicationLabel(info).toString()).isEqualTo(TEST_PACKAGE_LABEL); 1339 } 1340 1341 @Test getApplicationInfo_readsValuesFromSetPackageArchiveInfo()1342 public void getApplicationInfo_readsValuesFromSetPackageArchiveInfo() { 1343 PackageInfo packageInfo = new PackageInfo(); 1344 packageInfo.packageName = "some.package.name"; 1345 String archiveFilePath = "some/file/path"; 1346 shadowOf(packageManager).setPackageArchiveInfo(archiveFilePath, packageInfo); 1347 1348 assertThat(packageManager.getPackageArchiveInfo(archiveFilePath, /* flags= */ 0)) 1349 .isEqualTo(packageInfo); 1350 } 1351 1352 @Test removePackage_shouldHideItFromGetApplicationInfo()1353 public void removePackage_shouldHideItFromGetApplicationInfo() { 1354 PackageInfo packageInfo = new PackageInfo(); 1355 packageInfo.packageName = TEST_PACKAGE_NAME; 1356 packageInfo.applicationInfo = new ApplicationInfo(); 1357 packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME; 1358 packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL; 1359 shadowOf(packageManager).installPackage(packageInfo); 1360 shadowOf(packageManager).removePackage(TEST_PACKAGE_NAME); 1361 1362 try { 1363 packageManager.getApplicationInfo(TEST_PACKAGE_NAME, 0); 1364 fail("NameNotFoundException not thrown"); 1365 } catch (NameNotFoundException e) { 1366 // expected 1367 } 1368 } 1369 1370 @Test queryIntentActivities_EmptyResult()1371 public void queryIntentActivities_EmptyResult() { 1372 Intent i = new Intent(Intent.ACTION_APP_ERROR, null); 1373 i.addCategory(Intent.CATEGORY_APP_BROWSER); 1374 1375 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1376 assertThat(activities).isEmpty(); 1377 } 1378 1379 @Test queryIntentActivities_Match()1380 public void queryIntentActivities_Match() { 1381 Intent i = new Intent(Intent.ACTION_MAIN, null); 1382 i.addCategory(Intent.CATEGORY_LAUNCHER); 1383 1384 ResolveInfo info = new ResolveInfo(); 1385 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1386 info.activityInfo = new ActivityInfo(); 1387 info.activityInfo.name = "name"; 1388 info.activityInfo.packageName = TEST_PACKAGE_NAME; 1389 1390 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1391 1392 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1393 assertThat(activities).isNotNull(); 1394 assertThat(activities).hasSize(2); 1395 assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL); 1396 } 1397 1398 @Test queryIntentActivities_ServiceMatch()1399 public void queryIntentActivities_ServiceMatch() { 1400 Intent i = new Intent("SomeStrangeAction"); 1401 1402 ResolveInfo info = new ResolveInfo(); 1403 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1404 info.serviceInfo = new ServiceInfo(); 1405 info.serviceInfo.name = "name"; 1406 info.serviceInfo.packageName = TEST_PACKAGE_NAME; 1407 1408 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1409 1410 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1411 assertThat(activities).isNotNull(); 1412 assertThat(activities).isEmpty(); 1413 } 1414 1415 @Test queryIntentActivitiesAsUser_EmptyResult()1416 public void queryIntentActivitiesAsUser_EmptyResult() { 1417 Intent i = new Intent(Intent.ACTION_APP_ERROR, null); 1418 i.addCategory(Intent.CATEGORY_APP_BROWSER); 1419 1420 List<ResolveInfo> activities = packageManager.queryIntentActivitiesAsUser(i, 0, 0); 1421 assertThat(activities).isEmpty(); 1422 } 1423 1424 @Test 1425 @Config(minSdk = TIRAMISU) queryIntentActivities_Match_withResolveInfoFlags()1426 public void queryIntentActivities_Match_withResolveInfoFlags() { 1427 Intent i = new Intent(Intent.ACTION_MAIN, null); 1428 i.addCategory(Intent.CATEGORY_LAUNCHER); 1429 1430 ResolveInfo info = new ResolveInfo(); 1431 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1432 info.activityInfo = new ActivityInfo(); 1433 info.activityInfo.name = "name"; 1434 info.activityInfo.packageName = TEST_PACKAGE_NAME; 1435 1436 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1437 1438 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, ResolveInfoFlags.of(0)); 1439 assertThat(activities).isNotNull(); 1440 assertThat(activities).hasSize(2); 1441 assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL); 1442 } 1443 1444 @Test queryIntentActivitiesAsUser_Match()1445 public void queryIntentActivitiesAsUser_Match() { 1446 Intent i = new Intent(Intent.ACTION_MAIN, null); 1447 i.addCategory(Intent.CATEGORY_LAUNCHER); 1448 1449 ResolveInfo info = new ResolveInfo(); 1450 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1451 1452 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1453 1454 List<ResolveInfo> activities = packageManager.queryIntentActivitiesAsUser(i, 0, 0); 1455 assertThat(activities).isNotNull(); 1456 assertThat(activities).hasSize(2); 1457 assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL); 1458 } 1459 1460 @Test 1461 @Config(minSdk = TIRAMISU) queryIntentActivitiesAsUser_Match_withResolveInfoFlags()1462 public void queryIntentActivitiesAsUser_Match_withResolveInfoFlags() { 1463 Intent i = new Intent(Intent.ACTION_MAIN, null); 1464 i.addCategory(Intent.CATEGORY_LAUNCHER); 1465 1466 ResolveInfo info = new ResolveInfo(); 1467 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1468 1469 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1470 1471 List<ResolveInfo> activities = 1472 packageManager.queryIntentActivitiesAsUser(i, ResolveInfoFlags.of(0), 0); 1473 assertThat(activities).isNotNull(); 1474 assertThat(activities).hasSize(2); 1475 assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL); 1476 } 1477 1478 @Test queryIntentActivities_launcher()1479 public void queryIntentActivities_launcher() { 1480 Intent intent = new Intent(Intent.ACTION_MAIN); 1481 intent.addCategory(Intent.CATEGORY_LAUNCHER); 1482 1483 List<ResolveInfo> resolveInfos = 1484 packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL); 1485 assertThat(resolveInfos).hasSize(1); 1486 1487 assertThat(resolveInfos.get(0).activityInfo.name) 1488 .isEqualTo("org.robolectric.shadows.TestActivityAlias"); 1489 assertThat(resolveInfos.get(0).activityInfo.targetActivity) 1490 .isEqualTo("org.robolectric.shadows.TestActivity"); 1491 } 1492 1493 @Test queryIntentActivities_MatchSystemOnly()1494 public void queryIntentActivities_MatchSystemOnly() { 1495 Intent i = new Intent(Intent.ACTION_MAIN, null); 1496 i.addCategory(Intent.CATEGORY_LAUNCHER); 1497 1498 ResolveInfo info1 = ShadowResolveInfo.newResolveInfo(TEST_PACKAGE_LABEL, TEST_PACKAGE_NAME); 1499 ResolveInfo info2 = ShadowResolveInfo.newResolveInfo("System App", "system.launcher"); 1500 info2.activityInfo.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 1501 info2.nonLocalizedLabel = "System App"; 1502 1503 shadowOf(packageManager).addResolveInfoForIntent(i, info1); 1504 shadowOf(packageManager).addResolveInfoForIntent(i, info2); 1505 1506 List<ResolveInfo> activities = 1507 packageManager.queryIntentActivities(i, PackageManager.MATCH_SYSTEM_ONLY); 1508 assertThat(activities).isNotNull(); 1509 assertThat(activities).hasSize(1); 1510 assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo("System App"); 1511 } 1512 1513 @Test queryIntentActivities_EmptyResultWithNoMatchingImplicitIntents()1514 public void queryIntentActivities_EmptyResultWithNoMatchingImplicitIntents() { 1515 Intent i = new Intent(Intent.ACTION_MAIN, null); 1516 i.addCategory(Intent.CATEGORY_LAUNCHER); 1517 i.setDataAndType(Uri.parse("content://testhost1.com:1/testPath/test.jpeg"), "image/jpeg"); 1518 1519 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1520 assertThat(activities).isEmpty(); 1521 } 1522 1523 @Test queryIntentActivities_MatchWithExplicitIntent()1524 public void queryIntentActivities_MatchWithExplicitIntent() { 1525 Intent i = new Intent(); 1526 i.setClassName(context, "org.robolectric.shadows.TestActivity"); 1527 1528 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1529 assertThat(activities).isNotNull(); 1530 assertThat(activities).hasSize(1); 1531 assertThat(activities.get(0).resolvePackageName).isEqualTo("org.robolectric"); 1532 assertThat(activities.get(0).activityInfo.name) 1533 .isEqualTo("org.robolectric.shadows.TestActivity"); 1534 } 1535 1536 @Test queryIntentActivities_MatchWithImplicitIntents()1537 public void queryIntentActivities_MatchWithImplicitIntents() { 1538 Uri uri = Uri.parse("content://testhost1.com:1/testPath/test.jpeg"); 1539 Intent i = new Intent(Intent.ACTION_VIEW); 1540 i.addCategory(Intent.CATEGORY_DEFAULT); 1541 i.setDataAndType(uri, "image/jpeg"); 1542 1543 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1544 assertThat(activities).isNotNull(); 1545 assertThat(activities).hasSize(1); 1546 assertThat(activities.get(0).resolvePackageName).isEqualTo("org.robolectric"); 1547 assertThat(activities.get(0).activityInfo.name) 1548 .isEqualTo("org.robolectric.shadows.TestActivity"); 1549 } 1550 1551 @Test queryIntentActivities_MatchWithAliasIntents()1552 public void queryIntentActivities_MatchWithAliasIntents() { 1553 Intent i = new Intent(Intent.ACTION_MAIN); 1554 i.addCategory(Intent.CATEGORY_LAUNCHER); 1555 1556 List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0); 1557 assertThat(activities).isNotNull(); 1558 assertThat(activities).hasSize(1); 1559 assertThat(activities.get(0).resolvePackageName).isEqualTo("org.robolectric"); 1560 assertThat(activities.get(0).activityInfo.targetActivity) 1561 .isEqualTo("org.robolectric.shadows.TestActivity"); 1562 assertThat(activities.get(0).activityInfo.name) 1563 .isEqualTo("org.robolectric.shadows.TestActivityAlias"); 1564 } 1565 1566 @Test queryIntentActivities_DisabledComponentExplicitIntent()1567 public void queryIntentActivities_DisabledComponentExplicitIntent() { 1568 Intent i = new Intent(); 1569 i.setClassName(context, "org.robolectric.shadows.DisabledActivity"); 1570 1571 List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, 0); 1572 assertThat(resolveInfos).isEmpty(); 1573 } 1574 1575 @Test queryIntentActivities_MatchDisabledComponents()1576 public void queryIntentActivities_MatchDisabledComponents() { 1577 Intent i = new Intent(); 1578 i.setClassName(context, "org.robolectric.shadows.DisabledActivity"); 1579 1580 List<ResolveInfo> resolveInfos = 1581 packageManager.queryIntentActivities(i, PackageManager.MATCH_DISABLED_COMPONENTS); 1582 assertThat(resolveInfos).isNotNull(); 1583 assertThat(resolveInfos).hasSize(1); 1584 assertThat(resolveInfos.get(0).activityInfo.enabled).isFalse(); 1585 } 1586 1587 @Test queryIntentActivities_DisabledComponentViaPmExplicitIntent()1588 public void queryIntentActivities_DisabledComponentViaPmExplicitIntent() { 1589 Intent i = new Intent(); 1590 i.setClassName(context, "org.robolectric.shadows.TestActivity"); 1591 1592 ComponentName componentToDisable = 1593 new ComponentName(context, "org.robolectric.shadows.TestActivity"); 1594 packageManager.setComponentEnabledSetting( 1595 componentToDisable, 1596 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 1597 PackageManager.DONT_KILL_APP); 1598 1599 List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, 0); 1600 assertThat(resolveInfos).isEmpty(); 1601 } 1602 1603 @Test queryIntentActivities_DisabledComponentEnabledViaPmExplicitIntent()1604 public void queryIntentActivities_DisabledComponentEnabledViaPmExplicitIntent() { 1605 Intent i = new Intent(); 1606 i.setClassName(context, "org.robolectric.shadows.DisabledActivity"); 1607 1608 ComponentName componentToDisable = 1609 new ComponentName(context, "org.robolectric.shadows.DisabledActivity"); 1610 packageManager.setComponentEnabledSetting( 1611 componentToDisable, 1612 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 1613 PackageManager.DONT_KILL_APP); 1614 1615 List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, 0); 1616 assertThat(resolveInfos).hasSize(1); 1617 assertThat(resolveInfos.get(0).activityInfo.enabled).isFalse(); 1618 } 1619 1620 @Test queryIntentActivities_DisabledComponentViaPmImplicitIntent()1621 public void queryIntentActivities_DisabledComponentViaPmImplicitIntent() { 1622 Uri uri = Uri.parse("content://testhost1.com:1/testPath/test.jpeg"); 1623 Intent i = new Intent(Intent.ACTION_VIEW); 1624 i.addCategory(Intent.CATEGORY_DEFAULT); 1625 i.setDataAndType(uri, "image/jpeg"); 1626 1627 ComponentName componentToDisable = 1628 new ComponentName(context, "org.robolectric.shadows.TestActivity"); 1629 packageManager.setComponentEnabledSetting( 1630 componentToDisable, 1631 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 1632 PackageManager.DONT_KILL_APP); 1633 1634 List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, 0); 1635 assertThat(resolveInfos).isEmpty(); 1636 } 1637 1638 @Test queryIntentActivities_MatchDisabledViaPmComponents()1639 public void queryIntentActivities_MatchDisabledViaPmComponents() { 1640 Uri uri = Uri.parse("content://testhost1.com:1/testPath/test.jpeg"); 1641 Intent i = new Intent(Intent.ACTION_VIEW); 1642 i.addCategory(Intent.CATEGORY_DEFAULT); 1643 i.setDataAndType(uri, "image/jpeg"); 1644 1645 ComponentName componentToDisable = 1646 new ComponentName(context, "org.robolectric.shadows.TestActivity"); 1647 packageManager.setComponentEnabledSetting( 1648 componentToDisable, 1649 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 1650 PackageManager.DONT_KILL_APP); 1651 1652 List<ResolveInfo> resolveInfos = 1653 packageManager.queryIntentActivities(i, PackageManager.MATCH_DISABLED_COMPONENTS); 1654 assertThat(resolveInfos).isNotNull(); 1655 assertThat(resolveInfos).hasSize(1); 1656 assertThat(resolveInfos.get(0).activityInfo.enabled).isTrue(); 1657 } 1658 1659 @Test queryIntentActivities_appHidden_includeUninstalled()1660 public void queryIntentActivities_appHidden_includeUninstalled() { 1661 String packageName = context.getPackageName(); 1662 packageManager.setApplicationHiddenSettingAsUser( 1663 packageName, /* hidden= */ true, /* user= */ null); 1664 1665 Intent i = new Intent(); 1666 i.setClassName(context, "org.robolectric.shadows.TestActivity"); 1667 1668 List<ResolveInfo> activities = 1669 packageManager.queryIntentActivities(i, MATCH_UNINSTALLED_PACKAGES); 1670 assertThat(activities).hasSize(1); 1671 assertThat(activities.get(0).resolvePackageName).isEqualTo(packageName); 1672 assertThat(activities.get(0).activityInfo.name) 1673 .isEqualTo("org.robolectric.shadows.TestActivity"); 1674 } 1675 1676 @Test queryIntentActivities_appHidden_dontIncludeUninstalled()1677 public void queryIntentActivities_appHidden_dontIncludeUninstalled() { 1678 String packageName = context.getPackageName(); 1679 packageManager.setApplicationHiddenSettingAsUser( 1680 packageName, /* hidden= */ true, /* user= */ null); 1681 1682 Intent i = new Intent(); 1683 i.setClassName(context, "org.robolectric.shadows.TestActivity"); 1684 1685 assertThat(packageManager.queryIntentActivities(i, /* flags= */ 0)).isEmpty(); 1686 } 1687 1688 @Test resolveActivity_Match()1689 public void resolveActivity_Match() { 1690 Intent i = new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER); 1691 ResolveInfo info = new ResolveInfo(); 1692 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1693 info.activityInfo = new ActivityInfo(); 1694 info.activityInfo.name = "name"; 1695 info.activityInfo.packageName = TEST_PACKAGE_NAME; 1696 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1697 1698 assertThat(packageManager.resolveActivity(i, 0)).isNotNull(); 1699 assertThat(packageManager.resolveActivity(i, 0).activityInfo.name).isEqualTo("name"); 1700 assertThat(packageManager.resolveActivity(i, 0).activityInfo.packageName) 1701 .isEqualTo(TEST_PACKAGE_NAME); 1702 } 1703 1704 @Test addIntentFilterForComponent()1705 public void addIntentFilterForComponent() throws Exception { 1706 ComponentName testComponent = new ComponentName("package", "name"); 1707 IntentFilter intentFilter = new IntentFilter("ACTION"); 1708 intentFilter.addCategory(Intent.CATEGORY_DEFAULT); 1709 intentFilter.addCategory(Intent.CATEGORY_APP_CALENDAR); 1710 1711 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1712 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1713 Intent intent = new Intent(); 1714 1715 intent.setAction("ACTION"); 1716 assertThat(intent.resolveActivity(packageManager)).isEqualTo(testComponent); 1717 1718 intent.setPackage("package"); 1719 assertThat(intent.resolveActivity(packageManager)).isEqualTo(testComponent); 1720 1721 intent.addCategory(Intent.CATEGORY_APP_CALENDAR); 1722 assertThat(intent.resolveActivity(packageManager)).isEqualTo(testComponent); 1723 1724 intent.putExtra("key", "value"); 1725 assertThat(intent.resolveActivity(packageManager)).isEqualTo(testComponent); 1726 1727 intent.setData(Uri.parse("content://boo")); // data matches only if it is in the filter 1728 assertThat(intent.resolveActivity(packageManager)).isNull(); 1729 1730 intent.setData(null).setAction("BOO"); // different action 1731 assertThat(intent.resolveActivity(packageManager)).isNull(); 1732 } 1733 1734 @Test resolveActivity_NoMatch()1735 public void resolveActivity_NoMatch() { 1736 Intent i = new Intent(); 1737 i.setComponent(new ComponentName("foo.bar", "No Activity")); 1738 assertThat(packageManager.resolveActivity(i, 0)).isNull(); 1739 } 1740 1741 @Test resolveActivityAsUser_Match()1742 public void resolveActivityAsUser_Match() { 1743 Intent i = new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER); 1744 ResolveInfo info = new ResolveInfo(); 1745 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1746 info.activityInfo = new ActivityInfo(); 1747 info.activityInfo.name = "name"; 1748 info.activityInfo.packageName = TEST_PACKAGE_NAME; 1749 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1750 1751 ResolveInfo resolvedActivity = 1752 ReflectionHelpers.callInstanceMethod( 1753 packageManager, 1754 "resolveActivityAsUser", 1755 ClassParameter.from(Intent.class, i), 1756 ClassParameter.from(int.class, 0), 1757 ClassParameter.from(int.class, USER_ID)); 1758 1759 assertThat(resolvedActivity).isNotNull(); 1760 assertThat(resolvedActivity.activityInfo.name).isEqualTo("name"); 1761 assertThat(resolvedActivity.activityInfo.packageName).isEqualTo(TEST_PACKAGE_NAME); 1762 } 1763 1764 @Test resolveActivityAsUser_NoMatch()1765 public void resolveActivityAsUser_NoMatch() { 1766 Intent i = new Intent(); 1767 i.setComponent(new ComponentName("foo.bar", "No Activity")); 1768 1769 ResolveInfo resolvedActivity = 1770 ReflectionHelpers.callInstanceMethod( 1771 packageManager, 1772 "resolveActivityAsUser", 1773 ClassParameter.from(Intent.class, i), 1774 ClassParameter.from(int.class, 0), 1775 ClassParameter.from(int.class, USER_ID)); 1776 1777 assertThat(resolvedActivity).isNull(); 1778 } 1779 1780 @Test resolveExplicitIntent_sameApp()1781 public void resolveExplicitIntent_sameApp() throws Exception { 1782 ComponentName testComponent = new ComponentName(RuntimeEnvironment.getApplication(), "name"); 1783 IntentFilter intentFilter = new IntentFilter("ACTION"); 1784 1785 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1786 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1787 Intent intent = new Intent().setComponent(testComponent); 1788 ResolveInfo resolveInfo = packageManager.resolveActivity(intent, 0); 1789 assertThat(resolveInfo).isNotNull(); 1790 assertThat(resolveInfo.activityInfo.name).isEqualTo("name"); 1791 } 1792 1793 @Test 1794 @Config(minSdk = TIRAMISU) resolveExplicitIntent_filterMatch()1795 public void resolveExplicitIntent_filterMatch() throws Exception { 1796 ComponentName testComponent = new ComponentName("some.other.package", "name"); 1797 IntentFilter intentFilter = new IntentFilter("ACTION"); 1798 1799 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1800 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1801 Intent intent = new Intent("ACTION").setComponent(testComponent); 1802 ResolveInfo resolveInfo = packageManager.resolveActivity(intent, ResolveInfoFlags.of(0)); 1803 assertThat(resolveInfo).isNotNull(); 1804 assertThat(resolveInfo.activityInfo.name).isEqualTo("name"); 1805 assertThat(resolveInfo.activityInfo.packageName).isEqualTo("some.other.package"); 1806 } 1807 1808 @Test 1809 @Config(minSdk = TIRAMISU) resolveExplicitIntent_noFilterMatch()1810 public void resolveExplicitIntent_noFilterMatch() throws Exception { 1811 ComponentName testComponent = new ComponentName("some.other.package", "name"); 1812 IntentFilter intentFilter = new IntentFilter("ACTION"); 1813 1814 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1815 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1816 Intent intent = new Intent("OTHER_ACTION").setComponent(testComponent); 1817 assertThat(packageManager.resolveActivity(intent, ResolveInfoFlags.of(0))).isNull(); 1818 } 1819 1820 @Test 1821 @Config(maxSdk = S) resolveExplicitIntent_noFilterMatch_belowT()1822 public void resolveExplicitIntent_noFilterMatch_belowT() throws Exception { 1823 ComponentName testComponent = new ComponentName("some.other.package", "name"); 1824 IntentFilter intentFilter = new IntentFilter("ACTION"); 1825 1826 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1827 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1828 Intent intent = new Intent("OTHER_ACTION").setComponent(testComponent); 1829 assertThat(packageManager.resolveActivity(intent, 0)).isNotNull(); 1830 } 1831 1832 @Test 1833 @Config(minSdk = TIRAMISU) resolveExplicitIntent_noFilterMatch_targetBelowT()1834 public void resolveExplicitIntent_noFilterMatch_targetBelowT() throws Exception { 1835 PackageInfo testPackage = 1836 PackageInfoBuilder.newBuilder().setPackageName("some.other.package").build(); 1837 testPackage.applicationInfo.targetSdkVersion = S; 1838 ComponentName testComponent = new ComponentName("some.other.package", "name"); 1839 IntentFilter intentFilter = new IntentFilter("ACTION"); 1840 1841 shadowOf(packageManager).installPackage(testPackage); 1842 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1843 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1844 Intent intent = new Intent("OTHER_ACTION").setComponent(testComponent); 1845 assertThat(packageManager.resolveActivity(intent, ResolveInfoFlags.of(0))).isNotNull(); 1846 } 1847 1848 @Test 1849 @Config(minSdk = TIRAMISU) resolveExplicitIntent_noAction()1850 public void resolveExplicitIntent_noAction() throws Exception { 1851 ComponentName testComponent = new ComponentName("some.other.package", "name"); 1852 IntentFilter intentFilter = new IntentFilter("ACTION"); 1853 1854 shadowOf(packageManager).addActivityIfNotPresent(testComponent); 1855 shadowOf(packageManager).addIntentFilterForActivity(testComponent, intentFilter); 1856 Intent intent = new Intent().setComponent(testComponent); 1857 ResolveInfo resolveInfo = packageManager.resolveActivity(intent, ResolveInfoFlags.of(0)); 1858 assertThat(resolveInfo).isNotNull(); 1859 assertThat(resolveInfo.activityInfo.name).isEqualTo("name"); 1860 } 1861 1862 @Test queryIntentServices_EmptyResult()1863 public void queryIntentServices_EmptyResult() { 1864 Intent i = new Intent(Intent.ACTION_MAIN, null); 1865 i.addCategory(Intent.CATEGORY_LAUNCHER); 1866 1867 List<ResolveInfo> activities = packageManager.queryIntentServices(i, 0); 1868 assertThat(activities).isEmpty(); 1869 } 1870 1871 @Test queryIntentServices_MatchWithExplicitIntent()1872 public void queryIntentServices_MatchWithExplicitIntent() { 1873 Intent i = new Intent(); 1874 i.setClassName(context, "com.foo.Service"); 1875 1876 List<ResolveInfo> services = packageManager.queryIntentServices(i, 0); 1877 assertThat(services).isNotNull(); 1878 assertThat(services).hasSize(1); 1879 assertThat(services.get(0).resolvePackageName).isEqualTo("org.robolectric"); 1880 assertThat(services.get(0).serviceInfo.name).isEqualTo("com.foo.Service"); 1881 } 1882 1883 @Test queryIntentServices_Match()1884 public void queryIntentServices_Match() { 1885 Intent i = new Intent(Intent.ACTION_MAIN, null); 1886 1887 ResolveInfo info = new ResolveInfo(); 1888 info.serviceInfo = new ServiceInfo(); 1889 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1890 1891 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1892 1893 List<ResolveInfo> services = packageManager.queryIntentServices(i, 0); 1894 assertThat(services).hasSize(1); 1895 assertThat(services.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL); 1896 } 1897 1898 @Test 1899 @Config(minSdk = TIRAMISU) queryIntentServices_Match_withResolveInfoFlags()1900 public void queryIntentServices_Match_withResolveInfoFlags() { 1901 Intent i = new Intent(Intent.ACTION_MAIN, null); 1902 1903 ResolveInfo info = new ResolveInfo(); 1904 info.serviceInfo = new ServiceInfo(); 1905 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1906 1907 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1908 1909 List<ResolveInfo> services = packageManager.queryIntentServices(i, ResolveInfoFlags.of(0)); 1910 assertThat(services).hasSize(1); 1911 assertThat(services.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL); 1912 } 1913 1914 @Test queryIntentServices_fromManifest()1915 public void queryIntentServices_fromManifest() { 1916 Intent i = new Intent("org.robolectric.ACTION_DIFFERENT_PACKAGE"); 1917 i.addCategory(Intent.CATEGORY_LAUNCHER); 1918 i.setType("image/jpeg"); 1919 List<ResolveInfo> services = packageManager.queryIntentServices(i, 0); 1920 assertThat(services).isNotEmpty(); 1921 } 1922 1923 @Test queryIntentServices_appHidden_includeUninstalled()1924 public void queryIntentServices_appHidden_includeUninstalled() { 1925 String packageName = context.getPackageName(); 1926 packageManager.setApplicationHiddenSettingAsUser( 1927 packageName, /* hidden= */ true, /* user= */ null); 1928 1929 Intent i = new Intent(); 1930 i.setClassName(context, "com.foo.Service"); 1931 1932 List<ResolveInfo> services = packageManager.queryIntentServices(i, MATCH_UNINSTALLED_PACKAGES); 1933 assertThat(services).hasSize(1); 1934 assertThat(services.get(0).resolvePackageName).isEqualTo(packageName); 1935 assertThat(services.get(0).serviceInfo.name).isEqualTo("com.foo.Service"); 1936 } 1937 1938 @Test queryIntentServices_appHidden_dontIncludeUninstalled()1939 public void queryIntentServices_appHidden_dontIncludeUninstalled() { 1940 String packageName = context.getPackageName(); 1941 packageManager.setApplicationHiddenSettingAsUser( 1942 packageName, /* hidden= */ true, /* user= */ null); 1943 1944 Intent i = new Intent(); 1945 i.setClassName(context, "com.foo.Service"); 1946 1947 assertThat(packageManager.queryIntentServices(i, /* flags= */ 0)).isEmpty(); 1948 } 1949 1950 @Test queryIntentServicesAsUser()1951 public void queryIntentServicesAsUser() { 1952 Intent i = new Intent("org.robolectric.ACTION_DIFFERENT_PACKAGE"); 1953 i.addCategory(Intent.CATEGORY_LAUNCHER); 1954 i.setType("image/jpeg"); 1955 List<ResolveInfo> services = packageManager.queryIntentServicesAsUser(i, 0, 0); 1956 assertThat(services).isNotEmpty(); 1957 } 1958 1959 @Test queryBroadcastReceivers_EmptyResult()1960 public void queryBroadcastReceivers_EmptyResult() { 1961 Intent i = new Intent(Intent.ACTION_MAIN, null); 1962 i.addCategory(Intent.CATEGORY_LAUNCHER); 1963 1964 List<ResolveInfo> broadCastReceivers = packageManager.queryBroadcastReceivers(i, 0); 1965 assertThat(broadCastReceivers).isEmpty(); 1966 } 1967 1968 @Test queryBroadcastReceivers_Match()1969 public void queryBroadcastReceivers_Match() { 1970 Intent i = new Intent(Intent.ACTION_MAIN, null); 1971 1972 ResolveInfo info = new ResolveInfo(); 1973 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 1974 1975 shadowOf(packageManager).addResolveInfoForIntent(i, info); 1976 1977 List<ResolveInfo> broadCastReceivers = packageManager.queryBroadcastReceivers(i, 0); 1978 assertThat(broadCastReceivers).hasSize(1); 1979 assertThat(broadCastReceivers.get(0).nonLocalizedLabel.toString()) 1980 .isEqualTo(TEST_PACKAGE_LABEL); 1981 } 1982 1983 @Test queryBroadcastReceivers_MatchWithExplicitIntent()1984 public void queryBroadcastReceivers_MatchWithExplicitIntent() { 1985 Intent i = new Intent(); 1986 i.setClassName(context, "org.robolectric.fakes.ConfigTestReceiver"); 1987 1988 List<ResolveInfo> receivers = packageManager.queryBroadcastReceivers(i, 0); 1989 assertThat(receivers).isNotNull(); 1990 assertThat(receivers).hasSize(1); 1991 assertThat(receivers.get(0).resolvePackageName).isEqualTo("org.robolectric"); 1992 assertThat(receivers.get(0).activityInfo.name) 1993 .isEqualTo("org.robolectric.fakes.ConfigTestReceiver"); 1994 } 1995 1996 @Test queryBroadcastReceivers_appHidden_includeUninstalled()1997 public void queryBroadcastReceivers_appHidden_includeUninstalled() { 1998 String packageName = context.getPackageName(); 1999 packageManager.setApplicationHiddenSettingAsUser( 2000 packageName, /* hidden= */ true, /* user= */ null); 2001 2002 Intent i = new Intent(); 2003 i.setClassName(context, "org.robolectric.fakes.ConfigTestReceiver"); 2004 2005 List<ResolveInfo> activities = 2006 packageManager.queryBroadcastReceivers(i, MATCH_UNINSTALLED_PACKAGES); 2007 assertThat(activities).hasSize(1); 2008 assertThat(activities.get(0).resolvePackageName).isEqualTo(packageName); 2009 assertThat(activities.get(0).activityInfo.name) 2010 .isEqualTo("org.robolectric.fakes.ConfigTestReceiver"); 2011 } 2012 2013 @Test queryBroadcastReceivers_appHidden_dontIncludeUninstalled()2014 public void queryBroadcastReceivers_appHidden_dontIncludeUninstalled() { 2015 String packageName = context.getPackageName(); 2016 packageManager.setApplicationHiddenSettingAsUser( 2017 packageName, /* hidden= */ true, /* user= */ null); 2018 2019 Intent i = new Intent(); 2020 i.setClassName(context, "org.robolectric.fakes.ConfigTestReceiver"); 2021 2022 assertThat(packageManager.queryBroadcastReceivers(i, /* flags= */ 0)).isEmpty(); 2023 } 2024 2025 @Test queryIntentContentProviders_EmptyResult()2026 public void queryIntentContentProviders_EmptyResult() { 2027 Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE); 2028 2029 List<ResolveInfo> broadCastReceivers = packageManager.queryIntentContentProviders(i, 0); 2030 assertThat(broadCastReceivers).isEmpty(); 2031 } 2032 2033 @Test queryIntentContentProviders_Match()2034 public void queryIntentContentProviders_Match() { 2035 Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE); 2036 2037 ResolveInfo resolveInfo = new ResolveInfo(); 2038 ProviderInfo providerInfo = new ProviderInfo(); 2039 providerInfo.authority = "com.robolectric"; 2040 resolveInfo.providerInfo = providerInfo; 2041 2042 shadowOf(packageManager).addResolveInfoForIntent(i, resolveInfo); 2043 2044 List<ResolveInfo> contentProviders = packageManager.queryIntentContentProviders(i, 0); 2045 assertThat(contentProviders).hasSize(1); 2046 assertThat(contentProviders.get(0).providerInfo.authority).isEqualTo(providerInfo.authority); 2047 } 2048 2049 @Test queryIntentContentProviders_MatchSystemOnly()2050 public void queryIntentContentProviders_MatchSystemOnly() { 2051 Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE); 2052 2053 ResolveInfo info1 = new ResolveInfo(); 2054 info1.providerInfo = new ProviderInfo(); 2055 info1.providerInfo.applicationInfo = new ApplicationInfo(); 2056 2057 ResolveInfo info2 = new ResolveInfo(); 2058 info2.providerInfo = new ProviderInfo(); 2059 info2.providerInfo.applicationInfo = new ApplicationInfo(); 2060 info2.providerInfo.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 2061 info2.nonLocalizedLabel = "System App"; 2062 2063 shadowOf(packageManager).addResolveInfoForIntent(i, info1); 2064 shadowOf(packageManager).addResolveInfoForIntent(i, info2); 2065 2066 List<ResolveInfo> activities = 2067 packageManager.queryIntentContentProviders(i, PackageManager.MATCH_SYSTEM_ONLY); 2068 assertThat(activities).isNotNull(); 2069 assertThat(activities).hasSize(1); 2070 assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo("System App"); 2071 } 2072 2073 @Test queryIntentContentProviders_MatchDisabledComponents()2074 public void queryIntentContentProviders_MatchDisabledComponents() { 2075 Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE); 2076 2077 ResolveInfo resolveInfo = new ResolveInfo(); 2078 resolveInfo.providerInfo = new ProviderInfo(); 2079 resolveInfo.providerInfo.applicationInfo = new ApplicationInfo(); 2080 resolveInfo.providerInfo.applicationInfo.packageName = 2081 "org.robolectric.shadows.TestPackageName"; 2082 resolveInfo.providerInfo.name = "org.robolectric.shadows.TestProvider"; 2083 resolveInfo.providerInfo.enabled = false; 2084 2085 shadowOf(packageManager).addResolveInfoForIntent(i, resolveInfo); 2086 2087 List<ResolveInfo> resolveInfos = packageManager.queryIntentContentProviders(i, 0); 2088 assertThat(resolveInfos).isEmpty(); 2089 2090 resolveInfos = 2091 packageManager.queryIntentContentProviders(i, PackageManager.MATCH_DISABLED_COMPONENTS); 2092 assertThat(resolveInfos).isNotNull(); 2093 assertThat(resolveInfos).hasSize(1); 2094 } 2095 2096 @Test queryIntentContentProviders_appHidden_includeUninstalled()2097 public void queryIntentContentProviders_appHidden_includeUninstalled() { 2098 String packageName = context.getPackageName(); 2099 packageManager.setApplicationHiddenSettingAsUser( 2100 packageName, /* hidden= */ true, /* user= */ null); 2101 2102 Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE); 2103 i.setClassName(context, "org.robolectric.shadows.testing.TestContentProvider1"); 2104 2105 List<ResolveInfo> resolveInfos = packageManager.queryIntentContentProviders(i, 0); 2106 assertThat(resolveInfos).isEmpty(); 2107 2108 resolveInfos = packageManager.queryIntentContentProviders(i, MATCH_UNINSTALLED_PACKAGES); 2109 2110 assertThat(resolveInfos).hasSize(1); 2111 assertThat(resolveInfos.get(0).providerInfo.applicationInfo.packageName).isEqualTo(packageName); 2112 assertThat(resolveInfos.get(0).providerInfo.name) 2113 .isEqualTo("org.robolectric.shadows.testing.TestContentProvider1"); 2114 } 2115 2116 @Test resolveService_Match()2117 public void resolveService_Match() { 2118 Intent i = new Intent(Intent.ACTION_MAIN, null); 2119 ResolveInfo info = new ResolveInfo(); 2120 info.serviceInfo = new ServiceInfo(); 2121 info.serviceInfo.name = "name"; 2122 shadowOf(packageManager).addResolveInfoForIntent(i, info); 2123 assertThat(packageManager.resolveService(i, 0)).isNotNull(); 2124 assertThat(packageManager.resolveService(i, 0).serviceInfo.name).isEqualTo("name"); 2125 } 2126 2127 @Test removeResolveInfosForIntent_shouldCauseResolveActivityToReturnNull()2128 public void removeResolveInfosForIntent_shouldCauseResolveActivityToReturnNull() { 2129 Intent intent = 2130 new Intent(Intent.ACTION_APP_ERROR, null).addCategory(Intent.CATEGORY_APP_BROWSER); 2131 ResolveInfo info = new ResolveInfo(); 2132 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 2133 info.activityInfo = new ActivityInfo(); 2134 info.activityInfo.packageName = "com.org"; 2135 shadowOf(packageManager).addResolveInfoForIntent(intent, info); 2136 2137 shadowOf(packageManager).removeResolveInfosForIntent(intent, "com.org"); 2138 2139 assertThat(packageManager.resolveActivity(intent, 0)).isNull(); 2140 } 2141 2142 @Test removeResolveInfosForIntent_forService()2143 public void removeResolveInfosForIntent_forService() { 2144 Intent intent = 2145 new Intent(Intent.ACTION_APP_ERROR, null).addCategory(Intent.CATEGORY_APP_BROWSER); 2146 ResolveInfo info = new ResolveInfo(); 2147 info.nonLocalizedLabel = TEST_PACKAGE_LABEL; 2148 info.serviceInfo = new ServiceInfo(); 2149 info.serviceInfo.packageName = "com.org"; 2150 shadowOf(packageManager).addResolveInfoForIntent(intent, info); 2151 2152 shadowOf(packageManager).removeResolveInfosForIntent(intent, "com.org"); 2153 2154 assertThat(packageManager.resolveService(intent, 0)).isNull(); 2155 } 2156 2157 @Test resolveService_NoMatch()2158 public void resolveService_NoMatch() { 2159 Intent i = new Intent(); 2160 i.setComponent(new ComponentName("foo.bar", "No Activity")); 2161 assertThat(packageManager.resolveService(i, 0)).isNull(); 2162 } 2163 2164 @Test queryActivityIcons_Match()2165 public void queryActivityIcons_Match() throws Exception { 2166 Intent i = new Intent(); 2167 i.setComponent(new ComponentName(TEST_PACKAGE_NAME, "")); 2168 Drawable d = new BitmapDrawable(); 2169 2170 shadowOf(packageManager).addActivityIcon(i, d); 2171 2172 assertThat(packageManager.getActivityIcon(i)).isSameInstanceAs(d); 2173 assertThat(packageManager.getActivityIcon(i.getComponent())).isSameInstanceAs(d); 2174 } 2175 2176 @Test getApplicationIcon_componentName_matches()2177 public void getApplicationIcon_componentName_matches() throws Exception { 2178 Intent i = new Intent(); 2179 i.setComponent(new ComponentName(TEST_PACKAGE_NAME, "")); 2180 Drawable d = new BitmapDrawable(); 2181 2182 shadowOf(packageManager).setApplicationIcon(TEST_PACKAGE_NAME, d); 2183 2184 assertThat(packageManager.getApplicationIcon(TEST_PACKAGE_NAME)).isSameInstanceAs(d); 2185 } 2186 2187 @Test getApplicationIcon_applicationInfo_matches()2188 public void getApplicationIcon_applicationInfo_matches() { 2189 Intent i = new Intent(); 2190 i.setComponent(new ComponentName(TEST_PACKAGE_NAME, "")); 2191 Drawable d = new BitmapDrawable(); 2192 2193 shadowOf(packageManager).setApplicationIcon(TEST_PACKAGE_NAME, d); 2194 2195 ApplicationInfo applicationInfo = new ApplicationInfo(); 2196 applicationInfo.packageName = TEST_PACKAGE_NAME; 2197 2198 assertThat(packageManager.getApplicationIcon(applicationInfo)).isSameInstanceAs(d); 2199 } 2200 2201 @Test hasSystemFeature()2202 public void hasSystemFeature() { 2203 // uninitialized 2204 assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isFalse(); 2205 2206 // positive 2207 shadowOf(packageManager).setSystemFeature(PackageManager.FEATURE_CAMERA, true); 2208 assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isTrue(); 2209 2210 // negative 2211 shadowOf(packageManager).setSystemFeature(PackageManager.FEATURE_CAMERA, false); 2212 assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isFalse(); 2213 } 2214 2215 @Test addSystemSharedLibraryName()2216 public void addSystemSharedLibraryName() { 2217 shadowOf(packageManager).addSystemSharedLibraryName("com.foo.system_library_1"); 2218 shadowOf(packageManager).addSystemSharedLibraryName("com.foo.system_library_2"); 2219 2220 assertThat(packageManager.getSystemSharedLibraryNames()) 2221 .asList() 2222 .containsExactly("com.foo.system_library_1", "com.foo.system_library_2"); 2223 } 2224 2225 @Test clearSystemSharedLibraryName()2226 public void clearSystemSharedLibraryName() { 2227 shadowOf(packageManager).addSystemSharedLibraryName("com.foo.system_library_1"); 2228 shadowOf(packageManager).clearSystemSharedLibraryNames(); 2229 2230 assertThat(packageManager.getSystemSharedLibraryNames()).isEmpty(); 2231 } 2232 2233 @Test getPackageInfo_shouldReturnActivityInfos()2234 public void getPackageInfo_shouldReturnActivityInfos() throws Exception { 2235 PackageInfo packageInfo = 2236 packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); 2237 ActivityInfo activityInfoWithFilters = 2238 findActivity(packageInfo.activities, ActivityWithFilters.class.getName()); 2239 assertThat(activityInfoWithFilters.packageName).isEqualTo("org.robolectric"); 2240 assertThat(activityInfoWithFilters.exported).isEqualTo(true); 2241 assertThat(activityInfoWithFilters.permission).isEqualTo("com.foo.MY_PERMISSION"); 2242 } 2243 findActivity(ActivityInfo[] activities, String name)2244 private static ActivityInfo findActivity(ActivityInfo[] activities, String name) { 2245 for (ActivityInfo activityInfo : activities) { 2246 if (activityInfo.name.equals(name)) { 2247 return activityInfo; 2248 } 2249 } 2250 return null; 2251 } 2252 2253 @Test getPackageInfo_getProvidersShouldReturnProviderInfos()2254 public void getPackageInfo_getProvidersShouldReturnProviderInfos() throws Exception { 2255 PackageInfo packageInfo = 2256 packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS); 2257 ProviderInfo[] providers = packageInfo.providers; 2258 assertThat(providers).isNotEmpty(); 2259 assertThat(providers.length).isEqualTo(3); 2260 assertThat(providers[0].packageName).isEqualTo("org.robolectric"); 2261 assertThat(providers[1].packageName).isEqualTo("org.robolectric"); 2262 assertThat(providers[2].packageName).isEqualTo("org.robolectric"); 2263 } 2264 2265 @Test getProviderInfo_shouldReturnProviderInfos()2266 public void getProviderInfo_shouldReturnProviderInfos() throws Exception { 2267 ProviderInfo providerInfo1 = 2268 packageManager.getProviderInfo( 2269 new ComponentName(context, "org.robolectric.shadows.testing.TestContentProvider1"), 0); 2270 assertThat(providerInfo1.packageName).isEqualTo("org.robolectric"); 2271 assertThat(providerInfo1.authority).isEqualTo("org.robolectric.authority1"); 2272 2273 ProviderInfo providerInfo2 = 2274 packageManager.getProviderInfo( 2275 new ComponentName(context, "org.robolectric.shadows.testing.TestContentProvider2"), 0); 2276 assertThat(providerInfo2.packageName).isEqualTo("org.robolectric"); 2277 assertThat(providerInfo2.authority).isEqualTo("org.robolectric.authority2"); 2278 } 2279 2280 @Test getProviderInfo_packageNotFoundShouldThrowException()2281 public void getProviderInfo_packageNotFoundShouldThrowException() { 2282 try { 2283 packageManager.getProviderInfo( 2284 new ComponentName("non.existent.package", ".tester.DoesntExist"), 0); 2285 fail("should have thrown NameNotFoundException"); 2286 } catch (NameNotFoundException e) { 2287 // expected 2288 } 2289 } 2290 2291 @Test getProviderInfo_shouldPopulatePermissionsInProviderInfos()2292 public void getProviderInfo_shouldPopulatePermissionsInProviderInfos() throws Exception { 2293 ProviderInfo providerInfo = 2294 packageManager.getProviderInfo( 2295 new ComponentName(context, "org.robolectric.shadows.testing.TestContentProvider1"), 0); 2296 assertThat(providerInfo.authority).isEqualTo("org.robolectric.authority1"); 2297 2298 assertThat(providerInfo.readPermission).isEqualTo("READ_PERMISSION"); 2299 assertThat(providerInfo.writePermission).isEqualTo("WRITE_PERMISSION"); 2300 2301 assertThat(providerInfo.pathPermissions).asList().hasSize(1); 2302 assertThat(providerInfo.pathPermissions[0].getType()) 2303 .isEqualTo(PathPermission.PATTERN_SIMPLE_GLOB); 2304 assertThat(providerInfo.pathPermissions[0].getPath()).isEqualTo("/path/*"); 2305 assertThat(providerInfo.pathPermissions[0].getReadPermission()) 2306 .isEqualTo("PATH_READ_PERMISSION"); 2307 assertThat(providerInfo.pathPermissions[0].getWritePermission()) 2308 .isEqualTo("PATH_WRITE_PERMISSION"); 2309 } 2310 2311 @Test getProviderInfo_shouldMetaDataInProviderInfos()2312 public void getProviderInfo_shouldMetaDataInProviderInfos() throws Exception { 2313 ProviderInfo providerInfo = 2314 packageManager.getProviderInfo( 2315 new ComponentName(context, "org.robolectric.shadows.testing.TestContentProvider1"), 2316 PackageManager.GET_META_DATA); 2317 assertThat(providerInfo.authority).isEqualTo("org.robolectric.authority1"); 2318 2319 assertThat(providerInfo.metaData.getString("greeting")).isEqualTo("Hello"); 2320 } 2321 2322 @Test resolveContentProvider_shouldResolveByPackageName()2323 public void resolveContentProvider_shouldResolveByPackageName() { 2324 ProviderInfo providerInfo = 2325 packageManager.resolveContentProvider("org.robolectric.authority1", 0); 2326 assertThat(providerInfo.packageName).isEqualTo("org.robolectric"); 2327 assertThat(providerInfo.authority).isEqualTo("org.robolectric.authority1"); 2328 } 2329 2330 @Test resolveContentProvider_multiAuthorities()2331 public void resolveContentProvider_multiAuthorities() { 2332 ProviderInfo providerInfo = 2333 packageManager.resolveContentProvider("org.robolectric.authority3", 0); 2334 assertThat(providerInfo.packageName).isEqualTo("org.robolectric"); 2335 assertThat(providerInfo.authority) 2336 .isEqualTo("org.robolectric.authority3;org.robolectric.authority4"); 2337 } 2338 2339 @Test testReceiverInfo()2340 public void testReceiverInfo() throws Exception { 2341 ActivityInfo info = 2342 packageManager.getReceiverInfo( 2343 new ComponentName(context, "org.robolectric.test.ConfigTestReceiver"), 2344 PackageManager.GET_META_DATA); 2345 assertThat(info.metaData.getInt("numberOfSheep")).isEqualTo(42); 2346 } 2347 2348 @Test 2349 @Config(minSdk = TIRAMISU) testReceiverInfo_withComponentInfoFlags()2350 public void testReceiverInfo_withComponentInfoFlags() throws Exception { 2351 ActivityInfo info = 2352 packageManager.getReceiverInfo( 2353 new ComponentName(context, "org.robolectric.test.ConfigTestReceiver"), 2354 PackageManager.ComponentInfoFlags.of(PackageManager.GET_META_DATA)); 2355 assertThat(info.metaData.getInt("numberOfSheep")).isEqualTo(42); 2356 } 2357 2358 @Test testGetPackageInfo_ForReceiversIncorrectPackage()2359 public void testGetPackageInfo_ForReceiversIncorrectPackage() { 2360 try { 2361 packageManager.getPackageInfo("unknown_package", PackageManager.GET_RECEIVERS); 2362 fail("should have thrown NameNotFoundException"); 2363 } catch (PackageManager.NameNotFoundException e) { 2364 assertThat(e.getMessage()).contains("unknown_package"); 2365 } 2366 } 2367 2368 @Test 2369 @Config(maxSdk = O) getPackageInfo_shouldPopulateSignatures()2370 public void getPackageInfo_shouldPopulateSignatures() throws Exception { 2371 Signature testSignature = new Signature("00000000"); 2372 PackageInfo testPackageInfo = newPackageInfo("first.package", testSignature); 2373 assertThat(testPackageInfo.signatures).isNotNull(); 2374 assertThat(testPackageInfo.signatures.length).isEqualTo(1); 2375 shadowOf(packageManager).installPackage(testPackageInfo); 2376 PackageInfo packageInfo = 2377 packageManager.getPackageInfo("first.package", PackageManager.GET_SIGNATURES); 2378 assertThat(packageInfo.signatures).isNotNull(); 2379 assertThat(packageInfo.signatures.length).isEqualTo(1); 2380 assertThat(packageInfo.signatures[0]).isEqualTo(testSignature); 2381 } 2382 2383 @Test 2384 @Config(minSdk = P) getPackageInfo_shouldPopulateSigningInfo()2385 public void getPackageInfo_shouldPopulateSigningInfo() throws Exception { 2386 Signature testSignature = new Signature("00000000"); 2387 PackageInfo testPackageInfo = newPackageInfo("first.package", testSignature); 2388 shadowOf(packageManager).installPackage(testPackageInfo); 2389 PackageInfo packageInfo = 2390 packageManager.getPackageInfo("first.package", PackageManager.GET_SIGNING_CERTIFICATES); 2391 assertThat(packageInfo.signingInfo).isNotNull(); 2392 assertThat(packageInfo.signingInfo.getApkContentsSigners()).isNotNull(); 2393 assertThat(packageInfo.signingInfo.getApkContentsSigners().length).isEqualTo(1); 2394 assertThat(packageInfo.signingInfo.getApkContentsSigners()[0]).isEqualTo(testSignature); 2395 assertThat(packageInfo.signingInfo.getSigningCertificateHistory()).isNotNull(); 2396 } 2397 2398 @Test getPackageInfo_shouldReturnRequestedPermissions()2399 public void getPackageInfo_shouldReturnRequestedPermissions() throws Exception { 2400 PackageInfo packageInfo = 2401 packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS); 2402 String[] permissions = packageInfo.requestedPermissions; 2403 assertThat(permissions).isNotNull(); 2404 assertThat(permissions.length).isEqualTo(4); 2405 } 2406 2407 @Test getPackageInfo_uninstalledPackage_includeUninstalled()2408 public void getPackageInfo_uninstalledPackage_includeUninstalled() throws Exception { 2409 String packageName = context.getPackageName(); 2410 shadowOf(packageManager).deletePackage(packageName); 2411 2412 PackageInfo info = packageManager.getPackageInfo(packageName, MATCH_UNINSTALLED_PACKAGES); 2413 assertThat(info).isNotNull(); 2414 assertThat(info.packageName).isEqualTo(packageName); 2415 } 2416 2417 @Test getPackageInfo_uninstalledPackage_dontIncludeUninstalled()2418 public void getPackageInfo_uninstalledPackage_dontIncludeUninstalled() { 2419 String packageName = context.getPackageName(); 2420 shadowOf(packageManager).deletePackage(packageName); 2421 2422 try { 2423 PackageInfo info = packageManager.getPackageInfo(packageName, 0); 2424 fail("should have thrown NameNotFoundException:" + info.applicationInfo.flags); 2425 } catch (NameNotFoundException e) { 2426 // expected 2427 } 2428 } 2429 2430 @Test getPackageInfo_disabledPackage_includeDisabled()2431 public void getPackageInfo_disabledPackage_includeDisabled() throws Exception { 2432 packageManager.setApplicationEnabledSetting( 2433 context.getPackageName(), COMPONENT_ENABLED_STATE_DISABLED, 0); 2434 PackageInfo info = 2435 packageManager.getPackageInfo(context.getPackageName(), MATCH_DISABLED_COMPONENTS); 2436 assertThat(info).isNotNull(); 2437 assertThat(info.packageName).isEqualTo(context.getPackageName()); 2438 } 2439 2440 @Test 2441 @Config(minSdk = TIRAMISU) getPackageInfoAfterT_shouldReturnRequestedPermissions()2442 public void getPackageInfoAfterT_shouldReturnRequestedPermissions() throws Exception { 2443 PackageInfo packageInfo = 2444 packageManager.getPackageInfo( 2445 context.getPackageName(), PackageInfoFlags.of(PackageManager.GET_PERMISSIONS)); 2446 String[] permissions = packageInfo.requestedPermissions; 2447 assertThat(permissions).isNotNull(); 2448 assertThat(permissions).hasLength(4); 2449 } 2450 2451 @Test 2452 @Config(minSdk = TIRAMISU) getPackageInfoAfterT_uninstalledPackage_includeUninstalled()2453 public void getPackageInfoAfterT_uninstalledPackage_includeUninstalled() throws Exception { 2454 String packageName = context.getPackageName(); 2455 shadowOf(packageManager).deletePackage(packageName); 2456 2457 PackageInfo info = 2458 packageManager.getPackageInfo(packageName, PackageInfoFlags.of(MATCH_UNINSTALLED_PACKAGES)); 2459 assertThat(info).isNotNull(); 2460 assertThat(info.packageName).isEqualTo(packageName); 2461 } 2462 2463 @Test 2464 @Config(minSdk = TIRAMISU) getPackageInfoAfterT_uninstalledPackage_dontIncludeUninstalled()2465 public void getPackageInfoAfterT_uninstalledPackage_dontIncludeUninstalled() { 2466 String packageName = context.getPackageName(); 2467 shadowOf(packageManager).deletePackage(packageName); 2468 2469 try { 2470 PackageInfo info = packageManager.getPackageInfo(packageName, PackageInfoFlags.of(0)); 2471 fail("should have thrown NameNotFoundException:" + info.applicationInfo.flags); 2472 } catch (NameNotFoundException e) { 2473 // expected 2474 } 2475 } 2476 2477 @Test 2478 @Config(minSdk = TIRAMISU) getPackageInfoAfterT_disabledPackage_includeDisabled()2479 public void getPackageInfoAfterT_disabledPackage_includeDisabled() throws Exception { 2480 packageManager.setApplicationEnabledSetting( 2481 context.getPackageName(), COMPONENT_ENABLED_STATE_DISABLED, 0); 2482 PackageInfo info = 2483 packageManager.getPackageInfo( 2484 context.getPackageName(), PackageInfoFlags.of(MATCH_DISABLED_COMPONENTS)); 2485 assertThat(info).isNotNull(); 2486 assertThat(info.packageName).isEqualTo(context.getPackageName()); 2487 } 2488 2489 @Test getInstalledPackages_uninstalledPackage_includeUninstalled()2490 public void getInstalledPackages_uninstalledPackage_includeUninstalled() { 2491 shadowOf(packageManager).deletePackage(context.getPackageName()); 2492 2493 assertThat(packageManager.getInstalledPackages(MATCH_UNINSTALLED_PACKAGES)).isNotEmpty(); 2494 assertThat(packageManager.getInstalledPackages(MATCH_UNINSTALLED_PACKAGES).get(0).packageName) 2495 .isEqualTo(context.getPackageName()); 2496 } 2497 2498 @Test getInstalledPackages_uninstalledPackage_dontIncludeUninstalled()2499 public void getInstalledPackages_uninstalledPackage_dontIncludeUninstalled() { 2500 shadowOf(packageManager).deletePackage(context.getPackageName()); 2501 2502 assertThat(packageManager.getInstalledPackages(0)).isEmpty(); 2503 } 2504 2505 @Test getInstalledPackages_disabledPackage_includeDisabled()2506 public void getInstalledPackages_disabledPackage_includeDisabled() { 2507 packageManager.setApplicationEnabledSetting( 2508 context.getPackageName(), COMPONENT_ENABLED_STATE_DISABLED, 0); 2509 2510 assertThat(packageManager.getInstalledPackages(MATCH_DISABLED_COMPONENTS)).isNotEmpty(); 2511 assertThat(packageManager.getInstalledPackages(MATCH_DISABLED_COMPONENTS).get(0).packageName) 2512 .isEqualTo(context.getPackageName()); 2513 } 2514 2515 @Test 2516 @Config(minSdk = TIRAMISU) getInstalledPackagesAfterT_uninstalledPackage_includeUninstalled()2517 public void getInstalledPackagesAfterT_uninstalledPackage_includeUninstalled() { 2518 shadowOf(packageManager).deletePackage(context.getPackageName()); 2519 2520 assertThat(packageManager.getInstalledPackages(PackageInfoFlags.of(MATCH_UNINSTALLED_PACKAGES))) 2521 .isNotEmpty(); 2522 assertThat( 2523 packageManager 2524 .getInstalledPackages(PackageInfoFlags.of(MATCH_UNINSTALLED_PACKAGES)) 2525 .get(0) 2526 .packageName) 2527 .isEqualTo(context.getPackageName()); 2528 } 2529 2530 @Test 2531 @Config(minSdk = TIRAMISU) getInstalledPackagesAfterT_uninstalledPackage_dontIncludeUninstalled()2532 public void getInstalledPackagesAfterT_uninstalledPackage_dontIncludeUninstalled() { 2533 shadowOf(packageManager).deletePackage(context.getPackageName()); 2534 2535 assertThat(packageManager.getInstalledPackages(PackageInfoFlags.of(0))).isEmpty(); 2536 } 2537 2538 @Test 2539 @Config(minSdk = TIRAMISU) getInstalledPackagesAfterT_disabledPackage_includeDisabled()2540 public void getInstalledPackagesAfterT_disabledPackage_includeDisabled() { 2541 packageManager.setApplicationEnabledSetting( 2542 context.getPackageName(), COMPONENT_ENABLED_STATE_DISABLED, 0); 2543 2544 assertThat(packageManager.getInstalledPackages(PackageInfoFlags.of(MATCH_DISABLED_COMPONENTS))) 2545 .isNotEmpty(); 2546 assertThat( 2547 packageManager 2548 .getInstalledPackages(PackageInfoFlags.of(MATCH_DISABLED_COMPONENTS)) 2549 .get(0) 2550 .packageName) 2551 .isEqualTo(context.getPackageName()); 2552 } 2553 2554 @Test testGetPreferredActivities()2555 public void testGetPreferredActivities() { 2556 final String packageName = "com.example.dummy"; 2557 ComponentName name = new ComponentName(packageName, "LauncherActivity"); 2558 2559 // Setup an intentfilter and add to packagemanager 2560 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 2561 filter.addCategory(Intent.CATEGORY_HOME); 2562 packageManager.addPreferredActivity(filter, 0, null, name); 2563 2564 // Test match 2565 List<IntentFilter> filters = new ArrayList<>(); 2566 List<ComponentName> activities = new ArrayList<>(); 2567 int filterCount = packageManager.getPreferredActivities(filters, activities, null); 2568 2569 assertThat(filterCount).isEqualTo(1); 2570 assertThat(activities.size()).isEqualTo(1); 2571 assertThat(activities.get(0).getPackageName()).isEqualTo(packageName); 2572 assertThat(filters.size()).isEqualTo(1); 2573 2574 filterCount = packageManager.getPreferredActivities(filters, activities, "other"); 2575 2576 assertThat(filterCount).isEqualTo(0); 2577 } 2578 2579 @Test resolveActivity_preferred()2580 public void resolveActivity_preferred() { 2581 ComponentName preferredName = new ComponentName("preferred", "LauncherActivity"); 2582 ComponentName otherName = new ComponentName("other", "LauncherActivity"); 2583 Intent homeIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME); 2584 shadowOf(packageManager) 2585 .setResolveInfosForIntent( 2586 homeIntent, 2587 ImmutableList.of( 2588 ShadowResolveInfo.newResolveInfo( 2589 "label1", otherName.getPackageName(), otherName.getClassName()), 2590 ShadowResolveInfo.newResolveInfo( 2591 "label2", preferredName.getPackageName(), preferredName.getClassName()))); 2592 2593 ResolveInfo resolveInfo = packageManager.resolveActivity(homeIntent, 0); 2594 assertThat(resolveInfo.activityInfo.packageName).isEqualTo(otherName.getPackageName()); 2595 2596 // Setup an intentfilter and add to packagemanager 2597 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 2598 filter.addCategory(Intent.CATEGORY_HOME); 2599 packageManager.addPreferredActivity(filter, 0, null, preferredName); 2600 2601 resolveInfo = packageManager.resolveActivity(homeIntent, 0); 2602 assertThat(resolveInfo.activityInfo.packageName).isEqualTo(preferredName.getPackageName()); 2603 } 2604 2605 @Test canResolveDrawableGivenPackageAndResourceId()2606 public void canResolveDrawableGivenPackageAndResourceId() { 2607 Drawable drawable = 2608 Drawable.createFromStream(new ByteArrayInputStream(new byte[0]), "my_source"); 2609 shadowOf(packageManager).addDrawableResolution("com.example.foo", 4334, drawable); 2610 Drawable actual = packageManager.getDrawable("com.example.foo", 4334, null); 2611 assertThat(actual).isSameInstanceAs(drawable); 2612 } 2613 2614 @Test shouldAssignTheApplicationClassNameFromTheManifest()2615 public void shouldAssignTheApplicationClassNameFromTheManifest() throws Exception { 2616 ApplicationInfo applicationInfo = packageManager.getApplicationInfo("org.robolectric", 0); 2617 assertThat(applicationInfo.className) 2618 .isEqualTo("org.robolectric.shadows.testing.TestApplication"); 2619 } 2620 2621 @Test 2622 @Config(minSdk = N_MR1) shouldAssignTheApplicationNameFromTheManifest()2623 public void shouldAssignTheApplicationNameFromTheManifest() throws Exception { 2624 ApplicationInfo applicationInfo = packageManager.getApplicationInfo("org.robolectric", 0); 2625 assertThat(applicationInfo.name).isEqualTo("org.robolectric.shadows.testing.TestApplication"); 2626 } 2627 2628 @Test testLaunchIntentForPackage()2629 public void testLaunchIntentForPackage() { 2630 Intent intent = packageManager.getLaunchIntentForPackage(TEST_PACKAGE_LABEL); 2631 assertThat(intent).isNull(); 2632 2633 Intent launchIntent = new Intent(Intent.ACTION_MAIN); 2634 launchIntent.setPackage(TEST_PACKAGE_LABEL); 2635 launchIntent.addCategory(Intent.CATEGORY_LAUNCHER); 2636 ResolveInfo resolveInfo = new ResolveInfo(); 2637 resolveInfo.activityInfo = new ActivityInfo(); 2638 resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL; 2639 resolveInfo.activityInfo.name = "LauncherActivity"; 2640 shadowOf(packageManager).addResolveInfoForIntent(launchIntent, resolveInfo); 2641 2642 intent = packageManager.getLaunchIntentForPackage(TEST_PACKAGE_LABEL); 2643 assertThat(intent.getComponent().getClassName()).isEqualTo("LauncherActivity"); 2644 } 2645 2646 @Test testLeanbackLaunchIntentForPackage()2647 public void testLeanbackLaunchIntentForPackage() { 2648 Intent intent = packageManager.getLeanbackLaunchIntentForPackage(TEST_PACKAGE_LABEL); 2649 assertThat(intent).isNull(); 2650 2651 Intent launchIntent = new Intent(Intent.ACTION_MAIN); 2652 launchIntent.setPackage(TEST_PACKAGE_LABEL); 2653 launchIntent.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER); 2654 ResolveInfo resolveInfo = new ResolveInfo(); 2655 resolveInfo.activityInfo = new ActivityInfo(); 2656 resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL; 2657 resolveInfo.activityInfo.name = "LauncherActivity"; 2658 shadowOf(packageManager).addResolveInfoForIntent(launchIntent, resolveInfo); 2659 2660 intent = packageManager.getLeanbackLaunchIntentForPackage(TEST_PACKAGE_LABEL); 2661 assertThat(intent.getComponent().getClassName()).isEqualTo("LauncherActivity"); 2662 } 2663 2664 @Test shouldAssignTheAppMetaDataFromTheManifest()2665 public void shouldAssignTheAppMetaDataFromTheManifest() throws Exception { 2666 ApplicationInfo info = packageManager.getApplicationInfo(context.getPackageName(), 0); 2667 Bundle meta = info.metaData; 2668 2669 assertThat(meta.getString("org.robolectric.metaName1")).isEqualTo("metaValue1"); 2670 assertThat(meta.getString("org.robolectric.metaName2")).isEqualTo("metaValue2"); 2671 2672 assertThat(meta.getBoolean("org.robolectric.metaFalseLiteral")).isEqualTo(false); 2673 assertThat(meta.getBoolean("org.robolectric.metaTrueLiteral")).isEqualTo(true); 2674 2675 assertThat(meta.getInt("org.robolectric.metaInt")).isEqualTo(123); 2676 assertThat(meta.getFloat("org.robolectric.metaFloat")).isEqualTo(1.23f); 2677 2678 assertThat(meta.getInt("org.robolectric.metaColor")).isEqualTo(Color.WHITE); 2679 2680 assertThat(meta.getBoolean("org.robolectric.metaBooleanFromRes")) 2681 .isEqualTo(context.getResources().getBoolean(R.bool.false_bool_value)); 2682 2683 assertThat(meta.getInt("org.robolectric.metaIntFromRes")) 2684 .isEqualTo(context.getResources().getInteger(R.integer.test_integer1)); 2685 2686 assertThat(meta.getInt("org.robolectric.metaColorFromRes")) 2687 .isEqualTo(context.getResources().getColor(R.color.clear)); 2688 2689 assertThat(meta.getString("org.robolectric.metaStringFromRes")) 2690 .isEqualTo(context.getString(R.string.app_name)); 2691 2692 assertThat(meta.getString("org.robolectric.metaStringOfIntFromRes")) 2693 .isEqualTo(context.getString(R.string.str_int)); 2694 2695 assertThat(meta.getInt("org.robolectric.metaStringRes")).isEqualTo(R.string.app_name); 2696 } 2697 2698 @Test testResolveDifferentIntentObjects()2699 public void testResolveDifferentIntentObjects() { 2700 Intent intent1 = new Intent(Intent.ACTION_MAIN); 2701 intent1.setPackage(TEST_PACKAGE_LABEL); 2702 intent1.addCategory(Intent.CATEGORY_APP_BROWSER); 2703 2704 assertThat(packageManager.resolveActivity(intent1, 0)).isNull(); 2705 ResolveInfo resolveInfo = new ResolveInfo(); 2706 resolveInfo.activityInfo = new ActivityInfo(); 2707 resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL; 2708 resolveInfo.activityInfo.name = "BrowserActivity"; 2709 shadowOf(packageManager).addResolveInfoForIntent(intent1, resolveInfo); 2710 2711 // the original intent object should yield a result 2712 ResolveInfo result = packageManager.resolveActivity(intent1, 0); 2713 assertThat(result.activityInfo.name).isEqualTo("BrowserActivity"); 2714 2715 // AND a new, functionally equivalent intent should also yield a result 2716 Intent intent2 = new Intent(Intent.ACTION_MAIN); 2717 intent2.setPackage(TEST_PACKAGE_LABEL); 2718 intent2.addCategory(Intent.CATEGORY_APP_BROWSER); 2719 result = packageManager.resolveActivity(intent2, 0); 2720 assertThat(result.activityInfo.name).isEqualTo("BrowserActivity"); 2721 } 2722 2723 @Test testResolvePartiallySimilarIntents()2724 public void testResolvePartiallySimilarIntents() { 2725 Intent intent1 = new Intent(Intent.ACTION_APP_ERROR); 2726 intent1.setPackage(TEST_PACKAGE_LABEL); 2727 intent1.addCategory(Intent.CATEGORY_APP_BROWSER); 2728 2729 assertThat(packageManager.resolveActivity(intent1, 0)).isNull(); 2730 2731 ResolveInfo resolveInfo = new ResolveInfo(); 2732 resolveInfo.activityInfo = new ActivityInfo(); 2733 resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL; 2734 resolveInfo.activityInfo.name = "BrowserActivity"; 2735 shadowOf(packageManager).addResolveInfoForIntent(intent1, resolveInfo); 2736 2737 // the original intent object should yield a result 2738 ResolveInfo result = packageManager.resolveActivity(intent1, 0); 2739 assertThat(result.activityInfo.name).isEqualTo("BrowserActivity"); 2740 2741 // an intent with just the same action should not be considered the same 2742 Intent intent2 = new Intent(Intent.ACTION_APP_ERROR); 2743 result = packageManager.resolveActivity(intent2, 0); 2744 assertThat(result).isNull(); 2745 2746 // an intent with just the same category should not be considered the same 2747 Intent intent3 = new Intent(); 2748 intent3.addCategory(Intent.CATEGORY_APP_BROWSER); 2749 result = packageManager.resolveActivity(intent3, 0); 2750 assertThat(result).isNull(); 2751 2752 // an intent without the correct package restriction should not be the same 2753 Intent intent4 = new Intent(Intent.ACTION_APP_ERROR); 2754 intent4.addCategory(Intent.CATEGORY_APP_BROWSER); 2755 result = packageManager.resolveActivity(intent4, 0); 2756 assertThat(result).isNull(); 2757 } 2758 2759 @Test testSetApplicationEnabledSetting()2760 public void testSetApplicationEnabledSetting() { 2761 assertThat(packageManager.getApplicationEnabledSetting("org.robolectric")) 2762 .isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); 2763 2764 packageManager.setApplicationEnabledSetting( 2765 "org.robolectric", PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0); 2766 2767 assertThat(packageManager.getApplicationEnabledSetting("org.robolectric")) 2768 .isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_DISABLED); 2769 } 2770 2771 private static class ActivityWithMetadata extends Activity {} 2772 2773 @Test getActivityMetaData()2774 public void getActivityMetaData() throws Exception { 2775 Activity activity = setupActivity(ActivityWithMetadata.class); 2776 2777 ActivityInfo activityInfo = 2778 packageManager.getActivityInfo( 2779 activity.getComponentName(), 2780 PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA); 2781 assertThat(activityInfo.metaData.get("someName")).isEqualTo("someValue"); 2782 } 2783 2784 @Test shouldAssignLabelResFromTheManifest()2785 public void shouldAssignLabelResFromTheManifest() throws Exception { 2786 ApplicationInfo applicationInfo = packageManager.getApplicationInfo("org.robolectric", 0); 2787 assertThat(applicationInfo.labelRes).isEqualTo(R.string.app_name); 2788 assertThat(applicationInfo.nonLocalizedLabel).isNull(); 2789 } 2790 2791 @Test getServiceInfo_shouldReturnServiceInfoIfExists()2792 public void getServiceInfo_shouldReturnServiceInfoIfExists() throws Exception { 2793 ServiceInfo serviceInfo = 2794 packageManager.getServiceInfo(new ComponentName("org.robolectric", "com.foo.Service"), 0); 2795 assertThat(serviceInfo.packageName).isEqualTo("org.robolectric"); 2796 assertThat(serviceInfo.name).isEqualTo("com.foo.Service"); 2797 assertThat(serviceInfo.permission).isEqualTo("com.foo.MY_PERMISSION"); 2798 assertThat(serviceInfo.applicationInfo).isNotNull(); 2799 } 2800 2801 @Test getServiceInfo_shouldReturnServiceInfoWithMetaDataWhenFlagsSet()2802 public void getServiceInfo_shouldReturnServiceInfoWithMetaDataWhenFlagsSet() throws Exception { 2803 ServiceInfo serviceInfo = 2804 packageManager.getServiceInfo( 2805 new ComponentName("org.robolectric", "com.foo.Service"), PackageManager.GET_META_DATA); 2806 assertThat(serviceInfo.metaData).isNotNull(); 2807 } 2808 2809 @Test getServiceInfo_shouldReturnServiceInfoWithoutMetaDataWhenFlagsNotSet()2810 public void getServiceInfo_shouldReturnServiceInfoWithoutMetaDataWhenFlagsNotSet() 2811 throws Exception { 2812 ComponentName component = new ComponentName("org.robolectric", "com.foo.Service"); 2813 ServiceInfo serviceInfo = packageManager.getServiceInfo(component, 0); 2814 assertThat(serviceInfo.metaData).isNull(); 2815 } 2816 2817 @Test getServiceInfo_shouldThrowNameNotFoundExceptionIfNotExist()2818 public void getServiceInfo_shouldThrowNameNotFoundExceptionIfNotExist() { 2819 ComponentName nonExistComponent = 2820 new ComponentName("org.robolectric", "com.foo.NonExistService"); 2821 try { 2822 packageManager.getServiceInfo(nonExistComponent, PackageManager.GET_SERVICES); 2823 fail("should have thrown NameNotFoundException"); 2824 } catch (PackageManager.NameNotFoundException e) { 2825 assertThat(e.getMessage()).contains("com.foo.NonExistService"); 2826 } 2827 } 2828 2829 @Test getServiceInfo_shouldFindServiceIfAddedInResolveInfo()2830 public void getServiceInfo_shouldFindServiceIfAddedInResolveInfo() throws Exception { 2831 ComponentName componentName = new ComponentName("com.test", "com.test.ServiceName"); 2832 ResolveInfo resolveInfo = new ResolveInfo(); 2833 resolveInfo.serviceInfo = new ServiceInfo(); 2834 resolveInfo.serviceInfo.name = componentName.getClassName(); 2835 resolveInfo.serviceInfo.applicationInfo = new ApplicationInfo(); 2836 resolveInfo.serviceInfo.applicationInfo.packageName = componentName.getPackageName(); 2837 shadowOf(packageManager).addResolveInfoForIntent(new Intent("RANDOM_ACTION"), resolveInfo); 2838 2839 ServiceInfo serviceInfo = packageManager.getServiceInfo(componentName, 0); 2840 assertThat(serviceInfo).isNotNull(); 2841 } 2842 2843 @Test 2844 @Config(minSdk = TIRAMISU) getServiceInfo_withComponentInfoFlags_shouldReturnServiceInfoIfExists()2845 public void getServiceInfo_withComponentInfoFlags_shouldReturnServiceInfoIfExists() 2846 throws Exception { 2847 ServiceInfo serviceInfo = 2848 packageManager.getServiceInfo( 2849 new ComponentName("org.robolectric", "com.foo.Service"), 2850 PackageManager.ComponentInfoFlags.of(0)); 2851 assertThat(serviceInfo.packageName).isEqualTo("org.robolectric"); 2852 assertThat(serviceInfo.name).isEqualTo("com.foo.Service"); 2853 assertThat(serviceInfo.permission).isEqualTo("com.foo.MY_PERMISSION"); 2854 assertThat(serviceInfo.applicationInfo).isNotNull(); 2855 } 2856 2857 @Test 2858 @Config(minSdk = TIRAMISU) 2859 public void getServiceInfo_withComponentInfoFlags_shouldReturnServiceInfoWithMetaDataWhenFlagsSet()2860 getServiceInfo_withComponentInfoFlags_shouldReturnServiceInfoWithMetaDataWhenFlagsSet() 2861 throws Exception { 2862 ServiceInfo serviceInfo = 2863 packageManager.getServiceInfo( 2864 new ComponentName("org.robolectric", "com.foo.Service"), 2865 PackageManager.ComponentInfoFlags.of(PackageManager.GET_META_DATA)); 2866 assertThat(serviceInfo.metaData).isNotNull(); 2867 } 2868 2869 @Test 2870 @Config(minSdk = TIRAMISU) 2871 public void getServiceInfo_withComponentInfoFlags_shouldReturnServiceInfoWithoutMetaDataWhenFlagsNotSet()2872 getServiceInfo_withComponentInfoFlags_shouldReturnServiceInfoWithoutMetaDataWhenFlagsNotSet() 2873 throws Exception { 2874 ComponentName component = new ComponentName("org.robolectric", "com.foo.Service"); 2875 ServiceInfo serviceInfo = 2876 packageManager.getServiceInfo(component, PackageManager.ComponentInfoFlags.of(0)); 2877 assertThat(serviceInfo.metaData).isNull(); 2878 } 2879 2880 @Test 2881 @Config(minSdk = TIRAMISU) getServiceInfo_withComponentInfoFlags_shouldThrowNameNotFoundExceptionIfNotExist()2882 public void getServiceInfo_withComponentInfoFlags_shouldThrowNameNotFoundExceptionIfNotExist() { 2883 ComponentName nonExistComponent = 2884 new ComponentName("org.robolectric", "com.foo.NonExistService"); 2885 try { 2886 packageManager.getServiceInfo( 2887 nonExistComponent, PackageManager.ComponentInfoFlags.of(PackageManager.GET_SERVICES)); 2888 fail("should have thrown NameNotFoundException"); 2889 } catch (PackageManager.NameNotFoundException e) { 2890 assertThat(e.getMessage()).contains("com.foo.NonExistService"); 2891 } 2892 } 2893 2894 @Test 2895 @Config(minSdk = TIRAMISU) getServiceInfo_withComponentInfoFlags_shouldFindServiceIfAddedInResolveInfo()2896 public void getServiceInfo_withComponentInfoFlags_shouldFindServiceIfAddedInResolveInfo() 2897 throws Exception { 2898 ComponentName componentName = new ComponentName("com.test", "com.test.ServiceName"); 2899 ResolveInfo resolveInfo = new ResolveInfo(); 2900 resolveInfo.serviceInfo = new ServiceInfo(); 2901 resolveInfo.serviceInfo.name = componentName.getClassName(); 2902 resolveInfo.serviceInfo.applicationInfo = new ApplicationInfo(); 2903 resolveInfo.serviceInfo.applicationInfo.packageName = componentName.getPackageName(); 2904 shadowOf(packageManager).addResolveInfoForIntent(new Intent("RANDOM_ACTION"), resolveInfo); 2905 2906 ServiceInfo serviceInfo = 2907 packageManager.getServiceInfo(componentName, PackageManager.ComponentInfoFlags.of(0)); 2908 assertThat(serviceInfo).isNotNull(); 2909 } 2910 2911 @Test getNameForUid()2912 public void getNameForUid() { 2913 assertThat(packageManager.getNameForUid(10)).isNull(); 2914 2915 shadowOf(packageManager).setNameForUid(10, "a_name"); 2916 2917 assertThat(packageManager.getNameForUid(10)).isEqualTo("a_name"); 2918 } 2919 2920 @Test getPackagesForUid()2921 public void getPackagesForUid() { 2922 assertThat(packageManager.getPackagesForUid(10)).isNull(); 2923 2924 shadowOf(packageManager).setPackagesForUid(10, new String[] {"a_name"}); 2925 2926 assertThat(packageManager.getPackagesForUid(10)).asList().containsExactly("a_name"); 2927 } 2928 2929 @Test 2930 @Config(minSdk = N) getPackageUid()2931 public void getPackageUid() throws NameNotFoundException { 2932 shadowOf(packageManager).setPackagesForUid(10, new String[] {"a_name"}); 2933 assertThat(packageManager.getPackageUid("a_name", 0)).isEqualTo(10); 2934 } 2935 2936 @Test 2937 @Config(minSdk = N) getPackageUid_shouldThrowNameNotFoundExceptionIfNotExist()2938 public void getPackageUid_shouldThrowNameNotFoundExceptionIfNotExist() { 2939 try { 2940 packageManager.getPackageUid("a_name", 0); 2941 fail("should have thrown NameNotFoundException"); 2942 } catch (PackageManager.NameNotFoundException e) { 2943 assertThat(e.getMessage()).contains("a_name"); 2944 } 2945 } 2946 2947 @Test 2948 @Config(minSdk = TIRAMISU) getPackageUid_sdkT()2949 public void getPackageUid_sdkT() throws NameNotFoundException { 2950 shadowOf(packageManager).setPackagesForUid(10, new String[] {"a_name"}); 2951 assertThat(packageManager.getPackageUid("a_name", PackageInfoFlags.of(0))).isEqualTo(10); 2952 } 2953 2954 @Test 2955 @Config(minSdk = TIRAMISU) getPackageUid_sdkT_shouldThrowNameNotFoundExceptionIfNotExist()2956 public void getPackageUid_sdkT_shouldThrowNameNotFoundExceptionIfNotExist() { 2957 try { 2958 packageManager.getPackageUid("a_name", PackageInfoFlags.of(0)); 2959 fail("should have thrown NameNotFoundException"); 2960 } catch (PackageManager.NameNotFoundException e) { 2961 assertThat(e).hasMessageThat().contains("a_name"); 2962 } 2963 } 2964 2965 @Test getPackagesForUid_shouldReturnSetPackageName()2966 public void getPackagesForUid_shouldReturnSetPackageName() { 2967 shadowOf(packageManager).setPackagesForUid(10, new String[] {"a_name"}); 2968 assertThat(packageManager.getPackagesForUid(10)).asList().containsExactly("a_name"); 2969 } 2970 2971 @Test getResourcesForApplication_currentApplication()2972 public void getResourcesForApplication_currentApplication() throws Exception { 2973 assertThat( 2974 packageManager 2975 .getResourcesForApplication("org.robolectric") 2976 .getString(R.string.app_name)) 2977 .isEqualTo(context.getString(R.string.app_name)); 2978 } 2979 2980 @Test getResourcesForApplication_unknownPackage()2981 public void getResourcesForApplication_unknownPackage() { 2982 try { 2983 packageManager.getResourcesForApplication("non.existent.package"); 2984 fail("should have thrown NameNotFoundException"); 2985 } catch (NameNotFoundException e) { 2986 // expected 2987 } 2988 } 2989 2990 @Test getResourcesForApplication_anotherPackage()2991 public void getResourcesForApplication_anotherPackage() throws Exception { 2992 PackageInfo packageInfo = new PackageInfo(); 2993 packageInfo.packageName = "another.package"; 2994 2995 ApplicationInfo applicationInfo = new ApplicationInfo(); 2996 applicationInfo.packageName = "another.package"; 2997 packageInfo.applicationInfo = applicationInfo; 2998 shadowOf(packageManager).installPackage(packageInfo); 2999 3000 assertThat(packageManager.getResourcesForApplication("another.package")).isNotNull(); 3001 assertThat(packageManager.getResourcesForApplication("another.package")) 3002 .isNotEqualTo(context.getResources()); 3003 } 3004 verifyApkNotInstalled(String packageName)3005 private void verifyApkNotInstalled(String packageName) { 3006 try { 3007 packageManager.getPackageInfo(packageName, 0); 3008 Assert.fail("Package not expected to be installed."); 3009 } catch (NameNotFoundException e) { 3010 // expected exception 3011 } 3012 } 3013 3014 @Test getResourcesForApplication_ApkNotInstalled()3015 public void getResourcesForApplication_ApkNotInstalled() throws NameNotFoundException { 3016 File testApk = TestUtil.resourcesBaseDir().resolve(REAL_TEST_APP_ASSET_PATH).toFile(); 3017 3018 PackageInfo packageInfo = packageManager.getPackageArchiveInfo(testApk.getAbsolutePath(), 0); 3019 3020 assertThat(packageInfo).isNotNull(); 3021 ApplicationInfo applicationInfo = packageInfo.applicationInfo; 3022 assertThat(applicationInfo.packageName).isEqualTo(REAL_TEST_APP_PACKAGE_NAME); 3023 3024 // double-check that Robolectric doesn't consider this package to be installed 3025 verifyApkNotInstalled(packageInfo.packageName); 3026 3027 applicationInfo.sourceDir = applicationInfo.publicSourceDir = testApk.getAbsolutePath(); 3028 assertThat(packageManager.getResourcesForApplication(applicationInfo)).isNotNull(); 3029 } 3030 3031 @Test getResourcesForApplication_ApkNotPresent()3032 public void getResourcesForApplication_ApkNotPresent() { 3033 ApplicationInfo applicationInfo = 3034 ApplicationInfoBuilder.newBuilder().setPackageName("com.not.present").build(); 3035 applicationInfo.sourceDir = applicationInfo.publicSourceDir = "/some/nonexistent/path"; 3036 3037 try { 3038 packageManager.getResourcesForApplication(applicationInfo); 3039 Assert.fail("Expected NameNotFoundException not thrown"); 3040 } catch (NameNotFoundException ex) { 3041 // Expected exception 3042 } 3043 } 3044 3045 @Test 3046 @Config(minSdk = M) shouldShowRequestPermissionRationale()3047 public void shouldShowRequestPermissionRationale() { 3048 assertThat(packageManager.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) 3049 .isFalse(); 3050 3051 shadowOf(packageManager) 3052 .setShouldShowRequestPermissionRationale(Manifest.permission.CAMERA, true); 3053 3054 assertThat(packageManager.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) 3055 .isTrue(); 3056 } 3057 3058 @Test getSystemAvailableFeatures()3059 public void getSystemAvailableFeatures() { 3060 assertThat(packageManager.getSystemAvailableFeatures()).isNull(); 3061 3062 FeatureInfo feature = new FeatureInfo(); 3063 feature.reqGlEsVersion = 0x20000; 3064 feature.flags = FeatureInfo.FLAG_REQUIRED; 3065 shadowOf(packageManager).addSystemAvailableFeature(feature); 3066 3067 assertThat(packageManager.getSystemAvailableFeatures()).asList().contains(feature); 3068 3069 shadowOf(packageManager).clearSystemAvailableFeatures(); 3070 3071 assertThat(packageManager.getSystemAvailableFeatures()).isNull(); 3072 } 3073 3074 @Test verifyPendingInstall()3075 public void verifyPendingInstall() { 3076 packageManager.verifyPendingInstall(1234, VERIFICATION_ALLOW); 3077 3078 assertThat(shadowOf(packageManager).getVerificationResult(1234)).isEqualTo(VERIFICATION_ALLOW); 3079 } 3080 3081 @Test 3082 public void extendPendingInstallTimeout_verificationRejectAtTimeout_extendsPendingInstallTimeoutAndsetsCodeAtTimeoutToReject()3083 extendPendingInstallTimeout_verificationRejectAtTimeout_extendsPendingInstallTimeoutAndsetsCodeAtTimeoutToReject() { 3084 packageManager.extendVerificationTimeout( 3085 INSTALL_VERIFICATION_ID, 3086 /* verificationCodeAtTimeout= */ VERIFICATION_REJECT, 3087 /* millisecondsToDelay= */ 1000); 3088 3089 assertThat(shadowOf(packageManager).getVerificationExtendedTimeout(INSTALL_VERIFICATION_ID)) 3090 .isEqualTo(1000); 3091 assertThat( 3092 shadowOf(packageManager).getVerificationCodeAtTimeoutExtension(INSTALL_VERIFICATION_ID)) 3093 .isEqualTo(VERIFICATION_REJECT); 3094 } 3095 3096 @Test 3097 public void extendPendingInstallTimeout_verificationAllowAtTimeout_extendsPendingInstallTimeoutAndsetsCodeAtTimeoutToAllow()3098 extendPendingInstallTimeout_verificationAllowAtTimeout_extendsPendingInstallTimeoutAndsetsCodeAtTimeoutToAllow() { 3099 packageManager.extendVerificationTimeout( 3100 INSTALL_VERIFICATION_ID, 3101 /* verificationCodeAtTimeout= */ VERIFICATION_ALLOW, 3102 /* millisecondsToDelay= */ 1000); 3103 3104 assertThat(shadowOf(packageManager).getVerificationExtendedTimeout(INSTALL_VERIFICATION_ID)) 3105 .isEqualTo(1000); 3106 assertThat( 3107 shadowOf(packageManager).getVerificationCodeAtTimeoutExtension(INSTALL_VERIFICATION_ID)) 3108 .isEqualTo(VERIFICATION_ALLOW); 3109 } 3110 3111 @Test whenVerificationTimeOutNotExtended_verificationCodeAtTimeoutIsAllow()3112 public void whenVerificationTimeOutNotExtended_verificationCodeAtTimeoutIsAllow() { 3113 assertThat(shadowOf(packageManager).getVerificationExtendedTimeout(INSTALL_VERIFICATION_ID)) 3114 .isEqualTo(0); 3115 // Default verdict is to allow installation. 3116 assertThat( 3117 shadowOf(packageManager).getVerificationCodeAtTimeoutExtension(INSTALL_VERIFICATION_ID)) 3118 .isEqualTo(VERIFICATION_ALLOW); 3119 } 3120 3121 @Test triggerInstallVerificationTimeout_broadcastsPackageVerifiedIntent()3122 public void triggerInstallVerificationTimeout_broadcastsPackageVerifiedIntent() { 3123 ShadowPackageManager shadowPackageManagerMock = 3124 mock(ShadowPackageManager.class, Mockito.CALLS_REAL_METHODS); 3125 3126 doReturn(VERIFICATION_REJECT) 3127 .when(shadowPackageManagerMock) 3128 .getVerificationCodeAtTimeoutExtension(INSTALL_VERIFICATION_ID); 3129 3130 List<Integer> verificationIdList = new ArrayList<>(); 3131 List<Integer> verificationResultList = new ArrayList<>(); 3132 BroadcastReceiver receiver = 3133 new BroadcastReceiver() { 3134 @Override 3135 public void onReceive(Context context, Intent intent) { 3136 verificationIdList.add(intent.getIntExtra(EXTRA_VERIFICATION_ID, 0)); 3137 verificationResultList.add( 3138 intent.getIntExtra(PackageManager.EXTRA_VERIFICATION_RESULT, 0)); 3139 } 3140 }; 3141 IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_VERIFIED); 3142 context.registerReceiver(receiver, intentFilter); 3143 3144 shadowPackageManagerMock.triggerInstallVerificationTimeout( 3145 (Application) context, INSTALL_VERIFICATION_ID); 3146 3147 assertThat(verificationIdList).containsExactly(INSTALL_VERIFICATION_ID); 3148 assertThat(verificationResultList).containsExactly(VERIFICATION_REJECT); 3149 } 3150 3151 @Test 3152 @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O whenPackageNotPresent_getPackageSizeInfo_callsBackWithFailure()3153 public void whenPackageNotPresent_getPackageSizeInfo_callsBackWithFailure() throws Exception { 3154 IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class); 3155 packageManager.getPackageSizeInfo("nonexistent.package", packageStatsObserver); 3156 shadowMainLooper().idle(); 3157 3158 verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(false)); 3159 assertThat(packageStatsCaptor.getValue()).isNull(); 3160 } 3161 3162 @Test 3163 @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O whenPackageNotPresentAndPaused_getPackageSizeInfo_callsBackWithFailure()3164 public void whenPackageNotPresentAndPaused_getPackageSizeInfo_callsBackWithFailure() 3165 throws Exception { 3166 shadowMainLooper().pause(); 3167 IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class); 3168 packageManager.getPackageSizeInfo("nonexistent.package", packageStatsObserver); 3169 3170 verifyNoMoreInteractions(packageStatsObserver); 3171 3172 shadowMainLooper().idle(); 3173 verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(false)); 3174 assertThat(packageStatsCaptor.getValue()).isNull(); 3175 } 3176 3177 @Test 3178 @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O whenNotPreconfigured_getPackageSizeInfo_callsBackWithDefaults()3179 public void whenNotPreconfigured_getPackageSizeInfo_callsBackWithDefaults() throws Exception { 3180 IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class); 3181 packageManager.getPackageSizeInfo("org.robolectric", packageStatsObserver); 3182 shadowMainLooper().idle(); 3183 3184 verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true)); 3185 assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.robolectric"); 3186 } 3187 3188 @Test 3189 @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O whenPreconfigured_getPackageSizeInfo_callsBackWithConfiguredValues()3190 public void whenPreconfigured_getPackageSizeInfo_callsBackWithConfiguredValues() 3191 throws Exception { 3192 PackageInfo packageInfo = new PackageInfo(); 3193 packageInfo.packageName = "org.robolectric"; 3194 PackageStats packageStats = new PackageStats("org.robolectric"); 3195 shadowOf(packageManager).addPackage(packageInfo, packageStats); 3196 3197 IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class); 3198 packageManager.getPackageSizeInfo("org.robolectric", packageStatsObserver); 3199 shadowMainLooper().idle(); 3200 3201 verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true)); 3202 assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.robolectric"); 3203 assertThat(packageStatsCaptor.getValue().toString()).isEqualTo(packageStats.toString()); 3204 } 3205 3206 @Test 3207 @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O whenPreconfiguredForAnotherPackage_getPackageSizeInfo_callsBackWithConfiguredValues()3208 public void whenPreconfiguredForAnotherPackage_getPackageSizeInfo_callsBackWithConfiguredValues() 3209 throws Exception { 3210 PackageInfo packageInfo = new PackageInfo(); 3211 packageInfo.packageName = "org.other"; 3212 PackageStats packageStats = new PackageStats("org.other"); 3213 shadowOf(packageManager).addPackage(packageInfo, packageStats); 3214 3215 IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class); 3216 packageManager.getPackageSizeInfo("org.other", packageStatsObserver); 3217 shadowMainLooper().idle(); 3218 3219 verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true)); 3220 assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.other"); 3221 assertThat(packageStatsCaptor.getValue().toString()).isEqualTo(packageStats.toString()); 3222 } 3223 3224 @Test 3225 @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O whenPaused_getPackageSizeInfo_callsBackWithConfiguredValuesAfterIdle()3226 public void whenPaused_getPackageSizeInfo_callsBackWithConfiguredValuesAfterIdle() 3227 throws Exception { 3228 shadowMainLooper().pause(); 3229 3230 IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class); 3231 packageManager.getPackageSizeInfo("org.robolectric", packageStatsObserver); 3232 3233 verifyNoMoreInteractions(packageStatsObserver); 3234 3235 shadowMainLooper().idle(); 3236 verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true)); 3237 assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.robolectric"); 3238 } 3239 3240 @Test addCanonicalName()3241 public void addCanonicalName() { 3242 shadowOf(packageManager).addCanonicalName("current_name_1", "canonical_name_1"); 3243 shadowOf(packageManager).addCanonicalName("current_name_2", "canonical_name_2"); 3244 3245 assertThat( 3246 packageManager.canonicalToCurrentPackageNames( 3247 new String[] {"canonical_name_1", "canonical_name_2", "some_other_name"})) 3248 .asList() 3249 .containsExactly("current_name_1", "current_name_2", "some_other_name") 3250 .inOrder(); 3251 assertThat( 3252 packageManager.currentToCanonicalPackageNames( 3253 new String[] {"current_name_1", "current_name_2", "some_other_name"})) 3254 .asList() 3255 .containsExactly("canonical_name_1", "canonical_name_2", "some_other_name") 3256 .inOrder(); 3257 } 3258 3259 @Test getInstalledApplications_noFlags_oldSdk()3260 public void getInstalledApplications_noFlags_oldSdk() { 3261 List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(0); 3262 3263 // Default should include the application under test 3264 assertThat(installedApplications).hasSize(1); 3265 assertThat(installedApplications.get(0).packageName).isEqualTo("org.robolectric"); 3266 3267 PackageInfo packageInfo = new PackageInfo(); 3268 packageInfo.packageName = "org.other"; 3269 packageInfo.applicationInfo = new ApplicationInfo(); 3270 packageInfo.applicationInfo.packageName = "org.other"; 3271 shadowOf(packageManager).installPackage(packageInfo); 3272 3273 installedApplications = packageManager.getInstalledApplications(0); 3274 assertThat(installedApplications).hasSize(2); 3275 assertThat(installedApplications.get(1).packageName).isEqualTo("org.other"); 3276 } 3277 3278 @Test 3279 @Config(minSdk = TIRAMISU) getInstalledApplications_null_throwsException()3280 public void getInstalledApplications_null_throwsException() { 3281 assertThrows(Exception.class, () -> packageManager.getInstalledApplications(null)); 3282 } 3283 3284 @Test 3285 @Config(minSdk = TIRAMISU) getInstalledApplications_noFlags_returnsAllInstalledApplications()3286 public void getInstalledApplications_noFlags_returnsAllInstalledApplications() { 3287 List<ApplicationInfo> installedApplications = 3288 packageManager.getInstalledApplications(ApplicationInfoFlags.of(0)); 3289 3290 // Default should include the application under test 3291 assertThat(installedApplications).hasSize(1); 3292 assertThat(installedApplications.get(0).packageName).isEqualTo("org.robolectric"); 3293 3294 PackageInfo packageInfo = new PackageInfo(); 3295 packageInfo.packageName = "org.other"; 3296 packageInfo.applicationInfo = new ApplicationInfo(); 3297 packageInfo.applicationInfo.packageName = "org.other"; 3298 shadowOf(packageManager).installPackage(packageInfo); 3299 3300 installedApplications = packageManager.getInstalledApplications(0); 3301 assertThat(installedApplications).hasSize(2); 3302 assertThat(installedApplications.get(1).packageName).isEqualTo("org.other"); 3303 } 3304 3305 @Test getPermissionInfo()3306 public void getPermissionInfo() throws Exception { 3307 PermissionInfo permission = 3308 context.getPackageManager().getPermissionInfo("org.robolectric.some_permission", 0); 3309 assertThat(permission.labelRes).isEqualTo(R.string.test_permission_label); 3310 assertThat(permission.descriptionRes).isEqualTo(R.string.test_permission_description); 3311 assertThat(permission.name).isEqualTo("org.robolectric.some_permission"); 3312 } 3313 3314 @Test checkSignatures_same()3315 public void checkSignatures_same() { 3316 shadowOf(packageManager) 3317 .installPackage(newPackageInfo("first.package", new Signature("00000000"))); 3318 shadowOf(packageManager) 3319 .installPackage(newPackageInfo("second.package", new Signature("00000000"))); 3320 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3321 .isEqualTo(SIGNATURE_MATCH); 3322 } 3323 3324 @Test checkSignatures_firstNotSigned()3325 public void checkSignatures_firstNotSigned() { 3326 shadowOf(packageManager).installPackage(newPackageInfo("first.package", (Signature[]) null)); 3327 shadowOf(packageManager) 3328 .installPackage(newPackageInfo("second.package", new Signature("00000000"))); 3329 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3330 .isEqualTo(SIGNATURE_FIRST_NOT_SIGNED); 3331 } 3332 3333 @Test checkSignatures_secondNotSigned()3334 public void checkSignatures_secondNotSigned() { 3335 shadowOf(packageManager) 3336 .installPackage(newPackageInfo("first.package", new Signature("00000000"))); 3337 shadowOf(packageManager).installPackage(newPackageInfo("second.package", (Signature[]) null)); 3338 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3339 .isEqualTo(SIGNATURE_SECOND_NOT_SIGNED); 3340 } 3341 3342 @Test checkSignatures_neitherSigned()3343 public void checkSignatures_neitherSigned() { 3344 shadowOf(packageManager).installPackage(newPackageInfo("first.package", (Signature[]) null)); 3345 shadowOf(packageManager).installPackage(newPackageInfo("second.package", (Signature[]) null)); 3346 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3347 .isEqualTo(SIGNATURE_NEITHER_SIGNED); 3348 } 3349 3350 @Test checkSignatures_noMatch()3351 public void checkSignatures_noMatch() { 3352 shadowOf(packageManager) 3353 .installPackage(newPackageInfo("first.package", new Signature("00000000"))); 3354 shadowOf(packageManager) 3355 .installPackage(newPackageInfo("second.package", new Signature("FFFFFFFF"))); 3356 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3357 .isEqualTo(SIGNATURE_NO_MATCH); 3358 } 3359 3360 @Test checkSignatures_noMatch_mustBeExact()3361 public void checkSignatures_noMatch_mustBeExact() { 3362 shadowOf(packageManager) 3363 .installPackage(newPackageInfo("first.package", new Signature("00000000"))); 3364 shadowOf(packageManager) 3365 .installPackage( 3366 newPackageInfo("second.package", new Signature("00000000"), new Signature("FFFFFFFF"))); 3367 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3368 .isEqualTo(SIGNATURE_NO_MATCH); 3369 } 3370 3371 @Test checkSignatures_unknownPackage()3372 public void checkSignatures_unknownPackage() { 3373 assertThat(packageManager.checkSignatures("first.package", "second.package")) 3374 .isEqualTo(SIGNATURE_UNKNOWN_PACKAGE); 3375 } 3376 newPackageInfo(String packageName, Signature... signatures)3377 private static PackageInfo newPackageInfo(String packageName, Signature... signatures) { 3378 PackageInfo firstPackageInfo = new PackageInfo(); 3379 firstPackageInfo.packageName = packageName; 3380 if (VERSION.SDK_INT < P) { 3381 firstPackageInfo.signatures = signatures; 3382 } else { 3383 firstPackageInfo.signingInfo = new SigningInfo(); 3384 shadowOf(firstPackageInfo.signingInfo).setSignatures(signatures); 3385 } 3386 return firstPackageInfo; 3387 } 3388 3389 @Test getPermissionInfo_notFound()3390 public void getPermissionInfo_notFound() { 3391 try { 3392 packageManager.getPermissionInfo("non_existant_permission", 0); 3393 fail("should have thrown NameNotFoundException"); 3394 } catch (NameNotFoundException e) { 3395 // expected 3396 } 3397 } 3398 3399 @Test getPermissionInfo_noMetaData()3400 public void getPermissionInfo_noMetaData() throws Exception { 3401 PermissionInfo permission = 3402 packageManager.getPermissionInfo("org.robolectric.some_permission", 0); 3403 assertThat(permission.metaData).isNull(); 3404 assertThat(permission.name).isEqualTo("org.robolectric.some_permission"); 3405 assertThat(permission.descriptionRes).isEqualTo(R.string.test_permission_description); 3406 assertThat(permission.labelRes).isEqualTo(R.string.test_permission_label); 3407 assertThat(permission.nonLocalizedLabel).isNull(); 3408 assertThat(permission.group).isEqualTo("my_permission_group"); 3409 assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_DANGEROUS); 3410 } 3411 3412 @Test getPermissionInfo_withMetaData()3413 public void getPermissionInfo_withMetaData() throws Exception { 3414 PermissionInfo permission = 3415 packageManager.getPermissionInfo( 3416 "org.robolectric.some_permission", PackageManager.GET_META_DATA); 3417 assertThat(permission.metaData).isNotNull(); 3418 assertThat(permission.metaData.getString("meta_data_name")).isEqualTo("meta_data_value"); 3419 } 3420 3421 @Test getPermissionInfo_withLiteralLabel()3422 public void getPermissionInfo_withLiteralLabel() throws Exception { 3423 PermissionInfo permission = 3424 packageManager.getPermissionInfo("org.robolectric.permission_with_literal_label", 0); 3425 assertThat(permission.labelRes).isEqualTo(0); 3426 assertThat(permission.nonLocalizedLabel.toString()).isEqualTo("Literal label"); 3427 assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_NORMAL); 3428 } 3429 3430 @Test queryPermissionsByGroup_groupNotFound()3431 public void queryPermissionsByGroup_groupNotFound() { 3432 try { 3433 packageManager.queryPermissionsByGroup("nonexistent_permission_group", 0); 3434 fail("Exception expected"); 3435 } catch (NameNotFoundException expected) { 3436 } 3437 } 3438 3439 @Test queryPermissionsByGroup_noMetaData()3440 public void queryPermissionsByGroup_noMetaData() throws Exception { 3441 List<PermissionInfo> permissions = 3442 packageManager.queryPermissionsByGroup("my_permission_group", 0); 3443 assertThat(permissions).hasSize(1); 3444 3445 PermissionInfo permission = permissions.get(0); 3446 3447 assertThat(permission.group).isEqualTo("my_permission_group"); 3448 assertThat(permission.name).isEqualTo("org.robolectric.some_permission"); 3449 assertThat(permission.metaData).isNull(); 3450 } 3451 3452 @Test queryPermissionsByGroup_withMetaData()3453 public void queryPermissionsByGroup_withMetaData() throws Exception { 3454 List<PermissionInfo> permissions = 3455 packageManager.queryPermissionsByGroup("my_permission_group", PackageManager.GET_META_DATA); 3456 assertThat(permissions).hasSize(1); 3457 3458 PermissionInfo permission = permissions.get(0); 3459 3460 assertThat(permission.group).isEqualTo("my_permission_group"); 3461 assertThat(permission.name).isEqualTo("org.robolectric.some_permission"); 3462 assertThat(permission.metaData).isNotNull(); 3463 assertThat(permission.metaData.getString("meta_data_name")).isEqualTo("meta_data_value"); 3464 } 3465 3466 @Test queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup()3467 public void queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup() 3468 throws Exception { 3469 List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup(null, 0); 3470 3471 assertThat(permissions.stream().map(info -> info.name).collect(toImmutableList())) 3472 .containsExactly( 3473 "org.robolectric.permission_with_minimal_fields", 3474 "org.robolectric.permission_with_literal_label"); 3475 } 3476 3477 @Test 3478 public void queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup_with_addPermissionInfo()3479 queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup_with_addPermissionInfo() 3480 throws Exception { 3481 PermissionInfo permissionInfo = new PermissionInfo(); 3482 permissionInfo.name = "some_name"; 3483 shadowOf(packageManager).addPermissionInfo(permissionInfo); 3484 3485 List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup(null, 0); 3486 assertThat(permissions).isNotEmpty(); 3487 3488 assertThat(permissions.stream().map(info -> info.name).collect(toImmutableList())) 3489 .containsExactly( 3490 permissionInfo.name, 3491 "org.robolectric.permission_with_minimal_fields", 3492 "org.robolectric.permission_with_literal_label"); 3493 } 3494 3495 @Test queryPermissionsByGroup_with_addPermissionInfo()3496 public void queryPermissionsByGroup_with_addPermissionInfo() throws Exception { 3497 PermissionInfo permissionInfo = new PermissionInfo(); 3498 permissionInfo.name = "some_name"; 3499 permissionInfo.group = "some_group"; 3500 shadowOf(packageManager).addPermissionInfo(permissionInfo); 3501 3502 List<PermissionInfo> permissions = 3503 packageManager.queryPermissionsByGroup(permissionInfo.group, 0); 3504 assertThat(permissions).hasSize(1); 3505 3506 assertThat(permissions.get(0).name).isEqualTo(permissionInfo.name); 3507 assertThat(permissions.get(0).group).isEqualTo(permissionInfo.group); 3508 } 3509 3510 @Test getDefaultActivityIcon()3511 public void getDefaultActivityIcon() { 3512 assertThat(packageManager.getDefaultActivityIcon()).isNotNull(); 3513 } 3514 3515 @Test addPackageShouldUseUidToProvidePackageName()3516 public void addPackageShouldUseUidToProvidePackageName() { 3517 PackageInfo packageInfoOne = new PackageInfo(); 3518 packageInfoOne.packageName = "package.one"; 3519 packageInfoOne.applicationInfo = new ApplicationInfo(); 3520 packageInfoOne.applicationInfo.uid = 1234; 3521 packageInfoOne.applicationInfo.packageName = packageInfoOne.packageName; 3522 shadowOf(packageManager).installPackage(packageInfoOne); 3523 3524 PackageInfo packageInfoTwo = new PackageInfo(); 3525 packageInfoTwo.packageName = "package.two"; 3526 packageInfoTwo.applicationInfo = new ApplicationInfo(); 3527 packageInfoTwo.applicationInfo.uid = 1234; 3528 packageInfoTwo.applicationInfo.packageName = packageInfoTwo.packageName; 3529 shadowOf(packageManager).installPackage(packageInfoTwo); 3530 3531 assertThat(packageManager.getPackagesForUid(1234)) 3532 .asList() 3533 .containsExactly("package.one", "package.two"); 3534 } 3535 3536 @Test installerPackageName()3537 public void installerPackageName() { 3538 packageManager.setInstallerPackageName("target.package", "installer.package"); 3539 3540 assertThat(packageManager.getInstallerPackageName("target.package")) 3541 .isEqualTo("installer.package"); 3542 } 3543 3544 @Test 3545 @GetInstallerPackageNameMode(Mode.LEGACY) installerPackageName_notInstalledAndLegacySettings()3546 public void installerPackageName_notInstalledAndLegacySettings() { 3547 String packageName = packageManager.getInstallerPackageName("target.package"); 3548 assertThat(packageName).isNull(); 3549 } 3550 3551 @Test 3552 @GetInstallerPackageNameMode(Mode.REALISTIC) installerPackageName_notInstalledAndRealisticSettings()3553 public void installerPackageName_notInstalledAndRealisticSettings() { 3554 try { 3555 packageManager.getInstallerPackageName("target.package"); 3556 fail("Exception expected"); 3557 } catch (IllegalArgumentException e) { 3558 assertThat(e).hasMessageThat().contains("target.package"); 3559 } 3560 } 3561 3562 @Test 3563 @GetInstallerPackageNameMode(Mode.REALISTIC) installerPackageName_uninstalledAndRealisticSettings()3564 public void installerPackageName_uninstalledAndRealisticSettings() { 3565 try { 3566 packageManager.setInstallerPackageName(context.getPackageName(), "installer.pkg"); 3567 shadowOf(packageManager).deletePackage(context.getPackageName()); 3568 packageManager.getInstallerPackageName(context.getPackageName()); 3569 fail("Exception expected"); 3570 } catch (IllegalArgumentException e) { 3571 assertThat(e).hasMessageThat().contains(context.getPackageName()); 3572 } 3573 } 3574 3575 @Test 3576 @Config(minSdk = VERSION_CODES.R) installerSourceInfo_setPackageNames()3577 public void installerSourceInfo_setPackageNames() throws Exception { 3578 shadowOf(packageManager) 3579 .setInstallSourceInfo("target.package", INITIATING_PACKAGE_NAME, INSTALLING_PACKAGE_NAME); 3580 3581 InstallSourceInfo info = packageManager.getInstallSourceInfo("target.package"); 3582 assertThat(info.getInitiatingPackageName()).isEqualTo(INITIATING_PACKAGE_NAME); 3583 assertThat(info.getInstallingPackageName()).isEqualTo(INSTALLING_PACKAGE_NAME); 3584 } 3585 3586 @Test 3587 @Config(minSdk = VERSION_CODES.UPSIDE_DOWN_CAKE) installerSourceInfo()3588 public void installerSourceInfo() throws Exception { 3589 shadowOf(packageManager) 3590 .setInstallSourceInfo( 3591 "target.package", 3592 INITIATING_PACKAGE_NAME, 3593 new SigningInfo(), 3594 ORIGINATING_PACKAGE_NAME, 3595 INSTALLING_PACKAGE_NAME, 3596 UPDATE_OWNER_PACKAGE_NAME, 3597 PackageInstaller.PACKAGE_SOURCE_STORE); 3598 3599 InstallSourceInfo info = packageManager.getInstallSourceInfo("target.package"); 3600 assertThat(info.getInitiatingPackageName()).isEqualTo(INITIATING_PACKAGE_NAME); 3601 assertThat(info.getInstallingPackageName()).isEqualTo(INSTALLING_PACKAGE_NAME); 3602 assertThat(info.getOriginatingPackageName()).isEqualTo(ORIGINATING_PACKAGE_NAME); 3603 assertThat(info.getUpdateOwnerPackageName()).isEqualTo(UPDATE_OWNER_PACKAGE_NAME); 3604 assertThat(info.getInitiatingPackageSigningInfo()).isNotNull(); 3605 assertThat(info.getPackageSource()).isEqualTo(PackageInstaller.PACKAGE_SOURCE_STORE); 3606 } 3607 3608 @Test 3609 @Config(minSdk = VERSION_CODES.R) getInstallerSourceInfo_notExists_throwsException()3610 public void getInstallerSourceInfo_notExists_throwsException() throws Exception { 3611 assertThrows( 3612 NameNotFoundException.class, 3613 () -> packageManager.getInstallSourceInfo("nonExistTarget.package")); 3614 } 3615 3616 @Test getXml()3617 public void getXml() { 3618 XmlResourceParser in = 3619 packageManager.getXml( 3620 context.getPackageName(), R.xml.dialog_preferences, context.getApplicationInfo()); 3621 assertThat(in).isNotNull(); 3622 } 3623 3624 @Test addPackageShouldNotCreateSessions()3625 public void addPackageShouldNotCreateSessions() { 3626 3627 PackageInfo packageInfo = new PackageInfo(); 3628 packageInfo.packageName = "test.package"; 3629 shadowOf(packageManager).installPackage(packageInfo); 3630 3631 assertThat(packageManager.getPackageInstaller().getAllSessions()).isEmpty(); 3632 } 3633 3634 @Test installPackage_defaults()3635 public void installPackage_defaults() { 3636 PackageInfo info = new PackageInfo(); 3637 info.packageName = "name"; 3638 info.activities = new ActivityInfo[] {new ActivityInfo()}; 3639 3640 shadowOf(packageManager).installPackage(info); 3641 3642 PackageInfo installed = shadowOf(packageManager).getInternalMutablePackageInfo("name"); 3643 ActivityInfo activity = installed.activities[0]; 3644 assertThat(installed.applicationInfo).isNotNull(); 3645 assertThat(installed.applicationInfo.packageName).isEqualTo("name"); 3646 assertWithMessage("%s is installed", installed.applicationInfo) 3647 .that((installed.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) 3648 .isTrue(); 3649 assertThat(activity.packageName).isEqualTo("name"); 3650 // this should be really equal in parcel sense as ApplicationInfo doesn't implement equals(). 3651 assertThat(activity.applicationInfo).isEqualTo(installed.applicationInfo); 3652 assertThat(installed.applicationInfo.processName).isEqualTo("name"); 3653 assertThat(activity.name).isNotEmpty(); 3654 } 3655 3656 @Test installPackage_platformPermission_throws()3657 public void installPackage_platformPermission_throws() { 3658 PackageInfo info = new PackageInfo(); 3659 info.packageName = "name"; 3660 info.activities = new ActivityInfo[] {new ActivityInfo()}; 3661 PermissionInfo permissionInfo = new PermissionInfo(); 3662 permissionInfo.name = READ_CONTACTS; 3663 info.permissions = new PermissionInfo[] {permissionInfo}; 3664 3665 try { 3666 shadowOf(packageManager).installPackage(info); 3667 fail("Exception expected"); 3668 } catch (IllegalArgumentException expected) { 3669 } 3670 } 3671 3672 @Test addPackageMultipleTimesShouldWork()3673 public void addPackageMultipleTimesShouldWork() { 3674 shadowOf(packageManager).addPackage("test.package"); 3675 3676 // Shouldn't throw exception 3677 shadowOf(packageManager).addPackage("test.package"); 3678 } 3679 3680 @Test addPackageSetsStorage()3681 public void addPackageSetsStorage() throws Exception { 3682 shadowOf(packageManager).addPackage("test.package"); 3683 3684 PackageInfo packageInfo = packageManager.getPackageInfo("test.package", 0); 3685 assertThat(packageInfo.applicationInfo.sourceDir).isNotNull(); 3686 assertThat(new File(packageInfo.applicationInfo.sourceDir).exists()).isTrue(); 3687 assertThat(packageInfo.applicationInfo.publicSourceDir) 3688 .isEqualTo(packageInfo.applicationInfo.sourceDir); 3689 } 3690 3691 @Test addComponent_noData()3692 public void addComponent_noData() { 3693 try { 3694 shadowOf(packageManager).addOrUpdateActivity(new ActivityInfo()); 3695 fail(); 3696 } catch (IllegalArgumentException e) { 3697 // should throw 3698 } 3699 } 3700 3701 @Test addActivity()3702 public void addActivity() throws Exception { 3703 ActivityInfo activityInfo = new ActivityInfo(); 3704 activityInfo.name = "name"; 3705 activityInfo.packageName = "package"; 3706 3707 shadowOf(packageManager).addOrUpdateActivity(activityInfo); 3708 3709 assertThat(packageManager.getActivityInfo(new ComponentName("package", "name"), 0)).isNotNull(); 3710 } 3711 3712 @Test addService()3713 public void addService() throws Exception { 3714 ServiceInfo serviceInfo = new ServiceInfo(); 3715 serviceInfo.name = "name"; 3716 serviceInfo.packageName = "package"; 3717 3718 shadowOf(packageManager).addOrUpdateService(serviceInfo); 3719 3720 assertThat(packageManager.getServiceInfo(new ComponentName("package", "name"), 0)).isNotNull(); 3721 } 3722 3723 @Test 3724 @Config(minSdk = TIRAMISU) addService_withComponentInfoFlags()3725 public void addService_withComponentInfoFlags() throws Exception { 3726 ServiceInfo serviceInfo = new ServiceInfo(); 3727 serviceInfo.name = "name"; 3728 serviceInfo.packageName = "package"; 3729 3730 shadowOf(packageManager).addOrUpdateService(serviceInfo); 3731 3732 assertThat( 3733 packageManager.getServiceInfo( 3734 new ComponentName("package", "name"), PackageManager.ComponentInfoFlags.of(0))) 3735 .isNotNull(); 3736 } 3737 3738 @Test addProvider()3739 public void addProvider() throws Exception { 3740 ProviderInfo providerInfo = new ProviderInfo(); 3741 providerInfo.name = "name"; 3742 providerInfo.packageName = "package"; 3743 3744 shadowOf(packageManager).addOrUpdateProvider(providerInfo); 3745 3746 assertThat(packageManager.getProviderInfo(new ComponentName("package", "name"), 0)).isNotNull(); 3747 } 3748 3749 @Test addReceiver()3750 public void addReceiver() throws Exception { 3751 ActivityInfo receiverInfo = new ActivityInfo(); 3752 receiverInfo.name = "name"; 3753 receiverInfo.packageName = "package"; 3754 3755 shadowOf(packageManager).addOrUpdateReceiver(receiverInfo); 3756 3757 assertThat(packageManager.getReceiverInfo(new ComponentName("package", "name"), 0)).isNotNull(); 3758 } 3759 3760 @Test 3761 @Config(minSdk = TIRAMISU) addReceiver_withComponentInfoFlags()3762 public void addReceiver_withComponentInfoFlags() throws Exception { 3763 ActivityInfo receiverInfo = new ActivityInfo(); 3764 receiverInfo.name = "name"; 3765 receiverInfo.packageName = "package"; 3766 3767 shadowOf(packageManager).addOrUpdateReceiver(receiverInfo); 3768 3769 assertThat( 3770 packageManager.getReceiverInfo( 3771 new ComponentName("package", "name"), PackageManager.ComponentInfoFlags.of(0))) 3772 .isNotNull(); 3773 } 3774 3775 @Test addActivity_addsNewPackage()3776 public void addActivity_addsNewPackage() throws Exception { 3777 ActivityInfo activityInfo = new ActivityInfo(); 3778 activityInfo.name = "name"; 3779 activityInfo.packageName = "package"; 3780 3781 shadowOf(packageManager).addOrUpdateActivity(activityInfo); 3782 PackageInfo packageInfo = 3783 packageManager.getPackageInfo("package", PackageManager.GET_ACTIVITIES); 3784 3785 assertThat(packageInfo.packageName).isEqualTo("package"); 3786 assertThat(packageInfo.applicationInfo.packageName).isEqualTo("package"); 3787 assertWithMessage("applicationInfo is installed") 3788 .that((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) 3789 .isTrue(); 3790 assertThat(packageInfo.activities).hasLength(1); 3791 ActivityInfo addedInfo = packageInfo.activities[0]; 3792 assertThat(addedInfo.name).isEqualTo("name"); 3793 assertThat(addedInfo.applicationInfo).isNotNull(); 3794 assertThat(addedInfo.applicationInfo.packageName).isEqualTo("package"); 3795 } 3796 3797 @Test addActivity_usesExistingPackage()3798 public void addActivity_usesExistingPackage() throws Exception { 3799 String packageName = context.getPackageName(); 3800 int originalActivitiesCount = 3801 packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).activities.length; 3802 ActivityInfo activityInfo = new ActivityInfo(); 3803 activityInfo.name = "name"; 3804 activityInfo.packageName = packageName; 3805 3806 shadowOf(packageManager).addOrUpdateActivity(activityInfo); 3807 PackageInfo packageInfo = 3808 packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); 3809 3810 assertThat(packageInfo.activities).hasLength(originalActivitiesCount + 1); 3811 ActivityInfo addedInfo = packageInfo.activities[originalActivitiesCount]; 3812 assertThat(addedInfo.name).isEqualTo("name"); 3813 assertThat(addedInfo.applicationInfo).isNotNull(); 3814 assertThat(addedInfo.applicationInfo.packageName).isEqualTo(packageName); 3815 } 3816 3817 @Test removeActivity()3818 public void removeActivity() { 3819 ComponentName componentName = 3820 new ComponentName(context, "org.robolectric.shadows.TestActivity"); 3821 3822 ActivityInfo removed = shadowOf(packageManager).removeActivity(componentName); 3823 3824 assertThat(removed).isNotNull(); 3825 try { 3826 packageManager.getActivityInfo(componentName, 0); 3827 // for now it goes here because package manager autocreates activities... 3828 // fail(); 3829 } catch (NameNotFoundException e) { 3830 // expected 3831 } 3832 } 3833 3834 @Test removeService()3835 public void removeService() { 3836 ComponentName componentName = new ComponentName(context, "com.foo.Service"); 3837 3838 ServiceInfo removed = shadowOf(packageManager).removeService(componentName); 3839 3840 assertThat(removed).isNotNull(); 3841 try { 3842 packageManager.getServiceInfo(componentName, 0); 3843 fail(); 3844 } catch (NameNotFoundException e) { 3845 // expected 3846 } 3847 } 3848 3849 @Test 3850 @Config(minSdk = TIRAMISU) removeService_withComponentInfoFlags()3851 public void removeService_withComponentInfoFlags() { 3852 ComponentName componentName = new ComponentName(context, "com.foo.Service"); 3853 3854 ServiceInfo removed = shadowOf(packageManager).removeService(componentName); 3855 3856 assertThat(removed).isNotNull(); 3857 try { 3858 packageManager.getServiceInfo(componentName, PackageManager.ComponentInfoFlags.of(0)); 3859 fail(); 3860 } catch (NameNotFoundException e) { 3861 // expected 3862 } 3863 } 3864 3865 @Test removeProvider()3866 public void removeProvider() { 3867 ComponentName componentName = 3868 new ComponentName(context, "org.robolectric.shadows.testing.TestContentProvider1"); 3869 3870 ProviderInfo removed = shadowOf(packageManager).removeProvider(componentName); 3871 3872 assertThat(removed).isNotNull(); 3873 try { 3874 packageManager.getProviderInfo(componentName, 0); 3875 fail(); 3876 } catch (NameNotFoundException e) { 3877 // expected 3878 } 3879 } 3880 3881 @Test removeReceiver()3882 public void removeReceiver() { 3883 ComponentName componentName = 3884 new ComponentName(context, "org.robolectric.fakes.ConfigTestReceiver"); 3885 3886 ActivityInfo removed = shadowOf(packageManager).removeReceiver(componentName); 3887 3888 assertThat(removed).isNotNull(); 3889 try { 3890 packageManager.getReceiverInfo(componentName, 0); 3891 fail(); 3892 } catch (NameNotFoundException e) { 3893 // expected 3894 } 3895 } 3896 3897 @Test 3898 @Config(minSdk = TIRAMISU) removeReceiver_withComponentInfoFlags()3899 public void removeReceiver_withComponentInfoFlags() { 3900 ComponentName componentName = 3901 new ComponentName(context, "org.robolectric.fakes.ConfigTestReceiver"); 3902 3903 ActivityInfo removed = shadowOf(packageManager).removeReceiver(componentName); 3904 3905 assertThat(removed).isNotNull(); 3906 try { 3907 packageManager.getReceiverInfo(componentName, PackageManager.ComponentInfoFlags.of(0)); 3908 fail(); 3909 } catch (NameNotFoundException e) { 3910 // expected 3911 } 3912 } 3913 3914 @Test removeNonExistingComponent()3915 public void removeNonExistingComponent() { 3916 ComponentName componentName = new ComponentName(context, "org.robolectric.DoesnExist"); 3917 3918 ActivityInfo removed = shadowOf(packageManager).removeReceiver(componentName); 3919 3920 assertThat(removed).isNull(); 3921 } 3922 3923 @Test deletePackage()3924 public void deletePackage() throws Exception { 3925 // Apps must have the android.permission.DELETE_PACKAGES set to delete packages. 3926 PackageManager packageManager = context.getPackageManager(); 3927 shadowOf(packageManager) 3928 .getInternalMutablePackageInfo(context.getPackageName()) 3929 .requestedPermissions = 3930 new String[] {android.Manifest.permission.DELETE_PACKAGES}; 3931 3932 PackageInfo packageInfo = new PackageInfo(); 3933 packageInfo.packageName = "test.package"; 3934 shadowOf(packageManager).installPackage(packageInfo); 3935 3936 IPackageDeleteObserver mockObserver = mock(IPackageDeleteObserver.class); 3937 packageManager.deletePackage(packageInfo.packageName, mockObserver, 0); 3938 3939 shadowOf(packageManager).doPendingUninstallCallbacks(); 3940 3941 assertThat(shadowOf(packageManager).getDeletedPackages()).contains(packageInfo.packageName); 3942 verify(mockObserver).packageDeleted(packageInfo.packageName, PackageManager.DELETE_SUCCEEDED); 3943 } 3944 3945 @Test deletePackage_missingRequiredPermission()3946 public void deletePackage_missingRequiredPermission() throws Exception { 3947 PackageInfo packageInfo = new PackageInfo(); 3948 packageInfo.packageName = "test.package"; 3949 shadowOf(packageManager).installPackage(packageInfo); 3950 3951 IPackageDeleteObserver mockObserver = mock(IPackageDeleteObserver.class); 3952 packageManager.deletePackage(packageInfo.packageName, mockObserver, 0); 3953 3954 shadowOf(packageManager).doPendingUninstallCallbacks(); 3955 3956 assertThat(shadowOf(packageManager).getDeletedPackages()).hasSize(0); 3957 verify(mockObserver) 3958 .packageDeleted(packageInfo.packageName, PackageManager.DELETE_FAILED_INTERNAL_ERROR); 3959 } 3960 3961 private static class ActivityWithFilters extends Activity {} 3962 3963 @Test getIntentFiltersForComponent()3964 public void getIntentFiltersForComponent() throws Exception { 3965 List<IntentFilter> intentFilters = 3966 shadowOf(packageManager) 3967 .getIntentFiltersForActivity(new ComponentName(context, ActivityWithFilters.class)); 3968 assertThat(intentFilters).hasSize(1); 3969 IntentFilter intentFilter = intentFilters.get(0); 3970 assertThat(intentFilter.getCategory(0)).isEqualTo(Intent.CATEGORY_DEFAULT); 3971 assertThat(intentFilter.getAction(0)).isEqualTo(Intent.ACTION_VIEW); 3972 assertThat(intentFilter.getDataPath(0).getPath()).isEqualTo("/testPath/test.jpeg"); 3973 } 3974 3975 @Test getPackageInfo_shouldHaveWritableDataDirs()3976 public void getPackageInfo_shouldHaveWritableDataDirs() throws Exception { 3977 PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); 3978 3979 File dataDir = new File(packageInfo.applicationInfo.dataDir); 3980 assertThat(dataDir.isDirectory()).isTrue(); 3981 assertThat(dataDir.exists()).isTrue(); 3982 } 3983 3984 @Test getApplicationHiddenSettingAsUser_hidden()3985 public void getApplicationHiddenSettingAsUser_hidden() { 3986 String packageName = context.getPackageName(); 3987 3988 packageManager.setApplicationHiddenSettingAsUser( 3989 packageName, /* hidden= */ true, /* user= */ null); 3990 3991 assertThat(packageManager.getApplicationHiddenSettingAsUser(packageName, /* user= */ null)) 3992 .isTrue(); 3993 } 3994 3995 @Test getApplicationHiddenSettingAsUser_notHidden()3996 public void getApplicationHiddenSettingAsUser_notHidden() { 3997 String packageName = context.getPackageName(); 3998 3999 assertThat(packageManager.getApplicationHiddenSettingAsUser(packageName, /* user= */ null)) 4000 .isFalse(); 4001 } 4002 4003 @Test getApplicationHiddenSettingAsUser_unknownPackage()4004 public void getApplicationHiddenSettingAsUser_unknownPackage() { 4005 assertThat(packageManager.getApplicationHiddenSettingAsUser("not.a.package", /* user= */ null)) 4006 .isTrue(); 4007 } 4008 4009 @Test setApplicationHiddenSettingAsUser_includeUninstalled()4010 public void setApplicationHiddenSettingAsUser_includeUninstalled() throws Exception { 4011 String packageName = context.getPackageName(); 4012 4013 packageManager.setApplicationHiddenSettingAsUser( 4014 packageName, /* hidden= */ true, /* user= */ null); 4015 4016 assertThat(packageManager.getPackageInfo(packageName, MATCH_UNINSTALLED_PACKAGES)).isNotNull(); 4017 assertThat(packageManager.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES)) 4018 .isNotNull(); 4019 List<PackageInfo> installedPackages = 4020 packageManager.getInstalledPackages(MATCH_UNINSTALLED_PACKAGES); 4021 assertThat(installedPackages).hasSize(1); 4022 assertThat(installedPackages.get(0).packageName).isEqualTo(packageName); 4023 } 4024 4025 @Test setApplicationHiddenSettingAsUser_dontIncludeUninstalled()4026 public void setApplicationHiddenSettingAsUser_dontIncludeUninstalled() { 4027 String packageName = context.getPackageName(); 4028 4029 boolean success = 4030 packageManager.setApplicationHiddenSettingAsUser( 4031 packageName, /* hidden= */ true, /* user= */ null); 4032 4033 assertThat(success).isTrue(); 4034 4035 try { 4036 PackageInfo info = packageManager.getPackageInfo(packageName, /* flags= */ 0); 4037 fail( 4038 "PackageManager.NameNotFoundException not thrown. Returned app with flags: " 4039 + info.applicationInfo.flags); 4040 } catch (NameNotFoundException e) { 4041 // Expected 4042 } 4043 4044 try { 4045 packageManager.getApplicationInfo(packageName, /* flags= */ 0); 4046 fail("PackageManager.NameNotFoundException not thrown"); 4047 } catch (NameNotFoundException e) { 4048 // Expected 4049 } 4050 4051 assertThat(packageManager.getInstalledPackages(/* flags= */ 0)).isEmpty(); 4052 } 4053 4054 @Test 4055 @Config(minSdk = LOLLIPOP_MR1) setUnbadgedApplicationIcon()4056 public void setUnbadgedApplicationIcon() throws Exception { 4057 String packageName = context.getPackageName(); 4058 Drawable d = new BitmapDrawable(); 4059 4060 shadowOf(packageManager).setUnbadgedApplicationIcon(packageName, d); 4061 4062 assertThat( 4063 packageManager 4064 .getApplicationInfo(packageName, PackageManager.GET_SHARED_LIBRARY_FILES) 4065 .loadUnbadgedIcon(packageManager)) 4066 .isSameInstanceAs(d); 4067 } 4068 4069 @Test 4070 @Config(minSdk = android.os.Build.VERSION_CODES.P) isPackageSuspended_nonExistentPackage_shouldThrow()4071 public void isPackageSuspended_nonExistentPackage_shouldThrow() { 4072 try { 4073 packageManager.isPackageSuspended(TEST_PACKAGE_NAME); 4074 fail("Should have thrown NameNotFoundException"); 4075 } catch (Exception expected) { 4076 // The compiler thinks that isPackageSuspended doesn't throw NameNotFoundException because the 4077 // test is compiled against the publicly released SDK. 4078 assertThat(expected).isInstanceOf(NameNotFoundException.class); 4079 } 4080 } 4081 4082 @Test 4083 @Config(minSdk = android.os.Build.VERSION_CODES.P) isPackageSuspended_callersPackage_shouldReturnFalse()4084 public void isPackageSuspended_callersPackage_shouldReturnFalse() throws NameNotFoundException { 4085 assertThat(packageManager.isPackageSuspended(context.getPackageName())).isFalse(); 4086 } 4087 4088 @Test 4089 @Config(minSdk = android.os.Build.VERSION_CODES.P) isPackageSuspended_installedNeverSuspendedPackage_shouldReturnFalse()4090 public void isPackageSuspended_installedNeverSuspendedPackage_shouldReturnFalse() 4091 throws NameNotFoundException { 4092 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4093 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isFalse(); 4094 } 4095 4096 @Test 4097 @Config(minSdk = android.os.Build.VERSION_CODES.P) isPackageSuspended_installedSuspendedPackage_shouldReturnTrue()4098 public void isPackageSuspended_installedSuspendedPackage_shouldReturnTrue() 4099 throws NameNotFoundException { 4100 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4101 setPackagesSuspended( 4102 new String[] {TEST_PACKAGE_NAME}, 4103 /* suspended= */ true, 4104 /* appExtras= */ null, 4105 /* launcherExtras= */ null, 4106 /* dialogMessage= */ (String) null); 4107 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isTrue(); 4108 } 4109 4110 @Test 4111 @Config(minSdk = android.os.Build.VERSION_CODES.Q) isPackageSuspended_installedSuspendedPackage_suspendDialogInfo_shouldReturnTrue()4112 public void isPackageSuspended_installedSuspendedPackage_suspendDialogInfo_shouldReturnTrue() 4113 throws NameNotFoundException { 4114 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4115 packageManager.setPackagesSuspended( 4116 new String[] {TEST_PACKAGE_NAME}, 4117 /* suspended= */ true, 4118 /* appExtras= */ null, 4119 /* launcherExtras= */ null, 4120 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4121 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isTrue(); 4122 } 4123 4124 @Test 4125 @Config(minSdk = android.os.Build.VERSION_CODES.P) isPackageSuspended_installedUnsuspendedPackage_shouldReturnFalse()4126 public void isPackageSuspended_installedUnsuspendedPackage_shouldReturnFalse() 4127 throws NameNotFoundException { 4128 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4129 setPackagesSuspended( 4130 new String[] {TEST_PACKAGE_NAME}, 4131 /* suspended= */ true, 4132 /* appExtras= */ null, 4133 /* launcherExtras= */ null, 4134 /* dialogMessage= */ (String) null); 4135 setPackagesSuspended( 4136 new String[] {TEST_PACKAGE_NAME}, 4137 /* suspended= */ false, 4138 /* appExtras= */ null, 4139 /* launcherExtras= */ null, 4140 /* dialogMessage= */ (String) null); 4141 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isFalse(); 4142 } 4143 4144 @Test 4145 @Config(minSdk = android.os.Build.VERSION_CODES.Q) isPackageSuspended_installedUnsuspendedPackage_suspendDialogInfo_shouldReturnFalse()4146 public void isPackageSuspended_installedUnsuspendedPackage_suspendDialogInfo_shouldReturnFalse() 4147 throws NameNotFoundException { 4148 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4149 packageManager.setPackagesSuspended( 4150 new String[] {TEST_PACKAGE_NAME}, 4151 /* suspended= */ true, 4152 /* appExtras= */ null, 4153 /* launcherExtras= */ null, 4154 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4155 packageManager.setPackagesSuspended( 4156 new String[] {TEST_PACKAGE_NAME}, 4157 /* suspended= */ false, 4158 /* appExtras= */ null, 4159 /* launcherExtras= */ null, 4160 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4161 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isFalse(); 4162 } 4163 4164 @Test 4165 @Config(minSdk = android.os.Build.VERSION_CODES.P) setPackagesSuspended_withProfileOwner_shouldThrow()4166 public void setPackagesSuspended_withProfileOwner_shouldThrow() { 4167 DevicePolicyManager devicePolicyManager = 4168 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 4169 shadowOf(devicePolicyManager) 4170 .setProfileOwner(new ComponentName("com.profile.owner", "ProfileOwnerClass")); 4171 try { 4172 setPackagesSuspended( 4173 new String[] {TEST_PACKAGE_NAME}, 4174 /* suspended= */ true, 4175 /* appExtras= */ null, 4176 /* launcherExtras= */ null, 4177 /* dialogMessage= */ (String) null); 4178 fail("Should have thrown UnsupportedOperationException"); 4179 } catch (UnsupportedOperationException expected) { 4180 } 4181 } 4182 4183 @Test 4184 @Config(minSdk = android.os.Build.VERSION_CODES.Q) setPackagesSuspended_withProfileOwner_suspendDialogInfo_shouldThrow()4185 public void setPackagesSuspended_withProfileOwner_suspendDialogInfo_shouldThrow() { 4186 DevicePolicyManager devicePolicyManager = 4187 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 4188 shadowOf(devicePolicyManager) 4189 .setProfileOwner(new ComponentName("com.profile.owner", "ProfileOwnerClass")); 4190 try { 4191 packageManager.setPackagesSuspended( 4192 new String[] {TEST_PACKAGE_NAME}, 4193 /* suspended= */ true, 4194 /* appExtras= */ null, 4195 /* launcherExtras= */ null, 4196 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4197 fail("Should have thrown UnsupportedOperationException"); 4198 } catch (UnsupportedOperationException expected) { 4199 } 4200 } 4201 4202 @Test 4203 @Config(minSdk = android.os.Build.VERSION_CODES.Q) setPackagesSuspended_isProfileOwner_suspendDialogInfo()4204 public void setPackagesSuspended_isProfileOwner_suspendDialogInfo() throws NameNotFoundException { 4205 DevicePolicyManager devicePolicyManager = 4206 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 4207 String packageName = context.getPackageName(); 4208 ComponentName componentName = 4209 new ComponentName(packageName, ActivityWithFilters.class.getName()); 4210 shadowOf(devicePolicyManager).setProfileOwner(componentName); 4211 4212 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4213 packageManager.setPackagesSuspended( 4214 new String[] {TEST_PACKAGE_NAME}, 4215 /* suspended= */ true, 4216 /* appExtras= */ null, 4217 /* launcherExtras= */ null, 4218 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4219 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isTrue(); 4220 } 4221 4222 @Test 4223 @Config(minSdk = android.os.Build.VERSION_CODES.P) setPackagesSuspended_withDeviceOwner_shouldThrow()4224 public void setPackagesSuspended_withDeviceOwner_shouldThrow() { 4225 DevicePolicyManager devicePolicyManager = 4226 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 4227 shadowOf(devicePolicyManager) 4228 .setDeviceOwner(new ComponentName("com.device.owner", "DeviceOwnerClass")); 4229 // Robolectric uses a random UID (see ShadowProcess#getRandomApplicationUid) that falls within 4230 // the range of the system user, so the device owner is on the current user and hence apps 4231 // cannot be suspended. 4232 try { 4233 setPackagesSuspended( 4234 new String[] {TEST_PACKAGE_NAME}, 4235 /* suspended= */ true, 4236 /* appExtras= */ null, 4237 /* launcherExtras= */ null, 4238 /* dialogMessage= */ (String) null); 4239 fail("Should have thrown UnsupportedOperationException"); 4240 } catch (UnsupportedOperationException expected) { 4241 } 4242 } 4243 4244 @Test 4245 @Config(minSdk = android.os.Build.VERSION_CODES.Q) setPackagesSuspended_withDeviceOwner_suspendDialogInfo_shouldThrow()4246 public void setPackagesSuspended_withDeviceOwner_suspendDialogInfo_shouldThrow() { 4247 DevicePolicyManager devicePolicyManager = 4248 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 4249 shadowOf(devicePolicyManager) 4250 .setDeviceOwner(new ComponentName("com.device.owner", "DeviceOwnerClass")); 4251 // Robolectric uses a random UID (see ShadowProcess#getRandomApplicationUid) that falls within 4252 // the range of the system user, so the device owner is on the current user and hence apps 4253 // cannot be suspended. 4254 try { 4255 packageManager.setPackagesSuspended( 4256 new String[] {TEST_PACKAGE_NAME}, 4257 /* suspended= */ true, 4258 /* appExtras= */ null, 4259 /* launcherExtras= */ null, 4260 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4261 fail("Should have thrown UnsupportedOperationException"); 4262 } catch (UnsupportedOperationException expected) { 4263 } 4264 } 4265 4266 @Test 4267 @Config(minSdk = android.os.Build.VERSION_CODES.Q) setPackagesSuspended_isDeviceOwner_suspendDialogInfo()4268 public void setPackagesSuspended_isDeviceOwner_suspendDialogInfo() throws NameNotFoundException { 4269 DevicePolicyManager devicePolicyManager = 4270 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 4271 String packageName = context.getPackageName(); 4272 ComponentName componentName = 4273 new ComponentName(packageName, ActivityWithFilters.class.getName()); 4274 shadowOf(devicePolicyManager).setDeviceOwner(componentName); 4275 4276 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4277 packageManager.setPackagesSuspended( 4278 new String[] {TEST_PACKAGE_NAME}, 4279 /* suspended= */ true, 4280 /* appExtras= */ null, 4281 /* launcherExtras= */ null, 4282 /* suspendDialogInfo= */ (SuspendDialogInfo) null); 4283 assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isTrue(); 4284 } 4285 4286 @Test 4287 @Config(minSdk = android.os.Build.VERSION_CODES.P) setPackagesSuspended_shouldSuspendSuspendablePackagesAndReturnTheRest()4288 public void setPackagesSuspended_shouldSuspendSuspendablePackagesAndReturnTheRest() 4289 throws NameNotFoundException { 4290 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName("android")); 4291 shadowOf(packageManager) 4292 .installPackage(createPackageInfoWithPackageName("com.suspendable.package1")); 4293 shadowOf(packageManager) 4294 .installPackage(createPackageInfoWithPackageName("com.suspendable.package2")); 4295 4296 assertThat( 4297 setPackagesSuspended( 4298 new String[] { 4299 "com.nonexistent.package", // Unsuspenable (app doesn't exist). 4300 "com.suspendable.package1", 4301 "android", // Unsuspendable (platform package). 4302 "com.suspendable.package2", 4303 context.getPackageName() // Unsuspendable (caller's package). 4304 }, 4305 /* suspended= */ true, 4306 /* appExtras= */ null, 4307 /* launcherExtras= */ null, 4308 /* dialogMessage= */ (String) null)) 4309 .asList() 4310 .containsExactly("com.nonexistent.package", "android", context.getPackageName()); 4311 4312 assertThat(packageManager.isPackageSuspended("com.suspendable.package1")).isTrue(); 4313 assertThat(packageManager.isPackageSuspended("android")).isFalse(); 4314 assertThat(packageManager.isPackageSuspended("com.suspendable.package2")).isTrue(); 4315 assertThat(packageManager.isPackageSuspended(context.getPackageName())).isFalse(); 4316 } 4317 4318 @Test 4319 @Config(minSdk = android.os.Build.VERSION_CODES.Q) 4320 public void setPackagesSuspended_suspendDialogInfo_shouldSuspendSuspendablePackagesAndReturnTheRest()4321 setPackagesSuspended_suspendDialogInfo_shouldSuspendSuspendablePackagesAndReturnTheRest() 4322 throws NameNotFoundException { 4323 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName("android")); 4324 shadowOf(packageManager) 4325 .installPackage(createPackageInfoWithPackageName("com.suspendable.package1")); 4326 shadowOf(packageManager) 4327 .installPackage(createPackageInfoWithPackageName("com.suspendable.package2")); 4328 4329 assertThat( 4330 packageManager.setPackagesSuspended( 4331 new String[] { 4332 "com.nonexistent.package", // Unsuspenable (app doesn't exist). 4333 "com.suspendable.package1", 4334 "android", // Unsuspendable (platform package). 4335 "com.suspendable.package2", 4336 context.getPackageName() // Unsuspendable (caller's package). 4337 }, 4338 /* suspended= */ true, 4339 /* appExtras= */ null, 4340 /* launcherExtras= */ null, 4341 /* suspendDialogInfo= */ (SuspendDialogInfo) null)) 4342 .asList() 4343 .containsExactly("com.nonexistent.package", "android", context.getPackageName()); 4344 4345 assertThat(packageManager.isPackageSuspended("com.suspendable.package1")).isTrue(); 4346 assertThat(packageManager.isPackageSuspended("android")).isFalse(); 4347 assertThat(packageManager.isPackageSuspended("com.suspendable.package2")).isTrue(); 4348 assertThat(packageManager.isPackageSuspended(context.getPackageName())).isFalse(); 4349 } 4350 4351 @Test(expected = SecurityException.class) 4352 @Config(minSdk = android.os.Build.VERSION_CODES.Q) getUnsuspendablePackages_withoutSuspendAppsPermission_shouldThrow()4353 public void getUnsuspendablePackages_withoutSuspendAppsPermission_shouldThrow() { 4354 shadowOf(ApplicationProvider.<Application>getApplicationContext()) 4355 .denyPermissions(SUSPEND_APPS); 4356 4357 packageManager.getUnsuspendablePackages(new String[] {TEST_PACKAGE_NAME}); 4358 } 4359 4360 @Test 4361 @Config(minSdk = android.os.Build.VERSION_CODES.Q) getUnsuspendablePackages_allPackagesSuspendable_shouldReturnEmpty()4362 public void getUnsuspendablePackages_allPackagesSuspendable_shouldReturnEmpty() { 4363 shadowOf(ApplicationProvider.<Application>getApplicationContext()) 4364 .grantPermissions(SUSPEND_APPS); 4365 4366 assertThat(packageManager.getUnsuspendablePackages(new String[] {TEST_PACKAGE_NAME})).isEmpty(); 4367 } 4368 4369 @Test 4370 @Config(minSdk = android.os.Build.VERSION_CODES.Q) 4371 public void getUnsuspendablePackages_somePackagesSuspendableAndSomeNot_shouldReturnUnsuspendablePackages()4372 getUnsuspendablePackages_somePackagesSuspendableAndSomeNot_shouldReturnUnsuspendablePackages() { 4373 String dialerPackage = "dialer"; 4374 String platformPackage = "android"; 4375 shadowOf((Application) context).grantPermissions(SUSPEND_APPS); 4376 shadowOf(context.getSystemService(TelecomManager.class)).setDefaultDialerPackage(dialerPackage); 4377 4378 assertThat( 4379 packageManager.getUnsuspendablePackages( 4380 new String[] { 4381 "some.suspendable.app", 4382 dialerPackage, 4383 "some.other.suspendable.app", 4384 platformPackage 4385 })) 4386 .asList() 4387 .containsExactly(dialerPackage, platformPackage); 4388 } 4389 4390 @Test 4391 @Config(minSdk = android.os.Build.VERSION_CODES.O) getChangedPackages_negativeSequenceNumber_returnsNull()4392 public void getChangedPackages_negativeSequenceNumber_returnsNull() { 4393 shadowOf(packageManager).addChangedPackage(-5, TEST_PACKAGE_NAME); 4394 4395 assertThat(packageManager.getChangedPackages(-5)).isNull(); 4396 } 4397 4398 @Test 4399 @Config(minSdk = android.os.Build.VERSION_CODES.O) getChangedPackages_validSequenceNumber_withChangedPackages()4400 public void getChangedPackages_validSequenceNumber_withChangedPackages() { 4401 shadowOf(packageManager).addChangedPackage(0, TEST_PACKAGE_NAME); 4402 shadowOf(packageManager).addChangedPackage(0, TEST_PACKAGE2_NAME); 4403 shadowOf(packageManager).addChangedPackage(1, "appPackageName"); 4404 4405 ChangedPackages changedPackages = packageManager.getChangedPackages(0); 4406 assertThat(changedPackages.getSequenceNumber()).isEqualTo(1); 4407 assertThat(changedPackages.getPackageNames()) 4408 .containsExactly(TEST_PACKAGE_NAME, TEST_PACKAGE2_NAME); 4409 } 4410 4411 @Test 4412 @Config(minSdk = android.os.Build.VERSION_CODES.O) getChangedPackages_validSequenceNumber_noChangedPackages()4413 public void getChangedPackages_validSequenceNumber_noChangedPackages() { 4414 assertThat(packageManager.getChangedPackages(0)).isNull(); 4415 } 4416 4417 @Test 4418 @Config(minSdk = android.os.Build.VERSION_CODES.P) setPackagesSuspended_shouldUnsuspendSuspendablePackagesAndReturnTheRest()4419 public void setPackagesSuspended_shouldUnsuspendSuspendablePackagesAndReturnTheRest() 4420 throws NameNotFoundException { 4421 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName("android")); 4422 shadowOf(packageManager) 4423 .installPackage(createPackageInfoWithPackageName("com.suspendable.package1")); 4424 shadowOf(packageManager) 4425 .installPackage(createPackageInfoWithPackageName("com.suspendable.package2")); 4426 setPackagesSuspended( 4427 new String[] { 4428 "com.suspendable.package1", "com.suspendable.package2", 4429 }, 4430 /* suspended= */ false, 4431 /* appExtras= */ null, 4432 /* launcherExtras= */ null, 4433 /* dialogMessage= */ (String) null); 4434 4435 assertThat( 4436 setPackagesSuspended( 4437 new String[] { 4438 "com.nonexistent.package", // Unsuspenable (app doesn't exist). 4439 "com.suspendable.package1", 4440 "android", // Unsuspendable (platform package). 4441 "com.suspendable.package2", 4442 context.getPackageName() // Unsuspendable (caller's package). 4443 }, 4444 /* suspended= */ false, 4445 /* appExtras= */ null, 4446 /* launcherExtras= */ null, 4447 /* dialogMessage= */ (String) null)) 4448 .asList() 4449 .containsExactly("com.nonexistent.package", "android", context.getPackageName()); 4450 4451 assertThat(packageManager.isPackageSuspended("com.suspendable.package1")).isFalse(); 4452 assertThat(packageManager.isPackageSuspended("android")).isFalse(); 4453 assertThat(packageManager.isPackageSuspended("com.suspendable.package2")).isFalse(); 4454 assertThat(packageManager.isPackageSuspended(context.getPackageName())).isFalse(); 4455 } 4456 4457 @Test 4458 @Config(minSdk = android.os.Build.VERSION_CODES.P) getPackageSetting_nonExistentPackage_shouldReturnNull()4459 public void getPackageSetting_nonExistentPackage_shouldReturnNull() { 4460 assertThat(shadowOf(packageManager).getPackageSetting(TEST_PACKAGE_NAME)).isNull(); 4461 } 4462 4463 @Test 4464 @Config(minSdk = android.os.Build.VERSION_CODES.P) getPackageSetting_removedPackage_shouldReturnNull()4465 public void getPackageSetting_removedPackage_shouldReturnNull() { 4466 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4467 shadowOf(packageManager).removePackage(TEST_PACKAGE_NAME); 4468 4469 assertThat(shadowOf(packageManager).getPackageSetting(TEST_PACKAGE_NAME)).isNull(); 4470 } 4471 4472 @Test 4473 @Config(minSdk = android.os.Build.VERSION_CODES.P) getPackageSetting_installedNeverSuspendedPackage_shouldReturnUnsuspendedSetting()4474 public void getPackageSetting_installedNeverSuspendedPackage_shouldReturnUnsuspendedSetting() { 4475 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4476 4477 PackageSetting setting = shadowOf(packageManager).getPackageSetting(TEST_PACKAGE_NAME); 4478 4479 assertThat(setting.isSuspended()).isFalse(); 4480 assertThat(setting.getDialogMessage()).isNull(); 4481 assertThat(setting.getSuspendedAppExtras()).isNull(); 4482 assertThat(setting.getSuspendedLauncherExtras()).isNull(); 4483 } 4484 4485 @Test 4486 @Config(minSdk = android.os.Build.VERSION_CODES.P) getPackageSetting_installedSuspendedPackage_shouldReturnSuspendedSetting()4487 public void getPackageSetting_installedSuspendedPackage_shouldReturnSuspendedSetting() { 4488 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4489 PersistableBundle appExtras = new PersistableBundle(); 4490 appExtras.putString("key", "value"); 4491 PersistableBundle launcherExtras = new PersistableBundle(); 4492 launcherExtras.putInt("number", 7); 4493 setPackagesSuspended( 4494 new String[] {TEST_PACKAGE_NAME}, true, appExtras, launcherExtras, "Dialog message"); 4495 4496 PackageSetting setting = shadowOf(packageManager).getPackageSetting(TEST_PACKAGE_NAME); 4497 4498 assertThat(setting.isSuspended()).isTrue(); 4499 assertThat(setting.getDialogMessage()).isEqualTo("Dialog message"); 4500 assertThat(setting.getSuspendedAppExtras().getString("key")).isEqualTo("value"); 4501 assertThat(setting.getSuspendedLauncherExtras().getInt("number")).isEqualTo(7); 4502 } 4503 4504 @Test 4505 @Config(minSdk = android.os.Build.VERSION_CODES.Q) 4506 public void getPackageSetting_installedSuspendedPackage_dialogInfo_shouldReturnSuspendedSetting()4507 getPackageSetting_installedSuspendedPackage_dialogInfo_shouldReturnSuspendedSetting() { 4508 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4509 PersistableBundle appExtras = new PersistableBundle(); 4510 appExtras.putString("key", "value"); 4511 PersistableBundle launcherExtras = new PersistableBundle(); 4512 launcherExtras.putInt("number", 7); 4513 SuspendDialogInfo suspendDialogInfo = 4514 new SuspendDialogInfo.Builder() 4515 .setIcon(R.drawable.an_image) 4516 .setMessage("Dialog message") 4517 .setTitle(R.string.greeting) 4518 .setNeutralButtonText(R.string.copy) 4519 .build(); 4520 4521 packageManager.setPackagesSuspended( 4522 new String[] {TEST_PACKAGE_NAME}, true, appExtras, launcherExtras, suspendDialogInfo); 4523 4524 PackageSetting setting = shadowOf(packageManager).getPackageSetting(TEST_PACKAGE_NAME); 4525 4526 assertThat(setting.isSuspended()).isTrue(); 4527 assertThat(setting.getDialogMessage()).isNull(); 4528 assertThat(setting.getDialogInfo()).isEqualTo(suspendDialogInfo); 4529 assertThat(setting.getSuspendedAppExtras().getString("key")).isEqualTo("value"); 4530 assertThat(setting.getSuspendedLauncherExtras().getInt("number")).isEqualTo(7); 4531 4532 ShadowSuspendDialogInfo shadowDialogInfo = Shadow.extract(setting.getDialogInfo()); 4533 assertThat(shadowDialogInfo.getDialogMessage()).isEqualTo("Dialog message"); 4534 assertThat(shadowDialogInfo.getIconResId()).isEqualTo(R.drawable.an_image); 4535 assertThat(shadowDialogInfo.getTitleResId()).isEqualTo(R.string.greeting); 4536 assertThat(shadowDialogInfo.getNeutralButtonTextResId()).isEqualTo(R.string.copy); 4537 } 4538 4539 @Test 4540 @Config(minSdk = android.os.Build.VERSION_CODES.P) getPackageSetting_installedUnsuspendedPackage_shouldReturnUnsuspendedSetting()4541 public void getPackageSetting_installedUnsuspendedPackage_shouldReturnUnsuspendedSetting() { 4542 shadowOf(packageManager).installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME)); 4543 PersistableBundle appExtras = new PersistableBundle(); 4544 appExtras.putString("key", "value"); 4545 PersistableBundle launcherExtras = new PersistableBundle(); 4546 launcherExtras.putInt("number", 7); 4547 setPackagesSuspended( 4548 new String[] {TEST_PACKAGE_NAME}, true, appExtras, launcherExtras, "Dialog message"); 4549 setPackagesSuspended( 4550 new String[] {TEST_PACKAGE_NAME}, false, appExtras, launcherExtras, "Dialog message"); 4551 4552 PackageSetting setting = shadowOf(packageManager).getPackageSetting(TEST_PACKAGE_NAME); 4553 4554 assertThat(setting.isSuspended()).isFalse(); 4555 assertThat(setting.getDialogMessage()).isNull(); 4556 assertThat(setting.getSuspendedAppExtras()).isNull(); 4557 assertThat(setting.getSuspendedLauncherExtras()).isNull(); 4558 } 4559 4560 @Test 4561 @Config(minSdk = android.os.Build.VERSION_CODES.O) canRequestPackageInstalls_shouldReturnFalseByDefault()4562 public void canRequestPackageInstalls_shouldReturnFalseByDefault() { 4563 assertThat(packageManager.canRequestPackageInstalls()).isFalse(); 4564 } 4565 4566 @Test 4567 @Config(minSdk = android.os.Build.VERSION_CODES.O) canRequestPackageInstalls_shouldReturnTrue_whenSetToTrue()4568 public void canRequestPackageInstalls_shouldReturnTrue_whenSetToTrue() { 4569 shadowOf(packageManager).setCanRequestPackageInstalls(true); 4570 assertThat(packageManager.canRequestPackageInstalls()).isTrue(); 4571 } 4572 4573 @Test 4574 @Config(minSdk = android.os.Build.VERSION_CODES.O) canRequestPackageInstalls_shouldReturnFalse_whenSetToFalse()4575 public void canRequestPackageInstalls_shouldReturnFalse_whenSetToFalse() { 4576 shadowOf(packageManager).setCanRequestPackageInstalls(false); 4577 assertThat(packageManager.canRequestPackageInstalls()).isFalse(); 4578 } 4579 4580 @Test 4581 @Config(minSdk = android.os.Build.VERSION_CODES.Q) getModule()4582 public void getModule() throws Exception { 4583 ModuleInfo sentModuleInfo = 4584 ModuleInfoBuilder.newBuilder() 4585 .setName("test.module.name") 4586 .setPackageName("test.module.package.name") 4587 .setHidden(false) 4588 .build(); 4589 shadowOf(packageManager).installModule(sentModuleInfo); 4590 4591 ModuleInfo receivedModuleInfo = 4592 packageManager.getModuleInfo(sentModuleInfo.getPackageName(), 0); 4593 assertThat(receivedModuleInfo.getName().toString().contentEquals(sentModuleInfo.getName())) 4594 .isTrue(); 4595 assertThat(receivedModuleInfo.getPackageName().equals(sentModuleInfo.getPackageName())) 4596 .isTrue(); 4597 assertThat(receivedModuleInfo.isHidden()).isSameInstanceAs(sentModuleInfo.isHidden()); 4598 } 4599 4600 @Test 4601 @Config(minSdk = android.os.Build.VERSION_CODES.Q) getInstalledModules()4602 public void getInstalledModules() { 4603 List<ModuleInfo> sentModuleInfos = new ArrayList<>(); 4604 sentModuleInfos.add( 4605 ModuleInfoBuilder.newBuilder() 4606 .setName("test.module.name.one") 4607 .setPackageName("test.module.package.name.one") 4608 .setHidden(false) 4609 .build()); 4610 sentModuleInfos.add( 4611 ModuleInfoBuilder.newBuilder() 4612 .setName("test.module.name.two") 4613 .setPackageName("test.module.package.name.two") 4614 .setHidden(false) 4615 .build()); 4616 4617 for (ModuleInfo sentModuleInfo : sentModuleInfos) { 4618 shadowOf(packageManager).installModule(sentModuleInfo); 4619 } 4620 4621 List<ModuleInfo> receivedModuleInfos = packageManager.getInstalledModules(0); 4622 4623 for (int i = 0; i < receivedModuleInfos.size(); i++) { 4624 assertThat( 4625 receivedModuleInfos 4626 .get(i) 4627 .getName() 4628 .toString() 4629 .contentEquals(sentModuleInfos.get(i).getName())) 4630 .isTrue(); 4631 assertThat( 4632 receivedModuleInfos 4633 .get(i) 4634 .getPackageName() 4635 .equals(sentModuleInfos.get(i).getPackageName())) 4636 .isTrue(); 4637 assertThat(receivedModuleInfos.get(i).isHidden()) 4638 .isSameInstanceAs(sentModuleInfos.get(i).isHidden()); 4639 } 4640 } 4641 4642 @Test 4643 @Config(minSdk = android.os.Build.VERSION_CODES.Q) deleteModule()4644 public void deleteModule() throws Exception { 4645 ModuleInfo sentModuleInfo = 4646 ModuleInfoBuilder.newBuilder() 4647 .setName("test.module.name") 4648 .setPackageName("test.module.package.name") 4649 .setHidden(false) 4650 .build(); 4651 shadowOf(packageManager).installModule(sentModuleInfo); 4652 4653 ModuleInfo receivedModuleInfo = 4654 packageManager.getModuleInfo(sentModuleInfo.getPackageName(), 0); 4655 4656 assertThat(receivedModuleInfo.getPackageName().equals(sentModuleInfo.getPackageName())) 4657 .isTrue(); 4658 4659 ModuleInfo deletedModuleInfo = 4660 (ModuleInfo) shadowOf(packageManager).deleteModule(sentModuleInfo.getPackageName()); 4661 4662 assertThat(deletedModuleInfo.getName().toString().contentEquals(sentModuleInfo.getName())) 4663 .isTrue(); 4664 assertThat(deletedModuleInfo.getPackageName().equals(sentModuleInfo.getPackageName())).isTrue(); 4665 assertThat(deletedModuleInfo.isHidden()).isSameInstanceAs(sentModuleInfo.isHidden()); 4666 } 4667 4668 @Test loadIcon_default()4669 public void loadIcon_default() { 4670 ActivityInfo info = new ActivityInfo(); 4671 info.applicationInfo = new ApplicationInfo(); 4672 info.packageName = "testPackage"; 4673 info.name = "testName"; 4674 4675 Drawable icon = info.loadIcon(packageManager); 4676 4677 assertThat(icon).isNotNull(); 4678 } 4679 4680 @Test loadIcon_specified()4681 public void loadIcon_specified() { 4682 ActivityInfo info = new ActivityInfo(); 4683 info.applicationInfo = new ApplicationInfo(); 4684 info.packageName = "testPackage"; 4685 info.name = "testName"; 4686 info.icon = R.drawable.an_image; 4687 4688 Drawable icon = info.loadIcon(packageManager); 4689 4690 assertThat(icon).isNotNull(); 4691 } 4692 4693 @Test resolveInfoComparator()4694 public void resolveInfoComparator() { 4695 ResolveInfo priority = new ResolveInfo(); 4696 priority.priority = 100; 4697 ResolveInfo preferredOrder = new ResolveInfo(); 4698 preferredOrder.preferredOrder = 100; 4699 ResolveInfo defaultResolveInfo = new ResolveInfo(); 4700 4701 ResolveInfo[] array = new ResolveInfo[] {priority, preferredOrder, defaultResolveInfo}; 4702 Arrays.sort(array, new ResolveInfoComparator()); 4703 4704 assertThat(array) 4705 .asList() 4706 .containsExactly(preferredOrder, priority, defaultResolveInfo) 4707 .inOrder(); 4708 } 4709 4710 @Test reQueryOverriddenIntents_shouldReturnsDifferentInstancesOfSameParcelables()4711 public void reQueryOverriddenIntents_shouldReturnsDifferentInstancesOfSameParcelables() { 4712 Intent intent = new Intent(Intent.ACTION_VIEW); 4713 ResolveInfo resolveInfo = new ResolveInfo(); 4714 resolveInfo.activityInfo = new ActivityInfo(); 4715 resolveInfo.activityInfo.packageName = "test.package"; 4716 resolveInfo.activityInfo.name = "test.activity"; 4717 shadowOf(packageManager).addResolveInfoForIntent(intent, resolveInfo); 4718 4719 List<ResolveInfo> resolveInfoList1 = packageManager.queryIntentActivities(intent, 0); 4720 List<ResolveInfo> resolveInfoList2 = packageManager.queryIntentActivities(intent, 0); 4721 4722 assertThat(resolveInfoList1).hasSize(1); 4723 assertThat(resolveInfoList2).hasSize(1); 4724 assertThat(resolveInfoList1).containsNoneIn(resolveInfoList2); 4725 4726 Iterator<ResolveInfo> iterator1 = resolveInfoList1.iterator(); 4727 Iterator<ResolveInfo> iterator2 = resolveInfoList2.iterator(); 4728 while (iterator1.hasNext() && iterator2.hasNext()) { 4729 ResolveInfo parcellable1 = iterator1.next(); 4730 ResolveInfo parcellable2 = iterator2.next(); 4731 ActivityInfo activityInfo1 = parcellable1.activityInfo; 4732 ActivityInfo activityInfo2 = parcellable2.activityInfo; 4733 4734 assertThat(activityInfo1.packageName).isEqualTo("test.package"); 4735 assertThat(activityInfo1.name).isEqualTo("test.activity"); 4736 4737 assertThat(activityInfo1.packageName).isEqualTo(activityInfo2.packageName); 4738 assertThat(activityInfo1.name).isEqualTo(activityInfo2.name); 4739 } 4740 } 4741 createPackageInfoWithPackageName(String packageName)4742 private static PackageInfo createPackageInfoWithPackageName(String packageName) { 4743 PackageInfo packageInfo = new PackageInfo(); 4744 packageInfo.packageName = packageName; 4745 packageInfo.applicationInfo = new ApplicationInfo(); 4746 packageInfo.applicationInfo.packageName = packageName; 4747 packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL; 4748 return packageInfo; 4749 } 4750 4751 @Test addActivityIfNotPresent_newPackage()4752 public void addActivityIfNotPresent_newPackage() throws Exception { 4753 ComponentName componentName = new ComponentName("test.package", "Activity"); 4754 shadowOf(packageManager).addActivityIfNotPresent(componentName); 4755 4756 ActivityInfo activityInfo = packageManager.getActivityInfo(componentName, 0); 4757 4758 assertThat(activityInfo).isNotNull(); 4759 assertThat(activityInfo.packageName).isEqualTo("test.package"); 4760 assertThat(activityInfo.name).isEqualTo("Activity"); 4761 } 4762 4763 @Test addActivityIfNotPresent_existing()4764 public void addActivityIfNotPresent_existing() throws Exception { 4765 String packageName = context.getPackageName(); 4766 ComponentName componentName = 4767 new ComponentName(packageName, ActivityWithFilters.class.getName()); 4768 shadowOf(packageManager).addActivityIfNotPresent(componentName); 4769 4770 ActivityInfo activityInfo = packageManager.getActivityInfo(componentName, 0); 4771 4772 assertThat(activityInfo).isNotNull(); 4773 assertThat(activityInfo.packageName).isEqualTo(packageName); 4774 assertThat(activityInfo.name).isEqualTo(ActivityWithFilters.class.getName()); 4775 } 4776 4777 @Test addActivityIfNotPresent_newActivity()4778 public void addActivityIfNotPresent_newActivity() throws Exception { 4779 String packageName = context.getPackageName(); 4780 ComponentName componentName = new ComponentName(packageName, "NewActivity"); 4781 shadowOf(packageManager).addActivityIfNotPresent(componentName); 4782 4783 ActivityInfo activityInfo = packageManager.getActivityInfo(componentName, 0); 4784 4785 assertThat(activityInfo).isNotNull(); 4786 assertThat(activityInfo.packageName).isEqualTo(packageName); 4787 assertThat(activityInfo.name).isEqualTo("NewActivity"); 4788 } 4789 4790 @Test setSafeMode()4791 public void setSafeMode() { 4792 assertThat(packageManager.isSafeMode()).isFalse(); 4793 4794 shadowOf(packageManager).setSafeMode(true); 4795 assertThat(packageManager.isSafeMode()).isTrue(); 4796 } 4797 4798 @Test 4799 @Config(minSdk = Q) setDistractingPackageRestrictions()4800 public void setDistractingPackageRestrictions() { 4801 assertThat( 4802 packageManager.setDistractingPackageRestrictions( 4803 new String[] {TEST_PACKAGE_NAME, TEST_PACKAGE2_NAME}, 4804 PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS)) 4805 .isEmpty(); 4806 4807 assertThat(shadowOf(packageManager).getDistractingPackageRestrictions(TEST_PACKAGE_NAME)) 4808 .isEqualTo(PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS); 4809 assertThat(shadowOf(packageManager).getDistractingPackageRestrictions(TEST_PACKAGE2_NAME)) 4810 .isEqualTo(PackageManager.RESTRICTION_HIDE_FROM_SUGGESTIONS); 4811 assertThat(shadowOf(packageManager).getDistractingPackageRestrictions(TEST_PACKAGE3_NAME)) 4812 .isEqualTo(PackageManager.RESTRICTION_NONE); 4813 } 4814 4815 @Test getPackagesHoldingPermissions_returnPackages()4816 public void getPackagesHoldingPermissions_returnPackages() { 4817 String permissionA = "com.android.providers.permission.test.a"; 4818 String permissionB = "com.android.providers.permission.test.b"; 4819 4820 PackageInfo packageInfoA = new PackageInfo(); 4821 packageInfoA.packageName = TEST_PACKAGE_NAME; 4822 packageInfoA.applicationInfo = new ApplicationInfo(); 4823 packageInfoA.applicationInfo.packageName = TEST_PACKAGE_NAME; 4824 packageInfoA.requestedPermissions = new String[] {permissionA}; 4825 4826 PackageInfo packageInfoB = new PackageInfo(); 4827 packageInfoB.packageName = TEST_PACKAGE2_NAME; 4828 packageInfoB.applicationInfo = new ApplicationInfo(); 4829 packageInfoB.applicationInfo.packageName = TEST_PACKAGE2_NAME; 4830 packageInfoB.requestedPermissions = new String[] {permissionB}; 4831 4832 shadowOf(packageManager).installPackage(packageInfoA); 4833 shadowOf(packageManager).installPackage(packageInfoB); 4834 4835 List<PackageInfo> result = 4836 packageManager.getPackagesHoldingPermissions(new String[] {permissionA, permissionB}, 0); 4837 4838 assertThat(result).containsExactly(packageInfoA, packageInfoB); 4839 } 4840 4841 @Test getPackagesHoldingPermissions_returnsEmpty()4842 public void getPackagesHoldingPermissions_returnsEmpty() { 4843 String permissionA = "com.android.providers.permission.test.a"; 4844 4845 PackageInfo packageInfoA = new PackageInfo(); 4846 packageInfoA.packageName = TEST_PACKAGE_NAME; 4847 packageInfoA.applicationInfo = new ApplicationInfo(); 4848 packageInfoA.applicationInfo.packageName = TEST_PACKAGE_NAME; 4849 packageInfoA.requestedPermissions = new String[] {permissionA}; 4850 4851 shadowOf(packageManager).installPackage(packageInfoA); 4852 4853 List<PackageInfo> result = 4854 packageManager.getPackagesHoldingPermissions( 4855 new String[] {"com.android.providers.permission.test.b"}, 0); 4856 4857 assertThat(result).isEmpty(); 4858 } 4859 4860 @Test 4861 @Config(minSdk = O) isInstantApp()4862 public void isInstantApp() throws Exception { 4863 PackageInfo packageInfo = new PackageInfo(); 4864 packageInfo.packageName = TEST_PACKAGE_NAME; 4865 packageInfo.applicationInfo = new ApplicationInfo(); 4866 packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME; 4867 packageInfo 4868 .applicationInfo 4869 .getClass() 4870 .getDeclaredField("privateFlags") 4871 .setInt(packageInfo.applicationInfo, /*ApplicationInfo.PRIVATE_FLAG_INSTANT*/ 1 << 7); 4872 4873 shadowOf(packageManager).installPackage(packageInfo); 4874 4875 assertThat(packageManager.isInstantApp(TEST_PACKAGE_NAME)).isTrue(); 4876 } 4877 4878 @Test 4879 @Config(minSdk = O) isInstantApp_falseDefault()4880 public void isInstantApp_falseDefault() { 4881 PackageInfo packageInfo = new PackageInfo(); 4882 packageInfo.packageName = TEST_PACKAGE_NAME; 4883 packageInfo.applicationInfo = new ApplicationInfo(); 4884 packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME; 4885 4886 shadowOf(packageManager).installPackage(packageInfo); 4887 4888 assertThat(packageManager.isInstantApp(TEST_PACKAGE_NAME)).isFalse(); 4889 } 4890 4891 @Test getText_stringAdded_originalStringExists_returnsUserAddedString()4892 public void getText_stringAdded_originalStringExists_returnsUserAddedString() { 4893 shadowOf(packageManager) 4894 .addStringResource(context.getPackageName(), R.string.hello, "fake hello"); 4895 4896 assertThat( 4897 packageManager 4898 .getText(context.getPackageName(), R.string.hello, context.getApplicationInfo()) 4899 .toString()) 4900 .isEqualTo("fake hello"); 4901 } 4902 4903 @Test getText_stringAdded_originalStringDoesNotExists_returnsUserAddedString()4904 public void getText_stringAdded_originalStringDoesNotExists_returnsUserAddedString() { 4905 shadowOf(packageManager).addStringResource(TEST_PACKAGE_NAME, 1, "package1 resId1"); 4906 shadowOf(packageManager).addStringResource(TEST_PACKAGE_NAME, 2, "package1 resId2"); 4907 shadowOf(packageManager).addStringResource(TEST_PACKAGE2_NAME, 1, "package2 resId1"); 4908 shadowOf(packageManager).addStringResource(TEST_PACKAGE2_NAME, 3, "package2 resId3"); 4909 4910 assertThat(packageManager.getText(TEST_PACKAGE_NAME, 1, new ApplicationInfo()).toString()) 4911 .isEqualTo("package1 resId1"); 4912 assertThat(packageManager.getText(TEST_PACKAGE_NAME, 2, new ApplicationInfo()).toString()) 4913 .isEqualTo("package1 resId2"); 4914 assertThat(packageManager.getText(TEST_PACKAGE2_NAME, 1, new ApplicationInfo()).toString()) 4915 .isEqualTo("package2 resId1"); 4916 assertThat(packageManager.getText(TEST_PACKAGE2_NAME, 3, new ApplicationInfo()).toString()) 4917 .isEqualTo("package2 resId3"); 4918 } 4919 4920 @Test getText_stringAddedTwice_originalStringDoesNotExists_returnsNewlyUserAddedString()4921 public void getText_stringAddedTwice_originalStringDoesNotExists_returnsNewlyUserAddedString() { 4922 shadowOf(packageManager).addStringResource(TEST_PACKAGE_NAME, 1, "package1 resId1"); 4923 shadowOf(packageManager).addStringResource(TEST_PACKAGE_NAME, 1, "package1 resId2 new"); 4924 4925 assertThat(packageManager.getText(TEST_PACKAGE_NAME, 1, new ApplicationInfo()).toString()) 4926 .isEqualTo("package1 resId2 new"); 4927 } 4928 4929 @Test getText_stringNotAdded_originalStringExists_returnsOriginalText()4930 public void getText_stringNotAdded_originalStringExists_returnsOriginalText() { 4931 shadowOf(packageManager).addStringResource(context.getPackageName(), 1, "fake"); 4932 shadowOf(packageManager).addStringResource(TEST_PACKAGE_NAME, R.string.hello, "fake hello"); 4933 4934 assertThat( 4935 packageManager 4936 .getText(context.getPackageName(), R.string.hello, context.getApplicationInfo()) 4937 .toString()) 4938 .isEqualTo(context.getString(R.string.hello)); 4939 } 4940 4941 @Test getText_stringNotAdded_originalStringDoesNotExists_returnsNull()4942 public void getText_stringNotAdded_originalStringDoesNotExists_returnsNull() { 4943 assertThat(packageManager.getText(context.getPackageName(), 1, context.getApplicationInfo())) 4944 .isNull(); 4945 } 4946 4947 @Test 4948 @Config(minSdk = VERSION_CODES.R) setAutoRevokeWhitelisted()4949 public void setAutoRevokeWhitelisted() { 4950 assertThat(packageManager.isAutoRevokeWhitelisted()).isFalse(); 4951 4952 shadowOf(packageManager).setAutoRevokeWhitelisted(true); 4953 assertThat(packageManager.isAutoRevokeWhitelisted()).isTrue(); 4954 } 4955 4956 @Test hasSystemFeature_default()4957 public void hasSystemFeature_default() { 4958 for (String feature : SystemFeatureListInitializer.getSystemFeatures().keySet()) { 4959 assertThat(packageManager.hasSystemFeature(feature)).isTrue(); 4960 } 4961 } 4962 4963 @Test reset_setsSystemFeatureListToDefaults()4964 public void reset_setsSystemFeatureListToDefaults() { 4965 shadowOf(packageManager).setSystemFeature(PackageManager.FEATURE_CAMERA, true); 4966 ShadowPackageManager.reset(); 4967 for (String feature : SystemFeatureListInitializer.getSystemFeatures().keySet()) { 4968 assertThat(packageManager.hasSystemFeature(feature)).isTrue(); 4969 } 4970 assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isFalse(); 4971 } 4972 4973 @Test 4974 @Config(minSdk = S) getProperty()4975 public void getProperty() throws NameNotFoundException { 4976 assertThrows( 4977 NameNotFoundException.class, 4978 () -> 4979 packageManager.getProperty( 4980 "myproperty", RuntimeEnvironment.getApplication().getPackageName())); 4981 } 4982 4983 @Test 4984 @Config(minSdk = S) getProperty_component()4985 public void getProperty_component() throws NameNotFoundException { 4986 final ComponentName componentName = 4987 new ComponentName(RuntimeEnvironment.getApplication().getPackageName(), "mycomponentname"); 4988 assertThrows( 4989 NameNotFoundException.class, () -> packageManager.getProperty("myproperty", componentName)); 4990 } 4991 4992 @Test 4993 @Config(minSdk = TIRAMISU) setComponentEnabledSettingsSameSettings_getComponentEnabledSettingsConsistent()4994 public void setComponentEnabledSettingsSameSettings_getComponentEnabledSettingsConsistent() { 4995 ShadowApplicationPackageManager pm = (ShadowApplicationPackageManager) shadowOf(packageManager); 4996 ComponentName componentName0 = new ComponentName(context, "mycomponentname0"); 4997 ComponentName componentName1 = new ComponentName(context, "mycomponentname1"); 4998 ComponentEnabledSetting componentEnabledSetting0 = 4999 new ComponentEnabledSetting( 5000 componentName0, 5001 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 5002 PackageManager.DONT_KILL_APP); 5003 ComponentEnabledSetting componentEnabledSetting1 = 5004 new ComponentEnabledSetting( 5005 componentName1, 5006 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 5007 PackageManager.DONT_KILL_APP); 5008 ImmutableList<ComponentEnabledSetting> componentEnabledSettings = 5009 ImmutableList.of(componentEnabledSetting0, componentEnabledSetting1); 5010 5011 pm.setComponentEnabledSettings(componentEnabledSettings); 5012 5013 for (ComponentEnabledSetting setting : componentEnabledSettings) { 5014 assertThat(pm.getComponentEnabledSetting(setting.getComponentName())) 5015 .isEqualTo(setting.getEnabledState()); 5016 } 5017 } 5018 5019 @Test 5020 @Config(minSdk = TIRAMISU) setComponentEnabledSettingsDifferentSettings_getComponentEnabledSettingsConsistent()5021 public void setComponentEnabledSettingsDifferentSettings_getComponentEnabledSettingsConsistent() { 5022 ShadowApplicationPackageManager pm = (ShadowApplicationPackageManager) shadowOf(packageManager); 5023 ComponentName componentName0 = new ComponentName(context, "mycomponentname0"); 5024 ComponentName componentName1 = new ComponentName(context, "mycomponentname1"); 5025 ComponentEnabledSetting componentEnabledSetting0 = 5026 new ComponentEnabledSetting( 5027 componentName0, 5028 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 5029 PackageManager.DONT_KILL_APP); 5030 ComponentEnabledSetting componentEnabledSetting1 = 5031 new ComponentEnabledSetting( 5032 componentName1, 5033 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 5034 PackageManager.DONT_KILL_APP); 5035 ImmutableList<ComponentEnabledSetting> componentEnabledSettings = 5036 ImmutableList.of(componentEnabledSetting0, componentEnabledSetting1); 5037 5038 pm.setComponentEnabledSettings(componentEnabledSettings); 5039 5040 for (ComponentEnabledSetting setting : componentEnabledSettings) { 5041 assertThat(pm.getComponentEnabledSetting(setting.getComponentName())) 5042 .isEqualTo(setting.getEnabledState()); 5043 } 5044 } 5045 5046 @Test 5047 @Config(minSdk = Q) setSyntheticAppDetailsActivityEnabled_getConsistent()5048 public void setSyntheticAppDetailsActivityEnabled_getConsistent() { 5049 ShadowApplicationPackageManager pm = (ShadowApplicationPackageManager) shadowOf(packageManager); 5050 5051 pm.setSyntheticAppDetailsActivityEnabled(TEST_PACKAGE_NAME, true); 5052 boolean before = pm.getSyntheticAppDetailsActivityEnabled(TEST_PACKAGE_NAME); 5053 pm.setSyntheticAppDetailsActivityEnabled(TEST_PACKAGE_NAME, false); 5054 boolean after = pm.getSyntheticAppDetailsActivityEnabled(TEST_PACKAGE_NAME); 5055 5056 assertThat(before).isTrue(); 5057 assertThat(after).isFalse(); 5058 } 5059 5060 @Test 5061 @Config(minSdk = N) setDefaultBrowserPackageNameAsUser_getConsistent()5062 public void setDefaultBrowserPackageNameAsUser_getConsistent() { 5063 ShadowApplicationPackageManager pm = (ShadowApplicationPackageManager) shadowOf(packageManager); 5064 5065 boolean isSuccessful = pm.setDefaultBrowserPackageNameAsUser(TEST_PACKAGE_NAME, 0); 5066 5067 String defaultBrowserPackageNameUserAvailable = pm.getDefaultBrowserPackageNameAsUser(0); 5068 String defaultBrowserPackageNameUserNotAvailable = pm.getDefaultBrowserPackageNameAsUser(10); 5069 5070 assertThat(isSuccessful).isTrue(); 5071 assertThat(defaultBrowserPackageNameUserAvailable).isEqualTo(TEST_PACKAGE_NAME); 5072 assertThat(defaultBrowserPackageNameUserNotAvailable).isNull(); 5073 } 5074 5075 @Test addPackageInternal_platformPermissionGroup_throws()5076 public void addPackageInternal_platformPermissionGroup_throws() { 5077 Package pkg = new Package(TEST_PACKAGE_NAME); 5078 ApplicationInfo appInfo = pkg.applicationInfo; 5079 appInfo.flags = ApplicationInfo.FLAG_INSTALLED; 5080 appInfo.packageName = TEST_PACKAGE_NAME; 5081 appInfo.sourceDir = TEST_APP_PATH; 5082 appInfo.name = TEST_PACKAGE_LABEL; 5083 PermissionGroupInfo pgi = new PermissionGroupInfo(); 5084 pgi.name = permission_group.CALENDAR; 5085 PermissionGroup pg = new PermissionGroup(pkg, pgi); 5086 pkg.permissionGroups.add(pg); 5087 5088 try { 5089 shadowOf(packageManager).addPackageInternal(pkg); 5090 fail("Exception expected"); 5091 } catch (IllegalArgumentException expected) { 5092 } 5093 } 5094 setPackagesSuspended( String[] packageNames, boolean suspended, PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage)5095 public String[] setPackagesSuspended( 5096 String[] packageNames, 5097 boolean suspended, 5098 PersistableBundle appExtras, 5099 PersistableBundle launcherExtras, 5100 String dialogMessage) { 5101 return packageManager.setPackagesSuspended( 5102 packageNames, suspended, appExtras, launcherExtras, dialogMessage); 5103 } 5104 generateTestPackageInfo()5105 private PackageInfo generateTestPackageInfo() { 5106 ApplicationInfo appInfo = new ApplicationInfo(); 5107 appInfo.flags = ApplicationInfo.FLAG_INSTALLED; 5108 appInfo.packageName = TEST_PACKAGE_NAME; 5109 appInfo.sourceDir = TEST_APP_PATH; 5110 appInfo.name = TEST_PACKAGE_LABEL; 5111 5112 PackageInfo packageInfo = new PackageInfo(); 5113 packageInfo.packageName = TEST_PACKAGE_NAME; 5114 packageInfo.applicationInfo = appInfo; 5115 packageInfo.versionCode = TEST_PACKAGE_VERSION_CODE; 5116 return packageInfo; 5117 } 5118 verifyTestPackageInfo(PackageInfo packageInfo)5119 private void verifyTestPackageInfo(PackageInfo packageInfo) { 5120 assertThat(packageInfo).isNotNull(); 5121 assertThat(packageInfo.versionCode).isEqualTo(TEST_PACKAGE_VERSION_CODE); 5122 ApplicationInfo applicationInfo = packageInfo.applicationInfo; 5123 assertThat(applicationInfo).isInstanceOf(ApplicationInfo.class); 5124 assertThat(applicationInfo.packageName).isEqualTo(TEST_PACKAGE_NAME); 5125 assertThat(applicationInfo.sourceDir).isEqualTo(TEST_APP_PATH); 5126 } 5127 } 5128