1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.content.pm.cts; 18 19 import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE; 20 import static android.content.pm.ApplicationInfo.FLAG_INSTALLED; 21 import static android.content.pm.ApplicationInfo.FLAG_SYSTEM; 22 import static android.content.pm.PackageManager.GET_ACTIVITIES; 23 import static android.content.pm.PackageManager.GET_META_DATA; 24 import static android.content.pm.PackageManager.GET_PERMISSIONS; 25 import static android.content.pm.PackageManager.GET_PROVIDERS; 26 import static android.content.pm.PackageManager.GET_RECEIVERS; 27 import static android.content.pm.PackageManager.GET_SERVICES; 28 29 import static com.google.common.truth.Truth.assertThat; 30 import static com.google.common.truth.Truth.assertWithMessage; 31 32 import static org.junit.Assert.assertEquals; 33 import static org.junit.Assert.assertFalse; 34 import static org.junit.Assert.assertNotNull; 35 import static org.junit.Assert.assertNull; 36 import static org.junit.Assert.assertThat; 37 import static org.junit.Assert.assertTrue; 38 import static org.junit.Assert.fail; 39 40 import android.content.ComponentName; 41 import android.content.Intent; 42 import android.content.IntentFilter; 43 import android.content.cts.R; 44 import android.content.pm.ActivityInfo; 45 import android.content.pm.ApplicationInfo; 46 import android.content.pm.InstrumentationInfo; 47 import android.content.pm.PackageInfo; 48 import android.content.pm.PackageItemInfo; 49 import android.content.pm.PackageManager; 50 import android.content.pm.PackageManager.NameNotFoundException; 51 import android.content.pm.PermissionGroupInfo; 52 import android.content.pm.PermissionInfo; 53 import android.content.pm.ProviderInfo; 54 import android.content.pm.ResolveInfo; 55 import android.content.pm.ServiceInfo; 56 import android.content.pm.Signature; 57 import android.os.SystemProperties; 58 import android.os.UserHandle; 59 import android.platform.test.annotations.AppModeFull; 60 import android.text.TextUtils; 61 import android.util.Log; 62 63 import androidx.test.InstrumentationRegistry; 64 import androidx.test.runner.AndroidJUnit4; 65 66 import org.junit.Before; 67 import org.junit.Test; 68 import org.junit.runner.RunWith; 69 70 import java.util.ArrayList; 71 import java.util.Arrays; 72 import java.util.Iterator; 73 import java.util.List; 74 import java.util.stream.Collectors; 75 76 /** 77 * This test is based on the declarations in AndroidManifest.xml. We create mock declarations 78 * in AndroidManifest.xml just for test of PackageManager, and there are no corresponding parts 79 * of these declarations in test project. 80 */ 81 @AppModeFull // TODO(Instant) Figure out which APIs should work. 82 @RunWith(AndroidJUnit4.class) 83 public class PackageManagerTest { 84 private static final String TAG = "PackageManagerTest"; 85 86 private PackageManager mPackageManager; 87 private static final String PACKAGE_NAME = "android.content.cts"; 88 private static final String CONTENT_PKG_NAME = "android.content.cts"; 89 private static final String APPLICATION_NAME = "android.content.cts.MockApplication"; 90 private static final String ACTIVITY_ACTION_NAME = "android.intent.action.PMTEST"; 91 private static final String MAIN_ACTION_NAME = "android.intent.action.MAIN"; 92 private static final String SERVICE_ACTION_NAME = 93 "android.content.pm.cts.activity.PMTEST_SERVICE"; 94 private static final String GRANTED_PERMISSION_NAME = "android.permission.INTERNET"; 95 private static final String NOT_GRANTED_PERMISSION_NAME = "android.permission.HARDWARE_TEST"; 96 private static final String ACTIVITY_NAME = "android.content.pm.cts.TestPmActivity"; 97 private static final String SERVICE_NAME = "android.content.pm.cts.TestPmService"; 98 private static final String RECEIVER_NAME = "android.content.pm.cts.PmTestReceiver"; 99 private static final String INSTRUMENT_NAME = "android.content.pm.cts.TestPmInstrumentation"; 100 private static final String CALL_ABROAD_PERMISSION_NAME = 101 "android.content.cts.CALL_ABROAD_PERMISSION"; 102 private static final String PROVIDER_NAME = "android.content.cts.MockContentProvider"; 103 private static final String PERMISSIONGROUP_NAME = "android.permission-group.COST_MONEY"; 104 private static final String PERMISSION_TREE_ROOT = 105 "android.content.cts.permission.TEST_DYNAMIC"; 106 // There are 11 activities/activity-alias in AndroidManifest 107 private static final int NUM_OF_ACTIVITIES_IN_MANIFEST = 11; 108 109 private static final String SHIM_APEX_PACKAGE_NAME = "com.android.apex.cts.shim"; 110 111 @Before setup()112 public void setup() throws Exception { 113 mPackageManager = InstrumentationRegistry.getContext().getPackageManager(); 114 } 115 116 @Test testQuery()117 public void testQuery() throws NameNotFoundException { 118 // Test query Intent Activity related methods 119 120 Intent activityIntent = new Intent(ACTIVITY_ACTION_NAME); 121 String cmpActivityName = "android.content.pm.cts.TestPmCompare"; 122 // List with different activities and the filter doesn't work, 123 List<ResolveInfo> listWithDiff = mPackageManager.queryIntentActivityOptions( 124 new ComponentName(PACKAGE_NAME, cmpActivityName), null, activityIntent, 0); 125 checkActivityInfoName(ACTIVITY_NAME, listWithDiff); 126 127 // List with the same activities to make filter work 128 List<ResolveInfo> listInSame = mPackageManager.queryIntentActivityOptions( 129 new ComponentName(PACKAGE_NAME, ACTIVITY_NAME), null, activityIntent, 0); 130 assertEquals(0, listInSame.size()); 131 132 // Test queryIntentActivities 133 List<ResolveInfo> intentActivities = 134 mPackageManager.queryIntentActivities(activityIntent, 0); 135 assertTrue(intentActivities.size() > 0); 136 checkActivityInfoName(ACTIVITY_NAME, intentActivities); 137 138 // End of Test query Intent Activity related methods 139 140 // Test queryInstrumentation 141 String targetPackage = "android"; 142 List<InstrumentationInfo> instrumentations = mPackageManager.queryInstrumentation( 143 targetPackage, 0); 144 checkInstrumentationInfoName(INSTRUMENT_NAME, instrumentations); 145 146 // Test queryIntentServices 147 Intent serviceIntent = new Intent(SERVICE_ACTION_NAME); 148 List<ResolveInfo> services = mPackageManager.queryIntentServices(serviceIntent, 149 PackageManager.GET_INTENT_FILTERS); 150 checkServiceInfoName(SERVICE_NAME, services); 151 152 // Test queryBroadcastReceivers 153 String receiverActionName = "android.content.pm.cts.PackageManagerTest.PMTEST_RECEIVER"; 154 Intent broadcastIntent = new Intent(receiverActionName); 155 List<ResolveInfo> broadcastReceivers = new ArrayList<ResolveInfo>(); 156 broadcastReceivers = mPackageManager.queryBroadcastReceivers(broadcastIntent, 0); 157 checkActivityInfoName(RECEIVER_NAME, broadcastReceivers); 158 159 // Test queryPermissionsByGroup, queryContentProviders 160 String testPermissionsGroup = "android.permission-group.COST_MONEY"; 161 List<PermissionInfo> permissions = mPackageManager.queryPermissionsByGroup( 162 testPermissionsGroup, PackageManager.GET_META_DATA); 163 checkPermissionInfoName(CALL_ABROAD_PERMISSION_NAME, permissions); 164 165 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 166 List<ProviderInfo> providers = mPackageManager.queryContentProviders(PACKAGE_NAME, 167 appInfo.uid, 0); 168 checkProviderInfoName(PROVIDER_NAME, providers); 169 } 170 checkActivityInfoName(String expectedName, List<ResolveInfo> resolves)171 private void checkActivityInfoName(String expectedName, List<ResolveInfo> resolves) { 172 // Flag for checking if the name is contained in list array. 173 boolean isContained = false; 174 Iterator<ResolveInfo> infoIterator = resolves.iterator(); 175 String current; 176 while (infoIterator.hasNext()) { 177 current = infoIterator.next().activityInfo.name; 178 if (current.equals(expectedName)) { 179 isContained = true; 180 break; 181 } 182 } 183 assertTrue(isContained); 184 } 185 checkServiceInfoName(String expectedName, List<ResolveInfo> resolves)186 private void checkServiceInfoName(String expectedName, List<ResolveInfo> resolves) { 187 boolean isContained = false; 188 Iterator<ResolveInfo> infoIterator = resolves.iterator(); 189 String current; 190 while (infoIterator.hasNext()) { 191 current = infoIterator.next().serviceInfo.name; 192 if (current.equals(expectedName)) { 193 isContained = true; 194 break; 195 } 196 } 197 assertTrue(isContained); 198 } 199 checkPermissionInfoName(String expectedName, List<PermissionInfo> permissions)200 private void checkPermissionInfoName(String expectedName, List<PermissionInfo> permissions) { 201 List<String> names = new ArrayList<String>(); 202 for (PermissionInfo permission : permissions) { 203 names.add(permission.name); 204 } 205 boolean isContained = names.contains(expectedName); 206 assertTrue("Permission " + expectedName + " not present in " + names, isContained); 207 } 208 checkProviderInfoName(String expectedName, List<ProviderInfo> providers)209 private void checkProviderInfoName(String expectedName, List<ProviderInfo> providers) { 210 boolean isContained = false; 211 Iterator<ProviderInfo> infoIterator = providers.iterator(); 212 String current; 213 while (infoIterator.hasNext()) { 214 current = infoIterator.next().name; 215 if (current.equals(expectedName)) { 216 isContained = true; 217 break; 218 } 219 } 220 assertTrue(isContained); 221 } 222 checkInstrumentationInfoName(String expectedName, List<InstrumentationInfo> instrumentations)223 private void checkInstrumentationInfoName(String expectedName, 224 List<InstrumentationInfo> instrumentations) { 225 boolean isContained = false; 226 Iterator<InstrumentationInfo> infoIterator = instrumentations.iterator(); 227 String current; 228 while (infoIterator.hasNext()) { 229 current = infoIterator.next().name; 230 if (current.equals(expectedName)) { 231 isContained = true; 232 break; 233 } 234 } 235 assertTrue(isContained); 236 } 237 238 @Test testGetInfo()239 public void testGetInfo() throws NameNotFoundException { 240 // Test getApplicationInfo, getText 241 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 242 int discriptionRes = R.string.hello_android; 243 String expectedDisciptionRes = "Hello, Android!"; 244 CharSequence appText = mPackageManager.getText(PACKAGE_NAME, discriptionRes, appInfo); 245 assertEquals(expectedDisciptionRes, appText); 246 ComponentName activityName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME); 247 ComponentName serviceName = new ComponentName(PACKAGE_NAME, SERVICE_NAME); 248 ComponentName receiverName = new ComponentName(PACKAGE_NAME, RECEIVER_NAME); 249 ComponentName instrName = new ComponentName(PACKAGE_NAME, INSTRUMENT_NAME); 250 251 // Test getPackageInfo 252 PackageInfo packageInfo = mPackageManager.getPackageInfo(PACKAGE_NAME, 253 PackageManager.GET_INSTRUMENTATION); 254 assertEquals(PACKAGE_NAME, packageInfo.packageName); 255 256 // Test getApplicationInfo, getApplicationLabel 257 String appLabel = "Android TestCase"; 258 assertEquals(appLabel, mPackageManager.getApplicationLabel(appInfo)); 259 assertEquals(PACKAGE_NAME, appInfo.processName); 260 261 // Test getServiceInfo 262 assertEquals(SERVICE_NAME, mPackageManager.getServiceInfo(serviceName, 263 PackageManager.GET_META_DATA).name); 264 265 // Test getReceiverInfo 266 assertEquals(RECEIVER_NAME, mPackageManager.getReceiverInfo(receiverName, 0).name); 267 268 // Test getPackageArchiveInfo 269 final String apkRoute = InstrumentationRegistry.getContext().getPackageCodePath(); 270 final String apkName = InstrumentationRegistry.getContext().getPackageName(); 271 assertEquals(apkName, mPackageManager.getPackageArchiveInfo(apkRoute, 0).packageName); 272 273 // Test getPackagesForUid, getNameForUid 274 checkPackagesNameForUid(PACKAGE_NAME, mPackageManager.getPackagesForUid(appInfo.uid)); 275 assertEquals(PACKAGE_NAME, mPackageManager.getNameForUid(appInfo.uid)); 276 277 // Test getActivityInfo 278 assertEquals(ACTIVITY_NAME, mPackageManager.getActivityInfo(activityName, 0).name); 279 280 // Test getPackageGids 281 assertTrue(mPackageManager.getPackageGids(PACKAGE_NAME).length > 0); 282 283 // Test getPermissionInfo 284 assertEquals(GRANTED_PERMISSION_NAME, 285 mPackageManager.getPermissionInfo(GRANTED_PERMISSION_NAME, 0).name); 286 287 // Test getPermissionGroupInfo 288 assertEquals(PERMISSIONGROUP_NAME, mPackageManager.getPermissionGroupInfo( 289 PERMISSIONGROUP_NAME, 0).name); 290 291 // Test getAllPermissionGroups 292 List<PermissionGroupInfo> permissionGroups = mPackageManager.getAllPermissionGroups(0); 293 checkPermissionGroupInfoName(PERMISSIONGROUP_NAME, permissionGroups); 294 295 // Test getInstalledApplications 296 assertTrue(mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA).size() > 0); 297 298 // Test getInstalledPacakge 299 assertTrue(mPackageManager.getInstalledPackages(0).size() > 0); 300 301 // Test getInstrumentationInfo 302 assertEquals(INSTRUMENT_NAME, mPackageManager.getInstrumentationInfo(instrName, 0).name); 303 304 // Test getSystemSharedLibraryNames, in javadoc, String array and null 305 // are all OK as return value. 306 mPackageManager.getSystemSharedLibraryNames(); 307 308 // Test getLaunchIntentForPackage, Intent of activity 309 // android.content.pm.cts.TestPmCompare is set to match the condition 310 // to make sure the return of this method is not null. 311 assertEquals(MAIN_ACTION_NAME, mPackageManager.getLaunchIntentForPackage(PACKAGE_NAME) 312 .getAction()); 313 314 // Test isSafeMode. Because the test case will not run in safe mode, so 315 // the return will be false. 316 assertFalse(mPackageManager.isSafeMode()); 317 } 318 checkPackagesNameForUid(String expectedName, String[] uid)319 private void checkPackagesNameForUid(String expectedName, String[] uid) { 320 boolean isContained = false; 321 for (int i = 0; i < uid.length; i++) { 322 if (uid[i].equals(expectedName)) { 323 isContained = true; 324 break; 325 } 326 } 327 assertTrue(isContained); 328 } 329 checkPermissionGroupInfoName(String expectedName, List<PermissionGroupInfo> permissionGroups)330 private void checkPermissionGroupInfoName(String expectedName, 331 List<PermissionGroupInfo> permissionGroups) { 332 boolean isContained = false; 333 Iterator<PermissionGroupInfo> infoIterator = permissionGroups.iterator(); 334 String current; 335 while (infoIterator.hasNext()) { 336 current = infoIterator.next().name; 337 if (current.equals(expectedName)) { 338 isContained = true; 339 break; 340 } 341 } 342 assertTrue(isContained); 343 } 344 345 346 /** 347 * Simple test for {@link PackageManager#getPreferredActivities(List, List, String)} that tests 348 * calling it has no effect. The method is essentially a no-op because no preferred activities 349 * can be added. 350 * @see PackageManager#addPreferredActivity(IntentFilter, int, ComponentName[], ComponentName) 351 */ 352 @Test testGetPreferredActivities()353 public void testGetPreferredActivities() { 354 assertNoPreferredActivities(); 355 } 356 357 /** 358 * Helper method to test that {@link PackageManager#getPreferredActivities(List, List, String)} 359 * returns empty lists. 360 */ assertNoPreferredActivities()361 private void assertNoPreferredActivities() { 362 List<ComponentName> outActivities = new ArrayList<ComponentName>(); 363 List<IntentFilter> outFilters = new ArrayList<IntentFilter>(); 364 mPackageManager.getPreferredActivities(outFilters, outActivities, PACKAGE_NAME); 365 assertEquals(0, outActivities.size()); 366 assertEquals(0, outFilters.size()); 367 } 368 369 /** 370 * Test that calling {@link PackageManager#addPreferredActivity(IntentFilter, int, 371 * ComponentName[], ComponentName)} throws a {@link SecurityException}. 372 * <p/> 373 * The method is protected by the {@link android.permission.SET_PREFERRED_APPLICATIONS} 374 * signature permission. Even though this app declares that permission, it still should not be 375 * able to call this method because it is not signed with the platform certificate. 376 */ 377 @Test testAddPreferredActivity()378 public void testAddPreferredActivity() { 379 IntentFilter intentFilter = new IntentFilter(ACTIVITY_ACTION_NAME); 380 ComponentName[] componentName = {new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)}; 381 try { 382 mPackageManager.addPreferredActivity(intentFilter, IntentFilter.MATCH_CATEGORY_HOST, 383 componentName, componentName[0]); 384 fail("addPreferredActivity unexpectedly succeeded"); 385 } catch (SecurityException e) { 386 // expected 387 } 388 assertNoPreferredActivities(); 389 } 390 391 /** 392 * Test that calling {@link PackageManager#clearPackagePreferredActivities(String)} has no 393 * effect. 394 */ 395 @Test testClearPackagePreferredActivities()396 public void testClearPackagePreferredActivities() { 397 // just ensure no unexpected exceptions are thrown, nothing else to do 398 mPackageManager.clearPackagePreferredActivities(PACKAGE_NAME); 399 } 400 checkComponentName(String expectedName, List<ComponentName> componentNames)401 private void checkComponentName(String expectedName, List<ComponentName> componentNames) { 402 boolean isContained = false; 403 Iterator<ComponentName> nameIterator = componentNames.iterator(); 404 String current; 405 while (nameIterator.hasNext()) { 406 current = nameIterator.next().getClassName(); 407 if (current.equals(expectedName)) { 408 isContained = true; 409 break; 410 } 411 } 412 assertTrue(isContained); 413 } 414 checkIntentFilterAction(String expectedName, List<IntentFilter> intentFilters)415 private void checkIntentFilterAction(String expectedName, List<IntentFilter> intentFilters) { 416 boolean isContained = false; 417 Iterator<IntentFilter> filterIterator = intentFilters.iterator(); 418 IntentFilter currentFilter; 419 String currentAction; 420 while (filterIterator.hasNext()) { 421 currentFilter = filterIterator.next(); 422 for (int i = 0; i < currentFilter.countActions(); i++) { 423 currentAction = currentFilter.getAction(i); 424 if (currentAction.equals(expectedName)) { 425 isContained = true; 426 break; 427 } 428 } 429 } 430 assertTrue(isContained); 431 } 432 433 @Test testAccessEnabledSetting()434 public void testAccessEnabledSetting() { 435 mPackageManager.setApplicationEnabledSetting(PACKAGE_NAME, 436 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); 437 assertEquals(PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 438 mPackageManager.getApplicationEnabledSetting(PACKAGE_NAME)); 439 440 ComponentName componentName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME); 441 mPackageManager.setComponentEnabledSetting(componentName, 442 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); 443 assertEquals(PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 444 mPackageManager.getComponentEnabledSetting(componentName)); 445 } 446 447 @Test testGetApplicationEnabledSetting_notFound()448 public void testGetApplicationEnabledSetting_notFound() { 449 try { 450 mPackageManager.getApplicationEnabledSetting("this.package.does.not.exist"); 451 fail("Exception expected"); 452 } catch (IllegalArgumentException expected) { 453 } 454 } 455 456 @Test testGetIcon()457 public void testGetIcon() throws NameNotFoundException { 458 assertNotNull(mPackageManager.getApplicationIcon(PACKAGE_NAME)); 459 assertNotNull(mPackageManager.getApplicationIcon(mPackageManager.getApplicationInfo( 460 PACKAGE_NAME, 0))); 461 assertNotNull(mPackageManager 462 .getActivityIcon(new ComponentName(PACKAGE_NAME, ACTIVITY_NAME))); 463 assertNotNull(mPackageManager.getActivityIcon(new Intent(MAIN_ACTION_NAME))); 464 assertNotNull(mPackageManager.getDefaultActivityIcon()); 465 466 // getDrawable is called by ComponentInfo.loadIcon() which called by getActivityIcon() 467 // method of PackageMaganer. Here is just assurance for its functionality. 468 int iconRes = R.drawable.start; 469 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 470 assertNotNull(mPackageManager.getDrawable(PACKAGE_NAME, iconRes, appInfo)); 471 } 472 473 @Test testCheckSignaturesMatch_byPackageName()474 public void testCheckSignaturesMatch_byPackageName() { 475 // Compare the signature of this package to another package installed by this test suite 476 // (see AndroidTest.xml). Their signatures must match. 477 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(PACKAGE_NAME, 478 "com.android.cts.stub")); 479 // This package's signature should match its own signature. 480 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(PACKAGE_NAME, 481 PACKAGE_NAME)); 482 } 483 484 @Test testCheckSignaturesMatch_byUid()485 public void testCheckSignaturesMatch_byUid() throws NameNotFoundException { 486 // Compare the signature of this package to another package installed by this test suite 487 // (see AndroidTest.xml). Their signatures must match. 488 int uid1 = mPackageManager.getPackageInfo(PACKAGE_NAME, 0).applicationInfo.uid; 489 int uid2 = mPackageManager.getPackageInfo("com.android.cts.stub", 0).applicationInfo.uid; 490 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(uid1, uid2)); 491 492 // A UID's signature should match its own signature. 493 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(uid1, uid1)); 494 } 495 496 @Test testCheckSignaturesNoMatch_byPackageName()497 public void testCheckSignaturesNoMatch_byPackageName() { 498 // This test package's signature shouldn't match the system's signature. 499 assertEquals(PackageManager.SIGNATURE_NO_MATCH, mPackageManager.checkSignatures( 500 PACKAGE_NAME, "android")); 501 } 502 503 @Test testCheckSignaturesNoMatch_byUid()504 public void testCheckSignaturesNoMatch_byUid() throws NameNotFoundException { 505 // This test package's signature shouldn't match the system's signature. 506 int uid1 = mPackageManager.getPackageInfo(PACKAGE_NAME, 0).applicationInfo.uid; 507 int uid2 = mPackageManager.getPackageInfo("android", 0).applicationInfo.uid; 508 assertEquals(PackageManager.SIGNATURE_NO_MATCH, 509 mPackageManager.checkSignatures(uid1, uid2)); 510 } 511 512 @Test testCheckSignaturesUnknownPackage()513 public void testCheckSignaturesUnknownPackage() { 514 assertEquals(PackageManager.SIGNATURE_UNKNOWN_PACKAGE, mPackageManager.checkSignatures( 515 PACKAGE_NAME, "this.package.does.not.exist")); 516 } 517 518 @Test testCheckPermissionGranted()519 public void testCheckPermissionGranted() { 520 assertEquals(PackageManager.PERMISSION_GRANTED, 521 mPackageManager.checkPermission(GRANTED_PERMISSION_NAME, PACKAGE_NAME)); 522 } 523 524 @Test testCheckPermissionNotGranted()525 public void testCheckPermissionNotGranted() { 526 assertEquals(PackageManager.PERMISSION_DENIED, 527 mPackageManager.checkPermission(NOT_GRANTED_PERMISSION_NAME, PACKAGE_NAME)); 528 } 529 530 @Test testResolveMethods()531 public void testResolveMethods() { 532 // Test resolveActivity 533 Intent intent = new Intent(ACTIVITY_ACTION_NAME); 534 intent.setComponent(new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)); 535 assertEquals(ACTIVITY_NAME, mPackageManager.resolveActivity(intent, 536 PackageManager.MATCH_DEFAULT_ONLY).activityInfo.name); 537 538 // Test resolveService 539 intent = new Intent(SERVICE_ACTION_NAME); 540 intent.setComponent(new ComponentName(PACKAGE_NAME, SERVICE_NAME)); 541 ResolveInfo resolveInfo = mPackageManager.resolveService(intent, 542 PackageManager.GET_INTENT_FILTERS); 543 assertEquals(SERVICE_NAME, resolveInfo.serviceInfo.name); 544 545 // Test resolveContentProvider 546 String providerAuthorities = "ctstest"; 547 assertEquals(PROVIDER_NAME, 548 mPackageManager.resolveContentProvider(providerAuthorities, 0).name); 549 } 550 551 @Test testGetResources()552 public void testGetResources() throws NameNotFoundException { 553 ComponentName componentName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME); 554 int resourceId = R.xml.pm_test; 555 String xmlName = "android.content.cts:xml/pm_test"; 556 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 557 assertNotNull(mPackageManager.getXml(PACKAGE_NAME, resourceId, appInfo)); 558 assertEquals(xmlName, mPackageManager.getResourcesForActivity(componentName) 559 .getResourceName(resourceId)); 560 assertEquals(xmlName, mPackageManager.getResourcesForApplication(appInfo).getResourceName( 561 resourceId)); 562 assertEquals(xmlName, mPackageManager.getResourcesForApplication(PACKAGE_NAME) 563 .getResourceName(resourceId)); 564 } 565 566 @Test testGetPackageArchiveInfo()567 public void testGetPackageArchiveInfo() throws Exception { 568 final String apkPath = InstrumentationRegistry.getContext().getPackageCodePath(); 569 final String apkName = InstrumentationRegistry.getContext().getPackageName(); 570 571 final int flags = PackageManager.GET_SIGNATURES; 572 573 final PackageInfo pkgInfo = mPackageManager.getPackageArchiveInfo(apkPath, flags); 574 575 assertEquals("getPackageArchiveInfo should return the correct package name", 576 apkName, pkgInfo.packageName); 577 578 assertNotNull("Signatures should have been collected when GET_SIGNATURES flag specified", 579 pkgInfo.signatures); 580 } 581 582 @Test testGetNamesForUids_null()583 public void testGetNamesForUids_null() throws Exception { 584 assertNull(mPackageManager.getNamesForUids(null)); 585 } 586 587 @Test testGetNamesForUids_empty()588 public void testGetNamesForUids_empty() throws Exception { 589 assertNull(mPackageManager.getNamesForUids(new int[0])); 590 } 591 592 @Test testGetNamesForUids_valid()593 public void testGetNamesForUids_valid() throws Exception { 594 final int shimId = 595 mPackageManager.getApplicationInfo("com.android.cts.ctsshim", 0 /*flags*/).uid; 596 final int[] uids = new int[] { 597 1000, 598 Integer.MAX_VALUE, 599 shimId, 600 }; 601 final String[] result; 602 result = mPackageManager.getNamesForUids(uids); 603 assertNotNull(result); 604 assertEquals(3, result.length); 605 assertEquals("shared:android.uid.system", result[0]); 606 assertEquals(null, result[1]); 607 assertEquals("com.android.cts.ctsshim", result[2]); 608 } 609 610 @Test testGetPackageUid()611 public void testGetPackageUid() throws NameNotFoundException { 612 int userId = InstrumentationRegistry.getContext().getUserId(); 613 int expectedUid = UserHandle.getUid(userId, 1000); 614 615 assertEquals(expectedUid, mPackageManager.getPackageUid("android", 0)); 616 617 int uid = mPackageManager.getApplicationInfo("com.android.cts.ctsshim", 0 /*flags*/).uid; 618 assertEquals(uid, mPackageManager.getPackageUid("com.android.cts.ctsshim", 0)); 619 } 620 621 @Test testGetPackageInfo()622 public void testGetPackageInfo() throws NameNotFoundException { 623 PackageInfo pkgInfo = mPackageManager.getPackageInfo(PACKAGE_NAME, GET_META_DATA 624 | GET_PERMISSIONS | GET_ACTIVITIES | GET_PROVIDERS | GET_SERVICES | GET_RECEIVERS); 625 assertTestPackageInfo(pkgInfo); 626 } 627 628 @Test testGetPackageInfo_notFound()629 public void testGetPackageInfo_notFound() { 630 try { 631 mPackageManager.getPackageInfo("this.package.does.not.exist", 0); 632 fail("Exception expected"); 633 } catch (NameNotFoundException expected) { 634 } 635 } 636 637 @Test testGetInstalledPackages()638 public void testGetInstalledPackages() throws Exception { 639 List<PackageInfo> pkgs = mPackageManager.getInstalledPackages(GET_META_DATA 640 | GET_PERMISSIONS | GET_ACTIVITIES | GET_PROVIDERS | GET_SERVICES | GET_RECEIVERS); 641 642 PackageInfo pkgInfo = findPackageOrFail(pkgs, PACKAGE_NAME); 643 assertTestPackageInfo(pkgInfo); 644 } 645 646 /** 647 * Asserts that the pkgInfo object correctly describes the {@link #PACKAGE_NAME} package. 648 */ assertTestPackageInfo(PackageInfo pkgInfo)649 private void assertTestPackageInfo(PackageInfo pkgInfo) { 650 // Check metadata 651 ApplicationInfo appInfo = pkgInfo.applicationInfo; 652 assertEquals(APPLICATION_NAME, appInfo.name); 653 assertEquals("Android TestCase", appInfo.loadLabel(mPackageManager)); 654 assertEquals(PACKAGE_NAME, appInfo.packageName); 655 assertTrue(appInfo.enabled); 656 // The process name defaults to the package name when not set. 657 assertEquals(PACKAGE_NAME, appInfo.processName); 658 assertEquals(0, appInfo.flags & FLAG_SYSTEM); 659 assertEquals(FLAG_INSTALLED, appInfo.flags & FLAG_INSTALLED); 660 assertEquals(FLAG_HAS_CODE, appInfo.flags & FLAG_HAS_CODE); 661 662 // Check required permissions 663 List<String> requestedPermissions = Arrays.asList(pkgInfo.requestedPermissions); 664 assertThat(requestedPermissions).containsAllOf( 665 "android.permission.MANAGE_ACCOUNTS", 666 "android.permission.ACCESS_NETWORK_STATE", 667 "android.content.cts.permission.TEST_GRANTED"); 668 669 // Check declared permissions 670 PermissionInfo declaredPermission = (PermissionInfo) findPackageItemOrFail( 671 pkgInfo.permissions, CALL_ABROAD_PERMISSION_NAME); 672 assertEquals("Call abroad", declaredPermission.loadLabel(mPackageManager)); 673 assertEquals(PERMISSIONGROUP_NAME, declaredPermission.group); 674 assertEquals(PermissionInfo.PROTECTION_NORMAL, declaredPermission.protectionLevel); 675 676 // Check if number of activities in PackageInfo matches number of activities in manifest, 677 // to make sure no synthesized activities not in the manifest are returned. 678 assertEquals("Number of activities in manifest != Number of activities in PackageInfo", 679 NUM_OF_ACTIVITIES_IN_MANIFEST, pkgInfo.activities.length); 680 // Check activities 681 ActivityInfo activity = findPackageItemOrFail(pkgInfo.activities, ACTIVITY_NAME); 682 assertTrue(activity.enabled); 683 assertTrue(activity.exported); // Has intent filters - export by default. 684 assertEquals(PACKAGE_NAME, activity.taskAffinity); 685 assertEquals(ActivityInfo.LAUNCH_SINGLE_TOP, activity.launchMode); 686 687 // Check services 688 ServiceInfo service = findPackageItemOrFail(pkgInfo.services, SERVICE_NAME); 689 assertTrue(service.enabled); 690 assertTrue(service.exported); // Has intent filters - export by default. 691 assertEquals(PACKAGE_NAME, service.packageName); 692 assertEquals(CALL_ABROAD_PERMISSION_NAME, service.permission); 693 694 // Check ContentProviders 695 ProviderInfo provider = findPackageItemOrFail(pkgInfo.providers, PROVIDER_NAME); 696 assertTrue(provider.enabled); 697 assertFalse(provider.exported); // Don't export by default. 698 assertEquals(PACKAGE_NAME, provider.packageName); 699 assertEquals("ctstest", provider.authority); 700 701 // Check Receivers 702 ActivityInfo receiver = findPackageItemOrFail(pkgInfo.receivers, RECEIVER_NAME); 703 assertTrue(receiver.enabled); 704 assertTrue(receiver.exported); // Has intent filters - export by default. 705 assertEquals(PACKAGE_NAME, receiver.packageName); 706 } 707 708 // Tests that other packages can be queried. 709 @Test testGetInstalledPackages_OtherPackages()710 public void testGetInstalledPackages_OtherPackages() throws Exception { 711 List<PackageInfo> pkgInfos = mPackageManager.getInstalledPackages(0); 712 713 // Check a normal package. 714 PackageInfo pkgInfo = findPackageOrFail(pkgInfos, "com.android.cts.stub"); // A test package 715 assertEquals(0, pkgInfo.applicationInfo.flags & FLAG_SYSTEM); 716 717 // Check a system package. 718 pkgInfo = findPackageOrFail(pkgInfos, "android"); 719 assertEquals(FLAG_SYSTEM, pkgInfo.applicationInfo.flags & FLAG_SYSTEM); 720 } 721 722 @Test testGetInstalledApplications()723 public void testGetInstalledApplications() throws Exception { 724 List<ApplicationInfo> apps = mPackageManager.getInstalledApplications(GET_META_DATA); 725 726 ApplicationInfo app = findPackageItemOrFail( 727 apps.toArray(new ApplicationInfo[] {}), APPLICATION_NAME); 728 729 assertEquals(APPLICATION_NAME, app.name); 730 assertEquals("Android TestCase", app.loadLabel(mPackageManager)); 731 assertEquals(PACKAGE_NAME, app.packageName); 732 assertTrue(app.enabled); 733 // The process name defaults to the package name when not set. 734 assertEquals(PACKAGE_NAME, app.processName); 735 } 736 findPackageOrFail(List<PackageInfo> pkgInfos, String pkgName)737 private PackageInfo findPackageOrFail(List<PackageInfo> pkgInfos, String pkgName) { 738 for (PackageInfo pkgInfo : pkgInfos) { 739 if (pkgName.equals(pkgInfo.packageName)) { 740 return pkgInfo; 741 } 742 } 743 fail("Package not found with name " + pkgName); 744 return null; 745 } 746 findPackageItemOrFail(T[] items, String name)747 private <T extends PackageItemInfo> T findPackageItemOrFail(T[] items, String name) { 748 for (T item : items) { 749 if (name.equals(item.name)) { 750 return item; 751 } 752 } 753 fail("Package item not found with name " + name); 754 return null; 755 } 756 757 @Test testGetPackagesHoldingPermissions()758 public void testGetPackagesHoldingPermissions() { 759 List<PackageInfo> pkgInfos = mPackageManager.getPackagesHoldingPermissions( 760 new String[] { GRANTED_PERMISSION_NAME }, 0); 761 findPackageOrFail(pkgInfos, PACKAGE_NAME); 762 763 pkgInfos = mPackageManager.getPackagesHoldingPermissions( 764 new String[] { NOT_GRANTED_PERMISSION_NAME }, 0); 765 for (PackageInfo pkgInfo : pkgInfos) { 766 if (PACKAGE_NAME.equals(pkgInfo.packageName)) { 767 fail("Must not return package " + PACKAGE_NAME); 768 } 769 } 770 } 771 772 @Test testGetPermissionInfo()773 public void testGetPermissionInfo() throws NameNotFoundException { 774 // Check a normal permission. 775 String permissionName = "android.permission.INTERNET"; 776 PermissionInfo permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 777 assertEquals(permissionName, permissionInfo.name); 778 assertEquals(PermissionInfo.PROTECTION_NORMAL, permissionInfo.getProtection()); 779 780 // Check a dangerous (runtime) permission. 781 permissionName = "android.permission.RECORD_AUDIO"; 782 permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 783 assertEquals(permissionName, permissionInfo.name); 784 assertEquals(PermissionInfo.PROTECTION_DANGEROUS, permissionInfo.getProtection()); 785 assertNotNull(permissionInfo.group); 786 787 // Check a signature permission. 788 permissionName = "android.permission.MODIFY_PHONE_STATE"; 789 permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 790 assertEquals(permissionName, permissionInfo.name); 791 assertEquals(PermissionInfo.PROTECTION_SIGNATURE, permissionInfo.getProtection()); 792 793 // Check a special access (appop) permission. 794 permissionName = "android.permission.SYSTEM_ALERT_WINDOW"; 795 permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 796 assertEquals(permissionName, permissionInfo.name); 797 assertEquals(PermissionInfo.PROTECTION_SIGNATURE, permissionInfo.getProtection()); 798 assertEquals(PermissionInfo.PROTECTION_FLAG_APPOP, 799 permissionInfo.getProtectionFlags() & PermissionInfo.PROTECTION_FLAG_APPOP); 800 } 801 802 @Test testGetPermissionInfo_notFound()803 public void testGetPermissionInfo_notFound() { 804 try { 805 mPackageManager.getPermissionInfo("android.permission.nonexistent.permission", 0); 806 fail("Exception expected"); 807 } catch (NameNotFoundException expected) { 808 } 809 } 810 811 @Test testGetPermissionGroupInfo()812 public void testGetPermissionGroupInfo() throws NameNotFoundException { 813 PermissionGroupInfo groupInfo = mPackageManager.getPermissionGroupInfo( 814 PERMISSIONGROUP_NAME, 0); 815 assertEquals(PERMISSIONGROUP_NAME, groupInfo.name); 816 assertEquals(PACKAGE_NAME, groupInfo.packageName); 817 assertFalse(TextUtils.isEmpty(groupInfo.loadDescription(mPackageManager))); 818 } 819 820 @Test testGetPermissionGroupInfo_notFound()821 public void testGetPermissionGroupInfo_notFound() throws NameNotFoundException { 822 try { 823 mPackageManager.getPermissionGroupInfo("this.group.does.not.exist", 0); 824 fail("Exception expected"); 825 } catch (NameNotFoundException expected) { 826 } 827 } 828 829 @Test testAddPermission_cantAddOutsideRoot()830 public void testAddPermission_cantAddOutsideRoot() { 831 PermissionInfo permissionInfo = new PermissionInfo(); 832 permissionInfo.name = "some.other.permission.tree.some-permission"; 833 permissionInfo.nonLocalizedLabel = "Some Permission"; 834 permissionInfo.protectionLevel = PermissionInfo.PROTECTION_NORMAL; 835 // Remove first 836 try { 837 mPackageManager.removePermission(permissionInfo.name); 838 } catch (SecurityException se) { 839 } 840 try { 841 mPackageManager.addPermission(permissionInfo); 842 fail("Must not add permission outside the permission tree defined in the manifest."); 843 } catch (SecurityException expected) { 844 } 845 } 846 847 @Test testAddPermission()848 public void testAddPermission() throws NameNotFoundException { 849 PermissionInfo permissionInfo = new PermissionInfo(); 850 permissionInfo.name = PERMISSION_TREE_ROOT + ".some-permission"; 851 permissionInfo.protectionLevel = PermissionInfo.PROTECTION_NORMAL; 852 permissionInfo.nonLocalizedLabel = "Some Permission"; 853 // Remove first 854 try { 855 mPackageManager.removePermission(permissionInfo.name); 856 } catch (SecurityException se) { 857 } 858 mPackageManager.addPermission(permissionInfo); 859 PermissionInfo savedInfo = mPackageManager.getPermissionInfo(permissionInfo.name, 0); 860 assertEquals(PACKAGE_NAME, savedInfo.packageName); 861 assertEquals(PermissionInfo.PROTECTION_NORMAL, savedInfo.protectionLevel); 862 } 863 864 @Test testGetPackageInfo_ApexSupported_ApexPackage_MatchesApex()865 public void testGetPackageInfo_ApexSupported_ApexPackage_MatchesApex() throws Exception { 866 // This really should be a assumeTrue(isUpdatingApexSupported()), but JUnit3 doesn't support 867 // assumptions framework. 868 // TODO: change to assumeTrue after migrating tests to JUnit4. 869 if (!isUpdatingApexSupported()) { 870 Log.i(TAG, "Device doesn't support updating APEX"); 871 return; 872 } 873 PackageInfo packageInfo = mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 874 PackageManager.MATCH_APEX); 875 assertShimApexInfoIsCorrect(packageInfo); 876 } 877 878 @Test testGetPackageInfo_ApexSupported_ApexPackage_DoesNotMatchApex()879 public void testGetPackageInfo_ApexSupported_ApexPackage_DoesNotMatchApex() { 880 // This really should be a assumeTrue(isUpdatingApexSupported()), but JUnit3 doesn't support 881 // assumptions framework. 882 // TODO: change to assumeTrue after migrating tests to JUnit4. 883 if (!isUpdatingApexSupported()) { 884 Log.i(TAG, "Device doesn't support updating APEX"); 885 return; 886 } 887 try { 888 mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 0 /* flags */); 889 fail("NameNotFoundException expected"); 890 } catch (NameNotFoundException expected) { 891 } 892 } 893 894 @Test testGetPackageInfo_ApexNotSupported_ApexPackage_MatchesApex()895 public void testGetPackageInfo_ApexNotSupported_ApexPackage_MatchesApex() { 896 if (isUpdatingApexSupported()) { 897 Log.i(TAG, "Device supports updating APEX"); 898 return; 899 } 900 try { 901 mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, PackageManager.MATCH_APEX); 902 fail("NameNotFoundException expected"); 903 } catch (NameNotFoundException expected) { 904 } 905 } 906 907 @Test testGetPackageInfo_ApexNotSupported_ApexPackage_DoesNotMatchApex()908 public void testGetPackageInfo_ApexNotSupported_ApexPackage_DoesNotMatchApex() { 909 if (isUpdatingApexSupported()) { 910 Log.i(TAG, "Device supports updating APEX"); 911 return; 912 } 913 try { 914 mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 0); 915 fail("NameNotFoundException expected"); 916 } catch (NameNotFoundException expected) { 917 } 918 } 919 920 @Test testGetInstalledPackages_ApexSupported_MatchesApex()921 public void testGetInstalledPackages_ApexSupported_MatchesApex() { 922 if (!isUpdatingApexSupported()) { 923 Log.i(TAG, "Device doesn't support updating APEX"); 924 return; 925 } 926 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages( 927 PackageManager.MATCH_APEX); 928 List<PackageInfo> shimApex = installedPackages.stream().filter( 929 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 930 Collectors.toList()); 931 assertWithMessage("More than one shim apex found").that(shimApex).hasSize(1); 932 assertShimApexInfoIsCorrect(shimApex.get(0)); 933 } 934 935 @Test testGetInstalledPackages_ApexSupported_DoesNotMatchApex()936 public void testGetInstalledPackages_ApexSupported_DoesNotMatchApex() { 937 if (!isUpdatingApexSupported()) { 938 Log.i(TAG, "Device doesn't support updating APEX"); 939 return; 940 } 941 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(0); 942 List<PackageInfo> shimApex = installedPackages.stream().filter( 943 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 944 Collectors.toList()); 945 assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty(); 946 } 947 948 @Test testGetInstalledPackages_ApexNotSupported_MatchesApex()949 public void testGetInstalledPackages_ApexNotSupported_MatchesApex() { 950 if (isUpdatingApexSupported()) { 951 Log.i(TAG, "Device supports updating APEX"); 952 return; 953 } 954 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages( 955 PackageManager.MATCH_APEX); 956 List<PackageInfo> shimApex = installedPackages.stream().filter( 957 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 958 Collectors.toList()); 959 assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty(); 960 } 961 962 @Test testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex()963 public void testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex() { 964 if (isUpdatingApexSupported()) { 965 Log.i(TAG, "Device supports updating APEX"); 966 return; 967 } 968 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(0); 969 List<PackageInfo> shimApex = installedPackages.stream().filter( 970 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 971 Collectors.toList()); 972 assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty(); 973 } 974 isUpdatingApexSupported()975 private boolean isUpdatingApexSupported() { 976 return SystemProperties.getBoolean("ro.apex.updatable", false); 977 } 978 assertShimApexInfoIsCorrect(PackageInfo packageInfo)979 private static void assertShimApexInfoIsCorrect(PackageInfo packageInfo) { 980 assertThat(packageInfo.packageName).isEqualTo(SHIM_APEX_PACKAGE_NAME); 981 assertThat(packageInfo.getLongVersionCode()).isEqualTo(1); 982 assertThat(packageInfo.isApex).isTrue(); 983 assertThat(packageInfo.applicationInfo.sourceDir).isEqualTo( 984 "/system/apex/com.android.apex.cts.shim.apex"); 985 // Verify that legacy mechanism for handling signatures is supported. 986 Signature[] pastSigningCertificates = 987 packageInfo.signingInfo.getSigningCertificateHistory(); 988 assertThat(packageInfo.signatures) 989 .asList().containsExactly((Object[]) pastSigningCertificates); 990 } 991 } 992