@SmallTest
  @Feature({"AndroidWebView"})
  public void testCalledForImage() throws Throwable {
    final TestAwContentsClient contentsClient = new TestAwContentsClient();
    final AwTestContainerView testContainerView =
        createAwTestContainerViewOnMainSync(contentsClient);
    final AwContents awContents = testContainerView.getAwContents();
    final TestAwContentsClient.ShouldInterceptRequestHelper shouldInterceptRequestHelper =
        contentsClient.getShouldInterceptRequestHelper();

    final String imagePath = "/" + CommonResources.FAVICON_FILENAME;
    mWebServer.setResponseBase64(
        imagePath, CommonResources.FAVICON_DATA_BASE64, CommonResources.getImagePngHeaders(true));
    final String pageWithImage =
        addPageToTestServer(
            mWebServer,
            "/page_with_image.html",
            CommonResources.getOnImageLoadedHtml(CommonResources.FAVICON_FILENAME));

    int callCount = shouldInterceptRequestHelper.getCallCount();
    loadUrlSync(awContents, contentsClient.getOnPageFinishedHelper(), pageWithImage);
    shouldInterceptRequestHelper.waitForCallback(callCount, 2);

    assertEquals(2, shouldInterceptRequestHelper.getUrls().size());
    assertTrue(
        shouldInterceptRequestHelper.getUrls().get(1).endsWith(CommonResources.FAVICON_FILENAME));
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testCanIgnoreLoading() throws Throwable {
    standardSetup();

    final String redirectTargetUrl = createRedirectTargetPage();
    final String pageWithLinkToIgnorePath = "/page_with_link_to_ignore.html";
    final String pageWithLinkToIgnoreUrl =
        addPageToTestServer(
            pageWithLinkToIgnorePath,
            CommonResources.makeHtmlPageWithSimpleLinkTo(redirectTargetUrl));
    final String synchronizationPath = "/sync.html";
    final String synchronizationUrl =
        addPageToTestServer(
            synchronizationPath, CommonResources.makeHtmlPageWithSimpleLinkTo(redirectTargetUrl));

    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), pageWithLinkToIgnoreUrl);

    setShouldOverrideUrlLoadingReturnValueOnUiThread(true);

    int callCount = mShouldOverrideUrlLoadingHelper.getCallCount();
    clickOnLinkUsingJs();
    // Some time around here true should be returned from the shouldOverrideUrlLoading
    // callback causing the navigation caused by calling clickOnLinkUsingJs to be ignored.
    // We validate this by checking which pages were loaded on the server.
    mShouldOverrideUrlLoadingHelper.waitForCallback(callCount);

    setShouldOverrideUrlLoadingReturnValueOnUiThread(false);

    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), synchronizationUrl);

    assertEquals(1, mWebServer.getRequestCount(pageWithLinkToIgnorePath));
    assertEquals(1, mWebServer.getRequestCount(synchronizationPath));
    assertEquals(0, mWebServer.getRequestCount(REDIRECT_TARGET_PATH));
  }
 protected void doReload() throws Throwable {
   String url = mServer.setResponse("/form", LOAD_RESPONSE, null);
   String postData = "content=blabla";
   byte[] data = EncodingUtils.getBytes(postData, "BASE64");
   postUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url, data);
   assertEquals(0, mContentsClient.getResubmissions());
   assertEquals("Load", getTitleOnUiThread(mAwContents));
   // Verify reload works as expected.
   mServer.setResponse("/form", RELOAD_RESPONSE, null);
   TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
       mContentsClient.getOnPageFinishedHelper();
   int callCount = onPageFinishedHelper.getCallCount();
   // Run reload on UI thread.
   getInstrumentation()
       .runOnMainSync(
           new Runnable() {
             @Override
             public void run() {
               mAwContents.getContentViewCore().reload(true);
             }
           });
   try {
     // Wait for page finished callback, or a timeout. A timeout is necessary
     // to detect a dontResend response.
     onPageFinishedHelper.waitForCallback(callCount, 1, TIMEOUT, TimeUnit.SECONDS);
   } catch (TimeoutException e) {
   }
 }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testDoubleNavigateDoesNotSuppressInitialNavigate() throws Throwable {
    final String jsUrl = "javascript:try{console.log('processed js loadUrl');}catch(e){};";
    standardSetup();

    // Do a double navigagtion, the second being an effective no-op, in quick succession (i.e.
    // without yielding the main thread inbetween).
    int currentCallCount = mContentsClient.getOnPageFinishedHelper().getCallCount();
    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                mAwContents.loadUrl(
                    LoadUrlParams.createLoadDataParams(
                        CommonResources.makeHtmlPageWithSimpleLinkTo(DATA_URL),
                        "text/html",
                        false));
                mAwContents.loadUrl(new LoadUrlParams(jsUrl));
              }
            });
    mContentsClient
        .getOnPageFinishedHelper()
        .waitForCallback(currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    assertEquals(0, mShouldOverrideUrlLoadingHelper.getCallCount());
  }
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testJsScrollReflectedInUi() throws Throwable {
    final TestAwContentsClient contentsClient = new TestAwContentsClient();
    final ScrollTestContainerView testContainerView =
        (ScrollTestContainerView) createAwTestContainerViewOnMainSync(contentsClient);
    enableJavaScriptOnUiThread(testContainerView.getAwContents());

    final double deviceDIPScale =
        DeviceDisplayInfo.create(testContainerView.getContext()).getDIPScale();
    final int targetScrollXCss = 132;
    final int targetScrollYCss = 243;
    final int targetScrollXPix = (int) Math.floor(targetScrollXCss * deviceDIPScale);
    final int targetScrollYPix = (int) Math.floor(targetScrollYCss * deviceDIPScale);

    loadDataSync(
        testContainerView.getAwContents(),
        contentsClient.getOnPageFinishedHelper(),
        makeTestPage(null, null, ""),
        "text/html",
        false);

    final CallbackHelper onScrollToCallbackHelper = testContainerView.getOnScrollToCallbackHelper();
    final int scrollToCallCount = onScrollToCallbackHelper.getCallCount();
    executeJavaScriptAndWaitForResult(
        testContainerView.getAwContents(),
        contentsClient,
        String.format("window.scrollTo(%d, %d);", targetScrollXCss, targetScrollYCss));
    onScrollToCallbackHelper.waitForCallback(scrollToCallCount);

    assertScrollOnMainSync(testContainerView, targetScrollXPix, targetScrollYPix);
  }
  private void doTestNotCalledForAnchorNavigations(boolean useLoadData) throws Throwable {
    standardSetup();

    final String anchorLinkPath = "/anchor_link.html";
    final String anchorLinkUrl = mWebServer.getResponseUrl(anchorLinkPath);
    addPageToTestServer(
        anchorLinkPath, CommonResources.makeHtmlPageWithSimpleLinkTo(anchorLinkUrl + "#anchor"));

    if (useLoadData) {
      loadDataSync(
          mAwContents,
          mContentsClient.getOnPageFinishedHelper(),
          CommonResources.makeHtmlPageWithSimpleLinkTo("#anchor"),
          "text/html",
          false);
    } else {
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), anchorLinkUrl);
    }

    final int shouldOverrideUrlLoadingCallCount = mShouldOverrideUrlLoadingHelper.getCallCount();

    clickOnLinkUsingJs();

    // After we load this URL we're certain that any in-flight callbacks for the previous
    // navigation have been delivered.
    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), ABOUT_BLANK_URL);

    assertEquals(shouldOverrideUrlLoadingCallCount, mShouldOverrideUrlLoadingHelper.getCallCount());
  }
 /*
 @SmallTest
 @Feature({"AndroidWebView", "Navigation"})
 */
 @DisabledTest
 public void testResend() throws Throwable {
   mContentsClient.setResubmit(true);
   doReload();
   assertEquals(1, mContentsClient.getResubmissions());
   assertEquals("Reload", getTitleOnUiThread(mAwContents));
 }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testDoesNotCauseOnReceivedError() throws Throwable {
    standardSetup();
    OnReceivedErrorHelper onReceivedErrorHelper = mContentsClient.getOnReceivedErrorHelper();
    final int onReceivedErrorCallCount = onReceivedErrorHelper.getCallCount();

    loadDataSync(
        mAwContents,
        mContentsClient.getOnPageFinishedHelper(),
        CommonResources.makeHtmlPageWithSimpleLinkTo(DATA_URL),
        "text/html",
        false);

    final int shouldOverrideUrlLoadingCallCount = mShouldOverrideUrlLoadingHelper.getCallCount();
    setShouldOverrideUrlLoadingReturnValueOnUiThread(true);
    clickOnLinkUsingJs();
    mShouldOverrideUrlLoadingHelper.waitForCallback(shouldOverrideUrlLoadingCallCount);
    setShouldOverrideUrlLoadingReturnValueOnUiThread(false);

    // After we load this URL we're certain that any in-flight callbacks for the previous
    // navigation have been delivered.
    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), ABOUT_BLANK_URL);

    assertEquals(onReceivedErrorCallCount, onReceivedErrorHelper.getCallCount());
  }
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testDoesNotCrashOnInvalidData() throws Throwable {
    final TestAwContentsClient contentsClient = new TestAwContentsClient();
    final AwTestContainerView testContainerView =
        createAwTestContainerViewOnMainSync(contentsClient);
    final AwContents awContents = testContainerView.getAwContents();
    final TestAwContentsClient.ShouldInterceptRequestHelper shouldInterceptRequestHelper =
        contentsClient.getShouldInterceptRequestHelper();

    final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

    shouldInterceptRequestHelper.setReturnValue(
        new InterceptedRequestData("text/html", "UTF-8", null));
    int callCount = shouldInterceptRequestHelper.getCallCount();
    loadUrlAsync(awContents, aboutPageUrl);
    shouldInterceptRequestHelper.waitForCallback(callCount);

    shouldInterceptRequestHelper.setReturnValue(
        new InterceptedRequestData(null, null, new ByteArrayInputStream(new byte[0])));
    callCount = shouldInterceptRequestHelper.getCallCount();
    loadUrlAsync(awContents, aboutPageUrl);
    shouldInterceptRequestHelper.waitForCallback(callCount);

    shouldInterceptRequestHelper.setReturnValue(new InterceptedRequestData(null, null, null));
    callCount = shouldInterceptRequestHelper.getCallCount();
    loadUrlAsync(awContents, aboutPageUrl);
    shouldInterceptRequestHelper.waitForCallback(callCount);
  }
 @SmallTest
 @Feature({"AndroidWebView", "Navigation"})
 public void testDontResend() throws Throwable {
   mContentsClient.setResubmit(false);
   doReload();
   assertEquals(1, mContentsClient.getResubmissions());
   assertEquals("Load", getTitleOnUiThread(mAwContents));
 }
  @MediumTest
  @Feature({"AndroidWebView", "Privacy"})
  public void testThirdPartyCookie() throws Throwable {
    TestWebServer webServer = null;
    try {
      // In theory we need two servers to test this, one server ('the first party')
      // which returns a response with a link to a second server ('the third party')
      // at different origin. This second server attempts to set a cookie which should
      // fail if AcceptThirdPartyCookie() is false.
      // Strictly according to the letter of RFC6454 it should be possible to set this
      // situation up with two TestServers on different ports (these count as having
      // different origins) but Chrome is not strict about this and does not check the
      // port. Instead we cheat making some of the urls come from localhost and some
      // from 127.0.0.1 which count (both in theory and pratice) as having different
      // origins.
      webServer = new TestWebServer(false);

      // Turn global allow on.
      mCookieManager.setAcceptCookie(true);
      assertTrue(mCookieManager.acceptCookie());

      // When third party cookies are disabled...
      mAwContents.getSettings().setAcceptThirdPartyCookies(false);
      assertFalse(mAwContents.getSettings().getAcceptThirdPartyCookies());

      // ...we can't set third party cookies.
      // First on the third party server we create a url which tries to set a cookie.
      String cookieUrl =
          toThirdPartyUrl(makeCookieUrl(webServer, "/cookie_1.js", "test1", "value1"));
      // Then we create a url on the first party server which links to the first url.
      String url = makeScriptLinkUrl(webServer, "/content_1.html", cookieUrl);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      assertNull(mCookieManager.getCookie(cookieUrl));

      // When third party cookies are enabled...
      mAwContents.getSettings().setAcceptThirdPartyCookies(true);
      assertTrue(mAwContents.getSettings().getAcceptThirdPartyCookies());

      // ...we can set third party cookies.
      cookieUrl = toThirdPartyUrl(makeCookieUrl(webServer, "/cookie_2.js", "test2", "value2"));
      url = makeScriptLinkUrl(webServer, "/content_2.html", cookieUrl);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      waitForCookie(cookieUrl);
      String cookie = mCookieManager.getCookie(cookieUrl);
      assertNotNull(cookie);
      validateCookies(cookie, "test2");
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
  @MediumTest
  @Feature({"AndroidWebView"})
  public void testNoErrorOnFailedSubresourceLoad() throws Throwable {
    TestCallbackHelperContainer.OnReceivedErrorHelper onReceivedErrorHelper =
        mContentsClient.getOnReceivedErrorHelper();
    TestCallbackHelperContainer.OnPageFinishedHelper onPageFinishedHelper =
        mContentsClient.getOnPageFinishedHelper();

    int currentCallCount = onPageFinishedHelper.getCallCount();
    loadDataAsync(
        mAwContents, "<html><iframe src=\"http//invalid.url.co/\" /></html>", "text/html", false);

    onPageFinishedHelper.waitForCallback(currentCallCount);
    assertEquals(0, onReceivedErrorHelper.getCallCount());
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testNotCalledOnReload() throws Throwable {
    standardSetup();
    loadDataSync(
        mAwContents,
        mContentsClient.getOnPageFinishedHelper(),
        CommonResources.makeHtmlPageWithSimpleLinkTo(DATA_URL),
        "text/html",
        false);

    int callCountBeforeReload = mShouldOverrideUrlLoadingHelper.getCallCount();
    reloadSync(mAwContents, mContentsClient.getOnPageFinishedHelper());
    assertEquals(callCountBeforeReload, mShouldOverrideUrlLoadingHelper.getCallCount());
  }
  private void loadTestPageAndWaitForFirstFrame(
      final ScrollTestContainerView testContainerView,
      final TestAwContentsClient contentsClient,
      final String onscrollObserverName,
      final String extraContent)
      throws Exception {
    final JavascriptEventObserver firstFrameObserver = new JavascriptEventObserver();
    final String firstFrameObserverName = "firstFrameObserver";
    enableJavaScriptOnUiThread(testContainerView.getAwContents());

    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                firstFrameObserver.register(
                    testContainerView.getContentViewCore(), firstFrameObserverName);
              }
            });

    loadDataSync(
        testContainerView.getAwContents(),
        contentsClient.getOnPageFinishedHelper(),
        makeTestPage(onscrollObserverName, firstFrameObserverName, extraContent),
        "text/html",
        false);

    // We wait for "a couple" of frames for the active tree in CC to stabilize and for pending
    // tree activations to stop clobbering the root scroll layer's scroll offset. This wait
    // doesn't strictly guarantee that but there isn't a good alternative and this seems to
    // work fine.
    firstFrameObserver.waitForEvent(WAIT_TIMEOUT_MS);
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testNotCalledForIframeHttpNavigations() throws Throwable {
    standardSetup();

    final String iframeRedirectTargetUrl = createRedirectTargetPage();
    final String iframeRedirectUrl = mWebServer.setRedirect("/302.html", iframeRedirectTargetUrl);
    final String pageWithIframeUrl =
        addPageToTestServer(
            "/iframe_intercept.html",
            makeHtmlPageFrom("", "<iframe src=\"" + iframeRedirectUrl + "\" />"));

    final int shouldOverrideUrlLoadingCallCount = mShouldOverrideUrlLoadingHelper.getCallCount();

    assertEquals(0, mWebServer.getRequestCount(REDIRECT_TARGET_PATH));
    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), pageWithIframeUrl);

    // Wait for the redirect target URL to be fetched from the server.
    poll(
        new Callable<Boolean>() {
          @Override
          public Boolean call() throws Exception {
            return mWebServer.getRequestCount(REDIRECT_TARGET_PATH) == 1;
          }
        });

    assertEquals(shouldOverrideUrlLoadingCallCount, mShouldOverrideUrlLoadingHelper.getCallCount());
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testCalledFor302AfterPostNavigations() throws Throwable {
    // The reason POST requests are excluded is BUG 155250.
    standardSetup();

    final String redirectTargetUrl = createRedirectTargetPage();
    final String postToGetRedirectUrl = mWebServer.setRedirect("/302.html", redirectTargetUrl);
    final String postLinkUrl =
        addPageToTestServer(
            "/page_with_post_link.html",
            CommonResources.makeHtmlPageWithSimplePostFormTo(postToGetRedirectUrl));

    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), postLinkUrl);

    final int shouldOverrideUrlLoadingCallCount = mShouldOverrideUrlLoadingHelper.getCallCount();
    clickOnLinkUsingJs();
    mShouldOverrideUrlLoadingHelper.waitForCallback(shouldOverrideUrlLoadingCallCount);

    // Wait for the target URL to be fetched from the server.
    poll(
        new Callable<Boolean>() {
          @Override
          public Boolean call() throws Exception {
            return mWebServer.getRequestCount(REDIRECT_TARGET_PATH) == 1;
          }
        });

    assertEquals(
        redirectTargetUrl, mShouldOverrideUrlLoadingHelper.getShouldOverrideUrlLoadingUrl());
    assertTrue(mShouldOverrideUrlLoadingHelper.isRedirect());
    assertFalse(mShouldOverrideUrlLoadingHelper.hasUserGesture());
    assertTrue(mShouldOverrideUrlLoadingHelper.isMainFrame());
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testNotCalledForPostNavigations() throws Throwable {
    // The reason POST requests are excluded is BUG 155250.
    standardSetup();

    final String redirectTargetUrl = createRedirectTargetPage();
    final String postLinkUrl =
        addPageToTestServer(
            "/page_with_post_link.html",
            CommonResources.makeHtmlPageWithSimplePostFormTo(redirectTargetUrl));

    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), postLinkUrl);

    final int shouldOverrideUrlLoadingCallCount = mShouldOverrideUrlLoadingHelper.getCallCount();

    assertEquals(0, mWebServer.getRequestCount(REDIRECT_TARGET_PATH));
    clickOnLinkUsingJs();

    // Wait for the target URL to be fetched from the server.
    poll(
        new Callable<Boolean>() {
          @Override
          public Boolean call() throws Exception {
            return mWebServer.getRequestCount(REDIRECT_TARGET_PATH) == 1;
          }
        });

    // Since the targetURL was loaded from the test server it means all processing related
    // to dispatching a shouldOverrideUrlLoading callback had finished and checking the call
    // is stable.
    assertEquals(shouldOverrideUrlLoadingCallCount, mShouldOverrideUrlLoadingHelper.getCallCount());
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testCalledForDataUrl() throws Throwable {
    standardSetup();
    final String dataUrl =
        "data:text/html;base64,"
            + "PGh0bWw+PGhlYWQ+PHRpdGxlPmRhdGFVcmxUZXN0QmFzZTY0PC90aXRsZT48"
            + "L2hlYWQ+PC9odG1sPg==";
    loadDataSync(
        mAwContents,
        mContentsClient.getOnPageFinishedHelper(),
        CommonResources.makeHtmlPageWithSimpleLinkTo(dataUrl),
        "text/html",
        false);

    int callCount = mShouldOverrideUrlLoadingHelper.getCallCount();
    clickOnLinkUsingJs();

    mShouldOverrideUrlLoadingHelper.waitForCallback(callCount);
    assertTrue(
        "Expected URL that starts with 'data:' but got: <"
            + mShouldOverrideUrlLoadingHelper.getShouldOverrideUrlLoadingUrl()
            + "> instead.",
        mShouldOverrideUrlLoadingHelper.getShouldOverrideUrlLoadingUrl().startsWith("data:"));
    assertFalse(mShouldOverrideUrlLoadingHelper.isRedirect());
    assertFalse(mShouldOverrideUrlLoadingHelper.hasUserGesture());
    assertTrue(mShouldOverrideUrlLoadingHelper.isMainFrame());
  }
