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