Java Code Examples for com.gargoylesoftware.htmlunit.WebClient#setWebConnection()

The following examples show how to use com.gargoylesoftware.htmlunit.WebClient#setWebConnection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DomTextTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void asXml() throws Exception {
    final String unicodeString = "\u064A\u0627 \u0644\u064A\u064A\u0644";
    final String html = "<html>\n"
        + "<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head>\n"
        + "<body><span id='foo'>" + unicodeString + "</span></body></html>";

    final int[] expectedValues = {1610, 1575, 32, 1604, 1610, 1610, 1604};

    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    webConnection.setDefaultResponse(TextUtils.stringToByteArray(html, UTF_8), 200, "OK", MimeType.TEXT_HTML);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);
    final String xml = page.getHtmlElementById("foo").getFirstChild().asXml().trim();
    assertEquals(expectedValues.length, xml.length());
    int index = 0;
    for (final int expectedValue : expectedValues) {
        assertEquals(expectedValue, xml.codePointAt(index++));
    }
}
 
Example 2
Source File: HtmlScriptTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that cloned script nodes do not reload or re-execute their content (bug 1954869).
 * @throws Exception if an error occurs
 */
@Test
@Alerts("loaded")
public void scriptCloneDoesNotReloadScript() throws Exception {
    final String html = "<html><body><script src='" + URL_SECOND + "'></script></body></html>";
    final String js = "alert('loaded')";

    final WebClient client = getWebClient();

    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, html);
    conn.setResponse(URL_SECOND, js, MimeType.APPLICATION_JAVASCRIPT);
    client.setWebConnection(conn);

    final List<String> actual = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(actual));

    final HtmlPage page = client.getPage(URL_FIRST);
    assertEquals(2, conn.getRequestCount());

    page.cloneNode(true);
    assertEquals(2, conn.getRequestCount());

    assertEquals(getExpectedAlerts(), actual);
}
 
Example 3
Source File: XHtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void xpath2() throws Exception {
    final String html =
          "<html xmlns='http://www.w3.org/1999/xhtml' xmlns:xhtml='http://www.w3.org/1999/xhtml'>\n"
        + "<body><xhtml:div>foo</xhtml:div></body></html>";

    final MockWebConnection conn = new MockWebConnection();
    conn.setDefaultResponse(html, 200, "OK", "application/xhtml+xml");

    final WebClient client = getWebClient();
    client.setWebConnection(conn);
    final XHtmlPage page = client.getPage(URL_FIRST);

    assertEquals(1, page.getByXPath("//:body").size());
    assertEquals(0, page.getByXPath("//:BODY").size());
    assertEquals(0, page.getByXPath("//:bOdY").size());

    assertEquals(1, page.getByXPath("//xhtml:body").size());
    assertEquals(0, page.getByXPath("//xhtml:BODY").size());
    assertEquals(0, page.getByXPath("//xhtml:bOdY").size());

    assertEquals(1, page.getByXPath("//xhtml:div").size());
    assertEquals(0, page.getByXPath("//xhtml:DIV").size());
    assertEquals(0, page.getByXPath("//xhtml:dIv").size());
}
 
Example 4
Source File: XmlSerializerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void unsupportedProtocolImage() throws Exception {
    final String html =
            "<html>\n"
            + "<body>"
            + "  <img src='android-app://somehost'>\n"
            + "</body>\n"
            + "</html>";

    final WebClient client = getWebClient();
    final MockWebConnection connection = getMockWebConnection();
    connection.setResponse(URL_FIRST, html);
    client.setWebConnection(connection);

    final HtmlPage page = client.getPage(URL_FIRST);

    final File tmpFolder = tmpFolderProvider_.newFolder("hu");
    final File file = new File(tmpFolder, "hu_XmlSerializerTest_unsupportedProtocolImage.html");
    page.save(file);
    assertTrue(file.exists());
    assertTrue(file.isFile());
}
 
Example 5
Source File: HtmlNoScript2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void asText_jsDisabled() throws Exception {
    final String html = "<html><body>\n"
        + "<noscript>hello</noscript>"
        + "</body></html>";

    final String expected = "hello";

    final WebClient client = getWebClient();
    client.getOptions().setJavaScriptEnabled(false);

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(html);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);
    assertEquals(expected, page.getBody().asText());
}
 
