com.gargoylesoftware.htmlunit.html.HtmlPage Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.html.HtmlPage. 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: HTMLDocumentWriteTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that calling document.write() after document parsing has finished results in a whole
 * new page being loaded.
 * @throws Exception if an error occurs
 */
@Test
public void write_WhenParsingFinished() throws Exception {
    final String html =
          "<html><head><script>\n"
        + "  function test() { document.write(1); document.write(2); document.close(); }\n"
        + "</script></head>\n"
        + "<body><span id='s' onclick='test()'>click</span></body></html>";

    HtmlPage page = loadPage(html);
    assertEquals("click", page.getBody().asText());

    final HtmlSpan span = page.getHtmlElementById("s");
    page = span.click();
    assertEquals("12", page.getBody().asText());
}
 
Example #2
Source File: WebAssertTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void assertTextPresent() throws Exception {
    final String html = "<html><body><div id='a'>bar</div></body></html>";
    final HtmlPage page = loadPage(html);

    WebAssert.assertTextPresent(page, "bar");

    boolean caught = false;
    try {
        WebAssert.assertTextPresent(page, "baz");
    }
    catch (final AssertionError e) {
        caught = true;
    }
    assertTrue(caught);
}
 
Example #3
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
private List<DomNode> getItComputeElements(final HtmlPage page, final String name,
        final boolean forIDAndOrName, final boolean alsoFrames) {
    final List<DomElement> elements;
    if (forIDAndOrName) {
        elements = page.getElementsByIdAndOrName(name);
    }
    else {
        elements = page.getElementsByName(name);
    }
    final List<DomNode> matchingElements = new ArrayList<>();
    for (final DomElement elt : elements) {
        if (elt instanceof HtmlForm || elt instanceof HtmlImage
                || (alsoFrames && elt instanceof BaseFrameElement)) {
            matchingElements.add(elt);
        }
    }
    return matchingElements;
}
 
Example #4
Source File: WebClientTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test pressing an accesskey.
 * @throws Exception if something goes wrong
 */
@Test
public void accessKeys() throws Exception {
    final WebClient webClient = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage page = getPageForKeyboardTest(webClient, new String[]{"1", "2", "3"});

    assertEquals("submit0", page.pressAccessKey('a').getAttribute("name"));
    assertEquals("submit2", page.pressAccessKey('c').getAttribute("name"));
    assertEquals("submit1", page.pressAccessKey('b').getAttribute("name"));

    final String[] expectedAlerts = {"focus-0", "blur-0", "focus-2", "blur-2", "focus-1"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example #5
Source File: HttpWebConnectionTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void cookiesEnabledAfterDisable() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test1", Cookie1Servlet.class);
    servlets.put("/test2", Cookie2Servlet.class);
    startWebServer("./", null, servlets);

    final WebClient client = getWebClient();

    client.getCookieManager().setCookiesEnabled(false);
    HtmlPage page = client.getPage(URL_FIRST + "test1");
    assertTrue(page.asText().contains("No Cookies"));

    client.getCookieManager().setCookiesEnabled(true);
    page = client.getPage(URL_FIRST + "test1");
    assertTrue(page.asText().contains("key1=value1"));
}
 
Example #6
Source File: SvgFeMergeTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object SVGFEMergeElement]")
public void simpleScriptable() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
        + "    <feMerge id='myId'/>\n"
        + "  </svg>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(SvgFeMerge.class.isInstance(page.getElementById("myId")));
    }
}
 
Example #7
Source File: WebClientTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Test tabbing to the next element.
 * @throws Exception if something goes wrong
 */
