Moving come tests to Roboelectric

> Fixing resource loading in robo tests

Change-Id: Id5b8a0e4916a2a200da7a41b03f19846834beb1f
This commit is contained in:
Sunny Goyal 2018-11-07 16:54:02 -08:00
parent f1982fcaae
commit 06a07e9748
12 changed files with 69 additions and 91 deletions

View File

@ -29,6 +29,8 @@ LOCAL_STATIC_JAVA_LIBRARIES := \
LOCAL_JAVA_LIBRARIES := \
platform-robolectric-3.6.1-prebuilt
LOCAL_JAVA_RESOURCE_DIRS := resources config
LOCAL_INSTRUMENTATION_FOR := Launcher3
LOCAL_MODULE_TAGS := optional

View File

@ -0,0 +1,2 @@
manifest=packages/apps/Launcher3/AndroidManifest.xml
sdk=28

View File

@ -15,9 +15,6 @@ import android.graphics.Rect;
import android.net.Uri;
import android.util.Pair;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherSettings;
@ -30,6 +27,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.robolectric.RobolectricTestRunner;
import java.util.ArrayList;
import java.util.List;
@ -37,8 +35,7 @@ import java.util.List;
/**
* Tests for {@link AddWorkspaceItemsTask}
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
@RunWith(RobolectricTestRunner.class)
public class AddWorkspaceItemsTaskTest extends BaseModelUpdateTaskTestCase {
private final ComponentName mComponent1 = new ComponentName("a", "b");
@ -174,7 +171,7 @@ public class AddWorkspaceItemsTaskTest extends BaseModelUpdateTaskTestCase {
}
private void commitScreensToDb() throws Exception {
LauncherSettings.Settings.call(mProviderRule.getResolver(),
LauncherSettings.Settings.call(targetContext.getContentResolver(),
LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
@ -189,6 +186,6 @@ public class AddWorkspaceItemsTaskTest extends BaseModelUpdateTaskTestCase {
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
}
mProviderRule.getResolver().applyBatch(LauncherProvider.AUTHORITY, ops);
targetContext.getContentResolver().applyBatch(LauncherProvider.AUTHORITY, ops);
}
}

View File

@ -7,24 +7,17 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.os.Process;
import android.os.UserHandle;
import androidx.test.InstrumentationRegistry;
import androidx.test.rule.provider.ProviderTestRule;
import com.android.launcher3.AllAppsList;
import com.android.launcher3.AppFilter;
import com.android.launcher3.AppInfo;
import com.android.launcher3.icons.cache.CachingLogic;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppState;
@ -33,13 +26,18 @@ import com.android.launcher3.LauncherModel.Callbacks;
import com.android.launcher3.LauncherModel.ModelUpdateTask;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.cache.CachingLogic;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.Provider;
import com.android.launcher3.util.TestLauncherProvider;
import org.junit.Before;
import org.junit.Rule;
import org.mockito.ArgumentCaptor;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowContentResolver;
import org.robolectric.shadows.ShadowLog;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@ -55,12 +53,8 @@ import androidx.annotation.NonNull;
*/
public class BaseModelUpdateTaskTestCase {
@Rule
public ProviderTestRule mProviderRule =
new ProviderTestRule.Builder(TestLauncherProvider.class, LauncherProvider.AUTHORITY)
.build();
public final HashMap<Class, HashMap<String, Field>> fieldCache = new HashMap<>();
private TestLauncherProvider mProvider;
public Context targetContext;
public UserHandle myUser;
@ -77,6 +71,11 @@ public class BaseModelUpdateTaskTestCase {
@Before
public void setUp() throws Exception {
ShadowLog.stream = System.out;
mProvider = Robolectric.setupContentProvider(TestLauncherProvider.class);
ShadowContentResolver.registerProviderInternal(LauncherProvider.AUTHORITY, mProvider);
callbacks = mock(Callbacks.class);
appState = mock(LauncherAppState.class);
model = mock(LauncherModel.class);
@ -89,12 +88,8 @@ public class BaseModelUpdateTaskTestCase {
myUser = Process.myUserHandle();
bgDataModel = new BgDataModel();
targetContext = new ContextWrapper(InstrumentationRegistry.getTargetContext()) {
@Override
public ContentResolver getContentResolver() {
return mProviderRule.getResolver();
}
};
targetContext = RuntimeEnvironment.application;
idp = new InvariantDeviceProfile();
iconCache = new MyIconCache(targetContext, idp);
@ -103,7 +98,6 @@ public class BaseModelUpdateTaskTestCase {
when(appState.getIconCache()).thenReturn(iconCache);
when(appState.getInvariantDeviceProfile()).thenReturn(idp);
when(appState.getContext()).thenReturn(targetContext);
}
/**
@ -126,11 +120,8 @@ public class BaseModelUpdateTaskTestCase {
* Initializes mock data for the test.
*/
public void initializeData(String resourceName) throws Exception {
Context myContext = InstrumentationRegistry.getContext();
Resources res = myContext.getResources();
int id = res.getIdentifier(resourceName, "raw", myContext.getPackageName());
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(res.openRawResource(id)))) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream(resourceName)))) {
String line;
HashMap<String, Class> classMap = new HashMap<>();
while((line = reader.readLine()) != null) {

View File

@ -6,9 +6,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.AppInfo;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.ShortcutInfo;
@ -16,6 +13,7 @@ import com.android.launcher3.ShortcutInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.util.Arrays;
import java.util.HashSet;
@ -23,15 +21,14 @@ import java.util.HashSet;
/**
* Tests for {@link CacheDataUpdatedTask}
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
@RunWith(RobolectricTestRunner.class)
public class CacheDataUpdatedTaskTest extends BaseModelUpdateTaskTestCase {
private static final String NEW_LABEL_PREFIX = "new-label-";
@Before
public void initData() throws Exception {
initializeData("cache_data_updated_task_data");
initializeData("/cache_data_updated_task_data.txt");
// Add dummy entries in the cache to simulate update
for (ItemInfo info : bgDataModel.itemsIdMap) {
iconCache.addCache(info.getTargetComponent(), NEW_LABEL_PREFIX + info.id);

View File

@ -1,21 +1,20 @@
package com.android.launcher3.model;
import android.content.ContentResolver;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Point;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
import androidx.test.rule.provider.ProviderTestRule;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.config.FlagOverrideRule;
import com.android.launcher3.config.FlagOverrideRule.FlagOverride;
import com.android.launcher3.model.GridSizeMigrationTask.MultiStepMigrationTask;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.TestLauncherProvider;
@ -24,25 +23,20 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowContentResolver;
import java.util.HashSet;
import java.util.LinkedList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link GridSizeMigrationTask}
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
@RunWith(RobolectricTestRunner.class)
public class GridSizeMigrationTaskTest {
@Rule
public ProviderTestRule mProviderRule =
new ProviderTestRule.Builder(TestLauncherProvider.class, LauncherProvider.AUTHORITY)
.build();
private static final int DESKTOP = LauncherSettings.Favorites.CONTAINER_DESKTOP;
private static final int HOTSEAT = LauncherSettings.Favorites.CONTAINER_HOTSEAT;
@ -50,27 +44,25 @@ public class GridSizeMigrationTaskTest {
private static final int SHORTCUT = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
private static final String TEST_PACKAGE = "com.android.launcher3.validpackage";
private static final String VALID_INTENT =
new Intent(Intent.ACTION_MAIN).setPackage(TEST_PACKAGE).toUri(0);
@Rule
public final FlagOverrideRule flags = new FlagOverrideRule();
private HashSet<String> mValidPackages;
private InvariantDeviceProfile mIdp;
private Context mContext;
private TestLauncherProvider mProvider;
@Before
public void setUp() throws Exception {
public void setUp() {
mValidPackages = new HashSet<>();
mValidPackages.add(TEST_PACKAGE);
mIdp = new InvariantDeviceProfile();
mContext = RuntimeEnvironment.application;
mContext = new ContextWrapper(InstrumentationRegistry.getTargetContext()) {
@Override
public ContentResolver getContentResolver() {
return mProviderRule.getResolver();
}
};
mProvider = Robolectric.setupContentProvider(TestLauncherProvider.class);
ShadowContentResolver.registerProviderInternal(LauncherProvider.AUTHORITY, mProvider);
}
@Test
@ -112,7 +104,7 @@ public class GridSizeMigrationTaskTest {
int total = 0;
for (int id : sortedIds) {
Cursor c = mProviderRule.getResolver().query(LauncherSettings.Favorites.CONTENT_URI,
Cursor c = mContext.getContentResolver().query(LauncherSettings.Favorites.CONTENT_URI,
new String[]{LauncherSettings.Favorites._ID},
"container=-101 and screen=" + screenId, null, null, null);
@ -130,7 +122,7 @@ public class GridSizeMigrationTaskTest {
}
// Verify that not other entry exist in the DB.
Cursor c = mProviderRule.getResolver().query(LauncherSettings.Favorites.CONTENT_URI,
Cursor c = mContext.getContentResolver().query(LauncherSettings.Favorites.CONTENT_URI,
new String[]{LauncherSettings.Favorites._ID},
"container=-101", null, null, null);
assertEquals(total, c.getCount());
@ -240,6 +232,7 @@ public class GridSizeMigrationTaskTest {
}});
}
@FlagOverride(key = "QSB_ON_FIRST_SCREEN", value = true)
@Test
public void testWorkspace_first_row_blocked() throws Exception {
// The first screen has one item on the 4th column which needs moving, as the first row
@ -265,6 +258,7 @@ public class GridSizeMigrationTaskTest {
}});
}
@FlagOverride(key = "QSB_ON_FIRST_SCREEN", value = true)
@Test
public void testWorkspace_items_moved_to_empty_first_row() throws Exception {
// Items will get moved to the next screen to keep the first screen empty.
@ -301,7 +295,7 @@ public class GridSizeMigrationTaskTest {
* @return the same grid representation where each entry is the corresponding item id.
*/
private int[][][] createGrid(int[][][] typeArray, int startScreen) throws Exception {
LauncherSettings.Settings.call(mProviderRule.getResolver(),
LauncherSettings.Settings.call(mContext.getContentResolver(),
LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
int[][][] ids = new int[typeArray.length][][];
@ -310,13 +304,13 @@ public class GridSizeMigrationTaskTest {
int screenId = startScreen + i;
// Keep the screen id counter up to date
LauncherSettings.Settings.call(mProviderRule.getResolver(),
LauncherSettings.Settings.call(mContext.getContentResolver(),
LauncherSettings.Settings.METHOD_NEW_SCREEN_ID);
ContentValues v = new ContentValues();
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
mProviderRule.getResolver().insert(LauncherSettings.WorkspaceScreens.CONTENT_URI, v);
mContext.getContentResolver().insert(LauncherSettings.WorkspaceScreens.CONTENT_URI, v);
ids[i] = new int[typeArray[i].length][];
for (int y = 0; y < typeArray[i].length; y++) {
@ -331,6 +325,8 @@ public class GridSizeMigrationTaskTest {
}
}
}
IntArray allScreens = LauncherModel.loadWorkspaceScreensDb(mContext);
return ids;
}
@ -350,7 +346,7 @@ public class GridSizeMigrationTaskTest {
for (int x = 0; x < ids[i][y].length; x++) {
int id = ids[i][y][x];
Cursor c = mProviderRule.getResolver().query(
Cursor c = mContext.getContentResolver().query(
LauncherSettings.Favorites.CONTENT_URI,
new String[]{LauncherSettings.Favorites._ID},
"container=-100 and screen=" + screenId +
@ -370,7 +366,7 @@ public class GridSizeMigrationTaskTest {
}
// Verify that not other entry exist in the DB.
Cursor c = mProviderRule.getResolver().query(LauncherSettings.Favorites.CONTENT_URI,
Cursor c = mContext.getContentResolver().query(LauncherSettings.Favorites.CONTENT_URI,
new String[]{LauncherSettings.Favorites._ID},
"container=-100", null, null, null);
assertEquals(total, c.getCount());
@ -383,7 +379,7 @@ public class GridSizeMigrationTaskTest {
* folder (where the type represents the number of items in the folder).
*/
private int addItem(int type, int screen, int container, int x, int y) throws Exception {
int id = LauncherSettings.Settings.call(mProviderRule.getResolver(),
int id = LauncherSettings.Settings.call(mContext.getContentResolver(),
LauncherSettings.Settings.METHOD_NEW_ITEM_ID)
.getInt(LauncherSettings.Settings.EXTRA_VALUE);
@ -398,7 +394,8 @@ public class GridSizeMigrationTaskTest {
if (type == APPLICATION || type == SHORTCUT) {
values.put(LauncherSettings.Favorites.ITEM_TYPE, type);
values.put(LauncherSettings.Favorites.INTENT, VALID_INTENT);
values.put(LauncherSettings.Favorites.INTENT,
new Intent(Intent.ACTION_MAIN).setPackage(TEST_PACKAGE).toUri(0));
} else {
values.put(LauncherSettings.Favorites.ITEM_TYPE,
LauncherSettings.Favorites.ITEM_TYPE_FOLDER);
@ -408,7 +405,7 @@ public class GridSizeMigrationTaskTest {
}
}
mProviderRule.getResolver().insert(LauncherSettings.Favorites.CONTENT_URI, values);
mContext.getContentResolver().insert(LauncherSettings.Favorites.CONTENT_URI, values);
return id;
}

View File

@ -2,9 +2,6 @@ package com.android.launcher3.model;
import static org.junit.Assert.assertEquals;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.ShortcutInfo;
@ -14,6 +11,7 @@ import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.util.Arrays;
import java.util.HashSet;
@ -21,13 +19,12 @@ import java.util.HashSet;
/**
* Tests for {@link PackageInstallStateChangedTask}
*/
@SmallTest
@RunWith(AndroidJUnit4.class)
@RunWith(RobolectricTestRunner.class)
public class PackageInstallStateChangedTaskTest extends BaseModelUpdateTaskTestCase {
@Before
public void initData() throws Exception {
initializeData("package_install_state_change_task_data");
initializeData("/package_install_state_change_task_data.txt");
}
private PackageInstallStateChangedTask newTask(String pkg, int progress) {

View File

@ -21,7 +21,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -31,7 +30,6 @@ import static org.junit.Assert.assertTrue;
* Robolectric unit tests for {@link IntSet}
*/
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 26)
public class IntSetTest {
@Test

View File

@ -23,11 +23,6 @@ public class TestLauncherProvider extends LauncherProvider {
}
}
public SQLiteOpenHelper getHelper() {
createDbIfNotExists();
return mOpenHelper;
}
@Override
protected void notifyListeners() { }
@ -48,4 +43,4 @@ public class TestLauncherProvider extends LauncherProvider {
@Override
protected void handleOneTimeDataUpgrade(SQLiteDatabase db) { }
}
}
}

View File

@ -96,10 +96,12 @@ public class LauncherModel extends BroadcastReceiver
@Thunk boolean mIsLoaderTaskRunning;
@Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
private static final Looper mWorkerLooper;
static {
sWorkerThread.start();
mWorkerLooper = sWorkerThread.getLooper();
}
@Thunk static final Handler sWorker = new Handler(sWorkerThread.getLooper());
@Thunk static final Handler sWorker = new Handler(mWorkerLooper);
// Indicates whether the current model data is valid or not.
// We start off with everything not loaded. After that, we assume that
@ -708,7 +710,7 @@ public class LauncherModel extends BroadcastReceiver
* @return the looper for the worker thread which can be used to start background tasks.
*/
public static Looper getWorkerLooper() {
return sWorkerThread.getLooper();
return mWorkerLooper;
}
public static void setWorkerPriority(final int priority) {