Java Code Examples for com.gargoylesoftware.htmlunit.html.HtmlAnchor#click()

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlAnchor#click() . 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: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void acceptEquivalence(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	// http://localhost:8080/multiplayer/
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor acceptEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			acceptEquivalenceLink = a;
			break;
		}
	}

	if (!acceptEquivalenceLink.getHrefAttribute().startsWith("http://localhost:8080/")) {
		acceptEquivalenceLink.setAttribute("href",
				"http://localhost:8080/" + acceptEquivalenceLink.getHrefAttribute());
	}

	System.out.println(
			"DoubleEquivalenceSubmissionTest.HelperUser.acceptEquivalence() Accepting equivalence on game "
					+ gameId);
	acceptEquivalenceLink.click();
}
 
Example 2
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void claimEquivalenceOnLine(int gameId, int line)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage("http://localhost:8080" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor claimEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?equivLines=" + line)) {
			claimEquivalenceLink = a;
			break;
		}
	}

	if (!claimEquivalenceLink.getHrefAttribute().startsWith("http://localhost:8080/")) {
		claimEquivalenceLink.setAttribute("href",
				"http://localhost:8080/" + claimEquivalenceLink.getHrefAttribute());
	}
	claimEquivalenceLink.click();
}
 
Example 3
Source File: HTMLFormElement2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void formSubmitDoesntCallOnSubmit() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<form name='form1' method='get' action='" + URL_SECOND + "' onsubmit=\"this.action = 'foo.html'\">\n"
        + "  <input type='submit' />\n"
        + "</form>\n"
        + "<a href='javascript:document.form1.submit()' id='link1'>Click me</a>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>second</title></head><body>\n"
        + "<p>hello world</p>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse(secondContent);

    final HtmlPage page = loadPageWithAlerts(html);
    final HtmlAnchor link = page.getHtmlElementById("link1");
    final HtmlPage page2 = link.click();
    assertEquals("second", page2.getTitleText());
}
 
Example 4
Source File: DoubleEquivalenceSubmissionTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void joinOpenGame(int gameID, boolean isAttacker) throws FailingHttpStatusCodeException, IOException {
	HtmlPage openGames = browser.getPage("http://localhost:8080" + Paths.GAMES_OVERVIEW);

	// Really we can simply click on that link once we know the gameID,
	// no need to go to openGame page
	HtmlAnchor joinLink = null;
	for (HtmlAnchor a : openGames.getAnchors()) {
		if (a.getHrefAttribute().contains(
				Paths.BATTLEGROUND_GAME + "?" + ((isAttacker) ? "attacker" : "defender") + "=1&gameId=" + gameID)) {
			joinLink = a;
			break;
		}
	}
	if (!joinLink.getHrefAttribute().startsWith("http://localhost:8080/")) {
		joinLink.setAttribute("href", "http://localhost:8080/" + joinLink.getHrefAttribute());
	}
	HtmlPage page = joinLink.click();
}
 
Example 5
Source File: LocationTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that location.reload() works correctly.
 * @throws Exception if the test fails
 */
@Test
public void reload() throws Exception {
    final String content =
          "<html>\n"
        + "  <head><title>test</title></head>\n"
        + "  <body>\n"
        + "    <a href='javascript:window.location.reload();' id='link1'>reload</a>\n"
        + "  </body>\n"
        + "</html>";

    final HtmlPage page1 = loadPage(content);
    final HtmlAnchor link = page1.getHtmlElementById("link1");
    final HtmlPage page2 = link.click();

    assertEquals(page1.getTitleText(), page2.getTitleText());
    assertNotSame(page1, page2);
}
 
Example 6
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void acceptEquivalence(int gameId)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	// codedefendersHome+"/multiplayer/
	HtmlPage playPage = browser.getPage(codedefendersHome + "" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor acceptEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?acceptEquivalent=")) {
			acceptEquivalenceLink = a;
			break;
		}
	}

	if (!acceptEquivalenceLink.getHrefAttribute().startsWith(codedefendersHome + "/")) {
		acceptEquivalenceLink.setAttribute("href",
				codedefendersHome + "/" + acceptEquivalenceLink.getHrefAttribute());
	}

	System.out
			.println("DoubleEquivalenceSubmissionTest.HelperUser.acceptEquivalence() Accepting equivalence on game "
					+ gameId);
	acceptEquivalenceLink.click();
}
 
