• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.robolectric.shadows;
2 
3 import static android.content.pm.ApplicationInfo.FLAG_ALLOW_BACKUP;
4 import static android.content.pm.ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA;
5 import static android.content.pm.ApplicationInfo.FLAG_ALLOW_TASK_REPARENTING;
6 import static android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE;
7 import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE;
8 import static android.content.pm.ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS;
9 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS;
10 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS;
11 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES;
12 import static android.content.pm.ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS;
13 import static android.content.pm.ApplicationInfo.FLAG_VM_SAFE_MODE;
14 import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
15 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
16 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
17 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
18 import static android.content.pm.PackageManager.PERMISSION_DENIED;
19 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20 import static android.content.pm.PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
21 import static android.content.pm.PackageManager.SIGNATURE_MATCH;
22 import static android.content.pm.PackageManager.SIGNATURE_NEITHER_SIGNED;
23 import static android.content.pm.PackageManager.SIGNATURE_NO_MATCH;
24 import static android.content.pm.PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
25 import static android.content.pm.PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
26 import static android.content.pm.PackageManager.VERIFICATION_ALLOW;
27 import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
28 import static android.os.Build.VERSION_CODES.LOLLIPOP;
29 import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1;
30 import static android.os.Build.VERSION_CODES.M;
31 import static android.os.Build.VERSION_CODES.N;
32 import static android.os.Build.VERSION_CODES.N_MR1;
33 import static android.os.Build.VERSION_CODES.O;
34 import static com.google.common.truth.Truth.assertThat;
35 import static org.junit.Assert.assertEquals;
36 import static org.junit.Assert.fail;
37 import static org.mockito.Mockito.eq;
38 import static org.mockito.Mockito.mock;
39 import static org.mockito.Mockito.verify;
40 import static org.mockito.Mockito.verifyZeroInteractions;
41 import static org.robolectric.Robolectric.setupActivity;
42 import static org.robolectric.Shadows.shadowOf;
43 
44 import android.Manifest;
45 import android.Manifest.permission_group;
46 import android.app.Activity;
47 import android.app.admin.DevicePolicyManager;
48 import android.content.ComponentName;
49 import android.content.Context;
50 import android.content.Intent;
51 import android.content.IntentFilter;
52 import android.content.pm.ActivityInfo;
53 import android.content.pm.ApplicationInfo;
54 import android.content.pm.ChangedPackages;
55 import android.content.pm.FeatureInfo;
56 import android.content.pm.IPackageDeleteObserver;
57 import android.content.pm.IPackageStatsObserver;
58 import android.content.pm.PackageInfo;
59 import android.content.pm.PackageInstaller;
60 import android.content.pm.PackageManager;
61 import android.content.pm.PackageManager.NameNotFoundException;
62 import android.content.pm.PackageParser.Package;
63 import android.content.pm.PackageParser.PermissionGroup;
64 import android.content.pm.PackageStats;
65 import android.content.pm.PathPermission;
66 import android.content.pm.PermissionGroupInfo;
67 import android.content.pm.PermissionInfo;
68 import android.content.pm.ProviderInfo;
69 import android.content.pm.ResolveInfo;
70 import android.content.pm.ServiceInfo;
71 import android.content.pm.Signature;
72 import android.content.res.XmlResourceParser;
73 import android.graphics.Color;
74 import android.graphics.drawable.BitmapDrawable;
75 import android.graphics.drawable.Drawable;
76 import android.net.Uri;
77 import android.os.Bundle;
78 import android.os.PersistableBundle;
79 import android.os.Process;
80 import android.provider.DocumentsContract;
81 import androidx.test.core.app.ApplicationProvider;
82 import androidx.test.ext.junit.runners.AndroidJUnit4;
83 import com.google.common.base.Function;
84 import com.google.common.collect.Iterables;
85 import java.io.ByteArrayInputStream;
86 import java.io.File;
87 import java.util.ArrayList;
88 import java.util.List;
89 import javax.annotation.Nullable;
90 import org.junit.Before;
91 import org.junit.Rule;
92 import org.junit.Test;
93 import org.junit.rules.TemporaryFolder;
94 import org.junit.runner.RunWith;
95 import org.mockito.ArgumentCaptor;
96 import org.robolectric.R;
97 import org.robolectric.Robolectric;
98 import org.robolectric.annotation.Config;
99 import org.robolectric.shadows.ShadowPackageManager.PackageSetting;
100 
101 @RunWith(AndroidJUnit4.class)
102 public class ShadowPackageManagerTest {
103 
104   private static final String TEST_PACKAGE_NAME = "com.some.other.package";
105   private static final String TEST_PACKAGE_LABEL = "My Little App";
106   private static final String TEST_APP_PATH = "/values/app/application.apk";
107   private static final String TEST_PACKAGE2_NAME = "com.a.second.package";
108   private static final String TEST_PACKAGE2_LABEL = "A Second App";
109   private static final String TEST_APP2_PATH = "/values/app/application2.apk";
110   protected ShadowPackageManager shadowPackageManager;
111   @Rule
112   public TemporaryFolder temporaryFolder = new TemporaryFolder();
113   private PackageManager packageManager;
114 
115   private final ArgumentCaptor<PackageStats> packageStatsCaptor = ArgumentCaptor.forClass(PackageStats.class);
116 
117   @Before
setUp()118   public void setUp() {
119     packageManager =
120         ApplicationProvider.getApplicationContext().getPackageManager();
121     shadowPackageManager = shadowOf(packageManager);
122   }
123 
124   @Test
125   @Config(minSdk = LOLLIPOP)
packageInstallerCreateSession()126   public void packageInstallerCreateSession() throws Exception {
127     PackageInstaller packageInstaller =
128         ApplicationProvider.getApplicationContext()
129             .getPackageManager()
130             .getPackageInstaller();
131     int sessionId = packageInstaller.createSession(createSessionParams("packageName"));
132 
133     PackageInstaller.SessionInfo sessionInfo = packageInstaller.getSessionInfo(sessionId);
134     assertThat(sessionInfo.isActive()).isTrue();
135 
136     assertThat(sessionInfo.appPackageName).isEqualTo("packageName");
137 
138     packageInstaller.abandonSession(sessionId);
139 
140     assertThat(packageInstaller.getSessionInfo(sessionId)).isNull();
141   }
142 
143   @Test
144   @Config(minSdk = LOLLIPOP)
packageInstallerOpenSession()145   public void packageInstallerOpenSession() throws Exception {
146     PackageInstaller packageInstaller =
147         ApplicationProvider.getApplicationContext()
148             .getPackageManager()
149             .getPackageInstaller();
150     int sessionId = packageInstaller.createSession(createSessionParams("packageName"));
151 
152     PackageInstaller.Session session = packageInstaller.openSession(sessionId);
153 
154     assertThat(session).isNotNull();
155   }
156 
createSessionParams(String appPackageName)157   private static PackageInstaller.SessionParams createSessionParams(String appPackageName) {
158     PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
159     params.setAppPackageName(appPackageName);
160     return params;
161   }
162 
163   @Test
packageInstallerAndGetPackageArchiveInfo()164   public void packageInstallerAndGetPackageArchiveInfo() {
165     ApplicationInfo appInfo = new ApplicationInfo();
166     appInfo.flags = ApplicationInfo.FLAG_INSTALLED;
167     appInfo.packageName = TEST_PACKAGE_NAME;
168     appInfo.sourceDir = TEST_APP_PATH;
169     appInfo.name = TEST_PACKAGE_LABEL;
170 
171     PackageInfo packageInfo = new PackageInfo();
172     packageInfo.packageName = TEST_PACKAGE_NAME;
173     packageInfo.applicationInfo = appInfo;
174     shadowPackageManager.installPackage(packageInfo);
175 
176     PackageInfo packageInfoResult = shadowPackageManager.getPackageArchiveInfo(TEST_APP_PATH, 0);
177     assertThat(packageInfoResult).isNotNull();
178     ApplicationInfo applicationInfo = packageInfoResult.applicationInfo;
179     assertThat(applicationInfo).isInstanceOf(ApplicationInfo.class);
180     assertThat(applicationInfo.packageName).isEqualTo(TEST_PACKAGE_NAME);
181     assertThat(applicationInfo.sourceDir).isEqualTo(TEST_APP_PATH);
182   }
183 
184   @Test
applicationFlags()185   public void applicationFlags() throws Exception {
186     int flags = packageManager.getApplicationInfo("org.robolectric", 0).flags;
187     assertThat((flags & FLAG_ALLOW_BACKUP)).isEqualTo(FLAG_ALLOW_BACKUP);
188     assertThat((flags & FLAG_ALLOW_CLEAR_USER_DATA)).isEqualTo(FLAG_ALLOW_CLEAR_USER_DATA);
189     assertThat((flags & FLAG_ALLOW_TASK_REPARENTING)).isEqualTo(FLAG_ALLOW_TASK_REPARENTING);
190     assertThat((flags & FLAG_DEBUGGABLE)).isEqualTo(FLAG_DEBUGGABLE);
191     assertThat((flags & FLAG_HAS_CODE)).isEqualTo(FLAG_HAS_CODE);
192     assertThat((flags & FLAG_RESIZEABLE_FOR_SCREENS)).isEqualTo(FLAG_RESIZEABLE_FOR_SCREENS);
193     assertThat((flags & FLAG_SUPPORTS_LARGE_SCREENS)).isEqualTo(FLAG_SUPPORTS_LARGE_SCREENS);
194     assertThat((flags & FLAG_SUPPORTS_NORMAL_SCREENS)).isEqualTo(FLAG_SUPPORTS_NORMAL_SCREENS);
195     assertThat((flags & FLAG_SUPPORTS_SCREEN_DENSITIES)).isEqualTo(FLAG_SUPPORTS_SCREEN_DENSITIES);
196     assertThat((flags & FLAG_SUPPORTS_SMALL_SCREENS)).isEqualTo(FLAG_SUPPORTS_SMALL_SCREENS);
197     assertThat((flags & FLAG_VM_SAFE_MODE)).isEqualTo(FLAG_VM_SAFE_MODE);
198   }
199 
200   /**
201    * Tests the permission grants of this test package.
202    *
203    * <p>These grants are defined in the test package's AndroidManifest.xml.
204    */
205   @Test
testCheckPermission_thisPackage()206   public void testCheckPermission_thisPackage() throws Exception {
207     String thisPackage =
208         ApplicationProvider.getApplicationContext().getPackageName();
209     assertEquals(PERMISSION_GRANTED, packageManager.checkPermission(
210         "android.permission.INTERNET", thisPackage));
211     assertEquals(PERMISSION_GRANTED, packageManager.checkPermission(
212         "android.permission.SYSTEM_ALERT_WINDOW", thisPackage));
213     assertEquals(PERMISSION_GRANTED, packageManager.checkPermission(
214         "android.permission.GET_TASKS", thisPackage));
215 
216     assertEquals(PERMISSION_DENIED, packageManager.checkPermission(
217         "android.permission.ACCESS_FINE_LOCATION", thisPackage));
218     assertEquals(PERMISSION_DENIED, packageManager.checkPermission(
219         "android.permission.ACCESS_FINE_LOCATION", "random-package"));
220   }
221 
222   /**
223    * Tests the permission grants of other packages. These packages are added to the
224    * PackageManager by calling {@link ShadowPackageManager#addPackage}.
225    */
226   @Test
testCheckPermission_otherPackages()227   public void testCheckPermission_otherPackages() throws Exception {
228     PackageInfo packageInfo = new PackageInfo();
229     packageInfo.packageName = TEST_PACKAGE_NAME;
230     packageInfo.requestedPermissions = new String[] {
231         "android.permission.INTERNET", "android.permission.SEND_SMS" };
232     // Grant one of the permissions.
233     packageInfo.requestedPermissionsFlags = new int[] {
234         REQUESTED_PERMISSION_GRANTED, 0 /* this permission isn't granted */ };
235     shadowPackageManager.installPackage(packageInfo);
236 
237     assertEquals(PERMISSION_GRANTED, packageManager.checkPermission(
238         "android.permission.INTERNET", TEST_PACKAGE_NAME));
239     assertEquals(PERMISSION_DENIED, packageManager.checkPermission(
240         "android.permission.SEND_SMS", TEST_PACKAGE_NAME));
241     assertEquals(PERMISSION_DENIED, packageManager.checkPermission(
242         "android.permission.READ_SMS", TEST_PACKAGE_NAME));
243   }
244 
245   /**
246    * Tests the permission grants of other packages. These packages are added to the
247    * PackageManager by calling {@link ShadowPackageManager#addPackage}.
248    */
249   @Test
testCheckPermission_otherPackages_grantedByDefault()250   public void testCheckPermission_otherPackages_grantedByDefault() throws Exception {
251     PackageInfo packageInfo = new PackageInfo();
252     packageInfo.packageName = TEST_PACKAGE_NAME;
253     packageInfo.requestedPermissions = new String[] {
254         "android.permission.INTERNET", "android.permission.SEND_SMS" };
255     shadowPackageManager.installPackage(packageInfo);
256 
257     // Because we didn't specify permission grant state in the PackageInfo object, all requested
258     // permissions are automatically granted. See ShadowPackageManager.grantPermissionsByDefault()
259     // for the explanation.
260     assertEquals(PERMISSION_GRANTED, packageManager.checkPermission(
261         "android.permission.INTERNET", TEST_PACKAGE_NAME));
262     assertEquals(PERMISSION_GRANTED, packageManager.checkPermission(
263         "android.permission.SEND_SMS", TEST_PACKAGE_NAME));
264     assertEquals(PERMISSION_DENIED, packageManager.checkPermission(
265         "android.permission.READ_SMS", TEST_PACKAGE_NAME));
266   }
267 
268   @Test
269   @Config(minSdk = M)
testGrantRuntimePermission()270   public void testGrantRuntimePermission() throws Exception {
271     PackageInfo packageInfo = new PackageInfo();
272     packageInfo.packageName = TEST_PACKAGE_NAME;
273     packageInfo.requestedPermissions =
274         new String[] {"android.permission.SEND_SMS", "android.permission.READ_SMS"};
275     packageInfo.requestedPermissionsFlags = new int[] {0, 0}; // Not granted by default
276     shadowPackageManager.installPackage(packageInfo);
277 
278     packageManager.grantRuntimePermission(
279         TEST_PACKAGE_NAME, "android.permission.SEND_SMS", Process.myUserHandle());
280 
281     assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(REQUESTED_PERMISSION_GRANTED);
282     assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(0);
283 
284     packageManager.grantRuntimePermission(
285         TEST_PACKAGE_NAME, "android.permission.READ_SMS", Process.myUserHandle());
286 
287     assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(REQUESTED_PERMISSION_GRANTED);
288     assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(REQUESTED_PERMISSION_GRANTED);
289   }
290 
291   @Test
292   @Config(minSdk = M)
testGrantRuntimePermission_packageNotFound()293   public void testGrantRuntimePermission_packageNotFound() throws Exception {
294     try {
295       packageManager.grantRuntimePermission(
296           "com.unknown.package", "android.permission.SEND_SMS", Process.myUserHandle());
297       fail("Exception expected");
298     } catch (SecurityException expected) {
299     }
300   }
301 
302   @Test
303   @Config(minSdk = M)
testGrantRuntimePermission_doesntRequestPermission()304   public void testGrantRuntimePermission_doesntRequestPermission() throws Exception {
305     PackageInfo packageInfo = new PackageInfo();
306     packageInfo.packageName = TEST_PACKAGE_NAME;
307     packageInfo.requestedPermissions =
308         new String[] {"android.permission.SEND_SMS", "android.permission.READ_SMS"};
309     packageInfo.requestedPermissionsFlags = new int[] {0, 0}; // Not granted by default
310     shadowPackageManager.installPackage(packageInfo);
311 
312     try {
313       packageManager.grantRuntimePermission(
314           // This permission is not granted to the package.
315           TEST_PACKAGE_NAME, "android.permission.RECEIVE_SMS", Process.myUserHandle());
316       fail("Exception expected");
317     } catch (SecurityException expected) {
318     }
319   }
320 
321   @Test
322   @Config(minSdk = M)
testRevokeRuntimePermission()323   public void testRevokeRuntimePermission() throws Exception {
324     PackageInfo packageInfo = new PackageInfo();
325     packageInfo.packageName = TEST_PACKAGE_NAME;
326     packageInfo.requestedPermissions =
327         new String[] {"android.permission.SEND_SMS", "android.permission.READ_SMS"};
328     packageInfo.requestedPermissionsFlags =
329         new int[] {REQUESTED_PERMISSION_GRANTED, REQUESTED_PERMISSION_GRANTED};
330     shadowPackageManager.installPackage(packageInfo);
331 
332     packageManager.revokeRuntimePermission(
333         TEST_PACKAGE_NAME, "android.permission.SEND_SMS", Process.myUserHandle());
334 
335     assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(0);
336     assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(REQUESTED_PERMISSION_GRANTED);
337 
338     packageManager.revokeRuntimePermission(
339         TEST_PACKAGE_NAME, "android.permission.READ_SMS", Process.myUserHandle());
340 
341     assertThat(packageInfo.requestedPermissionsFlags[0]).isEqualTo(0);
342     assertThat(packageInfo.requestedPermissionsFlags[1]).isEqualTo(0);
343   }
344 
345   @Test
testQueryBroadcastReceiverSucceeds()346   public void testQueryBroadcastReceiverSucceeds() {
347     Intent intent = new Intent("org.robolectric.ACTION_RECEIVER_PERMISSION_PACKAGE");
348     intent.setPackage(ApplicationProvider.getApplicationContext().getPackageName());
349 
350     List<ResolveInfo> receiverInfos = packageManager.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS);
351     assertThat(receiverInfos).isNotEmpty();
352     assertThat(receiverInfos.get(0).activityInfo.name)
353         .isEqualTo("org.robolectric.ConfigTestReceiverPermissionsAndActions");
354     assertThat(receiverInfos.get(0).activityInfo.permission)
355         .isEqualTo("org.robolectric.CUSTOM_PERM");
356     assertThat(receiverInfos.get(0).filter.getAction(0))
357         .isEqualTo("org.robolectric.ACTION_RECEIVER_PERMISSION_PACKAGE");
358   }
359 
360   @Test
testQueryBroadcastReceiverFailsForMissingPackageName()361   public void testQueryBroadcastReceiverFailsForMissingPackageName() {
362     Intent intent = new Intent("org.robolectric.ACTION_ONE_MORE_PACKAGE");
363     List<ResolveInfo> receiverInfos = packageManager.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS);
364     assertThat(receiverInfos).hasSize(0);
365   }
366 
367   @Test
testQueryBroadcastReceiver_matchAllWithoutIntentFilter()368   public void testQueryBroadcastReceiver_matchAllWithoutIntentFilter() {
369     Intent intent = new Intent();
370     intent.setPackage(ApplicationProvider.getApplicationContext().getPackageName());
371     List<ResolveInfo> receiverInfos = packageManager.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS);
372     assertThat(receiverInfos).hasSize(7);
373 
374     for (ResolveInfo receiverInfo : receiverInfos) {
375       assertThat(receiverInfo.activityInfo.name)
376           .isNotEqualTo("com.bar.ReceiverWithoutIntentFilter");
377     }
378   }
379 
380   @Test
testGetPackageInfo_ForReceiversSucceeds()381   public void testGetPackageInfo_ForReceiversSucceeds() throws Exception {
382     PackageInfo receiverInfos =
383         packageManager.getPackageInfo(
384             ApplicationProvider.getApplicationContext().getPackageName(),
385             PackageManager.GET_RECEIVERS);
386 
387     assertThat(receiverInfos.receivers).isNotEmpty();
388     assertThat(receiverInfos.receivers[0].name).isEqualTo("org.robolectric.ConfigTestReceiver.InnerReceiver");
389     assertThat(receiverInfos.receivers[0].permission).isEqualTo("com.ignored.PERM");
390   }
391 
392   public static class ActivityWithConfigChanges extends Activity { }
393 
394   @Test
getActivityMetaData_configChanges()395   public void getActivityMetaData_configChanges() throws Exception {
396     Activity activity = setupActivity(ShadowPackageManagerTest.ActivityWithConfigChanges.class);
397 
398     ActivityInfo activityInfo = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0);
399 
400     int configChanges = activityInfo.configChanges;
401     assertThat(configChanges & ActivityInfo.CONFIG_SCREEN_LAYOUT).isEqualTo(ActivityInfo.CONFIG_SCREEN_LAYOUT);
402     assertThat(configChanges & ActivityInfo.CONFIG_ORIENTATION).isEqualTo(ActivityInfo.CONFIG_ORIENTATION);
403 
404     // Spot check a few other possible values that shouldn't be in the flags.
405     assertThat(configChanges & ActivityInfo.CONFIG_FONT_SCALE).isEqualTo(0);
406     assertThat(configChanges & ActivityInfo.CONFIG_SCREEN_SIZE).isEqualTo(0);
407   }
408 
409   /** MCC + MNC are always present in config changes since Oreo. */
410   @Test
411   @Config(minSdk = O)
getActivityMetaData_configChangesAlwaysIncludesMccAndMnc()412   public void getActivityMetaData_configChangesAlwaysIncludesMccAndMnc() throws Exception {
413     Activity activity = setupActivity(ShadowPackageManagerTest.ActivityWithConfigChanges.class);
414 
415     ActivityInfo activityInfo =
416         activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0);
417 
418     int configChanges = activityInfo.configChanges;
419     assertThat(configChanges & ActivityInfo.CONFIG_MCC).isEqualTo(ActivityInfo.CONFIG_MCC);
420     assertThat(configChanges & ActivityInfo.CONFIG_MNC).isEqualTo(ActivityInfo.CONFIG_MNC);
421   }
422 
423   @Test
getPermissionInfo_withMinimalFields()424   public void getPermissionInfo_withMinimalFields() throws Exception {
425     PermissionInfo permission =
426         packageManager.getPermissionInfo("org.robolectric.permission_with_minimal_fields", 0);
427     assertThat(permission.labelRes).isEqualTo(0);
428     assertThat(permission.descriptionRes).isEqualTo(0);
429     assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_NORMAL);
430   }
431 
432   @Test
getPermissionInfo_addedPermissions()433   public void getPermissionInfo_addedPermissions() throws Exception {
434     PermissionInfo permissionInfo = new PermissionInfo();
435     permissionInfo.name = "manually_added_permission";
436     shadowPackageManager.addPermissionInfo(permissionInfo);
437     PermissionInfo permission = packageManager.getPermissionInfo("manually_added_permission", 0);
438     assertThat(permission.name).isEqualTo("manually_added_permission");
439   }
440 
441   @Test
getPermissionGroupInfo_fromManifest()442   public void getPermissionGroupInfo_fromManifest() throws Exception {
443     PermissionGroupInfo permissionGroupInfo =
444         ApplicationProvider.getApplicationContext()
445             .getPackageManager()
446             .getPermissionGroupInfo("org.robolectric.package_permission_group", 0);
447     assertThat(permissionGroupInfo.name).isEqualTo("org.robolectric.package_permission_group");
448   }
449 
450   @Test
getPermissionGroupInfo_extraPermissionGroup()451   public void getPermissionGroupInfo_extraPermissionGroup() throws Exception {
452     PermissionGroupInfo newCameraPermission = new PermissionGroupInfo();
453     newCameraPermission.name = permission_group.CAMERA;
454     shadowPackageManager.addPermissionGroupInfo(newCameraPermission);
455 
456     assertThat(packageManager.getPermissionGroupInfo(permission_group.CAMERA, 0).name)
457         .isEqualTo(newCameraPermission.name);
458   }
459 
460   @Test
getAllPermissionGroups_fromManifest()461   public void getAllPermissionGroups_fromManifest() throws Exception {
462     List<PermissionGroupInfo> allPermissionGroups = packageManager.getAllPermissionGroups(0);
463     assertThat(allPermissionGroups).hasSize(1);
464     assertThat(allPermissionGroups.get(0).name).isEqualTo("org.robolectric.package_permission_group");
465   }
466 
467   @Test
getAllPermissionGroups_duplicateInExtraPermissions()468   public void getAllPermissionGroups_duplicateInExtraPermissions() throws Exception {
469     assertThat(packageManager.getAllPermissionGroups(0)).hasSize(1);
470 
471     PermissionGroupInfo overriddenPermission = new PermissionGroupInfo();
472     overriddenPermission.name = "org.robolectric.package_permission_group";
473     shadowPackageManager.addPermissionGroupInfo(overriddenPermission);
474     PermissionGroupInfo newCameraPermission = new PermissionGroupInfo();
475     newCameraPermission.name = permission_group.CAMERA;
476     shadowPackageManager.addPermissionGroupInfo(newCameraPermission);
477 
478     List<PermissionGroupInfo> allPermissionGroups = packageManager.getAllPermissionGroups(0);
479     assertThat(allPermissionGroups).hasSize(2);
480   }
481 
482   @Test
getAllPermissionGroups_duplicatePermission()483   public void getAllPermissionGroups_duplicatePermission() throws Exception {
484     assertThat(packageManager.getAllPermissionGroups(0)).hasSize(1);
485 
486     // Package 1
487     Package pkg = new Package(TEST_PACKAGE_NAME);
488     ApplicationInfo appInfo = pkg.applicationInfo;
489     appInfo.flags = ApplicationInfo.FLAG_INSTALLED;
490     appInfo.packageName = TEST_PACKAGE_NAME;
491     appInfo.sourceDir = TEST_APP_PATH;
492     appInfo.name = TEST_PACKAGE_LABEL;
493     PermissionGroupInfo contactsPermissionGroupInfoApp1 = new PermissionGroupInfo();
494     contactsPermissionGroupInfoApp1.name = Manifest.permission_group.CONTACTS;
495     PermissionGroup contactsPermissionGroupApp1 =
496         new PermissionGroup(pkg, contactsPermissionGroupInfoApp1);
497     pkg.permissionGroups.add(contactsPermissionGroupApp1);
498     PermissionGroupInfo storagePermissionGroupInfoApp1 = new PermissionGroupInfo();
499     storagePermissionGroupInfoApp1.name = permission_group.STORAGE;
500     PermissionGroup storagePermissionGroupApp1 =
501         new PermissionGroup(pkg, storagePermissionGroupInfoApp1);
502     pkg.permissionGroups.add(storagePermissionGroupApp1);
503 
504     shadowPackageManager.addPackageInternal(pkg);
505 
506     // Package 2, contains one permission group that is the same
507     Package pkg2 = new Package(TEST_PACKAGE2_NAME);
508     ApplicationInfo appInfo2 = pkg2.applicationInfo;
509     appInfo2.flags = ApplicationInfo.FLAG_INSTALLED;
510     appInfo2.packageName = TEST_PACKAGE2_NAME;
511     appInfo2.sourceDir = TEST_APP2_PATH;
512     appInfo2.name = TEST_PACKAGE2_LABEL;
513     PermissionGroupInfo contactsPermissionGroupInfoApp2 = new PermissionGroupInfo();
514     contactsPermissionGroupInfoApp2.name = Manifest.permission_group.CONTACTS;
515     PermissionGroup contactsPermissionGroupApp2 =
516         new PermissionGroup(pkg2, contactsPermissionGroupInfoApp2);
517     pkg2.permissionGroups.add(contactsPermissionGroupApp2);
518     PermissionGroupInfo calendarPermissionGroupInfoApp2 = new PermissionGroupInfo();
519     calendarPermissionGroupInfoApp2.name = permission_group.CALENDAR;
520     PermissionGroup calendarPermissionGroupApp2 =
521         new PermissionGroup(pkg2, calendarPermissionGroupInfoApp2);
522     pkg2.permissionGroups.add(calendarPermissionGroupApp2);
523 
524     shadowPackageManager.addPackageInternal(pkg2);
525 
526     // Make sure that the duplicate permission group does not show up in the list
527     // Total list should be: contacts, storage, calendar, "org.robolectric.package_permission_group"
528     List<PermissionGroupInfo> allPermissionGroups = packageManager.getAllPermissionGroups(0);
529     assertThat(allPermissionGroups).hasSize(4);
530   }
531 
532   @Test
getPackageArchiveInfo()533   public void getPackageArchiveInfo() {
534     ApplicationInfo appInfo = new ApplicationInfo();
535     appInfo.flags = ApplicationInfo.FLAG_INSTALLED;
536     appInfo.packageName = TEST_PACKAGE_NAME;
537     appInfo.sourceDir = TEST_APP_PATH;
538     appInfo.name = TEST_PACKAGE_LABEL;
539 
540     PackageInfo packageInfo = new PackageInfo();
541     packageInfo.packageName = TEST_PACKAGE_NAME;
542     packageInfo.applicationInfo = appInfo;
543     shadowPackageManager.installPackage(packageInfo);
544 
545     PackageInfo packageInfoResult = shadowPackageManager.getPackageArchiveInfo(TEST_APP_PATH, 0);
546     assertThat(packageInfoResult).isNotNull();
547     ApplicationInfo applicationInfo = packageInfoResult.applicationInfo;
548     assertThat(applicationInfo).isInstanceOf(ApplicationInfo.class);
549     assertThat(applicationInfo.packageName).isEqualTo(TEST_PACKAGE_NAME);
550     assertThat(applicationInfo.sourceDir).isEqualTo(TEST_APP_PATH);
551   }
552 
553   @Test
getApplicationInfo_ThisApplication()554   public void getApplicationInfo_ThisApplication() throws Exception {
555     ApplicationInfo info =
556         packageManager.getApplicationInfo(
557             ApplicationProvider.getApplicationContext().getPackageName(), 0);
558     assertThat(info).isNotNull();
559     assertThat(info.packageName)
560         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
561   }
562 
563   @Test
getApplicationInfo_uninstalledApplication_includeUninstalled()564   public void getApplicationInfo_uninstalledApplication_includeUninstalled() throws Exception {
565     packageManager.setApplicationEnabledSetting(
566         ApplicationProvider.getApplicationContext().getPackageName(),
567         COMPONENT_ENABLED_STATE_DISABLED,
568         0);
569     ApplicationInfo info =
570         packageManager.getApplicationInfo(
571             ApplicationProvider.getApplicationContext().getPackageName(),
572             MATCH_UNINSTALLED_PACKAGES);
573     assertThat(info).isNotNull();
574     assertThat(info.packageName)
575         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
576   }
577 
578   @Test
getApplicationInfo_uninstalledApplication_dontIncludeUninstalled()579   public void getApplicationInfo_uninstalledApplication_dontIncludeUninstalled() throws Exception {
580     packageManager.setApplicationEnabledSetting(
581         ApplicationProvider.getApplicationContext().getPackageName(),
582         COMPONENT_ENABLED_STATE_DISABLED,
583         0);
584 
585     try {
586       packageManager.getApplicationInfo(
587           ApplicationProvider.getApplicationContext().getPackageName(), 0);
588       fail("PackageManager.NameNotFoundException not thrown");
589     } catch (PackageManager.NameNotFoundException e) {
590       // expected
591     }
592   }
593 
594   @Test
getApplicationInfo_disabledApplication_includeDisabled()595   public void getApplicationInfo_disabledApplication_includeDisabled() throws Exception {
596     packageManager.setApplicationEnabledSetting(
597         ApplicationProvider.getApplicationContext().getPackageName(),
598         COMPONENT_ENABLED_STATE_DISABLED,
599         0);
600     ApplicationInfo info =
601         packageManager.getApplicationInfo(
602             ApplicationProvider.getApplicationContext().getPackageName(),
603             MATCH_DISABLED_COMPONENTS);
604     assertThat(info).isNotNull();
605     assertThat(info.packageName)
606         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
607   }
608 
609   @Test(expected = PackageManager.NameNotFoundException.class)
getApplicationInfo_whenUnknown_shouldThrowNameNotFoundException()610   public void getApplicationInfo_whenUnknown_shouldThrowNameNotFoundException() throws Exception {
611     try {
612       packageManager.getApplicationInfo("unknown_package", 0);
613       fail("should have thrown NameNotFoundException");
614     } catch (PackageManager.NameNotFoundException e) {
615       assertThat(e.getMessage()).contains("unknown_package");
616       throw e;
617     }
618   }
619 
620   @Test
getApplicationInfo_OtherApplication()621   public void getApplicationInfo_OtherApplication() throws Exception {
622     PackageInfo packageInfo = new PackageInfo();
623     packageInfo.packageName = TEST_PACKAGE_NAME;
624     packageInfo.applicationInfo = new ApplicationInfo();
625     packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME;
626     packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL;
627     shadowPackageManager.installPackage(packageInfo);
628 
629     ApplicationInfo info = packageManager.getApplicationInfo(TEST_PACKAGE_NAME, 0);
630     assertThat(info).isNotNull();
631     assertThat(info.packageName).isEqualTo(TEST_PACKAGE_NAME);
632     assertThat(packageManager.getApplicationLabel(info).toString()).isEqualTo(TEST_PACKAGE_LABEL);
633   }
634 
635   @Test
removePackage_shouldHideItFromGetApplicationInfo()636   public void removePackage_shouldHideItFromGetApplicationInfo() {
637     PackageInfo packageInfo = new PackageInfo();
638     packageInfo.packageName = TEST_PACKAGE_NAME;
639     packageInfo.applicationInfo = new ApplicationInfo();
640     packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME;
641     packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL;
642     shadowPackageManager.installPackage(packageInfo);
643     shadowPackageManager.removePackage(TEST_PACKAGE_NAME);
644 
645     try {
646       packageManager.getApplicationInfo(TEST_PACKAGE_NAME, 0);
647       fail("NameNotFoundException not thrown");
648     } catch (NameNotFoundException e) {
649       // expected
650     }
651   }
652 
653   @Test
queryIntentActivities_EmptyResult()654   public void queryIntentActivities_EmptyResult() throws Exception {
655     Intent i = new Intent(Intent.ACTION_APP_ERROR, null);
656     i.addCategory(Intent.CATEGORY_APP_BROWSER);
657 
658     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
659     assertThat(activities).isEmpty();
660   }
661 
662   @Test
queryIntentActivities_Match()663   public void queryIntentActivities_Match() throws Exception {
664     Intent i = new Intent(Intent.ACTION_MAIN, null);
665     i.addCategory(Intent.CATEGORY_LAUNCHER);
666 
667     ResolveInfo info = new ResolveInfo();
668     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
669     info.activityInfo = new ActivityInfo();
670     info.activityInfo.name = "name";
671     info.activityInfo.packageName = TEST_PACKAGE_NAME;
672 
673     shadowPackageManager.addResolveInfoForIntent(i, info);
674 
675     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
676     assertThat(activities).isNotNull();
677     assertThat(activities).hasSize(2);
678     assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL);
679   }
680 
681   @Test
queryIntentActivities_ServiceMatch()682   public void queryIntentActivities_ServiceMatch() throws Exception {
683     Intent i = new Intent("SomeStrangeAction");
684 
685     ResolveInfo info = new ResolveInfo();
686     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
687     info.serviceInfo = new ServiceInfo();
688     info.serviceInfo.name = "name";
689     info.serviceInfo.packageName = TEST_PACKAGE_NAME;
690 
691     shadowPackageManager.addResolveInfoForIntent(i, info);
692 
693     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
694     assertThat(activities).isNotNull();
695     assertThat(activities).isEmpty();
696   }
697 
698   @Test
699   @Config(minSdk = JELLY_BEAN_MR1)
queryIntentActivitiesAsUser_EmptyResult()700   public void queryIntentActivitiesAsUser_EmptyResult() throws Exception {
701     Intent i = new Intent(Intent.ACTION_APP_ERROR, null);
702     i.addCategory(Intent.CATEGORY_APP_BROWSER);
703 
704     List<ResolveInfo> activities = packageManager.queryIntentActivitiesAsUser(i, 0, -1);
705     assertThat(activities).isEmpty();
706   }
707 
708   @Test
709   @Config(minSdk = JELLY_BEAN_MR1)
queryIntentActivitiesAsUser_Match()710   public void queryIntentActivitiesAsUser_Match() throws Exception {
711     Intent i = new Intent(Intent.ACTION_MAIN, null);
712     i.addCategory(Intent.CATEGORY_LAUNCHER);
713 
714     ResolveInfo info = new ResolveInfo();
715     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
716 
717     shadowPackageManager.addResolveInfoForIntent(i, info);
718 
719     List<ResolveInfo> activities = packageManager.queryIntentActivitiesAsUser(i, 0, -1);
720     assertThat(activities).isNotNull();
721     assertThat(activities).hasSize(2);
722     assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL);
723   }
724 
725   @Test
queryIntentActivities_launcher()726   public void queryIntentActivities_launcher() {
727     Intent intent = new Intent(Intent.ACTION_MAIN);
728     intent.addCategory(Intent.CATEGORY_LAUNCHER);
729 
730     List<ResolveInfo> resolveInfos =
731         packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
732     assertThat(resolveInfos).hasSize(1);
733 
734     assertThat(resolveInfos.get(0).activityInfo.name)
735         .isEqualTo("org.robolectric.shadows.TestActivityAlias");
736     assertThat(resolveInfos.get(0).activityInfo.targetActivity)
737         .isEqualTo("org.robolectric.shadows.TestActivity");
738   }
739 
740   @Test
queryIntentActivities_MatchSystemOnly()741   public void queryIntentActivities_MatchSystemOnly() throws Exception {
742     Intent i = new Intent(Intent.ACTION_MAIN, null);
743     i.addCategory(Intent.CATEGORY_LAUNCHER);
744 
745     ResolveInfo info1 = ShadowResolveInfo.newResolveInfo(TEST_PACKAGE_LABEL, TEST_PACKAGE_NAME);
746     ResolveInfo info2 = ShadowResolveInfo.newResolveInfo("System App", "system.launcher");
747     info2.activityInfo.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
748     info2.nonLocalizedLabel = "System App";
749 
750     shadowPackageManager.addResolveInfoForIntent(i, info1);
751     shadowPackageManager.addResolveInfoForIntent(i, info2);
752 
753     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, PackageManager.MATCH_SYSTEM_ONLY);
754     assertThat(activities).isNotNull();
755     assertThat(activities).hasSize(1);
756     assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo("System App");
757   }
758 
759   @Test
queryIntentActivities_EmptyResultWithNoMatchingImplicitIntents()760   public void queryIntentActivities_EmptyResultWithNoMatchingImplicitIntents() throws Exception {
761     Intent i = new Intent(Intent.ACTION_MAIN, null);
762     i.addCategory(Intent.CATEGORY_LAUNCHER);
763     i.setDataAndType(Uri.parse("content://testhost1.com:1/testPath/test.jpeg"), "image/jpeg");
764 
765     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
766     assertThat(activities).isEmpty();
767   }
768 
769   @Test
queryIntentActivities_MatchWithExplicitIntent()770   public void queryIntentActivities_MatchWithExplicitIntent() throws Exception {
771     Intent i = new Intent();
772     i.setClassName(
773         ApplicationProvider.getApplicationContext(),
774         "org.robolectric.shadows.TestActivity");
775 
776     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
777     assertThat(activities).isNotNull();
778     assertThat(activities).hasSize(1);
779     assertThat(activities.get(0).resolvePackageName).isEqualTo("org.robolectric");
780     assertThat(activities.get(0).activityInfo.name)
781         .isEqualTo("org.robolectric.shadows.TestActivity");
782   }
783 
784   @Test
queryIntentActivities_MatchWithImplicitIntents()785   public void queryIntentActivities_MatchWithImplicitIntents() throws Exception {
786     Uri uri = Uri.parse("content://testhost1.com:1/testPath/test.jpeg");
787     Intent i = new Intent(Intent.ACTION_VIEW);
788     i.addCategory(Intent.CATEGORY_DEFAULT);
789     i.setDataAndType(uri, "image/jpeg");
790 
791     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
792     assertThat(activities).isNotNull();
793     assertThat(activities).hasSize(1);
794     assertThat(activities.get(0).resolvePackageName).isEqualTo("org.robolectric");
795     assertThat(activities.get(0).activityInfo.name)
796         .isEqualTo("org.robolectric.shadows.TestActivity");
797   }
798 
799   @Test
queryIntentActivities_MatchWithAliasIntents()800   public void queryIntentActivities_MatchWithAliasIntents() throws Exception {
801     Intent i = new Intent(Intent.ACTION_MAIN);
802     i.addCategory(Intent.CATEGORY_LAUNCHER);
803 
804     List<ResolveInfo> activities = packageManager.queryIntentActivities(i, 0);
805     assertThat(activities).isNotNull();
806     assertThat(activities).hasSize(1);
807     assertThat(activities.get(0).resolvePackageName).isEqualTo("org.robolectric");
808     assertThat(activities.get(0).activityInfo.targetActivity).isEqualTo("org.robolectric.shadows.TestActivity");
809     assertThat(activities.get(0).activityInfo.name).isEqualTo("org.robolectric.shadows.TestActivityAlias");
810   }
811 
812   @Test
queryIntentActivities_DisabledComponentExplicitIntent()813   public void queryIntentActivities_DisabledComponentExplicitIntent() throws Exception {
814     Intent i = new Intent();
815     i.setClassName(
816         ApplicationProvider.getApplicationContext(),
817         "org.robolectric.shadows.TestActivity");
818 
819     ComponentName componentToDisable =
820         new ComponentName(
821             ApplicationProvider.getApplicationContext(),
822             "org.robolectric.shadows.TestActivity");
823     packageManager.setComponentEnabledSetting(
824         componentToDisable,
825         PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
826         PackageManager.DONT_KILL_APP);
827 
828     List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, 0);
829     assertThat(resolveInfos).isEmpty();
830   }
831 
832   @Test
queryIntentActivities_DisabledComponentImplicitIntent()833   public void queryIntentActivities_DisabledComponentImplicitIntent() throws Exception {
834     Uri uri = Uri.parse("content://testhost1.com:1/testPath/test.jpeg");
835     Intent i = new Intent(Intent.ACTION_VIEW);
836     i.addCategory(Intent.CATEGORY_DEFAULT);
837     i.setDataAndType(uri, "image/jpeg");
838 
839     ComponentName componentToDisable =
840         new ComponentName(
841             ApplicationProvider.getApplicationContext(),
842             "org.robolectric.shadows.TestActivity");
843     packageManager.setComponentEnabledSetting(
844         componentToDisable,
845         PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
846         PackageManager.DONT_KILL_APP);
847 
848     List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, 0);
849     assertThat(resolveInfos).isEmpty();
850   }
851 
852   @Test
queryIntentActivities_MatchDisabledComponents()853   public void queryIntentActivities_MatchDisabledComponents() throws Exception {
854     Uri uri = Uri.parse("content://testhost1.com:1/testPath/test.jpeg");
855     Intent i = new Intent(Intent.ACTION_VIEW);
856     i.addCategory(Intent.CATEGORY_DEFAULT);
857     i.setDataAndType(uri, "image/jpeg");
858 
859     ComponentName componentToDisable =
860         new ComponentName(
861             ApplicationProvider.getApplicationContext(),
862             "org.robolectric.shadows.TestActivity");
863     packageManager.setComponentEnabledSetting(
864         componentToDisable,
865         PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
866         PackageManager.DONT_KILL_APP);
867 
868     List<ResolveInfo> resolveInfos =
869         packageManager.queryIntentActivities(i, PackageManager.MATCH_DISABLED_COMPONENTS);
870     assertThat(resolveInfos).isNotNull();
871     assertThat(resolveInfos).hasSize(1);
872   }
873 
874   @Test
875   @Config(minSdk = LOLLIPOP)
queryIntentActivities_appHidden_includeUninstalled()876   public void queryIntentActivities_appHidden_includeUninstalled() {
877     String packageName =
878         ApplicationProvider.getApplicationContext().getPackageName();
879     packageManager.setApplicationHiddenSettingAsUser(
880         packageName, /* hidden= */ true, /* user= */ null);
881 
882     Intent i = new Intent();
883     i.setClassName(
884         ApplicationProvider.getApplicationContext(),
885         "org.robolectric.shadows.TestActivity");
886 
887     List<ResolveInfo> activities =
888         packageManager.queryIntentActivities(i, MATCH_UNINSTALLED_PACKAGES);
889     assertThat(activities).hasSize(1);
890     assertThat(activities.get(0).resolvePackageName).isEqualTo(packageName);
891     assertThat(activities.get(0).activityInfo.name)
892         .isEqualTo("org.robolectric.shadows.TestActivity");
893   }
894 
895   @Test
896   @Config(minSdk = LOLLIPOP)
queryIntentActivities_appHidden_dontIncludeUninstalled()897   public void queryIntentActivities_appHidden_dontIncludeUninstalled() {
898     String packageName =
899         ApplicationProvider.getApplicationContext().getPackageName();
900     packageManager.setApplicationHiddenSettingAsUser(
901         packageName, /* hidden= */ true, /* user= */ null);
902 
903     Intent i = new Intent();
904     i.setClassName(
905         ApplicationProvider.getApplicationContext(),
906         "org.robolectric.shadows.TestActivity");
907 
908     assertThat(packageManager.queryIntentActivities(i, /* flags= */ 0)).isEmpty();
909   }
910 
911   @Test
resolveActivity_Match()912   public void resolveActivity_Match() throws Exception {
913     Intent i = new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER);
914     ResolveInfo info = new ResolveInfo();
915     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
916     info.activityInfo = new ActivityInfo();
917     info.activityInfo.name = "name";
918     info.activityInfo.packageName = TEST_PACKAGE_NAME;
919     shadowPackageManager.addResolveInfoForIntent(i, info);
920 
921     assertThat(packageManager.resolveActivity(i, 0)).isNotNull();
922     assertThat(packageManager.resolveActivity(i, 0).activityInfo.name).isEqualTo("name");
923     assertThat(packageManager.resolveActivity(i, 0).activityInfo.packageName)
924         .isEqualTo(TEST_PACKAGE_NAME);
925   }
926 
927   @Test
resolveActivity_NoMatch()928   public void resolveActivity_NoMatch() throws Exception {
929     Intent i = new Intent();
930     i.setComponent(new ComponentName("foo.bar", "No Activity"));
931     assertThat(packageManager.resolveActivity(i, 0)).isNull();
932   }
933 
934   @Test
queryIntentServices_EmptyResult()935   public void queryIntentServices_EmptyResult() throws Exception {
936     Intent i = new Intent(Intent.ACTION_MAIN, null);
937     i.addCategory(Intent.CATEGORY_LAUNCHER);
938 
939     List<ResolveInfo> activities = packageManager.queryIntentServices(i, 0);
940     assertThat(activities).isEmpty();
941   }
942 
943   @Test
queryIntentServices_MatchWithExplicitIntent()944   public void queryIntentServices_MatchWithExplicitIntent() throws Exception {
945     Intent i = new Intent();
946     i.setClassName(ApplicationProvider.getApplicationContext(), "com.foo.Service");
947 
948     List<ResolveInfo> services = packageManager.queryIntentServices(i, 0);
949     assertThat(services).isNotNull();
950     assertThat(services).hasSize(1);
951     assertThat(services.get(0).resolvePackageName).isEqualTo("org.robolectric");
952     assertThat(services.get(0).serviceInfo.name).isEqualTo("com.foo.Service");
953   }
954 
955   @Test
queryIntentServices_Match()956   public void queryIntentServices_Match() throws Exception {
957     Intent i = new Intent(Intent.ACTION_MAIN, null);
958 
959     ResolveInfo info = new ResolveInfo();
960     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
961 
962     shadowPackageManager.addResolveInfoForIntent(i, info);
963 
964     List<ResolveInfo> services = packageManager.queryIntentServices(i, 0);
965     assertThat(services).hasSize(1);
966     assertThat(services.get(0).nonLocalizedLabel.toString()).isEqualTo(TEST_PACKAGE_LABEL);
967   }
968 
969   @Test
queryIntentServices_fromManifest()970   public void queryIntentServices_fromManifest() {
971     Intent i = new Intent("org.robolectric.ACTION_DIFFERENT_PACKAGE");
972     i.addCategory(Intent.CATEGORY_LAUNCHER);
973     i.setType("image/jpeg");
974     List<ResolveInfo> services = packageManager.queryIntentServices(i, 0);
975     assertThat(services).isNotEmpty();
976   }
977 
978   @Test
979   @Config(minSdk = LOLLIPOP)
queryIntentServices_appHidden_includeUninstalled()980   public void queryIntentServices_appHidden_includeUninstalled() {
981     String packageName =
982         ApplicationProvider.getApplicationContext().getPackageName();
983     packageManager.setApplicationHiddenSettingAsUser(
984         packageName, /* hidden= */ true, /* user= */ null);
985 
986     Intent i = new Intent();
987     i.setClassName(ApplicationProvider.getApplicationContext(), "com.foo.Service");
988 
989     List<ResolveInfo> services = packageManager.queryIntentServices(i, MATCH_UNINSTALLED_PACKAGES);
990     assertThat(services).hasSize(1);
991     assertThat(services.get(0).resolvePackageName).isEqualTo(packageName);
992     assertThat(services.get(0).serviceInfo.name).isEqualTo("com.foo.Service");
993   }
994 
995   @Test
996   @Config(minSdk = LOLLIPOP)
queryIntentServices_appHidden_dontIncludeUninstalled()997   public void queryIntentServices_appHidden_dontIncludeUninstalled() {
998     String packageName =
999         ApplicationProvider.getApplicationContext().getPackageName();
1000     packageManager.setApplicationHiddenSettingAsUser(
1001         packageName, /* hidden= */ true, /* user= */ null);
1002 
1003     Intent i = new Intent();
1004     i.setClassName(ApplicationProvider.getApplicationContext(), "com.foo.Service");
1005 
1006     assertThat(packageManager.queryIntentServices(i, /* flags= */ 0)).isEmpty();
1007   }
1008 
1009   @Test
1010   @Config(minSdk = JELLY_BEAN_MR1)
queryIntentServicesAsUser()1011   public void queryIntentServicesAsUser() {
1012     Intent i = new Intent("org.robolectric.ACTION_DIFFERENT_PACKAGE");
1013     i.addCategory(Intent.CATEGORY_LAUNCHER);
1014     i.setType("image/jpeg");
1015     List<ResolveInfo> services = packageManager.queryIntentServicesAsUser(i, 0, 0);
1016     assertThat(services).isNotEmpty();
1017   }
1018 
1019   @Test
queryBroadcastReceivers_EmptyResult()1020   public void queryBroadcastReceivers_EmptyResult() throws Exception {
1021     Intent i = new Intent(Intent.ACTION_MAIN, null);
1022     i.addCategory(Intent.CATEGORY_LAUNCHER);
1023 
1024     List<ResolveInfo> broadCastReceivers = packageManager.queryBroadcastReceivers(i, 0);
1025     assertThat(broadCastReceivers).isEmpty();
1026   }
1027 
1028   @Test
queryBroadcastReceivers_Match()1029   public void queryBroadcastReceivers_Match() throws Exception {
1030     Intent i = new Intent(Intent.ACTION_MAIN, null);
1031 
1032     ResolveInfo info = new ResolveInfo();
1033     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
1034 
1035     shadowPackageManager.addResolveInfoForIntent(i, info);
1036 
1037     List<ResolveInfo> broadCastReceivers = packageManager.queryBroadcastReceivers(i, 0);
1038     assertThat(broadCastReceivers).hasSize(1);
1039     assertThat(broadCastReceivers.get(0).nonLocalizedLabel.toString())
1040         .isEqualTo(TEST_PACKAGE_LABEL);
1041   }
1042 
1043   @Test
queryBroadcastReceivers_MatchWithExplicitIntent()1044   public void queryBroadcastReceivers_MatchWithExplicitIntent() throws Exception {
1045     Intent i = new Intent();
1046     i.setClassName(
1047         ApplicationProvider.getApplicationContext(),
1048         "org.robolectric.fakes.ConfigTestReceiver");
1049 
1050     List<ResolveInfo> receivers = packageManager.queryBroadcastReceivers(i, 0);
1051     assertThat(receivers).isNotNull();
1052     assertThat(receivers).hasSize(1);
1053     assertThat(receivers.get(0).resolvePackageName).isEqualTo("org.robolectric");
1054     assertThat(receivers.get(0).activityInfo.name)
1055         .isEqualTo("org.robolectric.fakes.ConfigTestReceiver");
1056   }
1057 
1058   @Test
1059   @Config(minSdk = LOLLIPOP)
queryBroadcastReceivers_appHidden_includeUninstalled()1060   public void queryBroadcastReceivers_appHidden_includeUninstalled() {
1061     String packageName =
1062         ApplicationProvider.getApplicationContext().getPackageName();
1063     packageManager.setApplicationHiddenSettingAsUser(
1064         packageName, /* hidden= */ true, /* user= */ null);
1065 
1066     Intent i = new Intent();
1067     i.setClassName(
1068         ApplicationProvider.getApplicationContext(),
1069         "org.robolectric.fakes.ConfigTestReceiver");
1070 
1071     List<ResolveInfo> activities =
1072         packageManager.queryBroadcastReceivers(i, MATCH_UNINSTALLED_PACKAGES);
1073     assertThat(activities).hasSize(1);
1074     assertThat(activities.get(0).resolvePackageName).isEqualTo(packageName);
1075     assertThat(activities.get(0).activityInfo.name)
1076         .isEqualTo("org.robolectric.fakes.ConfigTestReceiver");
1077   }
1078 
1079   @Test
1080   @Config(minSdk = LOLLIPOP)
queryBroadcastReceivers_appHidden_dontIncludeUninstalled()1081   public void queryBroadcastReceivers_appHidden_dontIncludeUninstalled() {
1082     String packageName =
1083         ApplicationProvider.getApplicationContext().getPackageName();
1084     packageManager.setApplicationHiddenSettingAsUser(
1085         packageName, /* hidden= */ true, /* user= */ null);
1086 
1087     Intent i = new Intent();
1088     i.setClassName(
1089         ApplicationProvider.getApplicationContext(),
1090         "org.robolectric.fakes.ConfigTestReceiver");
1091 
1092     assertThat(packageManager.queryBroadcastReceivers(i, /* flags= */ 0)).isEmpty();
1093   }
1094 
1095   @Test
1096   @Config(minSdk = LOLLIPOP)
queryIntentContentProviders_EmptyResult()1097   public void queryIntentContentProviders_EmptyResult() throws Exception {
1098     Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE);
1099 
1100     List<ResolveInfo> broadCastReceivers = packageManager.queryIntentContentProviders(i, 0);
1101     assertThat(broadCastReceivers).isEmpty();
1102   }
1103 
1104   @Test
1105   @Config(minSdk = LOLLIPOP)
queryIntentContentProviders_Match()1106   public void queryIntentContentProviders_Match() throws Exception {
1107     Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE);
1108 
1109     ResolveInfo resolveInfo = new ResolveInfo();
1110     ProviderInfo providerInfo = new ProviderInfo();
1111     providerInfo.authority = "com.robolectric";
1112     resolveInfo.providerInfo = providerInfo;
1113 
1114     shadowPackageManager.addResolveInfoForIntent(i, resolveInfo);
1115 
1116     List<ResolveInfo> contentProviders = packageManager.queryIntentContentProviders(i, 0);
1117     assertThat(contentProviders).hasSize(1);
1118     assertThat(contentProviders.get(0).providerInfo.authority).isEqualTo(providerInfo.authority);
1119   }
1120 
1121   @Test
1122   @Config(minSdk = LOLLIPOP)
queryIntentContentProviders_MatchSystemOnly()1123   public void queryIntentContentProviders_MatchSystemOnly() throws Exception {
1124     Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE);
1125 
1126     ResolveInfo info1 = new ResolveInfo();
1127     info1.providerInfo = new ProviderInfo();
1128     info1.providerInfo.applicationInfo = new ApplicationInfo();
1129 
1130     ResolveInfo info2 = new ResolveInfo();
1131     info2.providerInfo = new ProviderInfo();
1132     info2.providerInfo.applicationInfo = new ApplicationInfo();
1133     info2.providerInfo.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
1134     info2.nonLocalizedLabel = "System App";
1135 
1136     shadowPackageManager.addResolveInfoForIntent(i, info1);
1137     shadowPackageManager.addResolveInfoForIntent(i, info2);
1138 
1139     List<ResolveInfo> activities =
1140         packageManager.queryIntentContentProviders(i, PackageManager.MATCH_SYSTEM_ONLY);
1141     assertThat(activities).isNotNull();
1142     assertThat(activities).hasSize(1);
1143     assertThat(activities.get(0).nonLocalizedLabel.toString()).isEqualTo("System App");
1144   }
1145 
1146   @Test
1147   @Config(minSdk = LOLLIPOP)
queryIntentContentProviders_MatchDisabledComponents()1148   public void queryIntentContentProviders_MatchDisabledComponents() throws Exception {
1149     Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE);
1150 
1151     ComponentName componentToDisable =
1152         new ComponentName(
1153             "org.robolectric.shadows.TestPackageName", "org.robolectric.shadows.TestProvider");
1154     packageManager.setComponentEnabledSetting(
1155         componentToDisable,
1156         PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
1157         PackageManager.DONT_KILL_APP);
1158 
1159     ResolveInfo resolveInfo = new ResolveInfo();
1160     resolveInfo.providerInfo = new ProviderInfo();
1161     resolveInfo.providerInfo.applicationInfo = new ApplicationInfo();
1162     resolveInfo.providerInfo.applicationInfo.packageName =
1163         "org.robolectric.shadows.TestPackageName";
1164     resolveInfo.providerInfo.name = "org.robolectric.shadows.TestProvider";
1165 
1166     shadowPackageManager.addResolveInfoForIntent(i, resolveInfo);
1167 
1168     List<ResolveInfo> resolveInfos = packageManager.queryIntentContentProviders(i, 0);
1169     assertThat(resolveInfos).isEmpty();
1170 
1171     resolveInfos =
1172         packageManager.queryIntentContentProviders(i, PackageManager.MATCH_DISABLED_COMPONENTS);
1173     assertThat(resolveInfos).isNotNull();
1174     assertThat(resolveInfos).hasSize(1);
1175   }
1176 
1177   @Test
1178   @Config(minSdk = LOLLIPOP)
queryIntentContentProviders_appHidden_includeUninstalled()1179   public void queryIntentContentProviders_appHidden_includeUninstalled() {
1180     String packageName =
1181         ApplicationProvider.getApplicationContext().getPackageName();
1182     packageManager.setApplicationHiddenSettingAsUser(
1183         packageName, /* hidden= */ true, /* user= */ null);
1184 
1185     Intent i = new Intent(DocumentsContract.PROVIDER_INTERFACE);
1186     i.setClassName(
1187         ApplicationProvider.getApplicationContext(),
1188         "org.robolectric.shadows.TestActivity");
1189 
1190     ResolveInfo resolveInfo = new ResolveInfo();
1191     resolveInfo.providerInfo = new ProviderInfo();
1192     resolveInfo.providerInfo.applicationInfo = new ApplicationInfo();
1193     resolveInfo.providerInfo.applicationInfo.packageName = packageName;
1194     resolveInfo.providerInfo.name = "org.robolectric.shadows.TestProvider";
1195 
1196     shadowPackageManager.addResolveInfoForIntent(i, resolveInfo);
1197 
1198     List<ResolveInfo> resolveInfos = packageManager.queryIntentContentProviders(i, 0);
1199     assertThat(resolveInfos).isEmpty();
1200 
1201     resolveInfos = packageManager.queryIntentContentProviders(i, MATCH_UNINSTALLED_PACKAGES);
1202 
1203     assertThat(resolveInfos).hasSize(1);
1204     assertThat(resolveInfos.get(0).providerInfo.applicationInfo.packageName).isEqualTo(packageName);
1205     assertThat(resolveInfos.get(0).providerInfo.name)
1206         .isEqualTo("org.robolectric.shadows.TestProvider");
1207   }
1208 
1209   @Test
resolveService_Match()1210   public void resolveService_Match() throws Exception {
1211     Intent i = new Intent(Intent.ACTION_MAIN, null);
1212     ResolveInfo info = new ResolveInfo();
1213     info.serviceInfo = new ServiceInfo();
1214     info.serviceInfo.name = "name";
1215     shadowPackageManager.addResolveInfoForIntent(i, info);
1216     assertThat(packageManager.resolveService(i, 0)).isNotNull();
1217     assertThat(packageManager.resolveService(i, 0).serviceInfo.name).isEqualTo("name");
1218   }
1219 
1220   @Test
removeResolveInfosForIntent_shouldCauseResolveActivityToReturnNull()1221   public void removeResolveInfosForIntent_shouldCauseResolveActivityToReturnNull() throws Exception {
1222     Intent intent =
1223         new Intent(Intent.ACTION_APP_ERROR, null).addCategory(Intent.CATEGORY_APP_BROWSER);
1224     ResolveInfo info = new ResolveInfo();
1225     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
1226     info.activityInfo = new ActivityInfo();
1227     info.activityInfo.packageName = "com.org";
1228     shadowPackageManager.addResolveInfoForIntent(intent, info);
1229 
1230     shadowPackageManager.removeResolveInfosForIntent(intent, "com.org");
1231 
1232     assertThat(packageManager.resolveActivity(intent, 0)).isNull();
1233   }
1234 
1235   @Test
removeResolveInfosForIntent_forService()1236   public void removeResolveInfosForIntent_forService() throws Exception {
1237     Intent intent =
1238         new Intent(Intent.ACTION_APP_ERROR, null).addCategory(Intent.CATEGORY_APP_BROWSER);
1239     ResolveInfo info = new ResolveInfo();
1240     info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
1241     info.serviceInfo = new ServiceInfo();
1242     info.serviceInfo.packageName = "com.org";
1243     shadowPackageManager.addResolveInfoForIntent(intent, info);
1244 
1245     shadowPackageManager.removeResolveInfosForIntent(intent, "com.org");
1246 
1247     assertThat(packageManager.resolveService(intent, 0)).isNull();
1248   }
1249 
1250   @Test
resolveService_NoMatch()1251   public void resolveService_NoMatch() throws Exception {
1252     Intent i = new Intent();
1253     i.setComponent(new ComponentName("foo.bar", "No Activity"));
1254     assertThat(packageManager.resolveService(i, 0)).isNull();
1255   }
1256 
1257   @Test
queryActivityIcons_Match()1258   public void queryActivityIcons_Match() throws Exception {
1259     Intent i = new Intent();
1260     i.setComponent(new ComponentName(TEST_PACKAGE_NAME, ""));
1261     Drawable d = new BitmapDrawable();
1262 
1263     shadowPackageManager.addActivityIcon(i, d);
1264 
1265     assertThat(packageManager.getActivityIcon(i)).isSameAs(d);
1266     assertThat(packageManager.getActivityIcon(i.getComponent())).isSameAs(d);
1267   }
1268 
1269   @Test
hasSystemFeature()1270   public void hasSystemFeature() throws Exception {
1271     // uninitialized
1272     assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isFalse();
1273 
1274     // positive
1275     shadowPackageManager.setSystemFeature(PackageManager.FEATURE_CAMERA, true);
1276     assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isTrue();
1277 
1278     // negative
1279     shadowPackageManager.setSystemFeature(PackageManager.FEATURE_CAMERA, false);
1280     assertThat(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)).isFalse();
1281   }
1282 
1283   @Test
addSystemSharedLibraryName()1284   public void addSystemSharedLibraryName() {
1285     shadowPackageManager.addSystemSharedLibraryName("com.foo.system_library_1");
1286     shadowPackageManager.addSystemSharedLibraryName("com.foo.system_library_2");
1287 
1288     assertThat(packageManager.getSystemSharedLibraryNames())
1289         .asList()
1290         .containsExactly("com.foo.system_library_1", "com.foo.system_library_2");
1291   }
1292 
1293   @Test
clearSystemSharedLibraryName()1294   public void clearSystemSharedLibraryName() {
1295     shadowPackageManager.addSystemSharedLibraryName("com.foo.system_library_1");
1296     shadowPackageManager.clearSystemSharedLibraryNames();
1297 
1298     assertThat(packageManager.getSystemSharedLibraryNames()).isEmpty();
1299   }
1300 
1301   @Test
getPackageInfo_shouldReturnActivityInfos()1302   public void getPackageInfo_shouldReturnActivityInfos() throws Exception {
1303     PackageInfo packageInfo =
1304         packageManager.getPackageInfo(
1305             ApplicationProvider.getApplicationContext().getPackageName(),
1306             PackageManager.GET_ACTIVITIES);
1307     ActivityInfo activityInfoWithFilters =
1308         findActivity(packageInfo.activities, ActivityWithFilters.class.getName());
1309     assertThat(activityInfoWithFilters.packageName).isEqualTo("org.robolectric");
1310     assertThat(activityInfoWithFilters.exported).isEqualTo(true);
1311     assertThat(activityInfoWithFilters.permission).isEqualTo("com.foo.MY_PERMISSION");
1312   }
1313 
findActivity(ActivityInfo[] activities, String name)1314   private static ActivityInfo findActivity(ActivityInfo[] activities, String name) {
1315     for (ActivityInfo activityInfo : activities) {
1316       if (activityInfo.name.equals(name)) {
1317         return activityInfo;
1318       }
1319     }
1320     return null;
1321   }
1322 
1323   @Test
getPackageInfo_getProvidersShouldReturnProviderInfos()1324   public void getPackageInfo_getProvidersShouldReturnProviderInfos() throws Exception {
1325     PackageInfo packageInfo =
1326         packageManager.getPackageInfo(
1327             ApplicationProvider.getApplicationContext().getPackageName(),
1328             PackageManager.GET_PROVIDERS);
1329     ProviderInfo[] providers = packageInfo.providers;
1330     assertThat(providers).isNotEmpty();
1331     assertThat(providers.length).isEqualTo(2);
1332     assertThat(providers[0].packageName).isEqualTo("org.robolectric");
1333     assertThat(providers[1].packageName).isEqualTo("org.robolectric");
1334   }
1335 
1336   @Test
getProviderInfo_shouldReturnProviderInfos()1337   public void getProviderInfo_shouldReturnProviderInfos() throws Exception {
1338     ProviderInfo providerInfo1 =
1339         packageManager.getProviderInfo(
1340             new ComponentName(
1341                 ApplicationProvider.getApplicationContext(),
1342                 ".shadows.testing.TestContentProvider1"),
1343             0);
1344     assertThat(providerInfo1.packageName).isEqualTo("org.robolectric");
1345     assertThat(providerInfo1.authority).isEqualTo("org.robolectric.authority1");
1346 
1347     ProviderInfo providerInfo2 =
1348         packageManager.getProviderInfo(
1349             new ComponentName(
1350                 ApplicationProvider.getApplicationContext(),
1351                 "org.robolectric.shadows.testing.TestContentProvider2"),
1352             0);
1353     assertThat(providerInfo2.packageName).isEqualTo("org.robolectric");
1354     assertThat(providerInfo2.authority).isEqualTo("org.robolectric.authority2");
1355   }
1356 
1357   @Test
getProviderInfo_packageNotFoundShouldThrowException()1358   public void getProviderInfo_packageNotFoundShouldThrowException() {
1359     try {
1360       packageManager.getProviderInfo(new ComponentName("non.existent.package", ".tester.DoesntExist"), 0);
1361       fail("should have thrown NameNotFoundException");
1362     } catch (NameNotFoundException e) {
1363       // expected
1364     }
1365   }
1366 
1367   @Test
getProviderInfo_shouldPopulatePermissionsInProviderInfos()1368   public void getProviderInfo_shouldPopulatePermissionsInProviderInfos() throws Exception {
1369     ProviderInfo providerInfo =
1370         packageManager.getProviderInfo(
1371             new ComponentName(
1372                 ApplicationProvider.getApplicationContext(),
1373                 "org.robolectric.shadows.testing.TestContentProvider1"),
1374             0);
1375     assertThat(providerInfo.authority).isEqualTo("org.robolectric.authority1");
1376 
1377     assertThat(providerInfo.readPermission).isEqualTo("READ_PERMISSION");
1378     assertThat(providerInfo.writePermission).isEqualTo("WRITE_PERMISSION");
1379 
1380     assertThat(providerInfo.pathPermissions).asList().hasSize(1);
1381     assertThat(providerInfo.pathPermissions[0].getType())
1382         .isEqualTo(PathPermission.PATTERN_SIMPLE_GLOB);
1383     assertThat(providerInfo.pathPermissions[0].getPath()).isEqualTo("/path/*");
1384     assertThat(providerInfo.pathPermissions[0].getReadPermission()).isEqualTo("PATH_READ_PERMISSION");
1385     assertThat(providerInfo.pathPermissions[0].getWritePermission()).isEqualTo("PATH_WRITE_PERMISSION");
1386   }
1387 
1388   @Test
getProviderInfo_shouldMetaDataInProviderInfos()1389   public void getProviderInfo_shouldMetaDataInProviderInfos() throws Exception {
1390     ProviderInfo providerInfo =
1391         packageManager.getProviderInfo(
1392             new ComponentName(
1393                 ApplicationProvider.getApplicationContext(),
1394                 "org.robolectric.shadows.testing.TestContentProvider1"),
1395             PackageManager.GET_META_DATA);
1396     assertThat(providerInfo.authority).isEqualTo("org.robolectric.authority1");
1397 
1398     assertThat(providerInfo.metaData.getString("greeting")).isEqualTo("Hello");
1399   }
1400 
1401   @Test
resolveContentProvider_shouldResolveByPackageName()1402   public void resolveContentProvider_shouldResolveByPackageName() throws Exception {
1403     ProviderInfo providerInfo = packageManager.resolveContentProvider("org.robolectric.authority1", 0);
1404     assertThat(providerInfo.packageName).isEqualTo("org.robolectric");
1405     assertThat(providerInfo.authority).isEqualTo("org.robolectric.authority1");
1406   }
1407 
1408   @Test
testReceiverInfo()1409   public void testReceiverInfo() throws Exception {
1410     ActivityInfo info =
1411         packageManager.getReceiverInfo(
1412             new ComponentName(
1413                 ApplicationProvider.getApplicationContext(),
1414                 ".test.ConfigTestReceiver"),
1415             PackageManager.GET_META_DATA);
1416     assertThat(info.metaData.getInt("numberOfSheep")).isEqualTo(42);
1417   }
1418 
1419   @Test
testGetPackageInfo_ForReceiversIncorrectPackage()1420   public void testGetPackageInfo_ForReceiversIncorrectPackage() {
1421     try {
1422       packageManager.getPackageInfo("unknown_package", PackageManager.GET_RECEIVERS);
1423       fail("should have thrown NameNotFoundException");
1424     } catch (PackageManager.NameNotFoundException e) {
1425       assertThat(e.getMessage()).contains("unknown_package");
1426     }
1427   }
1428 
1429   @Test
getPackageInfo_shouldReturnRequestedPermissions()1430   public void getPackageInfo_shouldReturnRequestedPermissions() throws Exception {
1431     PackageInfo packageInfo =
1432         packageManager.getPackageInfo(
1433             ApplicationProvider.getApplicationContext().getPackageName(),
1434             PackageManager.GET_PERMISSIONS);
1435     String[] permissions = packageInfo.requestedPermissions;
1436     assertThat(permissions).isNotNull();
1437     assertThat(permissions.length).isEqualTo(4);
1438   }
1439 
1440   @Test
getPackageInfo_uninstalledPackage_includeUninstalled()1441   public void getPackageInfo_uninstalledPackage_includeUninstalled() throws Exception {
1442     packageManager.setApplicationEnabledSetting(
1443         ApplicationProvider.getApplicationContext().getPackageName(),
1444         COMPONENT_ENABLED_STATE_DISABLED,
1445         0);
1446     PackageInfo info =
1447         packageManager.getPackageInfo(
1448             ApplicationProvider.getApplicationContext().getPackageName(),
1449             MATCH_UNINSTALLED_PACKAGES);
1450     assertThat(info).isNotNull();
1451     assertThat(info.packageName)
1452         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
1453   }
1454 
1455   @Test
getPackageInfo_uninstalledPackage_dontIncludeUninstalled()1456   public void getPackageInfo_uninstalledPackage_dontIncludeUninstalled() {
1457     packageManager.setApplicationEnabledSetting(
1458         ApplicationProvider.getApplicationContext().getPackageName(),
1459         COMPONENT_ENABLED_STATE_DISABLED,
1460         0);
1461 
1462     try {
1463       packageManager.getPackageInfo(
1464           ApplicationProvider.getApplicationContext().getPackageName(), 0);
1465       fail("should have thrown NameNotFoundException");
1466     } catch (NameNotFoundException e) {
1467       // expected
1468     }
1469   }
1470 
1471   @Test
getPackageInfo_disabledPackage_includeDisabled()1472   public void getPackageInfo_disabledPackage_includeDisabled() throws Exception {
1473     packageManager.setApplicationEnabledSetting(
1474         ApplicationProvider.getApplicationContext().getPackageName(),
1475         COMPONENT_ENABLED_STATE_DISABLED,
1476         0);
1477     PackageInfo info =
1478         packageManager.getPackageInfo(
1479             ApplicationProvider.getApplicationContext().getPackageName(),
1480             MATCH_DISABLED_COMPONENTS);
1481     assertThat(info).isNotNull();
1482     assertThat(info.packageName)
1483         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
1484   }
1485 
1486   @Test
getInstalledPackages_uninstalledPackage_includeUninstalled()1487   public void getInstalledPackages_uninstalledPackage_includeUninstalled() throws Exception {
1488     packageManager.setApplicationEnabledSetting(
1489         ApplicationProvider.getApplicationContext().getPackageName(),
1490         COMPONENT_ENABLED_STATE_DISABLED,
1491         0);
1492 
1493     assertThat(packageManager.getInstalledPackages(MATCH_UNINSTALLED_PACKAGES)).isNotEmpty();
1494     assertThat(packageManager.getInstalledPackages(MATCH_UNINSTALLED_PACKAGES).get(0).packageName)
1495         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
1496   }
1497 
1498   @Test
getInstalledPackages_uninstalledPackage_dontIncludeUninstalled()1499   public void getInstalledPackages_uninstalledPackage_dontIncludeUninstalled() throws Exception {
1500     packageManager.setApplicationEnabledSetting(
1501         ApplicationProvider.getApplicationContext().getPackageName(),
1502         COMPONENT_ENABLED_STATE_DISABLED,
1503         0);
1504 
1505     assertThat(packageManager.getInstalledPackages(0)).isEmpty();
1506   }
1507 
1508   @Test
getInstalledPackages_disabledPackage_includeDisabled()1509   public void getInstalledPackages_disabledPackage_includeDisabled() throws Exception {
1510     packageManager.setApplicationEnabledSetting(
1511         ApplicationProvider.getApplicationContext().getPackageName(),
1512         COMPONENT_ENABLED_STATE_DISABLED,
1513         0);
1514 
1515     assertThat(packageManager.getInstalledPackages(MATCH_DISABLED_COMPONENTS)).isNotEmpty();
1516     assertThat(packageManager.getInstalledPackages(MATCH_DISABLED_COMPONENTS).get(0).packageName)
1517         .isEqualTo(ApplicationProvider.getApplicationContext().getPackageName());
1518   }
1519 
1520   @Test
testGetPreferredActivities()1521   public void testGetPreferredActivities() throws Exception {
1522     // Setup an intentfilter and add to packagemanager
1523     IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
1524     filter.addCategory(Intent.CATEGORY_HOME);
1525     final String packageName = "com.example.dummy";
1526     ComponentName name = new ComponentName(packageName, "LauncherActivity");
1527     packageManager.addPreferredActivity(filter, 0, null, name);
1528 
1529     // Test match
1530     List<IntentFilter> filters = new ArrayList<>();
1531     filters.add(filter);
1532 
1533     List<ComponentName> activities = new ArrayList<>();
1534     packageManager.getPreferredActivities(filters, activities, null);
1535 
1536     assertThat(activities.size()).isEqualTo(1);
1537     assertThat(activities.get(0).getPackageName()).isEqualTo(packageName);
1538 
1539     // Test not match
1540     IntentFilter filter1 = new IntentFilter(Intent.ACTION_VIEW);
1541     filters.add(filter1);
1542     filters.clear();
1543     activities.clear();
1544     filters.add(filter1);
1545 
1546     packageManager.getPreferredActivities(filters, activities, null);
1547 
1548     assertThat(activities.size()).isEqualTo(0);
1549   }
1550 
1551   @Test
canResolveDrawableGivenPackageAndResourceId()1552   public void canResolveDrawableGivenPackageAndResourceId() throws Exception {
1553     Drawable drawable = ShadowDrawable.createFromStream(new ByteArrayInputStream(new byte[0]), "my_source");
1554     shadowPackageManager.addDrawableResolution("com.example.foo", 4334, drawable);
1555     Drawable actual = packageManager.getDrawable("com.example.foo", 4334, null);
1556     assertThat(actual).isSameAs(drawable);
1557   }
1558 
1559   @Test
shouldAssignTheApplicationClassNameFromTheManifest()1560   public void shouldAssignTheApplicationClassNameFromTheManifest() throws Exception {
1561     ApplicationInfo applicationInfo = packageManager.getApplicationInfo("org.robolectric", 0);
1562     assertThat(applicationInfo.className).isEqualTo("org.robolectric.shadows.testing.TestApplication");
1563   }
1564 
1565   @Test
1566   @Config(minSdk = N_MR1)
shouldAssignTheApplicationNameFromTheManifest()1567   public void shouldAssignTheApplicationNameFromTheManifest() throws Exception {
1568     ApplicationInfo applicationInfo = packageManager.getApplicationInfo("org.robolectric", 0);
1569     assertThat(applicationInfo.name).isEqualTo("org.robolectric.shadows.testing.TestApplication");
1570   }
1571 
1572   @Test
testLaunchIntentForPackage()1573   public void testLaunchIntentForPackage() {
1574     Intent intent = packageManager.getLaunchIntentForPackage(TEST_PACKAGE_LABEL);
1575     assertThat(intent).isNull();
1576 
1577     Intent launchIntent = new Intent(Intent.ACTION_MAIN);
1578     launchIntent.setPackage(TEST_PACKAGE_LABEL);
1579     launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1580     launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1581     ResolveInfo resolveInfo = new ResolveInfo();
1582     resolveInfo.activityInfo = new ActivityInfo();
1583     resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL;
1584     resolveInfo.activityInfo.name = "LauncherActivity";
1585     shadowPackageManager.addResolveInfoForIntent(launchIntent, resolveInfo);
1586 
1587     intent = packageManager.getLaunchIntentForPackage(TEST_PACKAGE_LABEL);
1588     assertThat(intent.getComponent().getClassName()).isEqualTo("LauncherActivity");
1589   }
1590 
1591   @Test
shouldAssignTheAppMetaDataFromTheManifest()1592   public void shouldAssignTheAppMetaDataFromTheManifest() throws Exception {
1593     ApplicationInfo info =
1594         packageManager.getApplicationInfo(
1595             ApplicationProvider.getApplicationContext().getPackageName(), 0);
1596     Bundle meta = info.metaData;
1597 
1598     assertThat(meta.getString("org.robolectric.metaName1")).isEqualTo("metaValue1");
1599     assertThat(meta.getString("org.robolectric.metaName2")).isEqualTo("metaValue2");
1600 
1601     assertThat(meta.getBoolean("org.robolectric.metaFalseLiteral")).isEqualTo(false);
1602     assertThat(meta.getBoolean("org.robolectric.metaTrueLiteral")).isEqualTo(true);
1603 
1604     assertThat(meta.getInt("org.robolectric.metaInt")).isEqualTo(123);
1605     assertThat(meta.getFloat("org.robolectric.metaFloat")).isEqualTo(1.23f);
1606 
1607     assertThat(meta.getInt("org.robolectric.metaColor")).isEqualTo(Color.WHITE);
1608 
1609     assertThat(meta.getBoolean("org.robolectric.metaBooleanFromRes"))
1610         .isEqualTo(
1611             ApplicationProvider.getApplicationContext()
1612                 .getResources()
1613                 .getBoolean(R.bool.false_bool_value));
1614 
1615     assertThat(meta.getInt("org.robolectric.metaIntFromRes"))
1616         .isEqualTo(
1617             ApplicationProvider.getApplicationContext()
1618                 .getResources()
1619                 .getInteger(R.integer.test_integer1));
1620 
1621     assertThat(meta.getInt("org.robolectric.metaColorFromRes"))
1622         .isEqualTo(
1623             ApplicationProvider.getApplicationContext()
1624                 .getResources()
1625                 .getColor(R.color.clear));
1626 
1627     assertThat(meta.getString("org.robolectric.metaStringFromRes"))
1628         .isEqualTo(
1629             ApplicationProvider.getApplicationContext()
1630                 .getString(R.string.app_name));
1631 
1632     assertThat(meta.getString("org.robolectric.metaStringOfIntFromRes"))
1633         .isEqualTo(
1634             ApplicationProvider.getApplicationContext()
1635                 .getString(R.string.str_int));
1636 
1637     assertThat(meta.getInt("org.robolectric.metaStringRes")).isEqualTo(R.string.app_name);
1638   }
1639 
1640   @Test
testResolveDifferentIntentObjects()1641   public void testResolveDifferentIntentObjects() {
1642     Intent intent1 = new Intent(Intent.ACTION_MAIN);
1643     intent1.setPackage(TEST_PACKAGE_LABEL);
1644     intent1.addCategory(Intent.CATEGORY_APP_BROWSER);
1645 
1646     assertThat(packageManager.resolveActivity(intent1, -1)).isNull();
1647     ResolveInfo resolveInfo = new ResolveInfo();
1648     resolveInfo.activityInfo = new ActivityInfo();
1649     resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL;
1650     resolveInfo.activityInfo.name = "BrowserActivity";
1651     shadowPackageManager.addResolveInfoForIntent(intent1, resolveInfo);
1652 
1653     // the original intent object should yield a result
1654     ResolveInfo result  = packageManager.resolveActivity(intent1, -1);
1655     assertThat(result.activityInfo.name).isEqualTo("BrowserActivity");
1656 
1657     // AND a new, functionally equivalent intent should also yield a result
1658     Intent intent2 = new Intent(Intent.ACTION_MAIN);
1659     intent2.setPackage(TEST_PACKAGE_LABEL);
1660     intent2.addCategory(Intent.CATEGORY_APP_BROWSER);
1661     result = packageManager.resolveActivity(intent2, -1);
1662     assertThat(result.activityInfo.name).isEqualTo("BrowserActivity");
1663   }
1664 
1665   @Test
testResolvePartiallySimilarIntents()1666   public void testResolvePartiallySimilarIntents() {
1667     Intent intent1 = new Intent(Intent.ACTION_APP_ERROR);
1668     intent1.setPackage(TEST_PACKAGE_LABEL);
1669     intent1.addCategory(Intent.CATEGORY_APP_BROWSER);
1670 
1671     assertThat(packageManager.resolveActivity(intent1, -1)).isNull();
1672 
1673     ResolveInfo resolveInfo = new ResolveInfo();
1674     resolveInfo.activityInfo = new ActivityInfo();
1675     resolveInfo.activityInfo.packageName = TEST_PACKAGE_LABEL;
1676     resolveInfo.activityInfo.name = "BrowserActivity";
1677     shadowPackageManager.addResolveInfoForIntent(intent1, resolveInfo);
1678 
1679     // the original intent object should yield a result
1680     ResolveInfo result  = packageManager.resolveActivity(intent1, -1);
1681     assertThat(result.activityInfo.name).isEqualTo("BrowserActivity");
1682 
1683     // an intent with just the same action should not be considered the same
1684     Intent intent2 = new Intent(Intent.ACTION_APP_ERROR);
1685     result = packageManager.resolveActivity(intent2, -1);
1686     assertThat(result).isNull();
1687 
1688     // an intent with just the same category should not be considered the same
1689     Intent intent3 = new Intent();
1690     intent3.addCategory(Intent.CATEGORY_APP_BROWSER);
1691     result = packageManager.resolveActivity(intent3, -1);
1692     assertThat(result).isNull();
1693 
1694     // an intent without the correct package restriction should not be the same
1695     Intent intent4 = new Intent(Intent.ACTION_APP_ERROR);
1696     intent4.addCategory(Intent.CATEGORY_APP_BROWSER);
1697     result = packageManager.resolveActivity(intent4, -1);
1698     assertThat(result).isNull();
1699   }
1700 
1701   @Test
testSetApplicationEnabledSetting()1702   public void testSetApplicationEnabledSetting() {
1703     assertThat(packageManager.getApplicationEnabledSetting("org.robolectric")).isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
1704 
1705     packageManager.setApplicationEnabledSetting("org.robolectric", PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
1706 
1707     assertThat(packageManager.getApplicationEnabledSetting("org.robolectric")).isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
1708   }
1709 
1710   @Test
testSetComponentEnabledSetting()1711   public void testSetComponentEnabledSetting() {
1712     ComponentName componentName =
1713         new ComponentName(
1714             ApplicationProvider.getApplicationContext(), "org.robolectric.component");
1715     assertThat(packageManager.getComponentEnabledSetting(componentName)).isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
1716 
1717     packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
1718 
1719     assertThat(packageManager.getComponentEnabledSetting(componentName)).isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
1720   }
1721 
1722   public static class ActivityWithMetadata extends Activity { }
1723 
1724   @Test
getActivityInfo_disabledActivity()1725   public void getActivityInfo_disabledActivity() throws Exception {
1726     ActivityInfo activityInfo =
1727         packageManager.getActivityInfo(
1728             new ComponentName("org.robolectric", "org.robolectric.shadows.DisabledActivity"),
1729             PackageManager.MATCH_DISABLED_COMPONENTS);
1730 
1731     assertThat(activityInfo).isNotNull();
1732     assertThat(activityInfo.enabled).isFalse();
1733   }
1734 
1735   @Test
getServiceInfo_disabledService()1736   public void getServiceInfo_disabledService() throws Exception {
1737     ServiceInfo activityInfo =
1738         packageManager.getServiceInfo(
1739             new ComponentName("org.robolectric", "org.robolectric.shadows.DisabledService"),
1740             PackageManager.MATCH_DISABLED_COMPONENTS);
1741 
1742     assertThat(activityInfo).isNotNull();
1743     assertThat(activityInfo.enabled).isFalse();
1744   }
1745 
1746   @Test
getActivityMetaData()1747   public void getActivityMetaData() throws Exception {
1748     Activity activity = setupActivity(ActivityWithMetadata.class);
1749 
1750     ActivityInfo activityInfo = packageManager.getActivityInfo(activity.getComponentName(), PackageManager.GET_ACTIVITIES|PackageManager.GET_META_DATA);
1751     assertThat(activityInfo.metaData.get("someName")).isEqualTo("someValue");
1752   }
1753 
1754   @Test
shouldAssignLabelResFromTheManifest()1755   public void shouldAssignLabelResFromTheManifest() throws Exception {
1756     ApplicationInfo applicationInfo = packageManager.getApplicationInfo("org.robolectric", 0);
1757     assertThat(applicationInfo.labelRes).isEqualTo(R.string.app_name);
1758     assertThat(applicationInfo.nonLocalizedLabel).isNull();
1759   }
1760 
1761   @Test
getServiceInfo_shouldReturnServiceInfoIfExists()1762   public void getServiceInfo_shouldReturnServiceInfoIfExists() throws Exception {
1763     ComponentName component = new ComponentName("org.robolectric", "com.foo.Service");
1764     ServiceInfo serviceInfo = packageManager.getServiceInfo(component, 0);
1765     assertThat(serviceInfo.packageName).isEqualTo("org.robolectric");
1766     assertThat(serviceInfo.processName).isEqualTo("org.robolectric");
1767     assertThat(serviceInfo.name).isEqualTo("com.foo.Service");
1768     assertThat(serviceInfo.permission).isEqualTo("com.foo.MY_PERMISSION");
1769     assertThat(serviceInfo.applicationInfo).isNotNull();
1770   }
1771 
1772   @Test
getServiceInfo_shouldReturnServiceInfoWithMetaDataWhenFlagsSet()1773   public void getServiceInfo_shouldReturnServiceInfoWithMetaDataWhenFlagsSet() throws Exception {
1774     ComponentName component = new ComponentName("org.robolectric", "com.foo.Service");
1775     ServiceInfo serviceInfo = packageManager.getServiceInfo(component, PackageManager.GET_META_DATA);
1776     assertThat(serviceInfo.metaData).isNotNull();
1777   }
1778 
1779   @Test
getServiceInfo_shouldReturnServiceInfoWithoutMetaDataWhenFlagsNotSet()1780   public void getServiceInfo_shouldReturnServiceInfoWithoutMetaDataWhenFlagsNotSet() throws Exception {
1781     ComponentName component = new ComponentName("org.robolectric", "com.foo.Service");
1782     ServiceInfo serviceInfo = packageManager.getServiceInfo(component, 0);
1783     assertThat(serviceInfo.metaData).isNull();
1784   }
1785 
1786   @Test
getServiceInfo_shouldThrowNameNotFoundExceptionIfNotExist()1787   public void getServiceInfo_shouldThrowNameNotFoundExceptionIfNotExist() {
1788     ComponentName nonExistComponent = new ComponentName("org.robolectric", "com.foo.NonExistService");
1789     try {
1790       packageManager.getServiceInfo(nonExistComponent, PackageManager.GET_SERVICES);
1791       fail("should have thrown NameNotFoundException");
1792     } catch (PackageManager.NameNotFoundException e) {
1793       assertThat(e.getMessage()).contains("com.foo.NonExistService");
1794     }
1795   }
1796 
1797   @Test
getNameForUid()1798   public void getNameForUid() {
1799     assertThat(packageManager.getNameForUid(10)).isNull();
1800 
1801     shadowPackageManager.setNameForUid(10, "a_name");
1802 
1803     assertThat(packageManager.getNameForUid(10)).isEqualTo("a_name");
1804   }
1805 
1806   @Test
getPackagesForUid()1807   public void getPackagesForUid() {
1808     assertThat(packageManager.getPackagesForUid(10)).isNull();
1809 
1810     shadowPackageManager.setPackagesForUid(10, new String[] {"a_name"});
1811 
1812     assertThat(packageManager.getPackagesForUid(10)).asList().containsExactly("a_name");
1813   }
1814 
1815   @Test
1816   @Config(minSdk = N)
getPackageUid()1817   public void getPackageUid() throws NameNotFoundException {
1818     shadowPackageManager.setPackagesForUid(10, new String[] {"a_name"});
1819     assertThat(packageManager.getPackageUid("a_name", 0)).isEqualTo(10);
1820   }
1821 
1822   @Test
1823   @Config(minSdk = N)
getPackageUid_shouldThrowNameNotFoundExceptionIfNotExist()1824   public void getPackageUid_shouldThrowNameNotFoundExceptionIfNotExist() {
1825     try {
1826       packageManager.getPackageUid("a_name", 0);
1827       fail("should have thrown NameNotFoundException");
1828     } catch (PackageManager.NameNotFoundException e) {
1829       assertThat(e.getMessage()).contains("a_name");
1830     }
1831   }
1832 
1833   @Test
getPackagesForUid_shouldReturnSetPackageName()1834   public void getPackagesForUid_shouldReturnSetPackageName() {
1835     shadowPackageManager.setPackagesForUid(10, new String[] {"a_name"});
1836     assertThat(packageManager.getPackagesForUid(10)).asList().containsExactly("a_name");
1837   }
1838 
1839   @Test
getResourcesForApplication_currentApplication()1840   public void getResourcesForApplication_currentApplication() throws Exception {
1841     assertThat(
1842             packageManager
1843                 .getResourcesForApplication("org.robolectric")
1844                 .getString(R.string.app_name))
1845         .isEqualTo(
1846             ApplicationProvider.getApplicationContext()
1847                 .getString(R.string.app_name));
1848   }
1849 
1850   @Test
getResourcesForApplication_unknownPackage()1851   public void getResourcesForApplication_unknownPackage() {
1852     try {
1853       packageManager.getResourcesForApplication("non.existent.package");
1854       fail("should have thrown NameNotFoundException");
1855     } catch (NameNotFoundException e) {
1856       // expected
1857     }
1858   }
1859 
1860   @Test
getResourcesForApplication_anotherPackage()1861   public void getResourcesForApplication_anotherPackage() throws Exception {
1862     PackageInfo packageInfo = new PackageInfo();
1863     packageInfo.packageName = "another.package";
1864 
1865     ApplicationInfo applicationInfo = new ApplicationInfo();
1866     applicationInfo.packageName = "another.package";
1867     packageInfo.applicationInfo = applicationInfo;
1868     shadowPackageManager.installPackage(packageInfo);
1869 
1870     assertThat(packageManager.getResourcesForApplication("another.package")).isNotNull();
1871     assertThat(packageManager.getResourcesForApplication("another.package"))
1872         .isNotEqualTo(ApplicationProvider.getApplicationContext().getResources());
1873   }
1874 
1875   @Test @Config(minSdk = M)
shouldShowRequestPermissionRationale()1876   public void shouldShowRequestPermissionRationale() {
1877     assertThat(packageManager.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)).isFalse();
1878 
1879     shadowPackageManager.setShouldShowRequestPermissionRationale(Manifest.permission.CAMERA, true);
1880 
1881     assertThat(packageManager.shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)).isTrue();
1882   }
1883 
1884   @Test
getSystemAvailableFeatures()1885   public void getSystemAvailableFeatures() {
1886     assertThat(packageManager.getSystemAvailableFeatures()).isNull();
1887 
1888     FeatureInfo feature = new FeatureInfo();
1889     feature.reqGlEsVersion = 0x20000;
1890     feature.flags = FeatureInfo.FLAG_REQUIRED;
1891     shadowPackageManager.addSystemAvailableFeature(feature);
1892 
1893     assertThat(packageManager.getSystemAvailableFeatures()).asList().contains(feature);
1894 
1895     shadowPackageManager.clearSystemAvailableFeatures();
1896 
1897     assertThat(packageManager.getSystemAvailableFeatures()).isNull();
1898   }
1899 
1900   @Test
verifyPendingInstall()1901   public void verifyPendingInstall() {
1902     packageManager.verifyPendingInstall(1234, VERIFICATION_ALLOW);
1903 
1904     assertThat(shadowPackageManager.getVerificationResult(1234)).isEqualTo(VERIFICATION_ALLOW);
1905   }
1906 
1907   @Test
1908   @Config(minSdk = JELLY_BEAN_MR1)
extendPendingInstallTimeout()1909   public void extendPendingInstallTimeout() {
1910     packageManager.extendVerificationTimeout(1234, 0, 1000);
1911 
1912     assertThat(shadowPackageManager.getVerificationExtendedTimeout(1234)).isEqualTo(1000);
1913   }
1914 
1915   @Test
1916   @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O
whenPackageNotPresent_getPackageSizeInfo_callsBackWithFailure()1917   public void whenPackageNotPresent_getPackageSizeInfo_callsBackWithFailure() throws Exception {
1918     IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class);
1919     packageManager.getPackageSizeInfo("nonexistant.package", packageStatsObserver);
1920 
1921     verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(false));
1922     assertThat(packageStatsCaptor.getValue()).isNull();
1923   }
1924 
1925   @Test
1926   @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O
whenPackageNotPresentAndPaused_getPackageSizeInfo_callsBackWithFailure()1927   public void whenPackageNotPresentAndPaused_getPackageSizeInfo_callsBackWithFailure() throws Exception {
1928     Robolectric.getForegroundThreadScheduler().pause();
1929     IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class);
1930     packageManager.getPackageSizeInfo("nonexistant.package", packageStatsObserver);
1931 
1932     verifyZeroInteractions(packageStatsObserver);
1933 
1934     Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
1935     verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(false));
1936     assertThat(packageStatsCaptor.getValue()).isNull();
1937   }
1938 
1939   @Test
1940   @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O
whenNotPreconfigured_getPackageSizeInfo_callsBackWithDefaults()1941   public void whenNotPreconfigured_getPackageSizeInfo_callsBackWithDefaults() throws Exception {
1942     IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class);
1943     packageManager.getPackageSizeInfo("org.robolectric", packageStatsObserver);
1944 
1945     verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true));
1946     assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.robolectric");
1947   }
1948 
1949   @Test
1950   @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O
whenPreconfigured_getPackageSizeInfo_callsBackWithConfiguredValues()1951   public void whenPreconfigured_getPackageSizeInfo_callsBackWithConfiguredValues() throws Exception {
1952     PackageInfo packageInfo = new PackageInfo();
1953     packageInfo.packageName = "org.robolectric";
1954     PackageStats packageStats = new PackageStats("org.robolectric");
1955     shadowPackageManager.addPackage(packageInfo, packageStats);
1956 
1957     IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class);
1958     packageManager.getPackageSizeInfo("org.robolectric", packageStatsObserver);
1959 
1960     verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true));
1961     assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.robolectric");
1962     assertThat(packageStatsCaptor.getValue().toString()).isEqualTo(packageStats.toString());
1963   }
1964 
1965   @Test
1966   @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O
whenPreconfiguredForAnotherPackage_getPackageSizeInfo_callsBackWithConfiguredValues()1967   public void whenPreconfiguredForAnotherPackage_getPackageSizeInfo_callsBackWithConfiguredValues() throws Exception {
1968     PackageInfo packageInfo = new PackageInfo();
1969     packageInfo.packageName = "org.other";
1970     PackageStats packageStats = new PackageStats("org.other");
1971     shadowPackageManager.addPackage(packageInfo, packageStats);
1972 
1973     IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class);
1974     packageManager.getPackageSizeInfo("org.other", packageStatsObserver);
1975 
1976     verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true));
1977     assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.other");
1978     assertThat(packageStatsCaptor.getValue().toString()).isEqualTo(packageStats.toString());
1979   }
1980 
1981   @Test
1982   @Config(minSdk = N, maxSdk = N_MR1) // Functionality removed in O
whenPaused_getPackageSizeInfo_callsBackWithConfiguredValuesAfterIdle()1983   public void whenPaused_getPackageSizeInfo_callsBackWithConfiguredValuesAfterIdle() throws Exception {
1984     Robolectric.getForegroundThreadScheduler().pause();
1985 
1986     IPackageStatsObserver packageStatsObserver = mock(IPackageStatsObserver.class);
1987     packageManager.getPackageSizeInfo("org.robolectric", packageStatsObserver);
1988 
1989     verifyZeroInteractions(packageStatsObserver);
1990 
1991     Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
1992     verify(packageStatsObserver).onGetStatsCompleted(packageStatsCaptor.capture(), eq(true));
1993     assertThat(packageStatsCaptor.getValue().packageName).isEqualTo("org.robolectric");
1994   }
1995 
1996   @Test
currentToCanonicalPackageNames()1997   public void currentToCanonicalPackageNames() {
1998     shadowPackageManager.addCurrentToCannonicalName("current_name_1", "cannonical_name_1");
1999     shadowPackageManager.addCurrentToCannonicalName("current_name_2", "cannonical_name_2");
2000 
2001     packageManager.currentToCanonicalPackageNames(new String[] {"current_name_1", "current_name_2"});
2002   }
2003 
2004   @Test
getInstalledApplications()2005   public void getInstalledApplications() {
2006     List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(0);
2007 
2008     // Default should include the application under test
2009     assertThat(installedApplications).hasSize(1);
2010     assertThat(installedApplications.get(0).packageName).isEqualTo("org.robolectric");
2011 
2012     PackageInfo packageInfo = new PackageInfo();
2013     packageInfo.packageName = "org.other";
2014     packageInfo.applicationInfo = new ApplicationInfo();
2015     packageInfo.applicationInfo.packageName = "org.other";
2016     shadowPackageManager.installPackage(packageInfo);
2017 
2018     installedApplications = packageManager.getInstalledApplications(0);
2019     assertThat(installedApplications).hasSize(2);
2020     assertThat(installedApplications.get(1).packageName).isEqualTo("org.other");
2021   }
2022 
2023   @Test
getPermissionInfo()2024   public void getPermissionInfo() throws Exception {
2025     PermissionInfo permission =
2026         ApplicationProvider.getApplicationContext()
2027             .getPackageManager()
2028             .getPermissionInfo("org.robolectric.some_permission", 0);
2029     assertThat(permission.labelRes).isEqualTo(R.string.test_permission_label);
2030     assertThat(permission.descriptionRes).isEqualTo(R.string.test_permission_description);
2031     assertThat(permission.name).isEqualTo("org.robolectric.some_permission");
2032   }
2033 
2034   @Test
checkSignatures_same()2035   public void checkSignatures_same() throws Exception {
2036     shadowPackageManager.installPackage(newPackageInfo("first.package", new Signature("00000000")));
2037     shadowPackageManager.installPackage(
2038         newPackageInfo("second.package", new Signature("00000000")));
2039     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_MATCH);
2040   }
2041 
2042   @Test
checkSignatures_firstNotSigned()2043   public void checkSignatures_firstNotSigned() throws Exception {
2044     shadowPackageManager.installPackage(newPackageInfo("first.package", (Signature[]) null));
2045     shadowPackageManager.installPackage(
2046         newPackageInfo("second.package", new Signature("00000000")));
2047     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_FIRST_NOT_SIGNED);
2048   }
2049 
2050   @Test
checkSignatures_secondNotSigned()2051   public void checkSignatures_secondNotSigned() throws Exception {
2052     shadowPackageManager.installPackage(newPackageInfo("first.package", new Signature("00000000")));
2053     shadowPackageManager.installPackage(newPackageInfo("second.package", (Signature[]) null));
2054     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_SECOND_NOT_SIGNED);
2055   }
2056 
2057   @Test
checkSignatures_neitherSigned()2058   public void checkSignatures_neitherSigned() throws Exception {
2059     shadowPackageManager.installPackage(newPackageInfo("first.package", (Signature[]) null));
2060     shadowPackageManager.installPackage(newPackageInfo("second.package", (Signature[]) null));
2061     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_NEITHER_SIGNED);
2062   }
2063 
2064   @Test
checkSignatures_noMatch()2065   public void checkSignatures_noMatch() throws Exception {
2066     shadowPackageManager.installPackage(newPackageInfo("first.package", new Signature("00000000")));
2067     shadowPackageManager.installPackage(
2068         newPackageInfo("second.package", new Signature("FFFFFFFF")));
2069     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_NO_MATCH);
2070   }
2071 
2072   @Test
checkSignatures_noMatch_mustBeExact()2073   public void checkSignatures_noMatch_mustBeExact() throws Exception {
2074     shadowPackageManager.installPackage(newPackageInfo("first.package", new Signature("00000000")));
2075     shadowPackageManager.installPackage(
2076         newPackageInfo("second.package", new Signature("00000000"), new Signature("FFFFFFFF")));
2077     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_NO_MATCH);
2078   }
2079 
2080   @Test
checkSignatures_unknownPackage()2081   public void checkSignatures_unknownPackage() throws Exception {
2082     assertThat(packageManager.checkSignatures("first.package", "second.package")).isEqualTo(SIGNATURE_UNKNOWN_PACKAGE);
2083   }
2084 
newPackageInfo(String packageName, Signature... signatures)2085   private static PackageInfo newPackageInfo(String packageName, Signature... signatures) {
2086     PackageInfo firstPackageInfo = new PackageInfo();
2087     firstPackageInfo.packageName = packageName;
2088     firstPackageInfo.signatures = signatures;
2089     return firstPackageInfo;
2090   }
2091 
2092   @Test
getPermissionInfo_notFound()2093   public void getPermissionInfo_notFound(){
2094     try {
2095       packageManager.getPermissionInfo("non_existant_permission", 0);
2096       fail("should have thrown NameNotFoundException");
2097     } catch (NameNotFoundException e) {
2098       // expected
2099     }
2100   }
2101 
2102   @Test
getPermissionInfo_noMetaData()2103   public void getPermissionInfo_noMetaData() throws Exception {
2104     PermissionInfo permission =
2105         packageManager.getPermissionInfo("org.robolectric.some_permission", 0);
2106     assertThat(permission.metaData).isNull();
2107     assertThat(permission.name).isEqualTo("org.robolectric.some_permission");
2108     assertThat(permission.descriptionRes).isEqualTo(R.string.test_permission_description);
2109     assertThat(permission.labelRes).isEqualTo(R.string.test_permission_label);
2110     assertThat(permission.nonLocalizedLabel).isNull();
2111     assertThat(permission.group).isEqualTo("my_permission_group");
2112     assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_DANGEROUS);
2113   }
2114 
2115   @Test
getPermissionInfo_withMetaData()2116   public void getPermissionInfo_withMetaData() throws Exception {
2117     PermissionInfo permission =
2118         packageManager.getPermissionInfo(
2119             "org.robolectric.some_permission", PackageManager.GET_META_DATA);
2120     assertThat(permission.metaData).isNotNull();
2121     assertThat(permission.metaData.getString("meta_data_name")).isEqualTo("meta_data_value");
2122   }
2123 
2124   @Test
getPermissionInfo_withLiteralLabel()2125   public void getPermissionInfo_withLiteralLabel() throws Exception {
2126     PermissionInfo permission =
2127         packageManager.getPermissionInfo("org.robolectric.permission_with_literal_label", 0);
2128     assertThat(permission.labelRes).isEqualTo(0);
2129     assertThat(permission.nonLocalizedLabel).isEqualTo("Literal label");
2130     assertThat(permission.protectionLevel).isEqualTo(PermissionInfo.PROTECTION_NORMAL);
2131   }
2132 
2133   @Test
queryPermissionsByGroup_groupNotFound()2134   public void queryPermissionsByGroup_groupNotFound() throws Exception {
2135     try {
2136       packageManager.queryPermissionsByGroup("nonexistent_permission_group", 0);
2137       fail("Exception expected");
2138     } catch (NameNotFoundException expected) {
2139     }
2140   }
2141 
2142   @Test
queryPermissionsByGroup_noMetaData()2143   public void queryPermissionsByGroup_noMetaData() throws Exception {
2144     List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup("my_permission_group", 0);
2145     assertThat(permissions).hasSize(1);
2146 
2147     PermissionInfo permission = permissions.get(0);
2148 
2149     assertThat(permission.group).isEqualTo("my_permission_group");
2150     assertThat(permission.name).isEqualTo("org.robolectric.some_permission");
2151     assertThat(permission.metaData).isNull();
2152   }
2153 
2154   @Test
queryPermissionsByGroup_withMetaData()2155   public void queryPermissionsByGroup_withMetaData() throws Exception {
2156     List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup("my_permission_group", PackageManager.GET_META_DATA);
2157     assertThat(permissions).hasSize(1);
2158 
2159     PermissionInfo permission = permissions.get(0);
2160 
2161     assertThat(permission.group).isEqualTo("my_permission_group");
2162     assertThat(permission.name).isEqualTo("org.robolectric.some_permission");
2163     assertThat(permission.metaData).isNotNull();
2164     assertThat(permission.metaData.getString("meta_data_name")).isEqualTo("meta_data_value");
2165   }
2166 
2167   @Test
queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup()2168   public void queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup() throws Exception {
2169     List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup(null, 0);
2170 
2171     assertThat(Iterables.transform(permissions, getPermissionNames())).containsExactly(
2172             "org.robolectric.permission_with_minimal_fields",
2173             "org.robolectric.permission_with_literal_label");
2174   }
2175 
2176   @Test
queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup_with_addPermissionInfo()2177   public void queryPermissionsByGroup_nullMatchesPermissionsNotAssociatedWithGroup_with_addPermissionInfo() throws Exception {
2178     PermissionInfo permissionInfo = new PermissionInfo();
2179     permissionInfo.name = "some_name";
2180     shadowPackageManager.addPermissionInfo(permissionInfo);
2181 
2182     List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup(null, 0);
2183     assertThat(permissions).isNotEmpty();
2184 
2185     assertThat(permissions.get(0).name).isEqualTo(permissionInfo.name);
2186   }
2187 
2188   @Test
queryPermissionsByGroup_with_addPermissionInfo()2189   public void queryPermissionsByGroup_with_addPermissionInfo() throws Exception {
2190     PermissionInfo permissionInfo = new PermissionInfo();
2191     permissionInfo.name = "some_name";
2192     permissionInfo.group = "some_group";
2193     shadowPackageManager.addPermissionInfo(permissionInfo);
2194 
2195     List<PermissionInfo> permissions = packageManager.queryPermissionsByGroup(permissionInfo.group, 0);
2196     assertThat(permissions).hasSize(1);
2197 
2198     assertThat(permissions.get(0).name).isEqualTo(permissionInfo.name);
2199     assertThat(permissions.get(0).group).isEqualTo(permissionInfo.group);
2200   }
2201 
2202   @Test
getDefaultActivityIcon()2203   public void getDefaultActivityIcon() {
2204     assertThat(packageManager.getDefaultActivityIcon()).isNotNull();
2205   }
2206 
2207   @Test
addPackageShouldUseUidToProvidePackageName()2208   public void addPackageShouldUseUidToProvidePackageName() throws Exception {
2209     PackageInfo packageInfoOne = new PackageInfo();
2210     packageInfoOne.packageName = "package.one";
2211     packageInfoOne.applicationInfo = new ApplicationInfo();
2212     packageInfoOne.applicationInfo.uid = 1234;
2213     packageInfoOne.applicationInfo.packageName = packageInfoOne.packageName;
2214     shadowPackageManager.installPackage(packageInfoOne);
2215 
2216     PackageInfo packageInfoTwo = new PackageInfo();
2217     packageInfoTwo.packageName = "package.two";
2218     packageInfoTwo.applicationInfo = new ApplicationInfo();
2219     packageInfoTwo.applicationInfo.uid = 1234;
2220     packageInfoTwo.applicationInfo.packageName = packageInfoTwo.packageName;
2221     shadowPackageManager.installPackage(packageInfoTwo);
2222 
2223     assertThat(packageManager.getPackagesForUid(1234))
2224         .asList()
2225         .containsExactly("package.one", "package.two");
2226   }
2227 
2228   @Test
installerPackageName()2229   public void installerPackageName() throws Exception {
2230     packageManager.setInstallerPackageName("target.package", "installer.package");
2231 
2232     assertThat(packageManager.getInstallerPackageName("target.package")).isEqualTo("installer.package");
2233   }
2234 
2235   @Test
getXml()2236   public void getXml() throws Exception {
2237     XmlResourceParser in =
2238         packageManager.getXml(
2239             ApplicationProvider.getApplicationContext().getPackageName(),
2240             R.xml.dialog_preferences,
2241             ApplicationProvider.getApplicationContext().getApplicationInfo());
2242     assertThat(in).isNotNull();
2243   }
2244 
2245   @Test @Config(minSdk = LOLLIPOP)
addPackageShouldNotCreateSessions()2246   public void addPackageShouldNotCreateSessions() {
2247 
2248     PackageInfo packageInfo = new PackageInfo();
2249     packageInfo.packageName = "test.package";
2250     shadowPackageManager.installPackage(packageInfo);
2251 
2252     assertThat(packageManager.getPackageInstaller().getAllSessions()).isEmpty();
2253   }
2254 
2255   @Test
addPackageMultipleTimesShouldWork()2256   public void addPackageMultipleTimesShouldWork() throws Exception {
2257     shadowPackageManager.addPackage("test.package");
2258 
2259     // Shouldn't throw exception
2260     shadowPackageManager.addPackage("test.package");
2261   }
2262 
2263   @Test
addPackageSetsStorage()2264   public void addPackageSetsStorage() throws Exception {
2265     shadowPackageManager.addPackage("test.package");
2266 
2267     PackageInfo packageInfo = packageManager.getPackageInfo("test.package", 0);
2268     assertThat(packageInfo.applicationInfo.sourceDir).isNotNull();
2269     assertThat(new File(packageInfo.applicationInfo.sourceDir).exists()).isTrue();
2270     assertThat(packageInfo.applicationInfo.publicSourceDir)
2271         .isEqualTo(packageInfo.applicationInfo.sourceDir);
2272   }
2273 
2274   @Test
deletePackage()2275   public void deletePackage() throws Exception {
2276     // Apps must have the android.permission.DELETE_PACKAGES set to delete packages.
2277     PackageManager packageManager =
2278         ApplicationProvider.getApplicationContext().getPackageManager();
2279     shadowPackageManager.getInternalMutablePackageInfo(
2280                 ApplicationProvider.getApplicationContext().getPackageName())
2281             .requestedPermissions =
2282         new String[] {android.Manifest.permission.DELETE_PACKAGES};
2283 
2284     PackageInfo packageInfo = new PackageInfo();
2285     packageInfo.packageName = "test.package";
2286     shadowPackageManager.installPackage(packageInfo);
2287 
2288     IPackageDeleteObserver mockObserver = mock(IPackageDeleteObserver.class);
2289     packageManager.deletePackage(packageInfo.packageName, mockObserver, 0);
2290 
2291     shadowPackageManager.doPendingUninstallCallbacks();
2292 
2293     assertThat(shadowPackageManager.getDeletedPackages()).contains(packageInfo.packageName);
2294     verify(mockObserver).packageDeleted(packageInfo.packageName, PackageManager.DELETE_SUCCEEDED);
2295   }
2296 
2297   @Test
deletePackage_missingRequiredPermission()2298   public void deletePackage_missingRequiredPermission() throws Exception {
2299     PackageInfo packageInfo = new PackageInfo();
2300     packageInfo.packageName = "test.package";
2301     shadowPackageManager.installPackage(packageInfo);
2302 
2303     IPackageDeleteObserver mockObserver = mock(IPackageDeleteObserver.class);
2304     packageManager.deletePackage(packageInfo.packageName, mockObserver, 0);
2305 
2306     shadowPackageManager.doPendingUninstallCallbacks();
2307 
2308     assertThat(shadowPackageManager.getDeletedPackages()).hasSize(0);
2309     verify(mockObserver).packageDeleted(packageInfo.packageName, PackageManager.DELETE_FAILED_INTERNAL_ERROR);
2310   }
2311 
2312   public static class ActivityWithFilters extends Activity {}
2313 
2314   @Test
getIntentFiltersForActivity()2315   public void getIntentFiltersForActivity() throws NameNotFoundException {
2316     List<IntentFilter> intentFilters =
2317         shadowPackageManager.getIntentFiltersForActivity(
2318             new ComponentName(
2319                 ApplicationProvider.getApplicationContext(),
2320                 ActivityWithFilters.class));
2321     assertThat(intentFilters).hasSize(1);
2322     IntentFilter intentFilter = intentFilters.get(0);
2323     assertThat(intentFilter.getCategory(0)).isEqualTo(Intent.CATEGORY_DEFAULT);
2324     assertThat(intentFilter.getAction(0)).isEqualTo(Intent.ACTION_VIEW);
2325     assertThat(intentFilter.getDataPath(0).getPath()).isEqualTo("/testPath/test.jpeg");
2326   }
2327 
2328   @Test
getPackageInfo_shouldHaveWritableDataDirs()2329   public void getPackageInfo_shouldHaveWritableDataDirs() throws Exception {
2330     PackageInfo packageInfo =
2331         packageManager.getPackageInfo(
2332             ApplicationProvider.getApplicationContext().getPackageName(), 0);
2333 
2334     File dataDir = new File(packageInfo.applicationInfo.dataDir);
2335     assertThat(dataDir.isDirectory()).isTrue();
2336     assertThat(dataDir.exists()).isTrue();
2337   }
2338 
getPermissionNames()2339   private static Function<PermissionInfo, String> getPermissionNames() {
2340     return new Function<PermissionInfo, String>() {
2341       @Nullable
2342       @Override
2343       public String apply(@Nullable PermissionInfo permissionInfo) {
2344         return permissionInfo.name;
2345       }
2346     };
2347   }
2348 
2349   @Test
2350   @Config(minSdk = LOLLIPOP)
2351   public void getApplicationHiddenSettingAsUser_hidden() throws Exception {
2352     String packageName =
2353         ApplicationProvider.getApplicationContext().getPackageName();
2354 
2355     packageManager.setApplicationHiddenSettingAsUser(
2356         packageName, /* hidden= */ true, /* user= */ null);
2357 
2358     assertThat(packageManager.getApplicationHiddenSettingAsUser(packageName, /* user= */ null))
2359         .isTrue();
2360   }
2361 
2362   @Test
2363   @Config(minSdk = LOLLIPOP)
2364   public void getApplicationHiddenSettingAsUser_notHidden() throws Exception {
2365     String packageName =
2366         ApplicationProvider.getApplicationContext().getPackageName();
2367 
2368     assertThat(packageManager.getApplicationHiddenSettingAsUser(packageName, /* user= */ null))
2369         .isFalse();
2370   }
2371 
2372   @Test
2373   @Config(minSdk = LOLLIPOP)
2374   public void getApplicationHiddenSettingAsUser_unknownPackage() throws Exception {
2375     assertThat(packageManager.getApplicationHiddenSettingAsUser("not.a.package", /* user= */ null))
2376         .isTrue();
2377   }
2378 
2379   @Test
2380   @Config(minSdk = LOLLIPOP)
2381   public void setApplicationHiddenSettingAsUser_includeUninstalled() throws Exception {
2382     String packageName =
2383         ApplicationProvider.getApplicationContext().getPackageName();
2384 
2385     packageManager.setApplicationHiddenSettingAsUser(
2386         packageName, /* hidden= */ true, /* user= */ null);
2387 
2388     assertThat(packageManager.getPackageInfo(packageName, MATCH_UNINSTALLED_PACKAGES)).isNotNull();
2389     assertThat(packageManager.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES))
2390         .isNotNull();
2391     List<PackageInfo> installedPackages =
2392         packageManager.getInstalledPackages(MATCH_UNINSTALLED_PACKAGES);
2393     assertThat(installedPackages).hasSize(1);
2394     assertThat(installedPackages.get(0).packageName).isEqualTo(packageName);
2395   }
2396 
2397   @Test
2398   @Config(minSdk = LOLLIPOP)
2399   public void setApplicationHiddenSettingAsUser_dontIncludeUninstalled() throws Exception {
2400     String packageName =
2401         ApplicationProvider.getApplicationContext().getPackageName();
2402 
2403     packageManager.setApplicationHiddenSettingAsUser(
2404         packageName, /* hidden= */ true, /* user= */ null);
2405 
2406     try {
2407       packageManager.getPackageInfo(packageName, /* flags= */ 0);
2408       fail("PackageManager.NameNotFoundException not thrown");
2409     } catch (NameNotFoundException e) {
2410       // Expected
2411     }
2412 
2413     try {
2414       packageManager.getApplicationInfo(packageName, /* flags= */ 0);
2415       fail("PackageManager.NameNotFoundException not thrown");
2416     } catch (NameNotFoundException e) {
2417       // Expected
2418     }
2419 
2420     assertThat(packageManager.getInstalledPackages(/* flags= */ 0)).isEmpty();
2421   }
2422 
2423   @Test
2424   @Config(minSdk = LOLLIPOP_MR1)
2425   public void setUnbadgedApplicationIcon() throws Exception {
2426     String packageName =
2427         ApplicationProvider.getApplicationContext().getPackageName();
2428     Drawable d = new BitmapDrawable();
2429 
2430     shadowPackageManager.setUnbadgedApplicationIcon(packageName, d);
2431 
2432     assertThat(
2433             packageManager
2434                 .getApplicationInfo(packageName, PackageManager.GET_SHARED_LIBRARY_FILES)
2435                 .loadUnbadgedIcon(packageManager))
2436         .isSameAs(d);
2437   }
2438 
2439   @Test
2440   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2441   public void isPackageSuspended_nonExistentPackage_shouldThrow() {
2442     try {
2443       packageManager.isPackageSuspended(TEST_PACKAGE_NAME);
2444       fail("Should have thrown NameNotFoundException");
2445     } catch (Exception expected) {
2446       // The compiler thinks that isPackageSuspended doesn't throw NameNotFoundException because the
2447       // test is compiled against the publicly released SDK.
2448       assertThat(expected).isInstanceOf(NameNotFoundException.class);
2449     }
2450   }
2451 
2452   @Test
2453   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2454   public void isPackageSuspended_callersPackage_shouldReturnFalse() throws NameNotFoundException {
2455     assertThat(packageManager.isPackageSuspended(ApplicationProvider.getApplicationContext().getPackageName()))
2456         .isFalse();
2457   }
2458 
2459   @Test
2460   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2461   public void isPackageSuspended_installedNeverSuspendedPackage_shouldReturnFalse()
2462       throws NameNotFoundException {
2463     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2464     assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isFalse();
2465   }
2466 
2467   @Test
2468   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2469   public void isPackageSuspended_installedSuspendedPackage_shouldReturnTrue()
2470       throws NameNotFoundException {
2471     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2472     packageManager.setPackagesSuspended(
2473         new String[] {TEST_PACKAGE_NAME},
2474         /* suspended= */ true,
2475         /* appExtras= */ null,
2476         /* launcherExtras= */ null,
2477         /* dialogMessage= */ (String) null);
2478     assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isTrue();
2479   }
2480 
2481   @Test
2482   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2483   public void isPackageSuspended_installedUnsuspendedPackage_shouldReturnFalse()
2484       throws NameNotFoundException {
2485     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2486     packageManager.setPackagesSuspended(
2487         new String[] {TEST_PACKAGE_NAME},
2488         /* suspended= */ true,
2489         /* appExtras= */ null,
2490         /* launcherExtras= */ null,
2491         /* dialogMessage= */ (String) null);
2492     packageManager.setPackagesSuspended(
2493         new String[] {TEST_PACKAGE_NAME},
2494         /* suspended= */ false,
2495         /* appExtras= */ null,
2496         /* launcherExtras= */ null,
2497         /* dialogMessage= */ (String) null);
2498     assertThat(packageManager.isPackageSuspended(TEST_PACKAGE_NAME)).isFalse();
2499   }
2500 
2501   @Test
2502   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2503   public void setPackagesSuspended_withProfileOwner_shouldThrow() {
2504     DevicePolicyManager devicePolicyManager =
2505         (DevicePolicyManager)
2506             ApplicationProvider.getApplicationContext()
2507                 .getSystemService(Context.DEVICE_POLICY_SERVICE);
2508     shadowOf(devicePolicyManager)
2509         .setProfileOwner(new ComponentName("com.profile.owner", "ProfileOwnerClass"));
2510     try {
2511       packageManager.setPackagesSuspended(
2512           new String[] {TEST_PACKAGE_NAME},
2513           /* suspended= */ true,
2514           /* appExtras= */ null,
2515           /* launcherExtras= */ null,
2516           /* dialogMessage= */ (String) null);
2517       fail("Should have thrown UnsupportedOperationException");
2518     } catch (UnsupportedOperationException expected) {
2519     }
2520   }
2521 
2522   @Test
2523   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2524   public void setPackagesSuspended_withDeviceOwner_shouldThrow() {
2525     DevicePolicyManager devicePolicyManager =
2526         (DevicePolicyManager)
2527             ApplicationProvider.getApplicationContext()
2528                 .getSystemService(Context.DEVICE_POLICY_SERVICE);
2529     shadowOf(devicePolicyManager)
2530         .setDeviceOwner(new ComponentName("com.device.owner", "DeviceOwnerClass"));
2531     // Robolectric uses a random UID (see ShadowProcess#getRandomApplicationUid) that falls within
2532     // the range of the system user, so the device owner is on the current user and hence apps
2533     // cannot be suspended.
2534     try {
2535       packageManager.setPackagesSuspended(
2536           new String[] {TEST_PACKAGE_NAME},
2537           /* suspended= */ true,
2538           /* appExtras= */ null,
2539           /* launcherExtras= */ null,
2540           /* dialogMessage= */ (String) null);
2541       fail("Should have thrown UnsupportedOperationException");
2542     } catch (UnsupportedOperationException expected) {
2543     }
2544   }
2545 
2546   @Test
2547   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2548   public void setPackagesSuspended_shouldSuspendSuspendablePackagesAndReturnTheRest()
2549       throws NameNotFoundException {
2550     shadowPackageManager.installPackage(createPackageInfoWithPackageName("android"));
2551     shadowPackageManager.installPackage(
2552         createPackageInfoWithPackageName("com.suspendable.package1"));
2553     shadowPackageManager.installPackage(
2554         createPackageInfoWithPackageName("com.suspendable.package2"));
2555 
2556     assertThat(
2557             packageManager.setPackagesSuspended(
2558                 new String[] {
2559                   "com.nonexistent.package", // Unsuspenable (app doesn't exist).
2560                   "com.suspendable.package1",
2561                   "android", // Unsuspendable (platform package).
2562                   "com.suspendable.package2",
2563                   ApplicationProvider.getApplicationContext()
2564                       .getPackageName() // Unsuspendable (caller's package).
2565                 },
2566                 /* suspended= */ true,
2567                 /* appExtras= */ null,
2568                 /* launcherExtras= */ null,
2569                 /* dialogMessage= */ (String) null))
2570         .asList()
2571         .containsExactly(
2572             "com.nonexistent.package", "android",
2573             ApplicationProvider.getApplicationContext().getPackageName());
2574 
2575     assertThat(packageManager.isPackageSuspended("com.suspendable.package1")).isTrue();
2576     assertThat(packageManager.isPackageSuspended("android")).isFalse();
2577     assertThat(packageManager.isPackageSuspended("com.suspendable.package2")).isTrue();
2578     assertThat(packageManager.isPackageSuspended(
2579                    ApplicationProvider.getApplicationContext().getPackageName()))
2580         .isFalse();
2581   }
2582 
2583   @Test
2584   @Config(minSdk = android.os.Build.VERSION_CODES.O)
2585   public void getChangedPackages_negativeSequenceNumber_returnsNull() {
2586     shadowPackageManager.addChangedPackage(-5, TEST_PACKAGE_NAME);
2587 
2588     assertThat(packageManager.getChangedPackages(-5)).isNull();
2589   }
2590 
2591   @Test
2592   @Config(minSdk = android.os.Build.VERSION_CODES.O)
2593   public void getChangedPackages_validSequenceNumber_withChangedPackages() {
2594     shadowPackageManager.addChangedPackage(0, TEST_PACKAGE_NAME);
2595     shadowPackageManager.addChangedPackage(0, TEST_PACKAGE2_NAME);
2596     shadowPackageManager.addChangedPackage(1, "appPackageName");
2597 
2598     ChangedPackages changedPackages = packageManager.getChangedPackages(0);
2599     assertThat(changedPackages.getSequenceNumber()).isEqualTo(1);
2600     assertThat(changedPackages.getPackageNames())
2601         .containsExactly(TEST_PACKAGE_NAME, TEST_PACKAGE2_NAME);
2602   }
2603 
2604   @Test
2605   @Config(minSdk = android.os.Build.VERSION_CODES.O)
2606   public void getChangedPackages_validSequenceNumber_noChangedPackages() {
2607     assertThat(packageManager.getChangedPackages(0)).isNull();
2608   }
2609 
2610   @Test
2611   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2612   public void setPackagesSuspended_shouldUnsuspendSuspendablePackagesAndReturnTheRest()
2613       throws NameNotFoundException {
2614     shadowPackageManager.installPackage(createPackageInfoWithPackageName("android"));
2615     shadowPackageManager.installPackage(
2616         createPackageInfoWithPackageName("com.suspendable.package1"));
2617     shadowPackageManager.installPackage(
2618         createPackageInfoWithPackageName("com.suspendable.package2"));
2619     packageManager.setPackagesSuspended(
2620         new String[] {
2621           "com.suspendable.package1", "com.suspendable.package2",
2622         },
2623         /* suspended= */ false,
2624         /* appExtras= */ null,
2625         /* launcherExtras= */ null,
2626         /* dialogMessage= */ (String) null);
2627 
2628     assertThat(
2629             packageManager.setPackagesSuspended(
2630                 new String[] {
2631                   "com.nonexistent.package", // Unsuspenable (app doesn't exist).
2632                   "com.suspendable.package1",
2633                   "android", // Unsuspendable (platform package).
2634                   "com.suspendable.package2",
2635                   ApplicationProvider.getApplicationContext()
2636                       .getPackageName() // Unsuspendable (caller's package).
2637                 },
2638                 /* suspended= */ false,
2639                 /* appExtras= */ null,
2640                 /* launcherExtras= */ null,
2641                 /* dialogMessage= */ (String) null))
2642         .asList()
2643         .containsExactly(
2644             "com.nonexistent.package", "android", ApplicationProvider.getApplicationContext().getPackageName());
2645 
2646     assertThat(packageManager.isPackageSuspended("com.suspendable.package1")).isFalse();
2647     assertThat(packageManager.isPackageSuspended("android")).isFalse();
2648     assertThat(packageManager.isPackageSuspended("com.suspendable.package2")).isFalse();
2649     assertThat(packageManager.isPackageSuspended(ApplicationProvider.getApplicationContext().getPackageName()))
2650         .isFalse();
2651   }
2652 
2653   @Test
2654   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2655   public void getPackageSetting_nonExistentPackage_shouldReturnNull() {
2656     assertThat(shadowPackageManager.getPackageSetting(TEST_PACKAGE_NAME)).isNull();
2657   }
2658 
2659   @Test
2660   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2661   public void getPackageSetting_removedPackage_shouldReturnNull() {
2662     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2663     shadowPackageManager.removePackage(TEST_PACKAGE_NAME);
2664 
2665     assertThat(shadowPackageManager.getPackageSetting(TEST_PACKAGE_NAME)).isNull();
2666   }
2667 
2668   @Test
2669   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2670   public void getPackageSetting_installedNeverSuspendedPackage_shouldReturnUnsuspendedSetting() {
2671     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2672 
2673     PackageSetting setting = shadowPackageManager.getPackageSetting(TEST_PACKAGE_NAME);
2674 
2675     assertThat(setting.isSuspended()).isFalse();
2676     assertThat(setting.getDialogMessage()).isNull();
2677     assertThat(setting.getSuspendedAppExtras()).isNull();
2678     assertThat(setting.getSuspendedLauncherExtras()).isNull();
2679   }
2680 
2681   @Test
2682   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2683   public void getPackageSetting_installedSuspendedPackage_shouldReturnSuspendedSetting() {
2684     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2685     PersistableBundle appExtras = new PersistableBundle();
2686     appExtras.putString("key", "value");
2687     PersistableBundle launcherExtras = new PersistableBundle();
2688     launcherExtras.putInt("number", 7);
2689     packageManager.setPackagesSuspended(
2690         new String[] {TEST_PACKAGE_NAME}, true, appExtras, launcherExtras, "Dialog message");
2691 
2692     PackageSetting setting = shadowPackageManager.getPackageSetting(TEST_PACKAGE_NAME);
2693 
2694     assertThat(setting.isSuspended()).isTrue();
2695     assertThat(setting.getDialogMessage()).isEqualTo("Dialog message");
2696     assertThat(setting.getSuspendedAppExtras().getString("key")).isEqualTo("value");
2697     assertThat(setting.getSuspendedLauncherExtras().getInt("number")).isEqualTo(7);
2698   }
2699 
2700   @Test
2701   @Config(minSdk = android.os.Build.VERSION_CODES.P)
2702   public void getPackageSetting_installedUnsuspendedPackage_shouldReturnUnsuspendedSetting() {
2703     shadowPackageManager.installPackage(createPackageInfoWithPackageName(TEST_PACKAGE_NAME));
2704     PersistableBundle appExtras = new PersistableBundle();
2705     appExtras.putString("key", "value");
2706     PersistableBundle launcherExtras = new PersistableBundle();
2707     launcherExtras.putInt("number", 7);
2708     packageManager.setPackagesSuspended(
2709         new String[] {TEST_PACKAGE_NAME}, true, appExtras, launcherExtras, "Dialog message");
2710     packageManager.setPackagesSuspended(
2711         new String[] {TEST_PACKAGE_NAME}, false, appExtras, launcherExtras, "Dialog message");
2712 
2713     PackageSetting setting = shadowPackageManager.getPackageSetting(TEST_PACKAGE_NAME);
2714 
2715     assertThat(setting.isSuspended()).isFalse();
2716     assertThat(setting.getDialogMessage()).isNull();
2717     assertThat(setting.getSuspendedAppExtras()).isNull();
2718     assertThat(setting.getSuspendedLauncherExtras()).isNull();
2719   }
2720 
2721   @Test
2722   @Config(minSdk = android.os.Build.VERSION_CODES.O)
2723   public void canRequestPackageInstalls_shouldReturnFalseByDefault() throws Exception {
2724     assertThat(packageManager.canRequestPackageInstalls()).isFalse();
2725   }
2726 
2727   @Test
2728   @Config(minSdk = android.os.Build.VERSION_CODES.O)
2729   public void canRequestPackageInstalls_shouldReturnTrue_whenSetToTrue() throws Exception {
2730     shadowPackageManager.setCanRequestPackageInstalls(true);
2731     assertThat(packageManager.canRequestPackageInstalls()).isTrue();
2732   }
2733 
2734   @Test
2735   @Config(minSdk = android.os.Build.VERSION_CODES.O)
2736   public void canRequestPackageInstalls_shouldReturnFalse_whenSetToFalse() throws Exception {
2737     shadowPackageManager.setCanRequestPackageInstalls(false);
2738     assertThat(packageManager.canRequestPackageInstalls()).isFalse();
2739   }
2740 
2741   @Test
2742   public void loadIcon_default() {
2743     ActivityInfo info = new ActivityInfo();
2744     info.applicationInfo = new ApplicationInfo();
2745     info.packageName = "testPackage";
2746     info.name = "testName";
2747 
2748     Drawable icon = info.loadIcon(packageManager);
2749 
2750     assertThat(icon).isNotNull();
2751   }
2752 
2753   @Test
2754   public void loadIcon_specified() {
2755     ActivityInfo info = new ActivityInfo();
2756     info.applicationInfo = new ApplicationInfo();
2757     info.packageName = "testPackage";
2758     info.name = "testName";
2759     info.icon = R.drawable.an_image;
2760 
2761     Drawable icon = info.loadIcon(packageManager);
2762 
2763     assertThat(icon).isNotNull();
2764   }
2765 
2766   private static PackageInfo createPackageInfoWithPackageName(String packageName) {
2767     PackageInfo packageInfo = new PackageInfo();
2768     packageInfo.packageName = packageName;
2769     packageInfo.applicationInfo = new ApplicationInfo();
2770     packageInfo.applicationInfo.packageName = packageName;
2771     packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL;
2772     return packageInfo;
2773   }
2774 
2775 }
2776