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