Example 6
Source File: HtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void testNoSlashURL(final String url) throws Exception {
    final String firstContent
        = "<html><body>\n"
        + "<iframe id='myIFrame' src='" + url + "'></iframe>\n"
        + "</body></html>";

    final String secondContent = "<html><body></body></html>";
    final WebClient client = getWebClient();

    final URL secondURL = new URL("http://second/");
    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(secondURL, secondContent);

    client.setWebConnection(webConnection);

    final HtmlPage firstPage = client.getPage(URL_FIRST);
    final HtmlInlineFrame iframe = firstPage.getHtmlElementById("myIFrame");

    assertEquals(secondURL, iframe.getEnclosedPage().getUrl());
}
 
Example 7
Source File: WindowTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void prompt_noPromptHandler() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    final List<String> collectedAlerts = new ArrayList<>();
    final List<String> collectedPrompts = new ArrayList<>();

    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final String firstContent
        = "<html><head><title>First</title><script>function doTest() {alert(prompt('foo'))}</script>\n"
        + "</head><body onload='doTest()'></body></html>";

    webConnection.setResponse(URL_FIRST, firstContent);
    webClient.setWebConnection(webConnection);

    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    assertEquals(Collections.EMPTY_LIST, collectedPrompts);
    assertEquals(new String[] {"null"}, collectedAlerts);
}
 
Example 8
Source File: XmlSerializerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void unknownHostExceptionLink() throws Exception {
    final URL imageUrl = new URL(URL_FIRST, "none.jpg");
    final String html =
            "<html>\n"
            + "<body>"
            + "  <link rel='alternate' href='" + imageUrl.toExternalForm() + "'>\n"
            + "</body>\n"
            + "</html>";

    final WebClient client = getWebClient();
    final MockWebConnection connection = getMockWebConnection();
    connection.setThrowable(imageUrl, new UnknownHostException(imageUrl.toExternalForm()));
    connection.setResponse(URL_FIRST, html);
    client.setWebConnection(connection);

    final HtmlPage page = client.getPage(URL_FIRST);

    final File tmpFolder = tmpFolderProvider_.newFolder("hu");
    final File file = new File(tmpFolder, "hu_XmlSerializerTest_unknownHostExceptionLink.html");
    page.save(file);
    assertTrue(file.exists());
    assertTrue(file.isFile());
}
 
Example 9
Source File: XHtmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a simplified real-life response from Ajax4jsf. Originally located in
 * {@link com.gargoylesoftware.htmlunit.xml.XmlPageTest}.
 * @throws Exception if an error occurs
 */
@Test
public void a4jResponse() throws Exception {
    final String content = "<html xmlns='http://www.w3.org/1999/xhtml'><head>\n"
        + "<script src='//:'></script>\n"
        + "</head><body><span id='j_id216:outtext'>Echo Hello World</span></body></html>";
    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(content, 200, "OK", MimeType.TEXT_XML);
    client.setWebConnection(webConnection);
    final Page page = client.getPage(URL_FIRST);
    assertEquals(URL_FIRST, page.getUrl());
    assertEquals("OK", page.getWebResponse().getStatusMessage());
    assertEquals(HttpStatus.SC_OK, page.getWebResponse().getStatusCode());
    assertEquals(MimeType.TEXT_XML, page.getWebResponse().getContentType());
    assertTrue(XHtmlPage.class.isInstance(page));
}
 
Example 10
Source File: DelegatingWebConnectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyExampleInClassLevelJavadoc() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);

	WebClient webClient = new WebClient();

	MockMvc mockMvc = MockMvcBuilders.standaloneSetup(TestController.class).build();
	MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc);
	mockConnection.setWebClient(webClient);

	WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
	WebConnection httpConnection = new HttpWebConnection(webClient);
	WebConnection webConnection = new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection));

	webClient.setWebConnection(webConnection);

	Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js");
	assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
	assertThat(page.getWebResponse().getContentAsString(), not(isEmptyString()));
}
 
Example 11
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void referencingVariablesFromOneScriptToAnother_Regression() throws Exception {
    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

    final String htmlContent
        = "<html><head><title>foo</title><script src='./test.js'></script>\n"
        + "<script>var testLocalVariable = new Array();</script>\n"
        + "</head><body onload='testNestedMethod();' >\n"
        + "<form name='form1' method='POST' action='../foo' >\n"
        + "  <input type='submit' value='Login' name='loginButton'>\n"
        + "</form></body></html>";

    final String jsContent
        = "function testNestedMethod() {\n"
        + "  if (testLocalVariable == null)\n"
        + "    testLocalVariable = 'foo';\n"
        + "} ";

    webConnection.setResponse(URL_FIRST, htmlContent);
    webConnection.setResponse(new URL(URL_FIRST, "test.js"), jsContent, "text/javascript");
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);
    assertEquals("foo", page.getTitleText());
}
 