@Test
public void tabNext() throws Exception {
    final WebClient webClient = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final HtmlPage page = getPageForKeyboardTest(webClient, new String[]{"1", "2", "3"});

    assertEquals("submit0", page.tabToNextElement().getAttribute("name"));
    assertEquals("submit1", page.tabToNextElement().getAttribute("name"));
    assertEquals("submit2", page.tabToNextElement().getAttribute("name"));

    final String[] expectedAlerts = {"focus-0", "blur-0", "focus-1", "blur-1", "focus-2"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example #8
Source File: JavaScriptEngine.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Handles an exception that occurred during execution of JavaScript code.
 * @param page the page in which the script causing this exception was executed
 * @param e the timeout error that was thrown from the script engine
 */
protected void handleJavaScriptTimeoutError(final HtmlPage page, final TimeoutError e) {
    final WebClient webClient = getWebClient();
    // shutdown was already called
    if (webClient == null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Caught script timeout error after the shutdown of the Javascript engine - ignored.");
        }
        return;
    }

    webClient.getJavaScriptErrorListener().timeoutError(page, e.getAllowedTime(), e.getExecutionTime());
    if (webClient.getOptions().isThrowExceptionOnScriptError()) {
        throw new RuntimeException(e);
    }
    LOG.info("Caught script timeout error", e);
}
 
Example #9
Source File: CodeFlowDevModeTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void useTenantConfigResolver() throws IOException, InterruptedException {
    try (final WebClient webClient = createWebClient()) {
        HtmlPage page = webClient.getPage("http://localhost:8080/web-app/tenant/tenant-config-resolver");

        assertEquals("Log in to devmode", page.getTitleText());

        HtmlForm loginForm = page.getForms().get(0);

        loginForm.getInputByName("username").setValueAttribute("alice-dev-mode");
        loginForm.getInputByName("password").setValueAttribute("alice-dev-mode");

        page = loginForm.getInputByName("login").click();

        assertEquals("tenant-config-resolver:alice-dev-mode", page.getBody().asText());
        webClient.getCookieManager().clearCookies();
    }
}
 
Example #10
Source File: SimpleWebTestCase.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Defines the provided HTML as the response of the MockWebConnection for {@link WebTestCase#URL_FIRST}
 * and loads the page with this URL using the current browser version; finally, asserts the alerts
 * equal the expected alerts.
 * @param html the HTML to use
 * @param url the URL from which the provided HTML code should be delivered
 * @param waitForJS the milliseconds to wait for background JS tasks to complete. Ignored if -1.
 * @return the new page
 * @throws Exception if something goes wrong
 */
protected final HtmlPage loadPageWithAlerts(final String html, final URL url, final int waitForJS)
    throws Exception {
    if (getExpectedAlerts() == null) {
        throw new IllegalStateException("You must annotate the test class with '@RunWith(BrowserRunner.class)'");
    }

    // expand variables in expected alerts
    expandExpectedAlertsVariables(url);

    createTestPageForRealBrowserIfNeeded(html, getExpectedAlerts());

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

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(url, html);

    final HtmlPage page = client.getPage(url);
    if (waitForJS > 0) {
        assertEquals(0, client.waitForBackgroundJavaScriptStartingBefore(waitForJS));
    }
    assertEquals(getExpectedAlerts(), collectedAlerts);
    return page;
}
 
Example #11
Source File: AbstractList.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void registerListener() {
    if (!listenerRegistered_) {
        final DomNode domNode = getDomNodeOrNull();
        if (domNode != null) {
            final DomHtmlAttributeChangeListenerImpl listener = new DomHtmlAttributeChangeListenerImpl(this);
            domNode.addDomChangeListener(listener);
            if (attributeChangeSensitive_) {
                if (domNode instanceof HtmlElement) {
                    ((HtmlElement) domNode).addHtmlAttributeChangeListener(listener);
                }
                else if (domNode instanceof HtmlPage) {
                    ((HtmlPage) domNode).addHtmlAttributeChangeListener(listener);
                }
            }
            listenerRegistered_ = true;
        }
    }
}
 
Example #12
Source File: WebAssertTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void assertElementNotPresent() throws Exception {
    final String html = "<html><body><div id='a'>bar</div></body></html>";
    final HtmlPage page = loadPage(html);

    WebAssert.assertElementNotPresent(page, "b");

    boolean caught = false;
    try {
        WebAssert.assertElementNotPresent(page, "a");
    }
    catch (final AssertionError e) {
        caught = true;
    }
    assertTrue(caught);
}
 
Example #13
Source File: SvgFeGaussianBlurTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object SVGFEGaussianBlurElement]")
public void simpleScriptable() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
        + "    <feGaussianBlur id='myId'/>\n"
        + "  </svg>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(SvgFeGaussianBlur.class.isInstance(page.getElementById("myId")));
    }
}
 
