• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 package com.android.cts.devicepolicy;
17 
18 import static com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier.assertMetricsLogged;
19 
20 import static com.google.common.truth.Truth.assertThat;
21 
22 import static org.junit.Assert.assertFalse;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25 
26 import android.platform.test.annotations.FlakyTest;
27 import android.platform.test.annotations.LargeTest;
28 import android.stats.devicepolicy.EventId;
29 
30 import com.android.cts.devicepolicy.DeviceAdminFeaturesCheckerRule.DoesNotRequireFeature;
31 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
32 import com.android.ddmlib.Log.LogLevel;
33 import com.android.tradefed.device.DeviceNotAvailableException;
34 import com.android.tradefed.log.LogUtil.CLog;
35 
36 
37 import org.junit.Ignore;
38 import org.junit.Test;
39 
40 import java.util.HashMap;
41 import java.util.Map;
42 import java.util.concurrent.TimeUnit;
43 
44 /**
45  * Set of tests for Managed Profile use cases.
46  */
47 public class ManagedProfileTest extends BaseManagedProfileTest {
48 
49     private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner";
50     private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk";
51     private static final String DEVICE_OWNER_ADMIN =
52             DEVICE_OWNER_PKG + ".BaseDeviceOwnerTest$BasicAdminReceiver";
53 
54     @Test
testManagedProfileSetup()55     public void testManagedProfileSetup() throws Exception {
56         runDeviceTestsAsUser(
57                 MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".ManagedProfileSetupTest",
58                 mProfileUserId);
59     }
60 
61     @DoesNotRequireFeature
62     @Test
testMaxOneManagedProfile()63     public void testMaxOneManagedProfile() throws Exception {
64         int newUserId = -1;
65         try {
66             newUserId = createManagedProfile(mParentUserId);
67         } catch (AssertionError expected) {
68         }
69         if (newUserId > 0) {
70             removeUser(newUserId);
71             if (mFeaturesCheckerRule.hasRequiredFeatures()) {
72                 // Exception is Android TV which can create multiple managed profiles
73                 if (!isTv()) {
74                     fail("Device must allow creating only one managed profile");
75                 }
76             } else {
77                 fail("Device must not allow creating a managed profile");
78             }
79         }
80     }
81 
82     /**
83      * Verify that removing a managed profile will remove all networks owned by that profile.
84      */
85     @Test
testProfileWifiCleanup()86     public void testProfileWifiCleanup() throws Exception {
87         assumeHasWifiFeature();
88 
89         try (LocationModeSetter locationModeSetter = new LocationModeSetter(getDevice())) {
90             locationModeSetter.setLocationEnabled(true);
91             runDeviceTestsAsUser(
92                     MANAGED_PROFILE_PKG, ".WifiTest", "testRemoveWifiNetworkIfExists",
93                     mParentUserId);
94 
95             runDeviceTestsAsUser(
96                     MANAGED_PROFILE_PKG, ".WifiTest", "testAddWifiNetwork", mProfileUserId);
97 
98             // Now delete the user - should undo the effect of testAddWifiNetwork.
99             removeUser(mProfileUserId);
100             runDeviceTestsAsUser(
101                     MANAGED_PROFILE_PKG, ".WifiTest", "testWifiNetworkDoesNotExist",
102                     mParentUserId);
103         }
104     }
105 
106     @Test
testSettingsIntents()107     public void testSettingsIntents() throws Exception {
108         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SettingsIntentsTest",
109                 mProfileUserId);
110     }
111 
112     /** Tests for the API helper class. */
113     @Test
testCurrentApiHelper()114     public void testCurrentApiHelper() throws Exception {
115         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CurrentApiHelperTest",
116                 mProfileUserId);
117     }
118 
119     /** Test: unsupported public APIs are disabled on a parent profile. */
120     @Test
testParentProfileApiDisabled()121     public void testParentProfileApiDisabled() throws Exception {
122         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ParentProfileTest",
123                 "testParentProfileApiDisabled", mProfileUserId);
124     }
125 
126     @Test
testOverrideApn()127     public void testOverrideApn() throws Exception {
128         assumeHasTelephonyFeature();
129 
130         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OverrideApnTest",
131                 "testAddGetRemoveOverrideApn", mProfileUserId);
132         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OverrideApnTest",
133                 "testUpdateOverrideApn", mProfileUserId);
134     }
135 
136     @Test
testCannotCallMethodsOnParentProfile()137     public void testCannotCallMethodsOnParentProfile() throws Exception {
138         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ParentProfileTest",
139                 "testCannotWipeParentProfile", mProfileUserId);
140 
141         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ParentProfileTest",
142                 "testCannotCallAutoTimeMethodsOnParentProfile", mProfileUserId);
143 
144         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ParentProfileTest",
145                 "testCannotCallSetDefaultSmsApplicationOnParentProfile", mProfileUserId);
146     }
147 
148     // TODO: This test is not specific to managed profiles, but applies to multi-user in general.
149     // Move it to a MultiUserTest class when there is one. Should probably move
150     // SetPolicyActivity to a more generic apk too as it might be useful for different kinds
151     // of tests (same applies to ComponentDisablingActivity).
152     @Test
testNoDebuggingFeaturesRestriction()153     public void testNoDebuggingFeaturesRestriction() throws Exception {
154         // If adb is running as root, then the adb uid is 0 instead of SHELL_UID,
155         // so the DISALLOW_DEBUGGING_FEATURES restriction does not work and this test
156         // fails.
157         if (getDevice().isAdbRoot()) {
158             CLog.logAndDisplay(LogLevel.WARN,
159                     "Cannot test testNoDebuggingFeaturesRestriction() in eng/userdebug build");
160             return;
161         }
162         String restriction = "no_debugging_features";  // UserManager.DISALLOW_DEBUGGING_FEATURES
163 
164         changeUserRestrictionOrFail(restriction, true, mProfileUserId);
165 
166 
167         // This should now fail, as the shell is not available to start activities under a different
168         // user once the restriction is in place.
169         String addRestrictionCommandOutput =
170                 changeUserRestriction(restriction, true, mProfileUserId);
171         assertTrue(
172                 "Expected SecurityException when starting the activity "
173                         + addRestrictionCommandOutput,
174                 addRestrictionCommandOutput.contains("SecurityException"));
175     }
176 
177     @Test
testOrganizationInfo()178     public void testOrganizationInfo() throws Exception {
179         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
180                 "testDefaultOrganizationColor", mProfileUserId);
181         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
182                 "testDefaultOrganizationNameIsNull", mProfileUserId);
183         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
184                 mProfileUserId);
185         assertMetricsLogged(getDevice(), () -> {
186             runDeviceTestsAsUser(
187                     MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".OrganizationInfoTest",
188                     "testSetOrganizationColor", mProfileUserId);
189         }, new DevicePolicyEventWrapper.Builder(EventId.SET_ORGANIZATION_COLOR_VALUE)
190                 .setAdminPackageName(MANAGED_PROFILE_PKG)
191                 .build());
192     }
193 
194     @Test
testDevicePolicyManagerParentSupport()195     public void testDevicePolicyManagerParentSupport() throws Exception {
196         runDeviceTestsAsUser(
197                 MANAGED_PROFILE_PKG, ".DevicePolicyManagerParentSupportTest", mProfileUserId);
198     }
199 
200     @Test
testBluetoothContactSharingDisabled()201     public void testBluetoothContactSharingDisabled() throws Exception {
202         assertMetricsLogged(getDevice(), () -> {
203             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
204                     "testSetBluetoothContactSharingDisabled_setterAndGetter", mProfileUserId);
205         }, new DevicePolicyEventWrapper
206                     .Builder(EventId.SET_BLUETOOTH_CONTACT_SHARING_DISABLED_VALUE)
207                     .setAdminPackageName(MANAGED_PROFILE_PKG)
208                     .setBoolean(false)
209                     .build(),
210             new DevicePolicyEventWrapper
211                     .Builder(EventId.SET_BLUETOOTH_CONTACT_SHARING_DISABLED_VALUE)
212                     .setAdminPackageName(MANAGED_PROFILE_PKG)
213                     .setBoolean(true)
214                     .build());
215     }
216 
217     @Test
testCannotSetProfileOwnerAgain()218     public void testCannotSetProfileOwnerAgain() throws Exception {
219         // verify that we can't set the same admin receiver as profile owner again
220         assertFalse(setProfileOwner(
221                 MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mProfileUserId,
222                 /*expectFailure*/ true));
223 
224         // verify that we can't set a different admin receiver as profile owner
225         installAppAsUser(DEVICE_OWNER_APK, mProfileUserId);
226         assertFalse(setProfileOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mProfileUserId,
227                 /*expectFailure*/ true));
228     }
229 
230     @LargeTest
231     @Test
testCannotSetDeviceOwnerWhenProfilePresent()232     public void testCannotSetDeviceOwnerWhenProfilePresent() throws Exception {
233         try {
234             installAppAsUser(DEVICE_OWNER_APK, mParentUserId);
235             assertFalse(setDeviceOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mParentUserId,
236                     /*expectFailure*/ true));
237         } finally {
238             // make sure we clean up in case we succeeded in setting the device owner
239             removeAdmin(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mParentUserId);
240             getDevice().uninstallPackage(DEVICE_OWNER_PKG);
241         }
242     }
243 
244     @Test
testNfcRestriction()245     public void testNfcRestriction() throws Exception {
246         assumeHasNfcFeatures();
247 
248         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
249                 "testNfcShareEnabled", mProfileUserId);
250         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
251                 "testNfcShareEnabled", mParentUserId);
252 
253         changeUserRestrictionOrFail("no_outgoing_beam" /* UserManager.DISALLOW_OUTGOING_BEAM */,
254                 true, mProfileUserId);
255 
256         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
257                 "testNfcShareDisabled", mProfileUserId);
258         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
259                 "testNfcShareEnabled", mParentUserId);
260     }
261 
262     @Test
testIsProvisioningAllowed()263     public void testIsProvisioningAllowed() throws DeviceNotAvailableException {
264         // Not allowed to add a managed profile from another managed profile.
265         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PreManagedProfileTest",
266                 "testIsProvisioningAllowedFalse", mProfileUserId);
267 
268         // Not allowed to add a managed profile to the parent user if one already exists.
269         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PreManagedProfileTest",
270                 "testIsProvisioningAllowedFalse", mParentUserId);
271     }
272 
273     @Test
testPhoneAccountVisibility()274     public void testPhoneAccountVisibility() throws Exception {
275         assumeHasTelephonyAndConnectionServiceFeatures();
276 
277         try {
278             // Register phone account in parent user.
279             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
280                     "testRegisterPhoneAccount",
281                     mParentUserId);
282             // The phone account should not be visible in managed user.
283             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
284                     "testPhoneAccountNotRegistered",
285                     mProfileUserId);
286         } finally {
287             // Unregister the phone account.
288             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
289                     "testUnregisterPhoneAccount",
290                     mParentUserId);
291         }
292 
293         try {
294             // Register phone account in profile user.
295             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
296                     "testRegisterPhoneAccount",
297                     mProfileUserId);
298             // The phone account should not be visible in parent user.
299             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
300                     "testPhoneAccountNotRegistered",
301                     mParentUserId);
302         } finally {
303             // Unregister the phone account.
304             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
305                     "testUnregisterPhoneAccount",
306                     mProfileUserId);
307         }
308     }
309 
310     @LargeTest
311     @Test
testManagedCall()312     public void testManagedCall() throws Exception {
313         assumeHasTelephonyAndConnectionServiceFeatures();
314 
315         getDevice().executeShellCommand("telecom set-default-dialer " + MANAGED_PROFILE_PKG);
316 
317         // Place a outgoing call through work phone account using TelecomManager and verify the
318         // call is inserted properly.
319         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
320                 "testOutgoingCallUsingTelecomManager",
321                 mProfileUserId);
322         // Make sure the call is not inserted into parent user.
323         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
324                 "testEnsureCallNotInserted",
325                 mParentUserId);
326 
327         // Place a outgoing call through work phone account using ACTION_CALL and verify the call
328         // is inserted properly.
329         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
330                 "testOutgoingCallUsingActionCall",
331                 mProfileUserId);
332         // Make sure the call is not inserted into parent user.
333         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
334                 "testEnsureCallNotInserted",
335                 mParentUserId);
336 
337         // Add an incoming call with parent user's phone account and verify the call is inserted
338         // properly.
339         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
340                 "testIncomingCall",
341                 mProfileUserId);
342         // Make sure the call is not inserted into parent user.
343         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
344                 "testEnsureCallNotInserted",
345                 mParentUserId);
346 
347         // Add an incoming missed call with parent user's phone account and verify the call is
348         // inserted properly.
349         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
350                 "testIncomingMissedCall",
351                 mProfileUserId);
352         // Make sure the call is not inserted into parent user.
353         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
354                 "testEnsureCallNotInserted",
355                 mParentUserId);
356     }
357 
358     @Test
testTrustAgentInfo()359     public void testTrustAgentInfo() throws Exception {
360         assumeHasSecureLockScreenFeature();
361 
362         // Set and get trust agent config using child dpm instance.
363         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
364                 "testSetAndGetTrustAgentConfiguration_child",
365                 mProfileUserId);
366         // Set and get trust agent config using parent dpm instance.
367         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
368                 "testSetAndGetTrustAgentConfiguration_parent",
369                 mProfileUserId);
370         // Unified case
371         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
372                 "testSetTrustAgentConfiguration_bothHaveTrustAgentConfigAndUnified",
373                 mProfileUserId);
374         // Non-unified case
375         try {
376             changeUserCredential(TEST_PASSWORD, null, mProfileUserId);
377             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
378                     "testSetTrustAgentConfiguration_bothHaveTrustAgentConfigAndNonUnified",
379                     mProfileUserId);
380         } finally {
381             changeUserCredential(null, TEST_PASSWORD, mProfileUserId);
382         }
383     }
384 
385     // TODO(b/149580605): Fix this flaky test.
386     @Test
387     @FlakyTest
388     @Ignore
testBasicCheck()389     public void testBasicCheck() throws Exception {
390         // Install SimpleApp in work profile only and check activity in it can be launched.
391         installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
392         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BasicTest", mProfileUserId);
393     }
394 
395     @Test
testBluetoothSharingRestriction()396     public void testBluetoothSharingRestriction() throws Exception {
397         assumeHasBluetoothFeature();
398 
399         // Primary profile should be able to use bluetooth sharing.
400         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionPrimaryProfileTest",
401                 "testBluetoothSharingAvailable", mPrimaryUserId);
402 
403         // Managed profile owner should be able to control it via DISALLOW_BLUETOOTH_SHARING.
404         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionTest",
405                 "testOppDisabledWhenRestrictionSet", mProfileUserId);
406     }
407 
408     @Test
testProfileOwnerOnPersonalDeviceCannotGetDeviceIdentifiers()409     public void testProfileOwnerOnPersonalDeviceCannotGetDeviceIdentifiers() throws Exception {
410         // The Profile Owner should have access to all device identifiers.
411         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DeviceIdentifiersTest",
412                 "testProfileOwnerOnPersonalDeviceCannotGetDeviceIdentifiers", mProfileUserId);
413     }
414 
415     @Test
testSetProfileNameLogged()416     public void testSetProfileNameLogged() throws Exception {
417         assertMetricsLogged(getDevice(), () -> {
418             runDeviceTestsAsUser(
419                     MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".DevicePolicyLoggingTest",
420                     "testSetProfileNameLogged", mProfileUserId);
421         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PROFILE_NAME_VALUE)
422                 .setAdminPackageName(MANAGED_PROFILE_PKG)
423                 .build());
424     }
425 
426     @Test
userManagerIsManagedProfileReturnsCorrectValues()427     public void userManagerIsManagedProfileReturnsCorrectValues() throws Exception {
428         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
429                 "testIsManagedProfileReturnsTrue", mProfileUserId);
430 
431         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
432                 "testIsManagedProfileReturnsFalse", mPrimaryUserId);
433     }
434 
435     @Test
testCanGetWorkShortcutIconDrawableFromPersonalProfile()436     public void testCanGetWorkShortcutIconDrawableFromPersonalProfile()
437             throws DeviceNotAvailableException {
438         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
439                 "addDynamicShortcuts", mProfileUserId);
440         try {
441             Map<String, String> params = new HashMap<>();
442             params.put("otherProfileUserId", String.valueOf(mProfileUserId));
443             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
444                     "shortcutIconDrawable_currentToOtherProfile_withUsersFullPermission_isNotNull",
445                     mPrimaryUserId, params);
446         } finally {
447             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
448                     "removeAllDynamicShortcuts", mProfileUserId);
449         }
450     }
451 
452     @Test
testCanGetPersonalShortcutIconDrawableFromWorkProfile()453     public void testCanGetPersonalShortcutIconDrawableFromWorkProfile()
454             throws DeviceNotAvailableException {
455         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
456                 "addDynamicShortcuts", mPrimaryUserId);
457         try {
458             Map<String, String> params = new HashMap<>();
459             params.put("otherProfileUserId", String.valueOf(mPrimaryUserId));
460             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
461                     "shortcutIconDrawable_currentToOtherProfile_withUsersFullPermission_isNotNull",
462                     mProfileUserId, params);
463             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
464                     "shortcutIconDrawable_currentToOtherProfile_withoutUsersFullPermission_isNull",
465                     mProfileUserId, params);
466         } finally {
467             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".LauncherAppsTest",
468                     "removeAllDynamicShortcuts", mPrimaryUserId);
469         }
470     }
471 
472     @Test
testCanGetProfiles()473     public void testCanGetProfiles() throws Exception {
474         // getAllProfiles should contain both the primary and profile
475         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
476                 "testGetAllProfiles", mPrimaryUserId);
477 
478         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
479                 "testGetAllProfiles", mProfileUserId);
480 
481         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
482                 "testIsProfileReturnsFalse_runAsPrimary", mPrimaryUserId);
483 
484         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
485                 "testIsProfileReturnsTrue_runAsProfile", mProfileUserId);
486     }
487 
488     @Test
testCanCreateProfile()489     public void testCanCreateProfile() throws Exception {
490         // remove pre-created profile
491         removeUser(mProfileUserId);
492 
493         // create profile from installed app
494         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".UserManagerTest",
495                 "testCreateProfile_managedProfile", mPrimaryUserId);
496     }
497 
498     @Test
testResolverActivityLaunchedFromPersonalProfileWithSelectedWorkTab()499     public void testResolverActivityLaunchedFromPersonalProfileWithSelectedWorkTab()
500             throws Exception {
501         installAppAsUser(SHARING_APP_1_APK, mPrimaryUserId);
502         installAppAsUser(SHARING_APP_2_APK, mPrimaryUserId);
503         installAppAsUser(SHARING_APP_1_APK, mProfileUserId);
504         installAppAsUser(SHARING_APP_2_APK, mProfileUserId);
505         try {
506             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
507                     "addCrossProfileIntents", mProfileUserId);
508             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
509                     "startSwitchToOtherProfileIntent", mPrimaryUserId);
510             assertResolverActivityInForeground(mPrimaryUserId);
511         } finally {
512             pressHome();
513             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
514                     "clearCrossProfileIntents", mProfileUserId);
515         }
516     }
517 
518     @Test
testResolverActivityLaunchedFromWorkProfileWithSelectedPersonalTab()519     public void testResolverActivityLaunchedFromWorkProfileWithSelectedPersonalTab()
520             throws Exception {
521         installAppAsUser(SHARING_APP_1_APK, mPrimaryUserId);
522         installAppAsUser(SHARING_APP_2_APK, mPrimaryUserId);
523         installAppAsUser(SHARING_APP_1_APK, mProfileUserId);
524         installAppAsUser(SHARING_APP_2_APK, mProfileUserId);
525         try {
526             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
527                     "addCrossProfileIntents", mProfileUserId);
528             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
529                     "startSwitchToOtherProfileIntent", mProfileUserId);
530 
531             // TODO(b/223178698): Investigate potential increase in latency
532             Thread.sleep(30000);
533 
534             assertResolverActivityInForeground(mProfileUserId);
535         } finally {
536             pressHome();
537             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
538                     "clearCrossProfileIntents", mProfileUserId);
539         }
540     }
541 
542     @Test
testChooserActivityLaunchedFromPersonalProfileWithSelectedWorkTab()543     public void testChooserActivityLaunchedFromPersonalProfileWithSelectedWorkTab()
544             throws Exception {
545         installAppAsUser(SHARING_APP_1_APK, mPrimaryUserId);
546         installAppAsUser(SHARING_APP_2_APK, mPrimaryUserId);
547         installAppAsUser(SHARING_APP_1_APK, mProfileUserId);
548         installAppAsUser(SHARING_APP_2_APK, mProfileUserId);
549         try {
550             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
551                     "addCrossProfileIntents", mProfileUserId);
552             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
553                     "startSwitchToOtherProfileIntent_chooser", mPrimaryUserId);
554             assertChooserActivityInForeground(mPrimaryUserId);
555         } finally {
556             pressHome();
557             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
558                     "clearCrossProfileIntents", mProfileUserId);
559         }
560     }
561 
562     @Test
testChooserActivityLaunchedFromWorkProfileWithSelectedPersonalTab()563     public void testChooserActivityLaunchedFromWorkProfileWithSelectedPersonalTab()
564             throws Exception {
565         installAppAsUser(SHARING_APP_1_APK, mPrimaryUserId);
566         installAppAsUser(SHARING_APP_2_APK, mPrimaryUserId);
567         installAppAsUser(SHARING_APP_1_APK, mProfileUserId);
568         installAppAsUser(SHARING_APP_2_APK, mProfileUserId);
569         try {
570             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
571                     "addCrossProfileIntents", mProfileUserId);
572             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
573                     "startSwitchToOtherProfileIntent_chooser", mProfileUserId);
574 
575             Thread.sleep(30000);
576 
577             assertChooserActivityInForeground(mProfileUserId);
578         } finally {
579             pressHome();
580             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileSharingTest",
581                     "clearCrossProfileIntents", mProfileUserId);
582         }
583     }
584 
pressHome()585     private void pressHome() throws Exception {
586         executeShellCommand("input keyevent KEYCODE_HOME");
587     }
588 
assertChooserActivityInForeground(int userId)589     private void assertChooserActivityInForeground(int userId)
590             throws Exception {
591         try {
592             assertActivityInForeground("android/com.android.internal.app.ChooserActivity", userId);
593         } catch (AssertionError e) {
594             CLog.v("ChooserActivity is not the default: " + e);
595             assertActivityInForeground(resolveActivity("android.intent.action.CHOOSER"), userId);
596         }
597     }
598 
assertResolverActivityInForeground(int userId)599     private void assertResolverActivityInForeground(int userId)
600             throws Exception {
601         try {
602             assertActivityInForeground("android/com.android.internal.app.ResolverActivity", userId);
603         } catch (AssertionError e) {
604             CLog.v("ResolverActivity is not the default: " + e);
605             assertActivityInForeground(getCustomResolverActivity(), userId);
606         }
607     }
608 
assertActivityInForeground(String fullActivityName, int userId)609     private void assertActivityInForeground(String fullActivityName, int userId)
610             throws DeviceNotAvailableException {
611         final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
612         while (System.nanoTime() <= deadline) {
613             String commandOutput = getDevice().executeShellCommand(
614                     "dumpsys activity activities | grep Resumed:");
615             if (commandOutput.contains("u" + userId + " " + fullActivityName)) {
616                 return;
617             }
618             try {
619                 Thread.sleep(100);
620             } catch (InterruptedException e){
621                 e.printStackTrace();
622                 Thread.currentThread().interrupt();
623             }
624         }
625         fail("Activity " + fullActivityName + " didn't become foreground");
626     }
627 
changeUserRestrictionOrFail(String key, boolean value, int userId)628     private void changeUserRestrictionOrFail(String key, boolean value, int userId)
629             throws DeviceNotAvailableException {
630         changeUserRestrictionOrFail(key, value, userId, MANAGED_PROFILE_PKG);
631     }
632 
changeUserRestriction(String key, boolean value, int userId)633     private String changeUserRestriction(String key, boolean value, int userId)
634             throws DeviceNotAvailableException {
635         return changeUserRestriction(key, value, userId, MANAGED_PROFILE_PKG);
636     }
637 
resolveActivity(String action)638     private String resolveActivity(String action) throws Exception  {
639         // Template output of 'pm resolve-activity -a {action} --brief' :
640         // priority=0 preferredOrder=0 match=0x0 specificIndex=-1 isDefault=false
641         // com.bar/.foo or com.bar/com.bar.foo
642         final String[] outputs = getDevice().executeShellCommand(
643                     "pm resolve-activity -a " + action + " --brief").split("\n");
644 
645         assertTrue("Result of shell command: 'pm resolve-activity -a " + action
646                    + " --brief' is " + outputs[0], outputs.length >= 2);
647 
648         return outputs[1];
649     }
650 
getCustomResolverActivity()651     private String getCustomResolverActivity() throws Exception {
652         final String[] outputs = getDevice().executeShellCommand(
653                 "cmd overlay lookup android android:string/config_customResolverActivity")
654                 .split("\n");
655 
656         String customResolverActivity = resolveActivity("android.intent.action.SEND");
657         if (outputs != null && outputs.length >= 1 && outputs[0] != null && !outputs[0].isEmpty()) {
658             customResolverActivity = outputs[0];
659         }
660         return customResolverActivity;
661     }
662 }
663