Merge "Migrate model tests to multivalent" into main

This commit is contained in:
Uwais Ashraf authored and Android (Google) Code Review committed 2024-08-21 10:05:40 +00:00
commit 06ffcf8c61
27 files changed
+673 -193

No files matched your search

@@ -0,0 +1,201 @@
/*
* Copyright (C) 2024 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.launcher3.folder
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.folder.FolderNameInfos.*
import org.junit.Test
import org.junit.runner.RunWith
data class Label(val index: Int, val label: String, val score: Float)
@SmallTest
@RunWith(AndroidJUnit4::class)
class FolderNameInfosTest {
companion object {
val statusList =
listOf(
SUCCESS,
HAS_PRIMARY,
HAS_SUGGESTIONS,
ERROR_NO_PROVIDER,
ERROR_APP_LOOKUP_FAILED,
ERROR_ALL_APP_LOOKUP_FAILED,
ERROR_NO_LABELS_GENERATED,
ERROR_LABEL_LOOKUP_FAILED,
ERROR_ALL_LABEL_LOOKUP_FAILED,
ERROR_NO_PACKAGES,
)
}
@Test
fun status() {
assertStatus(statusList)
assertStatus(
listOf(
ERROR_NO_PROVIDER,
ERROR_APP_LOOKUP_FAILED,
ERROR_ALL_APP_LOOKUP_FAILED,
ERROR_NO_LABELS_GENERATED,
ERROR_LABEL_LOOKUP_FAILED,
ERROR_ALL_LABEL_LOOKUP_FAILED,
ERROR_NO_PACKAGES,
)
)
assertStatus(
listOf(
SUCCESS,
HAS_PRIMARY,
HAS_SUGGESTIONS,
)
)
assertStatus(
listOf(
SUCCESS,
HAS_PRIMARY,
HAS_SUGGESTIONS,
)
)
}
fun assertStatus(statusList: List<Int>) {
var infos = FolderNameInfos()
statusList.forEach { infos.setStatus(it) }
assert(infos.status() == statusList.sum()) {
"There is an overlap on the status constants!"
}
}
@Test
fun hasPrimary() {
assertHasPrimary(
createNameInfos(listOf(Label(0, "label", 1f)), statusList),
hasPrimary = true
)
assertHasPrimary(
createNameInfos(listOf(Label(1, "label", 1f)), statusList),
hasPrimary = false
)
assertHasPrimary(
createNameInfos(
listOf(Label(0, "label", 1f)),
listOf(
ERROR_NO_PROVIDER,
ERROR_APP_LOOKUP_FAILED,
ERROR_ALL_APP_LOOKUP_FAILED,
ERROR_NO_LABELS_GENERATED,
ERROR_LABEL_LOOKUP_FAILED,
ERROR_ALL_LABEL_LOOKUP_FAILED,
ERROR_NO_PACKAGES,
)
),
hasPrimary = false
)
}
private fun assertHasPrimary(nameInfos: FolderNameInfos, hasPrimary: Boolean) =
assert(nameInfos.hasPrimary() == hasPrimary)
private fun createNameInfos(labels: List<Label>?, statusList: List<Int>?): FolderNameInfos {
val infos = FolderNameInfos()
labels?.forEach { infos.setLabel(it.index, it.label, it.score) }
statusList?.forEach { infos.setStatus(it) }
return infos
}
@Test
fun hasSuggestions() {
assertHasSuggestions(
createNameInfos(listOf(Label(0, "label", 1f)), null),
hasSuggestions = true
)
assertHasSuggestions(createNameInfos(null, null), hasSuggestions = false)
// There is a max of 4 suggestions
assertHasSuggestions(
createNameInfos(listOf(Label(5, "label", 1f)), null),
hasSuggestions = false
)
assertHasSuggestions(
createNameInfos(
listOf(
Label(0, "label", 1f),
Label(1, "label", 1f),
Label(2, "label", 1f),
Label(3, "label", 1f)
),
null
),
hasSuggestions = true
)
}
private fun assertHasSuggestions(nameInfos: FolderNameInfos, hasSuggestions: Boolean) =
assert(nameInfos.hasSuggestions() == hasSuggestions)
@Test
fun hasContains() {
assertContains(
createNameInfos(
listOf(
Label(0, "label1", 1f),
Label(1, "label2", 1f),
Label(2, "label3", 1f),
Label(3, "label4", 1f)
),
null
),
label = Label(-1, "label3", -1f),
contains = true
)
assertContains(
createNameInfos(
listOf(
Label(0, "label1", 1f),
Label(1, "label2", 1f),
Label(2, "label3", 1f),
Label(3, "label4", 1f)
),
null
),
label = Label(-1, "label5", -1f),
contains = false
)
assertContains(
createNameInfos(null, null),
label = Label(-1, "label1", -1f),
contains = false
)
assertContains(
createNameInfos(
listOf(
Label(0, "label1", 1f),
Label(1, "label2", 1f),
Label(2, "lAbel3", 1f),
Label(3, "lEbel4", 1f)
),
null
),
label = Label(-1, "LaBEl3", -1f),
contains = true
)
}
private fun assertContains(nameInfos: FolderNameInfos, label: Label, contains: Boolean) =
assert(nameInfos.contains(label.label) == contains)
}
@@ -0,0 +1,172 @@
/*
* Copyright (C) 2024 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.launcher3.folder
import android.graphics.Point
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import org.junit.Test
import org.junit.runner.RunWith
data class TestCase(val maxCountX: Int, val maxCountY: Int, val totalItems: Int)
@SmallTest
@RunWith(AndroidJUnit4::class)
class FolderPagedViewTest {
companion object {
private fun makeFolderGridOrganizer(testCase: TestCase): FolderGridOrganizer {
val folderGridOrganizer = FolderGridOrganizer(testCase.maxCountX, testCase.maxCountY)
folderGridOrganizer.setContentSize(testCase.totalItems)
return folderGridOrganizer
}
}
@Test
fun setContentSize() {
assertCountXandY(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 22),
expectedCountX = 4,
expectedCountY = 3
)
assertCountXandY(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 8),
expectedCountX = 3,
expectedCountY = 3
)
assertCountXandY(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 3),
expectedCountX = 2,
expectedCountY = 2
)
}
private fun assertCountXandY(testCase: TestCase, expectedCountX: Int, expectedCountY: Int) {
val folderGridOrganizer = makeFolderGridOrganizer(testCase)
assert(folderGridOrganizer.countX == expectedCountX) {
"Error on expected countX $expectedCountX got ${folderGridOrganizer.countX} using test case $testCase"
}
assert(folderGridOrganizer.countY == expectedCountY) {
"Error on expected countY $expectedCountY got ${folderGridOrganizer.countY} using test case $testCase"
}
}
@Test
fun getPosForRank() {
assertFolderRank(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 22),
expectedPos = Point(0, 0),
rank = 0
)
assertFolderRank(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 22),
expectedPos = Point(1, 0),
rank = 1
)
assertFolderRank(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 22),
expectedPos = Point(3, 0),
rank = 3
)
assertFolderRank(
TestCase(maxCountX = 4, maxCountY = 3, totalItems = 22),
expectedPos = Point(2, 1),
rank = 6
)
val testCase = TestCase(maxCountX = 4, maxCountY = 3, totalItems = 22)
// Rank 16 and 38 should yield the same point since 38 % 12 == 2
val folderGridOrganizer = makeFolderGridOrganizer(testCase)
assertFolderRank(testCase, expectedPos = folderGridOrganizer.getPosForRank(2), rank = 38)
}
private fun assertFolderRank(testCase: TestCase, expectedPos: Point, rank: Int) {
val folderGridOrganizer = makeFolderGridOrganizer(testCase)
val pos = folderGridOrganizer.getPosForRank(rank)
assert(pos == expectedPos) {
"Expected pos = $expectedPos doesn't match pos = $pos for the given rank $rank and the give test case $testCase"
}
}
@Test
fun isItemInPreview() {
val folderGridOrganizer = FolderGridOrganizer(5, 8)
folderGridOrganizer.setContentSize(ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW - 1)
// Very few items
for (i in 0..3) {
assertItemsInPreview(
TestCase(
maxCountX = 5,
maxCountY = 8,
totalItems = ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW - 1
),
expectedIsInPreview = true,
page = 0,
rank = i
)
}
for (i in 4..40) {
assertItemsInPreview(
TestCase(
maxCountX = 5,
maxCountY = 8,
totalItems = ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW - 1
),
expectedIsInPreview = false,
page = 0,
rank = i
)
}
// Full of items
assertItemsInPreview(
TestCase(maxCountX = 5, maxCountY = 8, totalItems = 40),
expectedIsInPreview = false,
page = 0,
rank = 2
)
assertItemsInPreview(
TestCase(maxCountX = 5, maxCountY = 8, totalItems = 40),
expectedIsInPreview = false,
page = 0,
rank = 2
)
assertItemsInPreview(
TestCase(maxCountX = 5, maxCountY = 8, totalItems = 40),
expectedIsInPreview = true,
page = 0,
rank = 5
)
assertItemsInPreview(
TestCase(maxCountX = 5, maxCountY = 8, totalItems = 40),
expectedIsInPreview = true,
page = 0,
rank = 6
)
}
private fun assertItemsInPreview(
testCase: TestCase,
expectedIsInPreview: Boolean,
page: Int,
rank: Int
) {
val folderGridOrganizer = makeFolderGridOrganizer(testCase)
val isInPreview = folderGridOrganizer.isItemInPreview(page, rank)
assert(isInPreview == expectedIsInPreview) {
"Item preview state should be $expectedIsInPreview but got $isInPreview, for page $page and rank $rank, for test case $testCase"
}
}
}
@@ -0,0 +1,928 @@
/*
* Copyright (C) 2024 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.launcher3.folder
import android.content.Context
import android.graphics.Point
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.Alarm
import com.android.launcher3.DragSource
import com.android.launcher3.DropTarget.DragObject
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER
import com.android.launcher3.OnAlarmListener
import com.android.launcher3.R
import com.android.launcher3.celllayout.board.FolderPoint
import com.android.launcher3.celllayout.board.TestWorkspaceBuilder
import com.android.launcher3.dragndrop.DragController
import com.android.launcher3.dragndrop.DragOptions
import com.android.launcher3.dragndrop.DragView
import com.android.launcher3.folder.Folder.MIN_CONTENT_DIMEN
import com.android.launcher3.folder.Folder.ON_EXIT_CLOSE_DELAY
import com.android.launcher3.folder.Folder.SCROLL_LEFT
import com.android.launcher3.folder.Folder.SCROLL_NONE
import com.android.launcher3.folder.Folder.STATE_ANIMATING
import com.android.launcher3.folder.Folder.STATE_CLOSED
import com.android.launcher3.model.data.FolderInfo
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.util.ActivityContextWrapper
import com.android.launcher3.util.ModelTestExtensions.clearModelDb
import java.util.ArrayList
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertNull
import junit.framework.TestCase.assertTrue
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.spy
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.kotlin.doNothing
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.whenever
/** Tests for [Folder] */
@SmallTest
@RunWith(AndroidJUnit4::class)
class FolderTest {
private val context: Context =
ActivityContextWrapper(ApplicationProvider.getApplicationContext())
private val workspaceBuilder = TestWorkspaceBuilder(context)
private val folder: Folder = spy(Folder(context, null))
@After
fun tearDown() {
LauncherAppState.getInstance(context).model.clearModelDb()
}
@Test
fun `Undo a folder with 1 icon when onDropCompleted is called`() {
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = folderInfo
folder.mInfo.getContents().removeAt(0)
folder.mContent = Mockito.mock(FolderPagedView::class.java)
val dragLayout = Mockito.mock(View::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
folder.deleteFolderOnDropCompleted = false
folder.onDropCompleted(dragLayout, dragObject, true)
verify(folder, times(1)).replaceFolderWithFinalItem()
assertEquals(folder.deleteFolderOnDropCompleted, false)
}
@Test
fun `Do not undo a folder with 2 icons when onDropCompleted is called`() {
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = folderInfo
folder.mContent = Mockito.mock(FolderPagedView::class.java)
val dragLayout = Mockito.mock(View::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
folder.deleteFolderOnDropCompleted = false
folder.onDropCompleted(dragLayout, dragObject, true)
verify(folder, times(0)).replaceFolderWithFinalItem()
assertEquals(folder.deleteFolderOnDropCompleted, false)
}
@Test
fun `Test that we accept valid item type ITEM_TYPE_APPLICATION`() {
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_APPLICATION
val willAcceptResult = Folder.willAccept(itemInfo)
assertTrue(willAcceptResult)
}
@Test
fun `Test that we accept valid item type ITEM_TYPE_DEEP_SHORTCUT`() {
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_DEEP_SHORTCUT
val willAcceptResult = Folder.willAccept(itemInfo)
assertTrue(willAcceptResult)
}
@Test
fun `Test that we accept valid item type ITEM_TYPE_APP_PAIR`() {
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_APP_PAIR
val willAcceptResult = Folder.willAccept(itemInfo)
assertTrue(willAcceptResult)
}
@Test
fun `Test that we do not accept invalid item type ITEM_TYPE_APPWIDGET`() {
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_APPWIDGET
val willAcceptResult = Folder.willAccept(itemInfo)
assertFalse(willAcceptResult)
}
@Test
fun `Test that we do not accept invalid item type ITEM_TYPE_FOLDER`() {
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_FOLDER
val willAcceptResult = Folder.willAccept(itemInfo)
assertFalse(willAcceptResult)
}
@Test
fun `We should not animate open if items is null or less than or equal to 1`() {
folder.mInfo = Mockito.mock(FolderInfo::class.java)
val shouldAnimateOpenResult = folder.shouldAnimateOpen(null)
assertFalse(shouldAnimateOpenResult)
assertFalse(
folder.shouldAnimateOpen(arrayListOf<ItemInfo>(Mockito.mock(ItemInfo::class.java)))
)
}
@Test
fun `We should animate open if items greater than 1`() {
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = folderInfo
val shouldAnimateOpenResult = folder.shouldAnimateOpen(folder.mInfo.getContents())
assertTrue(shouldAnimateOpenResult)
}
@Test
fun `Should be true if there is an open folder`() {
val closeOpenFolderResult = folder.closeOpenFolder(Mockito.mock(Folder::class.java))
assertTrue(closeOpenFolderResult)
}
@Test
fun `Should be false if the open folder is this folder`() {
val closeOpenFolderResult = folder.closeOpenFolder(folder)
assertFalse(closeOpenFolderResult)
}
@Test
fun `Should be false if there is not an open folder`() {
val closeOpenFolderResult = folder.closeOpenFolder(null)
assertFalse(closeOpenFolderResult)
}
@Test
fun `If drag is in progress we should set mItemAddedBackToSelfViaIcon to true`() {
folder.itemAddedBackToSelfViaIcon = false
folder.isDragInProgress = true
folder.notifyDrop()
assertTrue(folder.itemAddedBackToSelfViaIcon)
}
@Test
fun `If drag is not in progress we should not set mItemAddedBackToSelfViaIcon to true`() {
folder.itemAddedBackToSelfViaIcon = false
folder.isDragInProgress = false
folder.notifyDrop()
assertFalse(folder.itemAddedBackToSelfViaIcon)
}
@Test
fun `If launcher dragging is not enabled onLongClick should return true`() {
`when`(folder.isLauncherDraggingEnabled).thenReturn(false)
val onLongClickResult = folder.onLongClick(Mockito.mock(View::class.java))
assertTrue(onLongClickResult)
}
@Test
fun `If launcher dragging is enabled we should return startDrag result`() {
`when`(folder.isLauncherDraggingEnabled).thenReturn(true)
val viewMock = Mockito.mock(View::class.java)
val dragOptions = Mockito.mock(DragOptions::class.java)
val onLongClickResult = folder.onLongClick(viewMock)
assertEquals(onLongClickResult, folder.startDrag(viewMock, dragOptions))
verify(folder, times(1)).startDrag(viewMock, dragOptions)
}
@Test
fun `Verify start drag works as intended when view is instanceof ItemInfo`() {
val itemInfo = ItemInfo()
itemInfo.rank = 5
val viewMock = Mockito.mock(View::class.java)
val dragOptions = DragOptions()
`when`(viewMock.tag).thenReturn(itemInfo)
folder.dragController = Mockito.mock(DragController::class.java)
folder.startDrag(viewMock, dragOptions)
assertEquals(folder.mEmptyCellRank, 5)
assertEquals(folder.currentDragView, viewMock)
verify(folder, times(1)).addDragListener(dragOptions)
verify(folder, times(1)).callBeginDragShared(viewMock, dragOptions)
}
@Test
fun `Verify start drag works as intended when view is not instanceof ItemInfo`() {
val viewMock = Mockito.mock(View::class.java)
val dragOptions = DragOptions()
folder.startDrag(viewMock, dragOptions)
verify(folder, times(0)).addDragListener(dragOptions)
verify(folder, times(0)).callBeginDragShared(viewMock, dragOptions)
}
@Test
fun `Verify that onDragStart has an effect if dragSource is this folder`() {
folder.itemsInvalidated = false
folder.isDragInProgress = false
folder.itemAddedBackToSelfViaIcon = true
folder.currentDragView = Mockito.mock(View::class.java)
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = spy(folderInfo)
val dragObject = DragObject(context)
dragObject.dragInfo = Mockito.mock(ItemInfo::class.java)
folder.mContent = Mockito.mock(FolderPagedView::class.java)
dragObject.dragSource = folder
folder.onDragStart(dragObject, DragOptions())
verify(folder.mContent, times(1)).removeItem(folder.currentDragView)
verify(folder.mInfo, times(1)).remove(dragObject.dragInfo, true)
assertTrue(folder.itemsInvalidated)
assertTrue(folder.isDragInProgress)
assertFalse(folder.itemAddedBackToSelfViaIcon)
}
@Test
fun `Verify that onDragStart has no effects if dragSource is not this folder`() {
folder.itemsInvalidated = false
folder.isDragInProgress = false
folder.itemAddedBackToSelfViaIcon = true
folder.mContent = Mockito.mock(FolderPagedView::class.java)
val dragObject = DragObject(context)
dragObject.dragSource = Mockito.mock(DragSource::class.java)
folder.onDragStart(dragObject, DragOptions())
verify(folder.mContent, times(0)).removeItem(folder.currentDragView)
assertFalse(folder.itemsInvalidated)
assertFalse(folder.isDragInProgress)
assertTrue(folder.itemAddedBackToSelfViaIcon)
}
@Test
fun `Verify onDragEnd that we call completeDragExit and set drag in progress false`() {
doNothing().`when`(folder).completeDragExit()
folder.isExternalDrag = true
folder.isDragInProgress = true
folder.dragController = Mockito.mock(DragController::class.java)
folder.onDragEnd()
verify(folder, times(1)).completeDragExit()
verify(folder.dragController, times(1)).removeDragListener(folder)
assertFalse(folder.isDragInProgress)
}
@Test
fun `Verify onDragEnd that we do not call completeDragExit and set drag in progress false`() {
folder.isExternalDrag = false
folder.isDragInProgress = true
folder.dragController = Mockito.mock(DragController::class.java)
folder.onDragEnd()
verify(folder, times(0)).completeDragExit()
verify(folder.dragController, times(1)).removeDragListener(folder)
assertFalse(folder.isDragInProgress)
}
@Test
fun `startEditingFolderName should set hint to empty and showLabelSuggestions`() {
doNothing().`when`(folder).showLabelSuggestions()
folder.isEditingName = false
folder.folderName = FolderNameEditText(context)
folder.folderName.hint = "hello"
folder.startEditingFolderName()
verify(folder, times(1)).showLabelSuggestions()
assertEquals("", folder.folderName.hint)
assertTrue(folder.isEditingName)
}
@Test
fun `Ensure we set the title and hint correctly onBackKey when we have a new title`() {
val expectedHint = null
val expectedTitle = "hello"
folder.isEditingName = true
folder.folderName = spy(FolderNameEditText(context))
folder.folderName.setText(expectedTitle)
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = spy(folderInfo)
folder.mInfo.title = "world"
folder.mFolderIcon = Mockito.mock(FolderIcon::class.java)
folder.onBackKey()
assertEquals(expectedTitle, folder.mInfo.title)
verify(folder.mFolderIcon, times(1)).onTitleChanged(expectedTitle)
assertEquals(expectedHint, folder.folderName.hint)
assertFalse(folder.isEditingName)
verify(folder.folderName, times(1)).clearFocus()
}
@Test
fun `Ensure we set the title and hint correctly onBackKey when we do not have a new title`() {
val expectedHint = context.getString(R.string.folder_hint_text)
val expectedTitle = ""
folder.isEditingName = true
folder.folderName = spy(FolderNameEditText(context))
folder.folderName.setText(expectedTitle)
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = spy(folderInfo)
folder.mInfo.title = "world"
folder.mFolderIcon = Mockito.mock(FolderIcon::class.java)
folder.onBackKey()
assertEquals(expectedTitle, folder.mInfo.title)
verify(folder.mFolderIcon, times(1)).onTitleChanged(expectedTitle)
assertEquals(expectedHint, folder.folderName.hint)
assertFalse(folder.isEditingName)
verify(folder.folderName, times(1)).clearFocus()
}
@Test
fun `ensure onEditorAction calls dispatchBackKey when actionId is IME_ACTION_DONE`() {
folder.folderName = Mockito.mock(FolderNameEditText::class.java)
val result =
folder.onEditorAction(
Mockito.mock(TextView::class.java),
EditorInfo.IME_ACTION_DONE,
Mockito.mock(KeyEvent::class.java)
)
assertTrue(result)
verify(folder.folderName, times(1)).dispatchBackKey()
}
@Test
fun `ensure onEditorAction does not call dispatchBackKey when actionId is not IME_ACTION_DONE`() {
folder.folderName = Mockito.mock(FolderNameEditText::class.java)
val result =
folder.onEditorAction(
Mockito.mock(TextView::class.java),
EditorInfo.IME_ACTION_NONE,
Mockito.mock(KeyEvent::class.java)
)
assertFalse(result)
verify(folder.folderName, times(0)).dispatchBackKey()
}
@Test
fun `in completeDragExit we close the folder when mIsOpen`() {
doNothing().`when`(folder).close(true)
folder.setIsOpen(true)
folder.rearrangeOnClose = false
folder.completeDragExit()
verify(folder, times(1)).close(true)
assertTrue(folder.rearrangeOnClose)
}
@Test
fun `in completeDragExit we want to rearrange on close when it is animating`() {
folder.setIsOpen(false)
folder.rearrangeOnClose = false
folder.state = STATE_ANIMATING
folder.completeDragExit()
verify(folder, times(0)).close(true)
assertTrue(folder.rearrangeOnClose)
}
@Test
fun `in completeDragExit we want to call rearrangeChildren and clearDragInfo when not open and not animating`() {
doNothing().`when`(folder).rearrangeChildren()
doNothing().`when`(folder).clearDragInfo()
folder.setIsOpen(false)
folder.rearrangeOnClose = false
folder.state = STATE_CLOSED
folder.completeDragExit()
verify(folder, times(0)).close(true)
assertFalse(folder.rearrangeOnClose)
verify(folder, times(1)).rearrangeChildren()
verify(folder, times(1)).clearDragInfo()
}
@Test
fun `clearDragInfo should set current drag view to null and isExternalDrag to false`() {
folder.currentDragView = Mockito.mock(DragView::class.java)
folder.isExternalDrag = true
folder.clearDragInfo()
assertNull(folder.currentDragView)
assertFalse(folder.isExternalDrag)
}
@Test
fun `onDragExit should set alarm if drag is not complete`() {
folder.onExitAlarm = Mockito.mock(Alarm::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
dragObject.dragComplete = false
folder.onDragExit(dragObject)
verify(folder.onExitAlarm, times(1)).setOnAlarmListener(folder.mOnExitAlarmListener)
verify(folder.onExitAlarm, times(1)).setAlarm(ON_EXIT_CLOSE_DELAY.toLong())
}
@Test
fun `onDragExit should not set alarm if drag is complete`() {
folder.onExitAlarm = Mockito.mock(Alarm::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
dragObject.dragComplete = true
folder.onDragExit(dragObject)
verify(folder.onExitAlarm, times(0)).setOnAlarmListener(folder.mOnExitAlarmListener)
verify(folder.onExitAlarm, times(0)).setAlarm(ON_EXIT_CLOSE_DELAY.toLong())
}
@Test
fun `onDragExit should not clear scroll hint if already SCROLL_NONE`() {
folder.onExitAlarm = Mockito.mock(Alarm::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
folder.scrollHintDir = SCROLL_NONE
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.onDragExit(dragObject)
verify(folder.mContent, times(0)).clearScrollHint()
}
@Test
fun `onDragExit should clear scroll hint if not SCROLL_NONE and then set scroll hint to scroll none`() {
folder.onExitAlarm = Mockito.mock(Alarm::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
folder.scrollHintDir = SCROLL_LEFT
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.onDragExit(dragObject)
verify(folder.mContent, times(1)).clearScrollHint()
assertEquals(folder.scrollHintDir, SCROLL_NONE)
}
@Test
fun `onDragExit we should cancel reorder pause and hint alarms`() {
folder.onExitAlarm = Mockito.mock(Alarm::class.java)
val dragObject = Mockito.mock(DragObject::class.java)
folder.scrollHintDir = SCROLL_NONE
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.reorderAlarm = Mockito.mock(Alarm::class.java)
folder.onScrollHintAlarm = Mockito.mock(Alarm::class.java)
folder.scrollPauseAlarm = Mockito.mock(Alarm::class.java)
folder.onDragExit(dragObject)
verify(folder.reorderAlarm, times(1)).cancelAlarm()
verify(folder.onScrollHintAlarm, times(1)).cancelAlarm()
verify(folder.scrollPauseAlarm, times(1)).cancelAlarm()
assertEquals(folder.scrollHintDir, SCROLL_NONE)
}
@Test
fun `when calling prepareAccessibilityDrop we should cancel pending reorder alarm and call onAlarm`() {
folder.reorderAlarm = Mockito.mock(Alarm::class.java)
folder.mReorderAlarmListener = Mockito.mock(OnAlarmListener::class.java)
`when`(folder.reorderAlarm.alarmPending()).thenReturn(true)
folder.prepareAccessibilityDrop()
verify(folder.reorderAlarm, times(1)).cancelAlarm()
verify(folder.mReorderAlarmListener, times(1)).onAlarm(folder.reorderAlarm)
}
@Test
fun `when calling prepareAccessibilityDrop we should not do anything if there is no pending alarm`() {
folder.reorderAlarm = Mockito.mock(Alarm::class.java)
folder.mReorderAlarmListener = Mockito.mock(OnAlarmListener::class.java)
`when`(folder.reorderAlarm.alarmPending()).thenReturn(false)
folder.prepareAccessibilityDrop()
verify(folder.reorderAlarm, times(0)).cancelAlarm()
verify(folder.mReorderAlarmListener, times(0)).onAlarm(folder.reorderAlarm)
}
@Test
fun `isDropEnabled should be true as long as state is not STATE_ANIMATING`() {
folder.state = STATE_CLOSED
val isDropEnabled = folder.isDropEnabled
assertTrue(isDropEnabled)
}
@Test
fun `isDropEnabled should be false if state is STATE_ANIMATING`() {
folder.state = STATE_ANIMATING
val isDropEnabled = folder.isDropEnabled
assertFalse(isDropEnabled)
}
@Test
fun `getItemCount should return the number of items in the folder`() {
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = folderInfo
val itemCount = folder.itemCount
assertEquals(itemCount, 2)
}
@Test
fun `hideItem should set the visibility of the corresponding ItemInfo to invisible`() {
val itemInfo = ItemInfo()
val view = View(context)
view.isVisible = true
doReturn(view).whenever(folder).getViewForInfo(itemInfo)
folder.hideItem(itemInfo)
assertFalse(view.isVisible)
}
@Test
fun `showItem should set the visibility of the corresponding ItemInfo to visible`() {
val itemInfo = ItemInfo()
val view = View(context)
view.isVisible = false
doReturn(view).whenever(folder).getViewForInfo(itemInfo)
folder.showItem(itemInfo)
assertTrue(view.isVisible)
}
@Test
fun `onDragEnter should cancel exit alarm and set the scroll area offset to dragRegionWidth divided by two minus xOffset`() {
folder.mPrevTargetRank = 1
val dragObject = Mockito.mock(DragObject::class.java)
val dragView = Mockito.mock(DragView::class.java)
dragObject.dragView = dragView
folder.onExitAlarm = Mockito.mock(Alarm::class.java)
`when`(dragObject.dragView.getDragRegionWidth()).thenReturn(100)
dragObject.xOffset = 20
folder.onDragEnter(dragObject)
verify(folder.onExitAlarm, times(1)).cancelAlarm()
assertEquals(-1, folder.mPrevTargetRank)
assertEquals(30, folder.scrollAreaOffset)
}
@Test
fun `acceptDrop should return true with the correct item type as a parameter`() {
val dragObject = Mockito.mock(DragObject::class.java)
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_APP_PAIR
dragObject.dragInfo = itemInfo
val result = folder.acceptDrop(dragObject)
assertTrue(result)
}
@Test
fun `acceptDrop should return false with the incorrect item type as a parameter`() {
val dragObject = Mockito.mock(DragObject::class.java)
val itemInfo = Mockito.mock(ItemInfo::class.java)
itemInfo.itemType = ITEM_TYPE_APPWIDGET
dragObject.dragInfo = itemInfo
val result = folder.acceptDrop(dragObject)
assertFalse(result)
}
@Test
fun `rearrangeChildren should return early if content view are not bound`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.itemsInvalidated = false
doReturn(false).whenever(folder.mContent).areViewsBound()
folder.rearrangeChildren()
verify(folder.mContent, times(0)).arrangeChildren(folder.iconsInReadingOrder)
assertFalse(folder.itemsInvalidated)
}
@Test
fun `rearrangeChildren should call arrange children and invalidate items`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.itemsInvalidated = false
doReturn(true).whenever(folder.mContent).areViewsBound()
val iconsInReadingOrderList = ArrayList<View>()
`when`(folder.iconsInReadingOrder).thenReturn(iconsInReadingOrderList)
doNothing().`when`(folder.mContent).arrangeChildren(iconsInReadingOrderList)
folder.rearrangeChildren()
verify(folder.mContent, times(1)).arrangeChildren(folder.iconsInReadingOrder)
assertTrue(folder.itemsInvalidated)
}
@Test
fun `getItemCount should return the size of info getContents size`() {
val folderInfo =
workspaceBuilder.createFolderInCell(FolderPoint(Point(1, 0), TWO_ICON_FOLDER_TYPE), 0)
folder.mInfo = folderInfo
val itemCount = folder.itemCount
assertEquals(2, itemCount)
}
@Test
fun `replaceFolderWithFinalItem should set mDestroyed to true if we replace folder with final item`() {
val launcherDelegate = Mockito.mock(LauncherDelegate::class.java)
folder.mLauncherDelegate = launcherDelegate
`when`(folder.mLauncherDelegate.replaceFolderWithFinalItem(folder)).thenReturn(true)
folder.replaceFolderWithFinalItem()
assertTrue(folder.isDestroyed)
}
@Test
fun `replaceFolderWithFinalItem should set mDestroyed to false if we do not replace folder with final item`() {
val launcherDelegate = Mockito.mock(LauncherDelegate::class.java)
folder.mLauncherDelegate = launcherDelegate
`when`(folder.mLauncherDelegate.replaceFolderWithFinalItem(folder)).thenReturn(false)
folder.replaceFolderWithFinalItem()
assertFalse(folder.isDestroyed)
}
@Test
fun `getContentAreaHeight should return maxContentAreaHeight`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.mContent.desiredHeight).thenReturn(100)
`when`(folder.maxContentAreaHeight).thenReturn(50)
val height = folder.contentAreaHeight
assertEquals(50, height)
}
@Test
fun `getContentAreaHeight should return desiredHeight`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.mContent.desiredHeight).thenReturn(50)
`when`(folder.maxContentAreaHeight).thenReturn(100)
val height = folder.contentAreaHeight
assertEquals(50, height)
}
@Test
fun `getContentAreaHeight should return MIN_CONTENT_DIMEN`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.mContent.desiredHeight).thenReturn(1)
`when`(folder.maxContentAreaHeight).thenReturn(2)
val height = folder.contentAreaHeight
assertEquals(MIN_CONTENT_DIMEN, height)
}
@Test
fun `getContentAreaWidth should return desired width`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.mContent.desiredWidth).thenReturn(50)
val width = folder.contentAreaWidth
assertEquals(50, width)
}
@Test
fun `getContentAreaWidth should return MIN_CONTENT_DIMEN`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.mContent.desiredWidth).thenReturn(1)
val width = folder.contentAreaWidth
assertEquals(MIN_CONTENT_DIMEN, width)
}
@Test
fun `getFolderWidth should return padding left plus padding right plus desired width`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.mContent.desiredWidth).thenReturn(1)
`when`(folder.paddingLeft).thenReturn(10)
`when`(folder.paddingRight).thenReturn(10)
val width = folder.folderWidth
assertEquals(21, width)
}
@Test
fun `getFolderHeight with no params should return getFolderHeight`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.contentAreaHeight).thenReturn(100)
`when`(folder.getFolderHeight(folder.contentAreaHeight)).thenReturn(120)
val height = folder.folderHeight
assertEquals(120, height)
}
@Test
fun `getFolderWidth with contentAreaHeight should return padding top plus padding bottom plus contentAreaHeight plus footer height`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
`when`(folder.footerHeight).thenReturn(100)
`when`(folder.paddingTop).thenReturn(10)
`when`(folder.paddingBottom).thenReturn(10)
val height = folder.getFolderHeight(100)
assertEquals(220, height)
}
@Test
fun `onRemove should call removeItem with the correct views`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
val items =
arrayListOf<ItemInfo>(
Mockito.mock(ItemInfo::class.java),
Mockito.mock(ItemInfo::class.java)
)
val view1 = Mockito.mock(View::class.java)
val view2 = Mockito.mock(View::class.java)
doReturn(view1).whenever(folder).getViewForInfo(items[0])
doReturn(view2).whenever(folder).getViewForInfo(items[1])
doReturn(2).whenever(folder).itemCount
folder.onRemove(items)
verify(folder.mContent, times(1)).removeItem(view1)
verify(folder.mContent, times(1)).removeItem(view2)
}
@Test
fun `onRemove should set mRearrangeOnClose to true and not call rearrangeChildren if animating`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.state = STATE_ANIMATING
val items =
arrayListOf<ItemInfo>(
Mockito.mock(ItemInfo::class.java),
Mockito.mock(ItemInfo::class.java)
)
val view1 = Mockito.mock(View::class.java)
val view2 = Mockito.mock(View::class.java)
doReturn(view1).whenever(folder).getViewForInfo(items[0])
doReturn(view2).whenever(folder).getViewForInfo(items[1])
doReturn(2).whenever(folder).itemCount
folder.onRemove(items)
assertTrue(folder.rearrangeOnClose)
verify(folder, times(0)).rearrangeChildren()
}
@Test
fun `onRemove should set not change mRearrangeOnClose and not call rearrangeChildren if not animating`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
folder.state = STATE_CLOSED
folder.rearrangeOnClose = false
val items =
arrayListOf<ItemInfo>(
Mockito.mock(ItemInfo::class.java),
Mockito.mock(ItemInfo::class.java)
)
val view1 = Mockito.mock(View::class.java)
val view2 = Mockito.mock(View::class.java)
doReturn(view1).whenever(folder).getViewForInfo(items[0])
doReturn(view2).whenever(folder).getViewForInfo(items[1])
doReturn(2).whenever(folder).itemCount
folder.onRemove(items)
assertFalse(folder.rearrangeOnClose)
verify(folder, times(1)).rearrangeChildren()
}
@Test
fun `onRemove should call close if mIsOpen is true and item count is less than or equal to one`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
val items =
arrayListOf<ItemInfo>(
Mockito.mock(ItemInfo::class.java),
Mockito.mock(ItemInfo::class.java)
)
val view1 = Mockito.mock(View::class.java)
val view2 = Mockito.mock(View::class.java)
doReturn(view1).whenever(folder).getViewForInfo(items[0])
doReturn(view2).whenever(folder).getViewForInfo(items[1])
doReturn(1).whenever(folder).itemCount
folder.setIsOpen(true)
doNothing().`when`(folder).close(true)
folder.onRemove(items)
verify(folder, times(1)).close(true)
}
@Test
fun `onRemove should call replaceFolderWithFinalItem if mIsOpen is false and item count is less than or equal to one`() {
folder.mContent = Mockito.mock(FolderPagedView::class.java)
val items =
arrayListOf<ItemInfo>(
Mockito.mock(ItemInfo::class.java),
Mockito.mock(ItemInfo::class.java)
)
val view1 = Mockito.mock(View::class.java)
val view2 = Mockito.mock(View::class.java)
doReturn(view1).whenever(folder).getViewForInfo(items[0])
doReturn(view2).whenever(folder).getViewForInfo(items[1])
doReturn(1).whenever(folder).itemCount
folder.setIsOpen(false)
folder.onRemove(items)
verify(folder, times(1)).replaceFolderWithFinalItem()
}
companion object {
const val TWO_ICON_FOLDER_TYPE = 'A'
}
}
@@ -0,0 +1,325 @@
/*
* Copyright (C) 2023 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.launcher3.folder;
import static com.android.launcher3.folder.PreviewBackground.ACCEPT_SCALE_FACTOR;
import static com.android.launcher3.folder.PreviewBackground.CONSUMPTION_ANIMATION_DURATION;
import static com.android.launcher3.folder.PreviewBackground.HOVER_ANIMATION_DURATION;
import static com.android.launcher3.folder.PreviewBackground.HOVER_SCALE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.PathInterpolator;
import androidx.test.annotation.UiThreadTest;
import androidx.test.filters.SmallTest;
import androidx.test.platform.app.InstrumentationRegistry;
import com.android.launcher3.CellLayout;
import com.android.launcher3.util.LauncherMultivalentJUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@SmallTest
@UiThreadTest
@RunWith(LauncherMultivalentJUnit.class)
public class PreviewBackgroundTest {
private static final float REST_SCALE = 1f;
private static final float EPSILON = 0.00001f;
@Mock
CellLayout mCellLayout;
private final PreviewBackground mPreviewBackground =
new PreviewBackground(InstrumentationRegistry.getInstrumentation().getContext());
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mPreviewBackground.mScale = REST_SCALE;
mPreviewBackground.mIsAccepting = false;
mPreviewBackground.mIsHovered = false;
mPreviewBackground.mIsHoveredOrAnimating = false;
mPreviewBackground.invalidate();
}
@Test
public void testAnimateScale_restToHovered() {
mPreviewBackground.setHovered(true);
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, HOVER_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
HOVER_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator() instanceof PathInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_restToNotHovered() {
mPreviewBackground.setHovered(false);
assertEquals("Scale changed.", mPreviewBackground.mScale, REST_SCALE, EPSILON);
assertNull("Animator not null.", mPreviewBackground.mScaleAnimator);
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_hoveredToHovered() {
mPreviewBackground.mScale = HOVER_SCALE;
mPreviewBackground.mIsHovered = true;
mPreviewBackground.mIsHoveredOrAnimating = true;
mPreviewBackground.invalidate();
mPreviewBackground.setHovered(true);
assertEquals("Scale changed.", mPreviewBackground.mScale, HOVER_SCALE, EPSILON);
assertNull("Animator not null.", mPreviewBackground.mScaleAnimator);
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_hoveredToRest() {
mPreviewBackground.mScale = HOVER_SCALE;
mPreviewBackground.mIsHovered = true;
mPreviewBackground.mIsHoveredOrAnimating = true;
mPreviewBackground.invalidate();
mPreviewBackground.setHovered(false);
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, REST_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
HOVER_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator() instanceof PathInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_restToAccept() {
mPreviewBackground.animateToAccept(mCellLayout, 0, 0);
runAnimationToFraction(1f);
assertEquals("Scale changed.", mPreviewBackground.mScale, ACCEPT_SCALE_FACTOR, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
CONSUMPTION_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator()
instanceof AccelerateDecelerateInterpolator);
endAnimation();
assertEquals("Scale progress not 1.", mPreviewBackground.getAcceptScaleProgress(), 1,
EPSILON);
}
@Test
public void testAnimateScale_restToRest() {
mPreviewBackground.animateToRest();
assertEquals("Scale changed.", mPreviewBackground.mScale, REST_SCALE, EPSILON);
assertNull("Animator not null.", mPreviewBackground.mScaleAnimator);
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_acceptToRest() {
mPreviewBackground.mScale = ACCEPT_SCALE_FACTOR;
mPreviewBackground.mIsAccepting = true;
mPreviewBackground.invalidate();
mPreviewBackground.animateToRest();
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, REST_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
CONSUMPTION_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator()
instanceof AccelerateDecelerateInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_acceptToHover() {
mPreviewBackground.mScale = ACCEPT_SCALE_FACTOR;
mPreviewBackground.mIsAccepting = true;
mPreviewBackground.invalidate();
mPreviewBackground.mIsAccepting = false;
mPreviewBackground.setHovered(true);
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, HOVER_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
HOVER_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator() instanceof PathInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_hoverToAccept() {
mPreviewBackground.mScale = HOVER_SCALE;
mPreviewBackground.mIsHovered = true;
mPreviewBackground.mIsHoveredOrAnimating = true;
mPreviewBackground.invalidate();
mPreviewBackground.animateToAccept(mCellLayout, 0, 0);
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, ACCEPT_SCALE_FACTOR, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
CONSUMPTION_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator()
instanceof AccelerateDecelerateInterpolator);
mPreviewBackground.mIsHovered = false;
endAnimation();
assertEquals("Scale progress not 1.", mPreviewBackground.getAcceptScaleProgress(), 1,
EPSILON);
}
@Test
public void testAnimateScale_midwayToHoverToAccept() {
mPreviewBackground.setHovered(true);
runAnimationToFraction(0.5f);
assertTrue("Scale not changed.",
mPreviewBackground.mScale > REST_SCALE && mPreviewBackground.mScale < HOVER_SCALE);
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
mPreviewBackground.animateToAccept(mCellLayout, 0, 0);
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, ACCEPT_SCALE_FACTOR, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
CONSUMPTION_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator()
instanceof AccelerateDecelerateInterpolator);
mPreviewBackground.mIsHovered = false;
endAnimation();
assertEquals("Scale progress not 1.", mPreviewBackground.getAcceptScaleProgress(), 1,
EPSILON);
assertNull("Animator not null.", mPreviewBackground.mScaleAnimator);
}
@Test
public void testAnimateScale_partWayToAcceptToHover() {
mPreviewBackground.animateToAccept(mCellLayout, 0, 0);
runAnimationToFraction(0.25f);
assertTrue("Scale not changed part way.", mPreviewBackground.mScale > REST_SCALE
&& mPreviewBackground.mScale < ACCEPT_SCALE_FACTOR);
mPreviewBackground.mIsAccepting = false;
mPreviewBackground.setHovered(true);
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, HOVER_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
HOVER_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator() instanceof PathInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_midwayToAcceptEqualsHover() {
mPreviewBackground.animateToAccept(mCellLayout, 0, 0);
runAnimationToFraction(0.5f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, HOVER_SCALE, EPSILON);
mPreviewBackground.mIsAccepting = false;
mPreviewBackground.setHovered(true);
assertEquals("Scale changed.", mPreviewBackground.mScale, HOVER_SCALE, EPSILON);
assertNull("Animator not null.", mPreviewBackground.mScaleAnimator);
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_midwayToHoverToRest() {
mPreviewBackground.setHovered(true);
runAnimationToFraction(0.5f);
assertTrue("Scale not changed midway.",
mPreviewBackground.mScale > REST_SCALE && mPreviewBackground.mScale < HOVER_SCALE);
mPreviewBackground.mIsHovered = false;
mPreviewBackground.animateToRest();
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, REST_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
HOVER_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator() instanceof PathInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
@Test
public void testAnimateScale_midwayToAcceptToRest() {
mPreviewBackground.animateToAccept(mCellLayout, 0, 0);
runAnimationToFraction(0.5f);
assertTrue("Scale not changed.", mPreviewBackground.mScale > REST_SCALE
&& mPreviewBackground.mScale < ACCEPT_SCALE_FACTOR);
mPreviewBackground.animateToRest();
runAnimationToFraction(1f);
assertEquals("Scale not changed.", mPreviewBackground.mScale, REST_SCALE, EPSILON);
assertEquals("Duration not correct.", mPreviewBackground.mScaleAnimator.getDuration(),
CONSUMPTION_ANIMATION_DURATION);
assertTrue("Wrong interpolator used.",
mPreviewBackground.mScaleAnimator.getInterpolator()
instanceof AccelerateDecelerateInterpolator);
endAnimation();
assertEquals("Scale progress not 0.", mPreviewBackground.getAcceptScaleProgress(), 0,
EPSILON);
}
private void runAnimationToFraction(float animationFraction) {
mPreviewBackground.mScaleAnimator.setCurrentFraction(animationFraction);
}
private void endAnimation() {
mPreviewBackground.mScaleAnimator.end();
}
}
@@ -0,0 +1,268 @@
/*
* Copyright (C) 2023 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.launcher3.folder
import android.R
import android.content.Context
import android.os.Process
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import com.android.launcher3.LauncherPrefs.Companion.THEMED_ICONS
import com.android.launcher3.LauncherPrefs.Companion.get
import com.android.launcher3.graphics.PreloadIconDrawable
import com.android.launcher3.icons.BaseIconFactory
import com.android.launcher3.icons.FastBitmapDrawable
import com.android.launcher3.icons.UserBadgeDrawable
import com.android.launcher3.model.ModelTestRule
import com.android.launcher3.model.data.FolderInfo
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_ARCHIVED
import com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_INSTALL_SESSION_ACTIVE
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.util.ActivityContextWrapper
import com.android.launcher3.util.Executors
import com.android.launcher3.util.FlagOp
import com.android.launcher3.util.LauncherLayoutBuilder
import com.android.launcher3.util.LauncherModelHelper
import com.android.launcher3.util.TestUtil
import com.android.launcher3.util.UserIconInfo
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/** Tests for [PreviewItemManager] */
@SmallTest
@RunWith(AndroidJUnit4::class)
class PreviewItemManagerTest {
@get:Rule val modelTestRule = ModelTestRule()
private lateinit var previewItemManager: PreviewItemManager
private lateinit var context: Context
private lateinit var folderItems: ArrayList<ItemInfo>
private lateinit var modelHelper: LauncherModelHelper
private lateinit var folderIcon: FolderIcon
private var defaultThemedIcons = false
@Before
fun setup() {
getInstrumentation().runOnMainSync {
folderIcon =
FolderIcon(ActivityContextWrapper(ApplicationProvider.getApplicationContext()))
}
context = getInstrumentation().targetContext
previewItemManager = PreviewItemManager(folderIcon)
modelHelper = LauncherModelHelper()
modelHelper
.setupDefaultLayoutProvider(
LauncherLayoutBuilder()
.atWorkspace(0, 0, 1)
.putFolder(R.string.copy)
.addApp(LauncherModelHelper.TEST_PACKAGE, LauncherModelHelper.TEST_ACTIVITY)
.addApp(LauncherModelHelper.TEST_PACKAGE, LauncherModelHelper.TEST_ACTIVITY2)
.addApp(LauncherModelHelper.TEST_PACKAGE, LauncherModelHelper.TEST_ACTIVITY3)
.addApp(LauncherModelHelper.TEST_PACKAGE, LauncherModelHelper.TEST_ACTIVITY4)
.build()
)
.loadModelSync()
folderItems = modelHelper.bgDataModel.collections.valueAt(0).getContents()
folderIcon.mInfo = modelHelper.bgDataModel.collections.valueAt(0) as FolderInfo
folderIcon.mInfo.getContents().addAll(folderItems)
// Use getAppContents() to "cast" contents to WorkspaceItemInfo so we can set bitmaps
val folderApps = modelHelper.bgDataModel.collections.valueAt(0).getAppContents()
// Set first icon to be themed.
folderApps[0]
.bitmap
.setMonoIcon(
folderApps[0].bitmap.icon,
BaseIconFactory(
context,
context.resources.configuration.densityDpi,
previewItemManager.mIconSize
)
)
// Set second icon to be non-themed.
folderApps[1]
.bitmap
.setMonoIcon(
null,
BaseIconFactory(
context,
context.resources.configuration.densityDpi,
previewItemManager.mIconSize
)
)
// Set third icon to be themed with badge.
folderApps[2]
.bitmap
.setMonoIcon(
folderApps[2].bitmap.icon,
BaseIconFactory(
context,
context.resources.configuration.densityDpi,
previewItemManager.mIconSize
)
)
folderApps[2].bitmap = folderApps[2].bitmap.withFlags(profileFlagOp(UserIconInfo.TYPE_WORK))
// Set fourth icon to be non-themed with badge.
folderApps[3].bitmap = folderApps[3].bitmap.withFlags(profileFlagOp(UserIconInfo.TYPE_WORK))
folderApps[3]
.bitmap
.setMonoIcon(
null,
BaseIconFactory(
context,
context.resources.configuration.densityDpi,
previewItemManager.mIconSize
)
)
defaultThemedIcons = get(context).get(THEMED_ICONS)
}
@After
@Throws(Exception::class)
fun tearDown() {
get(context).put(THEMED_ICONS, defaultThemedIcons)
modelHelper.destroy()
}
@Test
fun checkThemedIconWithThemingOn_iconShouldBeThemed() {
get(context).put(THEMED_ICONS, true)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[0])
assert((drawingParams.drawable as FastBitmapDrawable).isThemed)
}
@Test
fun checkThemedIconWithThemingOff_iconShouldNotBeThemed() {
get(context).put(THEMED_ICONS, false)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[0])
assert(!(drawingParams.drawable as FastBitmapDrawable).isThemed)
}
@Test
fun checkUnthemedIconWithThemingOn_iconShouldNotBeThemed() {
get(context).put(THEMED_ICONS, true)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[1])
assert(!(drawingParams.drawable as FastBitmapDrawable).isThemed)
}
@Test
fun checkUnthemedIconWithThemingOff_iconShouldNotBeThemed() {
get(context).put(THEMED_ICONS, false)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[1])
assert(!(drawingParams.drawable as FastBitmapDrawable).isThemed)
}
@Test
fun checkThemedIconWithBadgeWithThemingOn_iconAndBadgeShouldBeThemed() {
get(context).put(THEMED_ICONS, true)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[2])
assert((drawingParams.drawable as FastBitmapDrawable).isThemed)
assert(
((drawingParams.drawable as FastBitmapDrawable).badge as UserBadgeDrawable).mIsThemed
)
}
@Test
fun checkUnthemedIconWithBadgeWithThemingOn_badgeShouldBeThemed() {
get(context).put(THEMED_ICONS, true)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[3])
assert(!(drawingParams.drawable as FastBitmapDrawable).isThemed)
assert(
((drawingParams.drawable as FastBitmapDrawable).badge as UserBadgeDrawable).mIsThemed
)
}
@Test
fun checkUnthemedIconWithBadgeWithThemingOff_iconAndBadgeShouldNotBeThemed() {
get(context).put(THEMED_ICONS, false)
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
previewItemManager.setDrawable(drawingParams, folderItems[3])
assert(!(drawingParams.drawable as FastBitmapDrawable).isThemed)
assert(
!((drawingParams.drawable as FastBitmapDrawable).badge as UserBadgeDrawable).mIsThemed
)
}
@Test
fun `Inactive archived app previews are not drawn as preload icon`() {
// Given
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
val archivedApp =
WorkspaceItemInfo().apply {
runtimeStatusFlags = runtimeStatusFlags or FLAG_ARCHIVED
runtimeStatusFlags = runtimeStatusFlags and FLAG_INSTALL_SESSION_ACTIVE.inv()
}
// When
previewItemManager.setDrawable(drawingParams, archivedApp)
// Then
assertThat(drawingParams.drawable).isNotInstanceOf(PreloadIconDrawable::class.java)
}
@Test
fun `Actively installing archived app previews are drawn as preload icon`() {
// Given
val drawingParams = PreviewItemDrawingParams(0f, 0f, 0f)
val archivedApp =
WorkspaceItemInfo().apply {
runtimeStatusFlags = runtimeStatusFlags or FLAG_ARCHIVED
runtimeStatusFlags = runtimeStatusFlags or FLAG_INSTALL_SESSION_ACTIVE
}
// When
TestUtil.runOnExecutorSync(Executors.MAIN_EXECUTOR) {
// Run on main thread because preload drawable triggers animator
previewItemManager.setDrawable(drawingParams, archivedApp)
}
// Then
assertThat(drawingParams.drawable).isInstanceOf(PreloadIconDrawable::class.java)
}
private fun profileFlagOp(type: Int) =
UserIconInfo(Process.myUserHandle(), type).applyBitmapInfoFlags(FlagOp.NO_OP)
}
@@ -0,0 +1,228 @@
/*
* Copyright (C) 2022 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.launcher3.model
import android.util.Pair
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.util.Executors
import com.android.launcher3.util.IntArray
import com.android.launcher3.util.TestUtil.runOnExecutorSync
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.times
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.same
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import org.mockito.kotlin.whenever
/** Tests for [AddWorkspaceItemsTask] */
@SmallTest
@RunWith(AndroidJUnit4::class)
class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
@get:Rule val modelTestRule = ModelTestRule()
private lateinit var mDataModelCallbacks: MyCallbacks
private val mWorkspaceItemSpaceFinder: WorkspaceItemSpaceFinder = mock()
@Before
override fun setup() {
super.setup()
mDataModelCallbacks = MyCallbacks()
Executors.MAIN_EXECUTOR.submit { mModelHelper.model.addCallbacks(mDataModelCallbacks) }
.get()
}
@After
override fun tearDown() {
super.tearDown()
}
@Test
fun givenNewItemAndNonEmptyPages_whenExecuteTask_thenAddNewItem() {
val itemToAdd = getNewItem()
val nonEmptyScreenIds = listOf(0, 1, 2)
givenNewItemSpaces(NewItemSpace(1, 2, 2))
val addedItems = testAddItems(nonEmptyScreenIds, itemToAdd)
assertThat(addedItems.size).isEqualTo(1)
assertThat(addedItems.first().itemInfo.screenId).isEqualTo(1)
assertThat(addedItems.first().isAnimated).isTrue()
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 1)
}
@Test
fun givenNewAndExistingItems_whenExecuteTask_thenOnlyAddNewItem() {
val itemsToAdd = arrayOf(getNewItem(), getExistingItem())
givenNewItemSpaces(NewItemSpace(1, 0, 0))
val nonEmptyScreenIds = listOf(0)
val addedItems = testAddItems(nonEmptyScreenIds, *itemsToAdd)
assertThat(addedItems.size).isEqualTo(1)
assertThat(addedItems.first().itemInfo.screenId).isEqualTo(1)
assertThat(addedItems.first().isAnimated).isTrue()
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 1)
}
@Test
fun givenOnlyExistingItem_whenExecuteTask_thenDoNotAddItem() {
val itemToAdd = getExistingItem()
givenNewItemSpaces(NewItemSpace(1, 0, 0))
val nonEmptyScreenIds = listOf(0)
val addedItems = testAddItems(nonEmptyScreenIds, itemToAdd)
assertThat(addedItems.size).isEqualTo(0)
// b/343530737
verifyNoMoreInteractions(mWorkspaceItemSpaceFinder)
}
@Test
fun givenNonSequentialScreenIds_whenExecuteTask_thenReturnNewScreenId() {
val itemToAdd = getNewItem()
givenNewItemSpaces(NewItemSpace(2, 1, 3))
val nonEmptyScreenIds = listOf(0, 2, 3)
val addedItems = testAddItems(nonEmptyScreenIds, itemToAdd)
assertThat(addedItems.size).isEqualTo(1)
assertThat(addedItems.first().itemInfo.screenId).isEqualTo(2)
assertThat(addedItems.first().isAnimated).isTrue()
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 1)
}
@Test
fun givenMultipleItems_whenExecuteTask_thenAddThem() {
val itemsToAdd =
arrayOf(
getNewItem(),
getExistingItem(),
getNewItem(),
getNewItem(),
getExistingItem(),
)
givenNewItemSpaces(
NewItemSpace(1, 3, 3),
NewItemSpace(2, 0, 0),
NewItemSpace(2, 0, 1),
)
val nonEmptyScreenIds = listOf(0, 1)
val addedItems = testAddItems(nonEmptyScreenIds, *itemsToAdd)
// Only the new items should be added
assertThat(addedItems.size).isEqualTo(3)
// Items that are added to the first screen should not be animated
val itemsAddedToFirstScreen = addedItems.filter { it.itemInfo.screenId == 1 }
assertThat(itemsAddedToFirstScreen.size).isEqualTo(1)
assertThat(itemsAddedToFirstScreen.first().isAnimated).isFalse()
// Items that are added to the second screen should be animated
val itemsAddedToSecondScreen = addedItems.filter { it.itemInfo.screenId == 2 }
assertThat(itemsAddedToSecondScreen.size).isEqualTo(2)
itemsAddedToSecondScreen.forEach { assertThat(it.isAnimated).isTrue() }
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 3)
}
/** Sets up the item space data that will be returned from WorkspaceItemSpaceFinder. */
private fun givenNewItemSpaces(vararg newItemSpaces: NewItemSpace) {
val spaceStack = newItemSpaces.toMutableList()
whenever(
mWorkspaceItemSpaceFinder.findSpaceForItem(any(), any(), any(), any(), any(), any())
)
.then { spaceStack.removeFirst().toIntArray() }
}
/**
* Verifies if WorkspaceItemSpaceFinder was called with proper arguments and how many times was
* it called.
*/
private fun verifyItemSpaceFinderCall(nonEmptyScreenIds: List<Int>, numberOfExpectedCall: Int) {
verify(mWorkspaceItemSpaceFinder, times(numberOfExpectedCall))
.findSpaceForItem(
same(mAppState),
same(mModelHelper.bgDataModel),
eq(IntArray.wrap(*nonEmptyScreenIds.toIntArray())),
eq(IntArray()),
eq(1),
eq(1)
)
}
/**
* Sets up the workspaces with items, executes the task, collects the added items from the model
* callback then returns it.
*/
private fun testAddItems(
nonEmptyScreenIds: List<Int>,
vararg itemsToAdd: WorkspaceItemInfo
): List<AddedItem> {
setupWorkspaces(nonEmptyScreenIds)
val task = newTask(*itemsToAdd)
val addedItems = mutableListOf<AddedItem>()
runOnExecutorSync(Executors.MODEL_EXECUTOR) {
mDataModelCallbacks.addedItems.clear()
mModelHelper.model.enqueueModelUpdateTask(task)
runOnExecutorSync(Executors.MAIN_EXECUTOR) {}
addedItems.addAll(mDataModelCallbacks.addedItems)
}
return addedItems
}
/**
* Creates the task with the given items and replaces the WorkspaceItemSpaceFinder dependency
* with a mock.
*/
private fun newTask(vararg items: ItemInfo): AddWorkspaceItemsTask =
items
.map { Pair.create(it, Any()) }
.toMutableList()
.let { AddWorkspaceItemsTask(it, mWorkspaceItemSpaceFinder) }
}
private data class AddedItem(val itemInfo: ItemInfo, val isAnimated: Boolean)
private class MyCallbacks : BgDataModel.Callbacks {
val addedItems = mutableListOf<AddedItem>()
override fun bindAppsAdded(
newScreens: IntArray?,
addNotAnimated: ArrayList<ItemInfo>,
addAnimated: ArrayList<ItemInfo>
) {
addedItems.addAll(addAnimated.map { AddedItem(it, true) })
addedItems.addAll(addNotAnimated.map { AddedItem(it, false) })
}
}
@@ -0,0 +1,214 @@
/*
* Copyright (C) 2024 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.launcher3.model
import android.os.Looper
import android.platform.test.flag.junit.SetFlagsRule
import android.util.Pair
import android.util.SparseArray
import android.view.View
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.Flags
import com.android.launcher3.model.BgDataModel.Callbacks
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.util.Executors.MAIN_EXECUTOR
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.util.IntArray
import com.android.launcher3.util.IntSet
import com.android.launcher3.util.ItemInflater
import com.android.launcher3.util.LauncherLayoutBuilder
import com.android.launcher3.util.LauncherModelHelper
import com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE
import com.android.launcher3.util.RunnableList
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.Spy
import org.mockito.kotlin.any
import org.mockito.kotlin.argThat
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.isNull
import org.mockito.kotlin.never
import org.mockito.kotlin.reset
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
/** Tests to verify async binding of model views */
@SmallTest
@RunWith(AndroidJUnit4::class)
class AsyncBindingTest {
@get:Rule val setFlagsRule = SetFlagsRule()
@get:Rule val modelTestRule = ModelTestRule()
@Spy private var callbacks = MyCallbacks()
@Mock private lateinit var itemInflater: ItemInflater<*>
private val inflationLooper = SparseArray<Looper>()
private lateinit var modelHelper: LauncherModelHelper
@Before
fun setUp() {
setFlagsRule.enableFlags(Flags.FLAG_ENABLE_WORKSPACE_INFLATION)
MockitoAnnotations.initMocks(this)
modelHelper = LauncherModelHelper()
doAnswer { i ->
inflationLooper[(i.arguments[0] as ItemInfo).id] = Looper.myLooper()
View(modelHelper.sandboxContext)
}
.whenever(itemInflater)
.inflateItem(any(), any(), isNull())
// Set up the workspace with 3 pages of apps
modelHelper.setupDefaultLayoutProvider(
LauncherLayoutBuilder()
.atWorkspace(0, 1, 0)
.putApp(TEST_PACKAGE, TEST_PACKAGE)
.atWorkspace(1, 1, 0)
.putApp(TEST_PACKAGE, TEST_PACKAGE)
.atWorkspace(0, 1, 1)
.putApp(TEST_PACKAGE, TEST_PACKAGE)
.atWorkspace(1, 1, 1)
.putApp(TEST_PACKAGE, TEST_PACKAGE)
.atWorkspace(0, 1, 2)
.putApp(TEST_PACKAGE, TEST_PACKAGE)
)
}
@After
fun tearDown() {
modelHelper.destroy()
}
@Test
fun test_bind_normally_without_itemInflater() {
MAIN_EXECUTOR.execute { modelHelper.model.addCallbacksAndLoad(callbacks) }
waitForLoaderAndTempMainThread()
verify(callbacks, never()).bindInflatedItems(any())
verify(callbacks, atLeastOnce()).bindItems(any(), any())
}
@Test
fun test_bind_inflates_item_on_background() {
callbacks.inflater = itemInflater
MAIN_EXECUTOR.execute { modelHelper.model.addCallbacksAndLoad(callbacks) }
waitForLoaderAndTempMainThread()
verify(callbacks, never()).bindItems(any(), any())
verify(callbacks, times(1)).bindInflatedItems(argThat { t -> t.size == 2 })
// Verify remaining items are bound using pendingTasks
reset(callbacks)
MAIN_EXECUTOR.submit(callbacks.pendingTasks!!::executeAllAndDestroy).get()
verify(callbacks, times(1)).bindInflatedItems(argThat { t -> t.size == 3 })
// Verify that all items were inflated on the background thread
assertEquals(5, inflationLooper.size())
for (i in 0..4) assertEquals(MODEL_EXECUTOR.looper, inflationLooper.valueAt(i))
}
@Test
fun test_bind_sync_partially_inflates_on_background() {
modelHelper.loadModelSync()
assertTrue(modelHelper.model.isModelLoaded)
callbacks.inflater = itemInflater
val firstPageBindIds = IntSet()
MAIN_EXECUTOR.submit {
modelHelper.model.addCallbacksAndLoad(callbacks)
verify(callbacks, never()).bindItems(any(), any())
verify(callbacks, times(1))
.bindInflatedItems(
argThat { t ->
t.forEach { firstPageBindIds.add(it.first.id) }
t.size == 2
}
)
// Verify that onInitialBindComplete is called and the binding is not yet complete
assertFalse(callbacks.onCompleteSignal!!.isDestroyed)
}
.get()
waitForLoaderAndTempMainThread()
assertTrue(callbacks.onCompleteSignal!!.isDestroyed)
// Verify that firstPageBindIds are loaded on the main thread and remaining
// on the background thread.
assertEquals(5, inflationLooper.size())
for (i in 0..4) {
if (firstPageBindIds.contains(inflationLooper.keyAt(i)))
assertEquals(MAIN_EXECUTOR.looper, inflationLooper.valueAt(i))
else assertEquals(MODEL_EXECUTOR.looper, inflationLooper.valueAt(i))
}
MAIN_EXECUTOR.submit {
reset(callbacks)
callbacks.pendingTasks!!.executeAllAndDestroy()
// Verify remaining 3 times are bound using pending tasks
verify(callbacks, times(1)).bindInflatedItems(argThat { t -> t.size == 3 })
}
.get()
}
private fun waitForLoaderAndTempMainThread() {
MAIN_EXECUTOR.submit {}.get()
MODEL_EXECUTOR.submit {}.get()
MAIN_EXECUTOR.submit {}.get()
}
class MyCallbacks : Callbacks {
var inflater: ItemInflater<*>? = null
var pendingTasks: RunnableList? = null
var onCompleteSignal: RunnableList? = null
override fun bindItems(shortcuts: MutableList<ItemInfo>, forceAnimateIcons: Boolean) {}
override fun bindInflatedItems(items: MutableList<Pair<ItemInfo, View>>) {}
override fun getPagesToBindSynchronously(orderedScreenIds: IntArray?) = IntSet.wrap(0)
override fun onInitialBindComplete(
boundPages: IntSet,
pendingTasks: RunnableList,
onCompleteSignal: RunnableList,
workspaceItemCount: Int,
isBindSync: Boolean
) {
this.pendingTasks = pendingTasks
this.onCompleteSignal = onCompleteSignal
}
override fun getItemInflater() = inflater
}
}
@@ -0,0 +1,185 @@
/*
* Copyright (C) 2024 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.launcher3.model;
import static android.os.Process.myUserHandle;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY2;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY3;
import static com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE;
import static com.android.launcher3.util.TestUtil.runOnExecutorSync;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import android.content.Context;
import android.content.pm.PackageInstaller;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.LauncherModelHelper;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.rule.TestStabilityRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
/**
* Tests for {@link CacheDataUpdatedTask}
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
public class CacheDataUpdatedTaskTest {
@Rule(order = 0)
public TestRule testStabilityRule = new TestStabilityRule();
@Rule(order = 1)
public ModelTestRule mModelTestRule = new ModelTestRule();
private static final String PENDING_APP_1 = TEST_PACKAGE + ".pending1";
private static final String PENDING_APP_2 = TEST_PACKAGE + ".pending2";
private LauncherModelHelper mModelHelper;
private Context mContext;
private int mSession1;
@Before
public void setup() throws Exception {
mModelHelper = new LauncherModelHelper();
mContext = mModelHelper.sandboxContext;
mSession1 = mModelHelper.createInstallerSession(PENDING_APP_1);
mModelHelper.createInstallerSession(PENDING_APP_2);
LauncherLayoutBuilder builder = new LauncherLayoutBuilder()
.atHotseat(1).putFolder("MyFolder")
.addApp(TEST_PACKAGE, TEST_ACTIVITY) // 2
.addApp(TEST_PACKAGE, TEST_ACTIVITY2) // 3
.addApp(TEST_PACKAGE, TEST_ACTIVITY3) // 4
// Pending App 1
.addApp(PENDING_APP_1, TEST_ACTIVITY) // 5
.addApp(PENDING_APP_1, TEST_ACTIVITY2) // 6
.addApp(PENDING_APP_1, TEST_ACTIVITY3) // 7
// Pending App 2
.addApp(PENDING_APP_2, TEST_ACTIVITY) // 8
.addApp(PENDING_APP_2, TEST_ACTIVITY2) // 9
.addApp(PENDING_APP_2, TEST_ACTIVITY3) // 10
.build();
mModelHelper.setupDefaultLayoutProvider(builder);
mModelHelper.loadModelSync();
assertEquals(10, mModelHelper.getBgDataModel().itemsIdMap.size());
}
@After
public void tearDown() {
mModelHelper.destroy();
}
private CacheDataUpdatedTask newTask(int op, String... pkg) {
return new CacheDataUpdatedTask(op, myUserHandle(),
new HashSet<>(Arrays.asList(pkg)));
}
@Test
public void testCacheUpdate_update_apps() {
// Run on model executor so that no other task runs in the middle.
runOnExecutorSync(MODEL_EXECUTOR, () -> {
// Clear all icons from apps list so that its easy to check what was updated
allItems().forEach(wi -> wi.bitmap = BitmapInfo.LOW_RES_INFO);
mModelHelper.getModel().enqueueModelUpdateTask(
newTask(CacheDataUpdatedTask.OP_CACHE_UPDATE, TEST_PACKAGE));
// Verify that only the app icons of TEST_PACKAGE (id 2, 3, 4) are updated.
verifyUpdate(2, 3, 4);
});
}
@Test
public void testSessionUpdate_ignores_normal_apps() {
// Run on model executor so that no other task runs in the middle.
runOnExecutorSync(MODEL_EXECUTOR, () -> {
// Clear all icons from apps list so that its easy to check what was updated
allItems().forEach(wi -> wi.bitmap = BitmapInfo.LOW_RES_INFO);
mModelHelper.getModel().enqueueModelUpdateTask(
newTask(CacheDataUpdatedTask.OP_SESSION_UPDATE, TEST_PACKAGE));
// TEST_PACKAGE has no restored shortcuts. Verify that nothing was updated.
verifyUpdate();
});
}
@Test
public void testSessionUpdate_updates_pending_apps() {
// Run on model executor so that no other task runs in the middle.
PackageInstaller.SessionInfo sessionInfo = ApplicationProvider.getApplicationContext()
.getPackageManager().getPackageInstaller().getSessionInfo(mSession1);
assertNotNull(sessionInfo);
runOnExecutorSync(MODEL_EXECUTOR, () -> {
LauncherAppState.getInstance(mContext).getIconCache().updateSessionCache(
new PackageUserKey(PENDING_APP_1, myUserHandle()),
sessionInfo);
// Clear all icons from apps list so that its easy to check what was updated
allItems().forEach(wi -> wi.bitmap = BitmapInfo.LOW_RES_INFO);
mModelHelper.getModel().enqueueModelUpdateTask(
newTask(CacheDataUpdatedTask.OP_SESSION_UPDATE, PENDING_APP_1));
// Only restored apps from PENDING_APP_1 (id 5, 6, 7) are updated
verifyUpdate(5, 6, 7);
});
}
private void verifyUpdate(int... idsUpdated) {
IntSet updates = IntSet.wrap(idsUpdated);
for (WorkspaceItemInfo info : allItems()) {
if (updates.contains(info.id)) {
assertFalse(info.bitmap.isNullOrLowRes());
} else {
assertTrue(info.bitmap.isNullOrLowRes());
}
}
}
private List<WorkspaceItemInfo> allItems() {
return ((FolderInfo) mModelHelper.getBgDataModel().itemsIdMap.get(1)).getAppContents();
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.model;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY;
import static com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;
import android.content.pm.LauncherApps;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageInstaller.SessionParams;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.LauncherModelHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for layout parser for remote layout
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
public class DefaultLayoutProviderTest {
@Rule public ModelTestRule rule = new ModelTestRule();
private LauncherModelHelper mModelHelper;
private LauncherModelHelper.SandboxModelContext mTargetContext;
@Before
public void setUp() {
mModelHelper = new LauncherModelHelper();
mTargetContext = mModelHelper.sandboxContext;
}
@After
public void tearDown() {
mModelHelper.destroy();
}
@Test
public void testCustomProfileLoaded_with_icon_on_hotseat() throws Exception {
writeLayoutAndLoad(new LauncherLayoutBuilder().atHotseat(0)
.putApp(TEST_PACKAGE, TEST_ACTIVITY));
// Verify one item in hotseat
assertEquals(1, mModelHelper.getBgDataModel().workspaceItems.size());
ItemInfo info = mModelHelper.getBgDataModel().workspaceItems.get(0);
assertEquals(LauncherSettings.Favorites.CONTAINER_HOTSEAT, info.container);
assertEquals(LauncherSettings.Favorites.ITEM_TYPE_APPLICATION, info.itemType);
}
@Test
public void testCustomProfileLoaded_with_folder() throws Exception {
writeLayoutAndLoad(new LauncherLayoutBuilder().atHotseat(0).putFolder(android.R.string.copy)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.build());
// Verify folder
assertEquals(1, mModelHelper.getBgDataModel().workspaceItems.size());
ItemInfo info = mModelHelper.getBgDataModel().workspaceItems.get(0);
assertEquals(LauncherSettings.Favorites.ITEM_TYPE_FOLDER, info.itemType);
assertEquals(3, ((FolderInfo) info).getContents().size());
}
@Test
public void testCustomProfileLoaded_with_folder_custom_title() throws Exception {
writeLayoutAndLoad(new LauncherLayoutBuilder().atHotseat(0).putFolder("CustomFolder")
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.build());
// Verify folder
assertEquals(1, mModelHelper.getBgDataModel().workspaceItems.size());
ItemInfo info = mModelHelper.getBgDataModel().workspaceItems.get(0);
assertEquals(LauncherSettings.Favorites.ITEM_TYPE_FOLDER, info.itemType);
assertEquals(3, ((FolderInfo) info).getContents().size());
assertEquals("CustomFolder", info.title.toString());
}
@Test
public void testCustomProfileLoaded_with_widget() throws Exception {
String pendingAppPkg = "com.test.pending";
// Add a placeholder session info so that the widget exists
SessionParams params = new SessionParams(SessionParams.MODE_FULL_INSTALL);
params.setAppPackageName(pendingAppPkg);
params.setAppIcon(BitmapInfo.LOW_RES_ICON);
params.installerPackageName = ApplicationProvider.getApplicationContext().getPackageName();
PackageInstaller installer = ApplicationProvider.getApplicationContext().getPackageManager()
.getPackageInstaller();
installer.createSession(params);
writeLayoutAndLoad(new LauncherLayoutBuilder().atWorkspace(0, 1, 0)
.putWidget(pendingAppPkg, "PlaceholderWidget", 2, 2));
// Verify widget
assertEquals(1, mModelHelper.getBgDataModel().appWidgets.size());
ItemInfo info = mModelHelper.getBgDataModel().appWidgets.get(0);
assertEquals(LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET, info.itemType);
assertEquals(2, info.spanX);
assertEquals(2, info.spanY);
}
@Test
public void testCustomProfileLoaded_with_shortcut_on_hotseat() throws Exception {
assumeTrue(mTargetContext.getSystemService(LauncherApps.class).hasShortcutHostPermission());
writeLayoutAndLoad(new LauncherLayoutBuilder().atHotseat(0)
.putShortcut(TEST_PACKAGE, "shortcut2"));
// Verify one item in hotseat
assertEquals(1, mModelHelper.getBgDataModel().workspaceItems.size());
ItemInfo info = mModelHelper.getBgDataModel().workspaceItems.get(0);
assertEquals(LauncherSettings.Favorites.CONTAINER_HOTSEAT, info.container);
assertEquals(LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT, info.itemType);
}
@Test
public void testCustomProfileLoaded_with_shortcut_in_folder() throws Exception {
assumeTrue(mTargetContext.getSystemService(LauncherApps.class).hasShortcutHostPermission());
writeLayoutAndLoad(new LauncherLayoutBuilder().atHotseat(0).putFolder(android.R.string.copy)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.addApp(TEST_PACKAGE, TEST_ACTIVITY)
.addShortcut(TEST_PACKAGE, "shortcut2")
.build());
// Verify folder
assertEquals(1, mModelHelper.getBgDataModel().workspaceItems.size());
FolderInfo info = (FolderInfo) mModelHelper.getBgDataModel().workspaceItems.get(0);
assertEquals(3, info.getContents().size());
// Verify last icon
assertEquals(LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT,
info.getContents().get(info.getContents().size() - 1).itemType);
}
private void writeLayoutAndLoad(LauncherLayoutBuilder builder) throws Exception {
mModelHelper.setupDefaultLayoutProvider(builder).loadModelSync();
}
}
@@ -0,0 +1,393 @@
/*
* Copyright (C) 2024 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.launcher3.model
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageInstaller.SessionInfo
import android.os.UserHandle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT
import com.android.launcher3.model.FirstScreenBroadcastHelper.MAX_BROADCAST_SIZE
import com.android.launcher3.model.FirstScreenBroadcastHelper.getTotalItemCount
import com.android.launcher3.model.FirstScreenBroadcastHelper.truncateModelForBroadcast
import com.android.launcher3.model.data.FolderInfo
import com.android.launcher3.model.data.LauncherAppWidgetInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.util.PackageManagerHelper
import com.android.launcher3.util.PackageUserKey
import junit.framework.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@RunWith(AndroidJUnit4::class)
class FirstScreenBroadcastHelperTest {
@get:Rule val modelTestRule = ModelTestRule()
private val context = spy(InstrumentationRegistry.getInstrumentation().targetContext)
private val mockPmHelper = mock<PackageManagerHelper>()
private val expectedAppPackage = "appPackageExpected"
private val expectedComponentName = ComponentName(expectedAppPackage, "expectedClass")
private val expectedInstallerPackage = "installerPackage"
private val expectedIntent =
Intent().apply {
component = expectedComponentName
setPackage(expectedAppPackage)
}
private val unexpectedAppPackage = "appPackageUnexpected"
private val unexpectedComponentName = ComponentName(expectedAppPackage, "unexpectedClass")
private val firstScreenItems =
listOf(
WorkspaceItemInfo().apply {
container = CONTAINER_DESKTOP
intent = expectedIntent
},
WorkspaceItemInfo().apply {
container = CONTAINER_HOTSEAT
intent = expectedIntent
},
LauncherAppWidgetInfo().apply { providerName = expectedComponentName }
)
@Test
fun `Broadcast Models are created with Pending Items from first screen`() {
// Given
val sessionInfoExpected =
SessionInfo().apply {
installerPackageName = expectedInstallerPackage
appPackageName = expectedAppPackage
}
val sessionInfoUnexpected =
SessionInfo().apply {
installerPackageName = expectedInstallerPackage
appPackageName = unexpectedAppPackage
}
val sessionInfoMap: HashMap<PackageUserKey, SessionInfo> =
hashMapOf(
PackageUserKey(unexpectedAppPackage, UserHandle(0)) to sessionInfoExpected,
PackageUserKey(expectedAppPackage, UserHandle(0)) to sessionInfoUnexpected
)
// When
val actualResult =
FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast(
packageManagerHelper = mockPmHelper,
firstScreenItems = firstScreenItems,
userKeyToSessionMap = sessionInfoMap,
allWidgets = listOf()
)
// Then
val expectedResult =
listOf(
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
pendingWorkspaceItems = mutableSetOf(expectedAppPackage),
pendingHotseatItems = mutableSetOf(expectedAppPackage),
pendingWidgetItems = mutableSetOf(expectedAppPackage)
)
)
assertEquals(expectedResult, actualResult)
}
@Test
fun `Broadcast Models are created with Installed Items from first screen`() {
// Given
whenever(mockPmHelper.getAppInstallerPackage(expectedAppPackage))
.thenReturn(expectedInstallerPackage)
// When
val actualResult =
FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast(
packageManagerHelper = mockPmHelper,
firstScreenItems = firstScreenItems,
userKeyToSessionMap = hashMapOf(),
allWidgets =
listOf(
LauncherAppWidgetInfo().apply {
providerName = expectedComponentName
screenId = 0
}
)
)
// Then
val expectedResult =
listOf(
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
installedHotseatItems = mutableSetOf(expectedAppPackage),
installedWorkspaceItems = mutableSetOf(expectedAppPackage),
firstScreenInstalledWidgets = mutableSetOf(expectedAppPackage)
)
)
assertEquals(expectedResult, actualResult)
}
@Test
fun `Broadcast Models are created with Installed Widgets from every screen`() {
// Given
val expectedAppPackage2 = "appPackageExpected2"
val expectedComponentName2 = ComponentName(expectedAppPackage2, "expectedClass2")
whenever(mockPmHelper.getAppInstallerPackage(expectedAppPackage))
.thenReturn(expectedInstallerPackage)
whenever(mockPmHelper.getAppInstallerPackage(expectedAppPackage2))
.thenReturn(expectedInstallerPackage)
// When
val actualResult =
FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast(
packageManagerHelper = mockPmHelper,
firstScreenItems = listOf(),
userKeyToSessionMap = hashMapOf(),
allWidgets =
listOf(
LauncherAppWidgetInfo().apply {
providerName = expectedComponentName
screenId = 0
},
LauncherAppWidgetInfo().apply {
providerName = expectedComponentName2
screenId = 1
},
LauncherAppWidgetInfo().apply {
providerName = unexpectedComponentName
screenId = 0
}
)
)
// Then
val expectedResult =
listOf(
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
installedHotseatItems = mutableSetOf(),
installedWorkspaceItems = mutableSetOf(),
firstScreenInstalledWidgets = mutableSetOf(expectedAppPackage),
secondaryScreenInstalledWidgets = mutableSetOf(expectedAppPackage2)
)
)
assertEquals(expectedResult, actualResult)
}
@Test
fun `Broadcast Models are created with Pending Items in Collections from the first screen`() {
// Given
val sessionInfoExpected =
SessionInfo().apply {
installerPackageName = expectedInstallerPackage
appPackageName = expectedAppPackage
}
val sessionInfoUnexpected =
SessionInfo().apply {
installerPackageName = expectedInstallerPackage
appPackageName = unexpectedAppPackage
}
val sessionInfoMap: HashMap<PackageUserKey, SessionInfo> =
hashMapOf(
PackageUserKey(unexpectedAppPackage, UserHandle(0)) to sessionInfoExpected,
PackageUserKey(expectedAppPackage, UserHandle(0)) to sessionInfoUnexpected,
)
val expectedItemInfo = WorkspaceItemInfo().apply { intent = expectedIntent }
val expectedFolderInfo = FolderInfo().apply { add(expectedItemInfo) }
val firstScreenItems = listOf(expectedFolderInfo)
// When
val actualResult =
FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast(
packageManagerHelper = mockPmHelper,
firstScreenItems = firstScreenItems,
userKeyToSessionMap = sessionInfoMap,
allWidgets = listOf()
)
// Then
val expectedResult =
listOf(
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
pendingCollectionItems = mutableSetOf(expectedAppPackage)
)
)
assertEquals(expectedResult, actualResult)
}
@Test
fun `Models with too many items get truncated to max Broadcast size`() {
// given
val broadcastModel =
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
pendingCollectionItems =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
pendingWorkspaceItems =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
pendingHotseatItems =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
pendingWidgetItems =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
installedWorkspaceItems =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
installedHotseatItems =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
firstScreenInstalledWidgets =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
secondaryScreenInstalledWidgets =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } }
)
// When
broadcastModel.truncateModelForBroadcast()
// Then
assertEquals(MAX_BROADCAST_SIZE, broadcastModel.getTotalItemCount())
}
@Test
fun `Broadcast truncates installed Hotseat items before other installed items`() {
// Given
val broadcastModel =
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
installedWorkspaceItems =
mutableSetOf<String>().apply { repeat(50) { add(it.toString()) } },
firstScreenInstalledWidgets =
mutableSetOf<String>().apply { repeat(10) { add(it.toString()) } },
secondaryScreenInstalledWidgets =
mutableSetOf<String>().apply { repeat(10) { add((it + 10).toString()) } },
installedHotseatItems =
mutableSetOf<String>().apply { repeat(10) { add(it.toString()) } },
)
// When
broadcastModel.truncateModelForBroadcast()
// Then
assertEquals(MAX_BROADCAST_SIZE, broadcastModel.getTotalItemCount())
assertEquals(50, broadcastModel.installedWorkspaceItems.size)
assertEquals(10, broadcastModel.firstScreenInstalledWidgets.size)
assertEquals(10, broadcastModel.secondaryScreenInstalledWidgets.size)
assertEquals(0, broadcastModel.installedHotseatItems.size)
}
@Test
fun `Broadcast truncates Widgets before the rest of the first screen items`() {
// Given
val broadcastModel =
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
installedWorkspaceItems =
mutableSetOf<String>().apply { repeat(70) { add(it.toString()) } },
firstScreenInstalledWidgets =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
secondaryScreenInstalledWidgets =
mutableSetOf<String>().apply { repeat(20) { add(it.toString()) } },
)
// When
broadcastModel.truncateModelForBroadcast()
// Then
assertEquals(MAX_BROADCAST_SIZE, broadcastModel.getTotalItemCount())
assertEquals(70, broadcastModel.installedWorkspaceItems.size)
assertEquals(0, broadcastModel.firstScreenInstalledWidgets.size)
assertEquals(0, broadcastModel.secondaryScreenInstalledWidgets.size)
}
@Test
fun `Broadcasts are correctly formed with Extras for each Installer`() {
// Given
val broadcastModels: List<FirstScreenBroadcastModel> =
listOf(
FirstScreenBroadcastModel(
installerPackage = expectedInstallerPackage,
pendingCollectionItems = mutableSetOf("pendingCollectionItem"),
pendingWorkspaceItems = mutableSetOf("pendingWorkspaceItem"),
pendingHotseatItems = mutableSetOf("pendingHotseatItems"),
pendingWidgetItems = mutableSetOf("pendingWidgetItems"),
installedWorkspaceItems = mutableSetOf("installedWorkspaceItems"),
installedHotseatItems = mutableSetOf("installedHotseatItems"),
firstScreenInstalledWidgets = mutableSetOf("firstScreenInstalledWidgetItems"),
secondaryScreenInstalledWidgets = mutableSetOf("secondaryInstalledWidgetItems")
)
)
val expectedPendingIntent =
PendingIntent.getActivity(
context,
0 /* requestCode */,
Intent(),
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
// When
FirstScreenBroadcastHelper.sendBroadcastsForModels(context, broadcastModels)
// Then
val argumentCaptor = ArgumentCaptor.forClass(Intent::class.java)
verify(context).sendBroadcast(argumentCaptor.capture())
assertEquals(
"com.android.launcher3.action.FIRST_SCREEN_ACTIVE_INSTALLS",
argumentCaptor.value.action
)
assertEquals(expectedInstallerPackage, argumentCaptor.value.`package`)
assertEquals(
expectedPendingIntent,
argumentCaptor.value.getParcelableExtra("verificationToken")
)
assertEquals(
arrayListOf("pendingCollectionItem"),
argumentCaptor.value.getStringArrayListExtra("folderItem")
)
assertEquals(
arrayListOf("pendingWorkspaceItem"),
argumentCaptor.value.getStringArrayListExtra("workspaceItem")
)
assertEquals(
arrayListOf("pendingHotseatItems"),
argumentCaptor.value.getStringArrayListExtra("hotseatItem")
)
assertEquals(
arrayListOf("pendingWidgetItems"),
argumentCaptor.value.getStringArrayListExtra("widgetItem")
)
assertEquals(
arrayListOf("installedWorkspaceItems"),
argumentCaptor.value.getStringArrayListExtra("workspaceInstalledItems")
)
assertEquals(
arrayListOf("installedHotseatItems"),
argumentCaptor.value.getStringArrayListExtra("hotseatInstalledItems")
)
assertEquals(
arrayListOf("firstScreenInstalledWidgetItems", "secondaryInstalledWidgetItems"),
argumentCaptor.value.getStringArrayListExtra("widgetInstalledItems")
)
}
}
@@ -0,0 +1,190 @@
/*
* Copyright (C) 2023 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.launcher3.model
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.LauncherAppState
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.util.Executors
import com.android.launcher3.util.LauncherLayoutBuilder
import com.android.launcher3.util.LauncherModelHelper
import com.android.launcher3.util.LauncherModelHelper.*
import com.android.launcher3.util.RoboApiWrapper
import com.android.launcher3.util.TestUtil
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.util.concurrent.CountDownLatch
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/** Tests to verify that folder icons are loaded with appropriate resolution */
@SmallTest
@RunWith(AndroidJUnit4::class)
class FolderIconLoadTest {
@get:Rule(order = 0) val modelTestRule = ModelTestRule()
private lateinit var modelHelper: LauncherModelHelper
private val uniqueActivities =
listOf(
TEST_ACTIVITY,
TEST_ACTIVITY2,
TEST_ACTIVITY3,
TEST_ACTIVITY4,
TEST_ACTIVITY5,
TEST_ACTIVITY6,
TEST_ACTIVITY7,
TEST_ACTIVITY8,
TEST_ACTIVITY9,
TEST_ACTIVITY10,
TEST_ACTIVITY11,
TEST_ACTIVITY12,
TEST_ACTIVITY13,
TEST_ACTIVITY14
)
@Before
fun setUp() {
modelHelper = LauncherModelHelper()
}
@After
@Throws(Exception::class)
fun tearDown() {
modelHelper.destroy()
TestUtil.uninstallDummyApp()
}
@Test
@Throws(Exception::class)
fun folderLoadedWithHighRes_2x2() {
val items = setupAndLoadFolder(4)
assertThat(items.size).isEqualTo(4)
verifyHighRes(items, 0, 1, 2, 3)
}
@Test
@Throws(Exception::class)
fun folderLoadedWithHighRes_3x2() {
val items = setupAndLoadFolder(6)
assertThat(items.size).isEqualTo(6)
verifyHighRes(items, 0, 1, 3, 4)
verifyLowRes(items, 2, 5)
}
@Test
@Throws(Exception::class)
fun folderLoadedWithHighRes_max_3x3() {
val idp = LauncherAppState.getIDP(modelHelper.sandboxContext)
idp.numFolderColumns = intArrayOf(3, 3, 3, 3)
idp.numFolderRows = intArrayOf(3, 3, 3, 3)
recreateSupportedDeviceProfiles()
val items = setupAndLoadFolder(14)
verifyHighRes(items, 0, 1, 3, 4)
verifyLowRes(items, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13)
}
@Test
@Throws(Exception::class)
fun folderLoadedWithHighRes_max_4x4() {
val idp = LauncherAppState.getIDP(modelHelper.sandboxContext)
idp.numFolderColumns = intArrayOf(4, 4, 4, 4)
idp.numFolderRows = intArrayOf(4, 4, 4, 4)
recreateSupportedDeviceProfiles()
val items = setupAndLoadFolder(14)
verifyHighRes(items, 0, 1, 4, 5)
verifyLowRes(items, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13)
}
@Test
@Throws(Exception::class)
fun folderLoadedWithHighRes_differentFolderConfigurations() {
val idp = LauncherAppState.getIDP(modelHelper.sandboxContext)
idp.numFolderColumns = intArrayOf(4, 3, 4, 4)
idp.numFolderRows = intArrayOf(4, 3, 4, 4)
recreateSupportedDeviceProfiles()
val items = setupAndLoadFolder(14)
verifyHighRes(items, 0, 1, 3, 4, 5)
verifyLowRes(items, 2, 6, 7, 8, 9, 10, 11, 12, 13)
}
@Throws(Exception::class)
private fun setupAndLoadFolder(itemCount: Int): ArrayList<WorkspaceItemInfo> {
val builder =
LauncherLayoutBuilder()
.atWorkspace(0, 0, 1)
.putFolder("Sample")
.apply {
for (i in 0..itemCount - 1) this.addApp(TEST_PACKAGE, uniqueActivities[i])
}
.build()
modelHelper.setupDefaultLayoutProvider(builder)
modelHelper.loadModelSync()
// The first load initializes the DB, load again so that icons are now used from the DB
// Wait for the icon cache to be updated and then reload
val app = LauncherAppState.getInstance(modelHelper.sandboxContext)
val cache = app.iconCache
while (cache.isIconUpdateInProgress) {
val wait = CountDownLatch(1)
Executors.MODEL_EXECUTOR.handler.postDelayed({ wait.countDown() }, 10)
RoboApiWrapper.waitForLooperSync(Executors.MODEL_EXECUTOR.handler.looper)
wait.await()
}
TestUtil.runOnExecutorSync(Executors.MODEL_EXECUTOR) { cache.clearMemoryCache() }
// Reload again with correct icon state
app.model.forceReload()
modelHelper.loadModelSync()
val collections = modelHelper.getBgDataModel().collections
assertThat(collections.size()).isEqualTo(1)
assertThat(collections.valueAt(0).getAppContents().size).isEqualTo(itemCount)
return collections.valueAt(0).getAppContents()
}
private fun verifyHighRes(items: ArrayList<WorkspaceItemInfo>, vararg indices: Int) {
for (index in indices) {
assertWithMessage("Index $index was not highRes")
.that(items[index].bitmap.isNullOrLowRes)
.isFalse()
}
}
private fun verifyLowRes(items: ArrayList<WorkspaceItemInfo>, vararg indices: Int) {
for (index in indices) {
assertWithMessage("Index $index was not lowRes")
.that(items[index].bitmap.isNullOrLowRes)
.isTrue()
}
}
/** Recreate DeviceProfiles after changing InvariantDeviceProfile */
private fun recreateSupportedDeviceProfiles() {
LauncherAppState.getIDP(modelHelper.sandboxContext).supportedProfiles =
LauncherAppState.getIDP(modelHelper.sandboxContext).supportedProfiles.map {
it.copy(modelHelper.sandboxContext)
}
}
}
@@ -0,0 +1,239 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.model;
import static androidx.test.InstrumentationRegistry.getContext;
import static com.android.launcher3.LauncherSettings.Favorites.APPWIDGET_ID;
import static com.android.launcher3.LauncherSettings.Favorites.APPWIDGET_PROVIDER;
import static com.android.launcher3.LauncherSettings.Favorites.APPWIDGET_SOURCE;
import static com.android.launcher3.LauncherSettings.Favorites.CELLX;
import static com.android.launcher3.LauncherSettings.Favorites.CELLY;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
import static com.android.launcher3.LauncherSettings.Favorites.ICON;
import static com.android.launcher3.LauncherSettings.Favorites.INTENT;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.LauncherSettings.Favorites.OPTIONS;
import static com.android.launcher3.LauncherSettings.Favorites.PROFILE_ID;
import static com.android.launcher3.LauncherSettings.Favorites.RANK;
import static com.android.launcher3.LauncherSettings.Favorites.RESTORED;
import static com.android.launcher3.LauncherSettings.Favorites.SCREEN;
import static com.android.launcher3.LauncherSettings.Favorites.SPANX;
import static com.android.launcher3.LauncherSettings.Favorites.SPANY;
import static com.android.launcher3.LauncherSettings.Favorites.TITLE;
import static com.android.launcher3.LauncherSettings.Favorites._ID;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.MatrixCursor;
import android.os.Process;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.LauncherModelHelper;
import com.android.launcher3.util.PackageManagerHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for {@link LoaderCursor}
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
public class LoaderCursorTest {
@Rule public ModelTestRule rule = new ModelTestRule();
private LauncherModelHelper mModelHelper;
private LauncherAppState mApp;
private PackageManagerHelper mPmHelper;
private MatrixCursor mCursor;
private InvariantDeviceProfile mIDP;
private Context mContext;
private LoaderCursor mLoaderCursor;
@Before
public void setup() {
mModelHelper = new LauncherModelHelper();
mContext = mModelHelper.sandboxContext;
mIDP = InvariantDeviceProfile.INSTANCE.get(mContext);
mApp = LauncherAppState.getInstance(mContext);
mPmHelper = PackageManagerHelper.INSTANCE.get(mContext);
mCursor = new MatrixCursor(new String[] {
ICON, TITLE, _ID, CONTAINER, ITEM_TYPE,
PROFILE_ID, SCREEN, CELLX, CELLY, RESTORED,
INTENT, APPWIDGET_ID, APPWIDGET_PROVIDER,
SPANX, SPANY, RANK, OPTIONS, APPWIDGET_SOURCE
});
UserManagerState ums = new UserManagerState();
mLoaderCursor = new LoaderCursor(mCursor, mApp, ums, mPmHelper, null);
ums.allUsers.put(0, Process.myUserHandle());
}
@After
public void tearDown() {
mModelHelper.destroy();
}
private void initCursor(int itemType, String title) {
mCursor.newRow()
.add(_ID, 1)
.add(PROFILE_ID, 0)
.add(ITEM_TYPE, itemType)
.add(TITLE, title)
.add(CONTAINER, CONTAINER_DESKTOP);
}
@Test
public void getAppShortcutInfo_dontAllowMissing_invalidComponent() {
initCursor(ITEM_TYPE_APPLICATION, "");
assertTrue(mLoaderCursor.moveToNext());
ComponentName cn = new ComponentName(mContext.getPackageName(), "placeholder-do");
assertNull(mLoaderCursor.getAppShortcutInfo(
new Intent().setComponent(cn), false /* allowMissingTarget */, true));
}
@Test
public void getAppShortcutInfo_dontAllowMissing_validComponent() throws Exception {
ComponentName cn = new ComponentName(getContext(), TEST_ACTIVITY);
initCursor(ITEM_TYPE_APPLICATION, "");
assertTrue(mLoaderCursor.moveToNext());
WorkspaceItemInfo info = Executors.MODEL_EXECUTOR.submit(() ->
mLoaderCursor.getAppShortcutInfo(
new Intent().setComponent(cn), false /* allowMissingTarget */, true))
.get();
assertNotNull(info);
assertTrue(PackageManagerHelper.isLauncherAppTarget(info.getIntent()));
}
@Test
public void getAppShortcutInfo_allowMissing_invalidComponent() throws Exception {
initCursor(ITEM_TYPE_APPLICATION, "");
assertTrue(mLoaderCursor.moveToNext());
ComponentName cn = new ComponentName(mContext.getPackageName(), "placeholder-do");
WorkspaceItemInfo info = Executors.MODEL_EXECUTOR.submit(() ->
mLoaderCursor.getAppShortcutInfo(
new Intent().setComponent(cn), true /* allowMissingTarget */, true))
.get();
assertNotNull(info);
assertTrue(PackageManagerHelper.isLauncherAppTarget(info.getIntent()));
}
@Test
public void loadSimpleShortcut() {
initCursor(ITEM_TYPE_DEEP_SHORTCUT, "my-shortcut");
assertTrue(mLoaderCursor.moveToNext());
WorkspaceItemInfo info = mLoaderCursor.loadSimpleWorkspaceItem();
assertTrue(mApp.getIconCache().isDefaultIcon(info.bitmap, info.user));
assertEquals("my-shortcut", info.title);
assertEquals(ITEM_TYPE_DEEP_SHORTCUT, info.itemType);
}
@Test
public void checkItemPlacement_outsideBounds() {
mIDP.numRows = 4;
mIDP.numColumns = 4;
mIDP.numDatabaseHotseatIcons = 3;
// Item outside screen bounds are not placed
assertFalse(mLoaderCursor.checkItemPlacement(
newItemInfo(4, 4, 1, 1, CONTAINER_DESKTOP, 1), true));
}
@Test
public void checkItemPlacement_overlappingItems() {
mIDP.numRows = 4;
mIDP.numColumns = 4;
mIDP.numDatabaseHotseatIcons = 3;
// Overlapping mItems are not placed
assertTrue(mLoaderCursor.checkItemPlacement(
newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1), true));
assertFalse(mLoaderCursor.checkItemPlacement(
newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1), true));
assertTrue(mLoaderCursor.checkItemPlacement(
newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2), true));
assertFalse(mLoaderCursor.checkItemPlacement(
newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2), true));
assertTrue(mLoaderCursor.checkItemPlacement(
newItemInfo(1, 1, 1, 1, CONTAINER_DESKTOP, 1), true));
assertTrue(mLoaderCursor.checkItemPlacement(
newItemInfo(2, 2, 2, 2, CONTAINER_DESKTOP, 1), true));
assertFalse(mLoaderCursor.checkItemPlacement(
newItemInfo(3, 2, 1, 2, CONTAINER_DESKTOP, 1), true));
}
@Test
public void checkItemPlacement_hotseat() {
mIDP.numRows = 4;
mIDP.numColumns = 4;
mIDP.numDatabaseHotseatIcons = 3;
// Hotseat mItems are only placed based on screenId
assertTrue(mLoaderCursor.checkItemPlacement(
newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 1), true));
assertTrue(mLoaderCursor.checkItemPlacement(
newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 2), true));
assertFalse(mLoaderCursor.checkItemPlacement(
newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 3), true));
}
private ItemInfo newItemInfo(int cellX, int cellY, int spanX, int spanY,
int container, int screenId) {
ItemInfo info = new ItemInfo();
info.cellX = cellX;
info.cellY = cellY;
info.spanX = spanX;
info.spanY = spanY;
info.container = container;
info.screenId = screenId;
return info;
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2024 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.launcher3.model
import com.android.launcher3.util.RoboApiWrapper
import org.junit.rules.TestWatcher
import org.junit.runner.Description
class ModelTestRule : TestWatcher() {
override fun starting(description: Description?) {
RoboApiWrapper.initialize()
}
}
@@ -0,0 +1,140 @@
/*
* Copyright (C) 2024 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.launcher3.model;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY2;
import static com.android.launcher3.util.LauncherModelHelper.TEST_ACTIVITY3;
import static com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE;
import static com.android.launcher3.util.TestUtil.runOnExecutorSync;
import static org.junit.Assert.assertEquals;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.LauncherModelHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests for {@link PackageInstallStateChangedTask}
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
public class PackageInstallStateChangedTaskTest {
@Rule public ModelTestRule mModelTestRule = new ModelTestRule();
private static final String PENDING_APP_1 = TEST_PACKAGE + ".pending1";
private static final String PENDING_APP_2 = TEST_PACKAGE + ".pending2";
private LauncherModelHelper mModelHelper;
private IntSet mDownloadingApps;
@Before
public void setup() throws Exception {
mModelHelper = new LauncherModelHelper();
mModelHelper.createInstallerSession(PENDING_APP_1);
mModelHelper.createInstallerSession(PENDING_APP_2);
LauncherLayoutBuilder builder = new LauncherLayoutBuilder()
.atWorkspace(0, 0, 1).putApp(TEST_PACKAGE, TEST_ACTIVITY) // 1
.atWorkspace(0, 0, 2).putApp(TEST_PACKAGE, TEST_ACTIVITY2) // 2
.atWorkspace(0, 0, 3).putApp(TEST_PACKAGE, TEST_ACTIVITY3) // 3
.atWorkspace(0, 0, 4).putApp(PENDING_APP_1, TEST_ACTIVITY) // 4
.atWorkspace(0, 0, 5).putApp(PENDING_APP_1, TEST_ACTIVITY2) // 5
.atWorkspace(0, 0, 6).putApp(PENDING_APP_1, TEST_ACTIVITY3) // 6
.atWorkspace(0, 0, 7).putWidget(PENDING_APP_1, "pending.widget", 1, 1) // 7
.atWorkspace(0, 0, 8).putApp(PENDING_APP_2, TEST_ACTIVITY) // 8
.atWorkspace(0, 0, 9).putApp(PENDING_APP_2, TEST_ACTIVITY2) // 9
.atWorkspace(0, 0, 10).putApp(PENDING_APP_2, TEST_ACTIVITY3); // 10
mDownloadingApps = IntSet.wrap(4, 5, 6, 7, 8, 9, 10);
mModelHelper.setupDefaultLayoutProvider(builder);
mModelHelper.loadModelSync();
assertEquals(10, mModelHelper.getBgDataModel().itemsIdMap.size());
}
@After
public void tearDown() {
mModelHelper.destroy();
}
private PackageInstallStateChangedTask newTask(String pkg, int progress) {
int state = PackageInstallInfo.STATUS_INSTALLING;
PackageInstallInfo installInfo = new PackageInstallInfo(pkg, state, progress,
android.os.Process.myUserHandle());
return new PackageInstallStateChangedTask(installInfo);
}
@Test
public void testSessionUpdate_ignore_installed() {
// Run on model executor so that no other task runs in the middle.
runOnExecutorSync(MODEL_EXECUTOR, () -> {
mModelHelper.getModel().enqueueModelUpdateTask(newTask(TEST_PACKAGE, 30));
// No shortcuts were updated
verifyProgressUpdate(0);
});
}
@Test
public void testSessionUpdate_shortcuts_updated() {
// Run on model executor so that no other task runs in the middle.
runOnExecutorSync(MODEL_EXECUTOR, () -> {
mModelHelper.getModel().enqueueModelUpdateTask(newTask(PENDING_APP_1, 30));
verifyProgressUpdate(30, 4, 5, 6, 7);
});
}
@Test
public void testSessionUpdate_widgets_updated() {
// Run on model executor so that no other task runs in the middle.
runOnExecutorSync(MODEL_EXECUTOR, () -> {
mModelHelper.getModel().enqueueModelUpdateTask(newTask(PENDING_APP_2, 30));
verifyProgressUpdate(30, 8, 9, 10);
});
}
private void verifyProgressUpdate(int progress, int... idsUpdated) {
IntSet updates = IntSet.wrap(idsUpdated);
for (ItemInfo info : mModelHelper.getBgDataModel().itemsIdMap) {
int expectedProgress = updates.contains(info.id) ? progress
: (mDownloadingApps.contains(info.id) ? 0 : 100);
if (info instanceof WorkspaceItemInfo wi) {
assertEquals(expectedProgress, wi.getProgressLevel());
} else {
assertEquals(expectedProgress, ((LauncherAppWidgetInfo) info).installProgress);
}
}
}
}
@@ -0,0 +1,712 @@
/*
* Copyright (C) 2024 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.launcher3.model
import android.appwidget.AppWidgetProviderInfo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.LauncherApps
import android.content.pm.PackageInstaller
import android.content.pm.ShortcutInfo
import android.os.Process
import android.os.UserHandle
import android.util.LongSparseArray
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherSettings.Favorites
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER
import com.android.launcher3.Utilities.EMPTY_PERSON_ARRAY
import com.android.launcher3.backuprestore.LauncherRestoreEventLogger
import com.android.launcher3.backuprestore.LauncherRestoreEventLogger.RestoreError.Companion.MISSING_INFO
import com.android.launcher3.backuprestore.LauncherRestoreEventLogger.RestoreError.Companion.MISSING_WIDGET_PROVIDER
import com.android.launcher3.backuprestore.LauncherRestoreEventLogger.RestoreError.Companion.PROFILE_DELETED
import com.android.launcher3.model.data.FolderInfo
import com.android.launcher3.model.data.IconRequestInfo
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.LauncherAppWidgetInfo
import com.android.launcher3.model.data.LauncherAppWidgetInfo.FLAG_UI_NOT_READY
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.pm.UserCache
import com.android.launcher3.shortcuts.ShortcutKey
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.PackageManagerHelper
import com.android.launcher3.util.PackageUserKey
import com.android.launcher3.util.UserIconInfo
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo
import com.android.launcher3.widget.WidgetInflater
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Mock
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@RunWith(AndroidJUnit4::class)
class WorkspaceItemProcessorTest {
@get:Rule val modelTestRule = ModelTestRule()
@Mock private lateinit var mockIconRequestInfo: IconRequestInfo<WorkspaceItemInfo>
@Mock private lateinit var mockWorkspaceInfo: WorkspaceItemInfo
@Mock private lateinit var mockBgDataModel: BgDataModel
@Mock private lateinit var mockContext: Context
@Mock private lateinit var mockAppState: LauncherAppState
@Mock private lateinit var mockPmHelper: PackageManagerHelper
@Mock private lateinit var mockLauncherApps: LauncherApps
@Mock private lateinit var mockCursor: LoaderCursor
@Mock private lateinit var mockUserCache: UserCache
@Mock private lateinit var mockUserManagerState: UserManagerState
@Mock private lateinit var mockWidgetInflater: WidgetInflater
private var intent: Intent = Intent()
private var mUserHandle: UserHandle = UserHandle(0)
private var mIconRequestInfos: MutableList<IconRequestInfo<WorkspaceItemInfo>> = mutableListOf()
private var mComponentName: ComponentName = ComponentName("package", "class")
private var mUnlockedUsersArray: LongSparseArray<Boolean> = LongSparseArray()
private var mKeyToPinnedShortcutsMap: MutableMap<ShortcutKey, ShortcutInfo> = mutableMapOf()
private var mInstallingPkgs: HashMap<PackageUserKey, PackageInstaller.SessionInfo> = hashMapOf()
private var mAllDeepShortcuts: MutableList<ShortcutInfo> = mutableListOf()
private var mWidgetProvidersMap: MutableMap<ComponentKey, AppWidgetProviderInfo?> =
mutableMapOf()
private var mPendingPackages: MutableSet<PackageUserKey> = mutableSetOf()
private lateinit var itemProcessorUnderTest: WorkspaceItemProcessor
@Before
fun setup() {
mUserHandle = UserHandle(0)
mockIconRequestInfo = mock<IconRequestInfo<WorkspaceItemInfo>>()
mockWorkspaceInfo = mock<WorkspaceItemInfo>()
mockBgDataModel = mock<BgDataModel>()
mComponentName = ComponentName("package", "class")
mUnlockedUsersArray = LongSparseArray<Boolean>(1).apply { put(101, true) }
intent =
Intent().apply {
component = mComponentName
`package` = "pkg"
putExtra(ShortcutKey.EXTRA_SHORTCUT_ID, "")
}
mockContext =
mock<Context>().apply {
whenever(packageManager).thenReturn(mock())
whenever(packageManager.getUserBadgedLabel(any(), any())).thenReturn("")
whenever(applicationContext).thenReturn(ApplicationProvider.getApplicationContext())
}
mockAppState =
mock<LauncherAppState>().apply {
whenever(context).thenReturn(mockContext)
whenever(iconCache).thenReturn(mock())
whenever(iconCache.getShortcutIcon(any(), any(), any())).then {}
}
mockPmHelper =
mock<PackageManagerHelper>().apply {
whenever(getAppLaunchIntent(mComponentName.packageName, mUserHandle))
.thenReturn(intent)
}
mockLauncherApps =
mock<LauncherApps>().apply {
whenever(isPackageEnabled("package", mUserHandle)).thenReturn(true)
whenever(isActivityEnabled(mComponentName, mUserHandle)).thenReturn(true)
}
mockCursor =
mock(LoaderCursor::class.java, RETURNS_DEEP_STUBS).apply {
user = mUserHandle
itemType = ITEM_TYPE_APPLICATION
id = 1
restoreFlag = 1
serialNumber = 101
whenever(parseIntent()).thenReturn(intent)
whenever(markRestored()).doAnswer { restoreFlag = 0 }
whenever(updater().put(Favorites.INTENT, intent.toUri(0)).commit()).thenReturn(1)
whenever(getAppShortcutInfo(any(), any(), any(), any()))
.thenReturn(mockWorkspaceInfo)
whenever(createIconRequestInfo(any(), any())).thenReturn(mockIconRequestInfo)
}
mockUserCache =
mock<UserCache>().apply {
val userIconInfo =
mock<UserIconInfo>().apply { whenever(isPrivate).thenReturn(false) }
whenever(getUserInfo(any())).thenReturn(userIconInfo)
}
mockUserManagerState = mock<UserManagerState>()
mockWidgetInflater = mock<WidgetInflater>()
mKeyToPinnedShortcutsMap = mutableMapOf()
mInstallingPkgs = hashMapOf()
mAllDeepShortcuts = mutableListOf()
mWidgetProvidersMap = mutableMapOf()
mIconRequestInfos = mutableListOf()
mPendingPackages = mutableSetOf()
}
/**
* Helper to create WorkspaceItemProcessor with defaults. WorkspaceItemProcessor has a lot of
* dependencies, so this method can be used to inject concrete arguments while keeping the rest
* as mocks/defaults, or to recreate it after modifying the default vars.
*/
private fun createWorkspaceItemProcessorUnderTest(
cursor: LoaderCursor = mockCursor,
memoryLogger: LoaderMemoryLogger? = null,
userCache: UserCache = mockUserCache,
userManagerState: UserManagerState = mockUserManagerState,
launcherApps: LauncherApps = mockLauncherApps,
shortcutKeyToPinnedShortcuts: Map<ShortcutKey, ShortcutInfo> = mKeyToPinnedShortcutsMap,
app: LauncherAppState = mockAppState,
bgDataModel: BgDataModel = mockBgDataModel,
widgetProvidersMap: MutableMap<ComponentKey, AppWidgetProviderInfo?> = mWidgetProvidersMap,
widgetInflater: WidgetInflater = mockWidgetInflater,
pmHelper: PackageManagerHelper = mockPmHelper,
iconRequestInfos: MutableList<IconRequestInfo<WorkspaceItemInfo>> = mIconRequestInfos,
isSdCardReady: Boolean = false,
pendingPackages: MutableSet<PackageUserKey> = mPendingPackages,
unlockedUsers: LongSparseArray<Boolean> = mUnlockedUsersArray,
installingPkgs: HashMap<PackageUserKey, PackageInstaller.SessionInfo> = mInstallingPkgs,
allDeepShortcuts: MutableList<ShortcutInfo> = mAllDeepShortcuts
) =
WorkspaceItemProcessor(
c = cursor,
memoryLogger = memoryLogger,
userCache = userCache,
userManagerState = userManagerState,
launcherApps = launcherApps,
app = app,
bgDataModel = bgDataModel,
widgetProvidersMap = widgetProvidersMap,
widgetInflater = widgetInflater,
pmHelper = pmHelper,
unlockedUsers = unlockedUsers,
iconRequestInfos = iconRequestInfos,
pendingPackages = pendingPackages,
isSdCardReady = isSdCardReady,
shortcutKeyToPinnedShortcuts = shortcutKeyToPinnedShortcuts,
installingPkgs = installingPkgs,
allDeepShortcuts = allDeepShortcuts
)
@Test
fun `When user is null then mark item deleted`() {
// Given
mockCursor = mock<LoaderCursor>().apply { id = 1 }
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor).markDeleted("User has been deleted for item id=1", PROFILE_DELETED)
verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When app has null intent then mark deleted`() {
// Given
mockCursor.apply { whenever(parseIntent()).thenReturn(null) }
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor).markDeleted("Null intent from db for item id=1", MISSING_INFO)
verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When app has null target package then mark deleted`() {
// Given
intent.apply {
component = null
`package` = null
}
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor).markDeleted("No target package for item id=1", MISSING_INFO)
verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When app has empty String target package then mark deleted`() {
// Given
mComponentName = ComponentName("", "")
intent.component = mComponentName
intent.`package` = ""
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor).markDeleted("No target package for item id=1", MISSING_INFO)
verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When valid app then mark restored`() {
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be set to 0")
.that(mockCursor.restoreFlag)
.isEqualTo(0)
// currently gets marked restored twice, although markRestore() has check for restoreFlag
verify(mockCursor, times(2)).markRestored()
assertThat(mIconRequestInfos).containsExactly(mockIconRequestInfo)
verify(mockCursor).checkAndAddItem(mockWorkspaceInfo, mockBgDataModel, null)
}
@Test
fun `When fallback Activity found for app then mark restored`() {
// Given
mockLauncherApps =
mock<LauncherApps>().apply {
whenever(isPackageEnabled("package", mUserHandle)).thenReturn(true)
whenever(isActivityEnabled(mComponentName, mUserHandle)).thenReturn(false)
}
mockPmHelper =
mock<PackageManagerHelper>().apply {
whenever(getAppLaunchIntent(mComponentName.packageName, mUserHandle))
.thenReturn(intent)
}
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be set to 0")
.that(mockCursor.restoreFlag)
.isEqualTo(0)
verify(mockCursor.updater().put(Favorites.INTENT, intent.toUri(0))).commit()
assertThat(mIconRequestInfos).containsExactly(mockIconRequestInfo)
verify(mockCursor).checkAndAddItem(mockWorkspaceInfo, mockBgDataModel, null)
}
@Test
fun `When app with disabled activity and no fallback found then mark deleted`() {
// Given
mockLauncherApps =
mock<LauncherApps>().apply {
whenever(isPackageEnabled("package", mUserHandle)).thenReturn(true)
whenever(isActivityEnabled(mComponentName, mUserHandle)).thenReturn(false)
}
mockPmHelper =
mock<PackageManagerHelper>().apply {
whenever(getAppLaunchIntent(mComponentName.packageName, mUserHandle))
.thenReturn(null)
}
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be unchanged")
.that(mockCursor.restoreFlag)
.isEqualTo(1)
verify(mockCursor)
.markDeleted(
"No Activities found for id=1," +
" targetPkg=package," +
" component=ComponentInfo{package/class}." +
" Unable to create launch Intent.",
MISSING_INFO
)
verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When valid Pinned Deep Shortcut then mark restored`() {
// Given
mockCursor.itemType = ITEM_TYPE_DEEP_SHORTCUT
val expectedShortcutInfo =
mock<ShortcutInfo>().apply {
whenever(id).thenReturn("")
whenever(`package`).thenReturn("")
whenever(activity).thenReturn(mock())
whenever(longLabel).thenReturn("")
whenever(isEnabled).thenReturn(true)
whenever(disabledMessage).thenReturn("")
whenever(disabledReason).thenReturn(0)
whenever(persons).thenReturn(EMPTY_PERSON_ARRAY)
}
val shortcutKey = ShortcutKey.fromIntent(intent, mockCursor.user)
mKeyToPinnedShortcutsMap[shortcutKey] = expectedShortcutInfo
mIconRequestInfos = mutableListOf()
// When
itemProcessorUnderTest =
createWorkspaceItemProcessorUnderTest(allDeepShortcuts = mAllDeepShortcuts)
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be set to 0")
.that(mockCursor.restoreFlag)
.isEqualTo(0)
assertThat(mIconRequestInfos).isEmpty()
assertThat(mAllDeepShortcuts).containsExactly(expectedShortcutInfo)
verify(mockCursor).markRestored()
verify(mockCursor).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When Pinned Deep Shortcut not found then mark deleted`() {
// Given
mockCursor.itemType = ITEM_TYPE_DEEP_SHORTCUT
mIconRequestInfos = mutableListOf()
mKeyToPinnedShortcutsMap = hashMapOf()
// When
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be set to 0")
.that(mockCursor.restoreFlag)
.isEqualTo(0)
assertThat(mIconRequestInfos).isEmpty()
verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull())
verify(mockCursor)
.markDeleted(
"Pinned shortcut not found from request. package=pkg, user=UserHandle{0}",
"shortcut_not_found"
)
}
@Test
fun `When valid Pinned Deep Shortcut with null intent package then use targetPkg`() {
// Given
mockCursor.itemType = ITEM_TYPE_DEEP_SHORTCUT
val expectedShortcutInfo =
mock<ShortcutInfo>().apply {
whenever(id).thenReturn("")
whenever(`package`).thenReturn("")
whenever(activity).thenReturn(mock())
whenever(longLabel).thenReturn("")
whenever(isEnabled).thenReturn(true)
whenever(disabledMessage).thenReturn("")
whenever(disabledReason).thenReturn(0)
whenever(persons).thenReturn(EMPTY_PERSON_ARRAY)
whenever(userHandle).thenReturn(Process.myUserHandle())
}
mIconRequestInfos = mutableListOf()
// Make sure shortcuts map has expected key from expected package
intent.`package` = mComponentName.packageName
val shortcutKey = ShortcutKey.fromIntent(intent, mockCursor.user)
mKeyToPinnedShortcutsMap[shortcutKey] = expectedShortcutInfo
// set intent package back to null to test scenario
intent.`package` = null
// When
itemProcessorUnderTest =
createWorkspaceItemProcessorUnderTest(allDeepShortcuts = mAllDeepShortcuts)
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be set to 0")
.that(mockCursor.restoreFlag)
.isEqualTo(0)
assertThat(mIconRequestInfos).isEmpty()
assertThat(mAllDeepShortcuts).containsExactly(expectedShortcutInfo)
verify(mockCursor).markRestored()
verify(mockCursor).checkAndAddItem(any(), any(), anyOrNull())
}
@Test
fun `When processing Folder then create FolderInfo and mark restored`() {
val actualFolderInfo = FolderInfo()
mockBgDataModel =
mock<BgDataModel>().apply { whenever(findOrMakeFolder(1)).thenReturn(actualFolderInfo) }
mockCursor =
mock<LoaderCursor>().apply {
user = UserHandle(0)
itemType = ITEM_TYPE_FOLDER
id = 1
container = 100
restoreFlag = 1
serialNumber = 101
whenever(applyCommonProperties(any<ItemInfo>())).then {}
whenever(markRestored()).doAnswer { restoreFlag = 0 }
whenever(getColumnIndex(Favorites.TITLE)).thenReturn(4)
whenever(getString(4)).thenReturn("title")
whenever(options).thenReturn(5)
}
val expectedFolderInfo =
FolderInfo().apply {
itemType = ITEM_TYPE_FOLDER
spanX = 1
spanY = 1
options = 5
}
itemProcessorUnderTest = createWorkspaceItemProcessorUnderTest()
// When
itemProcessorUnderTest.processItem()
// Then
assertWithMessage("item restoreFlag should be set to 0")
.that(mockCursor.restoreFlag)
.isEqualTo(0)
verify(mockCursor).markRestored()
assertThat(actualFolderInfo.id).isEqualTo(expectedFolderInfo.id)
assertThat(actualFolderInfo.container).isEqualTo(expectedFolderInfo.container)
assertThat(actualFolderInfo.itemType).isEqualTo(expectedFolderInfo.itemType)
assertThat(actualFolderInfo.screenId).isEqualTo(expectedFolderInfo.screenId)
assertThat(actualFolderInfo.cellX).isEqualTo(expectedFolderInfo.cellX)
assertThat(actualFolderInfo.cellY).isEqualTo(expectedFolderInfo.cellY)
assertThat(actualFolderInfo.spanX).isEqualTo(expectedFolderInfo.spanX)
assertThat(actualFolderInfo.spanY).isEqualTo(expectedFolderInfo.spanY)
assertThat(actualFolderInfo.options).isEqualTo(expectedFolderInfo.options)
verify(mockCursor).checkAndAddItem(actualFolderInfo, mockBgDataModel, null)
}
@Test
fun `When valid TYPE_REAL App Widget then add item`() {
// Given
val expectedProvider = "com.google.android.testApp/com.android.testApp.testAppProvider"
val expectedComponentName =
ComponentName.unflattenFromString(expectedProvider)!!.flattenToString()
val expectedRestoreStatus = FLAG_UI_NOT_READY
val expectedAppWidgetId = 0
mockCursor.apply {
itemType = ITEM_TYPE_APPWIDGET
user = mUserHandle
restoreFlag = FLAG_UI_NOT_READY
container = CONTAINER_DESKTOP
whenever(isOnWorkspaceOrHotseat).thenCallRealMethod()
whenever(appWidgetProvider).thenReturn(expectedProvider)
whenever(appWidgetId).thenReturn(expectedAppWidgetId)
whenever(spanX).thenReturn(2)
whenever(spanY).thenReturn(1)
whenever(options).thenReturn(0)
whenever(appWidgetSource).thenReturn(20)
whenever(applyCommonProperties(any())).thenCallRealMethod()
whenever(
updater()
.put(Favorites.APPWIDGET_PROVIDER, expectedComponentName)
.put(Favorites.APPWIDGET_ID, expectedAppWidgetId)
.put(Favorites.RESTORED, expectedRestoreStatus)
.commit()
)
.thenReturn(1)
}
val expectedWidgetInfo =
LauncherAppWidgetInfo().apply {
appWidgetId = expectedAppWidgetId
providerName = ComponentName.unflattenFromString(expectedProvider)
restoreStatus = expectedRestoreStatus
}
val expectedWidgetProviderInfo =
mock<LauncherAppWidgetProviderInfo>().apply {
provider = ComponentName.unflattenFromString(expectedProvider)
whenever(user).thenReturn(mUserHandle)
}
val inflationResult =
WidgetInflater.InflationResult(
type = WidgetInflater.TYPE_REAL,
widgetInfo = expectedWidgetProviderInfo
)
mockWidgetInflater =
mock<WidgetInflater>().apply {
whenever(inflateAppWidget(any())).thenReturn(inflationResult)
}
val packageUserKey = PackageUserKey("com.google.android.testApp", mUserHandle)
mInstallingPkgs[packageUserKey] = PackageInstaller.SessionInfo()
// When
itemProcessorUnderTest =
createWorkspaceItemProcessorUnderTest(widgetProvidersMap = mWidgetProvidersMap)
itemProcessorUnderTest.processItem()
// Then
val widgetInfoCaptor = ArgumentCaptor.forClass(LauncherAppWidgetInfo::class.java)
verify(mockCursor).checkAndAddItem(widgetInfoCaptor.capture(), eq(mockBgDataModel))
val actualWidgetInfo = widgetInfoCaptor.value
with(actualWidgetInfo) {
assertThat(providerName).isEqualTo(expectedWidgetInfo.providerName)
assertThat(restoreStatus).isEqualTo(expectedWidgetInfo.restoreStatus)
assertThat(targetComponent).isEqualTo(expectedWidgetInfo.targetComponent)
assertThat(appWidgetId).isEqualTo(expectedWidgetInfo.appWidgetId)
}
val expectedComponentKey =
ComponentKey(expectedWidgetProviderInfo.provider, expectedWidgetProviderInfo.user)
assertThat(mWidgetProvidersMap[expectedComponentKey]).isEqualTo(expectedWidgetProviderInfo)
}
@Test
fun `When valid Pending Widget then checkAndAddItem`() {
// Given
mockCursor =
mock<LoaderCursor>().apply {
itemType = ITEM_TYPE_APPWIDGET
id = 1
user = UserHandle(1)
restoreFlag = FLAG_UI_NOT_READY
container = CONTAINER_DESKTOP
whenever(isOnWorkspaceOrHotseat).thenCallRealMethod()
whenever(appWidgetProvider)
.thenReturn("com.google.android.testApp/com.android.testApp.testAppProvider")
whenever(appWidgetId).thenReturn(0)
whenever(spanX).thenReturn(2)
whenever(spanY).thenReturn(1)
whenever(options).thenReturn(0)
whenever(appWidgetSource).thenReturn(20)
whenever(applyCommonProperties(any())).thenCallRealMethod()
}
val mockProviderInfo =
mock<LauncherAppWidgetProviderInfo>().apply {
provider = mock()
whenever(user).thenReturn(UserHandle(1))
}
val inflationResult =
WidgetInflater.InflationResult(
type = WidgetInflater.TYPE_PENDING,
widgetInfo = mockProviderInfo
)
mockWidgetInflater =
mock<WidgetInflater>().apply {
whenever(inflateAppWidget(any())).thenReturn(inflationResult)
}
itemProcessorUnderTest =
createWorkspaceItemProcessorUnderTest(widgetProvidersMap = mWidgetProvidersMap)
// When
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor).checkAndAddItem(any(), any())
}
@Test
fun `When Unrestored Pending App Widget then mark deleted`() {
// Given
val expectedProvider = "com.google.android.testApp/com.android.testApp.testAppProvider"
mockCursor =
mock<LoaderCursor>().apply {
itemType = ITEM_TYPE_APPWIDGET
id = 1
user = UserHandle(1)
restoreFlag = FLAG_UI_NOT_READY
container = CONTAINER_DESKTOP
whenever(isOnWorkspaceOrHotseat).thenCallRealMethod()
whenever(appWidgetProvider).thenReturn(expectedProvider)
whenever(appWidgetId).thenReturn(0)
whenever(spanX).thenReturn(2)
whenever(spanY).thenReturn(1)
whenever(options).thenReturn(0)
whenever(appWidgetSource).thenReturn(20)
whenever(applyCommonProperties(any())).thenCallRealMethod()
}
mInstallingPkgs = hashMapOf()
val inflationResult =
WidgetInflater.InflationResult(type = WidgetInflater.TYPE_PENDING, widgetInfo = null)
mockWidgetInflater =
mock<WidgetInflater>().apply {
whenever(inflateAppWidget(any())).thenReturn(inflationResult)
}
val expectedComponentName = ComponentName.unflattenFromString(expectedProvider)
// When
itemProcessorUnderTest =
createWorkspaceItemProcessorUnderTest(widgetProvidersMap = mWidgetProvidersMap)
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor)
.markDeleted(
"processWidget: Unrestored Pending widget removed: id=1, appWidgetId=0, component=$expectedComponentName, restoreFlag:=4",
LauncherRestoreEventLogger.RestoreError.APP_NOT_INSTALLED
)
}
@Test
fun `When widget inflation result is TYPE_DELETE then mark deleted`() {
// Given
val expectedProvider = "com.google.android.testApp/com.android.testApp.testAppProvider"
val expectedComponentName = ComponentName.unflattenFromString(expectedProvider)
val expectedPackage = expectedComponentName!!.packageName
mockPmHelper =
mock<PackageManagerHelper>().apply {
whenever(isAppArchived(expectedPackage)).thenReturn(true)
}
mockCursor =
mock<LoaderCursor>().apply {
itemType = ITEM_TYPE_APPWIDGET
id = 1
user = UserHandle(1)
container = CONTAINER_DESKTOP
whenever(spanX).thenReturn(2)
whenever(spanY).thenReturn(1)
whenever(appWidgetProvider).thenReturn(expectedProvider)
whenever(isOnWorkspaceOrHotseat).thenCallRealMethod()
whenever(applyCommonProperties(any())).thenCallRealMethod()
}
mInstallingPkgs = hashMapOf()
val inflationResult =
WidgetInflater.InflationResult(
type = WidgetInflater.TYPE_DELETE,
widgetInfo = null,
reason = "test_delete_reason",
restoreErrorType = MISSING_WIDGET_PROVIDER
)
mockWidgetInflater =
mock<WidgetInflater>().apply {
whenever(inflateAppWidget(any())).thenReturn(inflationResult)
}
itemProcessorUnderTest =
createWorkspaceItemProcessorUnderTest(widgetProvidersMap = mWidgetProvidersMap)
// When
itemProcessorUnderTest.processItem()
// Then
verify(mockCursor).markDeleted(inflationResult.reason, inflationResult.restoreErrorType)
}
}
@@ -0,0 +1,182 @@
/*
* Copyright (C) 2022 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.launcher3.model
import android.graphics.Rect
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/** Tests for [WorkspaceItemSpaceFinder] */
@SmallTest
@RunWith(AndroidJUnit4::class)
class WorkspaceItemSpaceFinderTest : AbstractWorkspaceModelTest() {
@get:Rule val modelTestRule = ModelTestRule()
private val mItemSpaceFinder = WorkspaceItemSpaceFinder()
@Before
override fun setup() {
super.setup()
}
@After
override fun tearDown() {
super.tearDown()
}
private fun findSpace(spanX: Int, spanY: Int): NewItemSpace =
mItemSpaceFinder
.findSpaceForItem(
mAppState,
mModelHelper.bgDataModel,
mExistingScreens,
mNewScreens,
spanX,
spanY
)
.let { NewItemSpace.fromIntArray(it) }
private fun assertRegionVacant(newItemSpace: NewItemSpace, spanX: Int, spanY: Int) {
assertThat(
mScreenOccupancy[newItemSpace.screenId].isRegionVacant(
newItemSpace.cellX,
newItemSpace.cellY,
spanX,
spanY
)
)
.isTrue()
}
@Test
fun justEnoughSpaceOnFirstScreen_whenFindSpaceForItem_thenReturnFirstScreenId() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
screen1 = listOf(Rect(2, 2, 3, 3)), // 1x1 space
// 2 spaces of sizes 3x2 and 2x3
screen2 = listOf(Rect(2, 0, 5, 2), Rect(0, 2, 2, 5)),
)
val spaceFound = findSpace(1, 1)
assertThat(spaceFound.screenId).isEqualTo(1)
assertRegionVacant(spaceFound, 1, 1)
}
@Test
fun notEnoughSpaceOnFirstScreen_whenFindSpaceForItem_thenReturnSecondScreenId() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
screen1 = listOf(Rect(2, 2, 3, 3)), // 1x1 space
// 2 spaces of sizes 3x2 and 2x3
screen2 = listOf(Rect(2, 0, 5, 2), Rect(0, 2, 2, 5)),
)
// Find a larger space
val spaceFound = findSpace(2, 3)
assertThat(spaceFound.screenId).isEqualTo(2)
assertRegionVacant(spaceFound, 2, 3)
}
@Test
fun notEnoughSpaceOnExistingScreens_returnNewScreenId() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
// 2 spaces of sizes 3x2 and 2x3
screen1 = listOf(Rect(2, 0, 5, 2), Rect(0, 2, 2, 5)),
// 2 spaces of sizes 1x2 and 2x2
screen2 = listOf(Rect(1, 0, 2, 2), Rect(3, 2, 5, 4)),
)
val oldScreens = mExistingScreens.clone()
val spaceFound = findSpace(3, 3)
assertThat(oldScreens.contains(spaceFound.screenId)).isFalse()
assertThat(mNewScreens.contains(spaceFound.screenId)).isTrue()
}
@Test
fun firstScreenIsEmptyButSecondIsNotEmpty_returnSecondScreenId() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
// empty screens are skipped
screen2 = listOf(Rect(2, 0, 5, 2)), // 3x2 space
)
val spaceFound = findSpace(2, 1)
assertThat(spaceFound.screenId).isEqualTo(2)
assertRegionVacant(spaceFound, 2, 1)
}
@Test
fun twoEmptyMiddleScreens_returnThirdScreen() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
// empty screens are skipped
screen3 = listOf(Rect(1, 1, 4, 4)), // 3x3 space
)
val spaceFound = findSpace(2, 3)
assertThat(spaceFound.screenId).isEqualTo(3)
assertRegionVacant(spaceFound, 2, 3)
}
@Test
fun allExistingPagesAreFull_returnNewScreenId() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
screen1 = fullScreenSpaces,
screen2 = fullScreenSpaces,
)
val spaceFound = findSpace(2, 3)
assertThat(spaceFound.screenId).isEqualTo(3)
assertThat(mNewScreens.contains(spaceFound.screenId)).isTrue()
}
@Test
fun firstTwoPagesAreFull_and_ThirdPageIsEmpty_returnThirdPage() {
setupWorkspacesWithSpaces(
// 3x2 space on screen 0, but it should be skipped
screen0 = listOf(Rect(2, 0, 5, 2)),
screen1 = fullScreenSpaces, // full screens are skipped
screen2 = fullScreenSpaces, // full screens are skipped
screen3 = emptyScreenSpaces
)
val spaceFound = findSpace(3, 1)
assertThat(spaceFound.screenId).isEqualTo(3)
assertRegionVacant(spaceFound, 3, 1)
}
}
@@ -1,266 +0,0 @@
/*
* Copyright (C) 2024 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.launcher3.pm
import android.content.pm.ApplicationInfo
import android.content.pm.ApplicationInfo.FLAG_INSTALLED
import android.content.pm.LauncherApps
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.UserHandle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.LauncherPrefs
import com.android.launcher3.LauncherPrefs.Companion.PROMISE_ICON_IDS
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.util.IntArray
import com.android.launcher3.util.LauncherModelHelper
import com.android.launcher3.util.TestUtil
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.whenever
@SmallTest
@RunWith(AndroidJUnit4::class)
class InstallSessionHelperTest {
private val launcherModelHelper = LauncherModelHelper()
private val sandboxContext = spy(launcherModelHelper.sandboxContext)
private val packageManager = sandboxContext.packageManager
private val expectedAppPackage = "expectedAppPackage"
private val expectedInstallerPackage = "expectedInstallerPackage"
private val mockPackageInstaller: PackageInstaller = mock()
private lateinit var installSessionHelper: InstallSessionHelper
private lateinit var launcherApps: LauncherApps
@Before
fun setup() {
whenever(packageManager.packageInstaller).thenReturn(mockPackageInstaller)
whenever(sandboxContext.packageName).thenReturn(expectedInstallerPackage)
launcherApps = sandboxContext.spyService(LauncherApps::class.java)
installSessionHelper = InstallSessionHelper(sandboxContext)
}
@Test
fun `getActiveSessions fetches verified install sessions from LauncherApps`() {
// Given
val expectedVerifiedSession1 =
PackageInstaller.SessionInfo().apply {
sessionId = 0
installerPackageName = expectedInstallerPackage
appPackageName = expectedAppPackage
userId = 0
}
val expectedVerifiedSession2 =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = "app2"
userId = 0
}
val expectedSessions = listOf(expectedVerifiedSession1, expectedVerifiedSession2)
whenever(launcherApps.allPackageInstallerSessions).thenReturn(expectedSessions)
// When
val actualSessions = installSessionHelper.getActiveSessions()
// Then
assertThat(actualSessions.values.toList()).isEqualTo(expectedSessions)
}
@Test
fun `getActiveSessionInfo fetches verified install sessions for given user and pkg`() {
// Given
val expectedVerifiedSession =
PackageInstaller.SessionInfo().apply {
installerPackageName = expectedInstallerPackage
appPackageName = expectedAppPackage
userId = 0
}
whenever(launcherApps.allPackageInstallerSessions)
.thenReturn(listOf(expectedVerifiedSession))
// When
val actualSession =
installSessionHelper.getActiveSessionInfo(UserHandle(0), expectedAppPackage)
// Then
assertThat(actualSession).isEqualTo(expectedVerifiedSession)
}
@Test
fun `getVerifiedSessionInfo verifies and returns session for given id`() {
// Given
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = expectedAppPackage
userId = 0
}
whenever(mockPackageInstaller.getSessionInfo(1)).thenReturn(expectedSession)
// When
val actualSession = installSessionHelper.getVerifiedSessionInfo(1)
// Then
assertThat(actualSession).isEqualTo(expectedSession)
}
@Test
fun `isTrustedPackage returns true if LauncherApps finds ApplicationInfo`() {
// Given
val expectedApplicationInfo =
ApplicationInfo().apply {
flags = flags or FLAG_INSTALLED
enabled = true
}
doReturn(expectedApplicationInfo)
.whenever(launcherApps)
.getApplicationInfo(expectedAppPackage, ApplicationInfo.FLAG_SYSTEM, UserHandle(0))
// When
val actualResult = installSessionHelper.isTrustedPackage(expectedAppPackage, UserHandle(0))
// Then
assertThat(actualResult).isTrue()
}
@Test
fun `getAllVerifiedSessions verifies and returns all active install sessions`() {
// Given
val expectedVerifiedSession1 =
PackageInstaller.SessionInfo().apply {
sessionId = 0
installerPackageName = expectedInstallerPackage
appPackageName = expectedAppPackage
userId = 0
}
val expectedVerifiedSession2 =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = "app2"
userId = 0
}
val expectedSessions = listOf(expectedVerifiedSession1, expectedVerifiedSession2)
whenever(launcherApps.allPackageInstallerSessions).thenReturn(expectedSessions)
// When
val actualSessions = installSessionHelper.allVerifiedSessions
// Then
assertThat(actualSessions).isEqualTo(expectedSessions)
}
@Test
fun `promiseIconAddedForId returns true if there is a promiseIcon with the session id`() {
// Given
val expectedIdString = IntArray().apply { add(1) }.toConcatString()
LauncherPrefs.get(sandboxContext).putSync(Pair(PROMISE_ICON_IDS, expectedIdString))
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = "app2"
userId = 0
}
whenever(launcherApps.allPackageInstallerSessions).thenReturn(listOf(expectedSession))
// When
var actualResult = false
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
actualResult = installSessionHelper.promiseIconAddedForId(1)
}
// Then
assertThat(actualResult).isTrue()
}
@Test
fun `removePromiseIconId removes promiseIconId for given Session id`() {
// Given
val expectedIdString = IntArray().apply { add(1) }.toConcatString()
LauncherPrefs.get(sandboxContext).putSync(Pair(PROMISE_ICON_IDS, expectedIdString))
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = "app2"
userId = 0
}
whenever(launcherApps.allPackageInstallerSessions).thenReturn(listOf(expectedSession))
// When
var actualResult = true
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
installSessionHelper.removePromiseIconId(1)
actualResult = installSessionHelper.promiseIconAddedForId(1)
}
// Then
assertThat(actualResult).isFalse()
}
@Test
fun `tryQueuePromiseAppIcon will update promise icon ids from eligible sessions`() {
// Given
val expectedIdString = IntArray().apply { add(1) }.toConcatString()
LauncherPrefs.get(sandboxContext).putSync(Pair(PROMISE_ICON_IDS, expectedIdString))
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = "appPackage"
userId = 0
appIcon = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
appLabel = "appLabel"
installReason = PackageManager.INSTALL_REASON_USER
}
whenever(launcherApps.allPackageInstallerSessions).thenReturn(listOf(expectedSession))
// When
var wasPromiseIconAdded = false
var actualPromiseIconIds = ""
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
installSessionHelper.removePromiseIconId(1)
installSessionHelper.tryQueuePromiseAppIcon(expectedSession)
wasPromiseIconAdded = installSessionHelper.promiseIconAddedForId(1)
actualPromiseIconIds = LauncherPrefs.get(sandboxContext).get(PROMISE_ICON_IDS)
}
// Then
assertThat(wasPromiseIconAdded).isTrue()
assertThat(actualPromiseIconIds).isEqualTo(expectedIdString)
}
@Test
fun `verifySessionInfo is true if can verify given SessionInfo`() {
// Given
val expectedIdString = IntArray().apply { add(1) }.toConcatString()
LauncherPrefs.get(sandboxContext).putSync(Pair(PROMISE_ICON_IDS, expectedIdString))
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = 1
installerPackageName = expectedInstallerPackage
appPackageName = "appPackage"
userId = 0
appIcon = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
appLabel = "appLabel"
installReason = PackageManager.INSTALL_REASON_USER
}
whenever(launcherApps.allPackageInstallerSessions).thenReturn(listOf(expectedSession))
// When
var actualResult = false
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
actualResult = installSessionHelper.verifySessionInfo(expectedSession)
}
// Then
assertThat(actualResult).isTrue()
}
}
@@ -0,0 +1,229 @@
/*
* Copyright (C) 2024 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.launcher3.pm
import android.content.pm.LauncherApps
import android.content.pm.PackageInstaller
import android.os.Build
import android.os.UserHandle
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import com.android.launcher3.Flags.FLAG_ENABLE_SUPPORT_FOR_ARCHIVING
import com.android.launcher3.model.ModelTestRule
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.util.LauncherModelHelper
import com.android.launcher3.util.PackageUserKey
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.doNothing
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@SmallTest
@RunWith(AndroidJUnit4::class)
class InstallSessionTrackerTest {
@get:Rule(order = 0) val setFlagsRule = SetFlagsRule()
@get:Rule(order = 1) val modelTestRule = ModelTestRule()
private val mockInstallSessionHelper: InstallSessionHelper = mock()
private val mockCallback: InstallSessionTracker.Callback = mock()
private val mockPackageInstaller: PackageInstaller = mock()
private val launcherModelHelper = LauncherModelHelper()
private val sandboxContext = launcherModelHelper.sandboxContext
lateinit var launcherApps: LauncherApps
lateinit var installSessionTracker: InstallSessionTracker
@Before
fun setup() {
launcherApps = sandboxContext.spyService(LauncherApps::class.java)
installSessionTracker =
InstallSessionTracker(
mockInstallSessionHelper,
mockCallback,
mockPackageInstaller,
launcherApps
)
}
@After
fun teardown() {
launcherModelHelper.destroy()
}
@Test
fun `onCreated triggers callbacks for setting up new install session`() {
// Given
val expectedSessionId = 1
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = expectedSessionId
appPackageName = "appPackageName"
userId = 0
}
val expectedPackageKey = PackageUserKey("appPackageName", UserHandle(0))
whenever(mockInstallSessionHelper.getVerifiedSessionInfo(expectedSessionId))
.thenReturn(expectedSession)
// When
installSessionTracker.onCreated(expectedSessionId)
// Then
verify(mockCallback).onInstallSessionCreated(any())
verify(mockCallback).onUpdateSessionDisplay(expectedPackageKey, expectedSession)
verify(mockInstallSessionHelper).tryQueuePromiseAppIcon(expectedSession)
}
@Test
@EnableFlags(FLAG_ENABLE_SUPPORT_FOR_ARCHIVING)
fun `onCreated for unarchival triggers onPackageStateChanged`() {
// Given
val expectedSessionId = 1
val expectedSession =
spy(PackageInstaller.SessionInfo()).apply {
sessionId = expectedSessionId
appPackageName = "appPackageName"
userId = 0
whenever(isUnarchival).thenReturn(true)
}
whenever(mockInstallSessionHelper.getVerifiedSessionInfo(expectedSessionId))
.thenReturn(expectedSession)
// When
installSessionTracker.onCreated(expectedSessionId)
// Then
verify(mockCallback).onPackageStateChanged(any())
}
@Test
fun `onFinished triggers onPackageStateChanged if session found in cache`() {
// Given
val expectedSessionId = 1
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = expectedSessionId
appPackageName = "appPackageName"
userId = 0
}
val expectedPackageKey = PackageUserKey("appPackageName", UserHandle(0))
whenever(mockInstallSessionHelper.getVerifiedSessionInfo(expectedSessionId))
.thenReturn(expectedSession)
whenever(mockInstallSessionHelper.activeSessions)
.thenReturn(hashMapOf(expectedPackageKey to expectedSession))
// When
installSessionTracker.onFinished(expectedSessionId, /* success */ true)
// Then
verify(mockCallback).onPackageStateChanged(any())
}
@Test
fun `onFinished failure calls onSessionFailure and promise icon removal for existing icon`() {
// Given
val expectedSessionId = 1
val expectedPackage = "appPackageName"
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = expectedSessionId
appPackageName = expectedPackage
userId = 0
}
val expectedPackageKey = PackageUserKey(expectedPackage, UserHandle(0))
whenever(mockInstallSessionHelper.getVerifiedSessionInfo(expectedSessionId))
.thenReturn(expectedSession)
whenever(mockInstallSessionHelper.activeSessions)
.thenReturn(hashMapOf(expectedPackageKey to expectedSession))
whenever(mockInstallSessionHelper.promiseIconAddedForId(expectedSessionId)).thenReturn(true)
// When
installSessionTracker.onFinished(expectedSessionId, /* success */ false)
// Then
verify(mockCallback).onSessionFailure(expectedPackage, expectedPackageKey.mUser)
verify(mockInstallSessionHelper).removePromiseIconId(expectedSessionId)
}
@Test
fun `onProgressChanged triggers onPackageStateChanged if verified session found`() {
// Given
val expectedSessionId = 1
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = expectedSessionId
appPackageName = "appPackageName"
userId = 0
}
whenever(mockInstallSessionHelper.getVerifiedSessionInfo(expectedSessionId))
.thenReturn(expectedSession)
// When
installSessionTracker.onProgressChanged(expectedSessionId, /* progress */ 50f)
// Then
verify(mockCallback).onPackageStateChanged(any())
}
@Test
fun `onBadgingChanged triggers session display update and queues promise icon if verified`() {
// Given
val expectedSessionId = 1
val expectedSession =
PackageInstaller.SessionInfo().apply {
sessionId = expectedSessionId
appPackageName = "appPackageName"
userId = 0
}
val expectedPackageKey = PackageUserKey("appPackageName", UserHandle(0))
whenever(mockInstallSessionHelper.getVerifiedSessionInfo(expectedSessionId))
.thenReturn(expectedSession)
// When
installSessionTracker.onBadgingChanged(expectedSessionId)
// Then
verify(mockCallback).onUpdateSessionDisplay(expectedPackageKey, expectedSession)
verify(mockInstallSessionHelper).tryQueuePromiseAppIcon(expectedSession)
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.Q)
fun `register triggers registerPackageInstallerSessionCallback for versions from Q`() {
// Given
doNothing()
.whenever(launcherApps)
.registerPackageInstallerSessionCallback(MODEL_EXECUTOR, installSessionTracker)
// When
installSessionTracker.register()
// Then
verify(launcherApps)
.registerPackageInstallerSessionCallback(MODEL_EXECUTOR, installSessionTracker)
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.Q)
fun `unregister triggers unregisterPackageInstallerSessionCallback for versions from Q`() {
// Given
doNothing()
.whenever(launcherApps)
.unregisterPackageInstallerSessionCallback(installSessionTracker)
// When
installSessionTracker.unregister()
// Then
verify(launcherApps).unregisterPackageInstallerSessionCallback(installSessionTracker)
}
}
@@ -0,0 +1,145 @@
/*
* Copyright (C) 2024 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.launcher3.pm
import android.os.Process.myUserHandle
import android.os.UserHandle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.android.launcher3.model.ModelTestRule
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.util.LauncherModelHelper
import com.android.launcher3.util.TestUtil
import com.android.launcher3.util.UserIconInfo
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class UserCacheTest {
@get:Rule val modelTestRule = ModelTestRule()
private val launcherModelHelper = LauncherModelHelper()
private val sandboxContext = launcherModelHelper.sandboxContext
private lateinit var userCache: UserCache
@Before
fun setup() {
userCache = UserCache.getInstance(sandboxContext)
}
@After
fun teardown() {
launcherModelHelper.destroy()
}
@Test
fun `getBadgeDrawable only returns a UserBadgeDrawable given a user in the cache`() {
// Given
val expectedIconInfo = UserIconInfo(myUserHandle(), UserIconInfo.TYPE_WORK)
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
userCache.putToCache(myUserHandle(), expectedIconInfo)
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// When
val actualDrawable = UserCache.getBadgeDrawable(sandboxContext, myUserHandle())
val unexpectedDrawable = UserCache.getBadgeDrawable(sandboxContext, UserHandle(66))
// Then
assertThat(actualDrawable).isNotNull()
assertThat(unexpectedDrawable).isNull()
}
@Test
fun `getPreInstallApps returns list of pre installed apps given a user`() {
// Given
val expectedApps = listOf("Google")
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
userCache.putToPreInstallCache(myUserHandle(), expectedApps)
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// When
val actualApps = userCache.getPreInstallApps(myUserHandle())
// Then
assertThat(actualApps).isEqualTo(expectedApps)
}
@Test
fun `getUserProfiles returns copy of UserCache profiles`() {
// Given
val expectedProfiles = listOf(myUserHandle())
val expectedIconInfo = UserIconInfo(myUserHandle(), UserIconInfo.TYPE_MAIN)
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
userCache.putToCache(myUserHandle(), expectedIconInfo)
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// When
val actualProfiles = userCache.userProfiles
// Then
assertThat(actualProfiles).isEqualTo(expectedProfiles)
}
@Test
fun `getUserForSerialNumber returns user key matching given entry serial number`() {
// Given
val expectedSerial = 42L
val expectedProfile = UserHandle(42)
val expectedIconInfo = UserIconInfo(myUserHandle(), UserIconInfo.TYPE_MAIN, expectedSerial)
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
userCache.putToCache(expectedProfile, expectedIconInfo)
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// When
val actualProfile = userCache.getUserForSerialNumber(expectedSerial)
// Then
assertThat(actualProfile).isEqualTo(expectedProfile)
}
@Test
fun `getUserInfo returns cached UserIconInfo given user key`() {
// Given
val expectedProfile = UserHandle(1)
val expectedIconInfo = UserIconInfo(myUserHandle(), UserIconInfo.TYPE_WORK)
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
userCache.putToCache(expectedProfile, expectedIconInfo)
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// When
val actualIconInfo = userCache.getUserInfo(expectedProfile)
// Then
assertThat(actualIconInfo).isEqualTo(expectedIconInfo)
}
@Test
fun `getSerialNumberForUser returns cached UserIconInfo serial number given user key`() {
// Given
val expectedSerial = 42L
val expectedProfile = UserHandle(1)
val expectedIconInfo = UserIconInfo(myUserHandle(), UserIconInfo.TYPE_WORK, expectedSerial)
TestUtil.runOnExecutorSync(MODEL_EXECUTOR) {
userCache.putToCache(expectedProfile, expectedIconInfo)
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync()
// When
val actualSerial = userCache.getSerialNumberForUser(expectedProfile)
// Then
assertThat(actualSerial).isEqualTo(expectedSerial)
}
}
@@ -26,6 +26,7 @@ import static com.android.launcher3.BubbleTextView.DISPLAY_ALL_APPS;
import static com.android.launcher3.BubbleTextView.DISPLAY_PREDICTION_ROW;
import static com.android.launcher3.BubbleTextView.DISPLAY_SEARCH_RESULT;
import static com.android.launcher3.BubbleTextView.DISPLAY_SEARCH_RESULT_SMALL;
import static com.android.launcher3.Flags.FLAG_ENABLE_SUPPORT_FOR_ARCHIVING;
import static com.android.launcher3.Flags.FLAG_USE_NEW_ICON_FOR_ARCHIVED_APPS;
import static com.android.launcher3.LauncherPrefs.ENABLE_TWOLINE_ALLAPPS_TOGGLE;
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_ARCHIVED;
@@ -416,7 +417,7 @@ public class BubbleTextViewTest {
assertThat(mBubbleTextView.getIcon().hasBadge()).isEqualTo(false);
}
@EnableFlags(FLAG_USE_NEW_ICON_FOR_ARCHIVED_APPS)
@EnableFlags({FLAG_ENABLE_SUPPORT_FOR_ARCHIVING, FLAG_USE_NEW_ICON_FOR_ARCHIVED_APPS})
@Test
public void applyIconAndLabel_setsImageSpan_whenInactiveArchivedApp() {
// Given
@@ -452,7 +453,7 @@ public class BubbleTextViewTest {
assertThat(actualSpan.getVerticalAlignment()).isEqualTo(ALIGN_CENTER);
}
@EnableFlags(FLAG_USE_NEW_ICON_FOR_ARCHIVED_APPS)
@EnableFlags({FLAG_ENABLE_SUPPORT_FOR_ARCHIVING, FLAG_USE_NEW_ICON_FOR_ARCHIVED_APPS})
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
@Test
public void applyIconAndLabel_setsBoldDrawable_whenBoldedTextForArchivedApp() {
@@ -45,21 +45,24 @@ import android.test.mock.MockContentResolver;
import android.util.ArrayMap;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.uiautomator.UiDevice;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.ModelDbController;
import com.android.launcher3.testing.TestInformationProvider;
import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
@@ -85,6 +88,23 @@ public class LauncherModelHelper {
public static final String TEST_ACTIVITY13 = "com.android.launcher3.tests.Activity14";
public static final String TEST_ACTIVITY14 = "com.android.launcher3.tests.Activity15";
public static final List<String> ACTIVITY_LIST = Arrays.asList(
TEST_ACTIVITY,
TEST_ACTIVITY2,
TEST_ACTIVITY3,
TEST_ACTIVITY4,
TEST_ACTIVITY5,
TEST_ACTIVITY6,
TEST_ACTIVITY7,
TEST_ACTIVITY8,
TEST_ACTIVITY9,
TEST_ACTIVITY10,
TEST_ACTIVITY11,
TEST_ACTIVITY12,
TEST_ACTIVITY13,
TEST_ACTIVITY14
);
// Authority for providing a test default-workspace-layout data.
private static final String TEST_PROVIDER_AUTHORITY =
LauncherModelHelper.class.getName().toLowerCase();
@@ -128,7 +148,9 @@ public class LauncherModelHelper {
icon.eraseColor(Color.RED);
sp.setAppIcon(icon);
sp.setAppLabel(pkg);
PackageInstaller pi = sandboxContext.getPackageManager().getPackageInstaller();
sp.setInstallerPackageName(ApplicationProvider.getApplicationContext().getPackageName());
PackageInstaller pi = ApplicationProvider.getApplicationContext().getPackageManager()
.getPackageInstaller();
int sessionId = pi.createSession(sp);
mDestroyTask.add(() -> pi.abandonSession(sessionId));
return sessionId;
@@ -164,11 +186,19 @@ public class LauncherModelHelper {
public LauncherModelHelper setupDefaultLayoutProvider(LauncherLayoutBuilder builder)
throws Exception {
InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(sandboxContext);
idp.numRows = idp.numColumns = idp.numDatabaseHotseatIcons = DEFAULT_GRID_SIZE;
idp.iconBitmapSize = DEFAULT_BITMAP_SIZE;
if (idp.numRows == 0 && idp.numColumns == 0) {
idp.numRows = idp.numColumns = idp.numDatabaseHotseatIcons = DEFAULT_GRID_SIZE;
}
if (idp.iconBitmapSize == 0) {
idp.iconBitmapSize = DEFAULT_BITMAP_SIZE;
}
UiDevice.getInstance(getInstrumentation()).executeShellCommand(
"settings put secure launcher3.layout.provider " + TEST_PROVIDER_AUTHORITY);
Settings.Secure.putString(sandboxContext.getContentResolver(), "launcher3.layout.provider",
TEST_PROVIDER_AUTHORITY);
// TODO: use a wrapper class to differentiate the behavior
ByteArrayOutputStream bos = new ByteArrayOutputStream();
builder.build(new OutputStreamWriter(bos));
ContentProvider cp = new TestInformationProvider() {
@Override
@@ -177,8 +207,6 @@ public class LauncherModelHelper {
try {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
AutoCloseOutputStream outputStream = new AutoCloseOutputStream(pipe[1]);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
builder.build(new OutputStreamWriter(bos));
outputStream.write(bos.toByteArray());
outputStream.flush();
outputStream.close();
@@ -189,9 +217,13 @@ public class LauncherModelHelper {
}
};
setupProvider(TEST_PROVIDER_AUTHORITY, cp);
RoboApiWrapper.INSTANCE.registerInputStream(sandboxContext.getContentResolver(),
ModelDbController.getLayoutUri(TEST_PROVIDER_AUTHORITY, sandboxContext),
()-> new ByteArrayInputStream(bos.toByteArray()));
mDestroyTask.add(() -> runOnExecutorSync(MODEL_EXECUTOR, () ->
UiDevice.getInstance(getInstrumentation()).executeShellCommand(
"settings delete secure launcher3.layout.provider")));
Settings.Secure.putString(sandboxContext.getContentResolver(),
"launcher3.layout.provider", "")));
return this;
}
@@ -203,7 +235,7 @@ public class LauncherModelHelper {
MAIN_EXECUTOR.submit(() -> getModel().addCallbacksAndLoad(mockCb)).get();
Executors.MODEL_EXECUTOR.submit(() -> { }).get();
MAIN_EXECUTOR.submit(() -> { }).get();
getInstrumentation().waitForIdleSync();
MAIN_EXECUTOR.submit(() -> getModel().removeCallbacks(mockCb)).get();
}
@@ -0,0 +1,186 @@
/*
* Copyright (C) 2024 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.launcher3.util
import android.view.View
import android.view.ViewTreeObserver
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.launcher3.Launcher
import com.android.launcher3.Workspace
import com.android.launcher3.pageindicators.PageIndicator
import java.util.function.Consumer
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.mockito.kotlin.reset
import org.mockito.kotlin.same
import org.mockito.kotlin.verifyNoMoreInteractions
@RunWith(AndroidJUnit4::class)
class ViewOnDrawExecutorTest<T> where T : View, T : PageIndicator {
@Mock private lateinit var runnable: Runnable
@Mock private lateinit var consumer: Consumer<ViewOnDrawExecutor>
@Mock private lateinit var launcher: Launcher
@Mock private lateinit var workspace: Workspace<T>
@Mock private lateinit var rootView: View
@Mock private lateinit var viewTreeObserver: ViewTreeObserver
private lateinit var underTest: ViewOnDrawExecutor
private lateinit var runnableList: RunnableList
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
runnableList = RunnableList()
runnableList.add(runnable)
underTest = ViewOnDrawExecutor(runnableList, consumer)
`when`(launcher.workspace).thenReturn(workspace)
`when`(workspace.rootView).thenReturn(rootView)
`when`(workspace.viewTreeObserver).thenReturn(viewTreeObserver)
}
@Test
fun attachToLauncher_alreadyAttachedToWindow() {
`when`(workspace.isAttachedToWindow).thenReturn(true)
underTest.attachTo(launcher)
verify(workspace).addOnAttachStateChangeListener(same(underTest))
verify(viewTreeObserver).addOnDrawListener(same(underTest))
verify(rootView).invalidate()
}
@Test
fun attachToLauncher_notAttachedToWindow() {
`when`(workspace.isAttachedToWindow).thenReturn(false)
underTest.attachTo(launcher)
verify(workspace).addOnAttachStateChangeListener(same(underTest))
verifyNoMoreInteractions(viewTreeObserver)
verifyNoMoreInteractions(rootView)
}
@Test
fun onViewAttachedToWindow_registerObserver() {
`when`(workspace.isAttachedToWindow).thenReturn(false)
underTest.attachTo(launcher)
underTest.onViewAttachedToWindow(rootView)
verify(viewTreeObserver).addOnDrawListener(same(underTest))
verify(rootView).invalidate()
}
@Test
fun complete_then_onViewAttachedToWindow_registerObserver() {
underTest.markCompleted()
reset(viewTreeObserver)
reset(rootView)
underTest.onViewAttachedToWindow(rootView)
verifyNoMoreInteractions(viewTreeObserver)
verifyNoMoreInteractions(rootView)
}
@Test
fun onDraw_postRunnable() {
underTest.attachTo(launcher)
underTest.onDraw()
verify(workspace).post(same(underTest))
}
@Test
fun run_before_onDraw_noOp() {
underTest.run()
verifyNoMoreInteractions(runnable)
verifyNoMoreInteractions(viewTreeObserver)
verifyNoMoreInteractions(workspace)
verifyNoMoreInteractions(consumer)
}
@Test
fun first_run_executeRunnable() {
underTest.attachTo(launcher)
underTest.onDraw()
underTest.run()
verify(runnable).run()
verify(viewTreeObserver).removeOnDrawListener(same(underTest))
verify(workspace).removeOnAttachStateChangeListener(same(underTest))
verify(consumer).accept(same(underTest))
}
@Test
fun second_run_noOp() {
underTest.attachTo(launcher)
underTest.onDraw()
underTest.run()
reset(runnable)
reset(viewTreeObserver)
reset(workspace)
reset(consumer)
underTest.run()
verifyNoMoreInteractions(runnable)
verifyNoMoreInteractions(viewTreeObserver)
verifyNoMoreInteractions(workspace)
verifyNoMoreInteractions(consumer)
}
@Test
fun markCompleted_viewNotAttached() {
underTest.markCompleted()
verify(runnable).run()
verify(consumer).accept(underTest)
verifyNoMoreInteractions(workspace)
}
@Test
fun markCompleted_viewAttached() {
underTest.attachTo(launcher)
underTest.markCompleted()
verify(runnable).run()
verify(consumer).accept(underTest)
verify(workspace).removeOnAttachStateChangeListener(same(underTest))
verify(viewTreeObserver).removeOnDrawListener(same(underTest))
}
@Test
fun cancel_notRun() {
underTest.cancel()
verifyNoMoreInteractions(runnable)
verify(consumer).accept(underTest)
verifyNoMoreInteractions(workspace)
}
}