Example 7
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void claimEquivalenceOnLine(int gameId, int line)
		throws FailingHttpStatusCodeException, MalformedURLException, IOException {
	HtmlPage playPage = browser.getPage(codedefendersHome + "" + Paths.BATTLEGROUND_GAME + "?gameId=" + gameId);
	HtmlAnchor claimEquivalenceLink = null;
	for (HtmlAnchor a : playPage.getAnchors()) {
		if (a.getHrefAttribute().contains(Paths.BATTLEGROUND_GAME + "?equivLines=" + line)) {
			claimEquivalenceLink = a;
			break;
		}
	}

	if (!claimEquivalenceLink.getHrefAttribute().startsWith(codedefendersHome + "/")) {
		claimEquivalenceLink.setAttribute("href",
				codedefendersHome + "/" + claimEquivalenceLink.getHrefAttribute());
	}
	claimEquivalenceLink.click();
}
 
Example 8
Source File: HelperUser.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns the landing HtmlPage after joining the game
 *
 * @param gameID
 * @param isAttacker
 * @return
 * @throws FailingHttpStatusCodeException
 * @throws IOException
 */
public HtmlPage joinOpenGame(int gameID, boolean isAttacker) throws FailingHttpStatusCodeException, IOException {
	HtmlPage openGames = browser.getPage(codedefendersHome + Paths.GAMES_OVERVIEW);

	// Really we can simply click on that link once we know the gameID,
	// no need to go to openGame page
	HtmlAnchor joinLink = null;
	for (HtmlAnchor a : openGames.getAnchors()) {
		if (a.getHrefAttribute()
				.contains(Paths.BATTLEGROUND_GAME + "?" + ((isAttacker) ? "attacker" : "defender") + "=1&gameId=" + gameID)) {
			joinLink = a;
			break;
		}
	}
	if (!joinLink.getHrefAttribute().startsWith(codedefendersHome + "/")) {
		joinLink.setAttribute("href", codedefendersHome + "/" + joinLink.getHrefAttribute());
	}

	return joinLink.click();
}
 
Example 9
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void requestAuthorizeClientWhenInvalidClientThenStatusBadRequest() throws Exception {
	HtmlPage page = this.webClient.getPage("/");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();
	clientAnchorElement.setAttribute("href", clientAnchorElement.getHrefAttribute() + "-invalid");

	WebResponse response = null;
	try {
		clientAnchorElement.click();
	} catch (FailingHttpStatusCodeException ex) {
		response = ex.getResponse();
	}

	assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
}
 
Example 10
Source File: TestResultLinksTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@LocalData
@Test
public void testFailureLinks() throws Exception {
    FreeStyleBuild build = project.scheduleBuild2(0).get(10, TimeUnit.SECONDS);
    rule.assertBuildStatus(Result.UNSTABLE, build);

    TestResult theOverallTestResult =   build.getAction(TestResultAction.class).getResult();
    CaseResult theFailedTestCase = theOverallTestResult.getFailedTests().get(0);
    String relativePath = theFailedTestCase.getRelativePathFrom(theOverallTestResult);
    System.out.println("relative path seems to be: " + relativePath); 

    WebClient wc = rule.createWebClient();

    String testReportPageUrl =  project.getLastBuild().getUrl() + "/testReport";
    HtmlPage testReportPage = wc.goTo( testReportPageUrl );

    Page packagePage = testReportPage.getAnchorByText("tacoshack.meals").click();
    rule.assertGoodStatus(packagePage); // I expect this to work; just checking that my use of the APIs is correct.

    // Now we're on that page. We should be able to find a link to the failed test in there.
    HtmlAnchor anchor = testReportPage.getAnchorByText("tacoshack.meals.NachosTest.testBeanDip");
    String href = anchor.getHrefAttribute();
    System.out.println("link is : " + href);
    Page failureFromLink = anchor.click();
    rule.assertGoodStatus(failureFromLink);

    // Now check the >>> link -- this is harder, because we can't do the javascript click handler properly
    // The summary page is just tack on /summary to the url for the test

}
 