Example 12
Source File: HtmlInlineFrameTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * The iframe has no source and is filled from javascript.
 * The javascript writes windows charactes into the iframe content.
 * @throws Exception if an error occurs
 */
@Test
public void frameContentCreationViaJavascriptISO_8859_1() throws Exception {
    final String html =
        "<html><head><title>frames</title></head>\n"
        + "<body>\n"
        + "<iframe name='foo'></iframe>\n"
        + "<script type='text/javascript'>\n"
        + "var doc = window.frames['foo'].document;\n"
        + "doc.open();\n"
        + "doc.write('<html><body><div id=\"myContent\">\u00e4\u00f6\u00fc</div></body></html>');\n"
        + "doc.close();\n"
        + "</script>\n"
        + "<body>\n"
        + "</html>";

    final WebClient webClient = getWebClientWithMockWebConnection();
    final MockWebConnection conn = getMockWebConnection();
    webClient.setWebConnection(conn);

    conn.setResponse(URL_FIRST, html, "text/html; charset=ISO-8859-1", ISO_8859_1);
    final HtmlPage page = webClient.getPage(URL_FIRST);

    final HtmlPage enclosedPage = (HtmlPage) page.getFrames().get(0).getEnclosedPage();
    final HtmlElement element = enclosedPage.getHtmlElementById("myContent");
    final String content = element.asText();
    assertEquals("\u00e4\u00f6\u00fc", content);
}
 
Example 13
Source File: JavaScriptEngineTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void prototypeScope(final String name, final String value) throws Exception {
    final String content1
        = "<html><head>\n"
        + "<script>\n"
        + "window.open('second.html', 'secondWindow');\n"
        + "</script>\n"
        + "</head><body></body></html>";

    final String content2
        = "<html><head>\n"
        + "<script>\n"
        + "alert('in page 2');\n"
        + name + ".prototype.foo = function() {\n"
        + "   alert('in foo');\n"
        + "};\n"
        + "var x = " + value + ";\n"
        + "x.foo();\n"
        + "</script>\n"
        + "</head><body></body></html>";

    final String[] expectedAlerts = {"in page 2", "in foo"};

    final WebClient client = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setDefaultResponse(content2);
    webConnection.setResponse(URL_FIRST, content1);
    client.setWebConnection(webConnection);

    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    client.getPage(URL_FIRST);
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 14
Source File: HtmlArea2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private WebClient createWebClient(final String onClick) throws IOException {
    final MockWebConnection webConnection = new MockWebConnection();

    final URL urlImage = new URL(URL_FIRST, "img.jpg");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);
        final List<NameValuePair> emptyList = Collections.emptyList();
        webConnection.setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList);
    }

    final String firstContent
        = "<html><head><title>first</title></head><body>\n"
        + "<img src='" + urlImage + "' width='145' height='126' usemap='#planetmap'>\n"
        + "<map id='planetmap' name='planetmap'>\n"
        + "<area shape='rect' onClick=\"" + onClick + "\" coords='0,0,82,126' id='second' "
        + "href='" + URL_SECOND + "'>\n"
        + "<area shape='circle' coords='90,58,3' id='third' href='" + URL_THIRD + "'>\n"
        + "</map></body></html>";
    final String secondContent = "<html><head><title>second</title></head><body></body></html>";
    final String thirdContent = "<html><head><title>third</title></head><body></body></html>";

    final WebClient client = getWebClient();

    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);
    webConnection.setResponse(URL_THIRD, thirdContent);

    client.setWebConnection(webConnection);

    return client;
}
 
Example 15
Source File: HtmlAnchor2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void click_onClickHandler_returnFalse() throws Exception {
    final String firstContent
        = "<html><head><title>First</title></head><body>\n"
        + "<a href='http://www.foo1.com' id='a1'>link to foo1</a>\n"
        + "<a href='" + URL_SECOND + "' id='a2' "
        + "onClick='alert(\"clicked\");return false;'>link to foo2</a>\n"
        + "<a href='http://www.foo3.com' id='a3'>link to foo3</a>\n"
        + "</body></html>";
    final String secondContent = "<html><head><title>Second</title></head><body></body></html>";

    final WebClient client = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);
    client.setWebConnection(webConnection);

    final HtmlPage page = client.getPage(URL_FIRST);
    final HtmlAnchor anchor = page.getHtmlElementById("a2");

    assertEquals(Collections.EMPTY_LIST, collectedAlerts);

    final HtmlPage secondPage = anchor.click();

    assertEquals(new String[] {"clicked"}, collectedAlerts);
    assertSame(page, secondPage);
}
 