Example #14
Source File: HTMLScriptElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code src} property.
 * @return the {@code src} property
 */
@JsxGetter
public String getSrc() {
    final HtmlScript tmpScript = (HtmlScript) getDomNodeOrDie();
    String src = tmpScript.getSrcAttribute();
    if (ATTRIBUTE_NOT_DEFINED == src) {
        return src;
    }
    try {
        final URL expandedSrc = ((HtmlPage) tmpScript.getPage()).getFullyQualifiedUrl(src);
        src = expandedSrc.toString();
    }
    catch (final MalformedURLException e) {
        // ignore
    }
    return src;
}
 
Example #15
Source File: ConversationIT.java    From krazo with Apache License 2.0 6 votes vote down vote up
@Test
public void testConversation() throws Exception {
    HtmlPage page;
    Iterator<HtmlElement> it;

    page = webClient.getPage(webUrl + "resources/converse/start");
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    final String secret = it.next().asText();
    System.out.println(secret);

    page = webClient.getPage(webUrl + "resources/converse/" +
        page.getDocumentElement().getElementsByTagName("a")
            .iterator().next().getAttribute("href"));
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertTrue(secret.equals(it.next().asText()));

    page = webClient.getPage(webUrl + "resources/converse/stop");
    it = page.getDocumentElement().getElementsByTagName("p").iterator();
    assertFalse(secret.equals(it.next().asText()));
}
 
Example #16
Source File: HTMLScriptElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code src} property.
 * @return the {@code src} property
 */
@JsxGetter
public String getSrc() {
    final HtmlScript tmpScript = (HtmlScript) getDomNodeOrDie();
    String src = tmpScript.getSrcAttribute();
    if (ATTRIBUTE_NOT_DEFINED == src) {
        return src;
    }
    try {
        final URL expandedSrc = ((HtmlPage) tmpScript.getPage()).getFullyQualifiedUrl(src);
        src = expandedSrc.toString();
    }
    catch (final MalformedURLException e) {
        // ignore
    }
    return src;
}
 
Example #17
Source File: SgmlPageTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void getElementsByTagNameAsterisk() throws Exception {
    final String html
        = "<html><head><title>First</title></head>\n"
        + "<body>\n"
        + "<form><input type='button' name='button1' value='pushme'></form>\n"
        + "<div>a</div> <div>b</div> <div>c</div>\n"
        + "</body></html>";

    final HtmlPage page = loadPage(html);

    final DomNodeList<DomElement> elements = page.getElementsByTagName("*");

    assertEquals(9, elements.getLength());
    validateDomNodeList(elements);

    final HtmlDivision newDiv = new HtmlDivision(HtmlDivision.TAG_NAME, page, null);
    page.getBody().appendChild(newDiv);
    assertEquals(10, elements.getLength());
    validateDomNodeList(elements);
}
 
Example #18
Source File: SvgFontFaceNameTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object SVGElement]")
public void simpleScriptable() throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'>\n"
        + "    <font-face-name id='myId'/>\n"
        + "  </svg>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(SvgElement.class.isInstance(page.getElementById("myId")));
    }
}
 
Example #19
Source File: HTMLTableRowElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a new cell at the specified index in the element's cells collection. If the index
 * is -1 or there is no index specified, then the cell is appended at the end of the
 * element's cells collection.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536455.aspx">MSDN Documentation</a>
 * @param index specifies where to insert the cell in the tr.
 *        The default value is -1, which appends the new cell to the end of the cells collection
 * @return the newly-created cell
 */
