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

Side by Side Diff: android_webview/javatests/src/org/chromium/android_webview/test/AwTestBase.java

Issue 2933623002: Create AwJUnit4ClassRunner AwActivityTestRule and convert AwContentsTest (Closed)
Patch Set: address bo's comments Created 3 years, 4 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.android_webview.test; 5 package org.chromium.android_webview.test;
6 6
7 import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; 7 import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
8 8
9 import android.app.Instrumentation; 9 import android.app.Instrumentation;
10 import android.content.Context; 10 import android.content.Context;
11 import android.os.Build; 11 import android.os.Build;
12 import android.util.AndroidRuntimeException;
13 import android.util.Log;
14 import android.view.ViewGroup; 12 import android.view.ViewGroup;
15 13
16 import org.chromium.android_webview.AwBrowserContext; 14 import org.chromium.android_webview.AwBrowserContext;
17 import org.chromium.android_webview.AwBrowserProcess;
18 import org.chromium.android_webview.AwContents; 15 import org.chromium.android_webview.AwContents;
19 import org.chromium.android_webview.AwContents.DependencyFactory; 16 import org.chromium.android_webview.AwContents.DependencyFactory;
20 import org.chromium.android_webview.AwContents.InternalAccessDelegate; 17 import org.chromium.android_webview.AwContents.InternalAccessDelegate;
21 import org.chromium.android_webview.AwContents.NativeDrawGLFunctorFactory; 18 import org.chromium.android_webview.AwContents.NativeDrawGLFunctorFactory;
22 import org.chromium.android_webview.AwContentsClient; 19 import org.chromium.android_webview.AwContentsClient;
23 import org.chromium.android_webview.AwSettings; 20 import org.chromium.android_webview.AwSettings;
24 import org.chromium.android_webview.AwSwitches; 21 import org.chromium.android_webview.AwSwitches;
25 import org.chromium.android_webview.test.util.GraphicsTestUtils; 22 import org.chromium.android_webview.test.AwTestCommon.AwTestCommonCallback;
26 import org.chromium.android_webview.test.util.JSUtils; 23 import org.chromium.base.Log;
27 import org.chromium.base.ThreadUtils;
28 import org.chromium.base.test.BaseActivityInstrumentationTestCase; 24 import org.chromium.base.test.BaseActivityInstrumentationTestCase;
29 import org.chromium.base.test.util.CallbackHelper; 25 import org.chromium.base.test.util.CallbackHelper;
30 import org.chromium.base.test.util.InMemorySharedPreferences; 26 import org.chromium.base.test.util.InMemorySharedPreferences;
31 import org.chromium.base.test.util.MinAndroidSdkLevel; 27 import org.chromium.base.test.util.MinAndroidSdkLevel;
32 import org.chromium.base.test.util.parameter.CommandLineParameter; 28 import org.chromium.base.test.util.parameter.CommandLineParameter;
33 import org.chromium.content.browser.test.util.Criteria;
34 import org.chromium.content.browser.test.util.CriteriaHelper;
35 import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPage FinishedHelper;
36 import org.chromium.content_public.browser.LoadUrlParams;
37 import org.chromium.net.test.util.TestWebServer; 29 import org.chromium.net.test.util.TestWebServer;
38 30
39 import java.lang.annotation.Annotation; 31 import java.lang.annotation.Annotation;
40 import java.lang.reflect.AnnotatedElement; 32 import java.lang.reflect.AnnotatedElement;
41 import java.lang.reflect.Method; 33 import java.lang.reflect.Method;
42 import java.util.Map; 34 import java.util.Map;
43 import java.util.concurrent.Callable; 35 import java.util.concurrent.Callable;
44 import java.util.concurrent.FutureTask;
45 import java.util.concurrent.TimeUnit;
46 import java.util.regex.Matcher;
47 import java.util.regex.Pattern;
48 36
49 /** 37 /**
50 * A base class for android_webview tests. WebView only runs on KitKat and later , 38 * A base class for android_webview tests. WebView only runs on KitKat and
51 * so make sure no one attempts to run the tests on earlier OS releases. 39 * later, so make sure no one attempts to run the tests on earlier OS releases.
52 * 40 * By default, all tests run both in single-process mode, and with sandboxed
53 * By default, all tests run both in single-process mode, and with sandboxed ren derer. 41 * renderer. If a test doesn't yet work with sandboxed renderer, an entire
54 * If a test doesn't yet work with sandboxed renderer, an entire class, or an in dividual test 42 * class, or an individual test method can be marked for single-process testing
55 * method can be marked for single-process testing only by adding the following annotation: 43 * only by adding @SkipCommandLineParameterization to the test
56 *
57 * @SkipCommandLineParameterization
58 */ 44 */
59 @MinAndroidSdkLevel(Build.VERSION_CODES.KITKAT) 45 @MinAndroidSdkLevel(Build.VERSION_CODES.KITKAT)
60 @CommandLineParameter({"", AwSwitches.WEBVIEW_SANDBOXED_RENDERER}) 46 @CommandLineParameter({"", AwSwitches.WEBVIEW_SANDBOXED_RENDERER})
61 public class AwTestBase extends BaseActivityInstrumentationTestCase<AwTestRunner Activity> { 47 public class AwTestBase extends BaseActivityInstrumentationTestCase<AwTestRunner Activity>
48 implements AwTestCommonCallback {
49 private static final String TAG = "AwTestBase";
50
62 public static final long WAIT_TIMEOUT_MS = scaleTimeout(15000); 51 public static final long WAIT_TIMEOUT_MS = scaleTimeout(15000);
52
63 public static final int CHECK_INTERVAL = 100; 53 public static final int CHECK_INTERVAL = 100;
64 private static final String TAG = "AwTestBase";
65 private static final Pattern MAYBE_QUOTED_STRING = Pattern.compile("^(\"?)(. *)\\1$");
66 54
67 // The browser context needs to be a process-wide singleton. 55 private final AwTestCommon mTestCommon;
68 private AwBrowserContext mBrowserContext;
69 56
70 public AwTestBase() { 57 public AwTestBase() {
71 super(AwTestRunnerActivity.class); 58 super(AwTestRunnerActivity.class);
59 mTestCommon = new AwTestCommon(this);
72 } 60 }
73 61
74 @Override 62 @Override
75 protected void setUp() throws Exception { 63 protected void setUp() throws Exception {
76 if (needsAwBrowserContextCreated()) { 64 mTestCommon.setUp();
77 createAwBrowserContext();
78 }
79
80 super.setUp();
81 if (needsBrowserProcessStarted()) {
82 startBrowserProcess();
83 }
84 } 65 }
85 66
86 protected void createAwBrowserContext() { 67 protected void createAwBrowserContext() {
87 if (mBrowserContext != null) { 68 mTestCommon.createAwBrowserContext();
88 throw new AndroidRuntimeException("There should only be one browser context.");
89 }
90 getActivity(); // The Activity must be launched in order to load native code
91 final InMemorySharedPreferences prefs = new InMemorySharedPreferences();
92 final Context appContext = getInstrumentation().getTargetContext().getAp plicationContext();
93 getInstrumentation().runOnMainSync(new Runnable() {
94 @Override
95 public void run() {
96 mBrowserContext = createAwBrowserContextOnUiThread(prefs, appCon text);
97 }
98 });
99 } 69 }
100 70
101 protected AwBrowserContext createAwBrowserContextOnUiThread( 71 protected AwBrowserContext createAwBrowserContextOnUiThread(
102 InMemorySharedPreferences prefs, Context appContext) { 72 InMemorySharedPreferences prefs, Context appContext) {
103 return new AwBrowserContext(prefs, appContext); 73 return mTestCommon.createAwBrowserContextOnUiThread(prefs, appContext);
104 } 74 }
105 75
106 protected void startBrowserProcess() throws Exception { 76 protected void startBrowserProcess() throws Exception {
107 // The Activity must be launched in order for proper webview statics to be setup. 77 mTestCommon.startBrowserProcess();
108 getActivity();
109 getInstrumentation().runOnMainSync(new Runnable() {
110 @Override
111 public void run() {
112 AwBrowserProcess.start();
113 }
114 });
115 } 78 }
116 79
117 /** 80 /**
118 * Override this to return false if the test doesn't want to create an AwBro wserContext 81 * Override this to return false if the test doesn't want to create an
119 * automatically. 82 * AwBrowserContext automatically.
120 */ 83 */
121 protected boolean needsAwBrowserContextCreated() { 84 protected boolean needsAwBrowserContextCreated() {
122 return true; 85 return mTestCommon.needsAwBrowserContextCreated();
123 } 86 }
124 87
125 /** 88 /**
126 * Override this to return false if the test doesn't want the browser startu p sequence to 89 * Override this to return false if the test doesn't want the browser
127 * be run automatically. 90 * startup sequence to be run automatically.
128 * @return Whether the instrumentation test requires the browser process to already be started. 91 *
92 * @return Whether the instrumentation test requires the browser process to
93 * already be started.
129 */ 94 */
130 protected boolean needsBrowserProcessStarted() { 95 protected boolean needsBrowserProcessStarted() {
131 return true; 96 return mTestCommon.needsBrowserProcessStarted();
132 } 97 }
133 98
134 /** 99 /**
135 * Runs a {@link Callable} on the main thread, blocking until it is 100 * Runs a {@link Callable} on the main thread, blocking until it is
136 * complete, and returns the result. Calls 101 * complete, and returns the result. Calls
137 * {@link Instrumentation#waitForIdleSync()} first to help avoid certain 102 * {@link Instrumentation#waitForIdleSync()} first to help avoid certain
138 * race conditions. 103 * race conditions.
139 * 104 *
140 * @param <R> Type of result to return 105 * @param <R> Type of result to return
141 */ 106 */
142 public <R> R runTestOnUiThreadAndGetResult(Callable<R> callable) 107 public <R> R runTestOnUiThreadAndGetResult(Callable<R> callable)
143 throws Exception { 108 throws Exception {
144 FutureTask<R> task = new FutureTask<R>(callable); 109 return mTestCommon.runTestOnUiThreadAndGetResult(callable);
145 getInstrumentation().runOnMainSync(task);
146 return task.get();
147 } 110 }
148 111
149 public void enableJavaScriptOnUiThread(final AwContents awContents) { 112 public void enableJavaScriptOnUiThread(final AwContents awContents) {
150 getInstrumentation().runOnMainSync(new Runnable() { 113 mTestCommon.enableJavaScriptOnUiThread(awContents);
151 @Override
152 public void run() {
153 awContents.getSettings().setJavaScriptEnabled(true);
154 }
155 });
156 } 114 }
157 115
158 public void setNetworkAvailableOnUiThread(final AwContents awContents, 116 public void setNetworkAvailableOnUiThread(final AwContents awContents,
159 final boolean networkUp) { 117 final boolean networkUp) {
160 getInstrumentation().runOnMainSync(new Runnable() { 118 mTestCommon.setNetworkAvailableOnUiThread(awContents, networkUp);
161 @Override
162 public void run() {
163 awContents.setNetworkAvailable(networkUp);
164 }
165 });
166 } 119 }
167 120
168 /** 121 /**
169 * Loads url on the UI thread and blocks until onPageFinished is called. 122 * Loads url on the UI thread and blocks until onPageFinished is called.
170 */ 123 */
171 public void loadUrlSync(final AwContents awContents, 124 public void loadUrlSync(final AwContents awContents,
172 CallbackHelper onPageFinishedHelper, 125 CallbackHelper onPageFinishedHelper,
173 final String url) throws Exception { 126 final String url) throws Exception {
174 loadUrlSync(awContents, onPageFinishedHelper, url, null); 127 mTestCommon.loadUrlSync(awContents, onPageFinishedHelper, url);
175 } 128 }
176 129
177 public void loadUrlSync(final AwContents awContents, 130 public void loadUrlSync(final AwContents awContents,
178 CallbackHelper onPageFinishedHelper, 131 CallbackHelper onPageFinishedHelper,
179 final String url, 132 final String url,
180 final Map<String, String> extraHeaders) throws Exception { 133 final Map<String, String> extraHeaders) throws Exception {
181 int currentCallCount = onPageFinishedHelper.getCallCount(); 134 mTestCommon.loadUrlSync(awContents, onPageFinishedHelper, url, extraHead ers);
182 loadUrlAsync(awContents, url, extraHeaders);
183 onPageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_M S,
184 TimeUnit.MILLISECONDS);
185 } 135 }
186 136
187 public void loadUrlSyncAndExpectError(final AwContents awContents, 137 public void loadUrlSyncAndExpectError(final AwContents awContents,
188 CallbackHelper onPageFinishedHelper, 138 CallbackHelper onPageFinishedHelper,
189 CallbackHelper onReceivedErrorHelper, 139 CallbackHelper onReceivedErrorHelper,
190 final String url) throws Exception { 140 final String url) throws Exception {
191 int onErrorCallCount = onReceivedErrorHelper.getCallCount(); 141 mTestCommon.loadUrlSyncAndExpectError(
192 int onFinishedCallCount = onPageFinishedHelper.getCallCount(); 142 awContents, onPageFinishedHelper, onReceivedErrorHelper, url);
193 loadUrlAsync(awContents, url);
194 onReceivedErrorHelper.waitForCallback(onErrorCallCount, 1, WAIT_TIMEOUT_ MS,
195 TimeUnit.MILLISECONDS);
196 onPageFinishedHelper.waitForCallback(onFinishedCallCount, 1, WAIT_TIMEOU T_MS,
197 TimeUnit.MILLISECONDS);
198 } 143 }
199 144
200 /** 145 /**
201 * Loads url on the UI thread but does not block. 146 * Loads url on the UI thread but does not block.
202 */ 147 */
203 public void loadUrlAsync(final AwContents awContents, 148 public void loadUrlAsync(final AwContents awContents,
204 final String url) throws Exception { 149 final String url) throws Exception {
205 loadUrlAsync(awContents, url, null); 150 mTestCommon.loadUrlAsync(awContents, url);
206 } 151 }
207 152
208 public void loadUrlAsync(final AwContents awContents, 153 public void loadUrlAsync(final AwContents awContents,
209 final String url, 154 final String url,
210 final Map<String, String> extraHeaders) { 155 final Map<String, String> extraHeaders) {
211 getInstrumentation().runOnMainSync(new Runnable() { 156 mTestCommon.loadUrlAsync(awContents, url, extraHeaders);
212 @Override
213 public void run() {
214 awContents.loadUrl(url, extraHeaders);
215 }
216 });
217 } 157 }
218 158
219 /** 159 /**
220 * Posts url on the UI thread and blocks until onPageFinished is called. 160 * Posts url on the UI thread and blocks until onPageFinished is called.
221 */ 161 */
222 public void postUrlSync(final AwContents awContents, 162 public void postUrlSync(final AwContents awContents,
223 CallbackHelper onPageFinishedHelper, final String url, 163 CallbackHelper onPageFinishedHelper, final String url,
224 byte[] postData) throws Exception { 164 byte[] postData) throws Exception {
225 int currentCallCount = onPageFinishedHelper.getCallCount(); 165 mTestCommon.postUrlSync(awContents, onPageFinishedHelper, url, postData) ;
226 postUrlAsync(awContents, url, postData);
227 onPageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_M S,
228 TimeUnit.MILLISECONDS);
229 } 166 }
230 167
231 /** 168 /**
232 * Loads url on the UI thread but does not block. 169 * Loads url on the UI thread but does not block.
233 */ 170 */
234 public void postUrlAsync(final AwContents awContents, 171 public void postUrlAsync(final AwContents awContents,
235 final String url, byte[] postData) throws Exception { 172 final String url, byte[] postData) throws Exception {
236 class PostUrl implements Runnable { 173 mTestCommon.postUrlAsync(awContents, url, postData);
237 byte[] mPostData;
238 public PostUrl(byte[] postData) {
239 mPostData = postData;
240 }
241 @Override
242 public void run() {
243 awContents.postUrl(url, mPostData);
244 }
245 }
246 getInstrumentation().runOnMainSync(new PostUrl(postData));
247 } 174 }
248 175
249 /** 176 /**
250 * Loads data on the UI thread and blocks until onPageFinished is called. 177 * Loads data on the UI thread and blocks until onPageFinished is called.
251 */ 178 */
252 public void loadDataSync(final AwContents awContents, 179 public void loadDataSync(final AwContents awContents,
253 CallbackHelper onPageFinishedHelper, 180 CallbackHelper onPageFinishedHelper,
254 final String data, final String mimeType, 181 final String data, final String mimeType,
255 final boolean isBase64Encoded) throws Exception { 182 final boolean isBase64Encoded) throws Exception {
256 int currentCallCount = onPageFinishedHelper.getCallCount(); 183 mTestCommon.loadDataSync(awContents, onPageFinishedHelper, data, mimeTyp e, isBase64Encoded);
257 loadDataAsync(awContents, data, mimeType, isBase64Encoded);
258 onPageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_M S,
259 TimeUnit.MILLISECONDS);
260 } 184 }
261 185
262 public void loadDataSyncWithCharset(final AwContents awContents, 186 public void loadDataSyncWithCharset(final AwContents awContents,
263 CallbackHelper onPageFinishedHelper, 187 CallbackHelper onPageFinishedHelper,
264 final String data, final String mimeType, 188 final String data, final String mimeType,
265 final boolean isBase64Encoded, final String charset) 189 final boolean isBase64Encoded, final String charset)
266 throws Exception { 190 throws Exception {
267 int currentCallCount = onPageFinishedHelper.getCallCount(); 191 mTestCommon.loadDataSyncWithCharset(
268 getInstrumentation().runOnMainSync(new Runnable() { 192 awContents, onPageFinishedHelper, data, mimeType, isBase64Encode d, charset);
269 @Override
270 public void run() {
271 awContents.loadUrl(LoadUrlParams.createLoadDataParams(
272 data, mimeType, isBase64Encoded, charset));
273 }
274 });
275 onPageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_M S,
276 TimeUnit.MILLISECONDS);
277 } 193 }
278 194
279 /** 195 /**
280 * Loads data on the UI thread but does not block. 196 * Loads data on the UI thread but does not block.
281 */ 197 */
282 public void loadDataAsync(final AwContents awContents, final String data, 198 public void loadDataAsync(final AwContents awContents, final String data,
283 final String mimeType, final boolean isBase64Encoded) 199 final String mimeType, final boolean isBase64Encoded)
284 throws Exception { 200 throws Exception {
285 getInstrumentation().runOnMainSync(new Runnable() { 201 mTestCommon.loadDataAsync(awContents, data, mimeType, isBase64Encoded);
286 @Override
287 public void run() {
288 awContents.loadData(data, mimeType, isBase64Encoded ? "base64" : null);
289 }
290 });
291 } 202 }
292 203
293 public void loadDataWithBaseUrlSync(final AwContents awContents, 204 public void loadDataWithBaseUrlSync(final AwContents awContents,
294 CallbackHelper onPageFinishedHelper, final String data, final String mimeType, 205 CallbackHelper onPageFinishedHelper, final String data, final String mimeType,
295 final boolean isBase64Encoded, final String baseUrl, 206 final boolean isBase64Encoded, final String baseUrl,
296 final String historyUrl) throws Throwable { 207 final String historyUrl) throws Throwable {
297 int currentCallCount = onPageFinishedHelper.getCallCount(); 208 mTestCommon.loadDataWithBaseUrlSync(awContents, onPageFinishedHelper, da ta, mimeType,
298 loadDataWithBaseUrlAsync(awContents, data, mimeType, isBase64Encoded, ba seUrl, historyUrl); 209 isBase64Encoded, baseUrl, historyUrl);
299 onPageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_M S,
300 TimeUnit.MILLISECONDS);
301 } 210 }
302 211
303 public void loadDataWithBaseUrlAsync(final AwContents awContents, 212 public void loadDataWithBaseUrlAsync(final AwContents awContents,
304 final String data, final String mimeType, final boolean isBase64Enco ded, 213 final String data, final String mimeType, final boolean isBase64Enco ded,
305 final String baseUrl, final String historyUrl) throws Throwable { 214 final String baseUrl, final String historyUrl) throws Throwable {
306 runTestOnUiThread(new Runnable() { 215 mTestCommon.loadDataWithBaseUrlAsync(
307 @Override 216 awContents, data, mimeType, isBase64Encoded, baseUrl, historyUrl );
308 public void run() {
309 awContents.loadDataWithBaseURL(
310 baseUrl, data, mimeType, isBase64Encoded ? "base64" : nu ll, historyUrl);
311 }
312 });
313 } 217 }
314 218
315 /** 219 /**
316 * Reloads the current page synchronously. 220 * Reloads the current page synchronously.
317 */ 221 */
318 public void reloadSync(final AwContents awContents, 222 public void reloadSync(final AwContents awContents,
319 CallbackHelper onPageFinishedHelper) throws Exception { 223 CallbackHelper onPageFinishedHelper) throws Exception {
320 int currentCallCount = onPageFinishedHelper.getCallCount(); 224 mTestCommon.reloadSync(awContents, onPageFinishedHelper);
321 getInstrumentation().runOnMainSync(new Runnable() {
322 @Override
323 public void run() {
324 awContents.getNavigationController().reload(true);
325 }
326 });
327 onPageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_M S,
328 TimeUnit.MILLISECONDS);
329 } 225 }
330 226
331 /** 227 /**
332 * Stops loading on the UI thread. 228 * Stops loading on the UI thread.
333 */ 229 */
334 public void stopLoading(final AwContents awContents) { 230 public void stopLoading(final AwContents awContents) {
335 getInstrumentation().runOnMainSync(new Runnable() { 231 mTestCommon.stopLoading(awContents);
336 @Override
337 public void run() {
338 awContents.stopLoading();
339 }
340 });
341 } 232 }
342 233
343 public void waitForVisualStateCallback(final AwContents awContents) throws E xception { 234 public void waitForVisualStateCallback(final AwContents awContents) throws E xception {
344 final CallbackHelper ch = new CallbackHelper(); 235 mTestCommon.waitForVisualStateCallback(awContents);
345 final int chCount = ch.getCallCount();
346 getInstrumentation().runOnMainSync(new Runnable() {
347 @Override
348 public void run() {
349 final long requestId = 666;
350 awContents.insertVisualStateCallback(requestId,
351 new AwContents.VisualStateCallback() {
352 @Override
353 public void onComplete(long id) {
354 assertEquals(requestId, id);
355 ch.notifyCalled();
356 }
357 });
358 }
359 });
360 ch.waitForCallback(chCount);
361 } 236 }
362 237
363 public void insertVisualStateCallbackOnUIThread(final AwContents awContents, 238 public void insertVisualStateCallbackOnUIThread(final AwContents awContents,
364 final long requestId, final AwContents.VisualStateCallback callback) { 239 final long requestId, final AwContents.VisualStateCallback callback) {
365 getInstrumentation().runOnMainSync(new Runnable() { 240 mTestCommon.insertVisualStateCallbackOnUIThread(awContents, requestId, c allback);
366 @Override
367 public void run() {
368 awContents.insertVisualStateCallback(requestId, callback);
369 }
370 });
371 } 241 }
372 242
373 // Waits for the pixel at the center of AwContents to color up into expected Color. 243 // Waits for the pixel at the center of AwContents to color up into
374 // Note that this is a stricter condition that waiting for a visual state ca llback, 244 // expectedColor.
375 // as visual state callback only indicates that *something* has appeared in WebView. 245 // Note that this is a stricter condition that waiting for a visual state
246 // callback,
247 // as visual state callback only indicates that *something* has appeared in
248 // WebView.
376 public void waitForPixelColorAtCenterOfView(final AwContents awContents, 249 public void waitForPixelColorAtCenterOfView(final AwContents awContents,
377 final AwTestContainerView testContainerView, final int expectedColor ) throws Exception { 250 final AwTestContainerView testContainerView, final int expectedColor ) throws Exception {
378 pollUiThread(new Callable<Boolean>() { 251 mTestCommon.waitForPixelColorAtCenterOfView(awContents, testContainerVie w, expectedColor);
379 @Override
380 public Boolean call() throws Exception {
381 return GraphicsTestUtils.getPixelColorAtCenterOfView(awContents, testContainerView)
382 == expectedColor;
383 }
384 });
385 }
386
387 /**
388 * Checks the current test has |clazz| annotation. Note this swallows NoSuch MethodException
389 * and returns false in that case.
390 */
391 private boolean testMethodHasAnnotation(Class<? extends Annotation> clazz) {
392 String testName = getName();
393 Method method = null;
394 try {
395 method = getClass().getMethod(testName);
396 } catch (NoSuchMethodException e) {
397 Log.w(TAG, "Test method name not found.", e);
398 return false;
399 }
400
401 // Cast to AnnotatedElement to work around a compilation failure.
402 // Method.isAnnotationPresent() was removed in Java 8 (which is used by the Android N SDK),
403 // so compilation with Java 7 fails. See crbug.com/608792.
404 return ((AnnotatedElement) method).isAnnotationPresent(clazz);
405 }
406
407 /**
408 * Factory class used in creation of test AwContents instances.
409 *
410 * Test cases can provide subclass instances to the createAwTest* methods in order to create an
411 * AwContents instance with injected test dependencies.
412 */
413 public static class TestDependencyFactory extends AwContents.DependencyFacto ry {
414 public AwTestContainerView createAwTestContainerView(AwTestRunnerActivit y activity,
415 boolean allowHardwareAcceleration) {
416 return new AwTestContainerView(activity, allowHardwareAcceleration);
417 }
418 public AwSettings createAwSettings(Context context, boolean supportsLega cyQuirks) {
419 return new AwSettings(context, false /* isAccessFromFileURLsGrantedB yDefault */,
420 supportsLegacyQuirks, false /* allowEmptyDocumentPersistence */,
421 true /* allowGeolocationOnInsecureOrigins */,
422 false /* doNotUpdateSelectionOnMutatingSelectionRange */);
423 }
424
425 public AwContents createAwContents(AwBrowserContext browserContext, View Group containerView,
426 Context context, InternalAccessDelegate internalAccessAdapter,
427 NativeDrawGLFunctorFactory nativeDrawGLFunctorFactory,
428 AwContentsClient contentsClient, AwSettings settings,
429 DependencyFactory dependencyFactory) {
430 return new AwContents(browserContext, containerView, context, intern alAccessAdapter,
431 nativeDrawGLFunctorFactory, contentsClient, settings, depend encyFactory);
432 }
433 } 252 }
434 253
435 protected TestDependencyFactory createTestDependencyFactory() { 254 protected TestDependencyFactory createTestDependencyFactory() {
436 return new TestDependencyFactory(); 255 return mTestCommon.createTestDependencyFactory();
437 } 256 }
438 257
439 public AwTestContainerView createAwTestContainerView( 258 public AwTestContainerView createAwTestContainerView(
440 final AwContentsClient awContentsClient) { 259 final AwContentsClient awContentsClient) {
441 return createAwTestContainerView(awContentsClient, false, null); 260 return mTestCommon.createAwTestContainerView(awContentsClient);
442 } 261 }
443 262
444 public AwTestContainerView createAwTestContainerView(final AwContentsClient awContentsClient, 263 public AwTestContainerView createAwTestContainerView(final AwContentsClient awContentsClient,
445 boolean supportsLegacyQuirks, final TestDependencyFactory testDepend encyFactory) { 264 boolean supportsLegacyQuirks, final TestDependencyFactory testDepend encyFactory) {
446 AwTestContainerView testContainerView = createDetachedAwTestContainerVie w( 265 return mTestCommon.createAwTestContainerView(
447 awContentsClient, supportsLegacyQuirks, testDependencyFactory); 266 awContentsClient, supportsLegacyQuirks, testDependencyFactory);
448 getActivity().addView(testContainerView);
449 testContainerView.requestFocus();
450 return testContainerView;
451 } 267 }
452 268
453 public AwBrowserContext getAwBrowserContext() { 269 public AwBrowserContext getAwBrowserContext() {
454 return mBrowserContext; 270 return mTestCommon.getAwBrowserContext();
455 } 271 }
456 272
457 public AwTestContainerView createDetachedAwTestContainerView( 273 public AwTestContainerView createDetachedAwTestContainerView(
458 final AwContentsClient awContentsClient) { 274 final AwContentsClient awContentsClient) {
459 return createDetachedAwTestContainerView(awContentsClient, false, null); 275 return mTestCommon.createDetachedAwTestContainerView(awContentsClient);
460 } 276 }
461 277
462 public AwTestContainerView createDetachedAwTestContainerView( 278 public AwTestContainerView createDetachedAwTestContainerView(
463 final AwContentsClient awContentsClient, boolean supportsLegacyQuirk s, 279 final AwContentsClient awContentsClient, boolean supportsLegacyQuirk s,
464 TestDependencyFactory testDependencyFactory) { 280 TestDependencyFactory testDependencyFactory) {
465 if (testDependencyFactory == null) { 281 return mTestCommon.createDetachedAwTestContainerView(
466 testDependencyFactory = createTestDependencyFactory(); 282 awContentsClient, supportsLegacyQuirks, testDependencyFactory);
467 }
468 boolean allowHardwareAcceleration = isHardwareAcceleratedTest();
469 final AwTestContainerView testContainerView =
470 testDependencyFactory.createAwTestContainerView(
471 getActivity(), allowHardwareAcceleration);
472
473 AwSettings awSettings =
474 testDependencyFactory.createAwSettings(getActivity(), supportsLe gacyQuirks);
475 AwContents awContents = testDependencyFactory.createAwContents(mBrowserC ontext,
476 testContainerView, testContainerView.getContext(),
477 testContainerView.getInternalAccessDelegate(),
478 testContainerView.getNativeDrawGLFunctorFactory(), awContentsCli ent, awSettings,
479 testDependencyFactory);
480 testContainerView.initialize(awContents);
481 return testContainerView;
482 } 283 }
483 284
484 protected boolean isHardwareAcceleratedTest() { 285 protected boolean isHardwareAcceleratedTest() {
485 return !testMethodHasAnnotation(DisableHardwareAccelerationForTest.class ); 286 return mTestCommon.isHardwareAcceleratedTest();
486 } 287 }
487 288
488 public AwTestContainerView createAwTestContainerViewOnMainSync( 289 public AwTestContainerView createAwTestContainerViewOnMainSync(
489 final AwContentsClient client) throws Exception { 290 final AwContentsClient client) throws Exception {
490 return createAwTestContainerViewOnMainSync(client, false, null); 291 return mTestCommon.createAwTestContainerViewOnMainSync(client);
491 } 292 }
492 293
493 public AwTestContainerView createAwTestContainerViewOnMainSync( 294 public AwTestContainerView createAwTestContainerViewOnMainSync(
494 final AwContentsClient client, final boolean supportsLegacyQuirks) { 295 final AwContentsClient client, final boolean supportsLegacyQuirks) {
495 return createAwTestContainerViewOnMainSync(client, supportsLegacyQuirks, null); 296 return mTestCommon.createAwTestContainerViewOnMainSync(client, supportsL egacyQuirks);
496 } 297 }
497 298
498 public AwTestContainerView createAwTestContainerViewOnMainSync(final AwConte ntsClient client, 299 public AwTestContainerView createAwTestContainerViewOnMainSync(final AwConte ntsClient client,
499 final boolean supportsLegacyQuirks, final TestDependencyFactory test DependencyFactory) { 300 final boolean supportsLegacyQuirks, final TestDependencyFactory test DependencyFactory) {
500 return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<AwTestC ontainerView>() { 301 return mTestCommon.createAwTestContainerViewOnMainSync(
501 @Override 302 client, supportsLegacyQuirks, testDependencyFactory);
502 public AwTestContainerView call() {
503 return createAwTestContainerView(
504 client, supportsLegacyQuirks, testDependencyFactory);
505 }
506 });
507 } 303 }
508 304
509 public void destroyAwContentsOnMainSync(final AwContents awContents) { 305 public void destroyAwContentsOnMainSync(final AwContents awContents) {
510 if (awContents == null) return; 306 mTestCommon.destroyAwContentsOnMainSync(awContents);
511 getInstrumentation().runOnMainSync(new Runnable() {
512 @Override
513 public void run() {
514 awContents.destroy();
515 }
516 });
517 } 307 }
518 308
519 public String getTitleOnUiThread(final AwContents awContents) throws Excepti on { 309 public String getTitleOnUiThread(final AwContents awContents) throws Excepti on {
520 return runTestOnUiThreadAndGetResult(new Callable<String>() { 310 return mTestCommon.getTitleOnUiThread(awContents);
521 @Override
522 public String call() throws Exception {
523 return awContents.getTitle();
524 }
525 });
526 } 311 }
527 312
528 public AwSettings getAwSettingsOnUiThread( 313 public AwSettings getAwSettingsOnUiThread(
529 final AwContents awContents) throws Exception { 314 final AwContents awContents) throws Exception {
530 return runTestOnUiThreadAndGetResult(new Callable<AwSettings>() { 315 return mTestCommon.getAwSettingsOnUiThread(awContents);
531 @Override
532 public AwSettings call() throws Exception {
533 return awContents.getSettings();
534 }
535 });
536 } 316 }
537 317
538 /** 318 /**
539 * Verify double quotes in both sides of the raw string. Strip the double qu otes and 319 * Verify double quotes in both sides of the raw string. Strip the double
540 * returns rest of the string. 320 * quotes and returns rest of the string.
541 */ 321 */
542 protected String maybeStripDoubleQuotes(String raw) { 322 protected String maybeStripDoubleQuotes(String raw) {
543 assertNotNull(raw); 323 return mTestCommon.maybeStripDoubleQuotes(raw);
544 Matcher m = MAYBE_QUOTED_STRING.matcher(raw);
545 assertTrue(m.matches());
546 return m.group(2);
547 } 324 }
548 325
549 /** 326 /**
550 * Executes the given snippet of JavaScript code within the given ContentVie w. Returns the 327 * Executes the given snippet of JavaScript code within the given
551 * result of its execution in JSON format. 328 * ContentView. Returns the result of its execution in JSON format.
552 */ 329 */
553 public String executeJavaScriptAndWaitForResult(final AwContents awContents, 330 public String executeJavaScriptAndWaitForResult(final AwContents awContents,
554 TestAwContentsClient viewClient, final String code) throws Exception { 331 TestAwContentsClient viewClient, final String code) throws Exception {
555 return JSUtils.executeJavaScriptAndWaitForResult(this, awContents, 332 return mTestCommon.executeJavaScriptAndWaitForResult(awContents, viewCli ent, code);
556 viewClient.getOnEvaluateJavaScriptResultHelper(),
557 code);
558 } 333 }
559 334
560 /** 335 /**
561 * Executes JavaScript code within the given ContentView to get the text con tent in 336 * Executes JavaScript code within the given ContentView to get the text con tent in
562 * document body. Returns the result string without double quotes. 337 * document body. Returns the result string without double quotes.
563 */ 338 */
564 protected String getJavaScriptResultBodyTextContent( 339 protected String getJavaScriptResultBodyTextContent(
565 final AwContents awContents, final TestAwContentsClient viewClient) throws Exception { 340 final AwContents awContents, final TestAwContentsClient viewClient) throws Exception {
566 String raw = executeJavaScriptAndWaitForResult( 341 return mTestCommon.getJavaScriptResultBodyTextContent(awContents, viewCl ient);
567 awContents, viewClient, "document.body.textContent");
568 return maybeStripDoubleQuotes(raw);
569 } 342 }
570 343
571 /** 344 /**
572 * Wrapper around CriteriaHelper.pollInstrumentationThread. This uses AwTest Base-specifc 345 * Wrapper around CriteriaHelper.pollInstrumentationThread. This uses AwTest Base-specifc
573 * timeouts and treats timeouts and exceptions as test failures automaticall y. 346 * timeouts and treats timeouts and exceptions as test failures automaticall y.
574 */ 347 */
575 public static void pollInstrumentationThread(final Callable<Boolean> callabl e) 348 public static void pollInstrumentationThread(final Callable<Boolean> callabl e)
576 throws Exception { 349 throws Exception {
577 CriteriaHelper.pollInstrumentationThread(new Criteria() { 350 AwTestCommon.pollInstrumentationThread(callable);
578 @Override
579 public boolean isSatisfied() {
580 try {
581 return callable.call();
582 } catch (Throwable e) {
583 Log.e(TAG, "Exception while polling.", e);
584 return false;
585 }
586 }
587 }, WAIT_TIMEOUT_MS, CHECK_INTERVAL);
588 } 351 }
589 352
590 /** 353 /**
591 * Wrapper around {@link AwTestBase#poll()} but runs the callable on the UI thread. 354 * Wrapper around {@link AwTestBase#poll()} but runs the callable on the UI
355 * thread.
592 */ 356 */
593 public void pollUiThread(final Callable<Boolean> callable) throws Exception { 357 public void pollUiThread(final Callable<Boolean> callable) throws Exception {
594 pollInstrumentationThread(new Callable<Boolean>() { 358 mTestCommon.pollUiThread(callable);
595 @Override
596 public Boolean call() throws Exception {
597 return runTestOnUiThreadAndGetResult(callable);
598 }
599 });
600 } 359 }
601 360
602 /** 361 /**
603 * Clears the resource cache. Note that the cache is per-application, so thi s will clear the 362 * Clears the resource cache. Note that the cache is per-application, so
604 * cache for all WebViews used. 363 * this will clear the cache for all WebViews used.
605 */ 364 */
606 public void clearCacheOnUiThread( 365 public void clearCacheOnUiThread(
607 final AwContents awContents, 366 final AwContents awContents,
608 final boolean includeDiskFiles) throws Exception { 367 final boolean includeDiskFiles) throws Exception {
609 getInstrumentation().runOnMainSync(new Runnable() { 368 mTestCommon.clearCacheOnUiThread(awContents, includeDiskFiles);
610 @Override
611 public void run() {
612 awContents.clearCache(includeDiskFiles);
613 }
614 });
615 } 369 }
616 370
617 /** 371 /**
618 * Returns pure page scale. 372 * Returns pure page scale.
619 */ 373 */
620 public float getScaleOnUiThread(final AwContents awContents) throws Exceptio n { 374 public float getScaleOnUiThread(final AwContents awContents) throws Exceptio n {
621 return runTestOnUiThreadAndGetResult(new Callable<Float>() { 375 return mTestCommon.getScaleOnUiThread(awContents);
622 @Override
623 public Float call() throws Exception {
624 return awContents.getPageScaleFactor();
625 }
626 });
627 } 376 }
628 377
629 /** 378 /**
630 * Returns page scale multiplied by the screen density. 379 * Returns page scale multiplied by the screen density.
631 */ 380 */
632 public float getPixelScaleOnUiThread(final AwContents awContents) throws Exc eption { 381 public float getPixelScaleOnUiThread(final AwContents awContents) throws Exc eption {
633 return runTestOnUiThreadAndGetResult(new Callable<Float>() { 382 return mTestCommon.getPixelScaleOnUiThread(awContents);
634 @Override
635 public Float call() throws Exception {
636 return awContents.getScale();
637 }
638 });
639 } 383 }
640 384
641 /** 385 /**
642 * Returns whether a user can zoom the page in. 386 * Returns whether a user can zoom the page in.
643 */ 387 */
644 public boolean canZoomInOnUiThread(final AwContents awContents) throws Excep tion { 388 public boolean canZoomInOnUiThread(final AwContents awContents) throws Excep tion {
645 return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { 389 return mTestCommon.canZoomInOnUiThread(awContents);
646 @Override
647 public Boolean call() throws Exception {
648 return awContents.canZoomIn();
649 }
650 });
651 } 390 }
652 391
653 /** 392 /**
654 * Returns whether a user can zoom the page out. 393 * Returns whether a user can zoom the page out.
655 */ 394 */
656 public boolean canZoomOutOnUiThread(final AwContents awContents) throws Exce ption { 395 public boolean canZoomOutOnUiThread(final AwContents awContents) throws Exce ption {
657 return runTestOnUiThreadAndGetResult(new Callable<Boolean>() { 396 return mTestCommon.canZoomOutOnUiThread(awContents);
658 @Override
659 public Boolean call() throws Exception {
660 return awContents.canZoomOut();
661 }
662 });
663 } 397 }
664 398
665 public void killRenderProcessOnUiThreadAsync(final AwContents awContents) th rows Exception { 399 public void killRenderProcessOnUiThreadAsync(final AwContents awContents) th rows Exception {
666 getInstrumentation().runOnMainSync(new Runnable() { 400 mTestCommon.killRenderProcessOnUiThreadAsync(awContents);
667 @Override
668 public void run() {
669 awContents.killRenderProcess();
670 }
671 });
672 } 401 }
673 402
674 /** 403 /**
675 * Loads the main html then triggers the popup window. 404 * Loads the main html then triggers the popup window.
676 */ 405 */
677 public void triggerPopup(final AwContents parentAwContents, 406 public void triggerPopup(final AwContents parentAwContents,
678 TestAwContentsClient parentAwContentsClient, TestWebServer testWebSe rver, 407 TestAwContentsClient parentAwContentsClient, TestWebServer testWebSe rver,
679 String mainHtml, String popupHtml, String popupPath, String triggerS cript) 408 String mainHtml, String popupHtml, String popupPath, String triggerS cript)
680 throws Exception { 409 throws Exception {
681 enableJavaScriptOnUiThread(parentAwContents); 410 mTestCommon.triggerPopup(parentAwContents, parentAwContentsClient, testW ebServer, mainHtml,
682 getInstrumentation().runOnMainSync(new Runnable() { 411 popupHtml, popupPath, triggerScript);
683 @Override
684 public void run() {
685 parentAwContents.getSettings().setSupportMultipleWindows(true);
686 parentAwContents.getSettings().setJavaScriptCanOpenWindowsAutoma tically(true);
687 }
688 });
689
690 final String parentUrl = testWebServer.setResponse("/popupParent.html", mainHtml, null);
691 if (popupHtml != null) {
692 testWebServer.setResponse(popupPath, popupHtml, null);
693 } else {
694 testWebServer.setResponseWithNoContentStatus(popupPath);
695 }
696
697 parentAwContentsClient.getOnCreateWindowHelper().setReturnValue(true);
698 loadUrlSync(parentAwContents, parentAwContentsClient.getOnPageFinishedHe lper(), parentUrl);
699
700 TestAwContentsClient.OnCreateWindowHelper onCreateWindowHelper =
701 parentAwContentsClient.getOnCreateWindowHelper();
702 int currentCallCount = onCreateWindowHelper.getCallCount();
703 parentAwContents.evaluateJavaScriptForTests(triggerScript, null);
704 onCreateWindowHelper.waitForCallback(
705 currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
706 } 412 }
707 413
708 /** 414 /**
415 * Supplies the popup window with AwContents then waits for the popup window
416 * to finish loading.
417 */
418 public PopupInfo connectPendingPopup(final AwContents parentAwContents) thro ws Exception {
419 return mTestCommon.connectPendingPopup(parentAwContents);
420 }
421
422 /**
423 * Factory class used in creation of test AwContents instances. Test cases
424 * can provide subclass instances to the createAwTest* methods in order to
425 * create an AwContents instance with injected test dependencies.
426 */
427 public static class TestDependencyFactory extends AwContents.DependencyFacto ry {
428 public AwTestContainerView createAwTestContainerView(
429 AwTestRunnerActivity activity, boolean allowHardwareAcceleration ) {
430 return new AwTestContainerView(activity, allowHardwareAcceleration);
431 }
432
433 public AwSettings createAwSettings(Context context, boolean supportsLega cyQuirks) {
434 return new AwSettings(context, false /* isAccessFromFileURLsGrantedB yDefault */,
435 supportsLegacyQuirks, false /* allowEmptyDocumentPersistence */,
436 true /* allowGeolocationOnInsecureOrigins */,
437 false /* doNotUpdateSelectionOnMutatingSelectionRange */);
438 }
439
440 public AwContents createAwContents(AwBrowserContext browserContext, View Group containerView,
441 Context context, InternalAccessDelegate internalAccessAdapter,
442 NativeDrawGLFunctorFactory nativeDrawGLFunctorFactory,
443 AwContentsClient contentsClient, AwSettings settings,
444 DependencyFactory dependencyFactory) {
445 return new AwContents(browserContext, containerView, context, intern alAccessAdapter,
446 nativeDrawGLFunctorFactory, contentsClient, settings, depend encyFactory);
447 }
448 }
449
450 /**
709 * POD object for holding references to helper objects of a popup window. 451 * POD object for holding references to helper objects of a popup window.
710 */ 452 */
711 public static class PopupInfo { 453 public static class PopupInfo {
712 public final TestAwContentsClient popupContentsClient; 454 public final TestAwContentsClient popupContentsClient;
713 public final AwTestContainerView popupContainerView; 455 public final AwTestContainerView popupContainerView;
714 public final AwContents popupContents; 456 public final AwContents popupContents;
457
715 public PopupInfo(TestAwContentsClient popupContentsClient, 458 public PopupInfo(TestAwContentsClient popupContentsClient,
716 AwTestContainerView popupContainerView, AwContents popupContents ) { 459 AwTestContainerView popupContainerView, AwContents popupContents ) {
717 this.popupContentsClient = popupContentsClient; 460 this.popupContentsClient = popupContentsClient;
718 this.popupContainerView = popupContainerView; 461 this.popupContainerView = popupContainerView;
719 this.popupContents = popupContents; 462 this.popupContents = popupContents;
720 } 463 }
721 } 464 }
722 465
723 /** 466 /**
724 * Supplies the popup window with AwContents then waits for the popup window to finish loading. 467 * Checks the current test has |clazz| annotation. Note this swallows
468 * NoSuchMethodException and returns false in that case.
725 */ 469 */
726 public PopupInfo connectPendingPopup(final AwContents parentAwContents) thro ws Exception { 470 @Override
727 TestAwContentsClient popupContentsClient; 471 public boolean testMethodHasAnnotation(Class<? extends Annotation> clazz) {
728 AwTestContainerView popupContainerView; 472 String testName = getName();
729 final AwContents popupContents; 473 Method method = null;
730 popupContentsClient = new TestAwContentsClient(); 474 try {
731 popupContainerView = createAwTestContainerViewOnMainSync(popupContentsCl ient); 475 method = getClass().getMethod(testName);
732 popupContents = popupContainerView.getAwContents(); 476 } catch (NoSuchMethodException e) {
733 enableJavaScriptOnUiThread(popupContents); 477 Log.w(TAG, "Test method name not found.", e);
478 return false;
479 }
734 480
735 getInstrumentation().runOnMainSync(new Runnable() { 481 // Cast to AnnotatedElement to work around a compilation failure.
736 @Override 482 // Method.isAnnotationPresent() was removed in Java 8 (which is used by
737 public void run() { 483 // the Android N SDK),
738 parentAwContents.supplyContentsForPopup(popupContents); 484 // so compilation with Java 7 fails. See crbug.com/608792.
739 } 485 return ((AnnotatedElement) method).isAnnotationPresent(clazz);
740 }); 486 }
741 487
742 OnPageFinishedHelper onPageFinishedHelper = popupContentsClient.getOnPag eFinishedHelper(); 488 @Override
743 int finishCallCount = onPageFinishedHelper.getCallCount(); 489 public void runOnUiThread(Runnable runnable) {
744 TestAwContentsClient.OnReceivedTitleHelper onReceivedTitleHelper = 490 getInstrumentation().runOnMainSync(runnable);
745 popupContentsClient.getOnReceivedTitleHelper();
746 int titleCallCount = onReceivedTitleHelper.getCallCount();
747
748 onPageFinishedHelper.waitForCallback(finishCallCount, 1, WAIT_TIMEOUT_MS ,
749 TimeUnit.MILLISECONDS);
750 onReceivedTitleHelper.waitForCallback(titleCallCount, 1, WAIT_TIMEOUT_MS ,
751 TimeUnit.MILLISECONDS);
752
753 return new PopupInfo(popupContentsClient, popupContainerView, popupConte nts);
754 } 491 }
755 } 492 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698