Upstream version 9.37.193.0
[platform/framework/web/crosswalk.git] / src / xwalk / test / android / core / javatests / src / org / xwalk / core / xwview / test / XWalkViewTestBase.java
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Copyright (c) 2013-2014 Intel Corporation. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5
6 package org.xwalk.core.xwview.test;
7
8 import android.app.Activity;
9 import android.content.Context;
10 import android.test.ActivityInstrumentationTestCase2;
11 import android.util.Log;
12 import android.webkit.WebResourceResponse;
13
14 import java.io.InputStream;
15 import java.io.IOException;
16 import java.util.concurrent.atomic.AtomicReference;
17 import java.util.concurrent.Callable;
18 import java.util.concurrent.FutureTask;
19 import java.util.concurrent.TimeUnit;
20
21 import junit.framework.Assert;
22
23 import org.chromium.content.browser.LoadUrlParams;
24 import org.chromium.content.browser.test.util.CallbackHelper;
25 import org.chromium.content.browser.test.util.Criteria;
26 import org.chromium.content.browser.test.util.CriteriaHelper;
27
28 import org.xwalk.core.XWalkNavigationHistory;
29 import org.xwalk.core.XWalkNavigationItem;
30 import org.xwalk.core.XWalkResourceClient;
31 import org.xwalk.core.XWalkUIClient;
32 import org.xwalk.core.XWalkView;
33
34 public class XWalkViewTestBase
35        extends ActivityInstrumentationTestCase2<XWalkViewTestRunnerActivity> {
36     protected final static int WAIT_TIMEOUT_SECONDS = 15;
37     protected final static long WAIT_TIMEOUT_MS = 2000;
38     private final static int CHECK_INTERVAL = 100;
39     private final static String TAG = "XWalkViewTestBase";
40     private XWalkView mXWalkView;
41     final TestHelperBridge mTestHelperBridge = new TestHelperBridge();
42
43     class TestXWalkUIClientBase extends XWalkUIClient {
44         TestHelperBridge mInnerContentsClient;
45         public TestXWalkUIClientBase(TestHelperBridge client) {
46             super(getXWalkView());
47             mInnerContentsClient = client;
48         }
49
50         @Override
51         public void onPageLoadStarted(XWalkView view, String url) {
52             mInnerContentsClient.onPageStarted(url);
53         }
54
55         @Override
56         public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) {
57             mInnerContentsClient.onPageFinished(url);
58         }
59
60         @Override
61         public void onReceivedTitle(XWalkView view, String title) {
62             mInnerContentsClient.onTitleChanged(title);
63         }
64
65         @Override
66         public void onJavascriptCloseWindow(XWalkView view) {
67             mInnerContentsClient.onJavascriptCloseWindow();
68         }
69     }
70
71     class TestXWalkUIClient extends TestXWalkUIClientBase {
72         public TestXWalkUIClient() {
73             super(mTestHelperBridge);
74         }
75     }
76
77     class TestXWalkResourceClientBase extends XWalkResourceClient {
78         TestHelperBridge mInnerContentsClient;
79         public TestXWalkResourceClientBase(TestHelperBridge client) {
80             super(mXWalkView);
81             mInnerContentsClient = client;
82         }
83
84         @Override
85         public void onLoadStarted(XWalkView view, String url) {
86             mInnerContentsClient.onLoadStarted(url);
87         }
88
89         @Override
90         public void onReceivedLoadError(XWalkView view, int errorCode, String description, String failingUrl) {
91             mInnerContentsClient.onReceivedLoadError(errorCode, description, failingUrl);
92         }
93
94         @Override
95         public WebResourceResponse shouldInterceptLoadRequest(XWalkView view,
96                 String url) {
97             return mInnerContentsClient.shouldInterceptLoadRequest(url);
98         }
99
100         @Override
101         public void onProgressChanged(XWalkView view, int progressInPercent) {
102             mTestHelperBridge.onProgressChanged(progressInPercent);
103         }
104
105         @Override
106         public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
107             return mTestHelperBridge.shouldOverrideUrlLoading(url);
108         }
109     }
110
111     class TestXWalkResourceClient extends TestXWalkResourceClientBase {
112         public TestXWalkResourceClient() {
113             super(mTestHelperBridge);
114         }
115     }
116
117     void setUIClient(final XWalkUIClient client) {
118         getInstrumentation().runOnMainSync(new Runnable() {
119             @Override
120             public void run() {
121                 getXWalkView().setUIClient(client);
122             }
123         });
124     }
125
126     void setResourceClient(final XWalkResourceClient client) {
127         getInstrumentation().runOnMainSync(new Runnable() {
128             @Override
129             public void run() {
130                 getXWalkView().setResourceClient(client);
131             }
132         });
133     }
134
135     public XWalkViewTestBase() {
136         super(XWalkViewTestRunnerActivity.class);
137     }
138
139     @Override
140     protected void setUp() throws Exception {
141         super.setUp();
142
143         // Must call getActivity() here but not in main thread.
144         final Activity activity = getActivity();
145         getInstrumentation().runOnMainSync(new Runnable() {
146             @Override
147             public void run() {
148                 mXWalkView = new XWalkView(activity, activity);
149                 getActivity().addView(mXWalkView);
150                 mXWalkView.setUIClient(new TestXWalkUIClient());
151                 mXWalkView.setResourceClient(new TestXWalkResourceClient());
152                 // mXWalkView.getXWalkViewContentForTest().installWebContentsObserverForTest(mTestHelperBridge);
153             }
154         });
155     }
156
157     protected boolean pollOnUiThread(final Callable<Boolean> callable) throws Exception {
158         return CriteriaHelper.pollForCriteria(new Criteria() {
159             @Override
160             public boolean isSatisfied() {
161                 try {
162                     return runTestOnUiThreadAndGetResult(callable);
163                 } catch (Throwable e) {
164                     return false;
165                 }
166             }
167         });
168     }
169
170     protected void loadJavaScriptUrl(final String url) throws Exception {
171         if (!url.startsWith("javascript:")) {
172             Log.w(TAG, "loadJavascriptUrl only accepts javascript: url");
173             return;
174         }
175         loadUrlAsync(url);
176     }
177
178     protected void loadUrlSync(final String url) throws Exception {
179         CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper();
180         int currentCallCount = pageFinishedHelper.getCallCount();
181         loadUrlAsync(url);
182
183         pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS,
184                 TimeUnit.SECONDS);
185     }
186
187     protected void loadUrlAsync(final String url) throws Exception {
188         getInstrumentation().runOnMainSync(new Runnable() {
189             @Override
190             public void run() {
191                 mXWalkView.load(url, null);
192             }
193         });
194     }
195
196     protected void loadDataSync(final String url, final String data, final String mimeType,
197             final boolean isBase64Encoded) throws Exception {
198         CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper();
199         int currentCallCount = pageFinishedHelper.getCallCount();
200         loadDataAsync(url, data, mimeType, isBase64Encoded);
201         pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS,
202                 TimeUnit.SECONDS);
203     }
204
205     protected void loadDataAsync(final String url, final String data, final String mimeType,
206              final boolean isBase64Encoded) throws Exception {
207         getInstrumentation().runOnMainSync(new Runnable() {
208             @Override
209             public void run() {
210                 mXWalkView.load(url, data);
211             }
212         });
213     }
214
215     protected void loadUrlSyncByContent(final XWalkView xWalkContent,
216             final TestHelperBridge contentsClient,
217             final String url) throws Exception {
218         CallbackHelper pageFinishedHelper = contentsClient.getOnPageFinishedHelper();
219         int currentCallCount = pageFinishedHelper.getCallCount();
220         loadUrlAsyncByContent(xWalkContent, url);
221
222         pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS,
223                 TimeUnit.SECONDS);
224     }
225
226     protected void loadUrlAsyncByContent(final XWalkView xWalkContent,
227             final String url) throws Exception {
228         getInstrumentation().runOnMainSync(new Runnable() {
229             @Override
230             public void run() {
231                 xWalkContent.load(url, null);
232             }
233         });
234     }
235
236     protected String getTitleOnUiThread() throws Exception {
237         return runTestOnUiThreadAndGetResult(new Callable<String>() {
238             @Override
239             public String call() throws Exception {
240                 return mXWalkView.getTitle();
241             }
242         });
243     }
244
245     protected <R> R runTestOnUiThreadAndGetResult(Callable<R> callable)
246             throws Exception {
247         FutureTask<R> task = new FutureTask<R>(callable);
248         getInstrumentation().waitForIdleSync();
249         getInstrumentation().runOnMainSync(task);
250         return task.get();
251     }
252
253     protected String getFileContent(String fileName) {
254         try {
255             Context context = getInstrumentation().getContext();
256             InputStream inputStream = context.getAssets().open(fileName);
257             int size = inputStream.available();
258             byte buffer[] = new byte[size];
259             inputStream.read(buffer);
260             inputStream.close();
261
262             String fileContent = new String(buffer);
263             return fileContent;
264         } catch (IOException e) {
265             throw new RuntimeException(e);
266         }
267     }
268
269     protected String getTitleOnUiThreadByContent(final XWalkView xWalkContent) throws Exception {
270         return runTestOnUiThreadAndGetResult(new Callable<String>() {
271             @Override
272             public String call() throws Exception {
273                 String title = xWalkContent.getTitle();
274                 return title;
275             }
276         });
277     }
278
279     protected XWalkView createXWalkViewContainerOnMainSync(
280             final Context context,
281             final XWalkUIClient uiClient,
282             final XWalkResourceClient resourceClient) throws Exception {
283         final AtomicReference<XWalkView> xWalkViewContainer =
284                 new AtomicReference<XWalkView>();
285         getInstrumentation().runOnMainSync(new Runnable() {
286             @Override
287             public void run() {
288                 xWalkViewContainer.set(new XWalkView(context, getActivity()));
289                 getActivity().addView(xWalkViewContainer.get());
290                 xWalkViewContainer.get().setUIClient(uiClient);
291                 xWalkViewContainer.get().setResourceClient(resourceClient);
292             }
293         });
294
295         return xWalkViewContainer.get();
296     }
297
298     protected void loadAssetFile(String fileName) throws Exception {
299         String fileContent = getFileContent(fileName);
300         loadDataSync(fileName, fileContent, "text/html", false);
301     }
302
303     public void loadAssetFileAndWaitForTitle(String fileName) throws Exception {
304         CallbackHelper getTitleHelper = mTestHelperBridge.getOnTitleUpdatedHelper();
305         int currentCallCount = getTitleHelper.getCallCount();
306         String fileContent = getFileContent(fileName);
307
308         loadDataSync(fileName, fileContent, "text/html", false);
309
310         getTitleHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS,
311                 TimeUnit.SECONDS);
312     }
313
314     protected XWalkView getXWalkView() {
315         return mXWalkView;
316     }
317
318     protected void runTestWaitPageFinished(Runnable runnable) throws Exception{
319         CallbackHelper pageFinishedHelper = mTestHelperBridge.getOnPageFinishedHelper();
320         int currentCallCount = pageFinishedHelper.getCallCount();
321         runnable.run();
322         pageFinishedHelper.waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_SECONDS,
323                 TimeUnit.SECONDS);
324     }
325
326     protected void reloadSync(final int mode) throws Exception {
327         runTestWaitPageFinished(new Runnable(){
328             @Override
329             public void run() {
330                 getInstrumentation().runOnMainSync(new Runnable() {
331                     @Override
332                     public void run() {
333                         mXWalkView.reload(mode);
334                     }
335                 });
336             }
337         });
338     }
339
340     protected void goBackSync() throws Throwable {
341         runTestWaitPageFinished(new Runnable(){
342             @Override
343             public void run() {
344                 getInstrumentation().runOnMainSync(new Runnable() {
345                     @Override
346                     public void run() {
347                         mXWalkView.getNavigationHistory().navigate(
348                             XWalkNavigationHistory.Direction.BACKWARD, 1);
349                     }
350                 });
351             }
352         });
353     }
354
355     protected void goForwardSync() throws Throwable {
356         runTestWaitPageFinished(new Runnable(){
357             @Override
358             public void run() {
359                 getInstrumentation().runOnMainSync(new Runnable() {
360                     @Override
361                     public void run() {
362                         mXWalkView.getNavigationHistory().navigate(
363                             XWalkNavigationHistory.Direction.FORWARD, 1);
364                     }
365                 });
366             }
367         });
368     }
369
370     protected void clearHistoryOnUiThread() throws Exception {
371         getInstrumentation().runOnMainSync(new Runnable() {
372             @Override
373             public void run() {
374                 mXWalkView.getNavigationHistory().clear();
375             }
376         });
377     }
378
379     protected boolean canGoBackOnUiThread() throws Throwable {
380         return runTestOnUiThreadAndGetResult(new Callable<Boolean>() {
381             @Override
382             public Boolean call() {
383                 return mXWalkView.getNavigationHistory().canGoBack();
384             }
385         });
386     }
387
388     protected boolean canGoForwardOnUiThread() throws Throwable {
389         return runTestOnUiThreadAndGetResult(new Callable<Boolean>() {
390             @Override
391             public Boolean call() {
392                 return mXWalkView.getNavigationHistory().canGoForward();
393             }
394         });
395     }
396
397     protected int historySizeOnUiThread() throws Throwable {
398         return runTestOnUiThreadAndGetResult(new Callable<Integer>() {
399             @Override
400             public Integer call() {
401                 return mXWalkView.getNavigationHistory().size();
402             }
403         });
404     }
405
406     protected boolean hasItemAtOnUiThread(final int index) throws Throwable {
407         return runTestOnUiThreadAndGetResult(new Callable<Boolean>() {
408             @Override
409             public Boolean call() {
410                 return mXWalkView.getNavigationHistory().hasItemAt(index);
411             }
412         });
413     }
414
415     protected XWalkNavigationItem getItemAtOnUiThread(final int index) throws Throwable {
416         return runTestOnUiThreadAndGetResult(new Callable<XWalkNavigationItem>() {
417             @Override
418             public XWalkNavigationItem call() {
419                 return mXWalkView.getNavigationHistory().getItemAt(index);
420             }
421         });
422     }
423
424     protected XWalkNavigationItem getCurrentItemOnUiThread() throws Throwable {
425         return runTestOnUiThreadAndGetResult(new Callable<XWalkNavigationItem>() {
426             @Override
427             public XWalkNavigationItem call() {
428                 return mXWalkView.getNavigationHistory().getCurrentItem();
429             }
430         });
431     }
432
433     protected String executeJavaScriptAndWaitForResult(final String code) throws Exception {
434
435         final TestHelperBridge.OnEvaluateJavaScriptResultHelper helper =
436                 mTestHelperBridge.getOnEvaluateJavaScriptResultHelper();
437         getInstrumentation().runOnMainSync(new Runnable() {
438             @Override
439             public void run() {
440                 helper.evaluateJavascript(mXWalkView, code);
441             }
442         });
443         helper.waitUntilHasValue();
444         Assert.assertTrue("Failed to retrieve JavaScript evaluation results.", helper.hasValue());
445         return helper.getJsonResultAndClear();
446     }
447
448     protected String getUrlOnUiThread() throws Exception {
449         return runTestOnUiThreadAndGetResult(new Callable<String>() {
450             @Override
451             public String call() throws Exception {
452                 return mXWalkView.getUrl();
453             }
454         });
455     }
456
457     protected void clearCacheOnUiThread(final boolean includeDiskFiles) throws Exception {
458         getInstrumentation().runOnMainSync(new Runnable() {
459             @Override
460             public void run() {
461                 mXWalkView.clearCache(includeDiskFiles);
462             }
463         });
464     }
465
466     protected String getAPIVersionOnUiThread() throws Exception {
467         return runTestOnUiThreadAndGetResult(new Callable<String>() {
468             @Override
469             public String call() throws Exception {
470                 return mXWalkView.getAPIVersion();
471             }
472         });
473     }
474
475     protected String getXWalkVersionOnUiThread() throws Exception {
476         return runTestOnUiThreadAndGetResult(new Callable<String>() {
477             @Override
478             public String call() throws Exception {
479                 return mXWalkView.getXWalkVersion();
480             }
481         });
482     }
483
484     public void clickOnElementId(final String id) throws Exception {
485         Assert.assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
486             @Override
487             public boolean isSatisfied() {
488                 try {
489                     String idIsNotNull = executeJavaScriptAndWaitForResult(
490                         "document.getElementById('" + id + "') != null");
491                     return idIsNotNull.equals("true");
492                 } catch (Throwable t) {
493                     t.printStackTrace();
494                     Assert.fail("Failed to check if DOM is loaded: " + t.toString());
495                     return false;
496                 }
497             }
498         }, WAIT_TIMEOUT_MS, CHECK_INTERVAL));
499
500         try {
501             String result = executeJavaScriptAndWaitForResult(
502                 "var evObj = document.createEvent('Events'); " +
503                 "evObj.initEvent('click', true, false); " +
504                 "document.getElementById('" + id + "').dispatchEvent(evObj);" +
505                 "console.log('element with id [" + id + "] clicked');");
506         } catch (Throwable t) {
507             t.printStackTrace();
508         }
509     }
510 }