Example 16
Source File: ActiveXObjectTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void setProperty() throws Exception {
    if (!getBrowserVersion().isIE()) {
        return;
    }
    if (!isJacobInstalled()) {
        return;
    }
    final String html = "<html><head><title>foo</title><script>\n"
        + "  function test() {\n"
        + "    try {\n"
        + "      var ie = new ActiveXObject('InternetExplorer.Application');\n"
        + "      var full = ie.FullScreen;\n"
        + "      ie.FullScreen = true;\n"
        + "      alert(ie.FullScreen);\n"
        + "      ie.FullScreen = full;\n"
        + "    } catch(e) {alert('exception: ' + e.message);}\n"
        + "  }\n"
        + "</script></head><body onload='test()'>\n"
        + "</body></html>";

    final String[] expectedAlerts = {"true"};
    createTestPageForRealBrowserIfNeeded(html, expectedAlerts);

    final WebClient client = getWebClient();
    client.getOptions().setActiveXNative(true);
    final List<String> collectedAlerts = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, html);
    client.setWebConnection(webConnection);

    client.getPage(URL_FIRST);
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 17
Source File: AttachmentTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Tests {@link Attachment#getSuggestedFilename()}.
 * @throws Exception if an error occurs
 */
@Test
public void filename() throws Exception {
    final String content = "<html>But is it really?</html>";

    final WebClient client = getWebClient();
    final MockWebConnection conn = new MockWebConnection();
    client.setWebConnection(conn);
    final List<Attachment> attachments = new ArrayList<>();
    client.setAttachmentHandler(new CollectingAttachmentHandler(attachments));

    final List<NameValuePair> headers1 = new ArrayList<>();
    headers1.add(new NameValuePair("Content-Disposition", "attachment;filename=\"hello.html\""));
    conn.setResponse(URL_FIRST, content, 200, "OK", MimeType.TEXT_HTML, headers1);
    client.getPage(URL_FIRST);
    final Attachment result = attachments.get(0);
    assertEquals(result.getSuggestedFilename(), "hello.html");
    attachments.clear();

    final List<NameValuePair> headers2 = new ArrayList<>();
    headers2.add(new NameValuePair("Content-Disposition", "attachment; filename=hello2.html; something=else"));
    conn.setResponse(URL_SECOND, content, 200, "OK", MimeType.TEXT_PLAIN, headers2);
    client.getPage(URL_SECOND);
    final Attachment result2 = attachments.get(0);
    assertEquals(result2.getSuggestedFilename(), "hello2.html");
    assertEquals(content, ((TextPage) result2.getPage()).getContent());
    attachments.clear();

    final List<NameValuePair> headers3 = new ArrayList<>();
    headers3.add(new NameValuePair("Content-Disposition", "attachment; filename="));
    conn.setResponse(URL_SECOND, content, 200, "OK", MimeType.TEXT_PLAIN, headers3);
    client.getPage(URL_SECOND);
    final Attachment result3 = attachments.get(0);
    assertNull(result3.getSuggestedFilename());
    assertEquals(content, ((TextPage) result3.getPage()).getContent());
    attachments.clear();

    final List<NameValuePair> headers4 = new ArrayList<>();
    headers4.add(new NameValuePair("Content-Disposition", "attachment"));
    final byte[] contentb = new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
    conn.setResponse(URL_THIRD, contentb, 200, "OK", "application/x-rubbish", headers4);
    client.getPage(URL_THIRD);
    final Attachment result4 = attachments.get(0);
    final InputStream result4Stream = result4.getPage().getWebResponse().getContentAsStream();
    assertNull(result4.getSuggestedFilename());
    assertEquals(result4.getPage().getWebResponse().getContentType(), "application/x-rubbish");
    HttpWebConnectionTest.assertEquals(new ByteArrayInputStream(contentb), result4Stream);
    attachments.clear();
}
 
Example 18
Source File: WindowTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Test for the <tt>showModalDialog</tt> method.
 * This tests blocking until the window gets closed.
 * Can not currently be tested with WebDriver
 * https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/284
 *
 * To fix this, we need to allow user to interact with the opened dialog before showModalDialog() returns
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = {"undefined", "result", "finished"},
        CHROME = {"undefined", "not available"},
        FF = {"undefined", "not available"},
        FF68 = {"undefined", "not available"},
        FF60 = {"undefined", "not available"})