@JsxFunction
public Object insertCell(final Object index) {
    int position = -1;
    if (index != Undefined.instance) {
        position = (int) Context.toNumber(index);
    }
    final HtmlTableRow htmlRow = (HtmlTableRow) getDomNodeOrDie();

    final boolean indexValid = position >= -1 && position <= htmlRow.getCells().size();
    if (indexValid) {
        final DomElement newCell = ((HtmlPage) htmlRow.getPage()).createElement("td");
        if (position == -1 || position == htmlRow.getCells().size()) {
            htmlRow.appendChild(newCell);
        }
        else {
            htmlRow.getCell(position).insertBefore(newCell);
        }
        return getScriptableFor(newCell);
    }
    throw Context.reportRuntimeError("Index or size is negative or greater than the allowed amount");
}
 
Example #20
Source File: WebClient.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
 *
 * Opens a new dialog window.
 * @param url the URL of the document to load and display
 * @param opener the web window that is opening the dialog
 * @param dialogArguments the object to make available inside the dialog via <tt>window.dialogArguments</tt>
 * @return the new dialog window
 * @throws IOException if there is an IO error
 */
public DialogWindow openDialogWindow(final URL url, final WebWindow opener, final Object dialogArguments)
    throws IOException {

    WebAssert.notNull("url", url);
    WebAssert.notNull("opener", opener);

    final DialogWindow window = new DialogWindow(this, dialogArguments);
    fireWindowOpened(new WebWindowEvent(window, WebWindowEvent.OPEN, null, null));

    final HtmlPage openerPage = (HtmlPage) opener.getEnclosedPage();
    final WebRequest request = new WebRequest(url, getBrowserVersion().getHtmlAcceptHeader(),
                                                    getBrowserVersion().getAcceptEncodingHeader());
    request.setCharset(UTF_8);

    if (getBrowserVersion().hasFeature(DIALOGWINDOW_REFERER) && openerPage != null) {
        final String referer = openerPage.getUrl().toExternalForm();
        request.setAdditionalHeader(HttpHeader.REFERER, referer);
    }

    getPage(window, request);

    return window;
}
 
Example #21
Source File: Window.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the object.
 * @param enclosedPage the page containing the JavaScript
 */
public void initialize(final Page enclosedPage) {
    if (enclosedPage != null && enclosedPage.isHtmlPage()) {
        final HtmlPage htmlPage = (HtmlPage) enclosedPage;

        // Windows don't have corresponding DomNodes so set the domNode
        // variable to be the page. If this isn't set then SimpleScriptable.get()
        // won't work properly
        setDomNode(htmlPage);
        clearEventListenersContainer();

        WebAssert.notNull("document_", document_);
        document_.setDomNode(htmlPage);
    }
}
 
Example #22
Source File: DeployInWebAppsDirectoryTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void assertMoviesPresent(HtmlPage page) {
    String pageAsText = page.asText();
    assertTrue(pageAsText.contains("Wedding Crashers"));
    assertTrue(pageAsText.contains("Starsky & Hutch"));
    assertTrue(pageAsText.contains("Shanghai Knights"));
    assertTrue(pageAsText.contains("I-Spy"));
    assertTrue(pageAsText.contains("The Royal Tenenbaums"));
}
 
Example #23
Source File: TopLevelWindowTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Regression test for bug 2808520: onbeforeunload not called when window.close() is called.
 * @throws Exception if an error occurs
 */
@Test
public void onBeforeUnloadCalledOnClose() throws Exception {
    final String html = "<html><body onbeforeunload='alert(7)'>abc</body></html>";
    final List<String> alerts = new ArrayList<>();
    final HtmlPage page = loadPage(html, alerts);
    assertTrue(alerts.isEmpty());
    final TopLevelWindow w = (TopLevelWindow) page.getEnclosingWindow();
    w.close();
    assertEquals(Arrays.asList("7"), alerts);
}
 
Example #24
Source File: WebAssert.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the input element with the specified name on the specified page contains the
 * specified value.
 *
 * @param page the page to check
 * @param name the name of the input element to check
 * @param value the value to check for
 */