Esempio n. 19
0
  @Feature({"AndroidWebView", "Downloads"})
  @SmallTest
  public void testDownload() throws Throwable {
    AwTestContainerView testView = createAwTestContainerViewOnMainSync(mContentsClient);
    AwContents awContents = testView.getAwContents();

    final String data = "download data";
    final String contentDisposition = "attachment;filename=\"download.txt\"";
    final String mimeType = "text/plain";

    List<Pair<String, String>> downloadHeaders = new ArrayList<Pair<String, String>>();
    downloadHeaders.add(Pair.create("Content-Disposition", contentDisposition));
    downloadHeaders.add(Pair.create("Content-Type", mimeType));
    downloadHeaders.add(Pair.create("Content-Length", Integer.toString(data.length())));

    TestWebServer webServer = null;
    try {
      webServer = new TestWebServer(false);
      final String pageUrl = webServer.setResponse("/download.txt", data, downloadHeaders);
      final OnDownloadStartHelper downloadStartHelper = mContentsClient.getOnDownloadStartHelper();
      final int callCount = downloadStartHelper.getCallCount();
      loadUrlAsync(awContents, pageUrl);
      downloadStartHelper.waitForCallback(callCount);

      assertEquals(pageUrl, downloadStartHelper.getUrl());
      assertEquals(contentDisposition, downloadStartHelper.getContentDisposition());
      assertEquals(mimeType, downloadStartHelper.getMimeType());
      assertEquals(data.length(), downloadStartHelper.getContentLength());
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testCalledForUnsupportedSchemes() throws Throwable {
    final TestAwContentsClient contentsClient = new TestAwContentsClient();
    final AwTestContainerView testContainerView =
        createAwTestContainerViewOnMainSync(contentsClient);
    final AwContents awContents = testContainerView.getAwContents();
    final TestAwContentsClient.ShouldInterceptRequestHelper shouldInterceptRequestHelper =
        contentsClient.getShouldInterceptRequestHelper();

    final String unhandledSchemeUrl = "foobar://resource/1";
    int callCount = shouldInterceptRequestHelper.getCallCount();
    loadUrlAsync(awContents, unhandledSchemeUrl);
    shouldInterceptRequestHelper.waitForCallback(callCount);
    assertEquals(unhandledSchemeUrl, shouldInterceptRequestHelper.getUrls().get(0));
  }
  private void useAppCache() throws Exception {
    final String cachedFilePath = "/foo.js";
    final String cachedFileContents = "1 + 1;";
    mWebServer.setResponse(cachedFilePath, cachedFileContents, null);

    final String manifestPath = "/foo.manifest";
    final String manifestContents = "CACHE MANIFEST\nCACHE:\n" + cachedFilePath;
    List<Pair<String, String>> manifestHeaders = new ArrayList<Pair<String, String>>();
    manifestHeaders.add(Pair.create("Content-Disposition", "text/cache-manifest"));
    mWebServer.setResponse(manifestPath, manifestContents, manifestHeaders);

    final String pagePath = "/appcache.html";
    final String pageContents =
        "<html manifest=\""
            + manifestPath
            + "\">"
            + "<head><script src=\""
            + cachedFilePath
            + "\"></script></head></html>";
    String url = mWebServer.setResponse(pagePath, pageContents, null);

    loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
    executeJavaScriptAndWaitForResult(
        mAwContents, mContentsClient, "window.applicationCache.update();");
  }
    void assertThirdPartyIFrameCookieResult(String suffix, boolean expectedResult)
        throws Throwable {
      String key = "test" + suffix;
      String value = "value" + suffix;
      String iframePath = "/iframe_" + suffix + ".html";
      String pagePath = "/content_" + suffix + ".html";

      // We create a script which tries to set a cookie on a third party.
      String cookieUrl =
          toThirdPartyUrl(makeCookieScriptUrl(getWebServer(), iframePath, key, value));

      // Then we load it as an iframe.
      String url = makeIframeUrl(getWebServer(), pagePath, cookieUrl);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);

      if (expectedResult) {
        String cookie = mCookieManager.getCookie(cookieUrl);
        assertNotNull(cookie);
        validateCookies(cookie, key);
      } else {
        assertNull(mCookieManager.getCookie(cookieUrl));
      }

      // Clear the cookies.
      clearCookies();
      assertFalse(mCookieManager.hasCookies());
    }
 private boolean fileURLCanSetCookie(String suffix) throws Throwable {
   String value = "value" + suffix;
   String url = "file:///android_asset/cookie_test.html?value=" + value;
   loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
   String cookie = mCookieManager.getCookie(url);
   return cookie != null && cookie.contains("test=" + value);
 }
  @MediumTest
  @Feature({"AndroidWebView", "Privacy"})
  public void testAcceptCookie() throws Throwable {
    TestWebServer webServer = null;
    try {
      webServer = new TestWebServer(false);
      String path = "/cookie_test.html";
      String responseStr = "<html><head><title>TEST!</title></head><body>HELLO!</body></html>";
      String url = webServer.setResponse(path, responseStr, null);

      mCookieManager.setAcceptCookie(false);
      assertFalse(mCookieManager.acceptCookie());

      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      setCookieWithJavaScript("test1", "value1");
      assertNull(mCookieManager.getCookie(url));

      List<Pair<String, String>> responseHeaders = new ArrayList<Pair<String, String>>();
      responseHeaders.add(Pair.create("Set-Cookie", "header-test1=header-value1; path=" + path));
      url = webServer.setResponse(path, responseStr, responseHeaders);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      assertNull(mCookieManager.getCookie(url));

      mCookieManager.setAcceptCookie(true);
      assertTrue(mCookieManager.acceptCookie());

      url = webServer.setResponse(path, responseStr, null);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      setCookieWithJavaScript("test2", "value2");
      waitForCookie(url);
      String cookie = mCookieManager.getCookie(url);
      assertNotNull(cookie);
      validateCookies(cookie, "test2");

      responseHeaders = new ArrayList<Pair<String, String>>();
      responseHeaders.add(Pair.create("Set-Cookie", "header-test2=header-value2 path=" + path));
      url = webServer.setResponse(path, responseStr, responseHeaders);
      loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
      waitForCookie(url);
      cookie = mCookieManager.getCookie(url);
      assertNotNull(cookie);
      validateCookies(cookie, "test2", "header-test2");
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
 private void waitForNavigationRunnableAndAssertTitleChanged(Runnable navigationRunnable)
     throws Exception {
   CallbackHelper onPageFinishedHelper = mContentsClient.getOnPageFinishedHelper();
   final int callCount = onPageFinishedHelper.getCallCount();
   final String oldTitle = getTitleOnUiThread(mAwContents);
   getInstrumentation().runOnMainSync(navigationRunnable);
   onPageFinishedHelper.waitForCallback(callCount);
   assertFalse(oldTitle.equals(getTitleOnUiThread(mAwContents)));
 }
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testOnLoadResourceCalledWithCorrectUrl() throws Throwable {
    final TestAwContentsClient contentsClient = new TestAwContentsClient();
    final AwTestContainerView testContainerView =
        createAwTestContainerViewOnMainSync(contentsClient);
    final AwContents awContents = testContainerView.getAwContents();
    final TestAwContentsClient.OnLoadResourceHelper onLoadResourceHelper =
        contentsClient.getOnLoadResourceHelper();

    final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

    int callCount = onLoadResourceHelper.getCallCount();

    loadUrlAsync(awContents, aboutPageUrl);

    onLoadResourceHelper.waitForCallback(callCount);
    assertEquals(aboutPageUrl, onLoadResourceHelper.getUrl());
  }
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testDoesNotChangeReportedUrl() throws Throwable {
    final TestAwContentsClient contentsClient = new TestAwContentsClient();
    final AwTestContainerView testContainerView =
        createAwTestContainerViewOnMainSync(contentsClient);
    final AwContents awContents = testContainerView.getAwContents();
    final TestAwContentsClient.ShouldInterceptRequestHelper shouldInterceptRequestHelper =
        contentsClient.getShouldInterceptRequestHelper();

    shouldInterceptRequestHelper.setReturnValue(
        stringToInterceptedRequestData(makePageWithTitle("some title")));

    final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

    loadUrlSync(awContents, contentsClient.getOnPageFinishedHelper(), aboutPageUrl);

    assertEquals(aboutPageUrl, contentsClient.getOnPageFinishedHelper().getUrl());
    assertEquals(aboutPageUrl, contentsClient.getOnPageStartedHelper().getUrl());
  }
Esempio n. 28
0
  @SmallTest
  @Feature({"AndroidWebView"})
  public void testClearCacheMemoryAndDisk() throws Throwable {
    final AwTestContainerView testContainer = createAwTestContainerViewOnMainSync(mContentsClient);
    final AwContents awContents = testContainer.getAwContents();

    TestWebServer webServer = null;
    try {
      webServer = new TestWebServer(false);
      final String pagePath = "/clear_cache_test.html";
      List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
      // Set Cache-Control headers to cache this request. One century should be long enough.
      headers.add(Pair.create("Cache-Control", "max-age=3153600000"));
      headers.add(Pair.create("Last-Modified", "Wed, 3 Oct 2012 00:00:00 GMT"));
      final String pageUrl =
          webServer.setResponse(pagePath, "<html><body>foo</body></html>", headers);

      // First load to populate cache.
      clearCacheOnUiThread(awContents, true);
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl);
      assertEquals(1, webServer.getRequestCount(pagePath));

      // Load about:blank so next load is not treated as reload by webkit and force
      // revalidate with the server.
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), "about:blank");

      // No clearCache call, so should be loaded from cache.
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl);
      assertEquals(1, webServer.getRequestCount(pagePath));

      // Same as above.
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), "about:blank");

      // Clear cache, so should hit server again.
      clearCacheOnUiThread(awContents, true);
      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl);
      assertEquals(2, webServer.getRequestCount(pagePath));
    } finally {
      if (webServer != null) webServer.shutdown();
    }
  }
  @SmallTest
  @Feature({"AndroidWebView", "Navigation"})
  public void testCalledBeforeOnPageStarted() throws Throwable {
    standardSetup();
    OnPageStartedHelper onPageStartedHelper = mContentsClient.getOnPageStartedHelper();

    loadDataSync(
        mAwContents,
        mContentsClient.getOnPageFinishedHelper(),
        CommonResources.makeHtmlPageWithSimpleLinkTo(DATA_URL),
        "text/html",
        false);

    final int shouldOverrideUrlLoadingCallCount = mShouldOverrideUrlLoadingHelper.getCallCount();
    final int onPageStartedCallCount = onPageStartedHelper.getCallCount();
    setShouldOverrideUrlLoadingReturnValueOnUiThread(true);
    clickOnLinkUsingJs();

    mShouldOverrideUrlLoadingHelper.waitForCallback(shouldOverrideUrlLoadingCallCount);
    assertEquals(onPageStartedCallCount, onPageStartedHelper.getCallCount());
  }
Esempio n. 30
0
  @LargeTest
  @Feature({"AndroidWebView"})
  public void testCreateLoadDestroyManyTimes() throws Throwable {
    final int CREATE_AND_DESTROY_REPEAT_COUNT = 10;
    for (int i = 0; i < CREATE_AND_DESTROY_REPEAT_COUNT; ++i) {
      AwTestContainerView testView = createAwTestContainerViewOnMainSync(mContentsClient);
      AwContents awContents = testView.getAwContents();

      loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), "about:blank");
      destroyAwContentsOnMainSync(awContents);
    }
  }