@NotYetImplemented(IE)
public void showModalDialogWithButton() throws Exception {
    final String html1
        = "<html><head>\n"
        + "  <script>\n"
        + "    function test() {\n"
        + "      alert(window.returnValue);\n"
        + "      if (!window.showModalDialog) {alert('not available'); return; }\n"
        + "      var res = showModalDialog('myDialog.html', null, 'dialogHeight:300px; dialogLeft:200px;');\n"
        + "      alert(res);\n"
        + "      alert('finished');\n"
        + "    }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body>\n"
        + "  <button onclick='test()' id='openDlg'>Test</button>\n"
        + "</body></html>";

    final String html2
        = "<html><head>\n"
        + "</head>\n"
        + "<body>\n"
        + "  <button id='closeDlg' onclick='window.returnValue = \"result\"; window.close();'></button>\n"
        + "</body>\n"
        + "</html>";

    final WebClient client = getWebClient();
    final List<String> actual = new ArrayList<>();
    client.setAlertHandler(new CollectingAlertHandler(actual));

    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, html1);
    conn.setResponse(new URL(URL_FIRST, "myDialog.html"), html2);
    client.setWebConnection(conn);

    final HtmlPage page = getWebClient().getPage(URL_FIRST);
    final HtmlElement button = page.getHtmlElementById("openDlg");
    button.click();

    // TODO: <button id='closeDlg'> should be clicked
    assertEquals(getExpectedAlerts(), actual);
}
 
Example 19
Source File: XMLHttpRequest3Test.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the value of "this" in handler.
 * @throws Exception if the test fails
 */
@Test
@Alerts("this == request")
public void thisValueInHandler() throws Exception {
    final String html =
          "<html>\n"
        + "  <head>\n"
        + "    <title>XMLHttpRequest Test</title>\n"
        + "    <script>\n"
        + "      var request;\n"
        + "      function testAsync() {\n"
        + "        request = new XMLHttpRequest();\n"
        + "        request.onreadystatechange = onReadyStateChange;\n"
        + "        request.open('GET', 'foo.xml', true);\n"
        + "        request.send('');\n"
        + "      }\n"
        + "      function onReadyStateChange() {\n"
        + "        if (request.readyState == 4) {\n"
        + "          if (this == request)\n"
        + "            alert('this == request');\n"
        + "          else if (this == onReadyStateChange)\n"
        + "            alert('this == handler');\n"
        + "          else alert('not expected: ' + this)\n"
        + "        }\n"
        + "      }\n"
        + "    </script>\n"
        + "  </head>\n"
        + "  <body onload='testAsync()'>\n"
        + "  </body>\n"
        + "</html>";

    final WebClient client = getWebClient();
    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, html);
    conn.setDefaultResponse("");
    client.setWebConnection(conn);
    client.getPage(URL_FIRST);

    assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(1000));
    assertEquals(getExpectedAlerts(), collectedAlerts);
}
 
Example 20
Source File: FalsifyingWebConnectionTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void simulateHttpError() throws Exception {
    final WebClient webClient = getWebClient();

    final String html = "<html><head>\n"
        + "<script src='myJs.js'></script>\n"
        + "</head><body>\n"
        + "hello world!"
        + "<body></html>";

    final MockWebConnection mockConnection = new MockWebConnection();
    mockConnection.setResponse(URL_FIRST, html);
    mockConnection.setResponse(new URL(URL_FIRST, "myJs.js"), "alert('hello');");
    webClient.setWebConnection(mockConnection);

    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    // first test this "site" when everything is ok
    webClient.getPage(URL_FIRST);
    final String[] expectedAlerts = {"hello"};
    assertEquals(expectedAlerts, collectedAlerts);

    // now simulate some server problems

    // create a WebConnection that filters google-analytics scripts
    // c'tor configures connection on the web client
    try (FalsifyingWebConnection connection = new FalsifyingWebConnection(webClient) {
        @Override
        public WebResponse getResponse(final WebRequest request) throws IOException {
            if (request.getUrl().getPath().endsWith(".js")) {
                return createWebResponse(request, "", MimeType.TEXT_HTML, 500, "Application Error");
            }
            return super.getResponse(request);
        }
    }) {

        try {
            webClient.getPage(URL_FIRST);
            fail("HTTP Exception expected!");
        }
        catch (final FailingHttpStatusCodeException e) {
            // that's fine
        }
    }
}