1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.cts.devicepolicy;
18 
19 import static com.android.cts.devicepolicy.metrics.DevicePolicyEventLogVerifier.assertMetricsLogged;
20 
21 import android.stats.devicepolicy.EventId;
22 
23 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
24 import com.android.cts.devicepolicy.metrics.DevicePolicyEventWrapper;
25 import com.android.tradefed.device.DeviceNotAvailableException;
26 
27 import com.google.common.io.ByteStreams;
28 
29 import java.io.File;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.util.Collections;
35 import java.util.List;
36 import java.util.Map;
37 
38 /**
39  * Set of tests for Device Owner use cases.
40  */
41 public class DeviceOwnerTest extends BaseDevicePolicyTest {
42 
43     private static final String DEVICE_OWNER_PKG = "com.android.cts.deviceowner";
44     private static final String DEVICE_OWNER_APK = "CtsDeviceOwnerApp.apk";
45 
46     private static final String MANAGED_PROFILE_PKG = "com.android.cts.managedprofile";
47     private static final String MANAGED_PROFILE_APK = "CtsManagedProfileApp.apk";
48     private static final String MANAGED_PROFILE_ADMIN =
49             MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver";
50 
51     private static final String FEATURE_BACKUP = "android.software.backup";
52 
53     private static final String INTENT_RECEIVER_PKG = "com.android.cts.intent.receiver";
54     private static final String INTENT_RECEIVER_APK = "CtsIntentReceiverApp.apk";
55 
56     private static final String WIFI_CONFIG_CREATOR_PKG =
57             "com.android.cts.deviceowner.wificonfigcreator";
58     private static final String WIFI_CONFIG_CREATOR_APK = "CtsWifiConfigCreator.apk";
59 
60     private static final String ADMIN_RECEIVER_TEST_CLASS =
61             DEVICE_OWNER_PKG + ".BasicAdminReceiver";
62     private static final String DEVICE_OWNER_COMPONENT = DEVICE_OWNER_PKG + "/"
63             + ADMIN_RECEIVER_TEST_CLASS;
64 
65     private static final String TEST_APP_APK = "CtsEmptyTestApp.apk";
66     private static final String TEST_APP_PKG = "android.packageinstaller.emptytestapp.cts";
67     private static final String TEST_APP_LOCATION = "/data/local/tmp/cts/packageinstaller/";
68 
69     private static final String ARG_SECURITY_LOGGING_BATCH_NUMBER = "batchNumber";
70     private static final int SECURITY_EVENTS_BATCH_SIZE = 100;
71 
72     private static final String ARG_NETWORK_LOGGING_BATCH_COUNT = "batchCount";
73     private static final String TEST_UPDATE_LOCATION = "/data/local/tmp/cts/deviceowner";
74 
75     private static final String LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK =
76             "CtsHasLauncherActivityApp.apk";
77 
78     /**
79      * Copied from {@link android.app.admin.DevicePolicyManager
80      * .InstallSystemUpdateCallback#UPDATE_ERROR_UPDATE_FILE_INVALID}
81      */
82     private static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
83 
84     private static final int TYPE_NONE = 0;
85 
86     /**
87      * Copied from {@link android.app.admin.SystemUpdatePolicy}
88      */
89     private static final int TYPE_INSTALL_AUTOMATIC = 1;
90     private static final int TYPE_INSTALL_WINDOWED = 2;
91     private static final int TYPE_POSTPONE = 3;
92 
93     /**
94      * Copied from {@link android.provider.Settings}
95      */
96     private static final String SETTINGS_SECURE = "secure";
97     private static final String LOCATION_MODE = "location_mode";
98     private static final String LOCATION_MODE_HIGH_ACCURACY = "3";
99 
100     /** CreateAndManageUser is available and an additional user can be created. */
101     private boolean mHasCreateAndManageUserFeature;
102 
103     @Override
setUp()104     protected void setUp() throws Exception {
105         super.setUp();
106         if (mHasFeature) {
107             installAppAsUser(DEVICE_OWNER_APK, mPrimaryUserId);
108             if (!setDeviceOwner(DEVICE_OWNER_COMPONENT, mPrimaryUserId,
109                     /*expectFailure*/ false)) {
110                 removeAdmin(DEVICE_OWNER_COMPONENT, mPrimaryUserId);
111                 getDevice().uninstallPackage(DEVICE_OWNER_PKG);
112                 fail("Failed to set device owner");
113             }
114 
115             getDevice().executeShellCommand(" mkdir " + TEST_UPDATE_LOCATION);
116             // Enable the notification listener
117             getDevice().executeShellCommand("cmd notification allow_listener com.android.cts.deviceowner/com.android.cts.deviceowner.NotificationListener");
118         }
119         mHasCreateAndManageUserFeature = mHasFeature && canCreateAdditionalUsers(1)
120                 && hasDeviceFeature("android.software.managed_users");
121     }
122 
123     @Override
tearDown()124     protected void tearDown() throws Exception {
125         if (mHasFeature) {
126             assertTrue("Failed to remove device owner.",
127                     removeAdmin(DEVICE_OWNER_COMPONENT, mPrimaryUserId));
128             getDevice().uninstallPackage(DEVICE_OWNER_PKG);
129             switchUser(USER_SYSTEM);
130             removeTestUsers();
131             getDevice().executeShellCommand(" rm -r " + TEST_UPDATE_LOCATION);
132         }
133 
134         super.tearDown();
135     }
136 
testDeviceOwnerSetup()137     public void testDeviceOwnerSetup() throws Exception {
138         executeDeviceOwnerTest("DeviceOwnerSetupTest");
139     }
140 
testLockScreenInfo()141     public void testLockScreenInfo() throws Exception {
142         if (!mHasFeature) {
143             return;
144         }
145         executeDeviceOwnerTest("LockScreenInfoTest");
146         assertMetricsLogged(getDevice(), () -> {
147             executeDeviceTestMethod(".LockScreenInfoTest", "testSetAndGetLockInfo");
148         }, new DevicePolicyEventWrapper.Builder(EventId.SET_DEVICE_OWNER_LOCK_SCREEN_INFO_VALUE)
149                 .setAdminPackageName(DEVICE_OWNER_PKG)
150                 .build());
151     }
152 
testWifi()153     public void testWifi() throws Exception {
154         if (!mHasFeature || !hasDeviceFeature("android.hardware.wifi")) {
155             return;
156         }
157         executeDeviceOwnerTest("WifiTest");
158         assertMetricsLogged(getDevice(), () -> {
159             executeDeviceTestMethod(".WifiTest", "testGetWifiMacAddress");
160         }, new DevicePolicyEventWrapper.Builder(EventId.GET_WIFI_MAC_ADDRESS_VALUE)
161                 .setAdminPackageName(DEVICE_OWNER_PKG)
162                 .build());
163     }
164 
testRemoteBugreportWithTwoUsers()165     public void testRemoteBugreportWithTwoUsers() throws Exception {
166         if (!mHasFeature || !canCreateAdditionalUsers(1)) {
167             return;
168         }
169         final int userId = createUser();
170         try {
171             executeDeviceTestMethod(".RemoteBugreportTest",
172                     "testRequestBugreportThrowsSecurityException");
173         } finally {
174             removeUser(userId);
175         }
176     }
177 
testCreateAndManageUser_LowStorage()178     public void testCreateAndManageUser_LowStorage() throws Exception {
179         if (!mHasCreateAndManageUserFeature) {
180             return;
181         }
182 
183         try {
184             // Force low storage
185             getDevice().setSetting("global", "sys_storage_threshold_percentage", "100");
186             getDevice().setSetting("global", "sys_storage_threshold_max_bytes",
187                     String.valueOf(Long.MAX_VALUE));
188 
189             // The next createAndManageUser should return USER_OPERATION_ERROR_LOW_STORAGE.
190             executeDeviceTestMethod(".CreateAndManageUserTest",
191                     "testCreateAndManageUser_LowStorage");
192         } finally {
193             getDevice().executeShellCommand(
194                     "settings delete global sys_storage_threshold_percentage");
195             getDevice().executeShellCommand(
196                     "settings delete global sys_storage_threshold_max_bytes");
197         }
198     }
199 
testCreateAndManageUser_MaxUsers()200     public void testCreateAndManageUser_MaxUsers() throws Exception {
201         if (!mHasCreateAndManageUserFeature) {
202             return;
203         }
204 
205         int maxUsers = getDevice().getMaxNumberOfUsersSupported();
206         // Primary user is already there, so we can create up to maxUsers -1.
207         for (int i = 0; i < maxUsers - 1; i++) {
208             executeDeviceTestMethod(".CreateAndManageUserTest",
209                     "testCreateAndManageUser");
210         }
211         // The next createAndManageUser should return USER_OPERATION_ERROR_MAX_USERS.
212         executeDeviceTestMethod(".CreateAndManageUserTest",
213                 "testCreateAndManageUser_MaxUsers");
214     }
215 
216     /**
217      * Test creating an user using the DevicePolicyManager's createAndManageUser.
218      * {@link android.app.admin.DevicePolicyManager#getSecondaryUsers} is tested.
219      */
testCreateAndManageUser_GetSecondaryUsers()220     public void testCreateAndManageUser_GetSecondaryUsers() throws Exception {
221         if (!mHasCreateAndManageUserFeature) {
222             return;
223         }
224 
225         executeDeviceTestMethod(".CreateAndManageUserTest",
226                 "testCreateAndManageUser_GetSecondaryUsers");
227     }
228 
229     /**
230      * Test creating an user using the DevicePolicyManager's createAndManageUser method and switch
231      * to the user.
232      * {@link android.app.admin.DevicePolicyManager#switchUser} is tested.
233      */
testCreateAndManageUser_SwitchUser()234     public void testCreateAndManageUser_SwitchUser() throws Exception {
235         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
236             return;
237         }
238 
239         executeDeviceTestMethod(".CreateAndManageUserTest",
240                 "testCreateAndManageUser_SwitchUser");
241     }
242 
243     /**
244      * Test creating an user using the DevicePolicyManager's createAndManageUser method and switch
245      * to the user to test stop user while target user is in foreground.
246      * {@link android.app.admin.DevicePolicyManager#stopUser} is tested.
247      */
testCreateAndManageUser_CannotStopCurrentUser()248     public void testCreateAndManageUser_CannotStopCurrentUser() throws Exception {
249         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
250             return;
251         }
252 
253         executeDeviceTestMethod(".CreateAndManageUserTest",
254                 "testCreateAndManageUser_CannotStopCurrentUser");
255     }
256 
257     /**
258      * Test creating an user using the DevicePolicyManager's createAndManageUser method and start
259      * the user in background to test APIs on that user.
260      * {@link android.app.admin.DevicePolicyManager#startUserInBackground} is tested.
261      */
testCreateAndManageUser_StartInBackground()262     public void testCreateAndManageUser_StartInBackground() throws Exception {
263         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
264             return;
265         }
266 
267         executeDeviceTestMethod(".CreateAndManageUserTest",
268                 "testCreateAndManageUser_StartInBackground");
269     }
270 
271     /**
272      * Test creating an user using the DevicePolicyManager's createAndManageUser method and start
273      * the user in background to test APIs on that user.
274      * {@link android.app.admin.DevicePolicyManager#startUserInBackground} is tested.
275      */
testCreateAndManageUser_StartInBackground_MaxRunningUsers()276     public void testCreateAndManageUser_StartInBackground_MaxRunningUsers() throws Exception {
277         if (!mHasCreateAndManageUserFeature) {
278             return;
279         }
280 
281         int maxUsers = getDevice().getMaxNumberOfUsersSupported();
282         int maxRunningUsers = getDevice().getMaxNumberOfRunningUsersSupported();
283 
284         // Primary user is already running, so we can create and start up to minimum of above - 1.
285         int usersToCreateAndStart = Math.min(maxUsers, maxRunningUsers) - 1;
286         for (int i = 0; i < usersToCreateAndStart; i++) {
287             executeDeviceTestMethod(".CreateAndManageUserTest",
288                     "testCreateAndManageUser_StartInBackground");
289         }
290 
291         if (maxUsers > maxRunningUsers) {
292             // The next startUserInBackground should return USER_OPERATION_ERROR_MAX_RUNNING_USERS.
293             executeDeviceTestMethod(".CreateAndManageUserTest",
294                     "testCreateAndManageUser_StartInBackground_MaxRunningUsers");
295         } else {
296             // The next createAndManageUser should return USER_OPERATION_ERROR_MAX_USERS.
297             executeDeviceTestMethod(".CreateAndManageUserTest", "testCreateAndManageUser_MaxUsers");
298         }
299     }
300 
301     /**
302      * Test creating an user using the DevicePolicyManager's createAndManageUser method and start
303      * the user in background to test APIs on that user.
304      * {@link android.app.admin.DevicePolicyManager#stopUser} is tested.
305      */
testCreateAndManageUser_StopUser()306     public void testCreateAndManageUser_StopUser() throws Exception {
307         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
308             return;
309         }
310 
311         executeDeviceTestMethod(".CreateAndManageUserTest",
312                 "testCreateAndManageUser_StopUser");
313         assertNewUserStopped();
314     }
315 
316     /**
317      * Test creating an ephemeral user using the DevicePolicyManager's createAndManageUser method
318      * and start the user in background, user is then stopped. The user should be removed
319      * automatically even when DISALLOW_REMOVE_USER is set.
320      */
testCreateAndManageUser_StopEphemeralUser_DisallowRemoveUser()321     public void testCreateAndManageUser_StopEphemeralUser_DisallowRemoveUser() throws Exception {
322         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
323             return;
324         }
325 
326         executeDeviceTestMethod(".CreateAndManageUserTest",
327                 "testCreateAndManageUser_StopEphemeralUser_DisallowRemoveUser");
328         assertEquals(0, getUsersCreatedByTests().size());
329     }
330 
331     /**
332      * Test creating an user using the DevicePolicyManager's createAndManageUser method, affiliate
333      * the user and start the user in background to test APIs on that user.
334      * {@link android.app.admin.DevicePolicyManager#logoutUser} is tested.
335      */
testCreateAndManageUser_LogoutUser()336     public void testCreateAndManageUser_LogoutUser() throws Exception {
337         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
338             return;
339         }
340 
341         executeDeviceTestMethod(".CreateAndManageUserTest",
342                 "testCreateAndManageUser_LogoutUser");
343         assertNewUserStopped();
344     }
345 
346     /**
347      * Test creating an user using the DevicePolicyManager's createAndManageUser method, affiliate
348      * the user and start the user in background to test APIs on that user.
349      * {@link android.app.admin.DevicePolicyManager#isAffiliatedUser} is tested.
350      */
testCreateAndManageUser_Affiliated()351     public void testCreateAndManageUser_Affiliated() throws Exception {
352         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
353             return;
354         }
355 
356         executeDeviceTestMethod(".CreateAndManageUserTest",
357                 "testCreateAndManageUser_Affiliated");
358     }
359 
360     /**
361      * Test creating an ephemeral user using the DevicePolicyManager's createAndManageUser method,
362      * affiliate the user and start the user in background to test APIs on that user.
363      * {@link android.app.admin.DevicePolicyManager#isEphemeralUser} is tested.
364      */
testCreateAndManageUser_Ephemeral()365     public void testCreateAndManageUser_Ephemeral() throws Exception {
366         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
367             return;
368         }
369 
370         executeDeviceTestMethod(".CreateAndManageUserTest",
371                 "testCreateAndManageUser_Ephemeral");
372 
373         List<Integer> newUsers = getUsersCreatedByTests();
374         assertEquals(1, newUsers.size());
375         int newUserId = newUsers.get(0);
376 
377         // Get the flags of the new user and check the user is ephemeral.
378         int flags = getUserFlags(newUserId);
379         assertEquals("Ephemeral flag must be set", FLAG_EPHEMERAL, flags & FLAG_EPHEMERAL);
380     }
381 
382     /**
383      * Test creating an user using the DevicePolicyManager's createAndManageUser method, affiliate
384      * the user and start the user in background to test APIs on that user.
385      * {@link android.app.admin.DevicePolicyManager#LEAVE_ALL_SYSTEM_APPS_ENABLED} is tested.
386      */
testCreateAndManageUser_LeaveAllSystemApps()387     public void testCreateAndManageUser_LeaveAllSystemApps() throws Exception {
388         if (!mHasCreateAndManageUserFeature || !canStartAdditionalUsers(1)) {
389             return;
390         }
391 
392         executeDeviceTestMethod(".CreateAndManageUserTest",
393                 "testCreateAndManageUser_LeaveAllSystemApps");
394     }
395 
testCreateAndManageUser_SkipSetupWizard()396     public void testCreateAndManageUser_SkipSetupWizard() throws Exception {
397         if (mHasCreateAndManageUserFeature) {
398             executeDeviceTestMethod(".CreateAndManageUserTest",
399                     "testCreateAndManageUser_SkipSetupWizard");
400        }
401     }
402 
testCreateAndManageUser_AddRestrictionSet()403     public void testCreateAndManageUser_AddRestrictionSet() throws Exception {
404         if (mHasCreateAndManageUserFeature) {
405             executeDeviceTestMethod(".CreateAndManageUserTest",
406                     "testCreateAndManageUser_AddRestrictionSet");
407         }
408     }
409 
testCreateAndManageUser_RemoveRestrictionSet()410     public void testCreateAndManageUser_RemoveRestrictionSet() throws Exception {
411         if (mHasCreateAndManageUserFeature) {
412             executeDeviceTestMethod(".CreateAndManageUserTest",
413                     "testCreateAndManageUser_RemoveRestrictionSet");
414         }
415     }
416 
testUserAddedOrRemovedBroadcasts()417     public void testUserAddedOrRemovedBroadcasts() throws Exception {
418         if (mHasCreateAndManageUserFeature) {
419             executeDeviceTestMethod(".CreateAndManageUserTest",
420                     "testUserAddedOrRemovedBroadcasts");
421         }
422     }
423 
testUserSession()424     public void testUserSession() throws Exception {
425         if (!mHasFeature) {
426             return;
427         }
428         executeDeviceOwnerTest("UserSessionTest");
429     }
430 
testSecurityLoggingWithTwoUsers()431     public void testSecurityLoggingWithTwoUsers() throws Exception {
432         if (!mHasFeature || !canCreateAdditionalUsers(1)) {
433             return;
434         }
435 
436         final int userId = createUser();
437         try {
438             // The feature can be enabled, but in a "paused" state. Attempting to retrieve logs
439             // should throw security exception.
440             executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
441             executeDeviceTestMethod(".SecurityLoggingTest",
442                     "testRetrievingSecurityLogsThrowsSecurityException");
443             executeDeviceTestMethod(".SecurityLoggingTest",
444                     "testRetrievingPreviousSecurityLogsThrowsSecurityException");
445         } finally {
446             removeUser(userId);
447             executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
448         }
449     }
450 
testSecurityLoggingWithSingleUser()451     public void testSecurityLoggingWithSingleUser() throws Exception {
452         if (!mHasFeature) {
453             return;
454         }
455         // Backup stay awake setting because testGenerateLogs() will turn it off.
456         final String stayAwake = getDevice().getSetting("global", "stay_on_while_plugged_in");
457         try {
458             // Turn logging on.
459             executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
460             // Reboot to ensure ro.device_owner is set to true in logd and logging is on.
461             rebootAndWaitUntilReady();
462 
463             // Generate various types of events on device side and check that they are logged.
464             executeDeviceTestMethod(".SecurityLoggingTest", "testGenerateLogs");
465             getDevice().executeShellCommand("dpm force-security-logs");
466             executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyGeneratedLogs");
467 
468             // Reboot the device, so the security event ids are reset.
469             rebootAndWaitUntilReady();
470 
471             // Verify event ids are consistent across a consecutive batch.
472             for (int batchNumber = 0; batchNumber < 3; batchNumber++) {
473                 generateDummySecurityLogs();
474                 getDevice().executeShellCommand("dpm force-security-logs");
475                 executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyLogIds",
476                         Collections.singletonMap(ARG_SECURITY_LOGGING_BATCH_NUMBER,
477                                 Integer.toString(batchNumber)));
478             }
479 
480             // Immediately attempting to fetch events again should fail.
481             executeDeviceTestMethod(".SecurityLoggingTest",
482                     "testSecurityLoggingRetrievalRateLimited");
483             // Turn logging off.
484             executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
485         } finally {
486             // Restore stay awake setting.
487             if (stayAwake != null) {
488                 getDevice().setSetting("global", "stay_on_while_plugged_in", stayAwake);
489             }
490         }
491     }
492 
testSecurityLoggingEnabledLogged()493     public void testSecurityLoggingEnabledLogged() throws Exception {
494         if (!mHasFeature) {
495             return;
496         }
497         assertMetricsLogged(getDevice(), () -> {
498             executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
499             executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
500         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SECURITY_LOGGING_ENABLED_VALUE)
501                 .setAdminPackageName(DEVICE_OWNER_PKG)
502                 .setBoolean(true)
503                 .build(),
504             new DevicePolicyEventWrapper.Builder(EventId.SET_SECURITY_LOGGING_ENABLED_VALUE)
505                     .setAdminPackageName(DEVICE_OWNER_PKG)
506                     .setBoolean(false)
507                     .build());
508 
509     }
510 
generateDummySecurityLogs()511     private void generateDummySecurityLogs() throws DeviceNotAvailableException {
512         // Trigger security events of type TAG_ADB_SHELL_CMD.
513         for (int i = 0; i < SECURITY_EVENTS_BATCH_SIZE; i++) {
514             getDevice().executeShellCommand("echo just_testing_" + i);
515         }
516     }
517 
testNetworkLoggingWithTwoUsers()518     public void testNetworkLoggingWithTwoUsers() throws Exception {
519         if (!mHasFeature || !canCreateAdditionalUsers(1)) {
520             return;
521         }
522 
523         final int userId = createUser();
524         try {
525             // The feature can be enabled, but in a "paused" state. Attempting to retrieve logs
526             // should throw security exception.
527             executeDeviceTestMethod(".NetworkLoggingTest",
528                     "testRetrievingNetworkLogsThrowsSecurityException");
529         } finally {
530             removeUser(userId);
531         }
532     }
533 
testNetworkLoggingWithSingleUser()534     public void testNetworkLoggingWithSingleUser() throws Exception {
535         if (!mHasFeature) {
536             return;
537         }
538         executeDeviceTestMethod(".NetworkLoggingTest", "testProvidingWrongBatchTokenReturnsNull");
539         executeDeviceTestMethod(".NetworkLoggingTest", "testNetworkLoggingAndRetrieval",
540                 Collections.singletonMap(ARG_NETWORK_LOGGING_BATCH_COUNT, Integer.toString(1)));
541     }
542 
testNetworkLogging_multipleBatches()543     public void testNetworkLogging_multipleBatches() throws Exception {
544         if (!mHasFeature) {
545             return;
546         }
547         executeDeviceTestMethod(".NetworkLoggingTest", "testNetworkLoggingAndRetrieval",
548                 Collections.singletonMap(ARG_NETWORK_LOGGING_BATCH_COUNT, Integer.toString(2)));
549     }
550 
testNetworkLogging_rebootResetsId()551     public void testNetworkLogging_rebootResetsId() throws Exception {
552         if (!mHasFeature) {
553             return;
554         }
555         // First batch: retrieve and verify the events.
556         executeDeviceTestMethod(".NetworkLoggingTest", "testNetworkLoggingAndRetrieval",
557                 Collections.singletonMap(ARG_NETWORK_LOGGING_BATCH_COUNT, Integer.toString(1)));
558         // Reboot the device, so the security event IDs are re-set.
559         rebootAndWaitUntilReady();
560         // Make sure BOOT_COMPLETED is completed before proceeding.
561         waitForBroadcastIdle();
562         // First batch after reboot: retrieve and verify the events.
563         executeDeviceTestMethod(".NetworkLoggingTest", "testNetworkLoggingAndRetrieval",
564                 Collections.singletonMap(ARG_NETWORK_LOGGING_BATCH_COUNT, Integer.toString(1)));
565     }
566 
567 
testSetAffiliationId_IllegalArgumentException()568     public void testSetAffiliationId_IllegalArgumentException() throws Exception {
569         if (!mHasFeature) {
570             return;
571         }
572         executeDeviceTestMethod(".AffiliationTest", "testSetAffiliationId_null");
573         executeDeviceTestMethod(".AffiliationTest", "testSetAffiliationId_containsEmptyString");
574     }
575 
testSystemUpdatePolicy()576     public void testSystemUpdatePolicy() throws Exception {
577         if (!mHasFeature) {
578             return;
579         }
580         // Disabled due to 145932189
581         // executeDeviceOwnerTest("SystemUpdatePolicyTest");
582     }
583 
testSetSystemUpdatePolicyLogged()584     public void testSetSystemUpdatePolicyLogged() throws Exception {
585         if (!mHasFeature) {
586             return;
587         }
588         // Disabled due to 145932189
589         /*
590         assertMetricsLogged(getDevice(), () -> {
591             executeDeviceTestMethod(".SystemUpdatePolicyTest", "testSetAutomaticInstallPolicy");
592         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SYSTEM_UPDATE_POLICY_VALUE)
593                     .setAdminPackageName(DEVICE_OWNER_PKG)
594                     .setInt(TYPE_INSTALL_AUTOMATIC)
595                     .build());
596         assertMetricsLogged(getDevice(), () -> {
597             executeDeviceTestMethod(".SystemUpdatePolicyTest", "testSetWindowedInstallPolicy");
598         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SYSTEM_UPDATE_POLICY_VALUE)
599                     .setAdminPackageName(DEVICE_OWNER_PKG)
600                     .setInt(TYPE_INSTALL_WINDOWED)
601                     .build());
602         assertMetricsLogged(getDevice(), () -> {
603             executeDeviceTestMethod(".SystemUpdatePolicyTest", "testSetPostponeInstallPolicy");
604         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SYSTEM_UPDATE_POLICY_VALUE)
605                     .setAdminPackageName(DEVICE_OWNER_PKG)
606                     .setInt(TYPE_POSTPONE)
607                     .build());
608         assertMetricsLogged(getDevice(), () -> {
609             executeDeviceTestMethod(".SystemUpdatePolicyTest", "testSetEmptytInstallPolicy");
610         }, new DevicePolicyEventWrapper.Builder(EventId.SET_SYSTEM_UPDATE_POLICY_VALUE)
611                     .setAdminPackageName(DEVICE_OWNER_PKG)
612                     .setInt(TYPE_NONE)
613                     .build());
614         */
615     }
616 
testWifiConfigLockdown()617     public void testWifiConfigLockdown() throws Exception {
618         final boolean hasWifi = hasDeviceFeature("android.hardware.wifi");
619         if (hasWifi && mHasFeature) {
620             String oldLocationSetting = getDevice().getSetting(SETTINGS_SECURE, LOCATION_MODE);
621             try {
622                 installAppAsUser(WIFI_CONFIG_CREATOR_APK, mPrimaryUserId);
623                 getDevice().setSetting(SETTINGS_SECURE, LOCATION_MODE, LOCATION_MODE_HIGH_ACCURACY);
624                 executeDeviceOwnerTest("WifiConfigLockdownTest");
625             } finally {
626                 getDevice().uninstallPackage(WIFI_CONFIG_CREATOR_PKG);
627                 getDevice().setSetting(SETTINGS_SECURE, LOCATION_MODE, oldLocationSetting);
628             }
629         }
630     }
631 
632     /**
633      * Execute WifiSetHttpProxyTest as device owner.
634      */
testWifiSetHttpProxyTest()635     public void testWifiSetHttpProxyTest() throws Exception {
636         final boolean hasWifi = hasDeviceFeature("android.hardware.wifi");
637         if (hasWifi && mHasFeature) {
638             executeDeviceOwnerTest("WifiSetHttpProxyTest");
639         }
640     }
641 
testCannotSetDeviceOwnerAgain()642     public void testCannotSetDeviceOwnerAgain() throws Exception {
643         if (!mHasFeature) {
644             return;
645         }
646         // verify that we can't set the same admin receiver as device owner again
647         assertFalse(setDeviceOwner(
648                 DEVICE_OWNER_PKG + "/" + ADMIN_RECEIVER_TEST_CLASS, mPrimaryUserId,
649                 /*expectFailure*/ true));
650 
651         // verify that we can't set a different admin receiver as device owner
652         try {
653             installAppAsUser(MANAGED_PROFILE_APK, mPrimaryUserId);
654             assertFalse(setDeviceOwner(
655                     MANAGED_PROFILE_PKG + "/" + MANAGED_PROFILE_ADMIN, mPrimaryUserId,
656                     /*expectFailure*/ true));
657         } finally {
658             // Remove the device owner in case the test fails.
659             removeAdmin(MANAGED_PROFILE_PKG + "/" + MANAGED_PROFILE_ADMIN, mPrimaryUserId);
660             getDevice().uninstallPackage(MANAGED_PROFILE_PKG);
661         }
662     }
663 
664     // Execute HardwarePropertiesManagerTest as a device owner.
testHardwarePropertiesManagerAsDeviceOwner()665     public void testHardwarePropertiesManagerAsDeviceOwner() throws Exception {
666         if (!mHasFeature) {
667             return;
668         }
669 
670         executeDeviceTestMethod(".HardwarePropertiesManagerTest", "testHardwarePropertiesManager");
671     }
672 
673     // Execute VrTemperatureTest as a device owner.
testVrTemperaturesAsDeviceOwner()674     public void testVrTemperaturesAsDeviceOwner() throws Exception {
675         if (!mHasFeature) {
676             return;
677         }
678 
679         executeDeviceTestMethod(".VrTemperatureTest", "testVrTemperatures");
680     }
681 
testIsManagedDeviceProvisioningAllowed()682     public void testIsManagedDeviceProvisioningAllowed() throws Exception {
683         if (!mHasFeature) {
684             return;
685         }
686         // This case runs when DO is provisioned
687         // mHasFeature == true and provisioned, can't provision DO again.
688         executeDeviceTestMethod(".PreDeviceOwnerTest", "testIsProvisioningAllowedFalse");
689     }
690 
691     /**
692      * Can provision Managed Profile when DO is set by default if they are the same admin.
693      */
testIsManagedProfileProvisioningAllowed_deviceOwnerIsSet()694     public void testIsManagedProfileProvisioningAllowed_deviceOwnerIsSet() throws Exception {
695         if (!mHasFeature) {
696             return;
697         }
698         if (!hasDeviceFeature("android.software.managed_users")) {
699             return;
700         }
701         executeDeviceTestMethod(".PreDeviceOwnerTest",
702                 "testIsProvisioningAllowedTrueForManagedProfileAction");
703     }
704 
testAdminActionBookkeeping()705     public void testAdminActionBookkeeping() throws Exception {
706         if (!mHasFeature) {
707             return;
708         }
709         executeDeviceOwnerTest("AdminActionBookkeepingTest");
710         assertMetricsLogged(getDevice(), () -> {
711             executeDeviceTestMethod(".AdminActionBookkeepingTest", "testRetrieveSecurityLogs");
712         }, new DevicePolicyEventWrapper.Builder(EventId.RETRIEVE_SECURITY_LOGS_VALUE)
713                     .setAdminPackageName(DEVICE_OWNER_PKG)
714                     .build(),
715             new DevicePolicyEventWrapper.Builder(EventId.RETRIEVE_PRE_REBOOT_SECURITY_LOGS_VALUE)
716                     .setAdminPackageName(DEVICE_OWNER_PKG)
717                     .build());
718         assertMetricsLogged(getDevice(), () -> {
719             executeDeviceTestMethod(".AdminActionBookkeepingTest", "testRequestBugreport");
720         }, new DevicePolicyEventWrapper.Builder(EventId.REQUEST_BUGREPORT_VALUE)
721                 .setAdminPackageName(DEVICE_OWNER_PKG)
722                 .build());
723     }
724 
testBluetoothRestriction()725     public void testBluetoothRestriction() throws Exception {
726         if (!mHasFeature) {
727             return;
728         }
729         executeDeviceOwnerTest("BluetoothRestrictionTest");
730     }
731 
testSetTime()732     public void testSetTime() throws Exception {
733         if (!mHasFeature) {
734             return;
735         }
736         executeDeviceOwnerTest("SetTimeTest");
737     }
738 
testDeviceOwnerProvisioning()739     public void testDeviceOwnerProvisioning() throws Exception {
740         if (!mHasFeature) {
741             return;
742         }
743         executeDeviceOwnerTest("DeviceOwnerProvisioningTest");
744     }
745 
testDisallowFactoryReset()746     public void testDisallowFactoryReset() throws Exception {
747         if (!mHasFeature) {
748             return;
749         }
750         int adminVersion = 24;
751         changeUserRestrictionOrFail("no_factory_reset", true, mPrimaryUserId,
752                 DEVICE_OWNER_PKG);
753         try {
754             installAppAsUser(DeviceAdminHelper.getDeviceAdminApkFileName(adminVersion),
755                     mPrimaryUserId);
756             setDeviceAdmin(DeviceAdminHelper.getAdminReceiverComponent(adminVersion),
757                     mPrimaryUserId);
758             runDeviceTestsAsUser(
759                     DeviceAdminHelper.getDeviceAdminApkPackage(adminVersion),
760                     DeviceAdminHelper.getDeviceAdminJavaPackage() + ".WipeDataTest",
761                     "testWipeDataThrowsSecurityException", mPrimaryUserId);
762         } finally {
763             removeAdmin(DeviceAdminHelper.getAdminReceiverComponent(adminVersion), mPrimaryUserId);
764             getDevice().uninstallPackage(DeviceAdminHelper.getDeviceAdminApkPackage(adminVersion));
765         }
766     }
767 
testBackupServiceEnabling()768     public void testBackupServiceEnabling() throws Exception {
769         final boolean hasBackupService = getDevice().hasFeature(FEATURE_BACKUP);
770         // The backup service cannot be enabled if the backup feature is not supported.
771         if (!mHasFeature || !hasBackupService) {
772             return;
773         }
774         executeDeviceTestMethod(".BackupServicePoliciesTest",
775                 "testEnablingAndDisablingBackupService");
776     }
777 
testDeviceOwnerCanGetDeviceIdentifiers()778     public void testDeviceOwnerCanGetDeviceIdentifiers() throws Exception {
779         // The Device Owner should have access to all device identifiers.
780         if (!mHasFeature) {
781             return;
782         }
783         executeDeviceTestMethod(".DeviceIdentifiersTest",
784                 "testDeviceOwnerCanGetDeviceIdentifiersWithPermission");
785     }
786 
testDeviceOwnerCannotGetDeviceIdentifiersWithoutPermission()787     public void testDeviceOwnerCannotGetDeviceIdentifiersWithoutPermission() throws Exception {
788         // The Device Owner must have the READ_PHONE_STATE permission to get access to the device
789         // identifiers.
790         if (!mHasFeature) {
791             return;
792         }
793         // Revoke the READ_PHONE_STATE permission to ensure the device owner cannot access device
794         // identifiers without consent.
795         getDevice().executeShellCommand(
796                 "pm revoke " + DEVICE_OWNER_PKG + " android.permission.READ_PHONE_STATE");
797         executeDeviceTestMethod(".DeviceIdentifiersTest",
798                 "testDeviceOwnerCannotGetDeviceIdentifiersWithoutPermission");
799     }
800 
testPackageInstallCache()801     public void testPackageInstallCache() throws Exception {
802         if (!mHasFeature) {
803             return;
804         }
805         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
806         final File apk = buildHelper.getTestFile(TEST_APP_APK);
807         try {
808             getDevice().uninstallPackage(TEST_APP_PKG);
809             assertTrue(getDevice().pushFile(apk, TEST_APP_LOCATION + apk.getName()));
810 
811             // Install the package in primary user
812             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
813                     "testPackageInstall", mPrimaryUserId);
814 
815             assertMetricsLogged(getDevice(), () -> {
816                 runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
817                         "testKeepPackageCache", mPrimaryUserId);
818             }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEEP_UNINSTALLED_PACKAGES_VALUE)
819                     .setAdminPackageName(DEVICE_OWNER_PKG)
820                     .setBoolean(false)
821                     .setStrings(TEST_APP_PKG)
822                     .build());
823 
824             // Remove the package in primary user
825             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
826                     "testPackageUninstall", mPrimaryUserId);
827 
828             assertMetricsLogged(getDevice(), () -> {
829                 // Should be able to enable the cached package in primary user
830                 runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
831                         "testInstallExistingPackage", mPrimaryUserId);
832             }, new DevicePolicyEventWrapper.Builder(EventId.INSTALL_EXISTING_PACKAGE_VALUE)
833                     .setAdminPackageName(DEVICE_OWNER_PKG)
834                     .setBoolean(false)
835                     .setStrings(TEST_APP_PKG)
836                     .build());
837         } finally {
838             String command = "rm " + TEST_APP_LOCATION + apk.getName();
839             getDevice().executeShellCommand(command);
840             getDevice().uninstallPackage(TEST_APP_PKG);
841         }
842     }
843 
testPackageInstallCache_multiUser()844     public void testPackageInstallCache_multiUser() throws Exception {
845         if (!mHasFeature || !canCreateAdditionalUsers(1)) {
846             return;
847         }
848         final int userId = createAffiliatedSecondaryUser();
849         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
850         final File apk = buildHelper.getTestFile(TEST_APP_APK);
851         try {
852             getDevice().uninstallPackage(TEST_APP_PKG);
853             assertTrue(getDevice().pushFile(apk, TEST_APP_LOCATION + apk.getName()));
854 
855             // Install the package in primary user
856             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
857                     "testPackageInstall", mPrimaryUserId);
858 
859             // Should be able to enable the package in secondary user
860             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
861                     "testInstallExistingPackage", userId);
862 
863             // Remove the package in both user
864             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
865                     "testPackageUninstall", mPrimaryUserId);
866             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
867                     "testPackageUninstall", userId);
868 
869             // Install the package in secondary user
870             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
871                     "testPackageInstall", userId);
872 
873             // Should be able to enable the package in primary user
874             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
875                     "testInstallExistingPackage", mPrimaryUserId);
876 
877             // Keep the package in cache
878             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
879                     "testKeepPackageCache", mPrimaryUserId);
880 
881             // Remove the package in both user
882             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
883                     "testPackageUninstall", mPrimaryUserId);
884             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
885                     "testPackageUninstall", userId);
886 
887             // Should be able to enable the cached package in both users
888             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
889                     "testInstallExistingPackage", userId);
890             runDeviceTestsAsUser(DEVICE_OWNER_PKG, ".PackageInstallTest",
891                     "testInstallExistingPackage", mPrimaryUserId);
892         } finally {
893             String command = "rm " + TEST_APP_LOCATION + apk.getName();
894             getDevice().executeShellCommand(command);
895             getDevice().uninstallPackage(TEST_APP_PKG);
896         }
897     }
898 
testAirplaneModeRestriction()899     public void testAirplaneModeRestriction() throws Exception {
900         if (!mHasFeature) {
901             return;
902         }
903         executeDeviceOwnerTest("AirplaneModeRestrictionTest");
904     }
905 
testOverrideApn()906     public void testOverrideApn() throws Exception {
907         if (!mHasFeature || !hasDeviceFeature("android.hardware.telephony")) {
908             return;
909         }
910         executeDeviceOwnerTest("OverrideApnTest");
911     }
912 
testPrivateDnsPolicy()913     public void testPrivateDnsPolicy() throws Exception {
914         if (!mHasFeature) {
915             return;
916         }
917         executeDeviceOwnerTest("PrivateDnsPolicyTest");
918     }
919 
testInstallUpdate()920     public void testInstallUpdate() throws Exception {
921         if (!mHasFeature) {
922             return;
923         }
924 
925         pushUpdateFileToDevice("notZip.zi");
926         pushUpdateFileToDevice("empty.zip");
927         pushUpdateFileToDevice("wrongPayload.zip");
928         pushUpdateFileToDevice("wrongHash.zip");
929         pushUpdateFileToDevice("wrongSize.zip");
930         executeDeviceOwnerTest("InstallUpdateTest");
931     }
932 
testInstallUpdateLogged()933     public void testInstallUpdateLogged() throws Exception {
934         if (!mHasFeature || !isDeviceAb()) {
935             return;
936         }
937         pushUpdateFileToDevice("wrongHash.zip");
938         assertMetricsLogged(getDevice(), () -> {
939             executeDeviceTestMethod(".InstallUpdateTest", "testInstallUpdate_failWrongHash");
940         }, new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_VALUE)
941                     .setAdminPackageName(DEVICE_OWNER_PKG)
942                     .setBoolean(/* isDeviceAb */ true)
943                     .build(),
944             new DevicePolicyEventWrapper.Builder(EventId.INSTALL_SYSTEM_UPDATE_ERROR_VALUE)
945                     .setInt(UPDATE_ERROR_UPDATE_FILE_INVALID)
946                     .build());
947     }
948 
isDeviceAb()949     private boolean isDeviceAb() throws DeviceNotAvailableException {
950         final String result = getDevice().executeShellCommand("getprop ro.build.ab_update").trim();
951         return "true".equalsIgnoreCase(result);
952     }
953 
pushUpdateFileToDevice(String fileName)954     private void pushUpdateFileToDevice(String fileName)
955             throws IOException, DeviceNotAvailableException {
956         File file = File.createTempFile(
957                 fileName.split("\\.")[0], "." + fileName.split("\\.")[1]);
958         try (OutputStream outputStream = new FileOutputStream(file)) {
959             InputStream inputStream = getClass().getResourceAsStream("/" + fileName);
960             ByteStreams.copy(inputStream, outputStream);
961         }
962 
963         getDevice().pushFile(file, TEST_UPDATE_LOCATION + "/" + fileName);
964         file.delete();
965     }
966 
testSetKeyguardDisabledLogged()967     public void testSetKeyguardDisabledLogged() throws Exception {
968         if (!mHasFeature) {
969             return;
970         }
971         assertMetricsLogged(getDevice(), () -> {
972             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testSetKeyguardDisabledLogged");
973         }, new DevicePolicyEventWrapper.Builder(EventId.SET_KEYGUARD_DISABLED_VALUE)
974                 .setAdminPackageName(DEVICE_OWNER_PKG)
975                 .build());
976     }
977 
testSetStatusBarDisabledLogged()978     public void testSetStatusBarDisabledLogged() throws Exception {
979         if (!mHasFeature) {
980             return;
981         }
982         assertMetricsLogged(getDevice(), () -> {
983             executeDeviceTestMethod(".DevicePolicyLoggingTest", "testSetStatusBarDisabledLogged");
984         }, new DevicePolicyEventWrapper.Builder(EventId.SET_STATUS_BAR_DISABLED_VALUE)
985                     .setAdminPackageName(DEVICE_OWNER_PKG)
986                     .setBoolean(true)
987                     .build(),
988             new DevicePolicyEventWrapper.Builder(EventId.SET_STATUS_BAR_DISABLED_VALUE)
989                     .setAdminPackageName(DEVICE_OWNER_PKG)
990                     .setBoolean(true)
991                     .build());
992     }
993 
testNoHiddenActivityFoundTest()994     public void testNoHiddenActivityFoundTest() throws Exception {
995         if (!mHasFeature) {
996             return;
997         }
998         try {
999             // Install app to primary user
1000             installAppAsUser(BaseLauncherAppsTest.LAUNCHER_TESTS_APK, mPrimaryUserId);
1001             installAppAsUser(BaseLauncherAppsTest.LAUNCHER_TESTS_SUPPORT_APK, mPrimaryUserId);
1002             installAppAsUser(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK, mPrimaryUserId);
1003 
1004             // Run test to check if launcher api shows hidden app
1005             String mSerialNumber = Integer.toString(getUserSerialNumber(USER_SYSTEM));
1006             runDeviceTestsAsUser(BaseLauncherAppsTest.LAUNCHER_TESTS_PKG,
1007                     BaseLauncherAppsTest.LAUNCHER_TESTS_CLASS,
1008                     "testDoPoNoTestAppInjectedActivityFound",
1009                     mPrimaryUserId, Collections.singletonMap(BaseLauncherAppsTest.PARAM_TEST_USER,
1010                             mSerialNumber));
1011         } finally {
1012             getDevice().uninstallPackage(LAUNCHER_TESTS_HAS_LAUNCHER_ACTIVITY_APK);
1013             getDevice().uninstallPackage(BaseLauncherAppsTest.LAUNCHER_TESTS_SUPPORT_APK);
1014             getDevice().uninstallPackage(BaseLauncherAppsTest.LAUNCHER_TESTS_APK);
1015         }
1016     }
1017 
executeDeviceOwnerTest(String testClassName)1018     private void executeDeviceOwnerTest(String testClassName) throws Exception {
1019         if (!mHasFeature) {
1020             return;
1021         }
1022         String testClass = DEVICE_OWNER_PKG + "." + testClassName;
1023         runDeviceTestsAsUser(DEVICE_OWNER_PKG, testClass, mPrimaryUserId);
1024     }
1025 
executeDeviceTestMethod(String className, String testName)1026     private void executeDeviceTestMethod(String className, String testName) throws Exception {
1027         if (!mHasFeature) {
1028             return;
1029         }
1030         runDeviceTestsAsUser(DEVICE_OWNER_PKG, className, testName,
1031                 /* deviceOwnerUserId */ mPrimaryUserId);
1032     }
1033 
createAffiliatedSecondaryUser()1034     private int createAffiliatedSecondaryUser() throws Exception {
1035         final int userId = createUser();
1036         installAppAsUser(INTENT_RECEIVER_APK, userId);
1037         installAppAsUser(DEVICE_OWNER_APK, userId);
1038         setProfileOwnerOrFail(DEVICE_OWNER_COMPONENT, userId);
1039 
1040         switchUser(userId);
1041         waitForBroadcastIdle();
1042         wakeupAndDismissKeyguard();
1043 
1044         // Setting the same affiliation ids on both users
1045         runDeviceTestsAsUser(
1046                 DEVICE_OWNER_PKG, ".AffiliationTest", "testSetAffiliationId1", mPrimaryUserId);
1047         runDeviceTestsAsUser(
1048                 DEVICE_OWNER_PKG, ".AffiliationTest", "testSetAffiliationId1", userId);
1049         return userId;
1050     }
1051 
executeDeviceTestMethod(String className, String testName, Map<String, String> params)1052     private void executeDeviceTestMethod(String className, String testName,
1053             Map<String, String> params) throws Exception {
1054         if (!mHasFeature) {
1055             return;
1056         }
1057         runDeviceTestsAsUser(DEVICE_OWNER_PKG, className, testName,
1058                 /* deviceOwnerUserId */ mPrimaryUserId, params);
1059     }
1060 
assertNewUserStopped()1061     private void assertNewUserStopped() throws Exception {
1062         List<Integer> newUsers = getUsersCreatedByTests();
1063         assertEquals(1, newUsers.size());
1064         int newUserId = newUsers.get(0);
1065 
1066         assertFalse(getDevice().isUserRunning(newUserId));
1067     }
1068 }
1069