Example 11
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
private WebResponse followLinkDisableRedirects(HtmlAnchor anchorElement) throws Exception {
	WebResponse response = null;
	try {
		// Disable the automatic redirection (which will trigger
		// an exception) so that we can capture the response
		this.webClient.getOptions().setRedirectEnabled(false);
		anchorElement.click();
	} catch (FailingHttpStatusCodeException ex) {
		response = ex.getResponse();
		this.webClient.getOptions().setRedirectEnabled(true);
	}
	return response;
}
 
Example 12
Source File: AttachmentTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests attachment callbacks and the contents of attachments.
 * @throws Exception if an error occurs
 */
@Test
public void contentDispositionCaseInsensitive() throws Exception {
    final String content1 = "<html><body>\n"
        + "<form method='POST' name='form' action='" + URL_SECOND + "'>\n"
        + "<input type='submit' value='ok'>\n"
        + "</form>\n"
        + "<a href='#' onclick='document.form.submit()'>click me</a>\n"
        + "</body></html>";
    final String content2 = "download file contents";

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

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Content-Disposition", "AttachMent"));

    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, content1);
    conn.setResponse(URL_SECOND, content2, 200, "OK", MimeType.TEXT_HTML, headers);
    client.setWebConnection(conn);
    assertTrue(attachments.isEmpty());

    final HtmlPage result = client.getPage(URL_FIRST);
    final HtmlAnchor anchor = result.getAnchors().get(0);
    final Page clickResult = anchor.click();
    assertEquals(result, clickResult);
    assertEquals(1, attachments.size());
}
 
Example 13
Source File: HtmlUnitWebScrapingLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1() throws Exception {
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setJavaScriptEnabled(false);

    final String url = "http://www.baeldung.com/full_archive";
    final HtmlPage page = webClient.getPage(url);
    final String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a";
    final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath(xpath).get(0);
    final HtmlPage postPage = latestPostLink.click();

    final List<Object> h1 = postPage.getByXPath("//h1");

    Assert.assertTrue(h1.size() > 0);
}
 
Example 14
Source File: LocationTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that modifying <tt>window.location.hash</tt> works, but that it doesn't
 * force the page to reload from the server. This is very important for the Dojo
 * unit tests, which will keep reloading themselves if the page gets reloaded.
 *
 * @throws Exception if the test fails
 */
@Test
public void setHash() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection conn = new MockWebConnection();

    final String html
        = "<html><head><title>Test</title></head><body>\n"
        + "<a id='a' onclick='alert(location.hash);location.hash=\"b\";alert(location.hash);'>go</a>\n"
        + "<h2 id='b'>...</h2></body></html>";

    conn.setResponse(URL_FIRST, html);
    webClient.setWebConnection(conn);

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

    final HtmlPage page = webClient.getPage(URL_FIRST);
    final HtmlAnchor anchor = page.getHtmlElementById("a");
    final HtmlPage page2 = anchor.click();

    // Verify that it worked.
    final String[] expected = new String[] {"", "#b"};
    assertEquals(expected, actual);

    // Verify that we didn't reload the page.
    assertTrue(page == page2);
    assertEquals(URL_FIRST, conn.getLastWebRequest().getUrl());
}
 
Example 15
Source File: HTMLElement3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void clickHashAnchor() throws Exception {
    final String html
        = "<html><head><title>HashAnchor</title></head>\n"
        + "<body>\n"
        + "  <script language='javascript'>\n"
        + "    function test() {alert('test hash');}\n"
        + "  </script>\n"
        + "  <a onClick='javascript:test();' href='#' name='hash'>Click</a>\n"
        + "</body>\n"
        + "</html>";
    final String[] expectedAlerts = {"test hash"};
    // first use direct load
    final List<String> loadCollectedAlerts = new ArrayList<>();
    final HtmlPage loadPage = loadPage(html, loadCollectedAlerts);
    final HtmlAnchor loadHashAnchor = loadPage.getAnchorByName("hash");
    loadHashAnchor.click();

    assertEquals(expectedAlerts, loadCollectedAlerts);

    // finally try via the client
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, html);
    webClient.setWebConnection(webConnection);
    final CollectingAlertHandler clientCollectedAlertsHandler = new CollectingAlertHandler();
    webClient.setAlertHandler(clientCollectedAlertsHandler);
    final HtmlPage clientPage = webClient.getPage(URL_FIRST);
    final HtmlAnchor clientHashAnchor = clientPage.getAnchorByName("hash");
    clientHashAnchor.click();

    assertEquals(expectedAlerts, clientCollectedAlertsHandler.getCollectedAlerts());
}
 