public static void assertInputContainsValue(final HtmlPage page, final String name, final String value) {
    final String xpath = "//input[@name='" + name + "']";
    final List<?> list = page.getByXPath(xpath);
    if (list.isEmpty()) {
        throw new AssertionError("Unable to find an input element named '" + name + "'.");
    }
    final HtmlInput input = (HtmlInput) list.get(0);
    final String s = input.getValueAttribute();
    if (!s.equals(value)) {
        throw new AssertionError("The input element named '" + name + "' contains the value '" + s
                        + "', not the expected value '" + value + "'.");
    }
}
 
Example #25
Source File: WebClientWaitForBackgroundJobsTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@link WebClient#waitForBackgroundJavaScriptStartingBefore(long)} should have an overview of all windows.
 * @throws Exception if the test fails
 */
@Test
public void jobSchedulesJobInOtherWindow2() throws Exception {
    final String html = "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "    var counter = 0;\n"
        + "    function test() {\n"
        + "      var w = window.open('about:blank');\n"
        + "      w.setTimeout(doWork1, 200);\n"
        + "    }\n"
        + "    function doWork1() {\n"
        + "      alert('work1');\n"
        + "      setTimeout(doWork2, 400);\n"
        + "    }\n"
        + "    function doWork2() {\n"
        + "      alert('work2');\n"
        + "    }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "</body>\n"
        + "</html>";

    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    final HtmlPage page = loadPage(html, collectedAlerts);

    startTimedTest();
    assertEquals(0, page.getWebClient().waitForBackgroundJavaScriptStartingBefore(1000));
    assertMaxTestRunTime(1000);

    final String[] expectedAlerts = {"work1", "work2"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example #26
Source File: WebAssert.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the specified page contains a link with the specified text. The specified text
 * may be a substring of the entire text contained by the link.
 *
 * @param page the page to check
 * @param text the text which a link in the specified page is expected to contain
 */
public static void assertLinkPresentWithText(final HtmlPage page, final String text) {
    boolean found = false;
    for (final HtmlAnchor a : page.getAnchors()) {
        if (a.asText().contains(text)) {
            found = true;
            break;
        }
    }
    if (!found) {
        final String msg = "The page does not contain a link with text '" + text + "'.";
        throw new AssertionError(msg);
    }
}
 
Example #27
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 #28
Source File: ExternalTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that we use the latest gecko driver.
 * @throws Exception if an error occurs
 */
@Test
public void assertGeckoDriver() throws Exception {
    try (WebClient webClient = buildWebClient()) {
        try {
            final HtmlPage page = webClient.getPage("https://github.com/mozilla/geckodriver/releases/latest");
            final DomNodeList<DomNode> divs = page.querySelectorAll(".release-header div");
            assertEquals("Gecko Driver", divs.get(0).asText(), "v" + GECKO_DRIVER_);
        }
        catch (final FailingHttpStatusCodeException e) {
            // ignore
        }
    }
}
 
Example #29
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreatedClients() throws Exception {
    // Login to the client page successfully
    try (WebClient webClient = setupWebClientIDP("alice", "ecila")) {
        final HtmlPage registeredClientsPage = login(oidcEndpointBuilder("/console/clients"), webClient);
        final String bodyTextContent = registeredClientsPage.getBody().getTextContent();
        assertTrue(bodyTextContent.contains("Registered Clients"));

        // Get the new client identifier
        HtmlTable table = registeredClientsPage.getHtmlElementById("registered_clients");

        // 2 clients
        assertEquals(table.getRows().size(), 3);

        // Now check the first client
        String clientId = table.getCellAt(1, 1).asText();
        assertNotNull(clientId);

        // Check the Date
        String date = table.getCellAt(1, 2).asText();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        assertEquals(dateFormat.format(new Date()), date);

        // Check the redirect URI
        String redirectURI = table.getCellAt(1, 3).asText().trim(); // <br/>
        assertTrue(REDIRECT_URL.equals(redirectURI));
    }
}
 
Example #30
Source File: WebClient4Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void useProxy() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/test", UseProxyHeaderServlet.class);
    startWebServer("./", null, servlets);

    final WebClient client = getWebClient();
    final HtmlPage page = client.getPage(URL_FIRST + "test");
    assertEquals("Going anywhere?", page.asText());
}