diff options
| author | 2018-11-03 03:35:26 +0000 | |
|---|---|---|
| committer | 2018-11-03 03:35:26 +0000 | |
| commit | 89ff22fa57cedfc40d0c7383fc70a22abd667835 (patch) | |
| tree | 8c7956c5b94d3a2540743084b33493245aa705a9 | |
| parent | 492b35cd05ebdccd2851b436d455f69665dbb046 (diff) | |
| parent | 74ccec25d58b1dbe58789bcd046bf93569e719bd (diff) | |
Merge "Move ActivityManager tests to WmTests"
| -rw-r--r-- | services/core/java/com/android/server/am/PersisterQueue.java | 5 | ||||
| -rw-r--r-- | services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java | 2 | ||||
| -rw-r--r-- | services/tests/wmtests/Android.mk | 8 | ||||
| -rw-r--r-- | services/tests/wmtests/AndroidManifest.xml | 16 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityDisplayTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityDisplayTests.java) | 5 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityManagerInternalTest.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java) | 28 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityManagerServiceTest.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java) | 30 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityManagerTest.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java) | 16 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityOptionsTest.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityOptionsTest.java) | 17 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityRecordTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityRecordTests.java) | 34 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityStackSupervisorTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityStackSupervisorTests.java) | 54 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityStackTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityStackTests.java) | 180 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityStartControllerTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityStartControllerTests.java) | 14 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityStartInterceptorTest.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityStartInterceptorTest.java) | 16 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityStarterTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityStarterTests.java) | 38 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ActivityTestsBase.java (renamed from services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java) | 49 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/AppErrorDialogTest.java (renamed from services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java) | 13 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/AssistDataRequesterTest.java (renamed from services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java) | 93 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/BroadcastRecordTest.java (renamed from services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java) | 5 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/ClientLifecycleManagerTests.java (renamed from services/tests/servicestests/src/com/android/server/am/ClientLifecycleManagerTests.java) | 23 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/CoreSettingsObserverTest.java (renamed from services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java) | 43 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/DummyAmTests.java | 46 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java (renamed from services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java) | 26 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/LaunchParamsControllerTests.java (renamed from services/tests/servicestests/src/com/android/server/am/LaunchParamsControllerTests.java) | 24 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/LockTaskControllerTest.java (renamed from services/tests/servicestests/src/com/android/server/am/LockTaskControllerTest.java) | 44 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/MemoryStatUtilTest.java (renamed from services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java) | 97 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java (renamed from services/tests/servicestests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java) | 12 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/PersisterQueueTests.java (renamed from services/tests/servicestests/src/com/android/server/am/PersisterQueueTests.java) | 34 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/RecentTasksTest.java (renamed from services/tests/servicestests/src/com/android/server/am/RecentTasksTest.java) | 428 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/RecentsAnimationTest.java (renamed from services/tests/servicestests/src/com/android/server/am/RecentsAnimationTest.java) | 39 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/RunningTasksTest.java (renamed from services/tests/servicestests/src/com/android/server/am/RunningTasksTest.java) | 29 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/SafeActivityOptionsTest.java (renamed from services/tests/servicestests/src/com/android/server/am/SafeActivityOptionsTest.java) | 11 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/TaskLaunchParamsModifierTests.java (renamed from services/tests/servicestests/src/com/android/server/am/TaskLaunchParamsModifierTests.java) | 18 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/TaskPersisterTest.java (renamed from services/tests/servicestests/src/com/android/server/am/TaskPersisterTest.java) | 32 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/TaskRecordTests.java (renamed from services/tests/servicestests/src/com/android/server/am/TaskRecordTests.java) | 11 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/TaskStackChangedListenerTest.java (renamed from services/tests/servicestests/src/com/android/server/am/TaskStackChangedListenerTest.java) | 58 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/am/UserControllerTest.java (renamed from services/tests/servicestests/src/com/android/server/am/UserControllerTest.java) | 101 | ||||
| -rw-r--r-- | services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java | 81 |
38 files changed, 888 insertions, 892 deletions
diff --git a/services/core/java/com/android/server/am/PersisterQueue.java b/services/core/java/com/android/server/am/PersisterQueue.java index 60ea0faaffee..0bcc3b5a13f9 100644 --- a/services/core/java/com/android/server/am/PersisterQueue.java +++ b/services/core/java/com/android/server/am/PersisterQueue.java @@ -171,6 +171,11 @@ class PersisterQueue { mListeners.add(listener); } + @VisibleForTesting + boolean removeListener(Listener listener) { + return mListeners.remove(listener); + } + private void processNextItem() throws InterruptedException { // This part is extracted into a method so that the GC can clearly see the end of the // scope of the variable 'item'. If this part was in the loop in LazyTaskWriterThread, the diff --git a/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java b/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java index 1222b59e92b9..69db38438609 100644 --- a/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java +++ b/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java @@ -152,7 +152,7 @@ public class TestHandler extends Handler { @Override public int compareTo(MsgInfo o) { - return (int) (sendTime - o.sendTime); + return Long.compare(sendTime, o.sendTime); } @Override diff --git a/services/tests/wmtests/Android.mk b/services/tests/wmtests/Android.mk index c095ae0dd2ff..dd656c30466e 100644 --- a/services/tests/wmtests/Android.mk +++ b/services/tests/wmtests/Android.mk @@ -11,12 +11,18 @@ LOCAL_MODULE_TAGS := tests # Include all test java files. LOCAL_SRC_FILES := \ $(call all-java-files-under, src) \ - $(call all-java-files-under, ../servicestests/utils) + $(call all-java-files-under, ../servicestests/utils) \ LOCAL_STATIC_JAVA_LIBRARIES := \ + frameworks-base-testutils \ + services.core \ androidx.test.runner \ + androidx.test.rules \ mockito-target-minus-junit4 \ platform-test-annotations \ + truth-prebuilt \ + testables \ + ub-uiautomator \ LOCAL_JAVA_LIBRARIES := \ android.test.mock \ diff --git a/services/tests/wmtests/AndroidManifest.xml b/services/tests/wmtests/AndroidManifest.xml index 1fb947309028..0607eb94a1ce 100644 --- a/services/tests/wmtests/AndroidManifest.xml +++ b/services/tests/wmtests/AndroidManifest.xml @@ -22,7 +22,21 @@ android:minSdkVersion="1" android:targetSdkVersion="28" /> - <application android:testOnly="true" /> + <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> + <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> + <uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS" /> + <uses-permission android:name="android.permission.GET_TOP_ACTIVITY_INFO" /> + <uses-permission android:name="android.permission.MANAGE_USERS" /> + <uses-permission android:name="android.permission.STORAGE_INTERNAL" /> + <uses-permission android:name="android.permission.ACCESS_KEYGUARD_SECURE_STORAGE" /> + + <application android:testOnly="true"> + <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityA" /> + <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityB" /> + <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityRequestedOrientationChange" /> + <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityTaskChangeCallbacks" /> + <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityTaskDescriptionChange" /> + </application> <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner" diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityDisplayTests.java b/services/tests/wmtests/src/com/android/server/am/ActivityDisplayTests.java index 59c40673f105..e3b9e6f0c438 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityDisplayTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityDisplayTests.java @@ -32,11 +32,9 @@ import static org.mockito.Mockito.doReturn; import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; /** * Tests for the {@link ActivityDisplay} class. @@ -46,13 +44,10 @@ import org.junit.runner.RunWith; */ @SmallTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityDisplayTests extends ActivityTestsBase { @Before - @Override public void setUp() throws Exception { - super.setUp(); setupActivityTaskManagerService(); } diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java b/services/tests/wmtests/src/com/android/server/am/ActivityManagerInternalTest.java index 8c27e256456f..0e10836ae33d 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityManagerInternalTest.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -23,30 +23,18 @@ import android.app.ActivityManagerInternal; import android.os.SystemClock; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** * Test class for {@link ActivityManagerInternal}. * - * To run the tests, use - * - * runtest -c com.android.server.am.ActivityManagerInternalTest frameworks-services - * - * or the following steps: - * - * Build: m FrameworksServicesTests - * Install: adb install -r \ - * ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk - * Run: adb shell am instrument -e class com.android.server.am.ActivityManagerInternalTest -w \ - * com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner + * Build/Install/Run: + * atest WmTests:ActivityManagerInternalTest */ -@RunWith(AndroidJUnit4.class) public class ActivityManagerInternalTest { private static final int TEST_UID1 = 111; private static final int TEST_UID2 = 112; @@ -59,6 +47,7 @@ public class ActivityManagerInternalTest { private ActivityManagerService mAms; private ActivityManagerInternal mAmi; + @Before public void setUp() { MockitoAnnotations.initMocks(this); @@ -147,18 +136,19 @@ public class ActivityManagerInternalTest { private final Object mLock; private Runnable mRunnable; - boolean mNotified; + public boolean mNotified; - public CustomThread(Object lock) { + CustomThread(Object lock) { mLock = lock; } - public CustomThread(Object lock, Runnable runnable) { + CustomThread(Object lock, Runnable runnable) { super(runnable); mLock = lock; mRunnable = runnable; } + @SuppressWarnings("WaitNotInLoop") @Override public void run() { if (mRunnable != null) { @@ -168,7 +158,7 @@ public class ActivityManagerInternalTest { try { mLock.wait(); } catch (InterruptedException e) { - Thread.currentThread().interrupted(); + Thread.interrupted(); } } } diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java b/services/tests/wmtests/src/com/android/server/am/ActivityManagerServiceTest.java index 060c55d41bea..0ed076375cdc 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityManagerServiceTest.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -67,14 +67,12 @@ import android.os.SystemClock; import androidx.test.filters.FlakyTest; import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.AppOpsService; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -90,21 +88,11 @@ import java.util.function.Function; /** * Test class for {@link ActivityManagerService}. * - * To run the tests, use - * - * runtest -c com.android.server.am.ActivityManagerServiceTest frameworks-services - * - * or the following steps: - * - * Build: m FrameworksServicesTests - * Install: adb install -r \ - * ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk - * Run: adb shell am instrument -e class com.android.server.am.ActivityManagerServiceTest -w \ - * com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner + * Build/Install/Run: + * atest WmTests:ActivityManagerServiceTest */ @SmallTest @FlakyTest(bugId = 113616538) -@RunWith(AndroidJUnit4.class) public class ActivityManagerServiceTest { private static final String TAG = ActivityManagerServiceTest.class.getSimpleName(); @@ -149,6 +137,7 @@ public class ActivityManagerServiceTest { mHandlerThread.quit(); } + @SuppressWarnings("GuardedBy") @MediumTest @Test public void incrementProcStateSeqAndNotifyAppsLocked() throws Exception { @@ -175,6 +164,7 @@ public class ActivityManagerServiceTest { true); // expectNotify // Explicitly setting the seq counter for more verification. + // @SuppressWarnings("GuardedBy") mAms.mProcessList.mProcStateSeqCounter = 42; // Uid state is not moving from background to foreground or vice versa. @@ -267,6 +257,7 @@ public class ActivityManagerServiceTest { return uidRec; } + @SuppressWarnings("GuardedBy") private void verifySeqCounterAndInteractions(UidRecord uidRec, int prevState, int curState, int expectedGlobalCounter, int expectedCurProcStateSeq, int expectedBlockState, boolean expectNotify) throws Exception { @@ -277,6 +268,7 @@ public class ActivityManagerServiceTest { uidRec.setCurProcState(curState); mAms.incrementProcStateSeqAndNotifyAppsLocked(); + // @SuppressWarnings("GuardedBy") assertEquals(expectedGlobalCounter, mAms.mProcessList.mProcStateSeqCounter); assertEquals(expectedCurProcStateSeq, uidRec.curProcStateSeq); @@ -561,8 +553,8 @@ public class ActivityManagerServiceTest { ActivityManager.PROCESS_STATE_SERVICE, ActivityManager.PROCESS_STATE_RECEIVER }; - final ArrayList<UidRecord.ChangeItem> pendingItemsForUids - = new ArrayList<>(changesForPendingItems.length); + final ArrayList<UidRecord.ChangeItem> pendingItemsForUids = + new ArrayList<>(changesForPendingItems.length); for (int i = 0; i < changesForPendingItems.length; ++i) { final UidRecord.ChangeItem item = new UidRecord.ChangeItem(); item.uid = i; @@ -621,7 +613,7 @@ public class ActivityManagerServiceTest { } mAms.mPendingUidChanges.addAll(pendingItemsForUids); mAms.dispatchUidsChanged(); - assertEquals("validateUids should be empty, validateUids: " + mAms.mValidateUids, + assertEquals("validateUids should be empty, size=" + mAms.mValidateUids.size(), 0, mAms.mValidateUids.size()); } @@ -775,7 +767,7 @@ public class ActivityManagerServiceTest { mAms.mActiveUids.clear(); } - private class TestHandler extends Handler { + private static class TestHandler extends Handler { private static final long WAIT_FOR_MSG_TIMEOUT_MS = 4000; // 4 sec private static final long WAIT_FOR_MSG_INTERVAL_MS = 400; // 0.4 sec diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java b/services/tests/wmtests/src/com/android/server/am/ActivityManagerTest.java index 2dfb3751c021..1215ec401f5b 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityManagerTest.java @@ -27,33 +27,33 @@ import android.os.RemoteException; import android.os.UserHandle; import android.platform.test.annotations.Presubmit; +import androidx.test.filters.FlakyTest; + import org.junit.Before; import org.junit.Test; import java.util.List; -import androidx.test.filters.FlakyTest; - /** * Tests for {@link ActivityManager}. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.ActivityManagerTest + * atest WmTests:ActivityManagerTest */ -@Presubmit @FlakyTest(detail = "Promote to presubmit if stable") +@Presubmit public class ActivityManagerTest { - private IActivityManager service; + private IActivityManager mService; @Before public void setUp() throws Exception { - service = ActivityManager.getService(); + mService = ActivityManager.getService(); } @Test public void testTaskIdsForRunningUsers() throws RemoteException { - int[] runningUserIds = service.getRunningUserIds(); + int[] runningUserIds = mService.getRunningUserIds(); assertThat(runningUserIds).isNotEmpty(); for (int userId : runningUserIds) { testTaskIdsForUser(userId); @@ -61,7 +61,7 @@ public class ActivityManagerTest { } private void testTaskIdsForUser(int userId) throws RemoteException { - List<?> recentTasks = service.getRecentTasks(100, 0, userId).getList(); + List<?> recentTasks = mService.getRecentTasks(100, 0, userId).getList(); if (recentTasks != null) { for (Object elem : recentTasks) { assertThat(elem).isInstanceOf(RecentTaskInfo.class); diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityOptionsTest.java b/services/tests/wmtests/src/com/android/server/am/ActivityOptionsTest.java index d15bff4f6378..f250f55ed803 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityOptionsTest.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityOptionsTest.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -22,23 +22,22 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import android.app.ActivityOptions; import android.os.Bundle; import android.platform.test.annotations.Presubmit; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Test; -import org.junit.runner.RunWith; /** - * atest FrameworksServicesTests:ActivityOptionsTest + * Build/Install/Run: + * atest WmTests:ActivityOptionsTest */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityOptionsTest { @Test @@ -64,12 +63,12 @@ public class ActivityOptionsTest { assertEquals(Integer.MAX_VALUE, restoredOpts.getLaunchDisplayId()); assertEquals(ACTIVITY_TYPE_STANDARD, restoredOpts.getLaunchActivityType()); assertEquals(WINDOWING_MODE_FULLSCREEN, restoredOpts.getLaunchWindowingMode()); - assertEquals(true, restoredOpts.getAvoidMoveToFront()); + assertTrue(restoredOpts.getAvoidMoveToFront()); assertEquals(Integer.MAX_VALUE, restoredOpts.getLaunchTaskId()); - assertEquals(true, restoredOpts.getLockTaskMode()); + assertTrue(restoredOpts.getLockTaskMode()); assertEquals(ROTATION_ANIMATION_ROTATE, restoredOpts.getRotationAnimationHint()); - assertEquals(true, restoredOpts.getTaskOverlay()); - assertEquals(true, restoredOpts.canTaskOverlayResume()); + assertTrue(restoredOpts.getTaskOverlay()); + assertTrue(restoredOpts.canTaskOverlayResume()); assertEquals(SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT, restoredOpts.getSplitScreenCreateMode()); } diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/am/ActivityRecordTests.java index 101500812265..72af1841e4d0 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityRecordTests.java @@ -11,15 +11,11 @@ * 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 + * limitations under the License. */ package com.android.server.am; -import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; -import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; -import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE; -import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE; import static android.view.Display.DEFAULT_DISPLAY; import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING; @@ -37,11 +33,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.ActivityOptions; @@ -52,32 +44,26 @@ import android.platform.test.annotations.Presubmit; import android.util.MutableBoolean; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; /** * Tests for the {@link ActivityRecord} class. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.ActivityRecordTests + * atest WmTests:ActivityRecordTests */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityRecordTests extends ActivityTestsBase { private TestActivityStack mStack; private TaskRecord mTask; private ActivityRecord mActivity; @Before - @Override public void setUp() throws Exception { - super.setUp(); - setupActivityTaskManagerService(); mStack = new StackBuilder(mSupervisor).build(); mTask = mStack.getChildAt(0); @@ -85,26 +71,26 @@ public class ActivityRecordTests extends ActivityTestsBase { } @Test - public void testStackCleanupOnClearingTask() throws Exception { + public void testStackCleanupOnClearingTask() { mActivity.setTask(null); assertEquals(mStack.onActivityRemovedFromStackInvocationCount(), 1); } @Test - public void testStackCleanupOnActivityRemoval() throws Exception { + public void testStackCleanupOnActivityRemoval() { mTask.removeActivity(mActivity); assertEquals(mStack.onActivityRemovedFromStackInvocationCount(), 1); } @Test - public void testStackCleanupOnTaskRemoval() throws Exception { + public void testStackCleanupOnTaskRemoval() { mStack.removeTask(mTask, null /*reason*/, REMOVE_TASK_MODE_MOVING); // Stack should be gone on task removal. assertNull(mService.mStackSupervisor.getStack(mStack.mStackId)); } @Test - public void testNoCleanupMovingActivityInSameStack() throws Exception { + public void testNoCleanupMovingActivityInSameStack() { final TaskRecord newTask = new TaskBuilder(mService.mStackSupervisor).setStack(mStack) .build(); mActivity.reparent(newTask, 0, null /*reason*/); @@ -157,19 +143,19 @@ public class ActivityRecordTests extends ActivityTestsBase { } @Test - public void testPositionLimitedAspectRatioNavBarBottom() throws Exception { + public void testPositionLimitedAspectRatioNavBarBottom() { verifyPositionWithLimitedAspectRatio(NAV_BAR_BOTTOM, new Rect(0, 0, 1000, 2000), 1.5f, new Rect(0, 0, 1000, 1500)); } @Test - public void testPositionLimitedAspectRatioNavBarLeft() throws Exception { + public void testPositionLimitedAspectRatioNavBarLeft() { verifyPositionWithLimitedAspectRatio(NAV_BAR_LEFT, new Rect(0, 0, 2000, 1000), 1.5f, new Rect(500, 0, 2000, 1000)); } @Test - public void testPositionLimitedAspectRatioNavBarRight() throws Exception { + public void testPositionLimitedAspectRatioNavBarRight() { verifyPositionWithLimitedAspectRatio(NAV_BAR_RIGHT, new Rect(0, 0, 2000, 1000), 1.5f, new Rect(0, 0, 1500, 1000)); } @@ -186,7 +172,7 @@ public class ActivityRecordTests extends ActivityTestsBase { } @Test - public void testCanBeLaunchedOnDisplay() throws Exception { + public void testCanBeLaunchedOnDisplay() { mService.mSupportsMultiWindow = true; final ActivityRecord activity = new ActivityBuilder(mService).build(); diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStackSupervisorTests.java b/services/tests/wmtests/src/com/android/server/am/ActivityStackSupervisorTests.java index 8ab22105c3ae..a5e8b5706af7 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityStackSupervisorTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityStackSupervisorTests.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -30,6 +30,9 @@ import static com.android.server.am.ActivityDisplay.POSITION_TOP; import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING; import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE; + +import static com.google.common.truth.Truth.assertThat; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -55,11 +58,9 @@ import android.graphics.Rect; import android.platform.test.annotations.Presubmit; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.ArrayList; @@ -67,19 +68,15 @@ import java.util.ArrayList; * Tests for the {@link ActivityStackSupervisor} class. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.ActivityStackSupervisorTests + * atest WmTests:ActivityStackSupervisorTests */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityStackSupervisorTests extends ActivityTestsBase { private ActivityStack mFullscreenStack; @Before - @Override public void setUp() throws Exception { - super.setUp(); - setupActivityTaskManagerService(); mFullscreenStack = mService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); @@ -90,7 +87,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * should expect {@code null} to be returned in this case. */ @Test - public void testRestoringInvalidTask() throws Exception { + public void testRestoringInvalidTask() { ((TestActivityDisplay) mSupervisor.getDefaultDisplay()).removeAllTasks(); TaskRecord task = mSupervisor.anyTaskForIdLocked(0 /*taskId*/, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, null, false /* onTop */); @@ -102,7 +99,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * activity stack when a new task is added. */ @Test - public void testReplacingTaskInPinnedStack() throws Exception { + public void testReplacingTaskInPinnedStack() { final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true) .setStack(mFullscreenStack).build(); final TaskRecord firstTask = firstActivity.getTask(); @@ -156,7 +153,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * Ensures that an activity is removed from the stopping activities list once it is resumed. */ @Test - public void testStoppingActivityRemovedWhenResumed() throws Exception { + public void testStoppingActivityRemovedWhenResumed() { final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true) .setStack(mFullscreenStack).build(); mSupervisor.mStoppingActivities.add(firstActivity); @@ -169,8 +166,9 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { /** * Ensures that waiting results are notified of launches. */ + @SuppressWarnings("SynchronizeOnNonFinalField") @Test - public void testReportWaitingActivityLaunchedIfNeeded() throws Exception { + public void testReportWaitingActivityLaunchedIfNeeded() { final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true) .setStack(mFullscreenStack).build(); @@ -181,23 +179,23 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { mSupervisor.mWaitingActivityLaunched.add(taskToFrontWait); mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity, START_TASK_TO_FRONT); - assertTrue(mSupervisor.mWaitingActivityLaunched.isEmpty()); + assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty(); assertEquals(taskToFrontWait.result, START_TASK_TO_FRONT); - assertEquals(taskToFrontWait.who, null); + assertNull(taskToFrontWait.who); final WaitResult deliverToTopWait = new WaitResult(); mSupervisor.mWaitingActivityLaunched.add(deliverToTopWait); mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity, START_DELIVERED_TO_TOP); - assertTrue(mSupervisor.mWaitingActivityLaunched.isEmpty()); + assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty(); assertEquals(deliverToTopWait.result, START_DELIVERED_TO_TOP); assertEquals(deliverToTopWait.who, firstActivity.realActivity); } } @Test - public void testApplySleepTokensLocked() throws Exception { + public void testApplySleepTokensLocked() { final ActivityDisplay display = mSupervisor.getDefaultDisplay(); final KeyguardController keyguard = mSupervisor.getKeyguardController(); final ActivityStack stack = mock(ActivityStack.class); @@ -253,7 +251,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * Verifies that removal of activity with task and stack is done correctly. */ @Test - public void testRemovingStackOnAppCrash() throws Exception { + public void testRemovingStackOnAppCrash() { final ActivityDisplay defaultDisplay = mService.mStackSupervisor.getDefaultDisplay(); final int originalStackCount = defaultDisplay.getChildCount(); final ActivityStack stack = mService.mStackSupervisor.getDefaultDisplay().createStack( @@ -272,7 +270,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { } @Test - public void testFocusability() throws Exception { + public void testFocusability() { final ActivityStack stack = mService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); final ActivityRecord activity = new ActivityBuilder(mService).setCreateTask(true) @@ -316,7 +314,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * primary stack. */ @Test - public void testSplitScreenPrimaryChosenWhenTopActivityLaunchedToSecondary() throws Exception { + public void testSplitScreenPrimaryChosenWhenTopActivityLaunchedToSecondary() { // Create primary split-screen stack with a task and an activity. final ActivityStack primaryStack = mService.mStackSupervisor.getDefaultDisplay() .createStack(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, @@ -339,9 +337,9 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * {@link android.app.IActivityTaskManager#resizeDockedStack} as expect. */ @Test - public void testResizeDockedStackForSplitScreenPrimary() throws Exception { - final Rect TASK_SIZE = new Rect(0, 0, 600, 600); - final Rect STACK_SIZE = new Rect(0, 0, 300, 300); + public void testResizeDockedStackForSplitScreenPrimary() { + final Rect taskSize = new Rect(0, 0, 600, 600); + final Rect stackSize = new Rect(0, 0, 300, 300); // Create primary split-screen stack with a task. final ActivityStack primaryStack = mService.mStackSupervisor.getDefaultDisplay() @@ -350,18 +348,18 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { final TaskRecord task = new TaskBuilder(mSupervisor).setStack(primaryStack).build(); // Resize dock stack. - mService.resizeDockedStack(STACK_SIZE, TASK_SIZE, null, null, null); + mService.resizeDockedStack(stackSize, taskSize, null, null, null); // Verify dock stack & its task bounds if is equal as resized result. - assertEquals(primaryStack.getBounds(), STACK_SIZE); - assertEquals(task.getBounds(), TASK_SIZE); + assertEquals(primaryStack.getBounds(), stackSize); + assertEquals(task.getBounds(), taskSize); } /** * Verify that home stack would be moved to front when the top activity is Recents. */ @Test - public void testFindTaskToMoveToFrontWhenRecentsOnTop() throws Exception { + public void testFindTaskToMoveToFrontWhenRecentsOnTop() { // Create stack/task on default display. final ActivityDisplay display = mSupervisor.getDefaultDisplay(); final TestActivityStack targetStack = new StackBuilder(mSupervisor).setOnTop(false).build(); @@ -383,7 +381,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * Recents. */ @Test - public void testFindTaskToMoveToFrontWhenRecentsOnOtherDisplay() throws Exception { + public void testFindTaskToMoveToFrontWhenRecentsOnOtherDisplay() { // Create stack/task on default display. final ActivityDisplay display = mSupervisor.getDefaultDisplay(); final ActivityStack targetStack = display.createStack(WINDOWING_MODE_FULLSCREEN, @@ -410,7 +408,7 @@ public class ActivityStackSupervisorTests extends ActivityTestsBase { * the stack is the top focused. */ @Test - public void testResumeActivityWhenNonTopmostStackIsTopFocused() throws Exception { + public void testResumeActivityWhenNonTopmostStackIsTopFocused() { // Create a stack at bottom. final ActivityDisplay display = mSupervisor.getDefaultDisplay(); final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN, diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/am/ActivityStackTests.java index 839792d71bca..b61e05973248 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityStackTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityStackTests.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -26,13 +26,15 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMAR import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; -import static com.android.server.am.ActivityStack.ActivityState.STOPPING; import static com.android.server.am.ActivityStack.ActivityState.DESTROYING; import static com.android.server.am.ActivityStack.ActivityState.PAUSED; import static com.android.server.am.ActivityStack.ActivityState.PAUSING; import static com.android.server.am.ActivityStack.ActivityState.RESUMED; +import static com.android.server.am.ActivityStack.ActivityState.STOPPING; import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING; +import static com.google.common.truth.Truth.assertThat; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -52,31 +54,25 @@ import android.os.UserHandle; import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; /** * Tests for the {@link ActivityStack} class. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.ActivityStackTests + * atest WmTests:ActivityStackTests */ @SmallTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityStackTests extends ActivityTestsBase { private ActivityDisplay mDefaultDisplay; private ActivityStack mStack; private TaskRecord mTask; @Before - @Override public void setUp() throws Exception { - super.setUp(); - setupActivityTaskManagerService(); mDefaultDisplay = mSupervisor.getDefaultDisplay(); mStack = spy(mDefaultDisplay.createStack(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, @@ -85,14 +81,14 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testEmptyTaskCleanupOnRemove() throws Exception { + public void testEmptyTaskCleanupOnRemove() { assertNotNull(mTask.getWindowContainerController()); mStack.removeTask(mTask, "testEmptyTaskCleanupOnRemove", REMOVE_TASK_MODE_DESTROYING); assertNull(mTask.getWindowContainerController()); } @Test - public void testOccupiedTaskCleanupOnRemove() throws Exception { + public void testOccupiedTaskCleanupOnRemove() { final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); assertNotNull(mTask.getWindowContainerController()); mStack.removeTask(mTask, "testOccupiedTaskCleanupOnRemove", REMOVE_TASK_MODE_DESTROYING); @@ -100,13 +96,13 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testResumedActivity() throws Exception { + public void testResumedActivity() { final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); - assertEquals(mStack.getResumedActivity(), null); + assertNull(mStack.getResumedActivity()); r.setState(RESUMED, "testResumedActivity"); - assertEquals(mStack.getResumedActivity(), r); + assertEquals(r, mStack.getResumedActivity()); r.setState(PAUSING, "testResumedActivity"); - assertEquals(mStack.getResumedActivity(), null); + assertNull(mStack.getResumedActivity()); } @Test @@ -114,7 +110,7 @@ public class ActivityStackTests extends ActivityTestsBase { final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); // Ensure moving task between two stacks updates resumed activity r.setState(RESUMED, "testResumedActivityFromTaskReparenting"); - assertEquals(mStack.getResumedActivity(), r); + assertEquals(r, mStack.getResumedActivity()); final ActivityStack destStack = mService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); @@ -123,8 +119,8 @@ public class ActivityStackTests extends ActivityTestsBase { false /* animate */, true /* deferResume*/, "testResumedActivityFromTaskReparenting"); - assertEquals(mStack.getResumedActivity(), null); - assertEquals(destStack.getResumedActivity(), r); + assertNull(mStack.getResumedActivity()); + assertEquals(r, destStack.getResumedActivity()); } @Test @@ -132,7 +128,7 @@ public class ActivityStackTests extends ActivityTestsBase { final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); // Ensure moving task between two stacks updates resumed activity r.setState(RESUMED, "testResumedActivityFromActivityReparenting"); - assertEquals(mStack.getResumedActivity(), r); + assertEquals(r, mStack.getResumedActivity()); final ActivityStack destStack = mService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); @@ -141,60 +137,60 @@ public class ActivityStackTests extends ActivityTestsBase { mTask.removeActivity(r); destTask.addActivityToTop(r); - assertEquals(mStack.getResumedActivity(), null); - assertEquals(destStack.getResumedActivity(), r); + assertNull(mStack.getResumedActivity()); + assertEquals(r, destStack.getResumedActivity()); } @Test - public void testPrimarySplitScreenRestoresWhenMovedToBack() throws Exception { + public void testPrimarySplitScreenRestoresWhenMovedToBack() { // Create primary splitscreen stack. This will create secondary stacks and places the // existing fullscreen stack on the bottom. final ActivityStack primarySplitScreen = mDefaultDisplay.createStack( WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); // Assert windowing mode. - assertEquals(primarySplitScreen.getWindowingMode(), WINDOWING_MODE_SPLIT_SCREEN_PRIMARY); + assertEquals(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, primarySplitScreen.getWindowingMode()); // Move primary to back. primarySplitScreen.moveToBack("testPrimarySplitScreenToFullscreenWhenMovedToBack", null /* task */); // Assert that stack is at the bottom. - assertEquals(mDefaultDisplay.getIndexOf(primarySplitScreen), 0); + assertEquals(0, mDefaultDisplay.getIndexOf(primarySplitScreen)); // Ensure no longer in splitscreen. - assertEquals(primarySplitScreen.getWindowingMode(), WINDOWING_MODE_FULLSCREEN); + assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getWindowingMode()); // Ensure that the override mode is restored to undefined - assertEquals(primarySplitScreen.getOverrideWindowingMode(), WINDOWING_MODE_UNDEFINED); + assertEquals(WINDOWING_MODE_UNDEFINED, primarySplitScreen.getOverrideWindowingMode()); } @Test - public void testPrimarySplitScreenRestoresPreviousWhenMovedToBack() throws Exception { + public void testPrimarySplitScreenRestoresPreviousWhenMovedToBack() { // This time, start with a fullscreen activitystack final ActivityStack primarySplitScreen = mDefaultDisplay.createStack( - WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); + WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); primarySplitScreen.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY); // Assert windowing mode. - assertEquals(primarySplitScreen.getWindowingMode(), WINDOWING_MODE_SPLIT_SCREEN_PRIMARY); + assertEquals(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, primarySplitScreen.getWindowingMode()); // Move primary to back. primarySplitScreen.moveToBack("testPrimarySplitScreenToFullscreenWhenMovedToBack", - null /* task */); + null /* task */); // Assert that stack is at the bottom. - assertEquals(mDefaultDisplay.getIndexOf(primarySplitScreen), 0); + assertEquals(0, mDefaultDisplay.getIndexOf(primarySplitScreen)); // Ensure that the override mode is restored to what it was (fullscreen) - assertEquals(primarySplitScreen.getOverrideWindowingMode(), WINDOWING_MODE_FULLSCREEN); + assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getOverrideWindowingMode()); } @Test - public void testStackInheritsDisplayWindowingMode() throws Exception { + public void testStackInheritsDisplayWindowingMode() { final ActivityStack primarySplitScreen = mDefaultDisplay.createStack( - WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */); + WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */); assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getWindowingMode()); assertEquals(WINDOWING_MODE_UNDEFINED, primarySplitScreen.getOverrideWindowingMode()); @@ -205,9 +201,9 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testStackOverridesDisplayWindowingMode() throws Exception { + public void testStackOverridesDisplayWindowingMode() { final ActivityStack primarySplitScreen = mDefaultDisplay.createStack( - WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */); + WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */); assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getWindowingMode()); assertEquals(WINDOWING_MODE_UNDEFINED, primarySplitScreen.getOverrideWindowingMode()); @@ -221,7 +217,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testStopActivityWhenActivityDestroyed() throws Exception { + public void testStopActivityWhenActivityDestroyed() { final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); r.info.flags |= ActivityInfo.FLAG_NO_HISTORY; mStack.moveToFront("testStopActivityWithDestroy"); @@ -231,7 +227,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testFindTaskWithOverlay() throws Exception { + public void testFindTaskWithOverlay() { final ActivityRecord r = new ActivityBuilder(mService) .setCreateTask(true) .setStack(mStack) @@ -247,8 +243,8 @@ public class ActivityStackTests extends ActivityTestsBase { new ActivityStackSupervisor.FindTaskResult(); mStack.findTaskLocked(r, result); - assertEquals(task.getTopActivity(false /* includeOverlays */), r); - assertEquals(task.getTopActivity(true /* includeOverlays */), taskOverlay); + assertEquals(r, task.getTopActivity(false /* includeOverlays */)); + assertEquals(taskOverlay, task.getTopActivity(true /* includeOverlays */)); assertNotNull(result.mRecord); } @@ -273,7 +269,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testShouldBeVisible_Fullscreen() throws Exception { + public void testShouldBeVisible_Fullscreen() { final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); final ActivityStack pinnedStack = createStackForShouldBeVisibleTest(mDefaultDisplay, @@ -298,14 +294,16 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testShouldBeVisible_SplitScreen() throws Exception { + public void testShouldBeVisible_SplitScreen() { final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); // Home stack should always be fullscreen for this test. homeStack.setSupportsSplitScreen(false); - final TestActivityStack splitScreenPrimary = createStackForShouldBeVisibleTest(mDefaultDisplay, + final TestActivityStack splitScreenPrimary = + createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); - final TestActivityStack splitScreenSecondary = createStackForShouldBeVisibleTest(mDefaultDisplay, + final TestActivityStack splitScreenSecondary = + createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); // Home stack shouldn't be visible if both halves of split-screen are opaque. @@ -321,7 +319,8 @@ public class ActivityStackTests extends ActivityTestsBase { assertTrue(splitScreenPrimary.shouldBeVisible(null /* starting */)); assertTrue(splitScreenSecondary.shouldBeVisible(null /* starting */)); - final TestActivityStack splitScreenSecondary2 = createStackForShouldBeVisibleTest(mDefaultDisplay, + final TestActivityStack splitScreenSecondary2 = + createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); // First split-screen secondary shouldn't be visible behind another opaque split-split // secondary. @@ -364,7 +363,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testShouldBeVisible_Finishing() throws Exception { + public void testShouldBeVisible_Finishing() { final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); final TestActivityStack translucentStack = createStackForShouldBeVisibleTest( @@ -403,9 +402,9 @@ public class ActivityStackTests extends ActivityTestsBase { // Ensure that we don't move the home stack if it is already behind the top fullscreen stack int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack); + assertEquals(fullscreenStack, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack); - assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex); + assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack)); } @Test @@ -422,9 +421,9 @@ public class ActivityStackTests extends ActivityTestsBase { // Ensure that we don't move the home stack if it is already behind the top fullscreen stack int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack); + assertEquals(fullscreenStack, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack); - assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex); + assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack)); } @Test @@ -441,9 +440,9 @@ public class ActivityStackTests extends ActivityTestsBase { // Ensure we don't move the home stack if it is already on top int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == null); + assertNull(mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack); - assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex); + assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack)); } @Test @@ -467,13 +466,14 @@ public class ActivityStackTests extends ActivityTestsBase { // Ensure that we move the home stack behind the bottom most fullscreen stack, ignoring the // pinned stack - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1); + assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack2); + assertEquals(fullscreenStack2, mDefaultDisplay.getStackAbove(homeStack)); } @Test - public void testMoveHomeStackBehindBottomMostVisibleStack_MoveHomeBehindFullscreenAndTranslucent() { + public void + testMoveHomeStackBehindBottomMostVisibleStack_MoveHomeBehindFullscreenAndTranslucent() { mDefaultDisplay.removeChild(mStack); final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay, @@ -491,9 +491,9 @@ public class ActivityStackTests extends ActivityTestsBase { // Ensure that we move the home stack behind the bottom most non-translucent fullscreen // stack - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1); + assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1); + assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack)); } @Test @@ -516,7 +516,7 @@ public class ActivityStackTests extends ActivityTestsBase { // Ensure we don't move the home stack behind itself int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack); mDefaultDisplay.moveStackBehindStack(homeStack, homeStack); - assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex); + assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack)); } @Test @@ -539,13 +539,13 @@ public class ActivityStackTests extends ActivityTestsBase { WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack1); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1); + assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack2); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack2); + assertEquals(fullscreenStack2, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack4); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack4); + assertEquals(fullscreenStack4, mDefaultDisplay.getStackAbove(homeStack)); mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack2); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack2); + assertEquals(fullscreenStack2, mDefaultDisplay.getStackAbove(homeStack)); } @Test @@ -554,7 +554,7 @@ public class ActivityStackTests extends ActivityTestsBase { WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); final ActivityStack pinnedStack = createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_PINNED, ACTIVITY_TYPE_STANDARD, true /* onTop */); - assertTrue(mDefaultDisplay.getStackAbove(homeStack) == pinnedStack); + assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(homeStack)); final TestActivityStack alwaysOnTopStack = createStackForShouldBeVisibleTest( mDefaultDisplay, WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD, @@ -562,13 +562,13 @@ public class ActivityStackTests extends ActivityTestsBase { alwaysOnTopStack.setAlwaysOnTop(true); assertTrue(alwaysOnTopStack.isAlwaysOnTop()); // Ensure (non-pinned) always on top stack is put below pinned stack. - assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack) == pinnedStack); + assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack)); final TestActivityStack nonAlwaysOnTopStack = createStackForShouldBeVisibleTest( mDefaultDisplay, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); // Ensure non always on top stack is put below always on top stacks. - assertTrue(mDefaultDisplay.getStackAbove(nonAlwaysOnTopStack) == alwaysOnTopStack); + assertEquals(alwaysOnTopStack, mDefaultDisplay.getStackAbove(nonAlwaysOnTopStack)); final TestActivityStack alwaysOnTopStack2 = createStackForShouldBeVisibleTest( mDefaultDisplay, WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD, @@ -576,25 +576,25 @@ public class ActivityStackTests extends ActivityTestsBase { alwaysOnTopStack2.setAlwaysOnTop(true); assertTrue(alwaysOnTopStack2.isAlwaysOnTop()); // Ensure newly created always on top stack is placed above other all always on top stacks. - assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == pinnedStack); + assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2)); alwaysOnTopStack2.setAlwaysOnTop(false); // Ensure, when always on top is turned off for a stack, the stack is put just below all // other always on top stacks. - assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == alwaysOnTopStack); + assertEquals(alwaysOnTopStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2)); alwaysOnTopStack2.setAlwaysOnTop(true); // Ensure always on top state changes properly when windowing mode changes. alwaysOnTopStack2.setWindowingMode(WINDOWING_MODE_FULLSCREEN); assertFalse(alwaysOnTopStack2.isAlwaysOnTop()); - assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == alwaysOnTopStack); + assertEquals(alwaysOnTopStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2)); alwaysOnTopStack2.setWindowingMode(WINDOWING_MODE_FREEFORM); assertTrue(alwaysOnTopStack2.isAlwaysOnTop()); - assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == pinnedStack); + assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2)); } @Test - public void testSplitScreenMoveToFront() throws Exception { + public void testSplitScreenMoveToFront() { final TestActivityStack splitScreenPrimary = createStackForShouldBeVisibleTest( mDefaultDisplay, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */); @@ -619,6 +619,7 @@ public class ActivityStackTests extends ActivityTestsBase { assertFalse(assistantStack.shouldBeVisible(null /* starting */)); } + @SuppressWarnings("TypeParameterUnusedInFormals") private <T extends ActivityStack> T createStackForShouldBeVisibleTest( ActivityDisplay display, int windowingMode, int activityType, boolean onTop) { final T stack; @@ -639,7 +640,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testFinishDisabledPackageActivities() throws Exception { + public void testFinishDisabledPackageActivities() { final ActivityRecord firstActivity = new ActivityBuilder(mService).setTask(mTask).build(); final ActivityRecord secondActivity = new ActivityBuilder(mService).setTask(mTask).build(); @@ -648,17 +649,17 @@ public class ActivityStackTests extends ActivityTestsBase { secondActivity.mTaskOverlay = true; secondActivity.app = null; - assertEquals(mTask.mActivities.size(), 2); + assertEquals(2, mTask.mActivities.size()); mStack.finishDisabledPackageActivitiesLocked(firstActivity.packageName, null, true /* doit */, true /* evenPersistent */, UserHandle.USER_ALL); - assertTrue(mTask.mActivities.isEmpty()); - assertTrue(mStack.getAllTasks().isEmpty()); + assertThat(mTask.mActivities).isEmpty(); + assertThat(mStack.getAllTasks()).isEmpty(); } @Test - public void testHandleAppDied() throws Exception { + public void testHandleAppDied() { final ActivityRecord firstActivity = new ActivityBuilder(mService).setTask(mTask).build(); final ActivityRecord secondActivity = new ActivityBuilder(mService).setTask(mTask).build(); @@ -671,12 +672,12 @@ public class ActivityStackTests extends ActivityTestsBase { // second activity will be immediately removed as it has no state. secondActivity.haveState = false; - assertEquals(mTask.mActivities.size(), 2); + assertEquals(2, mTask.mActivities.size()); mStack.handleAppDiedLocked(secondActivity.app); - assertTrue(mTask.mActivities.isEmpty()); - assertTrue(mStack.getAllTasks().isEmpty()); + assertThat(mTask.mActivities).isEmpty(); + assertThat(mStack.getAllTasks()).isEmpty(); } @Test @@ -693,7 +694,7 @@ public class ActivityStackTests extends ActivityTestsBase { stack2.getTopActivity().visible = true; final ActivityRecord activity2 = finishCurrentActivity(stack2); assertEquals(STOPPING, activity2.getState()); - assertTrue(mSupervisor.mStoppingActivities.contains(activity2)); + assertThat(mSupervisor.mStoppingActivities).contains(activity2); // The display becomes empty. Since there is no next activity to be idle, the activity // should be destroyed immediately with updating configuration to restore original state. @@ -714,7 +715,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testShouldSleepActivities() throws Exception { + public void testShouldSleepActivities() { // When focused activity and keyguard is going away, we should not sleep regardless // of the display state verifyShouldSleepActivities(true /* focusedStack */, true /*keyguardGoingAway*/, @@ -732,7 +733,7 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testStackOrderChangedOnRemoveStack() throws Exception { + public void testStackOrderChangedOnRemoveStack() { StackOrderChangedListener listener = new StackOrderChangedListener(); mDefaultDisplay.registerStackOrderChangedListener(listener); try { @@ -740,11 +741,11 @@ public class ActivityStackTests extends ActivityTestsBase { } finally { mDefaultDisplay.unregisterStackOrderChangedListener(listener); } - assertTrue(listener.changed); + assertTrue(listener.mChanged); } @Test - public void testStackOrderChangedOnAddPositionStack() throws Exception { + public void testStackOrderChangedOnAddPositionStack() { mDefaultDisplay.removeChild(mStack); StackOrderChangedListener listener = new StackOrderChangedListener(); @@ -754,11 +755,11 @@ public class ActivityStackTests extends ActivityTestsBase { } finally { mDefaultDisplay.unregisterStackOrderChangedListener(listener); } - assertTrue(listener.changed); + assertTrue(listener.mChanged); } @Test - public void testStackOrderChangedOnPositionStack() throws Exception { + public void testStackOrderChangedOnPositionStack() { StackOrderChangedListener listener = new StackOrderChangedListener(); try { final TestActivityStack fullscreenStack1 = createStackForShouldBeVisibleTest( @@ -769,7 +770,7 @@ public class ActivityStackTests extends ActivityTestsBase { } finally { mDefaultDisplay.unregisterStackOrderChangedListener(listener); } - assertTrue(listener.changed); + assertTrue(listener.mChanged); } private void verifyShouldSleepActivities(boolean focusedStack, @@ -785,12 +786,13 @@ public class ActivityStackTests extends ActivityTestsBase { assertEquals(expected, mStack.shouldSleepActivities()); } - private class StackOrderChangedListener implements ActivityDisplay.OnStackOrderChangedListener { - boolean changed = false; + private static class StackOrderChangedListener + implements ActivityDisplay.OnStackOrderChangedListener { + public boolean mChanged = false; @Override public void onStackOrderChanged() { - changed = true; + mChanged = true; } } } diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStartControllerTests.java b/services/tests/wmtests/src/com/android/server/am/ActivityStartControllerTests.java index e1ebbcf8f653..80b72e39738a 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityStartControllerTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityStartControllerTests.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -32,13 +32,12 @@ import android.os.UserHandle; import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.am.ActivityStackSupervisor.PendingActivityLaunch; import com.android.server.am.ActivityStarter.Factory; +import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.Random; @@ -46,20 +45,17 @@ import java.util.Random; * Tests for the {@link ActivityStartController} class. * * Build/Install/Run: - * atest FrameworksServicesTests:ActivityStartControllerTests + * atest WmTests:ActivityStartControllerTests */ @SmallTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityStartControllerTests extends ActivityTestsBase { - private ActivityTaskManagerService mService; private ActivityStartController mController; private Factory mFactory; private ActivityStarter mStarter; - @Override + @Before public void setUp() throws Exception { - super.setUp(); mService = createActivityTaskManagerService(); mFactory = mock(Factory.class); mController = new ActivityStartController(mService, mService.mStackSupervisor, mFactory); @@ -100,7 +96,7 @@ public class ActivityStartControllerTests extends ActivityTestsBase { * Ensures instances are recycled after execution. */ @Test - public void testRecycling() throws Exception { + public void testRecycling() { final Intent intent = new Intent(); final ActivityStarter optionStarter = new ActivityStarter(mController, mService, mService.mStackSupervisor, mock(ActivityStartInterceptor.class)); diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStartInterceptorTest.java b/services/tests/wmtests/src/com/android/server/am/ActivityStartInterceptorTest.java index 270d394ead34..27e34037fa0d 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityStartInterceptorTest.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityStartInterceptorTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2017, The Android Open Source Project + * Copyright (C) 2017 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 + * 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, @@ -60,10 +60,10 @@ import org.mockito.MockitoAnnotations; * Unit tests for {@link ActivityStartInterceptorTest}. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.ActivityStartInterceptorTest + * atest WmTests:ActivityStartInterceptorTest */ -@Presubmit @SmallTest +@Presubmit public class ActivityStartInterceptorTest { private static final int TEST_USER_ID = 1; private static final int TEST_REAL_CALLING_UID = 2; @@ -133,8 +133,8 @@ public class ActivityStartInterceptorTest { // Mock KeyguardManager when(mContext.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(mKeyguardManager); when(mKeyguardManager.createConfirmDeviceCredentialIntent( - nullable(CharSequence.class), nullable(CharSequence.class), eq(TEST_USER_ID))). - thenReturn(CONFIRM_CREDENTIALS_INTENT); + nullable(CharSequence.class), nullable(CharSequence.class), eq(TEST_USER_ID))) + .thenReturn(CONFIRM_CREDENTIALS_INTENT); // Mock PackageManager when(mService.getPackageManager()).thenReturn(mPackageManager); @@ -221,8 +221,8 @@ public class ActivityStartInterceptorTest { assertTrue(mInterceptor.intercept(null, null, mAInfo, null, null, 0, 0, null)); // THEN the returned intent is the harmful app warning intent - assertTrue(mInterceptor.mIntent.getComponent().getClassName().equals( - HarmfulAppWarningActivity.class.getName())); + assertEquals(HarmfulAppWarningActivity.class.getName(), + mInterceptor.mIntent.getComponent().getClassName()); } @Test diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/am/ActivityStarterTests.java index fb11a04ece50..9aa98af5c81b 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityStarterTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityStarterTests.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -40,8 +40,9 @@ import static com.android.server.am.ActivityDisplay.POSITION_BOTTOM; import static com.android.server.am.ActivityDisplay.POSITION_TOP; import static com.android.server.am.ActivityTaskManagerService.ANIMATE; +import static com.google.common.truth.Truth.assertThat; + import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; @@ -74,23 +75,21 @@ import android.service.voice.IVoiceInteractionSession; import android.view.Gravity; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.am.LaunchParamsController.LaunchParamsModifier; import com.android.server.am.TaskRecord.TaskRecordFactory; +import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; /** * Tests for the {@link ActivityStarter} class. * * Build/Install/Run: - * atest FrameworksServicesTests:ActivityStarterTests + * atest WmTests:ActivityStarterTests */ @SmallTest @Presubmit -@RunWith(AndroidJUnit4.class) public class ActivityStarterTests extends ActivityTestsBase { private ActivityStarter mStarter; private ActivityStartController mController; @@ -112,9 +111,8 @@ public class ActivityStarterTests extends ActivityTestsBase { private static final int FAKE_REAL_CALLING_UID = 667; private static final String FAKE_CALLING_PACKAGE = "com.whatever.dude"; - @Override + @Before public void setUp() throws Exception { - super.setUp(); setupActivityTaskManagerService(); mController = mock(ActivityStartController.class); mActivityMetricsLogger = mock(ActivityMetricsLogger.class); @@ -124,7 +122,7 @@ public class ActivityStarterTests extends ActivityTestsBase { } @Test - public void testUpdateLaunchBounds() throws Exception { + public void testUpdateLaunchBounds() { // When in a non-resizeable stack, the task bounds should be updated. final TaskRecord task = new TaskBuilder(mService.mStackSupervisor) .setStack(mService.mStackSupervisor.getDefaultDisplay().createStack( @@ -133,7 +131,7 @@ public class ActivityStarterTests extends ActivityTestsBase { final Rect bounds = new Rect(10, 10, 100, 100); mStarter.updateBounds(task, bounds); - assertEquals(task.getOverrideBounds(), bounds); + assertEquals(bounds, task.getOverrideBounds()); assertEquals(new Rect(), task.getStack().getOverrideBounds()); // When in a resizeable stack, the stack bounds should be updated as well. @@ -141,7 +139,7 @@ public class ActivityStarterTests extends ActivityTestsBase { .setStack(mService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_PINNED, ACTIVITY_TYPE_STANDARD, true /* onTop */)) .build(); - assertTrue(task2.getStack() instanceof PinnedActivityStack); + assertThat((Object) task2.getStack()).isInstanceOf(PinnedActivityStack.class); mStarter.updateBounds(task2, bounds); verify(mService, times(1)).resizeStack(eq(task2.getStack().mStackId), @@ -149,15 +147,15 @@ public class ActivityStarterTests extends ActivityTestsBase { // In the case of no animation, the stack and task bounds should be set immediately. if (!ANIMATE) { - assertEquals(task2.getStack().getOverrideBounds(), bounds); - assertEquals(task2.getOverrideBounds(), bounds); + assertEquals(bounds, task2.getStack().getOverrideBounds()); + assertEquals(bounds, task2.getOverrideBounds()); } else { - assertEquals(task2.getOverrideBounds(), new Rect()); + assertEquals(new Rect(), task2.getOverrideBounds()); } } @Test - public void testStartActivityPreconditions() throws Exception { + public void testStartActivityPreconditions() { verifyStartActivityPreconditions(PRECONDITION_NO_CALLER_APP, START_PERMISSION_DENIED); verifyStartActivityPreconditions(PRECONDITION_NO_INTENT_COMPONENT, START_INTENT_NOT_RESOLVED); @@ -211,7 +209,7 @@ public class ActivityStarterTests extends ActivityTestsBase { final WindowProcessController wpc = containsConditions(preconditions, PRECONDITION_NO_CALLER_APP) ? null : new WindowProcessController( - service, mock(ApplicationInfo.class),null, 0, -1, null, null); + service, mock(ApplicationInfo.class), null, 0, -1, null, null); doReturn(wpc).when(service).getProcessController(anyObject()); final Intent intent = new Intent(); @@ -250,7 +248,7 @@ public class ActivityStarterTests extends ActivityTestsBase { anyInt(), anyInt(), anyInt(), anyInt(), any()); } - if (containsConditions(preconditions,PRECONDITION_CANNOT_START_ANY_ACTIVITY)) { + if (containsConditions(preconditions, PRECONDITION_CANNOT_START_ANY_ACTIVITY)) { doReturn(false).when(service.mStackSupervisor).checkStartAnyActivityPermission( any(), any(), any(), anyInt(), anyInt(), anyInt(), any(), anyBoolean(), anyBoolean(), any(), any(), any()); @@ -448,7 +446,7 @@ public class ActivityStarterTests extends ActivityTestsBase { final int result = starter.setReason("testSplitScreenDeliverToTop").execute(); // Ensure result is delivering intent to top. - assertEquals(result, START_DELIVERED_TO_TOP); + assertEquals(START_DELIVERED_TO_TOP, result); } /** @@ -480,7 +478,7 @@ public class ActivityStarterTests extends ActivityTestsBase { final int result = starter.setReason("testSplitScreenMoveToFront").execute(); // Ensure result is moving task to front. - assertEquals(result, START_TASK_TO_FRONT); + assertEquals(START_TASK_TO_FRONT, result); } /** @@ -506,7 +504,7 @@ public class ActivityStarterTests extends ActivityTestsBase { private void assertNoTasks(ActivityDisplay display) { for (int i = display.getChildCount() - 1; i >= 0; --i) { final ActivityStack stack = display.getChildAt(i); - assertTrue(stack.getAllTasks().isEmpty()); + assertThat(stack.getAllTasks()).isEmpty(); } } diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/am/ActivityTestsBase.java index 57960efee3c7..dbe43011a51f 100644 --- a/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java +++ b/services/tests/wmtests/src/com/android/server/am/ActivityTestsBase.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -24,6 +24,8 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMAR import static android.view.Display.DEFAULT_DISPLAY; import static android.view.DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING; import static com.android.server.am.ActivityStackSupervisor.ON_TOP; @@ -60,8 +62,6 @@ import android.testing.DexmakerShareClassLoaderRule; import android.view.Display; import android.view.DisplayInfo; -import androidx.test.InstrumentationRegistry; - import com.android.internal.app.IVoiceInteractor; import com.android.server.AppOpsService; import com.android.server.AttributeCache; @@ -79,8 +79,8 @@ import com.android.server.wm.WindowTestUtils; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Rule; -import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import java.io.File; @@ -89,16 +89,14 @@ import java.util.List; /** * A base class to handle common operations in activity related unit tests. */ -public class ActivityTestsBase { - private static boolean sOneTimeSetupDone = false; - +class ActivityTestsBase { private static int sNextDisplayId = DEFAULT_DISPLAY + 1; @Rule public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule = new DexmakerShareClassLoaderRule(); - private final Context mContext = InstrumentationRegistry.getContext(); + final Context mContext = getInstrumentation().getTargetContext(); final TestInjector mTestInjector = new TestInjector(); ActivityTaskManagerService mService; @@ -110,22 +108,22 @@ public class ActivityTestsBase { // Default base activity name private static final String DEFAULT_COMPONENT_CLASS_NAME = ".BarActivity"; + @BeforeClass + public static void setUpOnceBase() { + AttributeCache.init(getInstrumentation().getTargetContext()); + } + @Before - public void setUp() throws Exception { - if (!sOneTimeSetupDone) { - sOneTimeSetupDone = true; - MockitoAnnotations.initMocks(this); - AttributeCache.init(mContext); - } + public void setUpBase() { mTestInjector.setUp(); } @After - public void tearDown() { + public void tearDownBase() { mTestInjector.tearDown(); } - protected ActivityTaskManagerService createActivityTaskManagerService() { + ActivityTaskManagerService createActivityTaskManagerService() { final TestActivityTaskManagerService atm = spy(new TestActivityTaskManagerService(mContext)); setupActivityManagerService(atm); @@ -396,10 +394,10 @@ public class ActivityTestsBase { } private static class TestTaskRecord extends TaskRecord { - TestTaskRecord(ActivityTaskManagerService service, int _taskId, ActivityInfo info, - Intent _intent, IVoiceInteractionSession _voiceSession, - IVoiceInteractor _voiceInteractor) { - super(service, _taskId, info, _intent, _voiceSession, _voiceInteractor); + TestTaskRecord(ActivityTaskManagerService service, int taskId, ActivityInfo info, + Intent intent, IVoiceInteractionSession voiceSession, + IVoiceInteractor voiceInteractor) { + super(service, taskId, info, intent, voiceSession, voiceInteractor); } @Override @@ -451,7 +449,7 @@ public class ActivityTestsBase { } @Override - final protected ActivityStackSupervisor createStackSupervisor() { + protected final ActivityStackSupervisor createStackSupervisor() { if (mTestStackSupervisor == null) { final ActivityStackSupervisor supervisor = spy(createTestSupervisor()); final KeyguardController keyguardController = mock(KeyguardController.class); @@ -486,10 +484,13 @@ public class ActivityTestsBase { return mInternal; } + @Override PackageManagerInternal getPackageManagerInternalLocked() { if (mPmInternal == null) { mPmInternal = mock(PackageManagerInternal.class); - doReturn(false).when(mPmInternal).isPermissionsReviewRequired(anyString(), anyInt()); + doReturn(false) + .when(mPmInternal) + .isPermissionsReviewRequired(anyString(), anyInt()); } return mPmInternal; } @@ -500,7 +501,7 @@ public class ActivityTestsBase { @Override public Context getContext() { - return InstrumentationRegistry.getContext(); + return getInstrumentation().getTargetContext(); } @Override @@ -611,6 +612,7 @@ public class ActivityTestsBase { mSupervisor = supervisor; } + @SuppressWarnings("TypeParameterUnusedInFormals") @Override <T extends ActivityStack> T createStackUnchecked(int windowingMode, int activityType, int stackId, boolean onTop) { @@ -798,6 +800,7 @@ public class ActivityTestsBase { return this; } + @SuppressWarnings("TypeParameterUnusedInFormals") <T extends ActivityStack> T build() { final int stackId = mStackId >= 0 ? mStackId : mDisplay.getNextStackId(); if (mWindowingMode == WINDOWING_MODE_PINNED) { diff --git a/services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java b/services/tests/wmtests/src/com/android/server/am/AppErrorDialogTest.java index 3a7a24d2e103..e70f069e8027 100644 --- a/services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java +++ b/services/tests/wmtests/src/com/android/server/am/AppErrorDialogTest.java @@ -16,27 +16,26 @@ package com.android.server.am; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + import android.content.Context; import android.os.Handler; -import androidx.test.InstrumentationRegistry; import androidx.test.annotation.UiThreadTest; import androidx.test.filters.FlakyTest; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.AppOpsService; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.io.File; /** - * runtest -c com.android.server.am.AppErrorDialogTest frameworks-services + * Build/Install/Run: + * atest WmTests:AppErrorDialogTest */ -@RunWith(AndroidJUnit4.class) @SmallTest @FlakyTest(bugId = 113616538) public class AppErrorDialogTest { @@ -46,7 +45,7 @@ public class AppErrorDialogTest { @Before public void setUp() throws Exception { - mContext = InstrumentationRegistry.getTargetContext(); + mContext = getInstrumentation().getTargetContext(); mService = new ActivityManagerService(new ActivityManagerService.Injector() { @Override public AppOpsService getAppOpsService(File file, Handler handler) { @@ -67,7 +66,7 @@ public class AppErrorDialogTest { @Test @UiThreadTest - public void testCreateWorks() throws Exception { + public void testCreateWorks() { AppErrorDialog.Data data = new AppErrorDialog.Data(); data.proc = new ProcessRecord(null, mContext.getApplicationInfo(), "name", 12345); data.result = new AppErrorResult(); diff --git a/services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java b/services/tests/wmtests/src/com/android/server/am/AssistDataRequesterTest.java index 1b823ff8c6b4..4dc0857a12b6 100644 --- a/services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java +++ b/services/tests/wmtests/src/com/android/server/am/AssistDataRequesterTest.java @@ -22,6 +22,9 @@ import static android.app.AppOpsManager.OP_ASSIST_SCREENSHOT; import static android.app.AppOpsManager.OP_ASSIST_STRUCTURE; import static android.graphics.Bitmap.Config.ARGB_8888; +import static com.google.common.truth.Truth.assertThat; + +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -45,16 +48,13 @@ import android.os.Looper; import android.util.Log; import android.view.IWindowManager; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.FlakyTest; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.am.AssistDataRequester.AssistDataRequesterCallbacks; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; @@ -65,11 +65,11 @@ import java.util.concurrent.TimeUnit; * Note: Currently, we only support fetching the screenshot for the current application, so the * screenshot checks are hardcoded accordingly. * - * runtest --path frameworks/base/services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java + * Build/Install/Run: + * atest WmTests:AssistDataRequesterTest */ @MediumTest @FlakyTest(bugId = 113616538) -@RunWith(AndroidJUnit4.class) public class AssistDataRequesterTest extends ActivityTestsBase { private static final String TAG = AssistDataRequesterTest.class.getSimpleName(); @@ -105,14 +105,11 @@ public class AssistDataRequesterTest extends ActivityTestsBase { private CountDownLatch mGate; @Before - @Override public void setUp() throws Exception { - super.setUp(); mAm = mock(IActivityManager.class); mAtm = mock(IActivityTaskManager.class); mWm = mock(IWindowManager.class); mAppOpsManager = mock(AppOpsManager.class); - mContext = InstrumentationRegistry.getContext(); mHandler = new Handler(Looper.getMainLooper()); mCallbacksLock = new Object(); mCallbacks = new Callbacks(); @@ -190,35 +187,35 @@ public class AssistDataRequesterTest extends ActivityTestsBase { setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED, CALLER_ASSIST_SCREENSHOT_ALLOWED); - mCallbacks.canHandleReceivedData = false; + mCallbacks.mCanHandleReceivedData = false; mDataRequester.requestAssistData(createActivityList(5), FETCH_DATA, FETCH_SCREENSHOTS, ALLOW_FETCH_DATA, ALLOW_FETCH_SCREENSHOTS, TEST_UID, TEST_PACKAGE); - assertTrue(mDataRequester.getPendingDataCount() == 5); - assertTrue(mDataRequester.getPendingScreenshotCount() == 1); + assertEquals(5, mDataRequester.getPendingDataCount()); + assertEquals(1, mDataRequester.getPendingScreenshotCount()); mGate.countDown(); waitForIdle(mHandler); // Callbacks still not ready to receive, but all pending data is received - assertTrue(mDataRequester.getPendingDataCount() == 0); - assertTrue(mDataRequester.getPendingScreenshotCount() == 0); - assertTrue(mCallbacks.receivedData.isEmpty()); - assertTrue(mCallbacks.receivedScreenshots.isEmpty()); - assertFalse(mCallbacks.requestCompleted); + assertEquals(0, mDataRequester.getPendingDataCount()); + assertEquals(0, mDataRequester.getPendingScreenshotCount()); + assertThat(mCallbacks.mReceivedData).isEmpty(); + assertThat(mCallbacks.mReceivedScreenshots).isEmpty(); + assertFalse(mCallbacks.mRequestCompleted); - mCallbacks.canHandleReceivedData = true; + mCallbacks.mCanHandleReceivedData = true; mDataRequester.processPendingAssistData(); // Since we are posting the callback for the request-complete, flush the handler as well mGate.countDown(); waitForIdle(mHandler); - assertTrue(mCallbacks.receivedData.size() == 5); - assertTrue(mCallbacks.receivedScreenshots.size() == 1); - assertTrue(mCallbacks.requestCompleted); + assertEquals(5, mCallbacks.mReceivedData.size()); + assertEquals(1, mCallbacks.mReceivedScreenshots.size()); + assertTrue(mCallbacks.mRequestCompleted); // Clear the state and ensure that we only process pending data once mCallbacks.reset(); mDataRequester.processPendingAssistData(); - assertTrue(mCallbacks.receivedData.isEmpty()); - assertTrue(mCallbacks.receivedScreenshots.isEmpty()); + assertThat(mCallbacks.mReceivedData).isEmpty(); + assertThat(mCallbacks.mReceivedScreenshots).isEmpty(); } @Test @@ -281,13 +278,13 @@ public class AssistDataRequesterTest extends ActivityTestsBase { setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, !CALLER_ASSIST_STRUCTURE_ALLOWED, !CALLER_ASSIST_SCREENSHOT_ALLOWED); - mCallbacks.canHandleReceivedData = false; + mCallbacks.mCanHandleReceivedData = false; mDataRequester.requestAssistData(createActivityList(5), FETCH_DATA, FETCH_SCREENSHOTS, ALLOW_FETCH_DATA, ALLOW_FETCH_SCREENSHOTS, TEST_UID, TEST_PACKAGE); mGate.countDown(); waitForIdle(mHandler); - assertTrue(mCallbacks.receivedData.isEmpty()); - assertTrue(mCallbacks.receivedScreenshots.isEmpty()); + assertThat(mCallbacks.mReceivedData).isEmpty(); + assertThat(mCallbacks.mReceivedScreenshots).isEmpty(); } @Test @@ -302,22 +299,22 @@ public class AssistDataRequesterTest extends ActivityTestsBase { private void assertReceivedDataCount(int numPendingData, int numReceivedData, int numPendingScreenshots, int numReceivedScreenshots) throws Exception { - assertTrue("Expected " + numPendingData + " pending data, got " + assertEquals("Expected " + numPendingData + " pending data, got " + mDataRequester.getPendingDataCount(), - mDataRequester.getPendingDataCount() == numPendingData); - assertTrue("Expected " + numPendingScreenshots + " pending screenshots, got " + numPendingData, mDataRequester.getPendingDataCount()); + assertEquals("Expected " + numPendingScreenshots + " pending screenshots, got " + mDataRequester.getPendingScreenshotCount(), - mDataRequester.getPendingScreenshotCount() == numPendingScreenshots); - assertFalse("Expected request NOT completed", mCallbacks.requestCompleted); + numPendingScreenshots, mDataRequester.getPendingScreenshotCount()); + assertFalse("Expected request NOT completed", mCallbacks.mRequestCompleted); mGate.countDown(); waitForIdle(mHandler); - assertTrue("Expected " + numReceivedData + " data, received " - + mCallbacks.receivedData.size(), - mCallbacks.receivedData.size() == numReceivedData); - assertTrue("Expected " + numReceivedScreenshots + " screenshots, received " - + mCallbacks.receivedScreenshots.size(), - mCallbacks.receivedScreenshots.size() == numReceivedScreenshots); - assertTrue("Expected request completed", mCallbacks.requestCompleted); + assertEquals("Expected " + numReceivedData + " data, received " + + mCallbacks.mReceivedData.size(), + numReceivedData, mCallbacks.mReceivedData.size()); + assertEquals("Expected " + numReceivedScreenshots + " screenshots, received " + + mCallbacks.mReceivedScreenshots.size(), + numReceivedScreenshots, mCallbacks.mReceivedScreenshots.size()); + assertTrue("Expected request completed", mCallbacks.mRequestCompleted); } private List<IBinder> createActivityList(int size) { @@ -339,30 +336,30 @@ public class AssistDataRequesterTest extends ActivityTestsBase { private class Callbacks implements AssistDataRequesterCallbacks { - boolean canHandleReceivedData = true; - boolean requestCompleted = false; - ArrayList<Bundle> receivedData = new ArrayList<>(); - ArrayList<Bitmap> receivedScreenshots = new ArrayList<>(); + public boolean mCanHandleReceivedData = true; + public boolean mRequestCompleted = false; + public final ArrayList<Bundle> mReceivedData = new ArrayList<>(); + public final ArrayList<Bitmap> mReceivedScreenshots = new ArrayList<>(); void reset() { - canHandleReceivedData = true; - receivedData.clear(); - receivedScreenshots.clear(); + mCanHandleReceivedData = true; + mReceivedData.clear(); + mReceivedScreenshots.clear(); } @Override public boolean canHandleReceivedAssistDataLocked() { - return canHandleReceivedData; + return mCanHandleReceivedData; } @Override public void onAssistDataReceivedLocked(Bundle data, int activityIndex, int activityCount) { - receivedData.add(data); + mReceivedData.add(data); } @Override public void onAssistScreenshotReceivedLocked(Bitmap screenshot) { - receivedScreenshots.add(screenshot); + mReceivedScreenshots.add(screenshot); } @Override @@ -370,7 +367,7 @@ public class AssistDataRequesterTest extends ActivityTestsBase { mHandler.post(() -> { try { mGate.await(10, TimeUnit.SECONDS); - requestCompleted = true; + mRequestCompleted = true; } catch (InterruptedException e) { Log.e(TAG, "Failed to wait", e); } diff --git a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java b/services/tests/wmtests/src/com/android/server/am/BroadcastRecordTest.java index 75f7c4c2cdff..c39d84abdca7 100644 --- a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java +++ b/services/tests/wmtests/src/com/android/server/am/BroadcastRecordTest.java @@ -27,10 +27,8 @@ import android.os.UserHandle; import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; @@ -40,11 +38,10 @@ import java.util.List; * Test class for {@link BroadcastRecord}. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.BroadcastRecordTest + * atest WmTests:BroadcastRecordTest */ @SmallTest @Presubmit -@RunWith(AndroidJUnit4.class) public class BroadcastRecordTest { @Test diff --git a/services/tests/servicestests/src/com/android/server/am/ClientLifecycleManagerTests.java b/services/tests/wmtests/src/com/android/server/am/ClientLifecycleManagerTests.java index b4ad183db386..3346ab746eb6 100644 --- a/services/tests/servicestests/src/com/android/server/am/ClientLifecycleManagerTests.java +++ b/services/tests/wmtests/src/com/android/server/am/ClientLifecycleManagerTests.java @@ -1,3 +1,19 @@ +/* + * Copyright (C) 2018 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.server.am; import static org.mockito.Mockito.mock; @@ -11,12 +27,13 @@ import android.os.Binder; import android.platform.test.annotations.Presubmit; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Test; -import org.junit.runner.RunWith; -@RunWith(AndroidJUnit4.class) +/** + * Build/Install/Run: + * atest WmTests:ClientLifecycleManagerTests + */ @SmallTest @Presubmit public class ClientLifecycleManagerTests { diff --git a/services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java b/services/tests/wmtests/src/com/android/server/am/CoreSettingsObserverTest.java index 719e0edc20b7..14463e39e4d8 100644 --- a/services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java +++ b/services/tests/wmtests/src/com/android/server/am/CoreSettingsObserverTest.java @@ -11,15 +11,18 @@ * 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 + * limitations under the License. */ package com.android.server.am; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + import static com.android.server.am.ActivityManagerService.Injector; +import static com.google.common.truth.Truth.assertWithMessage; + import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.when; import android.content.Context; @@ -28,9 +31,7 @@ import android.os.Handler; import android.provider.Settings; import android.test.mock.MockContentResolver; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.internal.util.test.FakeSettingsProvider; import com.android.server.AppOpsService; @@ -39,7 +40,6 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -48,20 +48,10 @@ import java.io.File; /** * Test class for {@link CoreSettingsObserver}. * - * To run the tests, use - * - * runtest -c com.android.server.am.CoreSettingsObserverTest frameworks-services - * - * or the following steps: - * - * Build: m FrameworksServicesTests - * Install: adb install -r \ - * ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk - * Run: adb shell am instrument -e class com.android.server.am.CoreSettingsObserverTest -w \ - * com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner + * Build/Install/Run: + * atest WmTests:CoreSettingsObserverTest */ @SmallTest -@RunWith(AndroidJUnit4.class) public class CoreSettingsObserverTest { private static final String TEST_SETTING_SECURE_INT = "secureInt"; private static final String TEST_SETTING_GLOBAL_FLOAT = "globalFloat"; @@ -94,7 +84,7 @@ public class CoreSettingsObserverTest { public void setUp() { MockitoAnnotations.initMocks(this); - final Context originalContext = InstrumentationRegistry.getContext(); + final Context originalContext = getInstrumentation().getTargetContext(); when(mContext.getApplicationInfo()).thenReturn(originalContext.getApplicationInfo()); mContentResolver = new MockContentResolver(mContext); mContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider()); @@ -124,12 +114,12 @@ public class CoreSettingsObserverTest { public void testPopulateSettings_settingNotSet() { final Bundle settingsBundle = getPopulatedBundle(); - assertFalse("Bundle should not contain " + TEST_SETTING_SECURE_INT, - settingsBundle.containsKey(TEST_SETTING_SECURE_INT)); - assertFalse("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT, - settingsBundle.containsKey(TEST_SETTING_GLOBAL_FLOAT)); - assertFalse("Bundle should not contain " + TEST_SETTING_SYSTEM_STRING, - settingsBundle.containsKey(TEST_SETTING_SYSTEM_STRING)); + assertWithMessage("Bundle should not contain " + TEST_SETTING_SECURE_INT) + .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_SECURE_INT); + assertWithMessage("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT) + .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_GLOBAL_FLOAT); + assertWithMessage("Bundle should not contain " + TEST_SETTING_SYSTEM_STRING) + .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_SYSTEM_STRING); } @Test @@ -150,8 +140,8 @@ public class CoreSettingsObserverTest { Settings.Global.putString(mContentResolver, TEST_SETTING_GLOBAL_FLOAT, null); settingsBundle = getPopulatedBundle(); - assertFalse("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT, - settingsBundle.containsKey(TEST_SETTING_GLOBAL_FLOAT)); + assertWithMessage("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT) + .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_GLOBAL_FLOAT); assertEquals("Unexpected value of " + TEST_SETTING_SECURE_INT, TEST_INT, settingsBundle.getInt(TEST_SETTING_SECURE_INT)); assertEquals("Unexpected value of " + TEST_SETTING_SYSTEM_STRING, @@ -170,6 +160,7 @@ public class CoreSettingsObserverTest { return mContext; } + @Override public AppOpsService getAppOpsService(File file, Handler handler) { return null; } diff --git a/services/tests/wmtests/src/com/android/server/am/DummyAmTests.java b/services/tests/wmtests/src/com/android/server/am/DummyAmTests.java deleted file mode 100644 index 023e4ab6636f..000000000000 --- a/services/tests/wmtests/src/com/android/server/am/DummyAmTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2018 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.server.am; - -import android.platform.test.annotations.Presubmit; - -import org.junit.Test; - -import androidx.test.filters.FlakyTest; - -/** - * Dummy test for com.android.server.am. - * TODO(b/113800711): Remove this class once the actual tests are moved from servicestests. - */ -public class DummyAmTests { - - @Presubmit - @Test - public void preSubmitTest() {} - - @FlakyTest - @Presubmit - @Test - public void flakyPreSubmitTest() {} - - @Test - public void postSubmitTest() {} - - @FlakyTest - @Test - public void flakyPostSubmitTest() {} -} diff --git a/services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java b/services/tests/wmtests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java index 765aaad45efb..0d11af1e835e 100644 --- a/services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java +++ b/services/tests/wmtests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java @@ -11,34 +11,37 @@ * 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 + * limitations under the License. */ package com.android.server.am; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + import android.content.ContentResolver; import android.provider.Settings; import android.test.mock.MockContentResolver; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.internal.util.Preconditions; import com.android.internal.util.test.FakeSettingsProvider; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.HashMap; import java.util.Map; /** * Tests for {@link GlobalSettingsToPropertiesMapper} + * + * Build/Install/Run: + * atest WmTests:GlobalSettingsToPropertiesMapperTest */ -@RunWith(AndroidJUnit4.class) @SmallTest public class GlobalSettingsToPropertiesMapperTest { private static final String[][] TEST_MAPPING = new String[][] { @@ -51,7 +54,7 @@ public class GlobalSettingsToPropertiesMapperTest { @Before public void setup() { // Use FakeSettingsProvider to not affect global state - mMockContentResolver = new MockContentResolver(InstrumentationRegistry.getContext()); + mMockContentResolver = new MockContentResolver(getInstrumentation().getTargetContext()); mMockContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider()); mTestMapper = new TestMapper(mMockContentResolver); } @@ -63,21 +66,21 @@ public class GlobalSettingsToPropertiesMapperTest { mTestMapper.updatePropertiesFromGlobalSettings(); String propValue = mTestMapper.systemPropertiesGet("TestProperty"); - Assert.assertEquals("testValue", propValue); + assertEquals("testValue", propValue); Settings.Global.putString(mMockContentResolver, Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "testValue2"); mTestMapper.updatePropertyFromSetting(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "TestProperty"); propValue = mTestMapper.systemPropertiesGet("TestProperty"); - Assert.assertEquals("testValue2", propValue); + assertEquals("testValue2", propValue); Settings.Global.putString(mMockContentResolver, Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, null); mTestMapper.updatePropertyFromSetting(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "TestProperty"); propValue = mTestMapper.systemPropertiesGet("TestProperty"); - Assert.assertEquals("", propValue); + assertEquals("", propValue); } @Test @@ -85,7 +88,7 @@ public class GlobalSettingsToPropertiesMapperTest { // Test that empty property will not not be set if setting is not set mTestMapper.updatePropertiesFromGlobalSettings(); String propValue = mTestMapper.systemPropertiesGet("TestProperty"); - Assert.assertNull("Property should not be set if setting is null", propValue); + assertNull("Property should not be set if setting is null", propValue); } private static class TestMapper extends GlobalSettingsToPropertiesMapper { @@ -108,6 +111,5 @@ public class GlobalSettingsToPropertiesMapperTest { mProps.put(key, value); } } - } diff --git a/services/tests/servicestests/src/com/android/server/am/LaunchParamsControllerTests.java b/services/tests/wmtests/src/com/android/server/am/LaunchParamsControllerTests.java index 2fb10e13ab0b..cb5d29337c1e 100644 --- a/services/tests/servicestests/src/com/android/server/am/LaunchParamsControllerTests.java +++ b/services/tests/wmtests/src/com/android/server/am/LaunchParamsControllerTests.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -41,32 +41,26 @@ import android.content.pm.ActivityInfo.WindowLayout; import android.platform.test.annotations.Presubmit; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.am.LaunchParamsController.LaunchParams; import com.android.server.am.LaunchParamsController.LaunchParamsModifier; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; /** * Tests for exercising {@link LaunchParamsController}. * * Build/Install/Run: - * atest FrameworksServicesTests:LaunchParamsControllerTests + * atest WmTests:LaunchParamsControllerTests */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class LaunchParamsControllerTests extends ActivityTestsBase { - private ActivityTaskManagerService mService; private LaunchParamsController mController; @Before - @Override public void setUp() throws Exception { - super.setUp(); mService = createActivityTaskManagerService(); mController = new LaunchParamsController(mService); } @@ -181,8 +175,7 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { mController.registerModifier(positioner1); mController.registerModifier(positioner2); - final LaunchParams - result = new LaunchParams(); + final LaunchParams result = new LaunchParams(); mController.calculate(null /*task*/, null /*layout*/, null /*activity*/, null /*source*/, null /*options*/, result); @@ -253,19 +246,18 @@ public class LaunchParamsControllerTests extends ActivityTestsBase { mController.registerModifier(positioner); final int beforeWindowMode = task.getStack().getWindowingMode(); - assertNotEquals(beforeWindowMode, windowingMode); + assertNotEquals(windowingMode, beforeWindowMode); mController.layoutTask(task, null /* windowLayout */); final int afterWindowMode = task.getStack().getWindowingMode(); - assertEquals(afterWindowMode, windowingMode); + assertEquals(windowingMode, afterWindowMode); } - public static class InstrumentedPositioner implements - LaunchParamsModifier { + public static class InstrumentedPositioner implements LaunchParamsModifier { - final private int mReturnVal; - final private LaunchParams mParams; + private final int mReturnVal; + private final LaunchParams mParams; InstrumentedPositioner(int returnVal, LaunchParams params) { mReturnVal = returnVal; diff --git a/services/tests/servicestests/src/com/android/server/am/LockTaskControllerTest.java b/services/tests/wmtests/src/com/android/server/am/LockTaskControllerTest.java index 863a0d8d34a4..b3ac427cee1f 100644 --- a/services/tests/servicestests/src/com/android/server/am/LockTaskControllerTest.java +++ b/services/tests/wmtests/src/com/android/server/am/LockTaskControllerTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2017, The Android Open Source Project + * Copyright (C) 2017 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 + * 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, @@ -32,12 +32,25 @@ import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATI import static android.os.Process.SYSTEM_UID; import static android.telecom.TelecomManager.EMERGENCY_DIALER_COMPONENT; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + import static com.android.server.am.LockTaskController.STATUS_BAR_MASK_LOCKED; import static com.android.server.am.LockTaskController.STATUS_BAR_MASK_PINNED; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import android.app.StatusBarManager; import android.app.admin.DevicePolicyManager; @@ -56,7 +69,6 @@ import android.telecom.TelecomManager; import android.testing.DexmakerShareClassLoaderRule; import android.util.Pair; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import com.android.internal.statusbar.IStatusBarService; @@ -77,10 +89,10 @@ import org.mockito.verification.VerificationMode; * Unit tests for {@link LockTaskController}. * * Build/Install/Run: - * bit FrameworksServicesTests:com.android.server.am.LockTaskControllerTest + * atest WmTests:LockTaskControllerTest */ -@Presubmit @SmallTest +@Presubmit public class LockTaskControllerTest { private static final String TEST_PACKAGE_NAME = "com.test.package"; private static final String TEST_PACKAGE_NAME_2 = "com.test.package2"; @@ -109,7 +121,7 @@ public class LockTaskControllerTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - mContext = InstrumentationRegistry.getTargetContext(); + mContext = getInstrumentation().getTargetContext(); mLockToAppSetting = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.LOCK_TO_APP_EXIT_LOCKED); @@ -183,7 +195,7 @@ public class LockTaskControllerTest { } @Test - public void testStartLockTaskMode_pinningRequest() throws Exception { + public void testStartLockTaskMode_pinningRequest() { // GIVEN a task record that is not whitelisted, i.e. with pinned auth TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_PINNABLE); @@ -214,7 +226,7 @@ public class LockTaskControllerTest { } @Test - public void testLockTaskViolation() throws Exception { + public void testLockTaskViolation() { // GIVEN one task record with whitelisted auth that is in lock task mode TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); @@ -240,7 +252,7 @@ public class LockTaskControllerTest { } @Test - public void testLockTaskViolation_emergencyCall() throws Exception { + public void testLockTaskViolation_emergencyCall() { // GIVEN one task record with whitelisted auth that is in lock task mode TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); @@ -289,7 +301,7 @@ public class LockTaskControllerTest { } @Test(expected = SecurityException.class) - public void testStopLockTaskMode_differentCaller() throws Exception { + public void testStopLockTaskMode_differentCaller() { // GIVEN one task record with whitelisted auth that is in lock task mode TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); @@ -301,7 +313,7 @@ public class LockTaskControllerTest { } @Test - public void testStopLockTaskMode_systemCaller() throws Exception { + public void testStopLockTaskMode_systemCaller() { // GIVEN one task record with whitelisted auth that is in lock task mode TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); @@ -404,7 +416,7 @@ public class LockTaskControllerTest { } @Test - public void testUpdateLockTaskPackages() throws Exception { + public void testUpdateLockTaskPackages() { String[] whitelist1 = {TEST_PACKAGE_NAME, TEST_PACKAGE_NAME_2}; String[] whitelist2 = {TEST_PACKAGE_NAME}; @@ -541,7 +553,7 @@ public class LockTaskControllerTest { } @Test - public void testUpdateLockTaskFeatures_keyguard() throws Exception { + public void testUpdateLockTaskFeatures_keyguard() { // GIVEN a locked task TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED); mLockTaskController.startLockTaskMode(tr, false, TEST_UID); diff --git a/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java b/services/tests/wmtests/src/com/android/server/am/MemoryStatUtilTest.java index 72c5b105cfef..75e75c3e4860 100644 --- a/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java +++ b/services/tests/wmtests/src/com/android/server/am/MemoryStatUtilTest.java @@ -29,14 +29,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.Collections; -@RunWith(AndroidJUnit4.class) +/** + * Build/Install/Run: + * atest WmTests:MemoryStatUtilTest + */ @SmallTest public class MemoryStatUtilTest { private static final String MEMORY_STAT_CONTENTS = String.join( @@ -130,51 +131,51 @@ public class MemoryStatUtilTest { "0"); private static final String PROC_STATUS_CONTENTS = "Name:\tandroid.youtube\n" - + "State:\tS (sleeping)\n" - + "Tgid:\t12088\n" - + "Pid:\t12088\n" - + "PPid:\t723\n" - + "TracerPid:\t0\n" - + "Uid:\t10083\t10083\t10083\t10083\n" - + "Gid:\t10083\t10083\t10083\t10083\n" - + "Ngid:\t0\n" - + "FDSize:\t128\n" - + "Groups:\t3003 9997 20083 50083 \n" - + "VmPeak:\t 4546844 kB\n" - + "VmSize:\t 4542636 kB\n" - + "VmLck:\t 0 kB\n" - + "VmPin:\t 0 kB\n" - + "VmHWM:\t 137668 kB\n" // RSS high watermark - + "VmRSS:\t 126776 kB\n" - + "RssAnon:\t 37860 kB\n" - + "RssFile:\t 88764 kB\n" - + "RssShmem:\t 152 kB\n" - + "VmData:\t 4125112 kB\n" - + "VmStk:\t 8192 kB\n" - + "VmExe:\t 24 kB\n" - + "VmLib:\t 102432 kB\n" - + "VmPTE:\t 1300 kB\n" - + "VmPMD:\t 36 kB\n" - + "VmSwap:\t 0 kB\n" - + "Threads:\t95\n" - + "SigQ:\t0/13641\n" - + "SigPnd:\t0000000000000000\n" - + "ShdPnd:\t0000000000000000\n" - + "SigBlk:\t0000000000001204\n" - + "SigIgn:\t0000000000000001\n" - + "SigCgt:\t00000006400084f8\n" - + "CapInh:\t0000000000000000\n" - + "CapPrm:\t0000000000000000\n" - + "CapEff:\t0000000000000000\n" - + "CapBnd:\t0000000000000000\n" - + "CapAmb:\t0000000000000000\n" - + "Seccomp:\t2\n" - + "Cpus_allowed:\tff\n" - + "Cpus_allowed_list:\t0-7\n" - + "Mems_allowed:\t1\n" - + "Mems_allowed_list:\t0\n" - + "voluntary_ctxt_switches:\t903\n" - + "nonvoluntary_ctxt_switches:\t104\n"; + + "State:\tS (sleeping)\n" + + "Tgid:\t12088\n" + + "Pid:\t12088\n" + + "PPid:\t723\n" + + "TracerPid:\t0\n" + + "Uid:\t10083\t10083\t10083\t10083\n" + + "Gid:\t10083\t10083\t10083\t10083\n" + + "Ngid:\t0\n" + + "FDSize:\t128\n" + + "Groups:\t3003 9997 20083 50083 \n" + + "VmPeak:\t 4546844 kB\n" + + "VmSize:\t 4542636 kB\n" + + "VmLck:\t 0 kB\n" + + "VmPin:\t 0 kB\n" + + "VmHWM:\t 137668 kB\n" // RSS high watermark + + "VmRSS:\t 126776 kB\n" + + "RssAnon:\t 37860 kB\n" + + "RssFile:\t 88764 kB\n" + + "RssShmem:\t 152 kB\n" + + "VmData:\t 4125112 kB\n" + + "VmStk:\t 8192 kB\n" + + "VmExe:\t 24 kB\n" + + "VmLib:\t 102432 kB\n" + + "VmPTE:\t 1300 kB\n" + + "VmPMD:\t 36 kB\n" + + "VmSwap:\t 0 kB\n" + + "Threads:\t95\n" + + "SigQ:\t0/13641\n" + + "SigPnd:\t0000000000000000\n" + + "ShdPnd:\t0000000000000000\n" + + "SigBlk:\t0000000000001204\n" + + "SigIgn:\t0000000000000001\n" + + "SigCgt:\t00000006400084f8\n" + + "CapInh:\t0000000000000000\n" + + "CapPrm:\t0000000000000000\n" + + "CapEff:\t0000000000000000\n" + + "CapBnd:\t0000000000000000\n" + + "CapAmb:\t0000000000000000\n" + + "Seccomp:\t2\n" + + "Cpus_allowed:\tff\n" + + "Cpus_allowed_list:\t0-7\n" + + "Mems_allowed:\t1\n" + + "Mems_allowed_list:\t0\n" + + "voluntary_ctxt_switches:\t903\n" + + "nonvoluntary_ctxt_switches:\t104\n"; @Test public void testParseMemoryStatFromMemcg_parsesCorrectValues() { diff --git a/services/tests/servicestests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java b/services/tests/wmtests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java index 4beebc4dd2f9..484558c15413 100644 --- a/services/tests/servicestests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java +++ b/services/tests/wmtests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -26,35 +26,31 @@ import android.view.RemoteAnimationAdapter; import androidx.test.filters.FlakyTest; import androidx.test.filters.SmallTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.testutils.OffsettableClock; import com.android.server.testutils.TestHandler; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** - * atest PendingRemoteAnimationRegistryTest + * Build/Install/Run: + * atest WmTests:PendingRemoteAnimationRegistryTest */ @SmallTest -@Presubmit @FlakyTest -@RunWith(AndroidJUnit4.class) +@Presubmit public class PendingRemoteAnimationRegistryTest extends ActivityTestsBase { @Mock RemoteAnimationAdapter mAdapter; private PendingRemoteAnimationRegistry mRegistry; private final OffsettableClock mClock = new OffsettableClock.Stopped(); private TestHandler mHandler; - private ActivityTaskManagerService mService; @Before public void setUp() throws Exception { - super.setUp(); MockitoAnnotations.initMocks(this); mService = createActivityTaskManagerService(); mService.mH.runWithScissors(() -> { diff --git a/services/tests/servicestests/src/com/android/server/am/PersisterQueueTests.java b/services/tests/wmtests/src/com/android/server/am/PersisterQueueTests.java index d7794b04adca..fe9cebea3604 100644 --- a/services/tests/servicestests/src/com/android/server/am/PersisterQueueTests.java +++ b/services/tests/wmtests/src/com/android/server/am/PersisterQueueTests.java @@ -12,11 +12,12 @@ * 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.server.am; +import static com.google.common.truth.Truth.assertWithMessage; + import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; @@ -27,10 +28,12 @@ import static org.junit.Assert.assertTrue; import android.os.SystemClock; import android.platform.test.annotations.Presubmit; +import androidx.test.filters.FlakyTest; +import androidx.test.filters.MediumTest; + import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; @@ -39,17 +42,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; -import androidx.test.filters.FlakyTest; -import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; - /** - * atest PersisterQueueTests + * Build/Install/Run: + * atest WmTests:PersisterQueueTests */ -@RunWith(AndroidJUnit4.class) @MediumTest -@Presubmit @FlakyTest(detail = "Confirm stable in post-submit before removing") +@Presubmit public class PersisterQueueTests implements PersisterQueue.Listener { private static final long INTER_WRITE_DELAY_MS = 50; private static final long PRE_TASK_DELAY_MS = 300; @@ -63,7 +62,8 @@ public class PersisterQueueTests implements PersisterQueue.Listener { private volatile CountDownLatch mLatch; private List<Boolean> mProbablyDoneResults; - private PersisterQueue mTarget; + private final PersisterQueue mTarget = + new PersisterQueue(INTER_WRITE_DELAY_MS, PRE_TASK_DELAY_MS); @Before public void setUp() throws Exception { @@ -71,7 +71,6 @@ public class PersisterQueueTests implements PersisterQueue.Listener { mProbablyDoneResults = new ArrayList<>(); mSetUpLatch = new CountDownLatch(1); - mTarget = new PersisterQueue(INTER_WRITE_DELAY_MS, PRE_TASK_DELAY_MS); mTarget.addListener(this); mTarget.startPersisting(); @@ -82,10 +81,11 @@ public class PersisterQueueTests implements PersisterQueue.Listener { @After public void tearDown() throws Exception { mTarget.stopPersisting(); + mTarget.removeListener(this); } @Test - public void testCallCallbackOnStartUp() throws Exception { + public void testCallCallbackOnStartUp() { // The onPreProcessItem() must be called on start up. assertEquals(1, mProbablyDoneResults.size()); // The last one must be called with probably done being true. @@ -197,7 +197,7 @@ public class PersisterQueueTests implements PersisterQueue.Listener { } @Test - public void testFindLastItemNotReturnDifferentType() throws Exception { + public void testFindLastItemNotReturnDifferentType() { synchronized (mTarget) { mTarget.addItem(new TestItem(), false); assertNull(mTarget.findLastItem(TEST_ITEM_PREDICATE, MatchingTestItem.class)); @@ -205,7 +205,7 @@ public class PersisterQueueTests implements PersisterQueue.Listener { } @Test - public void testFindLastItemNotReturnMismatchItem() throws Exception { + public void testFindLastItemNotReturnMismatchItem() { synchronized (mTarget) { mTarget.addItem(new MatchingTestItem(false), false); assertNull(mTarget.findLastItem(TEST_ITEM_PREDICATE, MatchingTestItem.class)); @@ -213,7 +213,7 @@ public class PersisterQueueTests implements PersisterQueue.Listener { } @Test - public void testFindLastItemReturnMatchedItem() throws Exception { + public void testFindLastItemReturnMatchedItem() { synchronized (mTarget) { final MatchingTestItem item = new MatchingTestItem(true); mTarget.addItem(item, false); @@ -267,8 +267,8 @@ public class PersisterQueueTests implements PersisterQueue.Listener { assertEquals("Flush should wait until all items are processed before return.", 2, mItemCount.get()); final long processTime = SystemClock.uptimeMillis() - dispatchTime; - assertTrue("Flush should trigger immediate flush without delays. processTime: " - + processTime, processTime < TIMEOUT_ALLOWANCE); + assertWithMessage("Flush should trigger immediate flush without delays. processTime: " + + processTime).that(processTime).isLessThan(TIMEOUT_ALLOWANCE); } @Override diff --git a/services/tests/servicestests/src/com/android/server/am/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/am/RecentTasksTest.java index 04fe7873f5b1..e15f6cfdd2b0 100644 --- a/services/tests/servicestests/src/com/android/server/am/RecentTasksTest.java +++ b/services/tests/wmtests/src/com/android/server/am/RecentTasksTest.java @@ -17,7 +17,6 @@ package com.android.server.am; import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT; -import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT; import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME; import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD; import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; @@ -30,6 +29,9 @@ import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; import static android.view.Display.DEFAULT_DISPLAY; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -39,6 +41,8 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; +import static java.lang.Integer.MAX_VALUE; + import android.app.ActivityManager.RecentTaskInfo; import android.app.ActivityManager.RunningTaskInfo; import android.app.ActivityTaskManager; @@ -58,44 +62,37 @@ import android.platform.test.annotations.Presubmit; import android.util.MutableLong; import android.util.SparseBooleanArray; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import com.android.server.am.RecentTasks.Callbacks; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; - -import static java.lang.Integer.MAX_VALUE; import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; /** - * atest FrameworksServicesTests:RecentTasksTest + * Build/Install/Run: + * atest WmTests:RecentTasksTest */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class RecentTasksTest extends ActivityTestsBase { private static final int TEST_USER_0_ID = 0; private static final int TEST_USER_1_ID = 10; private static final int TEST_QUIET_USER_ID = 20; private static final UserInfo DEFAULT_USER_INFO = new UserInfo(); private static final UserInfo QUIET_USER_INFO = new UserInfo(); - private static int LAST_TASK_ID = 1; - private static int LAST_STACK_ID = 1; - private static int INVALID_STACK_ID = 999; + private static int sLastTaskId = 1; + private static int sLastStackId = 1; + private static final int INVALID_STACK_ID = 999; - private Context mContext = InstrumentationRegistry.getContext(); - private TestActivityTaskManagerService mService; + private TestActivityTaskManagerService mTestService; private ActivityDisplay mDisplay; private ActivityDisplay mOtherDisplay; private ActivityStack mStack; @@ -110,19 +107,16 @@ public class RecentTasksTest extends ActivityTestsBase { private CallbacksRecorder mCallbacksRecorder; @Before - @Override public void setUp() throws Exception { - super.setUp(); - mTaskPersister = new TestTaskPersister(mContext.getFilesDir()); - mService = spy(new MyTestActivityTaskManagerService(mContext)); + mTestService = spy(new MyTestActivityTaskManagerService(mContext)); final TestActivityManagerService am = spy(new MyTestActivityManagerService()); - setupActivityManagerService(am, mService); - mRecentTasks = (TestRecentTasks) mService.getRecentTasks(); + setupActivityManagerService(am, mTestService); + mRecentTasks = (TestRecentTasks) mTestService.getRecentTasks(); mRecentTasks.loadParametersFromResources(mContext.getResources()); - mHomeStack = mService.mStackSupervisor.getDefaultDisplay().getOrCreateStack( + mHomeStack = mTestService.mStackSupervisor.getDefaultDisplay().getOrCreateStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); - mStack = mService.mStackSupervisor.getDefaultDisplay().createStack( + mStack = mTestService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); mCallbacksRecorder = new CallbacksRecorder(); mRecentTasks.registerCallback(mCallbacksRecorder); @@ -141,50 +135,50 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testCallbacks() throws Exception { + public void testCallbacks() { // Add some tasks mRecentTasks.add(mTasks.get(0)); mRecentTasks.add(mTasks.get(1)); - assertTrue(mCallbacksRecorder.added.contains(mTasks.get(0)) - && mCallbacksRecorder.added.contains(mTasks.get(1))); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).contains(mTasks.get(0)); + assertThat(mCallbacksRecorder.mAdded).contains(mTasks.get(1)); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); mCallbacksRecorder.clear(); // Remove some tasks mRecentTasks.remove(mTasks.get(0)); mRecentTasks.remove(mTasks.get(1)); - assertTrue(mCallbacksRecorder.added.isEmpty()); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.contains(mTasks.get(0))); - assertTrue(mCallbacksRecorder.removed.contains(mTasks.get(1))); + assertThat(mCallbacksRecorder.mAdded).isEmpty(); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).contains(mTasks.get(0)); + assertThat(mCallbacksRecorder.mRemoved).contains(mTasks.get(1)); mCallbacksRecorder.clear(); // Remove the callback, ensure we don't get any calls mRecentTasks.unregisterCallback(mCallbacksRecorder); mRecentTasks.add(mTasks.get(0)); mRecentTasks.remove(mTasks.get(0)); - assertTrue(mCallbacksRecorder.added.isEmpty()); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).isEmpty(); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); } @Test - public void testAddTasksNoMultiple_expectNoTrim() throws Exception { + public void testAddTasksNoMultiple_expectNoTrim() { // Add same non-multiple-task document tasks will remove the task (to re-add it) but not // trim it TaskRecord documentTask1 = createDocumentTask(".DocumentTask1"); TaskRecord documentTask2 = createDocumentTask(".DocumentTask1"); mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask2); - assertTrue(mCallbacksRecorder.added.contains(documentTask1)); - assertTrue(mCallbacksRecorder.added.contains(documentTask2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.contains(documentTask1)); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask1); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).contains(documentTask1); } @Test - public void testAddTasksMaxTaskRecents_expectNoTrim() throws Exception { + public void testAddTasksMaxTaskRecents_expectNoTrim() { // Add a task hitting max-recents for that app will remove the task (to add the next one) // but not trim it TaskRecord documentTask1 = createDocumentTask(".DocumentTask1"); @@ -193,27 +187,27 @@ public class RecentTasksTest extends ActivityTestsBase { documentTask2.maxRecents = 1; mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask2); - assertTrue(mCallbacksRecorder.added.contains(documentTask1)); - assertTrue(mCallbacksRecorder.added.contains(documentTask2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.contains(documentTask1)); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask1); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).contains(documentTask1); } @Test - public void testAddTasksSameTask_expectNoTrim() throws Exception { + public void testAddTasksSameTask_expectNoTrim() { // Add a task that is already in the task list does not trigger any callbacks, it just // moves in the list TaskRecord documentTask1 = createDocumentTask(".DocumentTask1"); mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask1); - assertTrue(mCallbacksRecorder.added.size() == 1); - assertTrue(mCallbacksRecorder.added.contains(documentTask1)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).hasSize(1); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask1); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); } @Test - public void testAddTasksMultipleDocumentTasks_expectNoTrim() throws Exception { + public void testAddTasksMultipleDocumentTasks_expectNoTrim() { // Add same multiple-task document tasks does not trim the first tasks TaskRecord documentTask1 = createDocumentTask(".DocumentTask1", FLAG_ACTIVITY_MULTIPLE_TASK); @@ -221,15 +215,15 @@ public class RecentTasksTest extends ActivityTestsBase { FLAG_ACTIVITY_MULTIPLE_TASK); mRecentTasks.add(documentTask1); mRecentTasks.add(documentTask2); - assertTrue(mCallbacksRecorder.added.size() == 2); - assertTrue(mCallbacksRecorder.added.contains(documentTask1)); - assertTrue(mCallbacksRecorder.added.contains(documentTask2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).hasSize(2); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask1); + assertThat(mCallbacksRecorder.mAdded).contains(documentTask2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); } @Test - public void testAddTasksMultipleTasks_expectRemovedNoTrim() throws Exception { + public void testAddTasksMultipleTasks_expectRemovedNoTrim() { // Add multiple same-affinity non-document tasks, ensure that it removes the other task, // but that it does not trim it TaskRecord task1 = createTaskBuilder(".Task1") @@ -239,21 +233,21 @@ public class RecentTasksTest extends ActivityTestsBase { .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK) .build(); mRecentTasks.add(task1); - assertTrue(mCallbacksRecorder.added.size() == 1); - assertTrue(mCallbacksRecorder.added.contains(task1)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).hasSize(1); + assertThat(mCallbacksRecorder.mAdded).contains(task1); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); mCallbacksRecorder.clear(); mRecentTasks.add(task2); - assertTrue(mCallbacksRecorder.added.size() == 1); - assertTrue(mCallbacksRecorder.added.contains(task2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.size() == 1); - assertTrue(mCallbacksRecorder.removed.contains(task1)); + assertThat(mCallbacksRecorder.mAdded).hasSize(1); + assertThat(mCallbacksRecorder.mAdded).contains(task2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).hasSize(1); + assertThat(mCallbacksRecorder.mRemoved).contains(task1); } @Test - public void testAddTasksDifferentStacks_expectNoRemove() throws Exception { + public void testAddTasksDifferentStacks_expectNoRemove() { // Adding the same task with different activity types should not trigger removal of the // other task TaskRecord task1 = createTaskBuilder(".Task1") @@ -264,15 +258,15 @@ public class RecentTasksTest extends ActivityTestsBase { .setStack(mStack).build(); mRecentTasks.add(task1); mRecentTasks.add(task2); - assertTrue(mCallbacksRecorder.added.size() == 2); - assertTrue(mCallbacksRecorder.added.contains(task1)); - assertTrue(mCallbacksRecorder.added.contains(task2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).hasSize(2); + assertThat(mCallbacksRecorder.mAdded).contains(task1); + assertThat(mCallbacksRecorder.mAdded).contains(task2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); } @Test - public void testAddTaskCompatibleActivityType_expectRemove() throws Exception { + public void testAddTaskCompatibleActivityType_expectRemove() { // Test with undefined activity type since the type is not persisted by the task persister // and we want to ensure that a new task will match a restored task TaskRecord task1 = createTaskBuilder(".Task1") @@ -280,7 +274,7 @@ public class RecentTasksTest extends ActivityTestsBase { .setStack(mStack) .build(); setTaskActivityType(task1, ACTIVITY_TYPE_UNDEFINED); - assertTrue(task1.getActivityType() == ACTIVITY_TYPE_UNDEFINED); + assertThat(task1.getActivityType()).isEqualTo(ACTIVITY_TYPE_UNDEFINED); mRecentTasks.add(task1); mCallbacksRecorder.clear(); @@ -288,24 +282,24 @@ public class RecentTasksTest extends ActivityTestsBase { .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); - assertTrue(task2.getActivityType() == ACTIVITY_TYPE_STANDARD); + assertEquals(ACTIVITY_TYPE_STANDARD, task2.getActivityType()); mRecentTasks.add(task2); - assertTrue(mCallbacksRecorder.added.size() == 1); - assertTrue(mCallbacksRecorder.added.contains(task2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.size() == 1); - assertTrue(mCallbacksRecorder.removed.contains(task1)); + assertThat(mCallbacksRecorder.mAdded).hasSize(1); + assertThat(mCallbacksRecorder.mAdded).contains(task2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).hasSize(1); + assertThat(mCallbacksRecorder.mRemoved).contains(task1); } @Test - public void testAddTaskCompatibleActivityTypeDifferentUser_expectNoRemove() throws Exception { + public void testAddTaskCompatibleActivityTypeDifferentUser_expectNoRemove() { TaskRecord task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .setUserId(TEST_USER_0_ID) .build(); setTaskActivityType(task1, ACTIVITY_TYPE_UNDEFINED); - assertTrue(task1.getActivityType() == ACTIVITY_TYPE_UNDEFINED); + assertEquals(ACTIVITY_TYPE_UNDEFINED, task1.getActivityType()); mRecentTasks.add(task1); mCallbacksRecorder.clear(); @@ -314,22 +308,22 @@ public class RecentTasksTest extends ActivityTestsBase { .setStack(mStack) .setUserId(TEST_USER_1_ID) .build(); - assertTrue(task2.getActivityType() == ACTIVITY_TYPE_STANDARD); + assertEquals(ACTIVITY_TYPE_STANDARD, task2.getActivityType()); mRecentTasks.add(task2); - assertTrue(mCallbacksRecorder.added.size() == 1); - assertTrue(mCallbacksRecorder.added.contains(task2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).hasSize(1); + assertThat(mCallbacksRecorder.mAdded).contains(task2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); } @Test - public void testAddTaskCompatibleWindowingMode_expectRemove() throws Exception { + public void testAddTaskCompatibleWindowingMode_expectRemove() { TaskRecord task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); setTaskWindowingMode(task1, WINDOWING_MODE_UNDEFINED); - assertTrue(task1.getWindowingMode() == WINDOWING_MODE_UNDEFINED); + assertEquals(WINDOWING_MODE_UNDEFINED, task1.getWindowingMode()); mRecentTasks.add(task1); mCallbacksRecorder.clear(); @@ -338,24 +332,24 @@ public class RecentTasksTest extends ActivityTestsBase { .setStack(mStack) .build(); setTaskWindowingMode(task2, WINDOWING_MODE_FULLSCREEN); - assertTrue(task2.getWindowingMode() == WINDOWING_MODE_FULLSCREEN); + assertEquals(WINDOWING_MODE_FULLSCREEN, task2.getWindowingMode()); mRecentTasks.add(task2); - assertTrue(mCallbacksRecorder.added.size() == 1); - assertTrue(mCallbacksRecorder.added.contains(task2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.size() == 1); - assertTrue(mCallbacksRecorder.removed.contains(task1)); + assertThat(mCallbacksRecorder.mAdded).hasSize(1); + assertThat(mCallbacksRecorder.mAdded).contains(task2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).hasSize(1); + assertThat(mCallbacksRecorder.mRemoved).contains(task1); } @Test - public void testAddTaskIncompatibleWindowingMode_expectNoRemove() throws Exception { + public void testAddTaskIncompatibleWindowingMode_expectNoRemove() { TaskRecord task1 = createTaskBuilder(".Task1") .setFlags(FLAG_ACTIVITY_NEW_TASK) .setStack(mStack) .build(); setTaskWindowingMode(task1, WINDOWING_MODE_FULLSCREEN); - assertTrue(task1.getWindowingMode() == WINDOWING_MODE_FULLSCREEN); + assertEquals(WINDOWING_MODE_FULLSCREEN, task1.getWindowingMode()); mRecentTasks.add(task1); TaskRecord task2 = createTaskBuilder(".Task1") @@ -363,41 +357,41 @@ public class RecentTasksTest extends ActivityTestsBase { .setStack(mStack) .build(); setTaskWindowingMode(task2, WINDOWING_MODE_PINNED); - assertTrue(task2.getWindowingMode() == WINDOWING_MODE_PINNED); + assertEquals(WINDOWING_MODE_PINNED, task2.getWindowingMode()); mRecentTasks.add(task2); - assertTrue(mCallbacksRecorder.added.size() == 2); - assertTrue(mCallbacksRecorder.added.contains(task1)); - assertTrue(mCallbacksRecorder.added.contains(task2)); - assertTrue(mCallbacksRecorder.trimmed.isEmpty()); - assertTrue(mCallbacksRecorder.removed.isEmpty()); + assertThat(mCallbacksRecorder.mAdded).hasSize(2); + assertThat(mCallbacksRecorder.mAdded).contains(task1); + assertThat(mCallbacksRecorder.mAdded).contains(task2); + assertThat(mCallbacksRecorder.mTrimmed).isEmpty(); + assertThat(mCallbacksRecorder.mRemoved).isEmpty(); } @Test - public void testUsersTasks() throws Exception { + public void testUsersTasks() { mRecentTasks.setOnlyTestVisibleRange(); // Setup some tasks for the users - mTaskPersister.userTaskIdsOverride = new SparseBooleanArray(); - mTaskPersister.userTaskIdsOverride.put(1, true); - mTaskPersister.userTaskIdsOverride.put(2, true); - mTaskPersister.userTasksOverride = new ArrayList<>(); - mTaskPersister.userTasksOverride.add(createTaskBuilder(".UserTask1").build()); - mTaskPersister.userTasksOverride.add(createTaskBuilder(".UserTask2").build()); + mTaskPersister.mUserTaskIdsOverride = new SparseBooleanArray(); + mTaskPersister.mUserTaskIdsOverride.put(1, true); + mTaskPersister.mUserTaskIdsOverride.put(2, true); + mTaskPersister.mUserTasksOverride = new ArrayList<>(); + mTaskPersister.mUserTasksOverride.add(createTaskBuilder(".UserTask1").build()); + mTaskPersister.mUserTasksOverride.add(createTaskBuilder(".UserTask2").build()); // Assert no user tasks are initially loaded - assertTrue(mRecentTasks.usersWithRecentsLoadedLocked().length == 0); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).hasLength(0); // Load user 0 tasks mRecentTasks.loadUserRecentsLocked(TEST_USER_0_ID); - assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID)); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_0_ID); assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_0_ID)); assertTrue(mRecentTasks.containsTaskId(2, TEST_USER_0_ID)); // Load user 1 tasks mRecentTasks.loadUserRecentsLocked(TEST_USER_1_ID); - assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID)); - assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_1_ID)); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_0_ID); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_1_ID); assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_0_ID)); assertTrue(mRecentTasks.containsTaskId(2, TEST_USER_0_ID)); assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_1_ID)); @@ -405,19 +399,22 @@ public class RecentTasksTest extends ActivityTestsBase { // Unload user 1 tasks mRecentTasks.unloadUserDataFromMemoryLocked(TEST_USER_1_ID); - assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID)); - assertFalse(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_1_ID)); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_0_ID); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList() + .doesNotContain(TEST_USER_1_ID); assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_0_ID)); assertTrue(mRecentTasks.containsTaskId(2, TEST_USER_0_ID)); // Unload user 0 tasks mRecentTasks.unloadUserDataFromMemoryLocked(TEST_USER_0_ID); - assertFalse(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID)); - assertFalse(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_1_ID)); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList() + .doesNotContain(TEST_USER_0_ID); + assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList() + .doesNotContain(TEST_USER_1_ID); } @Test - public void testOrderedIteration() throws Exception { + public void testOrderedIteration() { mRecentTasks.setOnlyTestVisibleRange(); TaskRecord task1 = createTaskBuilder(".Task1").build(); task1.lastActiveTime = new Random().nextInt(); @@ -436,13 +433,13 @@ public class RecentTasksTest extends ActivityTestsBase { final ArrayList<TaskRecord> tasks = mRecentTasks.getRawTasks(); for (int i = 0; i < tasks.size(); i++) { final TaskRecord task = tasks.get(i); - assertTrue(task.lastActiveTime >= prevLastActiveTime.value); + assertThat(prevLastActiveTime.value).isLessThan(task.lastActiveTime); prevLastActiveTime.value = task.lastActiveTime; } } @Test - public void testTrimToGlobalMaxNumRecents() throws Exception { + public void testTrimToGlobalMaxNumRecents() { mRecentTasks.setOnlyTestVisibleRange(); // Limit the global maximum number of recent tasks to a fixed size @@ -458,7 +455,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testTrimQuietProfileTasks() throws Exception { + public void testTrimQuietProfileTasks() { mRecentTasks.setOnlyTestVisibleRange(); TaskRecord qt1 = createTaskBuilder(".QuietTask1").setUserId(TEST_QUIET_USER_ID).build(); TaskRecord qt2 = createTaskBuilder(".QuietTask2").setUserId(TEST_QUIET_USER_ID).build(); @@ -473,7 +470,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testSessionDuration() throws Exception { + public void testSessionDuration() { mRecentTasks.setOnlyTestVisibleRange(); mRecentTasks.setParameters(-1 /* min */, -1 /* max */, 50 /* ms */); @@ -493,7 +490,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testVisibleTasks_excludedFromRecents() throws Exception { + public void testVisibleTasks_excludedFromRecents() { mRecentTasks.setOnlyTestVisibleRange(); mRecentTasks.setParameters(-1 /* min */, 4 /* max */, -1 /* ms */); @@ -515,7 +512,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testVisibleTasks_minNum() throws Exception { + public void testVisibleTasks_minNum() { mRecentTasks.setOnlyTestVisibleRange(); mRecentTasks.setParameters(5 /* min */, -1 /* max */, 25 /* ms */); @@ -536,7 +533,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testVisibleTasks_maxNum() throws Exception { + public void testVisibleTasks_maxNum() { mRecentTasks.setOnlyTestVisibleRange(); mRecentTasks.setParameters(-1 /* min */, 3 /* max */, -1 /* ms */); @@ -551,11 +548,11 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testBackStackTasks_expectNoTrim() throws Exception { + public void testBackStackTasks_expectNoTrim() { mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */); final MyTestActivityStackSupervisor supervisor = - (MyTestActivityStackSupervisor) mService.mStackSupervisor; + (MyTestActivityStackSupervisor) mTestService.mStackSupervisor; final ActivityStack homeStack = mDisplay.getHomeStack(); final ActivityStack aboveHomeStack = new MyTestActivityStack(mDisplay, supervisor); @@ -570,11 +567,11 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testBehindHomeStackTasks_expectTaskTrimmed() throws Exception { + public void testBehindHomeStackTasks_expectTaskTrimmed() { mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */); final MyTestActivityStackSupervisor supervisor = - (MyTestActivityStackSupervisor) mService.mStackSupervisor; + (MyTestActivityStackSupervisor) mTestService.mStackSupervisor; final ActivityStack behindHomeStack = new MyTestActivityStack(mDisplay, supervisor); final ActivityStack homeStack = mDisplay.getHomeStack(); final ActivityStack aboveHomeStack = new MyTestActivityStack(mDisplay, supervisor); @@ -592,11 +589,11 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testOtherDisplayTasks_expectNoTrim() throws Exception { + public void testOtherDisplayTasks_expectNoTrim() { mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */); final MyTestActivityStackSupervisor supervisor = - (MyTestActivityStackSupervisor) mService.mStackSupervisor; + (MyTestActivityStackSupervisor) mTestService.mStackSupervisor; final ActivityStack homeStack = mDisplay.getHomeStack(); final ActivityStack otherDisplayStack = new MyTestActivityStack(mOtherDisplay, supervisor); @@ -611,7 +608,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testRemovePackageByName() throws Exception { + public void testRemovePackageByName() { // Add a number of tasks with the same package name mRecentTasks.add(createTaskBuilder("com.android.pkg1", ".Task1").build()); mRecentTasks.add(createTaskBuilder("com.android.pkg2", ".Task2").build()); @@ -628,7 +625,7 @@ public class RecentTasksTest extends ActivityTestsBase { } @Test - public void testRemoveAllVisibleTasks() throws Exception { + public void testRemoveAllVisibleTasks() { mRecentTasks.setParameters(-1 /* min */, 3 /* max */, 100 /* ms */); // Create some set of tasks, some of which are visible and some are not @@ -674,16 +671,16 @@ public class RecentTasksTest extends ActivityTestsBase { mStack.remove(); // The following APIs should not restore task from recents to the active list. - assertNotRestoreTask(() -> mService.setFocusedTask(taskId)); - assertNotRestoreTask(() -> mService.startSystemLockTaskMode(taskId)); - assertNotRestoreTask(() -> mService.cancelTaskWindowTransition(taskId)); + assertNotRestoreTask(() -> mTestService.setFocusedTask(taskId)); + assertNotRestoreTask(() -> mTestService.startSystemLockTaskMode(taskId)); + assertNotRestoreTask(() -> mTestService.cancelTaskWindowTransition(taskId)); assertNotRestoreTask( - () -> mService.resizeTask(taskId, null /* bounds */, 0 /* resizeMode */)); + () -> mTestService.resizeTask(taskId, null /* bounds */, 0 /* resizeMode */)); assertNotRestoreTask( - () -> mService.setTaskWindowingMode(taskId, WINDOWING_MODE_FULLSCREEN, + () -> mTestService.setTaskWindowingMode(taskId, WINDOWING_MODE_FULLSCREEN, false/* toTop */)); assertNotRestoreTask( - () -> mService.setTaskWindowingModeSplitScreenPrimary(taskId, + () -> mTestService.setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, false /* toTop */, false /* animate */, null /* initialBounds */, true /* showRecents */)); @@ -699,87 +696,90 @@ public class RecentTasksTest extends ActivityTestsBase { @Test public void testNotRecentsComponent_denyApiAccess() throws Exception { - doReturn(PackageManager.PERMISSION_DENIED).when(mService) + doReturn(PackageManager.PERMISSION_DENIED).when(mTestService) .checkGetTasksPermission(anyString(), anyInt(), anyInt()); // Expect the following methods to fail due to recents component not being set mRecentTasks.setIsCallerRecentsOverride(TestRecentTasks.DENY_THROW_SECURITY_EXCEPTION); - testRecentTasksApis(false /* expectNoSecurityException */); + doTestRecentTasksApis(false /* expectNoSecurityException */); // Don't throw for the following tests mRecentTasks.setIsCallerRecentsOverride(TestRecentTasks.DENY); testGetTasksApis(false /* expectNoSecurityException */); } @Test - public void testRecentsComponent_allowApiAccessWithoutPermissions() throws Exception { - doReturn(PackageManager.PERMISSION_DENIED).when(mService) + public void testRecentsComponent_allowApiAccessWithoutPermissions() { + doReturn(PackageManager.PERMISSION_DENIED).when(mTestService) .checkGetTasksPermission(anyString(), anyInt(), anyInt()); // Set the recents component and ensure that the following calls do not fail mRecentTasks.setIsCallerRecentsOverride(TestRecentTasks.GRANT); - testRecentTasksApis(true /* expectNoSecurityException */); + doTestRecentTasksApis(true /* expectNoSecurityException */); testGetTasksApis(true /* expectNoSecurityException */); } - private void testRecentTasksApis(boolean expectCallable) { - assertSecurityException(expectCallable, () -> mService.removeStack(INVALID_STACK_ID)); + private void doTestRecentTasksApis(boolean expectCallable) { + assertSecurityException(expectCallable, () -> mTestService.removeStack(INVALID_STACK_ID)); assertSecurityException(expectCallable, - () -> mService.removeStacksInWindowingModes(new int[] {WINDOWING_MODE_UNDEFINED})); + () -> mTestService.removeStacksInWindowingModes( + new int[]{WINDOWING_MODE_UNDEFINED})); assertSecurityException(expectCallable, - () -> mService.removeStacksWithActivityTypes(new int[] {ACTIVITY_TYPE_UNDEFINED})); - assertSecurityException(expectCallable, () -> mService.removeTask(0)); + () -> mTestService.removeStacksWithActivityTypes( + new int[]{ACTIVITY_TYPE_UNDEFINED})); + assertSecurityException(expectCallable, () -> mTestService.removeTask(0)); assertSecurityException(expectCallable, - () -> mService.setTaskWindowingMode(0, WINDOWING_MODE_UNDEFINED, true)); + () -> mTestService.setTaskWindowingMode(0, WINDOWING_MODE_UNDEFINED, true)); assertSecurityException(expectCallable, - () -> mService.moveTaskToStack(0, INVALID_STACK_ID, true)); + () -> mTestService.moveTaskToStack(0, INVALID_STACK_ID, true)); assertSecurityException(expectCallable, - () -> mService.setTaskWindowingModeSplitScreenPrimary(0, + () -> mTestService.setTaskWindowingModeSplitScreenPrimary(0, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, true, true, new Rect(), true)); - assertSecurityException(expectCallable, () -> mService.dismissSplitScreenMode(true)); - assertSecurityException(expectCallable, () -> mService.dismissPip(true, 0)); + assertSecurityException(expectCallable, () -> mTestService.dismissSplitScreenMode(true)); + assertSecurityException(expectCallable, () -> mTestService.dismissPip(true, 0)); assertSecurityException(expectCallable, - () -> mService.moveTopActivityToPinnedStack(INVALID_STACK_ID, new Rect())); + () -> mTestService.moveTopActivityToPinnedStack(INVALID_STACK_ID, new Rect())); assertSecurityException(expectCallable, - () -> mService.resizeStack(INVALID_STACK_ID, new Rect(), true, true, true, 0)); + () -> mTestService.resizeStack(INVALID_STACK_ID, new Rect(), true, true, true, 0)); assertSecurityException(expectCallable, - () -> mService.resizeDockedStack(new Rect(), new Rect(), new Rect(), new Rect(), + () -> mTestService.resizeDockedStack(new Rect(), new Rect(), new Rect(), new Rect(), new Rect())); assertSecurityException(expectCallable, - () -> mService.resizePinnedStack(new Rect(), new Rect())); - assertSecurityException(expectCallable, () -> mService.getAllStackInfos()); + () -> mTestService.resizePinnedStack(new Rect(), new Rect())); + assertSecurityException(expectCallable, () -> mTestService.getAllStackInfos()); assertSecurityException(expectCallable, - () -> mService.getStackInfo(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_UNDEFINED)); + () -> mTestService.getStackInfo(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_UNDEFINED)); assertSecurityException(expectCallable, () -> { try { - mService.getFocusedStackInfo(); + mTestService.getFocusedStackInfo(); } catch (RemoteException e) { // Ignore } }); assertSecurityException(expectCallable, - () -> mService.moveTasksToFullscreenStack(INVALID_STACK_ID, true)); + () -> mTestService.moveTasksToFullscreenStack(INVALID_STACK_ID, true)); + assertSecurityException(expectCallable, + () -> mTestService.startActivityFromRecents(0, new Bundle())); + assertSecurityException(expectCallable, () -> mTestService.getTaskSnapshot(0, true)); + assertSecurityException(expectCallable, () -> mTestService.registerTaskStackListener(null)); assertSecurityException(expectCallable, - () -> mService.startActivityFromRecents(0, new Bundle())); - assertSecurityException(expectCallable,() -> mService.getTaskSnapshot(0, true)); - assertSecurityException(expectCallable,() -> mService.registerTaskStackListener(null)); - assertSecurityException(expectCallable,() -> mService.unregisterTaskStackListener(null)); - assertSecurityException(expectCallable, () -> mService.getTaskDescription(0)); - assertSecurityException(expectCallable, () -> mService.cancelTaskWindowTransition(0)); - assertSecurityException(expectCallable, () -> mService.startRecentsActivity(null, null, + () -> mTestService.unregisterTaskStackListener(null)); + assertSecurityException(expectCallable, () -> mTestService.getTaskDescription(0)); + assertSecurityException(expectCallable, () -> mTestService.cancelTaskWindowTransition(0)); + assertSecurityException(expectCallable, () -> mTestService.startRecentsActivity(null, null, null)); - assertSecurityException(expectCallable, () -> mService.cancelRecentsAnimation(true)); - assertSecurityException(expectCallable, () -> mService.stopAppSwitches()); - assertSecurityException(expectCallable, () -> mService.resumeAppSwitches()); + assertSecurityException(expectCallable, () -> mTestService.cancelRecentsAnimation(true)); + assertSecurityException(expectCallable, () -> mTestService.stopAppSwitches()); + assertSecurityException(expectCallable, () -> mTestService.resumeAppSwitches()); } private void testGetTasksApis(boolean expectCallable) { - mService.getRecentTasks(MAX_VALUE, 0, TEST_USER_0_ID); - mService.getTasks(MAX_VALUE); + mTestService.getRecentTasks(MAX_VALUE, 0, TEST_USER_0_ID); + mTestService.getTasks(MAX_VALUE); if (expectCallable) { - assertTrue(mRecentTasks.lastAllowed); - assertTrue(mRunningTasks.lastAllowed); + assertTrue(mRecentTasks.mLastAllowed); + assertTrue(mRunningTasks.mLastAllowed); } else { - assertFalse(mRecentTasks.lastAllowed); - assertFalse(mRunningTasks.lastAllowed); + assertFalse(mRecentTasks.mLastAllowed); + assertFalse(mRunningTasks.mLastAllowed); } } @@ -788,10 +788,10 @@ public class RecentTasksTest extends ActivityTestsBase { } private TaskBuilder createTaskBuilder(String packageName, String className) { - return new TaskBuilder(mService.mStackSupervisor) + return new TaskBuilder(mTestService.mStackSupervisor) .setComponent(new ComponentName(packageName, className)) .setStack(mStack) - .setTaskId(LAST_TASK_ID++) + .setTaskId(sLastTaskId++) .setUserId(TEST_USER_0_ID); } @@ -824,25 +824,20 @@ public class RecentTasksTest extends ActivityTestsBase { return task; } - private boolean arrayContainsUser(int[] userIds, int targetUserId) { - Arrays.sort(userIds); - return Arrays.binarySearch(userIds, targetUserId) >= 0; - } - private void assertNoTasksTrimmed() { assertTrimmed(); } private void assertTrimmed(TaskRecord... tasks) { - final ArrayList<TaskRecord> trimmed = mCallbacksRecorder.trimmed; - final ArrayList<TaskRecord> removed = mCallbacksRecorder.removed; - assertTrue("Expected " + tasks.length + " trimmed tasks, got " + trimmed.size(), - trimmed.size() == tasks.length); - assertTrue("Expected " + tasks.length + " removed tasks, got " + removed.size(), - removed.size() == tasks.length); + final ArrayList<TaskRecord> trimmed = mCallbacksRecorder.mTrimmed; + final ArrayList<TaskRecord> removed = mCallbacksRecorder.mRemoved; + assertWithMessage("Expected " + tasks.length + " trimmed tasks, got " + trimmed.size()) + .that(trimmed).hasSize(tasks.length); + assertWithMessage("Expected " + tasks.length + " removed tasks, got " + removed.size()) + .that(removed).hasSize(tasks.length); for (TaskRecord task : tasks) { - assertTrue("Expected trimmed task: " + task, trimmed.contains(task)); - assertTrue("Expected removed task: " + task, removed.contains(task)); + assertWithMessage("Expected trimmed task: " + task).that(trimmed).contains(task); + assertWithMessage("Expected removed task: " + task).that(removed).contains(task); } } @@ -853,8 +848,7 @@ public class RecentTasksTest extends ActivityTestsBase { } catch (SecurityException se) { noSecurityException = false; } catch (Exception e) { - // We only care about SecurityExceptions, fall through here - e.printStackTrace(); + // We only care about SecurityExceptions, fall through here. } if (noSecurityException != expectCallable) { fail("Expected callable: " + expectCallable + " but got no security exception: " @@ -891,7 +885,7 @@ public class RecentTasksTest extends ActivityTestsBase { } private class MyTestActivityStackSupervisor extends TestActivityStackSupervisor { - public MyTestActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) { + MyTestActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) { super(service, looper); } @@ -911,11 +905,11 @@ public class RecentTasksTest extends ActivityTestsBase { } } - private class MyTestActivityStack extends TestActivityStack { + private static class MyTestActivityStack extends TestActivityStack { private ActivityDisplay mDisplay = null; MyTestActivityStack(ActivityDisplay display, ActivityStackSupervisor supervisor) { - super(display, LAST_STACK_ID++, supervisor, WINDOWING_MODE_FULLSCREEN, + super(display, sLastStackId++, supervisor, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */, false /* createActivity */); mDisplay = display; } @@ -930,33 +924,33 @@ public class RecentTasksTest extends ActivityTestsBase { } private static class CallbacksRecorder implements Callbacks { - ArrayList<TaskRecord> added = new ArrayList<>(); - ArrayList<TaskRecord> trimmed = new ArrayList<>(); - ArrayList<TaskRecord> removed = new ArrayList<>(); + public final ArrayList<TaskRecord> mAdded = new ArrayList<>(); + public final ArrayList<TaskRecord> mTrimmed = new ArrayList<>(); + public final ArrayList<TaskRecord> mRemoved = new ArrayList<>(); void clear() { - added.clear(); - trimmed.clear(); - removed.clear(); + mAdded.clear(); + mTrimmed.clear(); + mRemoved.clear(); } @Override public void onRecentTaskAdded(TaskRecord task) { - added.add(task); + mAdded.add(task); } @Override public void onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess) { if (wasTrimmed) { - trimmed.add(task); + mTrimmed.add(task); } - removed.add(task); + mRemoved.add(task); } } private static class TestTaskPersister extends TaskPersister { - SparseBooleanArray userTaskIdsOverride; - ArrayList<TaskRecord> userTasksOverride; + public SparseBooleanArray mUserTaskIdsOverride; + public ArrayList<TaskRecord> mUserTasksOverride; TestTaskPersister(File workingDir) { super(workingDir); @@ -964,16 +958,16 @@ public class RecentTasksTest extends ActivityTestsBase { @Override SparseBooleanArray loadPersistedTaskIdsForUser(int userId) { - if (userTaskIdsOverride != null) { - return userTaskIdsOverride; + if (mUserTaskIdsOverride != null) { + return mUserTaskIdsOverride; } return super.loadPersistedTaskIdsForUser(userId); } @Override List<TaskRecord> restoreTasksForUserLocked(int userId, SparseBooleanArray preaddedTasks) { - if (userTasksOverride != null) { - return userTasksOverride; + if (mUserTasksOverride != null) { + return mUserTasksOverride; } return super.restoreTasksForUserLocked(userId, preaddedTasks); } @@ -988,7 +982,7 @@ public class RecentTasksTest extends ActivityTestsBase { private boolean mIsTrimmableOverride; private int mIsCallerRecentsPolicy; - boolean lastAllowed; + public boolean mLastAllowed; TestRecentTasks(ActivityTaskManagerService service, TaskPersister taskPersister) { super(service, taskPersister); @@ -1053,7 +1047,7 @@ public class RecentTasksTest extends ActivityTestsBase { ParceledListSlice<RecentTaskInfo> getRecentTasks(int maxNum, int flags, boolean getTasksAllowed, boolean getDetailedTasks, int userId, int callingUid) { - lastAllowed = getTasksAllowed; + mLastAllowed = getTasksAllowed; return super.getRecentTasks(maxNum, flags, getTasksAllowed, getDetailedTasks, userId, callingUid); } @@ -1065,13 +1059,13 @@ public class RecentTasksTest extends ActivityTestsBase { } private static class TestRunningTasks extends RunningTasks { - boolean lastAllowed; + public boolean mLastAllowed; @Override void getTasks(int maxNum, List<RunningTaskInfo> list, int ignoreActivityType, int ignoreWindowingMode, ArrayList<ActivityDisplay> activityDisplays, int callingUid, boolean allowed) { - lastAllowed = allowed; + mLastAllowed = allowed; super.getTasks(maxNum, list, ignoreActivityType, ignoreWindowingMode, activityDisplays, callingUid, allowed); } diff --git a/services/tests/servicestests/src/com/android/server/am/RecentsAnimationTest.java b/services/tests/wmtests/src/com/android/server/am/RecentsAnimationTest.java index f15b5f7f04b0..36d5c5f7abcd 100644 --- a/services/tests/servicestests/src/com/android/server/am/RecentsAnimationTest.java +++ b/services/tests/wmtests/src/com/android/server/am/RecentsAnimationTest.java @@ -38,63 +38,60 @@ import android.view.IRecentsAnimationRunner; import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; /** - * atest FrameworksServicesTests:RecentsAnimationTest + * Build/Install/Run: + * atest WmTests:RecentsAnimationTest */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class RecentsAnimationTest extends ActivityTestsBase { private Context mContext = InstrumentationRegistry.getContext(); - private TestActivityTaskManagerService mService; + private TestActivityTaskManagerService mTestService; private ComponentName mRecentsComponent; @Before - @Override public void setUp() throws Exception { - super.setUp(); - mRecentsComponent = new ComponentName(mContext.getPackageName(), "RecentsActivity"); - mService = spy(new MyTestActivityTaskManagerService(mContext)); - setupActivityManagerService(mService); + mTestService = spy(new MyTestActivityTaskManagerService(mContext)); + setupActivityManagerService(mTestService); } @Test - public void testCancelAnimationOnStackOrderChange() throws Exception { - ActivityStack fullscreenStack = mService.mStackSupervisor.getDefaultDisplay().createStack( - WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); - ActivityStack recentsStack = mService.mStackSupervisor.getDefaultDisplay().createStack( + public void testCancelAnimationOnStackOrderChange() { + ActivityStack fullscreenStack = + mTestService.mStackSupervisor.getDefaultDisplay().createStack( + WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); + ActivityStack recentsStack = mTestService.mStackSupervisor.getDefaultDisplay().createStack( WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_RECENTS, true /* onTop */); - ActivityRecord recentsActivity = new ActivityBuilder(mService) + ActivityRecord recentsActivity = new ActivityBuilder(mTestService) .setComponent(mRecentsComponent) .setCreateTask(true) .setStack(recentsStack) .build(); - ActivityStack fullscreenStack2 = mService.mStackSupervisor.getDefaultDisplay().createStack( - WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); - ActivityRecord fsActivity = new ActivityBuilder(mService) + ActivityStack fullscreenStack2 = + mTestService.mStackSupervisor.getDefaultDisplay().createStack( + WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */); + ActivityRecord fsActivity = new ActivityBuilder(mTestService) .setComponent(new ComponentName(mContext.getPackageName(), "App1")) .setCreateTask(true) .setStack(fullscreenStack2) .build(); - doReturn(true).when(mService.mWindowManager).canStartRecentsAnimation(); + doReturn(true).when(mTestService.mWindowManager).canStartRecentsAnimation(); // Start the recents animation Intent recentsIntent = new Intent(); recentsIntent.setComponent(mRecentsComponent); - mService.startRecentsActivity(recentsIntent, null, mock(IRecentsAnimationRunner.class)); + mTestService.startRecentsActivity(recentsIntent, null, mock(IRecentsAnimationRunner.class)); fullscreenStack.moveToFront("Activity start"); // Ensure that the recents animation was canceled - verify(mService.mWindowManager, times(1)).cancelRecentsAnimationSynchronously( + verify(mTestService.mWindowManager, times(1)).cancelRecentsAnimationSynchronously( eq(REORDER_KEEP_IN_PLACE), any()); } diff --git a/services/tests/servicestests/src/com/android/server/am/RunningTasksTest.java b/services/tests/wmtests/src/com/android/server/am/RunningTasksTest.java index 849a41183672..656cbf0afe07 100644 --- a/services/tests/servicestests/src/com/android/server/am/RunningTasksTest.java +++ b/services/tests/wmtests/src/com/android/server/am/RunningTasksTest.java @@ -22,46 +22,39 @@ import static android.view.Display.DEFAULT_DISPLAY; import static com.android.server.am.ActivityDisplay.POSITION_BOTTOM; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; + +import static org.junit.Assert.assertEquals; import android.app.ActivityManager.RunningTaskInfo; import android.content.ComponentName; -import android.content.Context; import android.platform.test.annotations.Presubmit; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.ArrayList; /** - * atest FrameworksServicesTests:RunningTasksTest + * Build/Install/Run: + * atest WmTests:RunningTasksTest */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class RunningTasksTest extends ActivityTestsBase { - private Context mContext = InstrumentationRegistry.getContext(); - private RunningTasks mRunningTasks; @Before - @Override public void setUp() throws Exception { - super.setUp(); - setupActivityTaskManagerService(); mRunningTasks = new RunningTasks(); } @Test - public void testCollectTasksByLastActiveTime() throws Exception { + public void testCollectTasksByLastActiveTime() { // Create a number of stacks with tasks (of incrementing active time) final ArrayList<ActivityDisplay> displays = new ArrayList<>(); final ActivityDisplay display = TestActivityDisplay.create(mSupervisor, DEFAULT_DISPLAY); @@ -86,9 +79,9 @@ public class RunningTasksTest extends ActivityTestsBase { ArrayList<RunningTaskInfo> tasks = new ArrayList<>(); mRunningTasks.getTasks(5, tasks, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED, displays, -1 /* callingUid */, true /* allowed */); - assertTrue(tasks.size() == numFetchTasks); + assertThat(tasks).hasSize(numFetchTasks); for (int i = 0; i < numFetchTasks; i++) { - assertTrue(tasks.get(i).id == (numTasks - i - 1)); + assertEquals(numTasks - i - 1, tasks.get(i).id); } // Ensure that requesting more than the total number of tasks only returns the subset @@ -96,9 +89,9 @@ public class RunningTasksTest extends ActivityTestsBase { tasks.clear(); mRunningTasks.getTasks(100, tasks, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED, displays, -1 /* callingUid */, true /* allowed */); - assertTrue(tasks.size() == numTasks); + assertThat(tasks).hasSize(numTasks); for (int i = 0; i < numTasks; i++) { - assertTrue(tasks.get(i).id == (numTasks - i - 1)); + assertEquals(numTasks - i - 1, tasks.get(i).id); } } @@ -119,4 +112,4 @@ public class RunningTasksTest extends ActivityTestsBase { .build(); return task; } -}
\ No newline at end of file +} diff --git a/services/tests/servicestests/src/com/android/server/am/SafeActivityOptionsTest.java b/services/tests/wmtests/src/com/android/server/am/SafeActivityOptionsTest.java index 8e4e7e6b63c3..100e0ddd970d 100644 --- a/services/tests/servicestests/src/com/android/server/am/SafeActivityOptionsTest.java +++ b/services/tests/wmtests/src/com/android/server/am/SafeActivityOptionsTest.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -23,15 +23,16 @@ import android.platform.test.annotations.Presubmit; import androidx.test.filters.FlakyTest; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import org.junit.Test; -import org.junit.runner.RunWith; +/** + * Build/Install/Run: + * atest WmTests:SafeActivityOptionsTest + */ @MediumTest -@Presubmit @FlakyTest -@RunWith(AndroidJUnit4.class) +@Presubmit public class SafeActivityOptionsTest { @Test diff --git a/services/tests/servicestests/src/com/android/server/am/TaskLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/am/TaskLaunchParamsModifierTests.java index b7f2b3581fb6..d5beac3845ac 100644 --- a/services/tests/servicestests/src/com/android/server/am/TaskLaunchParamsModifierTests.java +++ b/services/tests/wmtests/src/com/android/server/am/TaskLaunchParamsModifierTests.java @@ -22,8 +22,6 @@ import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE; -import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; -import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED; import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; import static android.util.DisplayMetrics.DENSITY_DEFAULT; import static android.view.Display.DEFAULT_DISPLAY; @@ -32,7 +30,6 @@ import static com.android.server.am.LaunchParamsController.LaunchParamsModifier. import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -46,15 +43,13 @@ import android.os.Build; import android.platform.test.annotations.Presubmit; import android.view.Gravity; -import androidx.test.filters.SmallTest; import androidx.test.filters.FlakyTest; -import androidx.test.runner.AndroidJUnit4; +import androidx.test.filters.SmallTest; import com.android.server.am.LaunchParamsController.LaunchParams; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.Locale; @@ -62,12 +57,11 @@ import java.util.Locale; * Tests for default task bounds. * * Build/Install/Run: - * atest FrameworksServicesTests:TaskLaunchParamsModifierTests + * atest WmTests:TaskLaunchParamsModifierTests */ @SmallTest -@Presubmit -@RunWith(AndroidJUnit4.class) @FlakyTest(detail = "Confirm stable in post-submit before removing") +@Presubmit public class TaskLaunchParamsModifierTests extends ActivityTestsBase { private ActivityRecord mActivity; @@ -78,10 +72,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { private LaunchParams mResult; @Before - @Override public void setUp() throws Exception { - super.setUp(); - setupActivityTaskManagerService(); mService.mSupportsFreeformWindowManagement = true; when(mSupervisor.canUseActivityOptionsLaunchBounds(any())).thenCallRealMethod(); @@ -1027,8 +1018,7 @@ public class TaskLaunchParamsModifierTests extends ActivityTestsBase { assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null, mActivity, /* source */ null, options, mCurrent, mResult)); - assertEquals(new Rect(0, 0, 1680, - 953), mResult.mBounds); + assertEquals(new Rect(0, 0, 1680, 953), mResult.mBounds); } private TestActivityDisplay createNewActivityDisplay(int windowingMode) { diff --git a/services/tests/servicestests/src/com/android/server/am/TaskPersisterTest.java b/services/tests/wmtests/src/com/android/server/am/TaskPersisterTest.java index 48bfe1d963af..9da336ff24d6 100644 --- a/services/tests/servicestests/src/com/android/server/am/TaskPersisterTest.java +++ b/services/tests/wmtests/src/com/android/server/am/TaskPersisterTest.java @@ -16,54 +16,56 @@ package com.android.server.am; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static androidx.test.InstrumentationRegistry.getTargetContext; - +import android.content.Context; import android.content.pm.UserInfo; import android.os.UserHandle; import android.os.UserManager; import android.platform.test.annotations.Presubmit; import android.util.SparseBooleanArray; +import androidx.test.filters.FlakyTest; + import org.junit.After; import org.junit.Before; import org.junit.Test; -import androidx.test.filters.FlakyTest; - /** * Tests for {@link TaskPersister}. * * Build/Install/Run: - * atest FrameworksServicesTests:TaskPersisterTest + * atest WmTests:TaskPersisterTest */ -@Presubmit @FlakyTest(detail = "Promote to presubmit if stable") +@Presubmit public class TaskPersisterTest { private static final String TEST_USER_NAME = "AM-Test-User"; private TaskPersister mTaskPersister; - private int testUserId; + private int mTestUserId; private UserManager mUserManager; @Before public void setUp() throws Exception { - mUserManager = UserManager.get(getTargetContext()); - mTaskPersister = new TaskPersister(getTargetContext().getFilesDir()); + final Context context = getInstrumentation().getTargetContext(); + mUserManager = UserManager.get(context); + mTaskPersister = new TaskPersister(context.getFilesDir()); // In ARC, the maximum number of supported users is one, which is different from the ones of // most phones (more than 4). This prevents TaskPersisterTest from creating another user for // test. However, since guest users can be added as much as possible, we create guest user // in the test. - testUserId = createUser(TEST_USER_NAME, UserInfo.FLAG_GUEST); + mTestUserId = createUser(TEST_USER_NAME, UserInfo.FLAG_GUEST); } @After public void tearDown() throws Exception { - mTaskPersister.unloadUserDataFromMemory(testUserId); - removeUser(testUserId); + mTaskPersister.unloadUserDataFromMemory(mTestUserId); + removeUser(mTestUserId); } private int getRandomTaskIdForUser(int userId) { @@ -76,11 +78,11 @@ public class TaskPersisterTest { public void testTaskIdsPersistence() { SparseBooleanArray taskIdsOnFile = new SparseBooleanArray(); for (int i = 0; i < 100; i++) { - taskIdsOnFile.put(getRandomTaskIdForUser(testUserId), true); + taskIdsOnFile.put(getRandomTaskIdForUser(mTestUserId), true); } - mTaskPersister.writePersistedTaskIdsForUser(taskIdsOnFile, testUserId); + mTaskPersister.writePersistedTaskIdsForUser(taskIdsOnFile, mTestUserId); SparseBooleanArray newTaskIdsOnFile = mTaskPersister - .loadPersistedTaskIdsForUser(testUserId); + .loadPersistedTaskIdsForUser(mTestUserId); assertEquals("TaskIds written differ from TaskIds read back from file", taskIdsOnFile, newTaskIdsOnFile); } diff --git a/services/tests/servicestests/src/com/android/server/am/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/am/TaskRecordTests.java index 27766d3d8d6c..240a1d102aef 100644 --- a/services/tests/servicestests/src/com/android/server/am/TaskRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/am/TaskRecordTests.java @@ -12,7 +12,6 @@ * 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.server.am; @@ -35,14 +34,12 @@ import android.service.voice.IVoiceInteractionSession; import android.util.Xml; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import com.android.internal.app.IVoiceInteractor; import com.android.server.am.TaskRecord.TaskRecordFactory; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; @@ -60,18 +57,16 @@ import java.util.ArrayList; * Tests for exercising {@link TaskRecord}. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.TaskRecordTests + * atest WmTests:TaskRecordTests */ @MediumTest @Presubmit -@RunWith(AndroidJUnit4.class) public class TaskRecordTests extends ActivityTestsBase { private static final String TASK_TAG = "task"; @Before public void setUp() throws Exception { - super.setUp(); TaskRecord.setTaskRecordFactory(null); setupActivityTaskManagerService(); } @@ -124,7 +119,7 @@ public class TaskRecordTests extends ActivityTestsBase { private File serializeToFile(TaskRecord r) throws IOException, XmlPullParserException { final File tmpFile = File.createTempFile(r.taskId + "_task_", "xml"); - try (final OutputStream os = new FileOutputStream(tmpFile)) { + try (OutputStream os = new FileOutputStream(tmpFile)) { final XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument(null, true); @@ -138,7 +133,7 @@ public class TaskRecordTests extends ActivityTestsBase { } private TaskRecord restoreFromFile(File file) throws IOException, XmlPullParserException { - try (final Reader reader = new BufferedReader(new FileReader(file))) { + try (Reader reader = new BufferedReader(new FileReader(file))) { final XmlPullParser parser = Xml.newPullParser(); parser.setInput(reader); assertEquals(XmlPullParser.START_TAG, parser.next()); diff --git a/services/tests/servicestests/src/com/android/server/am/TaskStackChangedListenerTest.java b/services/tests/wmtests/src/com/android/server/am/TaskStackChangedListenerTest.java index 3f7c7148381e..6888da664146 100644 --- a/services/tests/servicestests/src/com/android/server/am/TaskStackChangedListenerTest.java +++ b/services/tests/wmtests/src/com/android/server/am/TaskStackChangedListenerTest.java @@ -11,12 +11,12 @@ * 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 + * limitations under the License. */ package com.android.server.am; -import static androidx.test.InstrumentationRegistry.getInstrumentation; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -38,23 +38,22 @@ import android.os.RemoteException; import android.support.test.uiautomator.UiDevice; import android.text.TextUtils; -import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; -import androidx.test.runner.AndroidJUnit4; import com.android.internal.annotations.GuardedBy; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +/** + * Build/Install/Run: + * atest WmTests:TaskStackChangedListenerTest + */ @MediumTest -@RunWith(AndroidJUnit4.class) public class TaskStackChangedListenerTest { private IActivityManager mService; @@ -87,13 +86,13 @@ public class TaskStackChangedListenerTest { } }); - Context ctx = InstrumentationRegistry.getContext(); - ctx.startActivity(new Intent(ctx, ActivityA.class)); + Context context = getInstrumentation().getContext(); + context.startActivity(new Intent(context, ActivityA.class)); UiDevice.getInstance(getInstrumentation()).waitForIdle(); synchronized (sLock) { - Assert.assertTrue(sTaskStackChangedCalled); + assertTrue(sTaskStackChangedCalled); } - Assert.assertTrue(sActivityBResumed); + assertTrue(sActivityBResumed); } @Test @@ -101,17 +100,17 @@ public class TaskStackChangedListenerTest { final Object[] params = new Object[2]; final CountDownLatch latch = new CountDownLatch(1); registerTaskStackChangedListener(new TaskStackListener() { - int taskId = -1; + int mTaskId = -1; @Override public void onTaskCreated(int taskId, ComponentName componentName) throws RemoteException { - this.taskId = taskId; + mTaskId = taskId; } @Override public void onTaskDescriptionChanged(int taskId, TaskDescription td) throws RemoteException { - if (this.taskId == taskId && !TextUtils.isEmpty(td.getLabel())) { + if (mTaskId == taskId && !TextUtils.isEmpty(td.getLabel())) { params[0] = taskId; params[1] = td; latch.countDown(); @@ -204,7 +203,7 @@ public class TaskStackChangedListenerTest { activity.finishAndRemoveTask(); waitForCallback(taskRemovalStartedLatch); // onTaskRemovalStarted happens before the activity's window is removed. - assertFalse(activity.onDetachedFromWindowCalled); + assertFalse(activity.mOnDetachedFromWindowCalled); assertEquals(id, params[0]); // Test for onTaskRemoved. @@ -212,19 +211,18 @@ public class TaskStackChangedListenerTest { waitForCallback(taskRemovedLatch); assertEquals(id, params[0]); waitForCallback(onDetachedFromWindowLatch); - assertTrue(activity.onDetachedFromWindowCalled); + assertTrue(activity.mOnDetachedFromWindowCalled); } /** * Starts the provided activity and returns the started instance. */ private TestActivity startTestActivity(Class<?> activityClass) throws InterruptedException { - final Context context = InstrumentationRegistry.getContext(); - final ActivityMonitor monitor = - new ActivityMonitor(activityClass.getName(), null, false); - InstrumentationRegistry.getInstrumentation().addMonitor(monitor); + final ActivityMonitor monitor = new ActivityMonitor(activityClass.getName(), null, false); + getInstrumentation().addMonitor(monitor); + final Context context = getInstrumentation().getContext(); context.startActivity(new Intent(context, activityClass)); - final TestActivity activity = (TestActivity)monitor.waitForActivityWithTimeout(1000); + final TestActivity activity = (TestActivity) monitor.waitForActivityWithTimeout(1000); if (activity == null) { throw new RuntimeException("Timed out waiting for Activity"); } @@ -239,11 +237,12 @@ public class TaskStackChangedListenerTest { private void waitForCallback(CountDownLatch latch) { try { - final boolean result = latch.await(2, TimeUnit.SECONDS); + final boolean result = latch.await(2, TimeUnit.SECONDS); if (!result) { throw new RuntimeException("Timed out waiting for task stack change notification"); } - }catch (InterruptedException e) {} + } catch (InterruptedException e) { + } } public static class TestActivity extends Activity { @@ -271,6 +270,7 @@ public class TaskStackChangedListenerTest { * If isResumed is {@code true}, sleep the thread until the activity is resumed. * if {@code false}, sleep the thread until the activity is paused. */ + @SuppressWarnings("WaitNotInLoop") public void waitForResumeStateChange(boolean isResumed) throws InterruptedException { synchronized (this) { if (mIsResumed == isResumed) { @@ -278,7 +278,7 @@ public class TaskStackChangedListenerTest { } wait(5000); } - assertTrue("The activity resume state change timed out", mIsResumed == isResumed); + assertEquals("The activity resume state change timed out", isResumed, mIsResumed); } } @@ -330,17 +330,17 @@ public class TaskStackChangedListenerTest { } public static class ActivityTaskChangeCallbacks extends TestActivity { - boolean onDetachedFromWindowCalled = false; - CountDownLatch onDetachedFromWindowCountDownLatch; + public boolean mOnDetachedFromWindowCalled = false; + private CountDownLatch mOnDetachedFromWindowCountDownLatch; @Override public void onDetachedFromWindow() { - onDetachedFromWindowCalled = true; - onDetachedFromWindowCountDownLatch.countDown(); + mOnDetachedFromWindowCalled = true; + mOnDetachedFromWindowCountDownLatch.countDown(); } void setDetachedFromWindowLatch(CountDownLatch countDownLatch) { - onDetachedFromWindowCountDownLatch = countDownLatch; + mOnDetachedFromWindowCountDownLatch = countDownLatch; } } } diff --git a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java b/services/tests/wmtests/src/com/android/server/am/UserControllerTest.java index 75e1d0d800db..e55c4f7031a8 100644 --- a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java +++ b/services/tests/wmtests/src/com/android/server/am/UserControllerTest.java @@ -11,7 +11,7 @@ * 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 + * limitations under the License. */ package com.android.server.am; @@ -19,6 +19,8 @@ package com.android.server.am; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.testing.DexmakerShareClassLoaderRule.runWithDexmakerShareClassLoader; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + import static com.android.server.am.UserController.CONTINUE_USER_SWITCH_MSG; import static com.android.server.am.UserController.REPORT_LOCKED_BOOT_COMPLETE_MSG; import static com.android.server.am.UserController.REPORT_USER_SWITCH_COMPLETE_MSG; @@ -49,8 +51,6 @@ import static org.mockito.Mockito.validateMockitoUsage; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static androidx.test.InstrumentationRegistry.getTargetContext; - import android.app.IUserSwitchObserver; import android.content.Context; import android.content.IIntentReceiver; @@ -68,6 +68,8 @@ import android.os.UserManagerInternal; import android.platform.test.annotations.Presubmit; import android.util.Log; +import androidx.test.filters.SmallTest; + import com.android.server.pm.UserManagerService; import com.android.server.wm.WindowManagerService; @@ -81,20 +83,18 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import androidx.test.filters.SmallTest; - /** * Tests for {@link UserController}. * * Build/Install/Run: - * atest FrameworksServicesTests:com.android.server.am.UserControllerTest + * atest WmTests:UserControllerTest */ -@Presubmit @SmallTest +@Presubmit public class UserControllerTest { private static final int TEST_USER_ID = 10; private static final int NONEXIST_USER_ID = 2; - private static String TAG = UserControllerTest.class.getSimpleName(); + private static final String TAG = UserControllerTest.class.getSimpleName(); private UserController mUserController; private TestInjector mInjector; @@ -121,7 +121,7 @@ public class UserControllerTest { @Before public void setUp() throws Exception { runWithDexmakerShareClassLoader(() -> { - mInjector = spy(new TestInjector(getTargetContext())); + mInjector = spy(new TestInjector(getInstrumentation().getTargetContext())); doNothing().when(mInjector).clearAllLockedTasks(anyString()); doNothing().when(mInjector).startHomeActivity(anyInt(), anyString()); doReturn(false).when(mInjector).stackSupervisorSwitchUser(anyInt(), any()); @@ -133,7 +133,7 @@ public class UserControllerTest { @After public void tearDown() throws Exception { - mInjector.handlerThread.quit(); + mInjector.mHandlerThread.quit(); validateMockitoUsage(); } @@ -169,8 +169,8 @@ public class UserControllerTest { private void startUserAssertions( List<String> expectedActions, Set<Integer> expectedMessageCodes) { - assertEquals(expectedActions, getActions(mInjector.sentIntents)); - Set<Integer> actualCodes = mInjector.handler.getMessageCodes(); + assertEquals(expectedActions, getActions(mInjector.mSentIntents)); + Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); assertEquals("Unexpected message sent", expectedMessageCodes, actualCodes); } @@ -180,7 +180,7 @@ public class UserControllerTest { private void startForegroundUserAssertions() { startUserAssertions(START_FOREGROUND_USER_ACTIONS, START_FOREGROUND_USER_MESSAGE_CODES); - Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG); + Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; assertNotNull(userState); @@ -211,19 +211,19 @@ public class UserControllerTest { mUserController.registerUserSwitchObserver(observer, "mock"); // Start user -- this will update state of mUserController mUserController.startUser(TEST_USER_ID, true); - Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG); + Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; int oldUserId = reportMsg.arg1; int newUserId = reportMsg.arg2; // Call dispatchUserSwitch and verify that observer was called only once - mInjector.handler.clearAllRecordedMessages(); + mInjector.mHandler.clearAllRecordedMessages(); mUserController.dispatchUserSwitch(userState, oldUserId, newUserId); verify(observer, times(1)).onUserSwitching(eq(TEST_USER_ID), any()); Set<Integer> expectedCodes = Collections.singleton(CONTINUE_USER_SWITCH_MSG); - Set<Integer> actualCodes = mInjector.handler.getMessageCodes(); + Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); assertEquals("Unexpected message sent", expectedCodes, actualCodes); - Message conMsg = mInjector.handler.getMessageForCode(CONTINUE_USER_SWITCH_MSG); + Message conMsg = mInjector.mHandler.getMessageForCode(CONTINUE_USER_SWITCH_MSG); assertNotNull(conMsg); userState = (UserState) conMsg.obj; assertNotNull(userState); @@ -241,17 +241,17 @@ public class UserControllerTest { mUserController.registerUserSwitchObserver(observer, "mock"); // Start user -- this will update state of mUserController mUserController.startUser(TEST_USER_ID, true); - Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG); + Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; int oldUserId = reportMsg.arg1; int newUserId = reportMsg.arg2; // Call dispatchUserSwitch and verify that observer was called only once - mInjector.handler.clearAllRecordedMessages(); + mInjector.mHandler.clearAllRecordedMessages(); mUserController.dispatchUserSwitch(userState, oldUserId, newUserId); verify(observer, times(1)).onUserSwitching(eq(TEST_USER_ID), any()); // Verify that CONTINUE_USER_SWITCH_MSG is not sent (triggers timeout) - Set<Integer> actualCodes = mInjector.handler.getMessageCodes(); + Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); assertWithMessage("No messages should be sent").that(actualCodes).isEmpty(); } @@ -259,12 +259,12 @@ public class UserControllerTest { public void testContinueUserSwitch() { // Start user -- this will update state of mUserController mUserController.startUser(TEST_USER_ID, true); - Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG); + Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; int oldUserId = reportMsg.arg1; int newUserId = reportMsg.arg2; - mInjector.handler.clearAllRecordedMessages(); + mInjector.mHandler.clearAllRecordedMessages(); // Verify that continueUserSwitch worked as expected mUserController.continueUserSwitch(userState, oldUserId, newUserId); verify(mInjector.getWindowManager(), times(1)).stopFreezingScreen(); @@ -276,12 +276,12 @@ public class UserControllerTest { mUserController.mUserSwitchUiEnabled = false; // Start user -- this will update state of mUserController mUserController.startUser(TEST_USER_ID, true); - Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG); + Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); UserState userState = (UserState) reportMsg.obj; int oldUserId = reportMsg.arg1; int newUserId = reportMsg.arg2; - mInjector.handler.clearAllRecordedMessages(); + mInjector.mHandler.clearAllRecordedMessages(); // Verify that continueUserSwitch worked as expected mUserController.continueUserSwitch(userState, oldUserId, newUserId); verify(mInjector.getWindowManager(), never()).stopFreezingScreen(); @@ -290,9 +290,9 @@ public class UserControllerTest { private void continueUserSwitchAssertions() { Set<Integer> expectedCodes = Collections.singleton(REPORT_USER_SWITCH_COMPLETE_MSG); - Set<Integer> actualCodes = mInjector.handler.getMessageCodes(); + Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes(); assertEquals("Unexpected message sent", expectedCodes, actualCodes); - Message msg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_COMPLETE_MSG); + Message msg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_COMPLETE_MSG); assertNotNull(msg); assertEquals("Unexpected userId", TEST_USER_ID, msg.arg1); } @@ -305,10 +305,10 @@ public class UserControllerTest { mUserController.registerUserSwitchObserver(observer, "mock"); // Start user -- this will update state of mUserController mUserController.startUser(TEST_USER_ID, true); - Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG); + Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG); assertNotNull(reportMsg); int newUserId = reportMsg.arg2; - mInjector.handler.clearAllRecordedMessages(); + mInjector.mHandler.clearAllRecordedMessages(); // Mockito can't reset only interactions, so just verify that this hasn't been // called with 'false' until after dispatchUserSwitchComplete. verify(mInjector.getWindowManager(), never()).setSwitchingUser(false); @@ -321,7 +321,7 @@ public class UserControllerTest { private void setUpUser(int userId, int flags) { UserInfo userInfo = new UserInfo(userId, "User" + userId, flags); - when(mInjector.userManagerMock.getUserInfo(eq(userId))).thenReturn(userInfo); + when(mInjector.mUserManagerMock.getUserInfo(eq(userId))).thenReturn(userInfo); } private static List<String> getActions(List<Intent> intents) { @@ -334,45 +334,46 @@ public class UserControllerTest { // Should be public to allow mocking private static class TestInjector extends UserController.Injector { - TestHandler handler; - TestHandler uiHandler; - HandlerThread handlerThread; - UserManagerService userManagerMock; - UserManagerInternal userManagerInternalMock; - WindowManagerService windowManagerMock; - private Context mCtx; - List<Intent> sentIntents = new ArrayList<>(); + public final TestHandler mHandler; + public final HandlerThread mHandlerThread; + public final UserManagerService mUserManagerMock; + public final List<Intent> mSentIntents = new ArrayList<>(); + + private final TestHandler mUiHandler; + private final UserManagerInternal mUserManagerInternalMock; + private final WindowManagerService mWindowManagerMock; + private final Context mCtx; TestInjector(Context ctx) { super(null); mCtx = ctx; - handlerThread = new HandlerThread(TAG); - handlerThread.start(); - handler = new TestHandler(handlerThread.getLooper()); - uiHandler = new TestHandler(handlerThread.getLooper()); - userManagerMock = mock(UserManagerService.class); - userManagerInternalMock = mock(UserManagerInternal.class); - windowManagerMock = mock(WindowManagerService.class); + mHandlerThread = new HandlerThread(TAG); + mHandlerThread.start(); + mHandler = new TestHandler(mHandlerThread.getLooper()); + mUiHandler = new TestHandler(mHandlerThread.getLooper()); + mUserManagerMock = mock(UserManagerService.class); + mUserManagerInternalMock = mock(UserManagerInternal.class); + mWindowManagerMock = mock(WindowManagerService.class); } @Override protected Handler getHandler(Handler.Callback callback) { - return handler; + return mHandler; } @Override protected Handler getUiHandler(Handler.Callback callback) { - return uiHandler; + return mUiHandler; } @Override protected UserManagerService getUserManager() { - return userManagerMock; + return mUserManagerMock; } @Override UserManagerInternal getUserManagerInternal() { - return userManagerInternalMock; + return mUserManagerInternalMock; } @Override @@ -388,7 +389,7 @@ public class UserControllerTest { @Override WindowManagerService getWindowManager() { - return windowManagerMock; + return mWindowManagerMock; } @Override @@ -402,7 +403,7 @@ public class UserControllerTest { String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) { Log.i(TAG, "broadcastIntentLocked " + intent); - sentIntents.add(intent); + mSentIntents.add(intent); return 0; } diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java new file mode 100644 index 000000000000..49643d2445a9 --- /dev/null +++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2017 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.server.wm; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyFloat; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.content.res.Configuration; +import android.graphics.Rect; + +import org.mockito.invocation.InvocationOnMock; + +/** + * A collection of static functions that can be referenced by other test packages to provide access + * to WindowManager related test functionality. + */ +public class WindowTestUtils { + /** + * Retrieves an instance of a mock {@link WindowManagerService}. + */ + public static WindowManagerService getMockWindowManagerService() { + final WindowManagerService service = mock(WindowManagerService.class); + final WindowHashMap windowMap = new WindowHashMap(); + when(service.getWindowManagerLock()).thenReturn(windowMap); + return service; + } + + /** + * Creates a mock instance of {@link StackWindowController}. + */ + public static StackWindowController createMockStackWindowContainerController() { + StackWindowController controller = mock(StackWindowController.class); + controller.mContainer = mock(TestTaskStack.class); + + // many components rely on the {@link StackWindowController#adjustConfigurationForBounds} + // to properly set bounds values in the configuration. We must mimick those actions here. + doAnswer((InvocationOnMock invocationOnMock) -> { + final Configuration config = invocationOnMock.<Configuration>getArgument(7); + final Rect bounds = invocationOnMock.<Rect>getArgument(0); + config.windowConfiguration.setBounds(bounds); + return null; + }).when(controller).adjustConfigurationForBounds(any(), any(), any(), any(), + anyBoolean(), anyBoolean(), anyFloat(), any(), any(), anyInt()); + + return controller; + } + + /** + * An extension of {@link TestTaskStack}, which overrides package scoped methods that would not + * normally be mocked out. + */ + public static class TestTaskStack extends TaskStack { + TestTaskStack(WindowManagerService service, int stackId) { + super(service, stackId, null); + } + + @Override + void addTask(Task task, int position, boolean showForAllUsers, boolean moveParents) { + // Do nothing. + } + } +} |