Example 16
Source File: Event3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void testEventBubblingReturns(final String onclick1,
    final String onclick2, final String onclick3, final boolean changesPage) throws Exception {

    final String html1
        = "<html><head><title>First</title></head><body>\n"
        + "<div onclick='alert(\"d\"); " + onclick1 + "'>\n"
        + "<span onclick='alert(\"s\"); " + onclick2 + "'>\n"
        + "<a href='" + URL_SECOND + "' id='a' onclick='alert(\"a\"); " + onclick3 + "'>go</a>\n"
        + "</span>\n"
        + "</div>\n"
        + "</body></html>";

    final String html2 = "<html><head><title>Second</title></head><body></body></html>";

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

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(URL_FIRST, html1);
    webConnection.setResponse(URL_SECOND, html2);

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

    final HtmlPage secondPage = anchor.click();
    assertEquals(new String[] {"a", "s", "d"}, collectedAlerts);

    if (changesPage) {
        assertNotSame(page, secondPage);
    }
    else {
        assertSame(page, secondPage);
    }
}
 
Example 17
Source File: JmxWebHandlerTest.java    From simplejmx with ISC License 4 votes vote down vote up
@Test(timeout = 10000)
public void testSimple() throws Exception {
	WebClient webClient = new WebClient();
	HtmlPage page = webClient.getPage("http://" + WEB_SERVER_NAME + ":" + WEB_SERVER_PORT);
	assertTrue(page.asText().contains("JMX Domains"));

	String domain = "java.lang";
	HtmlAnchor anchor = page.getAnchorByText(domain);
	assertNotNull(anchor);
	page = anchor.click();
	assertTrue(page.asText().contains("Beans in domain " + domain));

	anchor = page.getAnchorByName("text");
	TextPage textPage = anchor.click();
	String bean = "type=Memory";
	assertTrue(textPage.getContent().contains(domain + ":" + bean));

	anchor = page.getAnchorByText(bean);
	page = anchor.click();
	assertTrue(page.asText().contains("Information about object " + domain + ":" + bean));

	anchor = page.getAnchorByName("text");
	textPage = anchor.click();
	assertTrue(textPage.getContent().contains("Verbose"));

	HtmlForm form = page.getFormByName("Verbose");
	assertNotNull(form);
	HtmlInput input = form.getInputByName("val");
	assertEquals("false", input.getValueAttribute());
	assertNotNull(input);
	input.setValueAttribute("true");
	HtmlElement button = (HtmlElement) page.createElement("button");
	button.setAttribute("type", "submit");
	// append the button to the form to simulate
	form.appendChild(button);
	// submit the form
	page = button.click();
	assertTrue(page.asText().contains("Information about object " + domain + ":" + bean));

	form = page.getFormByName("Verbose");
	assertNotNull(form);
	input = form.getInputByName("val");
	assertEquals("true", input.getValueAttribute());

	String operation = "gc";
	form = page.getFormByName(operation);
	assertNotNull(form);
	input = form.getInputByValue(operation);
	page = input.click();

	assertTrue(page.asText().contains("Invoking Operation " + operation));
	assertTrue(page.asText().contains(operation + " method successfully invoked."));

	anchor = page.getAnchorByName("text");
	assertNotNull(anchor);
	textPage = anchor.click();
	assertEquals(operation + " method successfully invoked.\n", textPage.getContent());
}
 
Example 18
Source File: AttachmentTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Tests attachment callbacks and the contents of attachments.
 * @throws Exception if an error occurs
 */
