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.concurrent.Callable;
     26 import java.util.concurrent.TimeUnit;
     27 import java.util.regex.Matcher;
     28 import java.util.regex.Pattern;
     29 
     30 /**
     31  * Set of tests for Managed Profile use cases.
     32  */
     33 public class ManagedProfileTest extends BaseDevicePolicyTest {
     34 
     35     private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile";
     36     private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk";
     37 
     38     private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner";
     39     private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk";
     40     private static final String DEVICE_OWNER_ADMIN =
     41             DEVICE_OWNER_PKG + ".BaseDeviceOwnerTest$BasicAdminReceiver";
     42 
     43     private static final String INTENT_SENDER_PKG = "com.android.cts.intent.sender";
     44     private static final String INTENT_SENDER_APK = "CtsIntentSenderApp.apk";
     45 
     46     private static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver";
     47     private static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk";
     48 
     49     private static final String WIFI_CONFIG_CREATOR_PKG = "com.android.cts.wificonfigcreator";
     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 ADMIN_RECEIVER_TEST_CLASS =
     65             MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver";
     66 
     67     private static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
     68     private static final String FEATURE_CAMERA = "android.hardware.camera";
     69     private static final String FEATURE_WIFI = "android.hardware.wifi";
     70     private static final String FEATURE_TELEPHONY = "android.hardware.telephony";
     71     private static final String FEATURE_CONNECTION_SERVICE = "android.software.connectionservice";
     72 
     73     private static final String SIMPLE_APP_APK = "CtsSimpleApp.apk";
     74     private static final String SIMPLE_APP_PKG = "com.android.cts.launcherapps.simpleapp";
     75 
     76     private static final long TIMEOUT_USER_LOCKED_MILLIS = TimeUnit.SECONDS.toMillis(15);
     77 
     78     private int mParentUserId;
     79 
     80     // ID of the profile we'll create. This will always be a profile of the parent.
     81     private int mProfileUserId;
     82     private String mPackageVerifier;
     83 
     84     private boolean mHasNfcFeature;
     85 
     86     @Override
     87     protected void setUp() throws Exception {
     88         super.setUp();
     89 
     90         // We need multi user to be supported in order to create a profile of the user owner.
     91         mHasFeature = mHasFeature && hasDeviceFeature(
     92                 "android.software.managed_users");
     93         mHasNfcFeature = hasDeviceFeature("android.hardware.nfc");
     94 
     95         if (mHasFeature) {
     96             removeTestUsers();
     97             mParentUserId = mPrimaryUserId;
     98             mProfileUserId = createManagedProfile(mParentUserId);
     99 
    100             installAppAsUser(MANAGED_PROFILE_APK, mParentUserId);
    101             installAppAsUser(MANAGED_PROFILE_APK, mProfileUserId);
    102             setProfileOwnerOrFail(MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS,
    103                     mProfileUserId);
    104             startUser(mProfileUserId);
    105         }
    106     }
    107 
    108     @Override
    109     protected void tearDown() throws Exception {
    110         if (mHasFeature) {
    111             removeUser(mProfileUserId);
    112             getDevice().uninstallPackage(MANAGED_PROFILE_PKG);
    113             getDevice().uninstallPackage(INTENT_SENDER_PKG);
    114             getDevice().uninstallPackage(INTENT_RECEIVER_PKG);
    115         }
    116         super.tearDown();
    117     }
    118 
    119     public void testManagedProfileSetup() throws Exception {
    120         if (!mHasFeature) {
    121             return;
    122         }
    123         runDeviceTestsAsUser(
    124                 MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".ManagedProfileSetupTest",
    125                 mProfileUserId);
    126     }
    127 
    128     /**
    129      *  wipeData() test removes the managed profile, so it needs to separated from other tests.
    130      */
    131     public void testWipeData() throws Exception {
    132         if (!mHasFeature) {
    133             return;
    134         }
    135         assertTrue(listUsers().contains(mProfileUserId));
    136         runDeviceTestsAsUser(
    137                 MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".WipeDataTest", mProfileUserId);
    138         // Note: the managed profile is removed by this test, which will make removeUserCommand in
    139         // tearDown() to complain, but that should be OK since its result is not asserted.
    140         assertUserGetsRemoved(mProfileUserId);
    141     }
    142 
    143     public void testLockNowWithKeyEviction() throws Exception {
    144         if (!mHasFeature || !mSupportsFbe) {
    145             return;
    146         }
    147         changeUserCredential("1234", null, mProfileUserId);
    148         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".LockNowTest",
    149                 "testLockNowWithKeyEviction", mProfileUserId);
    150         final String cmd = "dumpsys activity | grep 'User #" + mProfileUserId + ": state='";
    151         final Pattern p = Pattern.compile("state=([\\p{Upper}_]+)$");
    152         SuccessCondition userLocked = () -> {
    153             final String activityDump = getDevice().executeShellCommand(cmd);
    154             final Matcher m = p.matcher(activityDump);
    155             return m.find() && m.group(1).equals("RUNNING_LOCKED");
    156         };
    157         tryWaitForSuccess(
    158                 userLocked,
    159                 "The managed profile has not been locked after calling "
    160                         + "lockNow(FLAG_SECURE_USER_DATA)",
    161                 TIMEOUT_USER_LOCKED_MILLIS);
    162     }
    163 
    164     public void testMaxOneManagedProfile() throws Exception {
    165         int newUserId = -1;
    166         try {
    167             newUserId = createManagedProfile(mParentUserId);
    168         } catch (AssertionFailedError expected) {
    169         }
    170         if (newUserId > 0) {
    171             removeUser(newUserId);
    172             fail(mHasFeature ? "Device must allow creating only one managed profile"
    173                     : "Device must not allow creating a managed profile");
    174         }
    175     }
    176 
    177     /**
    178      * Verify that removing a managed profile will remove all networks owned by that profile.
    179      */
    180     public void testProfileWifiCleanup() throws Exception {
    181         if (!mHasFeature || !hasDeviceFeature(FEATURE_WIFI)) {
    182             return;
    183         }
    184         installAppAsUser(WIFI_CONFIG_CREATOR_APK, mProfileUserId);
    185 
    186         runDeviceTestsAsUser(
    187                 MANAGED_PROFILE_PKG, ".WifiTest", "testRemoveWifiNetworkIfExists", mParentUserId);
    188 
    189         runDeviceTestsAsUser(
    190                 MANAGED_PROFILE_PKG, ".WifiTest", "testAddWifiNetwork", mProfileUserId);
    191 
    192         // Now delete the user - should undo the effect of testAddWifiNetwork.
    193         removeUser(mProfileUserId);
    194         runDeviceTestsAsUser(
    195                 MANAGED_PROFILE_PKG, ".WifiTest", "testWifiNetworkDoesNotExist",
    196                 mParentUserId);
    197     }
    198 
    199     public void testWifiMacAddress() throws Exception {
    200         if (!mHasFeature || !hasDeviceFeature(FEATURE_WIFI)) {
    201             return;
    202         }
    203         runDeviceTestsAsUser(
    204                 MANAGED_PROFILE_PKG, ".WifiTest", "testCannotGetWifiMacAddress", mProfileUserId);
    205     }
    206 
    207     public void testCrossProfileIntentFilters() throws Exception {
    208         if (!mHasFeature) {
    209             return;
    210         }
    211         // Set up activities: ManagedProfileActivity will only be enabled in the managed profile and
    212         // PrimaryUserActivity only in the primary one
    213         disableActivityForUser("ManagedProfileActivity", mParentUserId);
    214         disableActivityForUser("PrimaryUserActivity", mProfileUserId);
    215 
    216         runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    217                 MANAGED_PROFILE_PKG + ".ManagedProfileTest", mProfileUserId);
    218 
    219         // Set up filters from primary to managed profile
    220         String command = "am start -W --user " + mProfileUserId  + " " + MANAGED_PROFILE_PKG
    221                 + "/.PrimaryUserFilterSetterActivity";
    222         CLog.d("Output for command " + command + ": "
    223               + getDevice().executeShellCommand(command));
    224         runDeviceTestsAsUser(
    225                 MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".PrimaryUserTest", mParentUserId);
    226         // TODO: Test with startActivity
    227     }
    228 
    229     public void testAppLinks_verificationStatus() throws Exception {
    230         if (!mHasFeature) {
    231             return;
    232         }
    233         // Disable all pre-existing browsers in the managed profile so they don't interfere with
    234         // intents resolution.
    235         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    236                 "testDisableAllBrowsers", mProfileUserId);
    237         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    238         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    239         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    240         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    241 
    242         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "ask");
    243         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "ask");
    244         // We should have two receivers: IntentReceiverActivity and BrowserActivity in the
    245         // managed profile
    246         assertAppLinkResult("testTwoReceivers");
    247 
    248         changeUserRestrictionOrFail("allow_parent_profile_app_linking", true, mProfileUserId);
    249         // Now we should also have one receiver in the primary user, so three receivers in total.
    250         assertAppLinkResult("testThreeReceivers");
    251 
    252         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "never");
    253         // The primary user one has been set to never: we should only have the managed profile ones.
    254         assertAppLinkResult("testTwoReceivers");
    255 
    256         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "never");
    257         // Now there's only the browser in the managed profile left
    258         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    259 
    260         changeVerificationStatus(mProfileUserId, INTENT_RECEIVER_PKG, "always");
    261         changeVerificationStatus(mParentUserId, INTENT_RECEIVER_PKG, "always");
    262         // We have one always in the primary user and one always in the managed profile: the managed
    263         // profile one should have precedence.
    264         assertAppLinkResult("testReceivedByAppLinkActivityInManaged");
    265     }
    266 
    267     public void testAppLinks_enabledStatus() throws Exception {
    268         if (!mHasFeature) {
    269             return;
    270         }
    271         // Disable all pre-existing browsers in the managed profile so they don't interfere with
    272         // intents resolution.
    273         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    274                 "testDisableAllBrowsers", mProfileUserId);
    275         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    276         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    277         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    278         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    279 
    280         final String APP_HANDLER_COMPONENT = "com.android.cts.intent.receiver/.AppLinkActivity";
    281 
    282         // allow_parent_profile_app_linking is not set, try different enabled state combinations.
    283         // We should not have app link handler in parent user no matter whether it is enabled.
    284 
    285         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    286         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    287         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    288 
    289         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    290         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    291         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    292 
    293         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    294         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    295         assertAppLinkResult("testTwoReceivers");
    296 
    297         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    298         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    299         assertAppLinkResult("testTwoReceivers");
    300 
    301         // We now set allow_parent_profile_app_linking, and hence we should have the app handler
    302         // in parent user if it is enabled.
    303         changeUserRestrictionOrFail("allow_parent_profile_app_linking", true, mProfileUserId);
    304 
    305         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    306         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    307         assertAppLinkResult("testReceivedByBrowserActivityInManaged");
    308 
    309         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    310         disableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    311         assertAppLinkResult("testTwoReceivers");
    312 
    313         disableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    314         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    315         assertAppLinkResult("testTwoReceivers");
    316 
    317         enableComponentOrPackage(mParentUserId, APP_HANDLER_COMPONENT);
    318         enableComponentOrPackage(mProfileUserId, APP_HANDLER_COMPONENT);
    319         assertAppLinkResult("testThreeReceivers");
    320     }
    321 
    322     public void testSettingsIntents() throws Exception {
    323         if (!mHasFeature) {
    324             return;
    325         }
    326 
    327         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SettingsIntentsTest",
    328                 mProfileUserId);
    329     }
    330 
    331     public void testCrossProfileContent() throws Exception {
    332         if (!mHasFeature) {
    333             return;
    334         }
    335         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    336         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    337         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    338         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    339 
    340         // Test from parent to managed
    341         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    342                 "testRemoveAllFilters", mProfileUserId);
    343         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    344                 "testAddManagedCanAccessParentFilters", mProfileUserId);
    345         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".ContentTest", mParentUserId);
    346 
    347         // Test from managed to parent
    348         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    349                 "testRemoveAllFilters", mProfileUserId);
    350         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    351                 "testAddParentCanAccessManagedFilters", mProfileUserId);
    352         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".ContentTest", mProfileUserId);
    353 
    354     }
    355 
    356     public void testCrossProfileCopyPaste() throws Exception {
    357         if (!mHasFeature) {
    358             return;
    359         }
    360         installAppAsUser(INTENT_RECEIVER_APK, mParentUserId);
    361         installAppAsUser(INTENT_SENDER_APK, mParentUserId);
    362         installAppAsUser(INTENT_RECEIVER_APK, mProfileUserId);
    363         installAppAsUser(INTENT_SENDER_APK, mProfileUserId);
    364 
    365         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    366                 "testAllowCrossProfileCopyPaste", mProfileUserId);
    367         // Test that managed can see what is copied in the parent.
    368         testCrossProfileCopyPasteInternal(mProfileUserId, true);
    369         // Test that the parent can see what is copied in managed.
    370         testCrossProfileCopyPasteInternal(mParentUserId, true);
    371 
    372         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    373                 "testDisallowCrossProfileCopyPaste", mProfileUserId);
    374         // Test that managed can still see what is copied in the parent.
    375         testCrossProfileCopyPasteInternal(mProfileUserId, true);
    376         // Test that the parent cannot see what is copied in managed.
    377         testCrossProfileCopyPasteInternal(mParentUserId, false);
    378     }
    379 
    380     private void testCrossProfileCopyPasteInternal(int userId, boolean shouldSucceed)
    381             throws DeviceNotAvailableException {
    382         final String direction = (userId == mParentUserId)
    383                 ? "testAddManagedCanAccessParentFilters"
    384                 : "testAddParentCanAccessManagedFilters";
    385         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    386                 "testRemoveAllFilters", mProfileUserId);
    387         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileUtils",
    388                 direction, mProfileUserId);
    389         if (shouldSucceed) {
    390             runDeviceTestsAsUser(INTENT_SENDER_PKG, ".CopyPasteTest",
    391                     "testCanReadAcrossProfiles", userId);
    392             runDeviceTestsAsUser(INTENT_SENDER_PKG, ".CopyPasteTest",
    393                     "testIsNotified", userId);
    394         } else {
    395             runDeviceTestsAsUser(INTENT_SENDER_PKG, ".CopyPasteTest",
    396                     "testCannotReadAcrossProfiles", userId);
    397         }
    398     }
    399 
    400     /** Tests for the API helper class. */
    401     public void testCurrentApiHelper() throws Exception {
    402         if (!mHasFeature) {
    403             return;
    404         }
    405         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CurrentApiHelperTest",
    406                 mProfileUserId);
    407     }
    408 
    409     /** Test: unsupported public APIs are disabled on a parent profile. */
    410     public void testParentProfileApiDisabled() throws Exception {
    411         if (!mHasFeature) {
    412             return;
    413         }
    414         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ParentProfileTest",
    415                 "testParentProfileApiDisabled", mProfileUserId);
    416     }
    417 
    418     // TODO: This test is not specific to managed profiles, but applies to multi-user in general.
    419     // Move it to a MultiUserTest class when there is one. Should probably move
    420     // SetPolicyActivity to a more generic apk too as it might be useful for different kinds
    421     // of tests (same applies to ComponentDisablingActivity).
    422     public void testNoDebuggingFeaturesRestriction() throws Exception {
    423         if (!mHasFeature) {
    424             return;
    425         }
    426         // If adb is running as root, then the adb uid is 0 instead of SHELL_UID,
    427         // so the DISALLOW_DEBUGGING_FEATURES restriction does not work and this test
    428         // fails.
    429         if (getDevice().isAdbRoot()) {
    430             CLog.logAndDisplay(LogLevel.WARN,
    431                     "Cannot test testNoDebuggingFeaturesRestriction() in eng/userdebug build");
    432             return;
    433         }
    434         String restriction = "no_debugging_features";  // UserManager.DISALLOW_DEBUGGING_FEATURES
    435 
    436         changeUserRestrictionOrFail(restriction, true, mProfileUserId);
    437 
    438 
    439         // This should now fail, as the shell is not available to start activities under a different
    440         // user once the restriction is in place.
    441         String addRestrictionCommandOutput =
    442                 changeUserRestriction(restriction, true, mProfileUserId);
    443         assertTrue(
    444                 "Expected SecurityException when starting the activity "
    445                         + addRestrictionCommandOutput,
    446                 addRestrictionCommandOutput.contains("SecurityException"));
    447     }
    448 
    449     // Test the bluetooth API from a managed profile.
    450     public void testBluetooth() throws Exception {
    451         boolean hasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
    452         if (!mHasFeature || !hasBluetooth) {
    453             return ;
    454         }
    455 
    456         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    457                 "testEnableDisable", mProfileUserId);
    458         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    459                 "testGetAddress", mProfileUserId);
    460         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    461                 "testListenUsingRfcommWithServiceRecord", mProfileUserId);
    462         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothTest",
    463                 "testGetRemoteDevice", mProfileUserId);
    464     }
    465 
    466     public void testCameraPolicy() throws Exception {
    467         boolean hasCamera = hasDeviceFeature(FEATURE_CAMERA);
    468         if (!mHasFeature || !hasCamera) {
    469             return;
    470         }
    471         try {
    472             setDeviceAdmin(MANAGED_PROFILE_PKG + "/.PrimaryUserDeviceAdmin", mParentUserId);
    473 
    474             // Disable managed profile camera.
    475             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    476                     "testDisableCameraInManagedProfile",
    477                     mProfileUserId);
    478             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    479                     "testIsCameraEnabledInPrimaryProfile",
    480                     mParentUserId);
    481 
    482             // Enable managed profile camera.
    483             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    484                     "testEnableCameraInManagedProfile",
    485                     mProfileUserId);
    486             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    487                     "testIsCameraEnabledInPrimaryProfile",
    488                     mParentUserId);
    489 
    490             // Disable primary profile camera.
    491             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    492                     "testDisableCameraInPrimaryProfile",
    493                     mParentUserId);
    494             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    495                     "testIsCameraEnabledInManagedProfile",
    496                     mProfileUserId);
    497 
    498             // Enable primary profile camera.
    499             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    500                     "testEnableCameraInPrimaryProfile",
    501                     mParentUserId);
    502             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CameraPolicyTest",
    503                     "testIsCameraEnabledInManagedProfile",
    504                     mProfileUserId);
    505         } finally {
    506             final String adminHelperClass = ".PrimaryUserAdminHelper";
    507             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    508                     adminHelperClass, "testClearDeviceAdmin", mParentUserId);
    509         }
    510     }
    511 
    512 
    513     public void testManagedContactsUris() throws Exception {
    514         runManagedContactsTest(new Callable<Void>() {
    515             @Override
    516             public Void call() throws Exception {
    517                 ContactsTestSet contactsTestSet = new ContactsTestSet(ManagedProfileTest.this,
    518                         MANAGED_PROFILE_PKG, mParentUserId, mProfileUserId);
    519 
    520                 contactsTestSet.setCallerIdEnabled(true);
    521                 contactsTestSet.setContactsSearchEnabled(true);
    522                 contactsTestSet.checkIfCanLookupEnterpriseContacts(true);
    523                 contactsTestSet.checkIfCanFilterEnterpriseContacts(true);
    524                 contactsTestSet.checkIfCanFilterSelfContacts();
    525                 return null;
    526             }
    527         });
    528     }
    529 
    530     public void testManagedQuickContacts() throws Exception {
    531         runManagedContactsTest(new Callable<Void>() {
    532             @Override
    533             public Void call() throws Exception {
    534                 runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    535                         "testQuickContact", mParentUserId);
    536                 return null;
    537             }
    538         });
    539     }
    540 
    541     public void testManagedContactsPolicies() throws Exception {
    542         runManagedContactsTest(new Callable<Void>() {
    543             @Override
    544             public Void call() throws Exception {
    545                 ContactsTestSet contactsTestSet = new ContactsTestSet(ManagedProfileTest.this,
    546                         MANAGED_PROFILE_PKG, mParentUserId, mProfileUserId);
    547                 try {
    548                     contactsTestSet.setCallerIdEnabled(true);
    549                     contactsTestSet.setContactsSearchEnabled(false);
    550                     contactsTestSet.checkIfCanLookupEnterpriseContacts(true);
    551                     contactsTestSet.checkIfCanFilterEnterpriseContacts(false);
    552                     contactsTestSet.checkIfCanFilterSelfContacts();
    553                     contactsTestSet.setCallerIdEnabled(false);
    554                     contactsTestSet.setContactsSearchEnabled(true);
    555                     contactsTestSet.checkIfCanLookupEnterpriseContacts(false);
    556                     contactsTestSet.checkIfCanFilterEnterpriseContacts(true);
    557                     contactsTestSet.checkIfCanFilterSelfContacts();
    558                     contactsTestSet.setCallerIdEnabled(false);
    559                     contactsTestSet.setContactsSearchEnabled(false);
    560                     contactsTestSet.checkIfCanLookupEnterpriseContacts(false);
    561                     contactsTestSet.checkIfCanFilterEnterpriseContacts(false);
    562                     contactsTestSet.checkIfCanFilterSelfContacts();
    563                     contactsTestSet.checkIfNoEnterpriseDirectoryFound();
    564                     return null;
    565                 } finally {
    566                     // reset policies
    567                     contactsTestSet.setCallerIdEnabled(true);
    568                     contactsTestSet.setContactsSearchEnabled(true);
    569                 }
    570             }
    571         });
    572     }
    573 
    574     public void testOrganizationInfo() throws Exception {
    575         if (!mHasFeature) {
    576             return;
    577         }
    578         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
    579                 "testDefaultOrganizationColor", mProfileUserId);
    580         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
    581                 "testDefaultOrganizationNameIsNull", mProfileUserId);
    582         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".OrganizationInfoTest",
    583                 mProfileUserId);
    584     }
    585 
    586     public void testPasswordMinimumRestrictions() throws Exception {
    587         if (!mHasFeature) {
    588             return;
    589         }
    590         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PasswordMinimumRestrictionsTest",
    591                 mProfileUserId);
    592     }
    593 
    594     public void testBluetoothContactSharingDisabled() throws Exception {
    595         if (!mHasFeature) {
    596             return;
    597         }
    598         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    599                 "testSetBluetoothContactSharingDisabled_setterAndGetter", mProfileUserId);
    600     }
    601 
    602     public void testCannotSetProfileOwnerAgain() throws Exception {
    603         if (!mHasFeature) {
    604             return;
    605         }
    606         // verify that we can't set the same admin receiver as profile owner again
    607         assertFalse(setProfileOwner(
    608                 MANAGED_PROFILE_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mProfileUserId,
    609                 /*expectFailure*/ true));
    610 
    611         // verify that we can't set a different admin receiver as profile owner
    612         installAppAsUser(DEVICE_OWNER_APK, mProfileUserId);
    613         assertFalse(setProfileOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mProfileUserId,
    614                 /*expectFailure*/ true));
    615     }
    616 
    617     public void testCannotSetDeviceOwnerWhenProfilePresent() throws Exception {
    618         if (!mHasFeature) {
    619             return;
    620         }
    621 
    622         try {
    623             installAppAsUser(DEVICE_OWNER_APK, mParentUserId);
    624             assertFalse(setDeviceOwner(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mParentUserId,
    625                     /*expectFailure*/ true));
    626         } finally {
    627             // make sure we clean up in case we succeeded in setting the device owner
    628             removeAdmin(DEVICE_OWNER_PKG + "/" + DEVICE_OWNER_ADMIN, mParentUserId);
    629             getDevice().uninstallPackage(DEVICE_OWNER_PKG);
    630         }
    631     }
    632 
    633     public void testNfcRestriction() throws Exception {
    634         if (!mHasFeature || !mHasNfcFeature) {
    635             return;
    636         }
    637 
    638         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    639                 "testNfcShareEnabled", mProfileUserId);
    640         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    641                 "testNfcShareEnabled", mParentUserId);
    642 
    643         changeUserRestrictionOrFail("no_outgoing_beam" /* UserManager.DISALLOW_OUTGOING_BEAM */,
    644                 true, mProfileUserId);
    645 
    646         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    647                 "testNfcShareDisabled", mProfileUserId);
    648         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".NfcTest",
    649                 "testNfcShareEnabled", mParentUserId);
    650     }
    651 
    652     public void testCrossProfileWidgets() throws Exception {
    653         if (!mHasFeature) {
    654             return;
    655         }
    656 
    657         try {
    658             installAppAsUser(WIDGET_PROVIDER_APK, mProfileUserId);
    659             installAppAsUser(WIDGET_PROVIDER_APK, mParentUserId);
    660             getDevice().executeShellCommand("appwidget grantbind --user " + mParentUserId
    661                     + " --package " + WIDGET_PROVIDER_PKG);
    662             setIdleWhitelist(WIDGET_PROVIDER_PKG, true);
    663             startWidgetHostService();
    664 
    665             String commandOutput = changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG,
    666                     "add-cross-profile-widget", mProfileUserId);
    667             assertTrue("Command was expected to succeed " + commandOutput,
    668                     commandOutput.contains("Status: ok"));
    669 
    670             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileWidgetTest",
    671                     "testCrossProfileWidgetProviderAdded", mProfileUserId);
    672             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    673                     ".CrossProfileWidgetPrimaryUserTest",
    674                     "testHasCrossProfileWidgetProvider_true", mParentUserId);
    675             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    676                     ".CrossProfileWidgetPrimaryUserTest",
    677                     "testHostReceivesWidgetUpdates_true", mParentUserId);
    678 
    679             commandOutput = changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG,
    680                     "remove-cross-profile-widget", mProfileUserId);
    681             assertTrue("Command was expected to succeed " + commandOutput,
    682                     commandOutput.contains("Status: ok"));
    683 
    684             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".CrossProfileWidgetTest",
    685                     "testCrossProfileWidgetProviderRemoved", mProfileUserId);
    686             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    687                     ".CrossProfileWidgetPrimaryUserTest",
    688                     "testHasCrossProfileWidgetProvider_false", mParentUserId);
    689             runDeviceTestsAsUser(MANAGED_PROFILE_PKG,
    690                     ".CrossProfileWidgetPrimaryUserTest",
    691                     "testHostReceivesWidgetUpdates_false", mParentUserId);
    692         } finally {
    693             changeCrossProfileWidgetForUser(WIDGET_PROVIDER_PKG, "remove-cross-profile-widget",
    694                     mProfileUserId);
    695             getDevice().uninstallPackage(WIDGET_PROVIDER_PKG);
    696         }
    697     }
    698 
    699     public void testIsProvisioningAllowed() throws DeviceNotAvailableException {
    700         if (!mHasFeature) {
    701             return;
    702         }
    703         // In Managed profile user when managed profile is provisioned
    704         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PreManagedProfileTest",
    705                 "testIsProvisioningAllowedFalse", mProfileUserId);
    706 
    707         // In parent user when managed profile is provisioned
    708         // It's allowed to provision again by removing the previous profile
    709         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PreManagedProfileTest",
    710                 "testIsProvisioningAllowedTrue", mParentUserId);
    711     }
    712 
    713     private void setDirectoryPrefix(String directoryName, int userId)
    714             throws DeviceNotAvailableException {
    715         String command = "content call --uri " + DIRECTORY_PRIVOIDER_URI
    716                 + " --user " + userId
    717                 + " --method " + SET_CUSTOM_DIRECTORY_PREFIX_METHOD
    718                 + " --arg " + directoryName;
    719         CLog.d("Output for command " + command + ": "
    720                 + getDevice().executeShellCommand(command));
    721     }
    722 
    723     public void testPhoneAccountVisibility() throws Exception  {
    724         if (!mHasFeature) {
    725             return;
    726         }
    727         if (!shouldRunTelecomTest()) {
    728             return;
    729         }
    730         try {
    731             // Register phone account in parent user.
    732             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    733                     "testRegisterPhoneAccount",
    734                     mParentUserId);
    735             // The phone account should not be visible in managed user.
    736             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    737                     "testPhoneAccountNotRegistered",
    738                     mProfileUserId);
    739         } finally {
    740             // Unregister the phone account.
    741             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    742                     "testUnregisterPhoneAccount",
    743                     mParentUserId);
    744         }
    745 
    746         try {
    747             // Register phone account in profile user.
    748             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    749                     "testRegisterPhoneAccount",
    750                     mProfileUserId);
    751             // The phone account should not be visible in parent user.
    752             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    753                     "testPhoneAccountNotRegistered",
    754                     mParentUserId);
    755         } finally {
    756             // Unregister the phone account.
    757             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    758                     "testUnregisterPhoneAccount",
    759                     mProfileUserId);
    760         }
    761     }
    762 
    763     public void testManagedCall() throws Exception {
    764         if (!mHasFeature) {
    765             return;
    766         }
    767         if (!shouldRunTelecomTest()) {
    768             return;
    769         }
    770         // Place a outgoing call through work phone account using TelecomManager and verify the
    771         // call is inserted properly.
    772         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    773                 "testOutgoingCallUsingTelecomManager",
    774                 mProfileUserId);
    775         // Make sure the call is not inserted into parent user.
    776         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    777                 "testEnsureCallNotInserted",
    778                 mParentUserId);
    779 
    780         // Place a outgoing call through work phone account using ACTION_CALL and verify the call
    781         // is inserted properly.
    782         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    783                 "testOutgoingCallUsingActionCall",
    784                 mProfileUserId);
    785         // Make sure the call is not inserted into parent user.
    786         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    787                 "testEnsureCallNotInserted",
    788                 mParentUserId);
    789 
    790         // Add an incoming call with parent user's phone account and verify the call is inserted
    791         // properly.
    792         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    793                 "testIncomingCall",
    794                 mProfileUserId);
    795         // Make sure the call is not inserted into parent user.
    796         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".PhoneAccountTest",
    797                 "testEnsureCallNotInserted",
    798                 mParentUserId);
    799     }
    800 
    801     private void givePackageWriteSettingsPermission(int userId, String pkg) throws Exception {
    802         // Allow app to write to settings (for RingtoneManager.setActualDefaultUri to work)
    803         String command = "appops set --user " + userId + " " + pkg
    804                 + " android:write_settings allow";
    805         CLog.d("Output for command " + command + ": " + getDevice().executeShellCommand(command));
    806     }
    807 
    808     public void testRingtoneSync() throws Exception {
    809         if (!mHasFeature) {
    810             return;
    811         }
    812         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
    813         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
    814                 "testRingtoneSync", mProfileUserId);
    815     }
    816 
    817     // Test if setting RINGTONE disables sync
    818     public void testRingtoneSyncAutoDisableRingtone() throws Exception {
    819         if (!mHasFeature) {
    820             return;
    821         }
    822         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
    823         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
    824                 "testRingtoneDisableSync", mProfileUserId);
    825     }
    826 
    827     // Test if setting NOTIFICATION disables sync
    828     public void testRingtoneSyncAutoDisableNotification() throws Exception {
    829         if (!mHasFeature) {
    830             return;
    831         }
    832         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
    833         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
    834                 "testNotificationDisableSync", mProfileUserId);
    835     }
    836 
    837     // Test if setting ALARM disables sync
    838     public void testRingtoneSyncAutoDisableAlarm() throws Exception {
    839         if (!mHasFeature) {
    840             return;
    841         }
    842         givePackageWriteSettingsPermission(mProfileUserId, MANAGED_PROFILE_PKG);
    843         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".RingtoneSyncTest",
    844                 "testAlarmDisableSync", mProfileUserId);
    845     }
    846 
    847     public void testTrustAgentInfo() throws Exception {
    848         if (!mHasFeature) {
    849             return;
    850         }
    851         // Set and get trust agent config using child dpm instance.
    852         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
    853                 "testSetAndGetTrustAgentConfiguration_child",
    854                 mProfileUserId);
    855         // Set and get trust agent config using parent dpm instance.
    856         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
    857                 "testSetAndGetTrustAgentConfiguration_parent",
    858                 mProfileUserId);
    859         // Unified case
    860         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
    861                 "testSetTrustAgentConfiguration_bothHaveTrustAgentConfigAndUnified",
    862                 mProfileUserId);
    863         // Non-unified case
    864         try {
    865             changeUserCredential("1234", null, mProfileUserId);
    866             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".TrustAgentInfoTest",
    867                     "testSetTrustAgentConfiguration_bothHaveTrustAgentConfigAndNonUnified",
    868                     mProfileUserId);
    869         } finally {
    870             changeUserCredential(null, "1234", mProfileUserId);
    871         }
    872     }
    873 
    874     public void testSanityCheck() throws Exception {
    875         if (!mHasFeature) {
    876             return;
    877         }
    878         // Install SimpleApp in work profile only and check activity in it can be launched.
    879         installAppAsUser(SIMPLE_APP_APK, mProfileUserId);
    880         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".SanityTest", mProfileUserId);
    881     }
    882 
    883     public void testBluetoothSharingRestriction() throws Exception {
    884         final boolean hasBluetooth = hasDeviceFeature(FEATURE_BLUETOOTH);
    885         if (!mHasFeature || !hasBluetooth) {
    886             return;
    887         }
    888 
    889         // Primary profile should be able to use bluetooth sharing.
    890         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionPrimaryProfileTest",
    891                 "testBluetoothSharingAvailable", mPrimaryUserId);
    892 
    893         // Managed profile owner should be able to control it via DISALLOW_BLUETOOTH_SHARING.
    894         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".BluetoothSharingRestrictionTest",
    895                 "testOppDisabledWhenRestrictionSet", mProfileUserId);
    896     }
    897 
    898     private void disableActivityForUser(String activityName, int userId)
    899             throws DeviceNotAvailableException {
    900         String command = "am start -W --user " + userId
    901                 + " --es extra-package " + MANAGED_PROFILE_PKG
    902                 + " --es extra-class-name " + MANAGED_PROFILE_PKG + "." + activityName
    903                 + " " + MANAGED_PROFILE_PKG + "/.ComponentDisablingActivity ";
    904         CLog.d("Output for command " + command + ": "
    905                 + getDevice().executeShellCommand(command));
    906     }
    907 
    908     private void changeUserRestrictionOrFail(String key, boolean value, int userId)
    909             throws DeviceNotAvailableException {
    910         changeUserRestrictionOrFail(key, value, userId, MANAGED_PROFILE_PKG);
    911     }
    912 
    913     private String changeUserRestriction(String key, boolean value, int userId)
    914             throws DeviceNotAvailableException {
    915         return changeUserRestriction(key, value, userId, MANAGED_PROFILE_PKG);
    916     }
    917 
    918     private void setIdleWhitelist(String packageName, boolean enabled)
    919             throws DeviceNotAvailableException {
    920         String command = "cmd deviceidle whitelist " + (enabled ? "+" : "-") + packageName;
    921         CLog.d("Output for command " + command + ": "
    922                 + getDevice().executeShellCommand(command));
    923     }
    924 
    925     private String changeCrossProfileWidgetForUser(String packageName, String command, int userId)
    926             throws DeviceNotAvailableException {
    927         String adbCommand = "am start -W --user " + userId
    928                 + " -c android.intent.category.DEFAULT "
    929                 + " --es extra-command " + command
    930                 + " --es extra-package-name " + packageName
    931                 + " " + MANAGED_PROFILE_PKG + "/.SetPolicyActivity";
    932         String commandOutput = getDevice().executeShellCommand(adbCommand);
    933         CLog.d("Output for command " + adbCommand + ": " + commandOutput);
    934         return commandOutput;
    935     }
    936 
    937     // status should be one of never, undefined, ask, always
    938     private void changeVerificationStatus(int userId, String packageName, String status)
    939             throws DeviceNotAvailableException {
    940         String command = "pm set-app-link --user " + userId + " " + packageName + " " + status;
    941         CLog.d("Output for command " + command + ": "
    942                 + getDevice().executeShellCommand(command));
    943     }
    944 
    945     protected void startWidgetHostService() throws Exception {
    946         String command = "am startservice --user " + mParentUserId
    947                 + " -a " + WIDGET_PROVIDER_PKG + ".REGISTER_CALLBACK "
    948                 + "--ei user-extra " + getUserSerialNumber(mProfileUserId)
    949                 + " " + WIDGET_PROVIDER_PKG + "/.SimpleAppWidgetHostService";
    950         CLog.d("Output for command " + command + ": "
    951               + getDevice().executeShellCommand(command));
    952     }
    953 
    954     private void assertAppLinkResult(String methodName) throws DeviceNotAvailableException {
    955         runDeviceTestsAsUser(INTENT_SENDER_PKG, ".AppLinkTest", methodName,
    956                 mProfileUserId);
    957     }
    958 
    959     private boolean shouldRunTelecomTest() throws DeviceNotAvailableException {
    960         return hasDeviceFeature(FEATURE_TELEPHONY) && hasDeviceFeature(FEATURE_CONNECTION_SERVICE);
    961     }
    962 
    963     private void runManagedContactsTest(Callable<Void> callable) throws Exception {
    964         if (!mHasFeature) {
    965             return;
    966         }
    967 
    968         try {
    969             // Allow cross profile contacts search.
    970             // TODO test both on and off.
    971             getDevice().executeShellCommand(
    972                     "settings put --user " + mProfileUserId
    973                     + " secure managed_profile_contact_remote_search 1");
    974 
    975             // Add test account
    976             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    977                     "testAddTestAccount", mParentUserId);
    978             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    979                     "testAddTestAccount", mProfileUserId);
    980 
    981             // Install directory provider to both primary and managed profile
    982             installAppAsUser(DIRECTORY_PROVIDER_APK, mProfileUserId);
    983             installAppAsUser(DIRECTORY_PROVIDER_APK, mParentUserId);
    984             setDirectoryPrefix(PRIMARY_DIRECTORY_PREFIX, mParentUserId);
    985             setDirectoryPrefix(MANAGED_DIRECTORY_PREFIX, mProfileUserId);
    986 
    987             // Check enterprise directory API works
    988             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    989                     "testGetDirectoryListInPrimaryProfile", mParentUserId);
    990 
    991             // Insert Primary profile Contacts
    992             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    993                     "testPrimaryProfilePhoneAndEmailLookup_insertedAndfound", mParentUserId);
    994             // Insert Managed profile Contacts
    995             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
    996                     "testManagedProfilePhoneAndEmailLookup_insertedAndfound", mProfileUserId);
    997             // Insert a primary contact with same phone & email as other
    998             // enterprise contacts
    999             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1000                     "testPrimaryProfileDuplicatedPhoneEmailContact_insertedAndfound",
   1001                     mParentUserId);
   1002             // Insert a enterprise contact with same phone & email as other
   1003             // primary contacts
   1004             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1005                     "testManagedProfileDuplicatedPhoneEmailContact_insertedAndfound",
   1006                     mProfileUserId);
   1007 
   1008             callable.call();
   1009 
   1010         } finally {
   1011             // Clean up in managed profile and primary profile
   1012             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1013                     "testCurrentProfileContacts_removeContacts", mProfileUserId);
   1014             runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ContactsTest",
   1015                     "testCurrentProfileContacts_removeContacts", mParentUserId);
   1016             getDevice().uninstallPackage(DIRECTORY_PROVIDER_PKG);
   1017         }
   1018     }
   1019 
   1020 
   1021     /*
   1022      * Container for running ContactsTest under multi-user environment
   1023      */
   1024     private static class ContactsTestSet {
   1025 
   1026         private ManagedProfileTest mManagedProfileTest;
   1027         private String mManagedProfilePackage;
   1028         private int mParentUserId;
   1029         private int mProfileUserId;
   1030 
   1031         public ContactsTestSet(ManagedProfileTest managedProfileTest, String managedProfilePackage,
   1032                 int parentUserId, int profileUserId) {
   1033             mManagedProfileTest = managedProfileTest;
   1034             mManagedProfilePackage = managedProfilePackage;
   1035             mParentUserId = parentUserId;
   1036             mProfileUserId = profileUserId;
   1037         }
   1038 
   1039         private void runDeviceTestsAsUser(String pkgName, String testClassName,
   1040                 String testMethodName, Integer userId) throws DeviceNotAvailableException {
   1041             mManagedProfileTest.runDeviceTestsAsUser(pkgName, testClassName, testMethodName,
   1042                     userId);
   1043         }
   1044 
   1045         // Enable / Disable cross profile caller id
   1046         public void setCallerIdEnabled(boolean enabled) throws DeviceNotAvailableException {
   1047             if (enabled) {
   1048                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1049                         "testSetCrossProfileCallerIdDisabled_false", mProfileUserId);
   1050             } else {
   1051                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1052                         "testSetCrossProfileCallerIdDisabled_true", mProfileUserId);
   1053             }
   1054         }
   1055 
   1056         // Enable / Disable cross profile contacts search
   1057         public void setContactsSearchEnabled(boolean enabled) throws DeviceNotAvailableException {
   1058             if (enabled) {
   1059                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1060                         "testSetCrossProfileContactsSearchDisabled_false", mProfileUserId);
   1061             } else {
   1062                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1063                         "testSetCrossProfileContactsSearchDisabled_true", mProfileUserId);
   1064             }
   1065         }
   1066 
   1067         public void checkIfCanLookupEnterpriseContacts(boolean expected)
   1068                 throws DeviceNotAvailableException {
   1069             // Primary user cannot use ordinary phone/email lookup api to access
   1070             // managed contacts
   1071             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1072                     "testPrimaryProfilePhoneLookup_canNotAccessEnterpriseContact", mParentUserId);
   1073             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1074                     "testPrimaryProfileEmailLookup_canNotAccessEnterpriseContact", mParentUserId);
   1075             // Primary user can use ENTERPRISE_CONTENT_FILTER_URI to access
   1076             // primary contacts
   1077             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1078                     "testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryContact",
   1079                     mParentUserId);
   1080             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1081                     "testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryContact",
   1082                     mParentUserId);
   1083             // When there exist contacts with the same phone/email in primary &
   1084             // enterprise,
   1085             // primary user can use ENTERPRISE_CONTENT_FILTER_URI to access the
   1086             // primary contact.
   1087             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1088                     "testPrimaryProfileEnterpriseEmailLookupDuplicated_canAccessPrimaryContact",
   1089                     mParentUserId);
   1090             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1091                     "testPrimaryProfileEnterprisePhoneLookupDuplicated_canAccessPrimaryContact",
   1092                     mParentUserId);
   1093 
   1094             // Managed user cannot use ordinary phone/email lookup api to access
   1095             // primary contacts
   1096             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1097                     "testManagedProfilePhoneLookup_canNotAccessPrimaryContact", mProfileUserId);
   1098             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1099                     "testManagedProfileEmailLookup_canNotAccessPrimaryContact", mProfileUserId);
   1100             // Managed user can use ENTERPRISE_CONTENT_FILTER_URI to access
   1101             // enterprise contacts
   1102             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1103                     "testManagedProfileEnterprisePhoneLookup_canAccessEnterpriseContact",
   1104                     mProfileUserId);
   1105             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1106                     "testManagedProfileEnterpriseEmailLookup_canAccessEnterpriseContact",
   1107                     mProfileUserId);
   1108             // Managed user cannot use ENTERPRISE_CONTENT_FILTER_URI to access
   1109             // primary contacts
   1110             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1111                     "testManagedProfileEnterprisePhoneLookup_canNotAccessPrimaryContact",
   1112                     mProfileUserId);
   1113             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1114                     "testManagedProfileEnterpriseEmailLookup_canNotAccessPrimaryContact",
   1115                     mProfileUserId);
   1116             // When there exist contacts with the same phone/email in primary &
   1117             // enterprise,
   1118             // managed user can use ENTERPRISE_CONTENT_FILTER_URI to access the
   1119             // enterprise contact.
   1120             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1121                     "testManagedProfileEnterpriseEmailLookupDuplicated_canAccessEnterpriseContact",
   1122                     mProfileUserId);
   1123             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1124                     "testManagedProfileEnterprisePhoneLookupDuplicated_canAccessEnterpriseContact",
   1125                     mProfileUserId);
   1126 
   1127             // Check if phone lookup can access primary directories
   1128             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1129                     "testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryDirectories",
   1130                     mParentUserId);
   1131 
   1132             // Check if email lookup can access primary directories
   1133             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1134                     "testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryDirectories",
   1135                     mParentUserId);
   1136 
   1137             if (expected) {
   1138                 // Primary user can use ENTERPRISE_CONTENT_FILTER_URI to access
   1139                 // managed profile contacts
   1140                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1141                         "testPrimaryProfileEnterprisePhoneLookup_canAccessEnterpriseContact",
   1142                         mParentUserId);
   1143                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1144                         "testPrimaryProfileEnterpriseEmailLookup_canAccessEnterpriseContact",
   1145                         mParentUserId);
   1146 
   1147                 // Make sure SIP enterprise lookup works too.
   1148                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1149                         "testPrimaryProfileEnterpriseSipLookup_canAccessEnterpriseContact",
   1150                         mParentUserId);
   1151 
   1152                 // Check if phone lookup can access enterprise directories
   1153                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1154                         "testPrimaryProfileEnterprisePhoneLookup_canAccessManagedDirectories",
   1155                         mParentUserId);
   1156 
   1157                 // Check if email lookup can access enterprise directories
   1158                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1159                         "testPrimaryProfileEnterpriseEmailLookup_canAccessManagedDirectories",
   1160                         mParentUserId);
   1161             } else {
   1162                 // Primary user cannot use ENTERPRISE_CONTENT_FILTER_URI to
   1163                 // access managed contacts
   1164                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1165                         "testPrimaryProfileEnterprisePhoneLookup_canNotAccessEnterpriseContact",
   1166                         mParentUserId);
   1167                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1168                         "testPrimaryProfileEnterprisePhoneLookup_canNotAccessManagedDirectories",
   1169                         mParentUserId);
   1170 
   1171                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1172                         "testPrimaryProfileEnterpriseEmailLookup_canNotAccessManagedDirectories",
   1173                         mParentUserId);
   1174                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1175                         "testPrimaryProfileEnterprisePhoneLookup_canNotAccessManagedDirectories",
   1176                         mParentUserId);
   1177             }
   1178         }
   1179 
   1180         public void checkIfCanFilterSelfContacts() throws DeviceNotAvailableException {
   1181             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1182                     "testPrimaryProfileEnterpriseCallableFilter_canAccessPrimaryDirectories",
   1183                     mParentUserId);
   1184             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1185                     "testManagedProfileEnterpriseCallableFilter_canAccessManagedDirectories",
   1186                     mProfileUserId);
   1187 
   1188             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1189                     "testPrimaryProfileEnterpriseEmailFilter_canAccessPrimaryDirectories",
   1190                     mParentUserId);
   1191             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1192                     "testEnterpriseProfileEnterpriseEmailFilter_canAccessManagedDirectories",
   1193                     mProfileUserId);
   1194 
   1195             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1196                     "testPrimaryProfileEnterpriseContactFilter_canAccessPrimaryDirectories",
   1197                     mParentUserId);
   1198             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1199                     "testManagedProfileEnterpriseContactFilter_canAccessManagedDirectories",
   1200                     mProfileUserId);
   1201 
   1202             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1203                     "testPrimaryProfileEnterprisePhoneFilter_canAccessPrimaryDirectories",
   1204                     mParentUserId);
   1205             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1206                     "testManagedProfileEnterprisePhoneFilter_canAccessManagedDirectories",
   1207                     mProfileUserId);
   1208         }
   1209 
   1210         public void checkIfCanFilterEnterpriseContacts(boolean expected)
   1211                 throws DeviceNotAvailableException {
   1212             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1213                     "testFilterUriWhenDirectoryParamMissing", mParentUserId);
   1214             if (expected) {
   1215                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1216                         "testPrimaryProfileEnterpriseCallableFilter_canAccessManagedDirectories",
   1217                         mParentUserId);
   1218                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1219                         "testPrimaryProfileEnterpriseEmailFilter_canAccessManagedDirectories",
   1220                         mParentUserId);
   1221                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1222                         "testPrimaryProfileEnterpriseContactFilter_canAccessManagedDirectories",
   1223                         mParentUserId);
   1224                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1225                         "testPrimaryProfileEnterprisePhoneFilter_canAccessManagedDirectories",
   1226                         mParentUserId);
   1227             } else {
   1228                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1229                         "testPrimaryProfileEnterpriseCallableFilter_canNotAccessManagedDirectories",
   1230                         mParentUserId);
   1231                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1232                         "testPrimaryProfileEnterpriseEmailFilter_canNotAccessManagedDirectories",
   1233                         mParentUserId);
   1234                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1235                         "testPrimaryProfileEnterpriseContactFilter_canNotAccessManagedDirectories",
   1236                         mParentUserId);
   1237                 runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1238                         "testPrimaryProfileEnterprisePhoneFilter_canNotAccessManagedDirectories",
   1239                         mParentUserId);
   1240             }
   1241         }
   1242 
   1243         public void checkIfNoEnterpriseDirectoryFound() throws DeviceNotAvailableException {
   1244             runDeviceTestsAsUser(mManagedProfilePackage, ".ContactsTest",
   1245                     "testPrimaryProfileEnterpriseDirectories_canNotAccessManagedDirectories",
   1246                     mParentUserId);
   1247         }
   1248     }
   1249 }
   1250