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