@Test
public void handleResponseFromHanlder() throws Exception {
    final String content1 = "<html><body>\n"
        + "<form method='POST' name='form' action='" + URL_SECOND + "'>\n"
        + "<input type='submit' value='ok'>\n"
        + "</form>\n"
        + "<a href='#' onclick='document.form.submit()'>click me</a>\n"
        + "</body></html>";
    final String content2 = "download file contents";

    final WebClient client = getWebClient();
    final List<WebResponse> attachments = new ArrayList<>();

    client.setAttachmentHandler(new AttachmentHandler() {
        @Override
        public boolean handleAttachment(final WebResponse response) {
            attachments.add(response);
            return true;
        }

        @Override
        public void handleAttachment(final Page page) {
            throw new IllegalAccessError("handleAttachment(Page) called");
        }
    });

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Content-Disposition", "attachment"));

    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, content1);
    conn.setResponse(URL_SECOND, content2, 200, "OK", MimeType.TEXT_HTML, headers);
    client.setWebConnection(conn);
    assertTrue(attachments.isEmpty());

    final HtmlPage result = client.getPage(URL_FIRST);
    final HtmlAnchor anchor = result.getAnchors().get(0);
    final Page clickResult = anchor.click();
    assertEquals(result, clickResult);
    assertEquals(1, attachments.size());
    assertEquals(1, client.getWebWindows().size());

    final WebResponse attachmentResponse = attachments.get(0);
    final InputStream attachmentStream = attachmentResponse.getContentAsStream();
    HttpWebConnectionTest.assertEquals(new ByteArrayInputStream(content2.getBytes()), attachmentStream);
    assertEquals(MimeType.TEXT_HTML, attachmentResponse.getContentType());
    assertEquals(200, attachmentResponse.getStatusCode());
    assertEquals(URL_SECOND, attachmentResponse.getWebRequest().getUrl());
}
 
Example 19
Source File: AttachmentTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Tests attachment callbacks and the contents of attachments.
 * @throws Exception if an error occurs
 */
@Test
public void basic() throws Exception {
    final String content1 = "<html><body>\n"
        + "<form method='POST' name='form' action='" + URL_SECOND + "'>\n"
        + "<input type='submit' value='ok'>\n"
        + "</form>\n"
        + "<a href='#' onclick='document.form.submit()'>click me</a>\n"
        + "</body></html>";
    final String content2 = "download file contents";

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

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Content-Disposition", "attachment"));

    final MockWebConnection conn = new MockWebConnection();
    conn.setResponse(URL_FIRST, content1);
    conn.setResponse(URL_SECOND, content2, 200, "OK", MimeType.TEXT_HTML, headers);
    client.setWebConnection(conn);
    assertTrue(attachments.isEmpty());

    final HtmlPage result = client.getPage(URL_FIRST);
    final HtmlAnchor anchor = result.getAnchors().get(0);
    final Page clickResult = anchor.click();
    assertEquals(result, clickResult);
    assertEquals(1, attachments.size());
    assertTrue(HtmlPage.class.isInstance(attachments.get(0).getPage()));
    // the attachment is opened inside a new window
    assertEquals(2, client.getWebWindows().size());

    final Attachment attachment = attachments.get(0);
    final Page attachedPage = attachment.getPage();
    final WebResponse attachmentResponse = attachedPage.getWebResponse();
    final InputStream attachmentStream = attachmentResponse.getContentAsStream();
    HttpWebConnectionTest.assertEquals(new ByteArrayInputStream(content2.getBytes()), attachmentStream);
    assertEquals(MimeType.TEXT_HTML, attachmentResponse.getContentType());
    assertEquals(200, attachmentResponse.getStatusCode());
    assertEquals(URL_SECOND, attachmentResponse.getWebRequest().getUrl());
}
 
Example 20
Source File: WindowTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void openWindow_base() throws Exception {
    final WebClient webClient = getWebClient();
    final MockWebConnection webConnection = new MockWebConnection();

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

    final String firstContent
        = "<html><head><title>First</title><base target='MyNewWindow'></head><body>\n"
        + "<form name='form1'>\n"
        + "  <a id='link' href='" + URL_SECOND + "'>Click me</a>\n"
        + "</form>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>Second</title></head><body>\n"
        + "<script>alert(self.name)</script>\n"
        + "</body></html>";

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

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

    final HtmlAnchor anchor = firstPage.getHtmlElementById("link");
    final HtmlPage secondPage = anchor.click();
    assertEquals("Second", secondPage.getTitleText());
    assertNotSame(firstPage, secondPage);

    final WebWindow secondWebWindow = secondPage.getEnclosingWindow();
    assertNotSame(firstWebWindow, secondWebWindow);
    assertEquals("MyNewWindow", secondWebWindow.getName());
    assertEquals(secondWebWindow, secondWebWindow.getTopWindow());

    assertEquals(new String[] {"MyNewWindow"}, collectedAlerts);
}