Home | History | Annotate | Download | only in devicepolicy
      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 
     17 package com.android.cts.devicepolicy;
     18 
     19 import static com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier.assertMetricsLogged;
     20 
     21 
     22 import android.stats.devicepolicy.EventId;
     23 
     24 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
     25 import com.android.ddmlib.Log.LogLevel;
     26 import com.android.tradefed.device.DeviceNotAvailableException;
     27 import com.android.tradefed.log.LogUtil.CLog;
     28 
     29 import junit.framework.AssertionFailedError;
     30 
     31 import java.util.Collections;
     32 import java.util.concurrent.Callable;
     33 import java.util.concurrent.TimeUnit;
     34 import java.util.regex.Matcher;
     35 import java.util.regex.Pattern;
     36 
     37 /**
     38  * Set of tests for Managed Profile use cases.
     39  */
     40 public class ManagedProfileTest extends BaseDevicePolicyTest {
     41 
     42     private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile";
     43     private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk";
     44 
     45     private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner";
     46     private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk";
     47     private static final String DEVICE_OWNER_ADMIN =
     48             DEVICE_OWNER_PKG + ".BaseDeviceOwnerTest$BasicAdminReceiver";
     49 
     50     private static final String INTENT_SENDER_PKG = "com.android.cts.intent.sender";
     51     private static final String INTENT_SENDER_APK = "CtsIntentSenderApp.apk";
     52 
     53     private static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver";
     54     private static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk";
     55 
     56     private static final String WIDGET_PROVIDER_APK = "CtsWidgetProviderApp.apk";
     57     private static final String WIDGET_PROVIDER_PKG = "com.android.cts.widgetprovider";
     58 
     59     private static final String DIRECTORY_PROVIDER_APK = "CtsContactDirectoryProvider.apk";
     60     private static final String DIRECTORY_PROVIDER_PKG
     61             = "com.android.cts.contactdirectoryprovider";
     62     private static final String PRIMARY_DIRECTORY_PREFIX = "Primary";
     63     private static final String MANAGED_DIRECTORY_PREFIX = "Managed";
     64     private static final String DIRECTORY_PRIVOIDER_URI
     65             = "content://com.android.cts.contact.directory.provider/";
     66     private static final String SET_CUSTOM_DIRECTORY_PREFIX_METHOD = "set_prefix";
     67 
     68     private static final String NOTIFICATION_APK = "CtsNotificationSenderApp.apk";
     69     private static final String NOTIFICATION_PKG =
     70             "com.android.cts.managedprofiletests.notificationsender";
     71 
     72     private static final String ADMIN_RECEIVER_TEST_CLASS =
     73             MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver";
     74 
     75     private static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
     76     private static final String FEATURE_CAMERA = "android.hardware.camera";
     77     private static final String FEATURE_WIFI = "android.hardware.wifi";
     78     private static final String FEATURE_TELEPHONY = "android.hardware.telephony";
     79     private static final String FEATURE_CONNECTION_SERVICE = "android.software.connectionservice";
     80 
     81     private static final String SIMPLE_APP_APK = "CtsSimpleApp.apk";
     82 
     83     private static final long TIMEOUT_USER_LOCKED_MILLIS = TimeUnit.MINUTES.toMillis(2);
     84 
     85     private static final String PARAM_PROFILE_ID = "profile-id";
     86 
     87     // Password needs to be in sync with ResetPasswordWithTokenTest.PASSWORD1
     88     private static final String RESET_PASSWORD_TEST_DEFAULT_PASSWORD = "123456";
     89 
     90     private static final String PROFILE_CREDENTIAL = "1234";
     91     // This should be sufficiently larger than ProfileTimeoutTestHelper.TIMEOUT_MS
     92     private static final int PROFILE_TIMEOUT_DELAY_MS = 40_000;
     93 
     94     //The maximum time to wait for user to be unlocked.
     95     private static final long USER_UNLOCK_TIMEOUT_NANO = 30_000_000_000L;
     96 
     97     private static final String USER_UNLOCKED_SHELL_OUTPUT = "RUNNING_UNLOCKED";
     98 
     99     private int mParentUserId;
    100 
    101     // ID of the profile we'll create. This will always be a profile of the parent.
    102     private int mProfileUserId;
    103 
    104     private boolean mHasNfcFeature;
    105 
    106     @Override
    107     protected void setUp() throws Exception {
    108         super.setUp();
    109 
    110         // We need multi user to be supported in order to create a profile of the user owner.
    111         mHasFeature = mHasFeature && hasDeviceFeature("android.software.managed_users");
    112         mHasNfcFeature = hasDeviceFeature("android.hardware.nfc")
    113                 && hasDeviceFeature("android.sofware.nfc.beam");
    114 
    115         if (mHasFeature) {
    116             removeTestUsers();
    117             mParentUserId = mPrimaryUserId;
    118             mProfileUserId = createManagedProfile(mParentUserId);
    119             startUser(mProfileUserId);
    120 
    121             installAppAsUser(MANAGED_PROFILE_APK, mParentUserId);
    122             installAppAsUser(MANAGED_PROFILE_APK, mProfileUserId);
    123             setProfileOwnerOrFail(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS,
    124                     mProfileUserId);
    125             waitForUserUnlock();
    126         }
    127     }
    128 
    129     private void waitForUserUnlock() throws Exception {
    130         final String command = String.format("am get-started-user-state %d", mProfileUserId);
    131         final long deadline = System.nanoTime() + USER_UNLOCK_TIMEOUT_NANO;
    132         while (System.nanoTime() <= deadline) {
    133             if (getDevice().executeShellCommand(command).startsWith(USER_UNLOCKED_SHELL_OUTPUT)) {
    134                 return;
    135             }
    136             Thread.sleep(100);
    137         }
    138         fail("Profile user is not unlocked.");
    139     }
    140 
    141     @Override
    142     protected void tearDown() throws Exception {
    143         if (mHasFeature) {
    144             removeUser(mProfileUserId);
    145             getDevice().uninstallPackage(MANAGED_PROFILE_PKG);
    146             getDevice().uninstallPackage(INTENT_SENDER_PKG);
    147             getDevice().uninstallPackage(INTENT_RECEIVER_PKG);
    148             getDevice().uninstallPackage(NOTIFICATION_PKG);
    149         }
    150         super.tearDown();
    151     }
    152 
    153     public void testManagedProfilesSupportedWithLockScreenOnly() throws Exception {
    154         if (mHasFeature) {
    155             // Managed profiles should be only supported if the device supports the secure lock
    156             // screen feature.
    157             assertTrue(mHasSecureLockScreen);
    158         }
    159     }
    160 
    161     public void testManagedProfileSetup() throws Exception {
    162         if (!mHasFeature) {
    163             return;
    164         }
    165         runDeviceTestsAsUser(
    166                 MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".ManagedProfileSetupTest",
    167                 mProfileUserId);
    168     }
    169 
    170     public void testWipeDataWithReason() throws Exception {
    171         if (!mHasFeature) {
    172             return;
    173         }
    174         assertTrue(listUsers().contains(mProfileUserId));
    175         sendWipeProfileBroadcast("com.android.cts.managedprofile.WIPE_DATA_WITH_REASON");
    176         // Note: the managed profile is removed by this test, which will make removeUserCommand in
    177         // tearDown() to complain, but that should be OK since its result is not asserted.
    178         assertUserGetsRemoved(mProfileUserId);
    179         // testWipeDataWithReason() removes the managed profile,
    180         // so it needs to separated from other tests.
    181         // Check and clear the notification is presented after work profile got removed, so profile
    182         // user no longer exists, verification should be run in primary user.
    183         runDeviceTestsAsUser(
    184                 MANAGED_PROFILE_PKG,
    185                 ".WipeDataNotificationTest",
    186                 "testWipeDataWithReasonVerification",
    187                 mParentUserId);
    188     }
    189 
    190     public void testWipeDataLogged() throws Exception {
    191         if (!mHasFeature) {
    192             return;
    193         }
    194         assertTrue(listUsers().contains(mProfileUserId));
    195         assertMetricsLogged(getDevice(), () -> {
    196             sendWipeProfileBroadcast("com.android.cts.managedprofile.WIPE_DATA_WITH_REASON");
    197         }, new DevicePolicyEventWrapper.Builder(EventId.WIPE_DATA_WITH_REASON_VALUE)
    198                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    199                 .setInt(0)
    200                 .build());
    201         // Check and clear the notification is presented after work profile got removed, so profile
    202         // user no longer exists, verification should be run in primary user.
    203         runDeviceTestsAsUser(
    204                 MANAGED_PROFILE_PKG,
    205                 ".WipeDataNotificationTest",
    206                 "testWipeDataWithReasonVerification",
    207                 mParentUserId);
    208     }
    209 
    210     public void testWipeDataWithoutReason() throws Exception {
    211         if (!mHasFeature) {
    212             return;
    213         }
    214         assertTrue(listUsers().contains(mProfileUserId));
    215         sendWipeProfileBroadcast("com.android.cts.managedprofile.WIPE_DATA_WITHOUT_REASON");
    216         // Note: the managed profile is removed by this test, which will make removeUserCommand in
    217         // tearDown() to complain, but that should be OK since its result is not asserted.
    218         assertUserGetsRemoved(mProfileUserId);
    219         // testWipeDataWithoutReason() removes the managed profile,
    220         // so it needs to separated from other tests.
    221         // Check the notification is not presented after work profile got removed, so profile user
    222         // no longer exists, verification should be run in primary user.
    223         runDeviceTestsAsUser(
    224                 MANAGED_PROFILE_PKG,
    225                 ".WipeDataNotificationTest",
    226                 "testWipeDataWithoutReasonVerification",
    227                 mParentUserId);
    228     }
    229 
    230     /**
    231      * wipeData() test removes the managed profile, so it needs to be separated from other tests.
    232      */
    233     public void testWipeData() throws Exception {
    234         if (!mHasFeature) {
    235             return;
    236         }
    237         assertTrue(listUsers().contains(mProfileUserId));
    238         sendWipeProfileBroadcast("com.android.cts.managedprofile.WIPE_DATA");
    239         // Note: the managed profile is removed by this test, which will make removeUserCommand in
    240         // tearDown() to complain, but that should be OK since its result is not asserted.
    241         assertUserGetsRemoved(mProfileUserId);
    242     }
    243 
    244     private void sendWipeProfileBroadcast(String action) throws Exception {
    245         final String cmd = "am broadcast --receiver-foreground --user " + mProfileUserId
    246                 + " -a " + action
    247                 + " com.android.cts.managedprofile/.WipeDataReceiver";
    248         getDevice().executeShellCommand(cmd);
    249     }
    250 
    251     public void testLockNowWithKeyEviction() throws Exception {
    252         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
    253             return;
    254         }
    255         changeUserCredential("1234", null, mProfileUserId);
    256         lockProfile();
    257     }
    258 
    259     private void lockProfile() throws Exception {
    260         final String cmd = "am broadcast --receiver-foreground --user " + mProfileUserId
    261                 + " -a com.android.cts.managedprofile.LOCK_PROFILE"
    262                 + " com.android.cts.managedprofile/.LockProfileReceiver";
    263         getDevice().executeShellCommand(cmd);
    264         waitUntilProfileLocked();
    265     }
    266 
    267     private void waitUntilProfileLocked() throws Exception {
    268         final String cmd = "dumpsys activity | grep 'User #" + mProfileUserId + ": state='";
    269         final Pattern p = Pattern.compile("state=([\\p{Upper}_]+)$");
    270         SuccessCondition userLocked = () -> {
    271             final String activityDump = getDevice().executeShellCommand(cmd);
    272             final Matcher m = p.matcher(activityDump);
    273             return m.find() && m.group(1).equals("RUNNING_LOCKED");
    274         };
    275         tryWaitForSuccess(
    276                 userLocked,
    277                 "The managed profile has not been locked after calling "
    278                         + "lockNow(FLAG_SECURE_USER_DATA)",
    279                 TIMEOUT_USER_LOCKED_MILLIS);
    280     }
    281 
    282     /** Profile should get locked if it is not in foreground no matter what. */
    283     public void testWorkProfileTimeoutBackground() throws Exception {
    284         if (!mHasFeature) {
    285             return;
    286         }
    287         setUpWorkProfileTimeout();
    288 
    289         startDummyActivity(mPrimaryUserId, true);
    290         simulateUserInteraction(PROFILE_TIMEOUT_DELAY_MS);
    291 
    292         verifyOnlyProfileLocked(true);
    293     }
    294 
    295     /** Profile should get locked if it is in foreground but with no user activity. */
    296     public void testWorkProfileTimeoutIdleActivity() throws Exception {
    297         if (!mHasFeature) {
    298             return;
    299         }
    300         setUpWorkProfileTimeout();
    301 
    302         startDummyActivity(mProfileUserId, false);
    303         Thread.sleep(PROFILE_TIMEOUT_DELAY_MS);
    304 
    305         verifyOnlyProfileLocked(true);
    306     }
    307 
    308     /** User activity in profile should prevent it from locking. */
    309     public void testWorkProfileTimeoutUserActivity() throws Exception {
    310         if (!mHasFeature) {
    311             return;
    312         }
    313         setUpWorkProfileTimeout();
    314 
    315         startDummyActivity(mProfileUserId, false);
    316         simulateUserInteraction(PROFILE_TIMEOUT_DELAY_MS);
    317 
    318         verifyOnlyProfileLocked(false);
    319     }
    320 
    321     /** Keep screen on window flag in the profile should prevent it from locking. */
    322     public void testWorkProfileTimeoutKeepScreenOnWindow() throws Exception {
    323         if (!mHasFeature) {
    324             return;
    325         }
    326         setUpWorkProfileTimeout();
    327 
    328         startDummyActivity(mProfileUserId, true);
    329         Thread.sleep(PROFILE_TIMEOUT_DELAY_MS);
    330 
    331         verifyOnlyProfileLocked(false);
    332     }
    333 
    334     private void setUpWorkProfileTimeout() throws DeviceNotAvailableException {
    335         // Set separate challenge.
    336         changeUserCredential(PROFILE_CREDENTIAL, null, mProfileUserId);
    337 
    338         // Make sure the profile is not prematurely locked.
    339         verifyUserCredential(PROFILE_CREDENTIAL, mProfileUserId);
    340         verifyOnlyProfileLocked(false);
    341         // Set profile timeout to 5 seconds.
    342         runProfileTimeoutTest("testSetWorkProfileTimeout", mProfileUserId);
    343     }
    344 
    345     private void verifyOnlyProfileLocked(boolean locked) throws DeviceNotAvailableException {
    346         final String expectedResultTest = locked ? "testDeviceLocked" : "testDeviceNotLocked";
    347         runProfileTimeoutTest(expectedResultTest, mProfileUserId);
    348         // Primary profile shouldn't be locked.
    349         runProfileTimeoutTest("testDeviceNotLocked", mPrimaryUserId);
    350     }
    351 
    352     private void simulateUserInteraction(int timeMs) throws Exception {
    353         final long endTime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeMs);
    354         final UserActivityEmulator helper = new UserActivityEmulator(getDevice());
    355         while (System.nanoTime() < endTime) {
    356             helper.tapScreenCenter();
    357             // Just in case to prevent busy loop.
    358             Thread.sleep(100);
    359         }
    360     }
    361 
    362     private void runProfileTimeoutTest(String method, int userId)
    363             throws DeviceNotAvailableException {
    364         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".ProfileTimeoutTestHelper",
    365                 method, userId);
    366     }
    367 
    368     private void startDummyActivity(int profileUserId, boolean keepScreenOn) throws Exception {
    369         getDevice().executeShellCommand(String.format(
    370                 "am start-activity -W --user %d --ez keep_screen_on %s %s/.TimeoutActivity",
    371                 profileUserId, keepScreenOn, MANAGED_PROFILE_PKG));
    372     }
    373 
    374     public void testMaxOneManagedProfile() throws Exception {
    375         int newUserId = -1;
    376         try {
    377             newUserId = createManagedProfile(mParentUserId);
    378         } catch (AssertionFailedError expected) {
    379         }
    380         if (newUserId > 0) {
    381             removeUser(newUserId);
    382             fail(mHasFeature ? "Device must allow creating only one managed profile"
    383                     : "Device must not allow creating a managed profile");
    384         }
    385     }
    386 
    387     /**
    388      * Verify that removing a managed profile will remove all networks owned by that profile.
    389      */
    390     public void testProfileWifiCleanup() throws Exception {
    391         if (!mHasFeature || !hasDeviceFeature(FEATURE_WIFI)) {
    392             return;
    393         }
    394         runDeviceTestsAsUser(
    395                 MANAGED_PROFILE_PKG, ".WifiTest", "testRemoveWifiNetworkIfExists", mParentUserId);
    396 
    397         runDeviceTestsAsUser(
    398                 MANAGED_PROFILE_PKG, ".WifiTest", "testAddWifiNetwork", mProfileUserId);
    399 
    400         // Now delete the user - should undo the effect of testAddWifiNetwork.
    401         removeUser(mProfileUserId);
    402         runDeviceTestsAsUser(
    403                 MANAGED_PROFILE_PKG, ".WifiTest", "testWifiNetworkDoesNotExist",
    404                 mParentUserId);
    405     }
    406 
    407     public void testWifiMacAddress() throws Exception {
    408         if (!mHasFeature || !hasDeviceFeature(FEATURE_WIFI)) {
    409             return;
    410         }
    411         runDeviceTestsAsUser(
    412                 MANAGED_PROFILE_PKG, ".WifiTest", "testCannotGetWifiMacAddress", mProfileUserId);
    413     }
    414 
    415     public void testCrossProfileIntentFilters() throws Exception {
    416         if (!mHasFeature) {
    417             return;
    418         }
    419         // Set up activities: ManagedProfileActivity will only be enabled in the managed profile and
    420         // PrimaryUserActivity only in the primary one
    421         disableActivityForUser("ManagedProfileActivity", mParentUserId);
    422         disableActivityForUser("PrimaryUserActivity", mProfileUserId);
    423 
    424         runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    425                 MANAGED_PROFILE_PKG + ".ManagedProfileTest", mProfileUserId);
    426 
    427         assertMetricsLogged(getDevice(), () -> {
    428             runDeviceTestsAsUser(
    429                     MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".ManagedProfileTest",
    430                     "testAddCrossProfileIntentFilter_all", mProfileUserId);
    431         }, new DevicePolicyEventWrapper.Builder(EventId.ADD_CROSS_PROFILE_INTENT_FILTER_VALUE)
    432                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    433                 .setInt(1)
    434                 .setStrings("com.android.cts.managedprofile.ACTION_TEST_ALL_ACTIVITY")
    435                 .build());
    436 
    437         // Set up filters from primary to managed profile
    438         String command = "am start -W --user " + mProfileUserId + " " + MANAGED_PROFILE_PKG
    439                 + "/.PrimaryUserFilterSetterActivity";
    440         CLog.d("Output for command " + command + ": "
    441                 + getDevice().executeShellCommand(command));
    442         runDeviceTestsAsUser(
    443                 MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".PrimaryUserTest", mParentUserId);
    444         // TODO: Test with startActivity
    445     }
    446 
    447     public void testDisallowSharingIntoProfileFromProfile() throws Exception {
    448         if (!mHasFeature) {
    449             return;
    450         }
    451         // Set up activities: PrimaryUserActivity will only be enabled in the personal user
    452         // This activity is used to find out the ground truth about the system's cross profile
    453         // intent forwarding activity.
    454         disableActivityForUser("PrimaryUserActivity", mProfileUserId);
    455 
    456         // Tests from the profile side
    457         runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    458                 ".DisallowSharingIntoProfileTest", "testSharingFromProfile", mProfileUserId);
    459     }
    460 
    461     public void testDisallowSharingIntoProfileFromPersonal() throws Exception {
    462         if (!mHasFeature) {
    463             return;
    464         }
    465         // Set up activities: ManagedProfileActivity will only be enabled in the managed profile
    466         // This activity is used to find out the ground truth about the system's cross profile
    467         // intent forwarding activity.
    468         disableActivityForUser("ManagedProfileActivity", mParentUserId);
    469 
    470         // Tests from the personal side, which is mostly driven from host side.
    471         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DisallowSharingIntoProfileTest",
    472                 "testSetUp", mProfileUserId);
    473         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DisallowSharingIntoProfileTest",
    474                 "testDisableSharingIntoProfile", mProfileUserId);
    475         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DisallowSharingIntoProfileTest",
    476                 "testSharingFromPersonalFails", mParentUserId);
    477         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DisallowSharingIntoProfileTest",
    478                 "testEnableSharingIntoProfile", mProfileUserId);
    479         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DisallowSharingIntoProfileTest",
    480                 "testSharingFromPersonalSucceeds", mParentUserId);
    481     }
    482 
    483     public void testAppLinks_verificationStatus() throws Exception {
    484         if (!mHasFeature) {
    485             return;
    486         }
    487         // Disable all pre-existing browsers in the managed profile so they don't interfere with
    488         // intents resolution.
    489         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    490                 "testDisableAllBrowsers", mProfileUserId);
    491         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    492         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    493         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    494         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    495 
    496         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "ask");
    497         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "ask");
    498         // We should have two receivers: IntentReceiverActivity and BrowserActivity in the
    499         // managed profile
    500         assertAppLinkResult("testTwoReceivers");
    501 
    502         changeUserRestrictionOrFail("allow_parent_profile_app_linking", true, mProfileUserId);
    503         // Now we should also have one receiver in the primary user, so three receivers in total.
    504         assertAppLinkResult("testThreeReceivers");
    505 
    506         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "never");
    507         // The primary user one has been set to never: we should only have the managed profile ones.
    508         assertAppLinkResult("testTwoReceivers");
    509 
    510         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "never");
    511         // Now there's only the browser in the managed profile left
    512         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    513 
    514         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "always");
    515         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "always");
    516         // We have one always in the primary user and one always in the managed profile: the managed
    517         // profile one should have precedence.
    518         assertAppLinkResult("testReceivedByAppLinkActivityInManaged");
    519     }
    520 
    521     public void testAppLinks_enabledStatus() throws Exception {
    522         if (!mHasFeature) {
    523             return;
    524         }
    525         // Disable all pre-existing browsers in the managed profile so they don't interfere with
    526         // intents resolution.
    527         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    528                 "testDisableAllBrowsers", mProfileUserId);
    529         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    530         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    531         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    532         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    533 
    534         final String APP_HANDLER_COMPONENT = "com.android.cts.intent.receiver/.AppLinkActivity";
    535 
    536         // allow_parent_profile_app_linking is not set, try different enabled state combinations.
    537         // We should not have app link handler in parent user no matter whether it is enabled.
    538 
    539         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    540         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    541         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    542 
    543         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    544         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    545         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    546 
    547         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    548         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    549         assertAppLinkResult("testTwoReceivers");
    550 
    551         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    552         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    553         assertAppLinkResult("testTwoReceivers");
    554 
    555         // We now set allow_parent_profile_app_linking, and hence we should have the app handler
    556         // in parent user if it is enabled.
    557         changeUserRestrictionOrFail("allow_parent_profile_app_linking", true, mProfileUserId);
    558 
    559         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    560         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    561         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    562 
    563         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    564         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    565         assertAppLinkResult("testTwoReceivers");
    566 
    567         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    568         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    569         assertAppLinkResult("testTwoReceivers");
    570 
    571         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    572         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    573         assertAppLinkResult("testThreeReceivers");
    574     }
    575 
    576     public void testSettingsIntents() throws Exception {
    577         if (!mHasFeature) {
    578             return;
    579         }
    580 
    581         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SettingsIntentsTest",
    582                 mProfileUserId);
    583     }
    584 
    585     public void testCrossProfileContent() throws Exception {
    586         if (!mHasFeature) {
    587             return;
    588         }
    589 
    590         // Storage permission shouldn't be granted, we check if missing permissions are respected
    591         // in ContentTest#testSecurity.
    592         installAppAsUser(INTENT_SENDER_APK, false /* grantPermissions */, mParentUserId);
    593         installAppAsUser(INTENT_SENDER_APK, false /* grantPermissions */, mProfileUserId);
    594         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    595         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    596 
    597         // Test from parent to managed
    598         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    599                 "testRemoveAllFilters", mProfileUserId);
    600         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    601                 "testAddManagedCanAccessParentFilters", mProfileUserId);
    602         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".ContentTest", mParentUserId);
    603 
    604         // Test from managed to parent
    605         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    606                 "testRemoveAllFilters", mProfileUserId);
    607         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    608                 "testAddParentCanAccessManagedFilters", mProfileUserId);
    609         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".ContentTest", mProfileUserId);
    610 
    611     }
    612 
    613     public void testCrossProfileNotificationListeners_EmptyWhitelist() throws Exception {
    614         if (!mHasFeature) {
    615             return;
    616         }
    617 
    618         installAppAsUser(NOTIFICATION_APK, mProfileUserId);
    619         installAppAsUser(NOTIFICATION_APK, mParentUserId);
    620 
    621         // Profile owner in the profile sets an empty whitelist
    622         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    623                 "testSetEmptyWhitelist", mProfileUserId,
    624                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    625         // Listener outside the profile can only see personal notifications.
    626         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    627                 "testCannotReceiveProfileNotifications", mParentUserId,
    628                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    629     }
    630 
    631     public void testCrossProfileNotificationListeners_NullWhitelist() throws Exception {
    632         if (!mHasFeature) {
    633             return;
    634         }
    635 
    636         installAppAsUser(NOTIFICATION_APK, mProfileUserId);
    637         installAppAsUser(NOTIFICATION_APK, mParentUserId);
    638 
    639         // Profile owner in the profile sets a null whitelist
    640         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    641                 "testSetNullWhitelist", mProfileUserId,
    642                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    643         // Listener outside the profile can see profile and personal notifications
    644         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    645                 "testCanReceiveNotifications", mParentUserId,
    646                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    647     }
    648 
    649     public void testCrossProfileNotificationListeners_InWhitelist() throws Exception {
    650         if (!mHasFeature) {
    651             return;
    652         }
    653 
    654         installAppAsUser(NOTIFICATION_APK, mProfileUserId);
    655         installAppAsUser(NOTIFICATION_APK, mParentUserId);
    656 
    657         // Profile owner in the profile adds listener to the whitelist
    658         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    659                 "testAddListenerToWhitelist", mProfileUserId,
    660                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    661         // Listener outside the profile can see profile and personal notifications
    662         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    663                 "testCanReceiveNotifications", mParentUserId,
    664                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    665     }
    666 
    667     public void testCrossProfileNotificationListeners_setAndGet() throws Exception {
    668         if (!mHasFeature) {
    669             return;
    670         }
    671         installAppAsUser(NOTIFICATION_APK, mProfileUserId);
    672         installAppAsUser(NOTIFICATION_APK, mParentUserId);
    673 
    674         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NotificationListenerTest",
    675                 "testSetAndGetPermittedCrossProfileNotificationListeners", mProfileUserId,
    676                 Collections.singletonMap(PARAM_PROFILE_ID, Integer.toString(mProfileUserId)));
    677     }
    678 
    679     public void testCrossProfileCopyPaste() throws Exception {
    680         if (!mHasFeature) {
    681             return;
    682         }
    683         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    684         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    685         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    686         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    687 
    688         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    689                 "testAllowCrossProfileCopyPaste", mProfileUserId);
    690         // Test that managed can see what is copied in the parent.
    691         testCrossProfileCopyPasteInternal(mProfileUserId, true);
    692         // Test that the parent can see what is copied in managed.
    693         testCrossProfileCopyPasteInternal(mParentUserId, true);
    694 
    695         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    696                 "testDisallowCrossProfileCopyPaste", mProfileUserId);
    697         // Test that managed can still see what is copied in the parent.
    698         testCrossProfileCopyPasteInternal(mProfileUserId, true);
    699         // Test that the parent cannot see what is copied in managed.
    700         testCrossProfileCopyPasteInternal(mParentUserId, false);
    701     }
    702 
    703     private void testCrossProfileCopyPasteInternal(int userId, boolean shouldSucceed)
    704             throws DeviceNotAvailableException {
    705         final String direction = (userId == mParentUserId)
    706                 ? "testAddManagedCanAccessParentFilters"
    707                 : "testAddParentCanAccessManagedFilters";
    708         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    709                 "testRemoveAllFilters", mProfileUserId);
    710         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    711                 direction, mProfileUserId);
    712         if (shouldSucceed) {
    713             runDeviceTestsAsUser(INTENT_SENDER_PKG, ".CopyPasteTest",
    714                     "testCanReadAcrossProfiles", userId);
    715         } else {
    716             runDeviceTestsAsUser(INTENT_SENDER_PKG, ".CopyPasteTest",
    717                     "testCannotReadAcrossProfiles", userId);
    718         }
    719     }
    720 
    721     /** Tests for the API helper class. */
    722     public void testCurrentApiHelper() throws Exception {
    723         if (!mHasFeature) {
    724             return;
    725         }
    726         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CurrentApiHelperTest",
    727                 mProfileUserId);
    728     }
    729 
    730     /** Test: unsupported public APIs are disabled on a parent profile. */
    731     public void testParentProfileApiDisabled() throws Exception {
    732         if (!mHasFeature) {
    733             return;
    734         }
    735         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ParentProfileTest",
    736                 "testParentProfileApiDisabled", mProfileUserId);
    737     }
    738 
    739     // TODO: This test is not specific to managed profiles, but applies to multi-user in general.
    740     // Move it to a MultiUserTest class when there is one. Should probably move
    741     // SetPolicyActivity to a more generic apk too as it might be useful for different kinds
    742     // of tests (same applies to ComponentDisablingActivity).
    743     public void testNoDebuggingFeaturesRestriction() throws Exception {
    744         if (!mHasFeature) {
    745             return;
    746         }
    747         // If adb is running as root, then the adb uid is 0 instead of SHELL_UID,
    748         // so the DISALLOW_DEBUGGING_FEATURES restriction does not work and this test
    749         // fails.
    750         if (getDevice().isAdbRoot()) {
    751             CLog.logAndDisplay(LogLevel.WARN,
    752                     "Cannot test testNoDebuggingFeaturesRestriction() in eng/userdebug build");
    753             return;
    754         }
    755         String restriction = "no_debugging_features";  // UserManager.DISALLOW_DEBUGGING_FEATURES
    756 
    757         changeUserRestrictionOrFail(restriction, true, mProfileUserId);
    758 
    759 
    760         // This should now fail, as the shell is not available to start activities under a different
    761         // user once the restriction is in place.
    762         String addRestrictionCommandOutput =
    763                 changeUserRestriction(restriction, true, mProfileUserId);
    764         assertTrue(
    765                 "Expected SecurityException when starting the activity "
    766                         + addRestrictionCommandOutput,
    767                 addRestrictionCommandOutput.contains("SecurityException"));
    768     }
    769 
    770     // Test the bluetooth API from a managed profile.
    771     public void testBluetooth() throws Exception {
    772         boolean hasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
    773         if (!mHasFeature || !hasBluetooth) {
    774             return;
    775         }
    776 
    777         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    778                 "testEnableDisable", mProfileUserId);
    779         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    780                 "testGetAddress", mProfileUserId);
    781         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    782                 "testListenUsingRfcommWithServiceRecord", mProfileUserId);
    783         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    784                 "testGetRemoteDevice", mProfileUserId);
    785     }
    786 
    787     public void testCameraPolicy() throws Exception {
    788         boolean hasCamera = hasDeviceFeature(FEATURE_CAMERA);
    789         if (!mHasFeature || !hasCamera) {
    790             return;
    791         }
    792         try {
    793             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    794                     "testDisableCameraInManagedProfile",
    795                     mProfileUserId);
    796             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    797                     "testEnableCameraInManagedProfile",
    798                     mProfileUserId);
    799         } finally {
    800             final String adminHelperClass = ".PrimaryUserAdminHelper";
    801             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    802                     adminHelperClass, "testClearDeviceAdmin", mParentUserId);
    803         }
    804     }
    805 
    806 
    807     public void testManagedContactsUris() throws Exception {
    808         runManagedContactsTest(new Callable<Void>() {
    809             @Override
    810             public Void call() throws Exception {
    811                 ContactsTestSet contactsTestSet = new ContactsTestSet(ManagedProfileTest.this,
    812                         MANAGED_PROFILE_PKG, mParentUserId, mProfileUserId);
    813 
    814                 contactsTestSet.setCallerIdEnabled(true);
    815                 contactsTestSet.setContactsSearchEnabled(true);
    816                 contactsTestSet.checkIfCanLookupEnterpriseContacts(true);
    817                 contactsTestSet.checkIfCanFilterEnterpriseContacts(true);
    818                 contactsTestSet.checkIfCanFilterSelfContacts();
    819                 return null;
    820             }
    821         });
    822     }
    823 
    824     public void testManagedQuickContacts() throws Exception {
    825         runManagedContactsTest(new Callable<Void>() {
    826             @Override
    827             public Void call() throws Exception {
    828                 runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    829                         "testQuickContact", mParentUserId);
    830                 return null;
    831             }
    832         });
    833     }
    834 
    835     public void testManagedContactsPolicies() throws Exception {
    836         runManagedContactsTest(new Callable<Void>() {
    837             @Override
    838             public Void call() throws Exception {
    839                 ContactsTestSet contactsTestSet = new ContactsTestSet(ManagedProfileTest.this,
    840                         MANAGED_PROFILE_PKG, mParentUserId, mProfileUserId);
    841                 try {
    842                     contactsTestSet.setCallerIdEnabled(true);
    843                     contactsTestSet.setContactsSearchEnabled(false);
    844                     contactsTestSet.checkIfCanLookupEnterpriseContacts(true);
    845                     contactsTestSet.checkIfCanFilterEnterpriseContacts(false);
    846                     contactsTestSet.checkIfCanFilterSelfContacts();
    847                     contactsTestSet.setCallerIdEnabled(false);
    848                     contactsTestSet.setContactsSearchEnabled(true);
    849                     contactsTestSet.checkIfCanLookupEnterpriseContacts(false);
    850                     contactsTestSet.checkIfCanFilterEnterpriseContacts(true);
    851                     contactsTestSet.checkIfCanFilterSelfContacts();
    852                     contactsTestSet.setCallerIdEnabled(false);
    853                     contactsTestSet.setContactsSearchEnabled(false);
    854                     contactsTestSet.checkIfCanLookupEnterpriseContacts(false);
    855                     contactsTestSet.checkIfCanFilterEnterpriseContacts(false);
    856                     contactsTestSet.checkIfCanFilterSelfContacts();
    857                     contactsTestSet.checkIfNoEnterpriseDirectoryFound();
    858                     assertMetricsLogged(getDevice(), () -> {
    859                         contactsTestSet.setCallerIdEnabled(true);
    860                         contactsTestSet.setCallerIdEnabled(false);
    861                     }, new DevicePolicyEventWrapper
    862                                 .Builder(EventId.SET_CROSS_PROFILE_CALLER_ID_DISABLED_VALUE)
    863                                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    864                                 .setBoolean(false)
    865                                 .build(),
    866                         new DevicePolicyEventWrapper
    867                                 .Builder(EventId.SET_CROSS_PROFILE_CALLER_ID_DISABLED_VALUE)
    868                                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    869                                 .setBoolean(true)
    870                                 .build());
    871                     assertMetricsLogged(getDevice(), () -> {
    872                         contactsTestSet.setContactsSearchEnabled(true);
    873                         contactsTestSet.setContactsSearchEnabled(false);
    874                     }, new DevicePolicyEventWrapper
    875                                 .Builder(EventId.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED_VALUE)
    876                                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    877                                 .setBoolean(false)
    878                                 .build(),
    879                         new DevicePolicyEventWrapper
    880                                 .Builder(EventId.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED_VALUE)
    881                                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    882                                 .setBoolean(true)
    883                                 .build());
    884                     return null;
    885                 } finally {
    886                     // reset policies
    887                     contactsTestSet.setCallerIdEnabled(true);
    888                     contactsTestSet.setContactsSearchEnabled(true);
    889                 }
    890             }
    891         });
    892     }
    893 
    894     public void testOrganizationInfo() throws Exception {
    895         if (!mHasFeature) {
    896             return;
    897         }
    898         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
    899                 "testDefaultOrganizationColor", mProfileUserId);
    900         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
    901                 "testDefaultOrganizationNameIsNull", mProfileUserId);
    902         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
    903                 mProfileUserId);
    904         assertMetricsLogged(getDevice(), () -> {
    905             runDeviceTestsAsUser(
    906                     MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".OrganizationInfoTest",
    907                     "testSetOrganizationColor", mProfileUserId);
    908         }, new DevicePolicyEventWrapper.Builder(EventId.SET_ORGANIZATION_COLOR_VALUE)
    909                 .setAdminPackageName(MANAGED_PROFILE_PKG)
    910                 .build());
    911     }
    912 
    913     public void testPasswordMinimumRestrictions() throws Exception {
    914         if (!mHasFeature) {
    915             return;
    916         }
    917         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PasswordMinimumRestrictionsTest",
    918                 mProfileUserId);
    919     }
    920 
    921     public void testDevicePolicyManagerParentSupport() throws Exception {
    922         if (!mHasFeature) {
    923             return;
    924         }
    925         runDeviceTestsAsUser(
    926                 MANAGED_PROFILE_PKG, ".DevicePolicyManagerParentSupportTest", mProfileUserId);
    927     }
    928 
    929     public void testBluetoothContactSharingDisabled() throws Exception {
    930         if (!mHasFeature) {
    931             return;
    932         }
    933         assertMetricsLogged(getDevice(), () -> {
    934             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    935                     "testSetBluetoothContactSharingDisabled_setterAndGetter", mProfileUserId);
    936         }, new DevicePolicyEventWrapper
    937                     .Builder(EventId.SET_BLUETOOTH_CONTACT_SHARING_DISABLED_VALUE)
    938                     .setAdminPackageName(MANAGED_PROFILE_PKG)
    939                     .setBoolean(false)
    940                     .build(),
    941             new DevicePolicyEventWrapper
    942                     .Builder(EventId.SET_BLUETOOTH_CONTACT_SHARING_DISABLED_VALUE)
    943                     .setAdminPackageName(MANAGED_PROFILE_PKG)
    944                     .setBoolean(true)
    945                     .build());
    946     }
    947 
    948     public void testCannotSetProfileOwnerAgain() throws Exception {
    949         if (!mHasFeature) {
    950             return;
    951         }
    952         // verify that we can't set the same admin receiver as profile owner again
    953         assertFalse(setProfileOwner(
    954                 MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mProfileUserId,
    955                 /*expectFailure*/ true));
    956 
    957         // verify that we can't set a different admin receiver as profile owner
    958         installAppAsUser(DEVICE_OWNER_APK, mProfileUserId);
    959         assertFalse(setProfileOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mProfileUserId,
    960                 /*expectFailure*/ true));
    961     }
    962 
    963     public void testCannotSetDeviceOwnerWhenProfilePresent() throws Exception {
    964         if (!mHasFeature) {
    965             return;
    966         }
    967 
    968         try {
    969             installAppAsUser(DEVICE_OWNER_APK, mParentUserId);
    970             assertFalse(setDeviceOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mParentUserId,
    971                     /*expectFailure*/ true));
    972         } finally {
    973             // make sure we clean up in case we succeeded in setting the device owner
    974             removeAdmin(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mParentUserId);
    975             getDevice().uninstallPackage(DEVICE_OWNER_PKG);
    976         }
    977     }
    978 
    979     public void testNfcRestriction() throws Exception {
    980         if (!mHasFeature || !mHasNfcFeature) {
    981             return;
    982         }
    983 
    984         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    985                 "testNfcShareEnabled", mProfileUserId);
    986         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    987                 "testNfcShareEnabled", mParentUserId);
    988 
    989         changeUserRestrictionOrFail("no_outgoing_beam" /* UserManager.DISALLOW_OUTGOING_BEAM */,
    990                 true, mProfileUserId);
    991 
    992         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    993                 "testNfcShareDisabled", mProfileUserId);
    994         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    995                 "testNfcShareEnabled", mParentUserId);
    996     }
    997 
    998     public void testCrossProfileWidgets() throws Exception {
    999         if (!mHasFeature) {
   1000             return;
   1001         }
   1002 
   1003         try {
   1004             installAppAsUser(WIDGET_PROVIDER_APK, mProfileUserId);
   1005             installAppAsUser(WIDGET_PROVIDER_APK, mParentUserId);
   1006             getDevice().executeShellCommand("appwidget grantbind --user " + mParentUserId
   1007                     + " --package " + WIDGET_PROVIDER_PKG);
   1008             setIdleWhitelist(WIDGET_PROVIDER_PKG, true);
   1009             startWidgetHostService();
   1010 
   1011             String commandOutput = changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG,
   1012                     "add-cross-profile-widget", mProfileUserId);
   1013             assertTrue("Command was expected to succeed " + commandOutput,
   1014                     commandOutput.contains("Status: ok"));
   1015 
   1016             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileWidgetTest",
   1017                     "testCrossProfileWidgetProviderAdded", mProfileUserId);
   1018             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
   1019                     ".CrossProfileWidgetPrimaryUserTest",
   1020                     "testHasCrossProfileWidgetProvider_true", mParentUserId);
   1021             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
   1022                     ".CrossProfileWidgetPrimaryUserTest",
   1023                     "testHostReceivesWidgetUpdates_true", mParentUserId);
   1024 
   1025             commandOutput = changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG,
   1026                     "remove-cross-profile-widget", mProfileUserId);
   1027             assertTrue("Command was expected to succeed " + commandOutput,
   1028                     commandOutput.contains("Status: ok"));
   1029 
   1030             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileWidgetTest",
   1031                     "testCrossProfileWidgetProviderRemoved", mProfileUserId);
   1032             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
   1033                     ".CrossProfileWidgetPrimaryUserTest",
   1034                     "testHasCrossProfileWidgetProvider_false", mParentUserId);
   1035             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
   1036                     ".CrossProfileWidgetPrimaryUserTest",
   1037                     "testHostReceivesWidgetUpdates_false", mParentUserId);
   1038         } finally {
   1039             changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG, "remove-cross-profile-widget",
   1040                     mProfileUserId);
   1041             getDevice().uninstallPackage(WIDGET_PROVIDER_PKG);
   1042         }
   1043     }
   1044 
   1045     public void testCrossProfileWidgetsLogged() throws Exception {
   1046         if (!mHasFeature) {
   1047             return;
   1048         }
   1049 
   1050         try {
   1051             installAppAsUser(WIDGET_PROVIDER_APK, mProfileUserId);
   1052             installAppAsUser(WIDGET_PROVIDER_APK, mParentUserId);
   1053             getDevice().executeShellCommand("appwidget grantbind --user " + mParentUserId
   1054                     + " --package " + WIDGET_PROVIDER_PKG);
   1055             setIdleWhitelist(WIDGET_PROVIDER_PKG, true);
   1056             startWidgetHostService();
   1057 
   1058             assertMetricsLogged(getDevice(), () -> {
   1059                 changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG,
   1060                         "add-cross-profile-widget", mProfileUserId);
   1061                 changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG,
   1062                         "remove-cross-profile-widget", mProfileUserId);
   1063             }, new DevicePolicyEventWrapper
   1064                         .Builder(EventId.ADD_CROSS_PROFILE_WIDGET_PROVIDER_VALUE)
   1065                         .setAdminPackageName(MANAGED_PROFILE_PKG)
   1066                         .build(),
   1067                 new DevicePolicyEventWrapper
   1068                         .Builder(EventId.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER_VALUE)
   1069                         .setAdminPackageName(MANAGED_PROFILE_PKG)
   1070                         .build());
   1071         } finally {
   1072             changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG, "remove-cross-profile-widget",
   1073                     mProfileUserId);
   1074             getDevice().uninstallPackage(WIDGET_PROVIDER_PKG);
   1075         }
   1076     }
   1077 
   1078     public void testIsProvisioningAllowed() throws DeviceNotAvailableException {
   1079         if (!mHasFeature) {
   1080             return;
   1081         }
   1082         // In Managed profile user when managed profile is provisioned
   1083         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PreManagedProfileTest",
   1084                 "testIsProvisioningAllowedFalse", mProfileUserId);
   1085 
   1086         // In parent user when managed profile is provisioned
   1087         // It's allowed to provision again by removing the previous profile
   1088         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PreManagedProfileTest",
   1089                 "testIsProvisioningAllowedTrue", mParentUserId);
   1090     }
   1091 
   1092     private void setDirectoryPrefix(String directoryName, int userId)
   1093             throws DeviceNotAvailableException {
   1094         String command = "content call --uri " + DIRECTORY_PRIVOIDER_URI
   1095                 + " --user " + userId
   1096                 + " --method " + SET_CUSTOM_DIRECTORY_PREFIX_METHOD
   1097                 + " --arg " + directoryName;
   1098         CLog.d("Output for command " + command + ": "
   1099                 + getDevice().executeShellCommand(command));
   1100     }
   1101 
   1102     public void testPhoneAccountVisibility() throws Exception {
   1103         if (!mHasFeature) {
   1104             return;
   1105         }
   1106         if (!shouldRunTelecomTest()) {
   1107             return;
   1108         }
   1109         try {
   1110             // Register phone account in parent user.
   1111             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1112                     "testRegisterPhoneAccount",
   1113                     mParentUserId);
   1114             // The phone account should not be visible in managed user.
   1115             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1116                     "testPhoneAccountNotRegistered",
   1117                     mProfileUserId);
   1118         } finally {
   1119             // Unregister the phone account.
   1120             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1121                     "testUnregisterPhoneAccount",
   1122                     mParentUserId);
   1123         }
   1124 
   1125         try {
   1126             // Register phone account in profile user.
   1127             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1128                     "testRegisterPhoneAccount",
   1129                     mProfileUserId);
   1130             // The phone account should not be visible in parent user.
   1131             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1132                     "testPhoneAccountNotRegistered",
   1133                     mParentUserId);
   1134         } finally {
   1135             // Unregister the phone account.
   1136             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1137                     "testUnregisterPhoneAccount",
   1138                     mProfileUserId);
   1139         }
   1140     }
   1141 
   1142     public void testManagedCall() throws Exception {
   1143         if (!mHasFeature) {
   1144             return;
   1145         }
   1146         if (!shouldRunTelecomTest()) {
   1147             return;
   1148         }
   1149         getDevice().executeShellCommand("telecom set-default-dialer " + MANAGED_PROFILE_PKG);
   1150 
   1151         // Place a outgoing call through work phone account using TelecomManager and verify the
   1152         // call is inserted properly.
   1153         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1154                 "testOutgoingCallUsingTelecomManager",
   1155                 mProfileUserId);
   1156         // Make sure the call is not inserted into parent user.
   1157         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1158                 "testEnsureCallNotInserted",
   1159                 mParentUserId);
   1160 
   1161         // Place a outgoing call through work phone account using ACTION_CALL and verify the call
   1162         // is inserted properly.
   1163         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1164                 "testOutgoingCallUsingActionCall",
   1165                 mProfileUserId);
   1166         // Make sure the call is not inserted into parent user.
   1167         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1168                 "testEnsureCallNotInserted",
   1169                 mParentUserId);
   1170 
   1171         // Add an incoming call with parent user's phone account and verify the call is inserted
   1172         // properly.
   1173         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1174                 "testIncomingCall",
   1175                 mProfileUserId);
   1176         // Make sure the call is not inserted into parent user.
   1177         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1178                 "testEnsureCallNotInserted",
   1179                 mParentUserId);
   1180 
   1181         // Add an incoming missed call with parent user's phone account and verify the call is
   1182         // inserted properly.
   1183         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1184                 "testIncomingMissedCall",
   1185                 mProfileUserId);
   1186         // Make sure the call is not inserted into parent user.
   1187         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
   1188                 "testEnsureCallNotInserted",
   1189                 mParentUserId);
   1190     }
   1191 
   1192     private void givePackageWriteSettingsPermission(int userId, String pkg) throws Exception {
   1193         // Allow app to write to settings (for RingtoneManager.setActualDefaultUri to work)
   1194         String command = "appops set --user " + userId + " " + pkg
   1195                 + " android:write_settings allow";
   1196         CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
   1197     }
   1198 
   1199     public void testRingtoneSync() throws Exception {
   1200         if (!mHasFeature) {
   1201             return;
   1202         }
   1203         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
   1204         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
   1205                 "testRingtoneSync", mProfileUserId);
   1206     }
   1207 
   1208     // Test if setting RINGTONE disables sync
   1209     public void testRingtoneSyncAutoDisableRingtone() throws Exception {
   1210         if (!mHasFeature) {
   1211             return;
   1212         }
   1213         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
   1214         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
   1215                 "testRingtoneDisableSync", mProfileUserId);
   1216     }
   1217 
   1218     // Test if setting NOTIFICATION disables sync
   1219     public void testRingtoneSyncAutoDisableNotification() throws Exception {
   1220         if (!mHasFeature) {
   1221             return;
   1222         }
   1223         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
   1224         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
   1225                 "testNotificationDisableSync", mProfileUserId);
   1226     }
   1227 
   1228     // Test if setting ALARM disables sync
   1229     public void testRingtoneSyncAutoDisableAlarm() throws Exception {
   1230         if (!mHasFeature) {
   1231             return;
   1232         }
   1233         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
   1234         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
   1235                 "testAlarmDisableSync", mProfileUserId);
   1236     }
   1237 
   1238     public void testTrustAgentInfo() throws Exception {
   1239         if (!mHasFeature || !mHasSecureLockScreen) {
   1240             return;
   1241         }
   1242         // Set and get trust agent config using child dpm instance.
   1243         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
   1244                 "testSetAndGetTrustAgentConfiguration_child",
   1245                 mProfileUserId);
   1246         // Set and get trust agent config using parent dpm instance.
   1247         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
   1248                 "testSetAndGetTrustAgentConfiguration_parent",
   1249                 mProfileUserId);
   1250         // Unified case
   1251         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
   1252                 "testSetTrustAgentConfiguration_bothHaveTrustAgentConfigAndUnified",
   1253                 mProfileUserId);
   1254         // Non-unified case
   1255         try {
   1256             changeUserCredential("1234", null, mProfileUserId);
   1257             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
   1258                     "testSetTrustAgentConfiguration_bothHaveTrustAgentConfigAndNonUnified",
   1259                     mProfileUserId);
   1260         } finally {
   1261             changeUserCredential(null, "1234", mProfileUserId);
   1262         }
   1263     }
   1264 
   1265     public void testSanityCheck() throws Exception {
   1266         if (!mHasFeature) {
   1267             return;
   1268         }
   1269         // Install SimpleApp in work profile only and check activity in it can be launched.
   1270         installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
   1271         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SanityTest", mProfileUserId);
   1272     }
   1273 
   1274     public void testBluetoothSharingRestriction() throws Exception {
   1275         final boolean hasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
   1276         if (!mHasFeature || !hasBluetooth) {
   1277             return;
   1278         }
   1279 
   1280         // Primary profile should be able to use bluetooth sharing.
   1281         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionPrimaryProfileTest",
   1282                 "testBluetoothSharingAvailable", mPrimaryUserId);
   1283 
   1284         // Managed profile owner should be able to control it via DISALLOW_BLUETOOTH_SHARING.
   1285         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionTest",
   1286                 "testOppDisabledWhenRestrictionSet", mProfileUserId);
   1287     }
   1288 
   1289     public void testProfileOwnerCanGetDeviceIdentifiers() throws Exception {
   1290         // The Profile Owner should have access to all device identifiers.
   1291         if (!mHasFeature) {
   1292             return;
   1293         }
   1294 
   1295         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DeviceIdentifiersTest",
   1296                 "testProfileOwnerCanGetDeviceIdentifiersWithPermission", mProfileUserId);
   1297     }
   1298 
   1299     public void testProfileOwnerCannotGetDeviceIdentifiersWithoutPermission() throws Exception {
   1300         if (!mHasFeature) {
   1301             return;
   1302         }
   1303 
   1304         // Revoke the READ_PHONE_STATE permission for the profile user ID to ensure the profile
   1305         // owner cannot access device identifiers without consent.
   1306         getDevice().executeShellCommand(
   1307                 "pm revoke --user " + mProfileUserId + " " + MANAGED_PROFILE_PKG
   1308                         + " android.permission.READ_PHONE_STATE");
   1309         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".DeviceIdentifiersTest",
   1310                 "testProfileOwnerCannotGetDeviceIdentifiersWithoutPermission", mProfileUserId);
   1311     }
   1312 
   1313     public void testResetPasswordWithTokenBeforeUnlock() throws Exception {
   1314         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
   1315             return;
   1316         }
   1317 
   1318         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
   1319                 "testSetupWorkProfile", mProfileUserId);
   1320         lockProfile();
   1321         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
   1322                 "testResetPasswordBeforeUnlock", mProfileUserId);
   1323         // Password needs to be in sync with ResetPasswordWithTokenTest.PASSWORD1
   1324         verifyUserCredential(RESET_PASSWORD_TEST_DEFAULT_PASSWORD, mProfileUserId);
   1325     }
   1326 
   1327     public void testClearPasswordWithTokenBeforeUnlock() throws Exception {
   1328         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
   1329             return;
   1330         }
   1331 
   1332         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
   1333                 "testSetupWorkProfile", mProfileUserId);
   1334         lockProfile();
   1335         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
   1336                 "testClearPasswordBeforeUnlock", mProfileUserId);
   1337         // Make sure profile has no password
   1338         verifyUserCredential("", mProfileUserId);
   1339     }
   1340 
   1341     /**
   1342      * Test password reset token is still functional after the primary user clears and
   1343      * re-adds back its device lock. This is to detect a regression where the work profile
   1344      * undergoes an untrusted credential reset (causing synthetic password to change, invalidating
   1345      * existing password reset token) if it has unified work challenge and the primary user clears
   1346      * the device lock.
   1347      */
   1348     public void testResetPasswordTokenUsableAfterClearingLock() throws Exception {
   1349         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
   1350             return;
   1351         }
   1352         final String devicePassword = "1234";
   1353 
   1354         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
   1355                 "testSetResetPasswordToken", mProfileUserId);
   1356         try {
   1357             changeUserCredential(devicePassword, null, mParentUserId);
   1358             changeUserCredential(null, devicePassword, mParentUserId);
   1359             changeUserCredential(devicePassword, null, mParentUserId);
   1360             lockProfile();
   1361             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
   1362                     "testResetPasswordBeforeUnlock", mProfileUserId);
   1363             verifyUserCredential(RESET_PASSWORD_TEST_DEFAULT_PASSWORD, mProfileUserId);
   1364         } finally {
   1365             changeUserCredential(null, devicePassword, mParentUserId);
   1366             // Cycle the device screen to flush stale password information from keyguard,
   1367             // otherwise it will still ask for the non-existent password.
   1368             // return screen to be on for cts test runs
   1369             executeShellCommand("input keyevent KEYCODE_WAKEUP");
   1370             executeShellCommand("input keyevent KEYCODE_SLEEP");
   1371             executeShellCommand("input keyevent KEYCODE_WAKEUP");
   1372         }
   1373     }
   1374 
   1375     public void testIsUsingUnifiedPassword() throws Exception {
   1376         if (!mHasFeature || !mHasSecureLockScreen) {
   1377             return;
   1378         }
   1379 
   1380         // Freshly created profile has no separate challenge.
   1381         verifyUnifiedPassword(true);
   1382 
   1383         // Set separate challenge and verify that the API reports it correctly.
   1384         changeUserCredential("1234" /* newCredential */, null /* oldCredential */, mProfileUserId);
   1385         verifyUnifiedPassword(false);
   1386     }
   1387 
   1388     public void testUnlockWorkProfile_deviceWidePassword() throws Exception {
   1389         if (!mHasFeature || !mSupportsFbe || !mHasSecureLockScreen) {
   1390             return;
   1391         }
   1392         String password = "0000";
   1393         try {
   1394             // Add a device password after the work profile has been created.
   1395             changeUserCredential(password, /* oldCredential= */ null, mPrimaryUserId);
   1396             // Lock the profile with key eviction.
   1397             lockProfile();
   1398             // Turn on work profile, by unlocking the profile with the device password.
   1399             verifyUserCredential(password, mPrimaryUserId);
   1400 
   1401             // Verify profile user is running unlocked by running a sanity test on the work profile.
   1402             installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
   1403             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SanityTest", mProfileUserId);
   1404         } finally {
   1405             // Clean up
   1406             changeUserCredential(/* newCredential= */ null, password, mPrimaryUserId);
   1407         }
   1408     }
   1409 
   1410     public void testRebootDevice_unifiedPassword() throws Exception {
   1411         if (!mHasFeature || !mHasSecureLockScreen) {
   1412             return;
   1413         }
   1414         // Waiting before rebooting prevents flakiness.
   1415         waitForBroadcastIdle();
   1416         String password = "0000";
   1417         changeUserCredential(password, /* oldCredential= */ null, mPrimaryUserId);
   1418         try {
   1419             rebootAndWaitUntilReady();
   1420             verifyUserCredential(password, mPrimaryUserId);
   1421             installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
   1422             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SanityTest", mProfileUserId);
   1423         } finally {
   1424             changeUserCredential(/* newCredential= */ null, password, mPrimaryUserId);
   1425             // Work-around for http://b/113866275 - password prompt being erroneously shown at the
   1426             // end.
   1427             pressPowerButton();
   1428         }
   1429     }
   1430 
   1431     public void testRebootDevice_separatePasswords() throws Exception {
   1432         if (!mHasFeature || !mHasSecureLockScreen) {
   1433             return;
   1434         }
   1435         // Waiting before rebooting prevents flakiness.
   1436         waitForBroadcastIdle();
   1437         String profilePassword = "profile";
   1438         String primaryPassword = "primary";
   1439         int managedProfileUserId = getFirstManagedProfileUserId();
   1440         changeUserCredential(
   1441                 profilePassword, /* oldCredential= */ null, managedProfileUserId);
   1442         changeUserCredential(primaryPassword, /* oldCredential= */ null, mPrimaryUserId);
   1443         try {
   1444             rebootAndWaitUntilReady();
   1445             verifyUserCredential(profilePassword, managedProfileUserId);
   1446             verifyUserCredential(primaryPassword, mPrimaryUserId);
   1447             installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
   1448             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SanityTest", mProfileUserId);
   1449         } finally {
   1450             changeUserCredential(
   1451                     /* newCredential= */ null, profilePassword, managedProfileUserId);
   1452             changeUserCredential(/* newCredential= */ null, primaryPassword, mPrimaryUserId);
   1453             // Work-around for http://b/113866275 - password prompt being erroneously shown at the
   1454             // end.
   1455             pressPowerButton();
   1456         }
   1457     }
   1458 
   1459     public void testCrossProfileCalendarPackage() throws Exception {
   1460         if (!mHasFeature) {
   1461             return;
   1462         }
   1463         assertMetricsLogged(getDevice(), () -> {
   1464             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1465                     "testCrossProfileCalendarPackage", mProfileUserId);
   1466         }, new DevicePolicyEventWrapper.Builder(EventId.SET_CROSS_PROFILE_CALENDAR_PACKAGES_VALUE)
   1467                     .setAdminPackageName(MANAGED_PROFILE_PKG)
   1468                     .setStrings(MANAGED_PROFILE_PKG)
   1469                     .build());
   1470     }
   1471 
   1472     public void testCrossProfileCalendar() throws Exception {
   1473         if (!mHasFeature) {
   1474             return;
   1475         }
   1476         runCrossProfileCalendarTestsWhenWhitelistedAndEnabled();
   1477         runCrossProfileCalendarTestsWhenAllPackagesWhitelisted();
   1478         runCrossProfileCalendarTestsWhenDisabled();
   1479         runCrossProfileCalendarTestsWhenNotWhitelisted();
   1480     }
   1481 
   1482     private void runCrossProfileCalendarTestsWhenWhitelistedAndEnabled() throws Exception {
   1483         try {
   1484             // Setup. Add the test package into cross-profile calendar whitelist, enable
   1485             // cross-profile calendar in settings, and insert test data into calendar provider.
   1486             // All setups should be done in managed profile.
   1487             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1488                     "testWhitelistManagedProfilePackage", mProfileUserId);
   1489             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1490                     "testAddTestCalendarDataForWorkProfile", mProfileUserId);
   1491             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1492                     "testEnableCrossProfileCalendarSettings", mProfileUserId);
   1493 
   1494             // Testing.
   1495             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1496                     "testPrimaryProfile_getCorrectWorkCalendarsWhenEnabled", mParentUserId);
   1497             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1498                     "testPrimaryProfile_getCorrectWorkEventsWhenEnabled", mParentUserId);
   1499             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1500                     "testPrimaryProfile_getCorrectWorkInstancesWhenEnabled", mParentUserId);
   1501             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1502                     "testPrimaryProfile_getCorrectWorkInstancesByDayWhenEnabled", mParentUserId);
   1503             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1504                     "testPrimaryProfile_canAccessWorkInstancesSearch1", mParentUserId);
   1505             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1506                     "testPrimaryProfile_canAccessWorkInstancesSearch2", mParentUserId);
   1507             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1508                     "testPrimaryProfile_canAccessWorkInstancesSearchByDay", mParentUserId);
   1509             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1510                     "testPrimaryProfile_getExceptionWhenQueryNonWhitelistedColumns", mParentUserId);
   1511             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1512                     "testViewEventCrossProfile_intentReceivedWhenWhitelisted", mParentUserId);
   1513         } finally {
   1514             // Cleanup.
   1515             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1516                     "testCleanupWhitelist", mProfileUserId);
   1517             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1518                     "testCleanupTestCalendarDataForWorkProfile", mProfileUserId);
   1519             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1520                     "testDisableCrossProfileCalendarSettings", mProfileUserId);
   1521         }
   1522     }
   1523 
   1524     private void runCrossProfileCalendarTestsWhenAllPackagesWhitelisted() throws Exception {
   1525         try {
   1526             // Setup. Allow all packages to access cross-profile calendar APIs by setting
   1527             // the whitelist to null, enable cross-profile calendar in settings,
   1528             // and insert test data into calendar provider.
   1529             // All setups should be done in managed profile.
   1530             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1531                     "testWhitelistAllPackages", mProfileUserId);
   1532             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1533                     "testAddTestCalendarDataForWorkProfile", mProfileUserId);
   1534             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1535                     "testEnableCrossProfileCalendarSettings", mProfileUserId);
   1536 
   1537             // Testing.
   1538             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1539                     "testPrimaryProfile_getCorrectWorkCalendarsWhenEnabled", mParentUserId);
   1540             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1541                     "testPrimaryProfile_getCorrectWorkEventsWhenEnabled", mParentUserId);
   1542             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1543                     "testPrimaryProfile_getCorrectWorkInstancesWhenEnabled", mParentUserId);
   1544             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1545                     "testPrimaryProfile_getCorrectWorkInstancesByDayWhenEnabled", mParentUserId);
   1546             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1547                     "testPrimaryProfile_canAccessWorkInstancesSearch1", mParentUserId);
   1548             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1549                     "testPrimaryProfile_canAccessWorkInstancesSearch2", mParentUserId);
   1550             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1551                     "testPrimaryProfile_canAccessWorkInstancesSearchByDay", mParentUserId);
   1552             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1553                     "testPrimaryProfile_getExceptionWhenQueryNonWhitelistedColumns", mParentUserId);
   1554             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1555                     "testViewEventCrossProfile_intentReceivedWhenWhitelisted", mParentUserId);
   1556         } finally {
   1557             // Cleanup.
   1558             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1559                     "testCleanupWhitelist", mProfileUserId);
   1560             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1561                     "testCleanupTestCalendarDataForWorkProfile", mProfileUserId);
   1562             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1563                     "testDisableCrossProfileCalendarSettings", mProfileUserId);
   1564         }
   1565     }
   1566 
   1567     private void runCrossProfileCalendarTestsWhenDisabled() throws Exception {
   1568         try {
   1569             // Setup. Add the test package into cross-profile calendar whitelist,
   1570             // and insert test data into calendar provider. But disable cross-profile calendar
   1571             // in settings. Thus cross-profile calendar Uris should not be accessible.
   1572             // All setups should be done in managed profile.
   1573             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1574                     "testWhitelistManagedProfilePackage", mProfileUserId);
   1575             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1576                     "testAddTestCalendarDataForWorkProfile", mProfileUserId);
   1577             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1578                     "testDisableCrossProfileCalendarSettings", mProfileUserId);
   1579 
   1580             // Testing.
   1581             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1582                     "testPrimaryProfile_cannotAccessWorkCalendarsWhenDisabled", mParentUserId);
   1583             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1584                     "testPrimaryProfile_cannotAccessWorkEventsWhenDisabled", mParentUserId);
   1585             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1586                     "testPrimaryProfile_cannotAccessWorkInstancesWhenDisabled", mParentUserId);
   1587         } finally {
   1588             // Cleanup.
   1589             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1590                     "testCleanupWhitelist", mProfileUserId);
   1591             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1592                     "testCleanupTestCalendarDataForWorkProfile", mProfileUserId);
   1593         }
   1594     }
   1595 
   1596     private void runCrossProfileCalendarTestsWhenNotWhitelisted() throws Exception {
   1597         try {
   1598             // Setup. Enable cross-profile calendar in settings and insert test data into calendar
   1599             // provider. But make sure that the test package is not whitelisted for cross-profile
   1600             // calendar. Thus cross-profile calendar Uris should not be accessible.
   1601             // All setups should be done in managed profile.
   1602             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1603                     "testAddTestCalendarDataForWorkProfile", mProfileUserId);
   1604             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1605                     "testEnableCrossProfileCalendarSettings", mProfileUserId);
   1606 
   1607             // Testing.
   1608             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1609                     "testPrimaryProfile_cannotAccessWorkCalendarsWhenDisabled", mParentUserId);
   1610             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1611                     "testPrimaryProfile_cannotAccessWorkEventsWhenDisabled", mParentUserId);
   1612             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1613                     "testPrimaryProfile_cannotAccessWorkInstancesWhenDisabled", mParentUserId);
   1614             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1615                     "testViewEventCrossProfile_intentFailedWhenNotWhitelisted", mParentUserId);
   1616         } finally {
   1617             // Cleanup.
   1618             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1619                     "testCleanupTestCalendarDataForWorkProfile", mProfileUserId);
   1620             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileCalendarTest",
   1621                     "testDisableCrossProfileCalendarSettings", mProfileUserId);
   1622         }
   1623     }
   1624 
   1625     public void testCreateSeparateChallengeChangedLogged() throws Exception {
   1626         if (!mHasFeature || !mHasSecureLockScreen) {
   1627             return;
   1628         }
   1629         assertMetricsLogged(getDevice(), () -> {
   1630             changeUserCredential(
   1631                     "1234" /* newCredential */, null /* oldCredential */, mProfileUserId);
   1632         }, new DevicePolicyEventWrapper.Builder(EventId.SEPARATE_PROFILE_CHALLENGE_CHANGED_VALUE)
   1633                 .setBoolean(true)
   1634                 .build());
   1635     }
   1636 
   1637     public void testSetProfileNameLogged() throws Exception {
   1638         if (!mHasFeature) {
   1639             return;
   1640         }
   1641         assertMetricsLogged(getDevice(), () -> {
   1642             runDeviceTestsAsUser(
   1643                     MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".DevicePolicyLoggingTest",
   1644                     "testSetProfileNameLogged", mProfileUserId);
   1645         }, new DevicePolicyEventWrapper.Builder(EventId.SET_PROFILE_NAME_VALUE)
   1646                 .setAdminPackageName(MANAGED_PROFILE_PKG)
   1647                 .build());
   1648     }
   1649 
   1650     private void verifyUnifiedPassword(boolean unified) throws DeviceNotAvailableException {
   1651         final String testMethod =
   1652                 unified ? "testUsingUnifiedPassword" : "testNotUsingUnifiedPassword";
   1653         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".IsUsingUnifiedPasswordTest",
   1654                 testMethod, mProfileUserId);
   1655     }
   1656 
   1657     private void disableActivityForUser(String activityName, int userId)
   1658             throws DeviceNotAvailableException {
   1659         String command = "am start -W --user " + userId
   1660                 + " --es extra-package " + MANAGED_PROFILE_PKG
   1661                 + " --es extra-class-name " + MANAGED_PROFILE_PKG + "." + activityName
   1662                 + " " + MANAGED_PROFILE_PKG + "/.ComponentDisablingActivity ";
   1663         CLog.d("Output for command " + command + ": "
   1664                 + getDevice().executeShellCommand(command));
   1665     }
   1666 
   1667     private void changeUserRestrictionOrFail(String key, boolean value, int userId)
   1668             throws DeviceNotAvailableException {
   1669         changeUserRestrictionOrFail(key, value, userId, MANAGED_PROFILE_PKG);
   1670     }
   1671 
   1672     private String changeUserRestriction(String key, boolean value, int userId)
   1673             throws DeviceNotAvailableException {
   1674         return changeUserRestriction(key, value, userId, MANAGED_PROFILE_PKG);
   1675     }
   1676 
   1677     private void setIdleWhitelist(String packageName, boolean enabled)
   1678             throws DeviceNotAvailableException {
   1679         String command = "cmd deviceidle whitelist " + (enabled ? "+" : "-") + packageName;
   1680         CLog.d("Output for command " + command + ": "
   1681                 + getDevice().executeShellCommand(command));
   1682     }
   1683 
   1684     private String changeCrossProfileWidgetForUser(String packageName, String command, int userId)
   1685             throws DeviceNotAvailableException {
   1686         String adbCommand = "am start -W --user " + userId
   1687                 + " -c android.intent.category.DEFAULT "
   1688                 + " --es extra-command " + command
   1689                 + " --es extra-package-name " + packageName
   1690                 + " " + MANAGED_PROFILE_PKG + "/.SetPolicyActivity";
   1691         String commandOutput = getDevice().executeShellCommand(adbCommand);
   1692         CLog.d("Output for command " + adbCommand + ": " + commandOutput);
   1693         return commandOutput;
   1694     }
   1695 
   1696     // status should be one of never, undefined, ask, always
   1697     private void changeVerificationStatus(int userId, String packageName, String status)
   1698             throws DeviceNotAvailableException {
   1699         String command = "pm set-app-link --user " + userId + " " + packageName + " " + status;
   1700         CLog.d("Output for command " + command + ": "
   1701                 + getDevice().executeShellCommand(command));
   1702     }
   1703 
   1704     protected void startWidgetHostService() throws Exception {
   1705         String command = "am startservice --user " + mParentUserId
   1706                 + " -a " + WIDGET_PROVIDER_PKG + ".REGISTER_CALLBACK "
   1707                 + "--ei user-extra " + getUserSerialNumber(mProfileUserId)
   1708                 + " " + WIDGET_PROVIDER_PKG + "/.SimpleAppWidgetHostService";
   1709         CLog.d("Output for command " + command + ": "
   1710                 + getDevice().executeShellCommand(command));
   1711     }
   1712 
   1713     private void assertAppLinkResult(String methodName) throws DeviceNotAvailableException {
   1714         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".AppLinkTest", methodName,
   1715                 mProfileUserId);
   1716     }
   1717 
   1718     private boolean shouldRunTelecomTest() throws DeviceNotAvailableException {
   1719         return hasDeviceFeature(FEATURE_TELEPHONY) && hasDeviceFeature(FEATURE_CONNECTION_SERVICE);
   1720     }
   1721 
   1722     private void runManagedContactsTest(Callable<Void> callable) throws Exception {
   1723         if (!mHasFeature) {
   1724             return;
   1725         }
   1726 
   1727         try {
   1728             // Allow cross profile contacts search.
   1729             // TODO test both on and off.
   1730             getDevice().executeShellCommand(
   1731                     "settings put --user " + mProfileUserId
   1732                     + " secure managed_profile_contact_remote_search 1");
   1733 
   1734             // Add test account
   1735             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1736                     "testAddTestAccount", mParentUserId);
   1737             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1738                     "testAddTestAccount", mProfileUserId);
   1739 
   1740             // Install directory provider to both primary and managed profile
   1741             installAppAsUser(DIRECTORY_PROVIDER_APK, mProfileUserId);
   1742             installAppAsUser(DIRECTORY_PROVIDER_APK, mParentUserId);
   1743             setDirectoryPrefix(PRIMARY_DIRECTORY_PREFIX, mParentUserId);
   1744             setDirectoryPrefix(MANAGED_DIRECTORY_PREFIX, mProfileUserId);
   1745 
   1746             // Check enterprise directory API works
   1747             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1748                     "testGetDirectoryListInPrimaryProfile", mParentUserId);
   1749 
   1750             // Insert Primary profile Contacts
   1751             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1752                     "testPrimaryProfilePhoneAndEmailLookup_insertedAndfound", mParentUserId);
   1753             // Insert Managed profile Contacts
   1754             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1755                     "testManagedProfilePhoneAndEmailLookup_insertedAndfound", mProfileUserId);
   1756             // Insert a primary contact with same phone & email as other
   1757             // enterprise contacts
   1758             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1759                     "testPrimaryProfileDuplicatedPhoneEmailContact_insertedAndfound",
   1760                     mParentUserId);
   1761             // Insert a enterprise contact with same phone & email as other
   1762             // primary contacts
   1763             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1764                     "testManagedProfileDuplicatedPhoneEmailContact_insertedAndfound",
   1765                     mProfileUserId);
   1766 
   1767             callable.call();
   1768 
   1769         } finally {
   1770             // Clean up in managed profile and primary profile
   1771             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1772                     "testCurrentProfileContacts_removeContacts", mProfileUserId);
   1773             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1774                     "testCurrentProfileContacts_removeContacts", mParentUserId);
   1775             getDevice().uninstallPackage(DIRECTORY_PROVIDER_PKG);
   1776         }
   1777     }
   1778 
   1779 
   1780     /*
   1781      * Container for running ContactsTest under multi-user environment
   1782      */
   1783     private static class ContactsTestSet {
   1784 
   1785         private ManagedProfileTest mManagedProfileTest;
   1786         private String mManagedProfilePackage;
   1787         private int mParentUserId;
   1788         private int mProfileUserId;
   1789 
   1790         public ContactsTestSet(ManagedProfileTest managedProfileTest, String managedProfilePackage,
   1791                 int parentUserId, int profileUserId) {
   1792             mManagedProfileTest = managedProfileTest;
   1793             mManagedProfilePackage = managedProfilePackage;
   1794             mParentUserId = parentUserId;
   1795             mProfileUserId = profileUserId;
   1796         }
   1797 
   1798         private void runDeviceTestsAsUser(String pkgName, String testClassName,
   1799                 String testMethodName, Integer userId) throws DeviceNotAvailableException {
   1800             mManagedProfileTest.runDeviceTestsAsUser(pkgName, testClassName, testMethodName,
   1801                     userId);
   1802         }
   1803 
   1804         // Enable / Disable
   1805         public void setCallerIdEnabled(boolean enabled) throws DeviceNotAvailableException {
   1806             if (enabled) {
   1807                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1808                         "testSetCrossProfileCallerIdDisabled_false", mProfileUserId);
   1809             } else {
   1810                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1811                         "testSetCrossProfileCallerIdDisabled_true", mProfileUserId);
   1812             }
   1813         }
   1814 
   1815         // Enable / Disable cross profile contacts search
   1816         public void setContactsSearchEnabled(boolean enabled) throws DeviceNotAvailableException {
   1817             if (enabled) {
   1818                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1819                         "testSetCrossProfileContactsSearchDisabled_false", mProfileUserId);
   1820             } else {
   1821                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1822                         "testSetCrossProfileContactsSearchDisabled_true", mProfileUserId);
   1823             }
   1824         }
   1825 
   1826         public void checkIfCanLookupEnterpriseContacts(boolean expected)
   1827                 throws DeviceNotAvailableException {
   1828             // Primary user cannot use ordinary phone/email lookup api to access
   1829             // managed contacts
   1830             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1831                     "testPrimaryProfilePhoneLookup_canNotAccessEnterpriseContact", mParentUserId);
   1832             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1833                     "testPrimaryProfileEmailLookup_canNotAccessEnterpriseContact", mParentUserId);
   1834             // Primary user can use ENTERPRISE_CONTENT_FILTER_URI to access
   1835             // primary contacts
   1836             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1837                     "testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryContact",
   1838                     mParentUserId);
   1839             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1840                     "testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryContact",
   1841                     mParentUserId);
   1842             // When there exist contacts with the same phone/email in primary &
   1843             // enterprise,
   1844             // primary user can use ENTERPRISE_CONTENT_FILTER_URI to access the
   1845             // primary contact.
   1846             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1847                     "testPrimaryProfileEnterpriseEmailLookupDuplicated_canAccessPrimaryContact",
   1848                     mParentUserId);
   1849             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1850                     "testPrimaryProfileEnterprisePhoneLookupDuplicated_canAccessPrimaryContact",
   1851                     mParentUserId);
   1852 
   1853             // Managed user cannot use ordinary phone/email lookup api to access
   1854             // primary contacts
   1855             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1856                     "testManagedProfilePhoneLookup_canNotAccessPrimaryContact", mProfileUserId);
   1857             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1858                     "testManagedProfileEmailLookup_canNotAccessPrimaryContact", mProfileUserId);
   1859             // Managed user can use ENTERPRISE_CONTENT_FILTER_URI to access
   1860             // enterprise contacts
   1861             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1862                     "testManagedProfileEnterprisePhoneLookup_canAccessEnterpriseContact",
   1863                     mProfileUserId);
   1864             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1865                     "testManagedProfileEnterpriseEmailLookup_canAccessEnterpriseContact",
   1866                     mProfileUserId);
   1867             // Managed user cannot use ENTERPRISE_CONTENT_FILTER_URI to access
   1868             // primary contacts
   1869             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1870                     "testManagedProfileEnterprisePhoneLookup_canNotAccessPrimaryContact",
   1871                     mProfileUserId);
   1872             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1873                     "testManagedProfileEnterpriseEmailLookup_canNotAccessPrimaryContact",
   1874                     mProfileUserId);
   1875             // When there exist contacts with the same phone/email in primary &
   1876             // enterprise,
   1877             // managed user can use ENTERPRISE_CONTENT_FILTER_URI to access the
   1878             // enterprise contact.
   1879             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1880                     "testManagedProfileEnterpriseEmailLookupDuplicated_canAccessEnterpriseContact",
   1881                     mProfileUserId);
   1882             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1883                     "testManagedProfileEnterprisePhoneLookupDuplicated_canAccessEnterpriseContact",
   1884                     mProfileUserId);
   1885 
   1886             // Check if phone lookup can access primary directories
   1887             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1888                     "testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryDirectories",
   1889                     mParentUserId);
   1890 
   1891             // Check if email lookup can access primary directories
   1892             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1893                     "testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryDirectories",
   1894                     mParentUserId);
   1895 
   1896             if (expected) {
   1897                 // Primary user can use ENTERPRISE_CONTENT_FILTER_URI to access
   1898                 // managed profile contacts
   1899                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1900                         "testPrimaryProfileEnterprisePhoneLookup_canAccessEnterpriseContact",
   1901                         mParentUserId);
   1902                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1903                         "testPrimaryProfileEnterpriseEmailLookup_canAccessEnterpriseContact",
   1904                         mParentUserId);
   1905 
   1906                 // Make sure SIP enterprise lookup works too.
   1907                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1908                         "testPrimaryProfileEnterpriseSipLookup_canAccessEnterpriseContact",
   1909                         mParentUserId);
   1910 
   1911                 // Check if phone lookup can access enterprise directories
   1912                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1913                         "testPrimaryProfileEnterprisePhoneLookup_canAccessManagedDirectories",
   1914                         mParentUserId);
   1915 
   1916                 // Check if email lookup can access enterprise directories
   1917                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1918                         "testPrimaryProfileEnterpriseEmailLookup_canAccessManagedDirectories",
   1919                         mParentUserId);
   1920             } else {
   1921                 // Primary user cannot use ENTERPRISE_CONTENT_FILTER_URI to
   1922                 // access managed contacts
   1923                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1924                         "testPrimaryProfileEnterprisePhoneLookup_canNotAccessEnterpriseContact",
   1925                         mParentUserId);
   1926                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1927                         "testPrimaryProfileEnterprisePhoneLookup_canNotAccessManagedDirectories",
   1928                         mParentUserId);
   1929 
   1930                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1931                         "testPrimaryProfileEnterpriseEmailLookup_canNotAccessManagedDirectories",
   1932                         mParentUserId);
   1933                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1934                         "testPrimaryProfileEnterprisePhoneLookup_canNotAccessManagedDirectories",
   1935                         mParentUserId);
   1936             }
   1937         }
   1938 
   1939         public void checkIfCanFilterSelfContacts() throws DeviceNotAvailableException {
   1940             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1941                     "testPrimaryProfileEnterpriseCallableFilter_canAccessPrimaryDirectories",
   1942                     mParentUserId);
   1943             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1944                     "testManagedProfileEnterpriseCallableFilter_canAccessManagedDirectories",
   1945                     mProfileUserId);
   1946 
   1947             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1948                     "testPrimaryProfileEnterpriseEmailFilter_canAccessPrimaryDirectories",
   1949                     mParentUserId);
   1950             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1951                     "testEnterpriseProfileEnterpriseEmailFilter_canAccessManagedDirectories",
   1952                     mProfileUserId);
   1953 
   1954             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1955                     "testPrimaryProfileEnterpriseContactFilter_canAccessPrimaryDirectories",
   1956                     mParentUserId);
   1957             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1958                     "testManagedProfileEnterpriseContactFilter_canAccessManagedDirectories",
   1959                     mProfileUserId);
   1960 
   1961             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1962                     "testPrimaryProfileEnterprisePhoneFilter_canAccessPrimaryDirectories",
   1963                     mParentUserId);
   1964             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1965                     "testManagedProfileEnterprisePhoneFilter_canAccessManagedDirectories",
   1966                     mProfileUserId);
   1967         }
   1968 
   1969         public void checkIfCanFilterEnterpriseContacts(boolean expected)
   1970                 throws DeviceNotAvailableException {
   1971             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1972                     "testFilterUriWhenDirectoryParamMissing", mParentUserId);
   1973             if (expected) {
   1974                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1975                         "testPrimaryProfileEnterpriseCallableFilter_canAccessManagedDirectories",
   1976                         mParentUserId);
   1977                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1978                         "testPrimaryProfileEnterpriseEmailFilter_canAccessManagedDirectories",
   1979                         mParentUserId);
   1980                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1981                         "testPrimaryProfileEnterpriseContactFilter_canAccessManagedDirectories",
   1982                         mParentUserId);
   1983                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1984                         "testPrimaryProfileEnterprisePhoneFilter_canAccessManagedDirectories",
   1985                         mParentUserId);
   1986             } else {
   1987                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1988                         "testPrimaryProfileEnterpriseCallableFilter_canNotAccessManagedDirectories",
   1989                         mParentUserId);
   1990                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1991                         "testPrimaryProfileEnterpriseEmailFilter_canNotAccessManagedDirectories",
   1992                         mParentUserId);
   1993                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1994                         "testPrimaryProfileEnterpriseContactFilter_canNotAccessManagedDirectories",
   1995                         mParentUserId);
   1996                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1997                         "testPrimaryProfileEnterprisePhoneFilter_canNotAccessManagedDirectories",
   1998                         mParentUserId);
   1999             }
   2000         }
   2001 
   2002         public void checkIfNoEnterpriseDirectoryFound() throws DeviceNotAvailableException {
   2003             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   2004                     "testPrimaryProfileEnterpriseDirectories_canNotAccessManagedDirectories",
   2005                     mParentUserId);
   2006         }
   2007     }
   2008 }
   2009