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

Side by Side Diff: content/shell/android/javatests/src/org/chromium/content_shell_apk/ContentShellTestBase.java

Issue 2632043002: Create ContentShellActivityTestRule and BaseJUnitRunner (Closed)
Patch Set: Refactor to TestBase and TestRule to use same delegate class (Only ContentShellTestBase) Created 3 years, 9 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 unified diff | Download patch
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package org.chromium.content_shell_apk; 5 package org.chromium.content_shell_apk;
6 6
7 import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
8
9 import android.annotation.TargetApi;
10 import android.content.ComponentName;
11 import android.content.Context;
12 import android.content.Intent;
13 import android.net.Uri;
14 import android.os.Build;
15 import android.os.PowerManager;
16 import android.text.TextUtils;
17 import android.view.ViewGroup;
18
19 import org.chromium.base.ThreadUtils;
20 import org.chromium.base.test.BaseActivityInstrumentationTestCase; 7 import org.chromium.base.test.BaseActivityInstrumentationTestCase;
21 import org.chromium.base.test.util.CallbackHelper; 8 import org.chromium.base.test.util.CallbackHelper;
22 import org.chromium.base.test.util.CommandLineFlags; 9 import org.chromium.base.test.util.CommandLineFlags;
23 import org.chromium.base.test.util.UrlUtils; 10 import org.chromium.base.test.util.UrlUtils;
24 import org.chromium.content.browser.ContentView; 11 import org.chromium.content.browser.ContentView;
25 import org.chromium.content.browser.ContentViewCore; 12 import org.chromium.content.browser.ContentViewCore;
26 import org.chromium.content.browser.test.util.Criteria;
27 import org.chromium.content.browser.test.util.CriteriaHelper;
28 import org.chromium.content.browser.test.util.TestCallbackHelperContainer; 13 import org.chromium.content.browser.test.util.TestCallbackHelperContainer;
29 import org.chromium.content.common.ContentSwitches; 14 import org.chromium.content.common.ContentSwitches;
30 import org.chromium.content_public.browser.LoadUrlParams; 15 import org.chromium.content_public.browser.LoadUrlParams;
31 import org.chromium.content_public.browser.NavigationController; 16 import org.chromium.content_public.browser.NavigationController;
32 import org.chromium.content_public.browser.WebContents; 17 import org.chromium.content_public.browser.WebContents;
33 import org.chromium.content_shell.Shell; 18 import org.chromium.content_shell.Shell;
19 import org.chromium.content_shell_apk.ContentShellActivityTestRule.RerunWithUpda tedContainerView;
34 20
35 import java.lang.annotation.ElementType;
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.lang.annotation.Target;
39 import java.lang.reflect.AnnotatedElement; 21 import java.lang.reflect.AnnotatedElement;
40 import java.util.concurrent.Callable;
41 import java.util.concurrent.ExecutionException; 22 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.TimeUnit;
43 23
44 /** 24 /**
45 * Base test class for all ContentShell based tests. 25 * Base test class for all ContentShell based tests.
46 */ 26 */
47 @CommandLineFlags.Add(ContentSwitches.ENABLE_TEST_INTENTS) 27 @CommandLineFlags.Add(ContentSwitches.ENABLE_TEST_INTENTS)
48 public class ContentShellTestBase 28 public class ContentShellTestBase
49 extends BaseActivityInstrumentationTestCase<ContentShellActivity> { 29 extends BaseActivityInstrumentationTestCase<ContentShellActivity> {
50 /** The maximum time the waitForActiveShellToBeDoneLoading method will wait. */ 30 private final ContentShellTestBaseDelegate mDelegate;
51 private static final long WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT = scaleTimeo ut(10000); 31 protected static final long WAIT_PAGE_LOADING_TIMEOUT_SECONDS =
52 32 ContentShellTestBaseDelegate.WAIT_PAGE_LOADING_TIMEOUT_SECONDS;
53 protected static final long WAIT_PAGE_LOADING_TIMEOUT_SECONDS = scaleTimeout (15);
54 33
55 public ContentShellTestBase() { 34 public ContentShellTestBase() {
56 super(ContentShellActivity.class); 35 super(ContentShellActivity.class);
36 mDelegate = new ContentShellTestBaseDelegate();
57 } 37 }
58 38
59 @Override 39 @Override
60 protected void setUp() throws Exception { 40 protected void setUp() throws Exception {
61 super.setUp(); 41 super.setUp();
62 assertScreenIsOn(); 42 mDelegate.assertScreenIsOn(getInstrumentation());
63 }
64
65 @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
66 @SuppressWarnings("deprecation")
67 private void assertScreenIsOn() {
68 PowerManager pm = (PowerManager) getInstrumentation().getContext().getSy stemService(
69 Context.POWER_SERVICE);
70
71 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
72 assertTrue("Many tests will fail if the screen is not on.", pm.isInt eractive());
73 } else {
74 assertTrue("Many tests will fail if the screen is not on.", pm.isScr eenOn());
75 }
76 } 43 }
77 44
78 /** 45 /**
79 * Starts the ContentShell activity and loads the given URL. 46 * Starts the ContentShell activity and loads the given URL.
80 * The URL can be null, in which case will default to ContentShellActivity.D EFAULT_SHELL_URL. 47 * The URL can be null, in which case will default to ContentShellActivity.D EFAULT_SHELL_URL.
81 */ 48 */
82 protected ContentShellActivity launchContentShellWithUrl(String url) { 49 protected ContentShellActivity launchContentShellWithUrl(String url) {
83 Intent intent = new Intent(Intent.ACTION_MAIN); 50 setActivityIntent(
84 intent.addCategory(Intent.CATEGORY_LAUNCHER); 51 mDelegate.getActivityLaunchIntent(getInstrumentation().getTarget Context(), url));
85 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
86 if (url != null) intent.setData(Uri.parse(url));
87 intent.setComponent(new ComponentName(getInstrumentation().getTargetCont ext(),
88 ContentShellActivity.class));
89 setActivityIntent(intent);
90 return getActivity(); 52 return getActivity();
91 } 53 }
92 54
93 // TODO(cjhopman): These functions are inconsistent with launchContentShell* **. Should be 55 // TODO(cjhopman): These functions are inconsistent with launchContentShell* **. Should be
94 // startContentShell*** and should use the url exactly without the getTestFi leUrl call. Possibly 56 // startContentShell*** and should use the url exactly without the getTestFi leUrl call. Possibly
95 // these two ways of starting the activity (launch* and start*) should be me rged into one. 57 // these two ways of starting the activity (launch* and start*) should be me rged into one.
96 /** 58 /**
97 * Starts the content shell activity with the provided test url. 59 * Starts the content shell activity with the provided test url.
98 * The url is synchronously loaded. 60 * The url is synchronously loaded.
99 * @param url Test url to load. 61 * @param url Test url to load.
100 */ 62 */
101 protected void startActivityWithTestUrl(String url) { 63 protected void startActivityWithTestUrl(String url) {
102 launchContentShellWithUrl(UrlUtils.getIsolatedTestFileUrl(url)); 64 launchContentShellWithUrl(UrlUtils.getIsolatedTestFileUrl(url));
103 assertNotNull(getActivity()); 65 assertNotNull(getActivity());
104 waitForActiveShellToBeDoneLoading(); 66 waitForActiveShellToBeDoneLoading();
105 assertEquals(UrlUtils.getIsolatedTestFileUrl(url), 67 assertEquals(UrlUtils.getIsolatedTestFileUrl(url),
106 getContentViewCore().getWebContents().getUrl()); 68 getContentViewCore().getWebContents().getUrl());
107 } 69 }
108 70
109 /** 71 /**
110 * Returns the current ContentViewCore or null if there is no ContentView. 72 * Returns the current ContentViewCore or null if there is no ContentView.
111 */ 73 */
112 protected ContentViewCore getContentViewCore() { 74 protected ContentViewCore getContentViewCore() {
113 return getActivity().getActiveShell().getContentViewCore(); 75 return mDelegate.getContentViewCore(getActivity());
114 } 76 }
115 77
116 /** 78 /**
117 * Returns the WebContents of this Shell. 79 * Returns the WebContents of this Shell.
118 */ 80 */
119 protected WebContents getWebContents() { 81 protected WebContents getWebContents() {
120 return getActivity().getActiveShell().getWebContents(); 82 return mDelegate.getWebContents(getActivity());
121 } 83 }
122 84
123 /** 85 /**
124 * Waits for the Active shell to finish loading. This times out after 86 * Waits for the Active shell to finish loading. This times out after
125 * WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT milliseconds and it shouldn't be us ed for long 87 * WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT milliseconds and it shouldn't be us ed for long
126 * loading pages. Instead it should be used more for test initialization. Th e proper way 88 * loading pages. Instead it should be used more for test initialization. Th e proper way
127 * to wait is to use a TestCallbackHelperContainer after the initial load is completed. 89 * to wait is to use a TestCallbackHelperContainer after the initial load is completed.
128 */ 90 */
129 protected void waitForActiveShellToBeDoneLoading() { 91 protected void waitForActiveShellToBeDoneLoading() {
130 final ContentShellActivity activity = getActivity(); 92 mDelegate.waitForActiveShellToBeDoneLoading(getActivity());
131
132 // Wait for the Content Shell to be initialized.
133 CriteriaHelper.pollUiThread(new Criteria() {
134 @Override
135 public boolean isSatisfied() {
136 Shell shell = activity.getActiveShell();
137 // There are two cases here that need to be accounted for.
138 // The first is that we've just created a Shell and it isn't
139 // loading because it has no URL set yet. The second is that
140 // we've set a URL and it actually is loading.
141 if (shell == null) {
142 updateFailureReason("Shell is null.");
143 return false;
144 }
145 if (shell.isLoading()) {
146 updateFailureReason("Shell is still loading.");
147 return false;
148 }
149 if (TextUtils.isEmpty(shell.getContentViewCore().getWebContents( ).getUrl())) {
150 updateFailureReason("Shell's URL is empty or null.");
151 return false;
152 }
153 return true;
154 }
155 }, WAIT_FOR_ACTIVE_SHELL_LOADING_TIMEOUT, CriteriaHelper.DEFAULT_POLLING _INTERVAL);
156 } 93 }
157 94
158 /** 95 /**
159 * Creates a new {@link Shell} and waits for it to finish loading. 96 * Creates a new {@link Shell} and waits for it to finish loading.
160 * @param url The URL to create the new {@link Shell} with. 97 * @param url The URL to create the new {@link Shell} with.
161 * @return A new instance of a {@link Shell}. 98 * @return A new instance of a {@link Shell}.
162 * @throws ExecutionException 99 * @throws ExecutionException
163 */ 100 */
164 protected Shell loadNewShell(final String url) throws ExecutionException { 101 protected Shell loadNewShell(String url) throws ExecutionException {
165 Shell shell = ThreadUtils.runOnUiThreadBlocking(new Callable<Shell>() { 102 return mDelegate.loadNewShell(getActivity(), url);
166 @Override
167 public Shell call() {
168 getActivity().getShellManager().launchShell(url);
169 return getActivity().getActiveShell();
170 }
171 });
172
173 assertNotNull("Unable to create shell.", shell);
174 assertEquals("Active shell unexpected.", shell, getActivity().getActiveS hell());
175
176 waitForActiveShellToBeDoneLoading();
177
178 return shell;
179 } 103 }
180 /** 104 /**
181 * Loads a URL in the specified content view. 105 * Loads a URL in the specified content view.
182 * 106 *
183 * @param navigationController The navigation controller to load the URL in. 107 * @param navigationController The navigation controller to load the URL in.
184 * @param callbackHelperContainer The callback helper container used to moni tor progress. 108 * @param callbackHelperContainer The callback helper container used to moni tor progress.
185 * @param params The URL params to use. 109 * @param params The URL params to use.
186 */ 110 */
187 protected void loadUrl( 111 protected void loadUrl(
188 final NavigationController navigationController, 112 final NavigationController navigationController,
(...skipping 10 matching lines...) Expand all
199 } 123 }
200 124
201 /** 125 /**
202 * Handles performing an action on the UI thread that will return when the s pecified callback 126 * Handles performing an action on the UI thread that will return when the s pecified callback
203 * is incremented. 127 * is incremented.
204 * 128 *
205 * @param callbackHelper The callback helper that will be blocked on. 129 * @param callbackHelper The callback helper that will be blocked on.
206 * @param action The action to be performed on the UI thread. 130 * @param action The action to be performed on the UI thread.
207 */ 131 */
208 protected void handleBlockingCallbackAction( 132 protected void handleBlockingCallbackAction(
209 CallbackHelper callbackHelper, Runnable action) throws Throwable { 133 CallbackHelper callbackHelper, final Runnable action) throws Throwab le {
210 int currentCallCount = callbackHelper.getCallCount(); 134 Runnable uiThreadRunnable = new Runnable() {
211 runTestOnUiThread(action); 135 @Override
212 callbackHelper.waitForCallback( 136 public void run() {
213 currentCallCount, 1, WAIT_PAGE_LOADING_TIMEOUT_SECONDS, TimeUnit .SECONDS); 137 try {
138 runTestOnUiThread(action);
139 } catch (Throwable e) {
140 throw new RuntimeException("Unable to run on Ui Thread", e);
141 }
142 }
143 };
144 mDelegate.handleBlockingCallbackAction(callbackHelper, uiThreadRunnable) ;
214 } 145 }
215 146
216 // TODO(aelias): This method needs to be removed once http://crbug.com/17951 1 is fixed. 147 // TODO(aelias): This method needs to be removed once http://crbug.com/17951 1 is fixed.
217 // Meanwhile, we have to wait if the page has the <meta viewport> tag. 148 // Meanwhile, we have to wait if the page has the <meta viewport> tag.
218 /** 149 /**
219 * Waits till the ContentViewCore receives the expected page scale factor 150 * Waits till the ContentViewCore receives the expected page scale factor
220 * from the compositor and asserts that this happens. 151 * from the compositor and asserts that this happens.
221 */ 152 */
222 protected void assertWaitForPageScaleFactorMatch(float expectedScale) { 153 protected void assertWaitForPageScaleFactorMatch(float expectedScale) {
223 CriteriaHelper.pollInstrumentationThread( 154 mDelegate.assertWaitForPageScaleFactorMatch(getContentViewCore(), expect edScale);
224 Criteria.equals(expectedScale, new Callable<Float>() {
225 @Override
226 public Float call() {
227 return getContentViewCore().getScale();
228 }
229 }));
230 } 155 }
231 156
232 /** 157 /**
233 * Replaces the {@link ContentViewCore#mContainerView} with a newly created 158 * Replaces the {@link ContentViewCore#mContainerView} with a newly created
234 * {@link ContentView}. 159 * {@link ContentView}.
235 */ 160 */
236 @SuppressWarnings("javadoc") 161 @SuppressWarnings("javadoc")
237 protected void replaceContainerView() throws Throwable { 162 protected void replaceContainerView() throws Throwable {
238 ThreadUtils.runOnUiThreadBlocking(new Runnable() { 163 mDelegate.replaceContainerView(getActivity());
239 @Override
240 public void run() {
241 ContentView cv = ContentView.createContentView(getActivity(), ge tContentViewCore());
242 ((ViewGroup) getContentViewCore().getContainerView().getParent() ).addView(cv);
243 getContentViewCore().setContainerView(cv);
244 getContentViewCore().setContainerViewInternals(cv);
245 cv.requestFocus();
246 }
247 });
248 } 164 }
249 165
250 @Override 166 @Override
251 protected void runTest() throws Throwable { 167 protected void runTest() throws Throwable {
252 super.runTest(); 168 super.runTest();
253 try { 169 try {
254 AnnotatedElement method = getClass().getMethod(getName(), (Class[]) null); 170 AnnotatedElement method = getClass().getMethod(getName(), (Class[]) null);
255 if (method.isAnnotationPresent(RerunWithUpdatedContainerView.class)) { 171 if (method.isAnnotationPresent(RerunWithUpdatedContainerView.class)) {
256 replaceContainerView(); 172 replaceContainerView();
257 super.runTest(); 173 super.runTest();
258 } 174 }
259 } catch (Throwable e) { 175 } catch (Throwable e) {
260 throw new Throwable("@RerunWithUpdatedContainerView failed." 176 throw new Throwable("@RerunWithUpdatedContainerView failed."
261 + " See ContentShellTestBase#runTest.", e); 177 + " See ContentShellTestBase#runTest.", e);
262 } 178 }
263 } 179 }
264
265 /**
266 * Annotation for tests that should be executed a second time after replacin g
267 * the ContentViewCore's container view (see {@link #runTest()}).
268 *
269 * <p>Please note that {@link #setUp()} is only invoked once before both run s,
270 * and that any state changes produced by the first run are visible to the s econd run.
271 */
272 @Target(ElementType.METHOD)
273 @Retention(RetentionPolicy.RUNTIME)
274 public @interface RerunWithUpdatedContainerView {
275 }
276 } 180 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698