Add host side test for secondary user rollback

Run RollbackTest#testBasic only under a secondary user.

The host-driven test adds a new user and then installs the TEST (not the
test app) for that new user.
Note: this was the missing step in the previous attempt to test
RollbackTest under a secondary user.

Test: atest SecondaryUserRollbackTest
Test: test failed when multiuser support was removed from rollback
manager
Test: adb shell pm list packages --user 11 | grep rollback while running
the test in order to make sure the test is installing packages for the right user

Bug: 133852817
Bug: 129747710
Change-Id: Id1e54769cc2a9631d1464c07bad2b685f78689bc
diff --git a/tests/RollbackTest/Android.bp b/tests/RollbackTest/Android.bp
index aec40558..5172935 100644
--- a/tests/RollbackTest/Android.bp
+++ b/tests/RollbackTest/Android.bp
@@ -105,3 +105,11 @@
     test_suites: ["general-tests"],
     test_config: "StagedRollbackTest.xml",
 }
+
+java_test_host {
+    name: "SecondaryUserRollbackTest",
+    srcs: ["SecondaryUserRollbackTest/src/**/*.java"],
+    libs: ["tradefed"],
+    test_suites: ["general-tests"],
+    test_config: "SecondaryUserRollbackTest.xml",
+}
diff --git a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
index eac173e..21b9869 100644
--- a/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
+++ b/tests/RollbackTest/RollbackTest/src/com/android/tests/rollback/RollbackTest.java
@@ -147,9 +147,15 @@
             // TODO: Race condition between the timeout and when the broadcast is
             // received could lead to test flakiness.
             Intent broadcast = broadcastReceiver.poll(5, TimeUnit.SECONDS);
-            assertNotNull(broadcast);
-            assertNull(broadcastReceiver.poll(0, TimeUnit.SECONDS));
-
+            if (context.getUser().isSystem()) {
+                // Only system user should receive those broadcasts.
+                assertNotNull(broadcast);
+                assertNull(broadcastReceiver.poll(0, TimeUnit.SECONDS));
+            } else {
+                // This is in case the test was running under a secondary user, in which case
+                // the broadcast won't be received here.
+                assertNull(broadcast);
+            }
             // Verify the recent rollback has been recorded.
             rollback = getUniqueRollbackInfoForPackage(
                     rm.getRecentlyCommittedRollbacks(), TEST_APP_A);
diff --git a/tests/RollbackTest/SecondaryUserRollbackTest.xml b/tests/RollbackTest/SecondaryUserRollbackTest.xml
new file mode 100644
index 0000000..ad376101
--- /dev/null
+++ b/tests/RollbackTest/SecondaryUserRollbackTest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Runs the rollback test from a secondary user">
+    <option name="test-suite-tag" value="SecondaryUserRollbackTest" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="RollbackTest.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.HostTest" >
+        <option name="class" value="com.android.tests.rollback.host.SecondaryUserRollbackTest" />
+    </test>
+</configuration>
diff --git a/tests/RollbackTest/SecondaryUserRollbackTest/src/com/android/tests/rollback/host/SecondaryUserRollbackTest.java b/tests/RollbackTest/SecondaryUserRollbackTest/src/com/android/tests/rollback/host/SecondaryUserRollbackTest.java
new file mode 100644
index 0000000..11fe964
--- /dev/null
+++ b/tests/RollbackTest/SecondaryUserRollbackTest/src/com/android/tests/rollback/host/SecondaryUserRollbackTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.tests.rollback.host;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Runs rollback tests from a secondary user.
+ */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class SecondaryUserRollbackTest extends BaseHostJUnit4Test {
+    private static final int SYSTEM_USER_ID = 0;
+    // The user that was running originally when the test starts.
+    private int mOriginalUser = SYSTEM_USER_ID;
+    private int mSecondaryUserId = -1;
+    private static final long SWITCH_USER_COMPLETED_NUMBER_OF_POLLS = 60;
+    private static final long SWITCH_USER_COMPLETED_POLL_INTERVAL_IN_MILLIS = 1000;
+
+
+    @After
+    public void tearDown() throws Exception {
+        getDevice().switchUser(mOriginalUser);
+        getDevice().executeShellCommand("pm uninstall com.android.tests.rollback.testapp.A");
+        getDevice().executeShellCommand("pm uninstall com.android.tests.rollback.testapp.B");
+        removeSecondaryUserIfNecessary();
+    }
+
+    @Before
+    public void setup() throws Exception {
+        createAndSwitchToSecondaryUserIfNecessary();
+        installPackageAsUser("RollbackTest.apk", true, mSecondaryUserId, "--user current");
+    }
+
+    @Test
+    public void testBasic() throws Exception {
+        assertTrue(runDeviceTests("com.android.tests.rollback",
+                "com.android.tests.rollback.RollbackTest",
+                "testBasic"));
+    }
+
+    private void removeSecondaryUserIfNecessary() throws Exception {
+        if (mSecondaryUserId != -1) {
+            getDevice().removeUser(mSecondaryUserId);
+            mSecondaryUserId = -1;
+        }
+    }
+
+    private void createAndSwitchToSecondaryUserIfNecessary() throws Exception {
+        if (mSecondaryUserId == -1) {
+            mOriginalUser = getDevice().getCurrentUser();
+            mSecondaryUserId = getDevice().createUser("SecondaryUserRollbackTest_User");
+            assertTrue(getDevice().switchUser(mSecondaryUserId));
+            // give time for user to be switched
+            waitForSwitchUserCompleted(mSecondaryUserId);
+        }
+    }
+
+    private void waitForSwitchUserCompleted(int userId) throws Exception {
+        for (int i = 0; i < SWITCH_USER_COMPLETED_NUMBER_OF_POLLS; ++i) {
+            String logs = getDevice().executeAdbCommand("logcat", "-v", "brief", "-d",
+                    "ActivityManager:D");
+            if (logs.contains("Posting BOOT_COMPLETED user #" + userId)) {
+                return;
+            }
+            Thread.sleep(SWITCH_USER_COMPLETED_POLL_INTERVAL_IN_MILLIS);
+        }
+        fail("User switch to user " + userId + " timed out");
+    }
+}
diff --git a/tests/RollbackTest/TEST_MAPPING b/tests/RollbackTest/TEST_MAPPING
index 6be93a0..7ae03e6 100644
--- a/tests/RollbackTest/TEST_MAPPING
+++ b/tests/RollbackTest/TEST_MAPPING
@@ -5,6 +5,9 @@
     },
     {
       "name": "StagedRollbackTest"
+    },
+    {
+      "name": "SecondaryUserRollbackTest"
     }
   ]
 }