• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.enterprise;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 
21 import static org.mockito.ArgumentMatchers.any;
22 import static org.mockito.ArgumentMatchers.anyInt;
23 import static org.mockito.ArgumentMatchers.argThat;
24 import static org.mockito.ArgumentMatchers.eq;
25 import static org.mockito.Mockito.mock;
26 import static org.mockito.Mockito.never;
27 import static org.mockito.Mockito.reset;
28 import static org.mockito.Mockito.verify;
29 import static org.mockito.Mockito.verifyNoMoreInteractions;
30 import static org.mockito.Mockito.when;
31 
32 import android.app.admin.DevicePolicyManager;
33 import android.app.supervision.SupervisionManager;
34 import android.content.ComponentName;
35 import android.content.Context;
36 import android.content.Intent;
37 import android.content.pm.ActivityInfo;
38 import android.content.pm.ApplicationInfo;
39 import android.content.pm.PackageManager;
40 import android.content.pm.ResolveInfo;
41 import android.content.pm.UserInfo;
42 import android.content.res.Resources;
43 import android.net.ConnectivityManager;
44 import android.net.VpnManager;
45 import android.os.UserHandle;
46 import android.os.UserManager;
47 import android.platform.test.annotations.DisableFlags;
48 import android.platform.test.annotations.EnableFlags;
49 import android.platform.test.flag.junit.SetFlagsRule;
50 import android.provider.Settings;
51 import android.text.SpannableStringBuilder;
52 
53 import com.android.settings.R;
54 
55 import com.google.common.collect.ImmutableList;
56 
57 import org.junit.Before;
58 import org.junit.Ignore;
59 import org.junit.Rule;
60 import org.junit.Test;
61 import org.junit.runner.RunWith;
62 import org.mockito.ArgumentCaptor;
63 import org.mockito.ArgumentMatcher;
64 import org.mockito.Mock;
65 import org.mockito.MockitoAnnotations;
66 import org.robolectric.RobolectricTestRunner;
67 import org.robolectric.RuntimeEnvironment;
68 
69 import java.util.ArrayList;
70 import java.util.Arrays;
71 import java.util.Date;
72 import java.util.List;
73 
74 
75 @RunWith(RobolectricTestRunner.class)
76 public class EnterprisePrivacyFeatureProviderImplTest {
77 
78     @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
79 
80     private static final String OWNER_ORGANIZATION = "ACME";
81     private static final String VPN_PACKAGE_ID = "com.example.vpn";
82     private static final String IME_PACKAGE_ID = "com.example.ime";
83     private static final String IME_PACKAGE_LABEL = "Test IME";
84     private static final String SUPERVISION_PACKAGE = "com.supervision.app";
85 
86     private final ComponentName mOwner = new ComponentName("mock", "component");
87     private final ComponentName mAdmin1 = new ComponentName("mock", "admin1");
88     private final ComponentName mAdmin2 = new ComponentName("mock", "admin2");
89     private final Date mDate = new Date(2011, 11, 11);
90     private final int mUserId = UserHandle.myUserId();
91     private final int mManagedProfileUserId = mUserId + 1;
92 
93     private List<UserInfo> mProfiles = new ArrayList<>();
94 
95     @Mock private Context mContext;
96     @Mock private DevicePolicyManager mDevicePolicyManager;
97     @Mock private PackageManager mPackageManager;
98     @Mock private UserManager mUserManager;
99     @Mock private ConnectivityManager mConnectivityManager;
100     @Mock private VpnManager mVpnManager;
101     private Resources mResources;
102     @Mock private SupervisionManager mSupervisionManager;
103 
104     private EnterprisePrivacyFeatureProvider mProvider;
105 
106     @Before
setUp()107     public void setUp() {
108         MockitoAnnotations.initMocks(this);
109 
110         when(mContext.getApplicationContext()).thenReturn(mContext);
111         resetAndInitializePackageManager();
112         when(mUserManager.getProfiles(mUserId)).thenReturn(mProfiles);
113         when(mContext.getSystemService(Context.DEVICE_POLICY_SERVICE))
114                 .thenReturn(mDevicePolicyManager);
115         when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
116         when(mContext.getSystemService(SupervisionManager.class))
117                 .thenReturn(mSupervisionManager);
118         when(mContext.getPackageManager()).thenReturn(mPackageManager);
119         mProfiles.add(new UserInfo(mUserId, "", "", 0 /* flags */));
120         mResources = RuntimeEnvironment.application.getResources();
121 
122         mProvider = new EnterprisePrivacyFeatureProviderImpl(mContext, mDevicePolicyManager,
123                 mPackageManager, mUserManager, mConnectivityManager, mVpnManager, mResources);
124     }
125 
126     @Test
testHasDeviceOwner()127     public void testHasDeviceOwner() {
128         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(null);
129         assertThat(mProvider.hasDeviceOwner()).isFalse();
130 
131         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(mOwner);
132         assertThat(mProvider.hasDeviceOwner()).isTrue();
133     }
134 
135     @Test
testIsInCompMode()136     public void testIsInCompMode() {
137         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(mOwner);
138         assertThat(mProvider.isInCompMode()).isFalse();
139 
140         mProfiles.add(new UserInfo(mManagedProfileUserId, "", "", UserInfo.FLAG_MANAGED_PROFILE));
141         assertThat(mProvider.isInCompMode()).isTrue();
142     }
143 
144     @Test
testGetDeviceOwnerOrganizationName()145     public void testGetDeviceOwnerOrganizationName() {
146         when(mDevicePolicyManager.getDeviceOwnerOrganizationName()).thenReturn(null);
147         assertThat(mProvider.getDeviceOwnerOrganizationName()).isNull();
148 
149         when(mDevicePolicyManager.getDeviceOwnerOrganizationName()).thenReturn(OWNER_ORGANIZATION);
150         assertThat(mProvider.getDeviceOwnerOrganizationName()).isEqualTo(OWNER_ORGANIZATION);
151     }
152 
153     @Test
154     @Ignore
testGetDeviceOwnerDisclosure()155     public void testGetDeviceOwnerDisclosure() {
156         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(null);
157         assertThat(mProvider.getDeviceOwnerDisclosure()).isNull();
158 
159         SpannableStringBuilder disclosure = new SpannableStringBuilder();
160         disclosure.append(mResources.getString(R.string.do_disclosure_generic));
161         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(mOwner);
162         when(mDevicePolicyManager.getDeviceOwnerOrganizationName()).thenReturn(null);
163         assertThat(mProvider.getDeviceOwnerDisclosure()).isEqualTo(disclosure);
164 
165         disclosure = new SpannableStringBuilder();
166         disclosure.append(mResources.getString(R.string.do_disclosure_with_name,
167                 OWNER_ORGANIZATION));
168         when(mDevicePolicyManager.getDeviceOwnerOrganizationName()).thenReturn(OWNER_ORGANIZATION);
169         assertThat(mProvider.getDeviceOwnerDisclosure()).isEqualTo(disclosure);
170     }
171 
172     @Test
testGetLastSecurityLogRetrievalTime()173     public void testGetLastSecurityLogRetrievalTime() {
174         when(mDevicePolicyManager.getLastSecurityLogRetrievalTime()).thenReturn(-1L);
175         assertThat(mProvider.getLastSecurityLogRetrievalTime()).isNull();
176 
177         when(mDevicePolicyManager.getLastSecurityLogRetrievalTime())
178                 .thenReturn(mDate.getTime());
179         assertThat(mProvider.getLastSecurityLogRetrievalTime()).isEqualTo(mDate);
180     }
181 
182     @Test
testGetLastBugReportRequestTime()183     public void testGetLastBugReportRequestTime() {
184         when(mDevicePolicyManager.getLastBugReportRequestTime()).thenReturn(-1L);
185         assertThat(mProvider.getLastBugReportRequestTime()).isNull();
186 
187         when(mDevicePolicyManager.getLastBugReportRequestTime()).thenReturn(mDate.getTime());
188         assertThat(mProvider.getLastBugReportRequestTime()).isEqualTo(mDate);
189     }
190 
191     @Test
testGetLastNetworkLogRetrievalTime()192     public void testGetLastNetworkLogRetrievalTime() {
193         when(mDevicePolicyManager.getLastNetworkLogRetrievalTime()).thenReturn(-1L);
194         assertThat(mProvider.getLastNetworkLogRetrievalTime()).isNull();
195 
196         when(mDevicePolicyManager.getLastNetworkLogRetrievalTime()).thenReturn(mDate.getTime());
197         assertThat(mProvider.getLastNetworkLogRetrievalTime()).isEqualTo(mDate);
198     }
199 
200     @Test
testIsSecurityLoggingEnabled()201     public void testIsSecurityLoggingEnabled() {
202         when(mDevicePolicyManager.isSecurityLoggingEnabled(null)).thenReturn(false);
203         assertThat(mProvider.isSecurityLoggingEnabled()).isFalse();
204 
205         when(mDevicePolicyManager.isSecurityLoggingEnabled(null)).thenReturn(true);
206         assertThat(mProvider.isSecurityLoggingEnabled()).isTrue();
207     }
208 
209     @Test
testIsNetworkLoggingEnabled()210     public void testIsNetworkLoggingEnabled() {
211         when(mDevicePolicyManager.isNetworkLoggingEnabled(null)).thenReturn(false);
212         assertThat(mProvider.isNetworkLoggingEnabled()).isFalse();
213 
214         when(mDevicePolicyManager.isNetworkLoggingEnabled(null)).thenReturn(true);
215         assertThat(mProvider.isNetworkLoggingEnabled()).isTrue();
216     }
217 
218     @Test
testIsAlwaysOnVpnSetInCurrentUser()219     public void testIsAlwaysOnVpnSetInCurrentUser() {
220         when(mVpnManager.getAlwaysOnVpnPackageForUser(mUserId)).thenReturn(null);
221         assertThat(mProvider.isAlwaysOnVpnSetInCurrentUser()).isFalse();
222 
223         when(mVpnManager.getAlwaysOnVpnPackageForUser(mUserId)).thenReturn(VPN_PACKAGE_ID);
224         assertThat(mProvider.isAlwaysOnVpnSetInCurrentUser()).isTrue();
225     }
226 
227     @Test
testIsAlwaysOnVpnSetInManagedProfileProfile()228     public void testIsAlwaysOnVpnSetInManagedProfileProfile() {
229         assertThat(mProvider.isAlwaysOnVpnSetInManagedProfile()).isFalse();
230 
231         mProfiles.add(new UserInfo(mManagedProfileUserId, "", "", UserInfo.FLAG_MANAGED_PROFILE));
232 
233         when(mVpnManager.getAlwaysOnVpnPackageForUser(mManagedProfileUserId)).thenReturn(null);
234         assertThat(mProvider.isAlwaysOnVpnSetInManagedProfile()).isFalse();
235 
236         when(mVpnManager.getAlwaysOnVpnPackageForUser(mManagedProfileUserId))
237                 .thenReturn(VPN_PACKAGE_ID);
238         assertThat(mProvider.isAlwaysOnVpnSetInManagedProfile()).isTrue();
239     }
240 
241     @Test
testGetMaximumFailedPasswordsForWipeInCurrentUser()242     public void testGetMaximumFailedPasswordsForWipeInCurrentUser() {
243         when(mDevicePolicyManager.getDeviceOwnerComponentOnCallingUser()).thenReturn(null);
244         when(mDevicePolicyManager.getProfileOwnerAsUser(mUserId)).thenReturn(null);
245         when(mDevicePolicyManager.getMaximumFailedPasswordsForWipe(mOwner, mUserId))
246                 .thenReturn(10);
247         assertThat(mProvider.getMaximumFailedPasswordsBeforeWipeInCurrentUser()).isEqualTo(0);
248 
249         when(mDevicePolicyManager.getProfileOwnerAsUser(mUserId)).thenReturn(mOwner);
250         assertThat(mProvider.getMaximumFailedPasswordsBeforeWipeInCurrentUser()).isEqualTo(10);
251 
252         when(mDevicePolicyManager.getDeviceOwnerComponentOnCallingUser()).thenReturn(mOwner);
253         when(mDevicePolicyManager.getProfileOwnerAsUser(mUserId)).thenReturn(null);
254         assertThat(mProvider.getMaximumFailedPasswordsBeforeWipeInCurrentUser()).isEqualTo(10);
255     }
256 
257     @Test
testGetMaximumFailedPasswordsForWipeInManagedProfile()258     public void testGetMaximumFailedPasswordsForWipeInManagedProfile() {
259         when(mDevicePolicyManager.getProfileOwnerAsUser(mManagedProfileUserId)).thenReturn(mOwner);
260         when(mDevicePolicyManager.getMaximumFailedPasswordsForWipe(mOwner, mManagedProfileUserId))
261                 .thenReturn(10);
262         assertThat(mProvider.getMaximumFailedPasswordsBeforeWipeInManagedProfile()).isEqualTo(0);
263 
264         mProfiles.add(new UserInfo(mManagedProfileUserId, "", "", UserInfo.FLAG_MANAGED_PROFILE));
265         assertThat(mProvider.getMaximumFailedPasswordsBeforeWipeInManagedProfile()).isEqualTo(10);
266     }
267 
268     @Test
testGetImeLabelIfOwnerSet()269     public void testGetImeLabelIfOwnerSet() throws Exception {
270         final ApplicationInfo applicationInfo = mock(ApplicationInfo.class);
271         when(applicationInfo.loadLabel(mPackageManager)).thenReturn(IME_PACKAGE_LABEL);
272 
273         Settings.Secure.putString(null, Settings.Secure.DEFAULT_INPUT_METHOD, IME_PACKAGE_ID);
274         when(mPackageManager.getApplicationInfoAsUser(IME_PACKAGE_ID, 0, mUserId))
275                 .thenReturn(applicationInfo);
276 
277         // IME not set by Device Owner.
278         when(mDevicePolicyManager.isCurrentInputMethodSetByOwner()).thenReturn(false);
279         assertThat(mProvider.getImeLabelIfOwnerSet()).isNull();
280 
281         // Device Owner set IME to empty string.
282         when(mDevicePolicyManager.isCurrentInputMethodSetByOwner()).thenReturn(true);
283         Settings.Secure.putString(null, Settings.Secure.DEFAULT_INPUT_METHOD, null);
284         assertThat(mProvider.getImeLabelIfOwnerSet()).isNull();
285 
286         // Device Owner set IME to nonexistent package.
287         Settings.Secure.putString(null, Settings.Secure.DEFAULT_INPUT_METHOD, IME_PACKAGE_ID);
288         when(mPackageManager.getApplicationInfoAsUser(IME_PACKAGE_ID, 0, mUserId))
289                 .thenThrow(new PackageManager.NameNotFoundException());
290         assertThat(mProvider.getImeLabelIfOwnerSet()).isNull();
291 
292         // Device Owner set IME to existent package.
293         resetAndInitializePackageManager();
294         when(mPackageManager.getApplicationInfoAsUser(IME_PACKAGE_ID, 0, mUserId))
295                 .thenReturn(applicationInfo);
296         assertThat(mProvider.getImeLabelIfOwnerSet()).isEqualTo(IME_PACKAGE_LABEL);
297     }
298 
299     @Test
testGetNumberOfOwnerInstalledCaCertsForCurrent()300     public void testGetNumberOfOwnerInstalledCaCertsForCurrent() {
301         final UserHandle userHandle = new UserHandle(UserHandle.USER_SYSTEM);
302         final UserHandle managedProfileUserHandle = new UserHandle(mManagedProfileUserId);
303 
304         when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
305                 .thenReturn(Arrays.asList("ca1", "ca2"));
306 
307         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
308                 .thenReturn(null);
309         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUser())
310                 .isEqualTo(0);
311         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
312                 .thenReturn(new ArrayList<>());
313         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUser())
314                 .isEqualTo(0);
315         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
316                 .thenReturn(Arrays.asList("ca1", "ca2"));
317         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUser())
318                 .isEqualTo(2);
319     }
320 
321     @Test
testGetNumberOfOwnerInstalledCaCertsForManagedProfile()322     public void testGetNumberOfOwnerInstalledCaCertsForManagedProfile() {
323         final UserHandle userHandle = new UserHandle(UserHandle.USER_SYSTEM);
324         final UserHandle managedProfileUserHandle = new UserHandle(mManagedProfileUserId);
325         final UserInfo managedProfile =
326                 new UserInfo(mManagedProfileUserId, "", "", UserInfo.FLAG_MANAGED_PROFILE);
327 
328         // Without a profile
329         when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
330                 .thenReturn(Arrays.asList("ca1", "ca2"));
331         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForManagedProfile())
332                 .isEqualTo(0);
333 
334         // With a profile
335         mProfiles.add(managedProfile);
336         when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
337                 .thenReturn(null);
338         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForManagedProfile())
339                 .isEqualTo(0);
340         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
341                 .thenReturn(new ArrayList<>());
342         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForManagedProfile())
343                 .isEqualTo(0);
344         when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
345                 .thenReturn(Arrays.asList("ca1", "ca2"));
346         assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForManagedProfile())
347                 .isEqualTo(2);
348     }
349 
350     @Test
testGetNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile()351     public void testGetNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile() {
352         when(mDevicePolicyManager.getActiveAdminsAsUser(mUserId))
353                 .thenReturn(Arrays.asList(mAdmin1, mAdmin2));
354         when(mDevicePolicyManager.getActiveAdminsAsUser(mManagedProfileUserId))
355                 .thenReturn(Arrays.asList(mAdmin1));
356 
357         assertThat(mProvider.getNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile())
358                 .isEqualTo(2);
359 
360         mProfiles.add(new UserInfo(mManagedProfileUserId, "", "", UserInfo.FLAG_MANAGED_PROFILE));
361         assertThat(mProvider.getNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile())
362                 .isEqualTo(3);
363     }
364 
365     @Test
workPolicyInfo_unmanagedDevice_shouldDoNothing()366     public void workPolicyInfo_unmanagedDevice_shouldDoNothing() {
367         // Even if we have the intent resolved, don't show it if there's no DO or PO
368         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(null);
369         addWorkPolicyInfoIntent(mOwner.getPackageName(), true, false);
370         assertThat(mProvider.hasWorkPolicyInfo()).isFalse();
371 
372         assertThat(mProvider.showWorkPolicyInfo(mContext)).isFalse();
373         verify(mContext, never()).startActivity(any());
374     }
375 
376     @Test
workPolicyInfo_deviceOwner_shouldResolveIntent()377     public void workPolicyInfo_deviceOwner_shouldResolveIntent() {
378         // If the intent is not resolved, then there's no info to show for DO
379         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(mOwner);
380         assertThat(mProvider.hasWorkPolicyInfo()).isFalse();
381         assertThat(mProvider.showWorkPolicyInfo(mContext)).isFalse();
382 
383         // If the intent is resolved, then we can use it to launch the activity
384         Intent intent = addWorkPolicyInfoIntent(mOwner.getPackageName(), true, false);
385         assertThat(mProvider.hasWorkPolicyInfo()).isTrue();
386         assertThat(mProvider.showWorkPolicyInfo(mContext)).isTrue();
387         verify(mContext).startActivity(intentEquals(intent));
388     }
389 
390     @Test
workPolicyInfo_profileOwner_shouldResolveIntent()391     public void workPolicyInfo_profileOwner_shouldResolveIntent()
392             throws PackageManager.NameNotFoundException {
393         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(null);
394         List<UserHandle> mAllProfiles = new ArrayList<>();
395         mAllProfiles.add(new UserHandle(mManagedProfileUserId));
396         when(mUserManager.getAllProfiles()).thenReturn(mAllProfiles);
397         when(mUserManager.isManagedProfile(mManagedProfileUserId)).thenReturn(true);
398         when(mContext.getPackageName()).thenReturn("somePackageName");
399         when(mContext.createPackageContextAsUser(
400                 eq(mContext.getPackageName()),
401                 anyInt(),
402                 any(UserHandle.class))
403         ).thenReturn(mContext);
404         when(mContext.getSystemService(Context.DEVICE_POLICY_SERVICE))
405                 .thenReturn(mDevicePolicyManager);
406         when(mDevicePolicyManager.getProfileOwner()).thenReturn(mOwner);
407 
408         // If the intent is not resolved, then there's no info to show for PO
409         assertThat(mProvider.hasWorkPolicyInfo()).isFalse();
410         assertThat(mProvider.showWorkPolicyInfo(mContext)).isFalse();
411 
412         // If the intent is resolved, then we can use it to launch the activity in managed profile
413         Intent intent = addWorkPolicyInfoIntent(mOwner.getPackageName(), false, true);
414         assertThat(mProvider.hasWorkPolicyInfo()).isTrue();
415         assertThat(mProvider.showWorkPolicyInfo(mContext)).isTrue();
416         verify(mContext)
417                 .startActivityAsUser(
418                         intentEquals(intent),
419                         argThat(handle -> handle.getIdentifier() == mManagedProfileUserId));
420     }
421 
422     @Test
workPolicyInfo_comp_shouldUseDeviceOwnerIntent()423     public void workPolicyInfo_comp_shouldUseDeviceOwnerIntent() {
424         when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(mOwner);
425         mProfiles.add(new UserInfo(mManagedProfileUserId, "", "", UserInfo.FLAG_MANAGED_PROFILE));
426         when(mDevicePolicyManager.getProfileOwnerAsUser(mUserId)).thenReturn(mOwner);
427 
428         // If the intent is not resolved, then there's no info to show for COMP
429         assertThat(mProvider.hasWorkPolicyInfo()).isFalse();
430         assertThat(mProvider.showWorkPolicyInfo(mContext)).isFalse();
431 
432         // If the intent is resolved, then we can use it to launch the activity for device owner
433         Intent intent = addWorkPolicyInfoIntent(mOwner.getPackageName(), true, true);
434         assertThat(mProvider.hasWorkPolicyInfo()).isTrue();
435         assertThat(mProvider.showWorkPolicyInfo(mContext)).isTrue();
436         verify(mContext).startActivity(intentEquals(intent));
437     }
438 
439     @Test
440     @DisableFlags(android.app.supervision.flags.Flags.FLAG_DEPRECATE_DPM_SUPERVISION_APIS)
testShowParentalControls()441     public void testShowParentalControls() {
442         when(mDevicePolicyManager.getProfileOwnerOrDeviceOwnerSupervisionComponent(any()))
443                 .thenReturn(mOwner);
444 
445         // If the intent is resolved, then we can use it to launch the activity
446         Intent intent = addParentalControlsIntent(mOwner.getPackageName());
447         assertThat(mProvider.showParentalControls()).isTrue();
448         verify(mContext).startActivity(intentEquals(intent));
449     }
450 
451     @Test
452     @EnableFlags(android.app.supervision.flags.Flags.FLAG_DEPRECATE_DPM_SUPERVISION_APIS)
testShowParentalControls_usingSupervisionManager()453     public void testShowParentalControls_usingSupervisionManager() {
454         when(mSupervisionManager.getActiveSupervisionAppPackage())
455                 .thenReturn(SUPERVISION_PACKAGE);
456         when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
457                 .thenReturn(ImmutableList.of(new ResolveInfo()));
458 
459         // If the intent is resolved, then we can use it to launch the activity.
460         assertThat(mProvider.showParentalControls()).isTrue();
461         verifyNoMoreInteractions(mDevicePolicyManager);
462 
463         ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
464         verify(mContext).startActivity(captor.capture());
465         Intent intent = captor.getValue();
466         assertThat(intent).isNotNull();
467         assertThat(intent.getPackage()).isEqualTo(SUPERVISION_PACKAGE);
468     }
469 
addWorkPolicyInfoIntent( String packageName, boolean deviceOwner, boolean profileOwner)470     private Intent addWorkPolicyInfoIntent(
471             String packageName, boolean deviceOwner, boolean profileOwner) {
472         Intent intent = new Intent(Settings.ACTION_SHOW_WORK_POLICY_INFO);
473         intent.setPackage(packageName);
474         ResolveInfo resolveInfo = new ResolveInfo();
475         resolveInfo.resolvePackageName = packageName;
476         resolveInfo.activityInfo = new ActivityInfo();
477         resolveInfo.activityInfo.name = "activityName";
478         resolveInfo.activityInfo.packageName = packageName;
479 
480         List<ResolveInfo> activities = ImmutableList.of(resolveInfo);
481         if (deviceOwner) {
482             when(mPackageManager.queryIntentActivities(intentEquals(intent), anyInt()))
483                     .thenReturn(activities);
484         }
485         if (profileOwner) {
486             when(mPackageManager.queryIntentActivitiesAsUser(
487                     intentEquals(intent), anyInt(), eq(UserHandle.of(mManagedProfileUserId))))
488                     .thenReturn(activities);
489         }
490 
491         return intent;
492     }
493 
addParentalControlsIntent(String packageName)494     private Intent addParentalControlsIntent(String packageName) {
495         Intent intent = new Intent(EnterprisePrivacyFeatureProviderImpl.ACTION_PARENTAL_CONTROLS);
496         intent.setPackage(packageName);
497         ResolveInfo resolveInfo = new ResolveInfo();
498         resolveInfo.resolvePackageName = packageName;
499         resolveInfo.activityInfo = new ActivityInfo();
500         resolveInfo.activityInfo.name = "activityName";
501         resolveInfo.activityInfo.packageName = packageName;
502 
503         List<ResolveInfo> activities = ImmutableList.of(resolveInfo);
504         when(mPackageManager.queryIntentActivities(intentEquals(intent), anyInt()))
505                 .thenReturn(activities);
506         when(mPackageManager.queryIntentActivitiesAsUser(intentEquals(intent), anyInt(), anyInt()))
507                 .thenReturn(activities);
508         return intent;
509     }
510 
511     private static class IntentMatcher implements ArgumentMatcher<Intent> {
512         private final Intent mExpectedIntent;
513 
IntentMatcher(Intent expectedIntent)514         public IntentMatcher(Intent expectedIntent) {
515             mExpectedIntent = expectedIntent;
516         }
517 
518         @Override
matches(Intent actualIntent)519         public boolean matches(Intent actualIntent) {
520             // filterEquals() compares only the action, data, type, class, and categories.
521             return actualIntent != null && mExpectedIntent.filterEquals(actualIntent);
522         }
523     }
524 
intentEquals(Intent intent)525     private static Intent intentEquals(Intent intent) {
526         return argThat(new IntentMatcher(intent));
527     }
528 
resetAndInitializePackageManager()529     private void resetAndInitializePackageManager() {
530         reset(mPackageManager);
531         when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
532                 .thenReturn(true);
533     }
534 }
535