Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(155)

Unified Diff: chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCommon.java

Issue 2815453003: Create ChromeActivityTestRule for converting JUnit4 tests (Closed)
Patch Set: nits and rebase Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCommon.java
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCaseBase.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCommon.java
similarity index 68%
copy from chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCaseBase.java
copy to chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCommon.java
index 725048b20a738a0c80dc3698b1d1cc99e172b3ea..c26b1ac52a999472a92f843bc207b77b7c1b77d1 100644
--- a/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCaseBase.java
+++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/ChromeActivityTestCommon.java
@@ -1,4 +1,4 @@
-// Copyright 2015 The Chromium Authors. All rights reserved.
+// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@@ -13,11 +13,12 @@ import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Browser;
-import android.test.InstrumentationTestRunner;
+import android.support.test.internal.runner.listener.InstrumentationResultPrinter;
import android.text.TextUtils;
-import android.view.View;
import android.widget.ListView;
+import org.junit.Assert;
+
import org.chromium.base.ActivityState;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.ApplicationStatus.ActivityStateListener;
@@ -25,14 +26,10 @@ import org.chromium.base.Log;
import org.chromium.base.PerfTraceEvent;
import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.SuppressFBWarnings;
-import org.chromium.base.test.BaseActivityInstrumentationTestCase;
import org.chromium.base.test.util.CallbackHelper;
-import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.PerfTest;
-import org.chromium.base.test.util.parameter.BaseParameter;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeActivity;
-import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.ChromeTabbedActivity;
import org.chromium.chrome.browser.DeferredStartupHandler;
import org.chromium.chrome.browser.document.ChromeLauncherActivity;
@@ -56,15 +53,10 @@ import org.chromium.chrome.test.util.ApplicationTestUtils;
import org.chromium.chrome.test.util.ChromeTabUtils;
import org.chromium.chrome.test.util.MenuUtils;
import org.chromium.chrome.test.util.NewTabPageTestUtils;
-import org.chromium.chrome.test.util.parameters.AddFakeAccountToAppParameter;
-import org.chromium.chrome.test.util.parameters.AddFakeAccountToOsParameter;
-import org.chromium.chrome.test.util.parameters.AddGoogleAccountToOsParameter;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.content.browser.test.util.JavaScriptUtils;
import org.chromium.content.browser.test.util.RenderProcessLimit;
-import org.chromium.content.browser.test.util.TestTouchUtils;
-import org.chromium.content.browser.test.util.TouchCommon;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.ui.base.PageTransition;
@@ -74,7 +66,6 @@ import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
@@ -83,23 +74,11 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
-/**
- * Base class for all Chrome instrumentation tests.
- * All tests must inherit from this class and define their own test methods
- * See ChromeTabbedActivityTestBase.java for example.
- * @param <T> A {@link ChromeActivity} class
- */
-@CommandLineFlags.Add({
- ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
- // Preconnect causes issues with the single-threaded Java test server.
- "--disable-features=NetworkPrediction"})
-public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
- extends BaseActivityInstrumentationTestCase<T> {
-
- private static final String TAG = "cr_CATestCaseBase";
+final class ChromeActivityTestCommon<T extends ChromeActivity> {
+ private static final String TAG = "cr_CATestCommon";
// The number of ms to wait for the rendering activity to be started.
- protected static final int ACTIVITY_START_TIMEOUT_MS = 1000;
+ static final int ACTIVITY_START_TIMEOUT_MS = 1000;
private static final String PERF_ANNOTATION_FORMAT = "**PERFANNOTATION(%s):";
@@ -112,10 +91,11 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
protected boolean mSkipClearAppData;
private Thread.UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;
private Class<T> mChromeActivityClass;
+ private ChromeTestCommonCallback<T> mCallback;
- public ChromeActivityTestCaseBase(Class<T> activityClass) {
- super(activityClass);
+ ChromeActivityTestCommon(Class<T> activityClass, ChromeTestCommonCallback<T> callback) {
mChromeActivityClass = activityClass;
+ mCallback = callback;
}
private class ChromeUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@@ -126,49 +106,38 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
stackTrace += "\nSearch logcat for \"StrictMode policy violation\" for full stack.";
}
Bundle resultsBundle = new Bundle();
- resultsBundle.putString(InstrumentationTestRunner.REPORT_KEY_NAME_CLASS,
- getClass().getName());
- resultsBundle.putString(InstrumentationTestRunner.REPORT_KEY_NAME_TEST, getName());
- resultsBundle.putString(InstrumentationTestRunner.REPORT_KEY_STACK, stackTrace);
- getInstrumentation().sendStatus(-1, resultsBundle);
+ resultsBundle.putString(
+ InstrumentationResultPrinter.REPORT_KEY_NAME_CLASS, getClass().getName());
+ resultsBundle.putString(
+ InstrumentationResultPrinter.REPORT_KEY_NAME_TEST, mCallback.getTestName());
+ resultsBundle.putString(InstrumentationResultPrinter.REPORT_KEY_STACK, stackTrace);
+ mCallback.getInstrumentation().sendStatus(-1, resultsBundle);
mDefaultUncaughtExceptionHandler.uncaughtException(t, e);
}
}
- @Override
- protected void setUp() throws Exception {
- super.setUp();
+ void setUp() throws Exception {
mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new ChromeUncaughtExceptionHandler());
- ApplicationTestUtils.setUp(getInstrumentation().getTargetContext(), !mSkipClearAppData);
- setActivityInitialTouchMode(false);
+ ApplicationTestUtils.setUp(
+ mCallback.getInstrumentation().getTargetContext(), !mSkipClearAppData);
+ mCallback.setActivityInitialTouchMode(false);
// Preload Calendar so that it does not trigger ReadFromDisk Strict mode violations if
// called on the UI Thread. See https://crbug.com/705477 and https://crbug.com/577185
Calendar.getInstance();
-
- startMainActivity();
}
- @Override
- protected void tearDown() throws Exception {
- ApplicationTestUtils.tearDown(getInstrumentation().getTargetContext());
+ void tearDown() throws Exception {
+ ApplicationTestUtils.tearDown(mCallback.getInstrumentation().getTargetContext());
Thread.setDefaultUncaughtExceptionHandler(mDefaultUncaughtExceptionHandler);
- super.tearDown();
}
/**
- * Called to start the Main Activity, the subclass should implemented with it desired start
- * method.
- * TODO: Make startMainActivityFromLauncher the default.
- */
- public abstract void startMainActivity() throws InterruptedException;
-
- /**
* Matches testString against baseString.
* Returns 0 if there is no match, 1 if an exact match and 2 if a fuzzy match.
*/
- protected static int matchUrl(String baseString, String testString) {
+ static int matchUrl(String baseString, String testString) {
if (baseString.equals(testString)) {
return 1;
}
@@ -185,7 +154,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* return, but generally speaking the activity's "onCreate" has completed
* and the activity's main looper has become idle.
*/
- protected void startActivityCompletely(Intent intent) {
+ void startActivityCompletely(Intent intent) {
final CallbackHelper activityCallback = new CallbackHelper();
final AtomicReference<T> activityRef = new AtomicReference<>();
ActivityStateListener stateListener = new ActivityStateListener() {
@@ -206,11 +175,11 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
ApplicationStatus.registerStateListenerForAllActivities(stateListener);
try {
- getInstrumentation().startActivitySync(intent);
+ mCallback.getInstrumentation().startActivitySync(intent);
activityCallback.waitForCallback("Activity did not start as expected", 0);
T activity = activityRef.get();
- assertNotNull("Activity reference is null.", activity);
- setActivity(activity);
+ Assert.assertNotNull("Activity reference is null.", activity);
+ mCallback.setActivity(activity);
Log.d(TAG, "startActivityCompletely <<");
} catch (InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
@@ -220,16 +189,16 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
}
/** Convenience function for {@link ApplicationTestUtils#clearAppData(Context)}. */
- protected void clearAppData() {
- ApplicationTestUtils.clearAppData(getInstrumentation().getTargetContext());
+ void clearAppData() {
+ ApplicationTestUtils.clearAppData(mCallback.getInstrumentation().getTargetContext());
}
/**
* Enables or disables network predictions, i.e. prerendering, prefetching, DNS preresolution,
* etc. Network predictions are enabled by default.
*/
- protected void setNetworkPredictionEnabled(final boolean enabled) {
- getInstrumentation().runOnMainSync(new Runnable() {
+ void setNetworkPredictionEnabled(final boolean enabled) {
+ mCallback.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
PrefServiceBridge.getInstance().setNetworkPredictionEnabled(enabled);
@@ -238,70 +207,13 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
}
/**
- * Starts (synchronously) a drag motion. Normally followed by dragTo() and dragEnd().
- *
- * @param x
- * @param y
- * @param downTime (in ms)
- * @see TestTouchUtils
- */
- protected void dragStart(float x, float y, long downTime) {
- TouchCommon.dragStart(getActivity(), x, y, downTime);
- }
-
- /**
- * Drags / moves (synchronously) to the specified coordinates. Normally preceeded by
- * dragStart() and followed by dragEnd()
- *
- * @param fromX
- * @param toX
- * @param fromY
- * @param toY
- * @param stepCount
- * @param downTime (in ms)
- * @see TestTouchUtils
- */
- protected void dragTo(float fromX, float toX, float fromY,
- float toY, int stepCount, long downTime) {
- TouchCommon.dragTo(getActivity(), fromX, toX, fromY, toY, stepCount, downTime);
- }
-
- /**
- * Finishes (synchronously) a drag / move at the specified coordinate.
- * Normally preceeded by dragStart() and dragTo().
- *
- * @param x
- * @param y
- * @param downTime (in ms)
- * @see TestTouchUtils
- */
- protected void dragEnd(float x, float y, long downTime) {
- TouchCommon.dragEnd(getActivity(), x, y, downTime);
- }
-
- /**
- * Sends (synchronously) a single click to the center of the View.
- *
- * <p>
- * Differs from
- * {@link TestTouchUtils#singleClickView(android.app.Instrumentation, View)}
- * as this does not rely on injecting events into the different activity. Injecting events has
- * been unreliable for us and simulating the touch events in this manner is just as effective.
- *
- * @param v The view to be clicked.
- */
- public void singleClickView(View v) {
- TouchCommon.singleClickView(v);
- }
-
- /**
* Waits for {@link AsyncTask}'s that have been queued to finish. Note, this
* only waits for tasks that have been started using the default
* {@link java.util.concurrent.Executor}, which executes tasks serially.
*
* @param timeout how long to wait for tasks to complete
*/
- public void waitForAsyncTasks(long timeout) throws InterruptedException {
+ void waitForAsyncTasks(long timeout) throws InterruptedException {
final Semaphore s = new Semaphore(0);
new AsyncTask<Void, Void, Void>() {
@Override
@@ -309,8 +221,9 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
s.release();
return null;
}
- }.execute();
- assertTrue(s.tryAcquire(timeout, TimeUnit.MILLISECONDS));
+ }
+ .execute();
+ Assert.assertTrue(s.tryAcquire(timeout, TimeUnit.MILLISECONDS));
}
/**
@@ -321,10 +234,10 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @return FULL_PRERENDERED_PAGE_LOAD or PARTIAL_PRERENDERED_PAGE_LOAD if the page has been
* prerendered. DEFAULT_PAGE_LOAD if it had not.
*/
- public int loadUrl(final String url, long secondsToWait)
+ int loadUrl(final String url, long secondsToWait)
throws IllegalArgumentException, InterruptedException {
return loadUrlInTab(url, PageTransition.TYPED | PageTransition.FROM_ADDRESS_BAR,
- getActivity().getActivityTab(), secondsToWait);
+ mCallback.getActivity().getActivityTab(), secondsToWait);
}
/**
@@ -334,9 +247,9 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @return FULL_PRERENDERED_PAGE_LOAD or PARTIAL_PRERENDERED_PAGE_LOAD if the page has been
* prerendered. DEFAULT_PAGE_LOAD if it had not.
*/
- public int loadUrl(final String url) throws IllegalArgumentException, InterruptedException {
+ int loadUrl(final String url) throws IllegalArgumentException, InterruptedException {
return loadUrlInTab(url, PageTransition.TYPED | PageTransition.FROM_ADDRESS_BAR,
- getActivity().getActivityTab());
+ mCallback.getActivity().getActivityTab());
}
/**
@@ -349,9 +262,9 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @return FULL_PRERENDERED_PAGE_LOAD or PARTIAL_PRERENDERED_PAGE_LOAD if the
* page has been prerendered. DEFAULT_PAGE_LOAD if it had not.
*/
- public int loadUrlInTab(final String url, final int pageTransition, final Tab tab,
- long secondsToWait) throws InterruptedException {
- assertNotNull("Cannot load the url in a null tab", tab);
+ int loadUrlInTab(final String url, final int pageTransition, final Tab tab, long secondsToWait)
+ throws InterruptedException {
+ Assert.assertNotNull("Cannot load the url in a null tab", tab);
final AtomicInteger result = new AtomicInteger();
ChromeTabUtils.waitForTabPageLoaded(tab, new Runnable() {
@@ -360,13 +273,12 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
- result.set(tab.loadUrl(
- new LoadUrlParams(url, pageTransition)));
+ result.set(tab.loadUrl(new LoadUrlParams(url, pageTransition)));
}
});
}
}, secondsToWait);
- getInstrumentation().waitForIdleSync();
+ mCallback.getInstrumentation().waitForIdleSync();
return result.get();
}
@@ -379,7 +291,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @return FULL_PRERENDERED_PAGE_LOAD or PARTIAL_PRERENDERED_PAGE_LOAD if the
* page has been prerendered. DEFAULT_PAGE_LOAD if it had not.
*/
- public int loadUrlInTab(final String url, final int pageTransition, final Tab tab)
+ int loadUrlInTab(final String url, final int pageTransition, final Tab tab)
throws InterruptedException {
return loadUrlInTab(url, pageTransition, tab, CallbackHelper.WAIT_TIMEOUT_SECONDS);
}
@@ -388,7 +300,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* Load a url in a new tab. The {@link Tab} will pretend to be created from a link.
* @param url The url of the page to load.
*/
- public Tab loadUrlInNewTab(final String url) throws InterruptedException {
+ Tab loadUrlInNewTab(final String url) throws InterruptedException {
return loadUrlInNewTab(url, false);
}
@@ -397,29 +309,28 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @param url The url of the page to load.
* @param incognito Whether the new tab should be incognito.
*/
- public Tab loadUrlInNewTab(final String url, final boolean incognito)
- throws InterruptedException {
+ Tab loadUrlInNewTab(final String url, final boolean incognito) throws InterruptedException {
Tab tab = null;
try {
tab = ThreadUtils.runOnUiThreadBlocking(new Callable<Tab>() {
@Override
public Tab call() throws Exception {
- return getActivity().getTabCreator(incognito)
- .launchUrl(url, TabLaunchType.FROM_LINK);
+ return mCallback.getActivity().getTabCreator(incognito).launchUrl(
+ url, TabLaunchType.FROM_LINK);
}
});
} catch (ExecutionException e) {
- fail("Failed to create new tab");
+ Assert.fail("Failed to create new tab");
}
ChromeTabUtils.waitForTabPageLoaded(tab, url);
- getInstrumentation().waitForIdleSync();
+ mCallback.getInstrumentation().waitForIdleSync();
return tab;
}
/**
* Simulates starting Main Activity from launcher, blocks until it is started.
*/
- protected void startMainActivityFromLauncher() throws InterruptedException {
+ void startMainActivityFromLauncher() throws InterruptedException {
startMainActivityWithURL(null);
}
@@ -427,10 +338,10 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* Starts the Main activity on the specified URL. Passing a null URL ensures the default page is
* loaded, which is the NTP with a new profile .
*/
- protected void startMainActivityWithURL(String url) throws InterruptedException {
+ void startMainActivityWithURL(String url) throws InterruptedException {
// Only launch Chrome.
- Intent intent = new Intent(
- TextUtils.isEmpty(url) ? Intent.ACTION_MAIN : Intent.ACTION_VIEW);
+ Intent intent =
+ new Intent(TextUtils.isEmpty(url) ? Intent.ACTION_MAIN : Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startMainActivityFromIntent(intent, url);
}
@@ -439,7 +350,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* Starts the Main activity and open a blank page.
* This is faster and less flakyness-prone than starting on the NTP.
*/
- protected void startMainActivityOnBlankPage() throws InterruptedException {
+ void startMainActivityOnBlankPage() throws InterruptedException {
startMainActivityWithURL("about:blank");
}
@@ -447,8 +358,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* Starts the Main activity as if it was started from an external application, on the specified
* URL.
*/
- protected void startMainActivityFromExternalApp(String url, String appId)
- throws InterruptedException {
+ void startMainActivityFromExternalApp(String url, String appId) throws InterruptedException {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (appId != null) {
intent.putExtra(Browser.EXTRA_APPLICATION_ID, appId);
@@ -462,8 +372,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* idle-sync of the main looper thread, and the initial tab must either
* complete its load or it must crash before this method will return.
*/
- protected void startMainActivityFromIntent(Intent intent, String url)
- throws InterruptedException {
+ void startMainActivityFromIntent(Intent intent, String url) throws InterruptedException {
prepareUrlIntent(intent, url);
startActivityCompletely(intent);
@@ -471,10 +380,10 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
CriteriaHelper.pollUiThread(new Criteria("Tab never selected/initialized.") {
@Override
public boolean isSatisfied() {
- return getActivity().getActivityTab() != null;
+ return mCallback.getActivity().getActivityTab() != null;
}
});
- Tab tab = getActivity().getActivityTab();
+ Tab tab = mCallback.getActivity().getActivityTab();
ChromeTabUtils.waitForTabPageLoaded(tab, (String) null);
@@ -489,9 +398,9 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
}
});
- assertNotNull(tab);
- assertNotNull(tab.getView());
- getInstrumentation().waitForIdleSync();
+ Assert.assertNotNull(tab);
+ Assert.assertNotNull(tab.getView());
+ mCallback.getInstrumentation().waitForIdleSync();
}
/**
@@ -499,21 +408,21 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @param intent the intent to be modified
* @param url the URL to be used (may be null)
*/
- protected Intent prepareUrlIntent(Intent intent, String url) {
+ Intent prepareUrlIntent(Intent intent, String url) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setComponent(new ComponentName(getInstrumentation().getTargetContext(),
- ChromeLauncherActivity.class));
+ intent.setComponent(new ComponentName(
+ mCallback.getInstrumentation().getTargetContext(), ChromeLauncherActivity.class));
if (url != null) {
intent.setData(Uri.parse(url));
}
try {
- Method method = getClass().getMethod(getName(), (Class[]) null);
+ Method method = getClass().getMethod(mCallback.getTestName(), (Class[]) null);
if (((AnnotatedElement) method).isAnnotationPresent(RenderProcessLimit.class)) {
RenderProcessLimit limit = method.getAnnotation(RenderProcessLimit.class);
- intent.putExtra(ChromeTabbedActivity.INTENT_EXTRA_TEST_RENDER_PROCESS_LIMIT,
- limit.value());
+ intent.putExtra(
+ ChromeTabbedActivity.INTENT_EXTRA_TEST_RENDER_PROCESS_LIMIT, limit.value());
}
} catch (NoSuchMethodException ex) {
// Ignore exception.
@@ -525,13 +434,13 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* Open an incognito tab by invoking the 'new incognito' menu item.
* Returns when receiving the 'PAGE_LOAD_FINISHED' notification.
*/
- protected void newIncognitoTabFromMenu() throws InterruptedException {
+ void newIncognitoTabFromMenu() throws InterruptedException {
Tab tab = null;
final CallbackHelper createdCallback = new CallbackHelper();
final CallbackHelper selectedCallback = new CallbackHelper();
- TabModel incognitoTabModel = getActivity().getTabModelSelector().getModel(true);
+ TabModel incognitoTabModel = mCallback.getActivity().getTabModelSelector().getModel(true);
TabModelObserver observer = new EmptyTabModelObserver() {
@Override
public void didAddTab(Tab tab, TabLaunchType type) {
@@ -545,26 +454,26 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
};
incognitoTabModel.addObserver(observer);
- MenuUtils.invokeCustomMenuActionSync(getInstrumentation(), getActivity(),
- R.id.new_incognito_tab_menu_id);
+ MenuUtils.invokeCustomMenuActionSync(mCallback.getInstrumentation(),
+ mCallback.getActivity(), R.id.new_incognito_tab_menu_id);
try {
createdCallback.waitForCallback(0);
} catch (TimeoutException ex) {
- fail("Never received tab created event");
+ Assert.fail("Never received tab created event");
}
try {
selectedCallback.waitForCallback(0);
} catch (TimeoutException ex) {
- fail("Never received tab selected event");
+ Assert.fail("Never received tab selected event");
}
incognitoTabModel.removeObserver(observer);
- tab = getActivity().getActivityTab();
+ tab = mCallback.getActivity().getActivityTab();
ChromeTabUtils.waitForTabPageLoaded(tab, (String) null);
NewTabPageTestUtils.waitForNtpLoaded(tab);
- getInstrumentation().waitForIdleSync();
+ mCallback.getInstrumentation().waitForIdleSync();
Log.d(TAG, "newIncognitoTabFromMenu <<");
}
@@ -572,8 +481,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* New multiple incognito tabs by invoking the 'new incognito' menu item n times.
* @param n The number of tabs you want to create.
*/
- protected void newIncognitoTabsFromMenu(int n)
- throws InterruptedException {
+ void newIncognitoTabsFromMenu(int n) throws InterruptedException {
while (n > 0) {
newIncognitoTabFromMenu();
--n;
@@ -583,11 +491,11 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
/**
* @return The number of incognito tabs currently open.
*/
- protected int incognitoTabsCount() {
+ int incognitoTabsCount() {
return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Integer>() {
@Override
public Integer call() {
- return getActivity().getTabModelSelector().getModel(true).getCount();
+ return mCallback.getActivity().getTabModelSelector().getModel(true).getCount();
}
});
}
@@ -601,10 +509,10 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
*
* @throws InterruptedException
*/
- public void typeInOmnibox(final String text, final boolean oneCharAtATime)
+ void typeInOmnibox(final String text, final boolean oneCharAtATime)
throws InterruptedException {
- final UrlBar urlBar = (UrlBar) getActivity().findViewById(R.id.url_bar);
- assertNotNull(urlBar);
+ final UrlBar urlBar = (UrlBar) mCallback.getActivity().findViewById(R.id.url_bar);
+ Assert.assertNotNull(urlBar);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
@@ -617,7 +525,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
});
if (oneCharAtATime) {
- final Instrumentation instrumentation = getInstrumentation();
+ final Instrumentation instrumentation = mCallback.getInstrumentation();
for (int i = 0; i < text.length(); ++i) {
instrumentation.sendStringSync(text.substring(i, i + 1));
// Let's put some delay between key strokes to simulate a user pressing the keys.
@@ -636,20 +544,18 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
*
* @throws InterruptedException
*/
- protected OmniboxSuggestion findOmniboxSuggestion(String inputText, String displayText,
- String url, int type) throws InterruptedException {
+ OmniboxSuggestion findOmniboxSuggestion(String inputText, String displayText, String url,
+ int type) throws InterruptedException {
long endTime = System.currentTimeMillis() + OMNIBOX_FIND_SUGGESTION_TIMEOUT_MS;
// Multiple suggestion events may occur before the one we're interested in is received.
final CallbackHelper onSuggestionsReceivedHelper = new CallbackHelper();
final LocationBarLayout locationBar =
- (LocationBarLayout) getActivity().findViewById(R.id.location_bar);
+ (LocationBarLayout) mCallback.getActivity().findViewById(R.id.location_bar);
locationBar.setAutocompleteController(new AutocompleteController(locationBar) {
@Override
- public void onSuggestionsReceived(
- List<OmniboxSuggestion> suggestions,
- String inlineAutocompleteText,
- long currentNativeAutocompleteResult) {
+ public void onSuggestionsReceived(List<OmniboxSuggestion> suggestions,
+ String inlineAutocompleteText, long currentNativeAutocompleteResult) {
super.onSuggestionsReceived(
suggestions, inlineAutocompleteText, currentNativeAutocompleteResult);
onSuggestionsReceivedHelper.notifyCalled();
@@ -662,8 +568,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
while (true) {
try {
int callbackCount = onSuggestionsReceivedHelper.getCallCount();
- onSuggestionsReceivedHelper.waitForCallback(
- callbackCount, 1,
+ onSuggestionsReceivedHelper.waitForCallback(callbackCount, 1,
endTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException exception) {
return null;
@@ -673,13 +578,15 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
CriteriaHelper.pollInstrumentationThread(new Criteria() {
@Override
public boolean isSatisfied() {
- return ((LocationBarLayout) getActivity().findViewById(
- R.id.location_bar)).getSuggestionList() != null;
+ return ((LocationBarLayout) mCallback.getActivity().findViewById(
+ R.id.location_bar))
+ .getSuggestionList()
+ != null;
}
}, 3000, 10);
final ListView suggestionListView = locationBar.getSuggestionList();
- OmniboxResultItem popupItem = (OmniboxResultItem) suggestionListView
- .getItemAtPosition(0);
+ OmniboxResultItem popupItem =
+ (OmniboxResultItem) suggestionListView.getItemAtPosition(0);
OmniboxSuggestion suggestion = popupItem.getSuggestion();
if (suggestionListView.getCount() == 1
&& suggestion.getDisplayText().equals(inputText)
@@ -717,13 +624,13 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
/**
* Returns the infobars being displayed by the current tab, or null if they don't exist.
*/
- protected List<InfoBar> getInfoBars() {
+ List<InfoBar> getInfoBars() {
return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<List<InfoBar>>() {
@Override
public List<InfoBar> call() throws Exception {
- Tab currentTab = getActivity().getActivityTab();
- assertNotNull(currentTab);
- assertNotNull(currentTab.getInfoBarContainer());
+ Tab currentTab = mCallback.getActivity().getActivityTab();
+ Assert.assertNotNull(currentTab);
+ Assert.assertNotNull(currentTab.getInfoBarContainer());
return currentTab.getInfoBarContainer().getInfoBarsForTesting();
}
});
@@ -733,11 +640,11 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* Launches the preferences menu and starts the preferences activity named fragmentName.
* Returns the activity that was started.
*/
- protected Preferences startPreferences(String fragmentName) {
- Context context = getInstrumentation().getTargetContext();
+ Preferences startPreferences(String fragmentName) {
+ Context context = mCallback.getInstrumentation().getTargetContext();
Intent intent = PreferencesLauncher.createIntentForSettingsPage(context, fragmentName);
- Activity activity = getInstrumentation().startActivitySync(intent);
- assertTrue(activity instanceof Preferences);
+ Activity activity = mCallback.getInstrumentation().startActivitySync(intent);
+ Assert.assertTrue(activity instanceof Preferences);
return (Preferences) activity;
}
@@ -746,38 +653,19 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* its execution in JSON format.
* @throws InterruptedException
*/
- protected String runJavaScriptCodeInCurrentTab(String code) throws InterruptedException,
- TimeoutException {
+ String runJavaScriptCodeInCurrentTab(String code)
+ throws InterruptedException, TimeoutException {
return JavaScriptUtils.executeJavaScriptAndWaitForResult(
- getActivity().getCurrentContentViewCore().getWebContents(), code);
- }
-
- @Override
- protected void runTest() throws Throwable {
- String perfTagAnalysisString = setupPotentialPerfTest();
- super.runTest();
- endPerfTest(perfTagAnalysisString);
- }
-
- @Override
- protected Map<String, BaseParameter> createAvailableParameters() {
- Map<String, BaseParameter> availableParameters = super.createAvailableParameters();
- availableParameters.put(AddFakeAccountToAppParameter.PARAMETER_TAG,
- new AddFakeAccountToAppParameter(getParameterReader(), getInstrumentation()));
- availableParameters.put(AddFakeAccountToOsParameter.PARAMETER_TAG,
- new AddFakeAccountToOsParameter(getParameterReader(), getInstrumentation()));
- availableParameters.put(AddGoogleAccountToOsParameter.PARAMETER_TAG,
- new AddGoogleAccountToOsParameter(getParameterReader(), getInstrumentation()));
- return availableParameters;
+ mCallback.getActivity().getCurrentContentViewCore().getWebContents(), code);
}
/**
* Waits till the ContentViewCore receives the expected page scale factor
* from the compositor and asserts that this happens.
*/
- protected void assertWaitForPageScaleFactorMatch(final float expectedScale)
- throws InterruptedException {
- ApplicationTestUtils.assertWaitForPageScaleFactorMatch(getActivity(), expectedScale);
+ void assertWaitForPageScaleFactorMatch(final float expectedScale) {
+ ApplicationTestUtils.assertWaitForPageScaleFactorMatch(
+ mCallback.getActivity(), expectedScale);
}
/**
@@ -790,16 +678,13 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* perf output in this case. In the case that the autoTrace parameter is set for the current
* test method, this will also start the PerfTrace facility automatically.
*
- * @param willTestRun Whether or not this test will actually be run.
* @return A specially formatted string that contains which JSON perf markers to look at. This
* will be analyzed by the perf test harness.
*/
@SuppressFBWarnings({
- "REC_CATCH_EXCEPTION",
- "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
- })
- private String setupPotentialPerfTest() {
- File perfFile = getInstrumentation().getTargetContext().getFileStreamPath(
+ "REC_CATCH_EXCEPTION", "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", })
+ String setupPotentialPerfTest() {
+ File perfFile = mCallback.getInstrumentation().getTargetContext().getFileStreamPath(
PERF_OUTPUT_FILE);
perfFile.delete();
PerfTraceEvent.setOutputFile(perfFile);
@@ -807,7 +692,7 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
String perfAnnotationString = "";
try {
- Method method = getClass().getMethod(getName(), (Class[]) null);
+ Method method = getClass().getMethod(mCallback.getTestName(), (Class[]) null);
PerfTest annotation = method.getAnnotation(PerfTest.class);
if (annotation != null) {
StringBuilder annotationData = new StringBuilder();
@@ -816,8 +701,8 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
// Grab the minimum number of trace calls we will track (if names(),
// graphNames(), and graphValues() do not have the same number of elements, we
// will track as many as we can given the data available.
- final int maxIndex = Math.min(annotation.traceNames().length, Math.min(
- annotation.graphNames().length, annotation.seriesNames().length));
+ final int maxIndex = Math.min(annotation.traceNames().length,
+ Math.min(annotation.graphNames().length, annotation.seriesNames().length));
List<String> allNames = new LinkedList<>();
for (int i = 0; i < maxIndex; ++i) {
@@ -827,9 +712,12 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
String graphName = annotation.graphNames()[i].replaceAll("[,;]", "-");
String seriesName = annotation.seriesNames()[i].replaceAll("[,;]", "-");
if (annotation.traceTiming()) {
- annotationData.append(name).append(",")
- .append(graphName).append(",")
- .append(seriesName).append(';');
+ annotationData.append(name)
+ .append(",")
+ .append(graphName)
+ .append(",")
+ .append(seriesName)
+ .append(';');
}
// If memory tracing is enabled, add an additional graph for each one
@@ -841,9 +729,12 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
String memName = PerfTraceEvent.makeMemoryTraceNameFromTimingName(name);
String memGraphName = PerfTraceEvent.makeSafeTraceName(
graphName, MEMORY_TRACE_GRAPH_SUFFIX);
- annotationData.append(memName).append(",")
- .append(memGraphName).append(",")
- .append(seriesName).append(';');
+ annotationData.append(memName)
+ .append(",")
+ .append(memGraphName)
+ .append(",")
+ .append(seriesName)
+ .append(';');
allNames.add(memName);
}
}
@@ -877,9 +768,9 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
* @param perfTagAnalysisString A specially formatted string that tells the perf test harness
* which perf tags to analyze.
*/
- private void endPerfTest(String perfTagAnalysisString) {
+ void endPerfTest(String perfTagAnalysisString) {
try {
- Method method = getClass().getMethod(getName(), (Class[]) null);
+ Method method = getClass().getMethod(mCallback.getTestName(), (Class[]) null);
PerfTest annotation = method.getAnnotation(PerfTest.class);
if (annotation != null) {
if (PerfTraceEvent.enabled()) {
@@ -892,4 +783,12 @@ public abstract class ChromeActivityTestCaseBase<T extends ChromeActivity>
// Eat exception here.
}
}
+
+ public interface ChromeTestCommonCallback<T extends ChromeActivity> {
+ String getTestName();
+ void setActivity(T t);
+ Instrumentation getInstrumentation();
+ void setActivityInitialTouchMode(boolean touchMode);
+ T getActivity();
+ }
}

Powered by Google App Engine
This is Rietveld 408576698