Example usage for org.openqa.selenium WebDriver getPageSource

List of usage examples for org.openqa.selenium WebDriver getPageSource

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver getPageSource.

Prototype

String getPageSource();

Source Link

Document

Get the source of the last loaded page.

Usage

From source file:org.keycloak.testsuite.samlfilter.SamlAdapterTest.java

License:Apache License

@Test
public void testPostSimpleUnauthorized() {
    List<String> requiredRoles = new LinkedList<>();
    requiredRoles.add("manager");
    requiredRoles.add("employee");
    requiredRoles.add("user");
    SendUsernameServlet.checkRoles = requiredRoles;
    try {// ww  w.  j a  v a2 s .co  m
        testStrategy.testPostSimpleUnauthorized(new SamlAdapterTestStrategy.CheckAuthError() {
            @Override
            public void check(WebDriver driver) {
                Assert.assertTrue(driver.getPageSource().contains("Error Page"));
            }
        });
    } finally {
        SendUsernameServlet.checkRoles = null;
    }
}

From source file:org.keycloak.testsuite.TomcatSamlTest.java

License:Apache License

@Test
public void testPostSimpleUnauthorized() {
    testStrategy.testPostSimpleUnauthorized(new SamlAdapterTestStrategy.CheckAuthError() {
        @Override/*from  ww w .  j  av  a  2  s.  c  o m*/
        public void check(WebDriver driver) {
            Assert.assertTrue(driver.getPageSource().contains("forbidden"));
        }
    });
}

From source file:org.keycloak.testsuite.util.WaitUtils.java

License:Apache License

/**
 * Waits for page to finish any pending redirects, REST API requests etc.
 * Because Keycloak's Admin Console is a single-page application, we need to
 * take extra steps to ensure the page is fully loaded
 *//*  w  w w .  j a  va2  s .c om*/
public static void waitForPageToLoad() {
    WebDriver driver = getCurrentDriver();

    if (driver instanceof HtmlUnitDriver) {
        return; // not needed
    }

    String currentUrl = null;

    // Ensure the URL is "stable", i.e. is not changing anymore; if it'd changing, some redirects are probably still in progress
    for (int maxRedirects = 4; maxRedirects > 0; maxRedirects--) {
        currentUrl = driver.getCurrentUrl();
        FluentWait<WebDriver> wait = new FluentWait<>(driver).withTimeout(Duration.ofMillis(250));
        try {
            wait.until(not(urlToBe(currentUrl)));
        } catch (TimeoutException e) {
            break; // URL has not changed recently - ok, the URL is stable and page is current
        }
        if (maxRedirects == 1) {
            log.warn("URL seems unstable! (Some redirect are probably still in progress)");
        }
    }

    WebDriverWait wait = new WebDriverWait(getCurrentDriver(), PAGELOAD_TIMEOUT_MILLIS / 1000);
    ExpectedCondition waitCondition = null;

    // Different wait strategies for Admin and Account Consoles
    if (currentUrl.matches("^[^\\/]+:\\/\\/[^\\/]+\\/auth\\/admin\\/.*$")) { // Admin Console
        // Checks if the document is ready and asks AngularJS, if present, whether there are any REST API requests in progress
        waitCondition = javaScriptThrowsNoExceptions("if (document.readyState !== 'complete' "
                + "|| (typeof angular !== 'undefined' && angular.element(document.body).injector().get('$http').pendingRequests.length !== 0)) {"
                + "throw \"Not ready\";" + "}");
    } else if (currentUrl.matches("^[^\\/]+:\\/\\/[^\\/]+\\/auth\\/realms\\/[^\\/]+\\/account\\/.*$") // check for Account Console URL
            && driver.getPageSource().contains("patternfly-ng") // check for new Account Console (don't use this strategy with the old one)
    ) {
        waitCondition = javaScriptThrowsNoExceptions(
                "if (!window.getAngularTestability(document.querySelector('app-root')).isStable()) {"
                        + "throw 'Not ready';" + "}");
    }

    if (waitCondition != null) {
        try {
            wait.until(waitCondition);
        } catch (TimeoutException e) {
            log.warn("waitForPageToLoad time exceeded!");
        }
    }
}

From source file:org.kuali.rice.testtools.selenium.WebDriverAftBase.java

License:Educational Community License

/**
 * <p>/* w w  w . j  av  a  2s. c  o  m*/
 * Logs in using the KRAD Login Page, if the JVM arg remote.autologin is set, auto login as admin will not be done.
 * </p>
 *
 * @param driver to login with
 * @param userName to login with
 * @param failable to fail on if there is a login problem
 * @throws InterruptedException
 */
public void login(WebDriver driver, String userName, JiraAwareFailable failable) throws InterruptedException {
    if ("true".equalsIgnoreCase(System.getProperty(WebDriverUtils.REMOTE_AUTOLOGIN_PROPERTY, "true"))) {
        driver.findElement(By.name("login_user")).clear();
        driver.findElement(By.name("login_user")).sendKeys(userName);
        driver.findElement(By.id("Rice-LoginButton")).click();
        Thread.sleep(1000);
        String contents = driver.getPageSource();
        AutomatedFunctionalTestUtils.failOnInvalidUserName(userName, contents, failable);
        AutomatedFunctionalTestUtils.checkForIncidentReport(driver.getPageSource(), "Login", "Login failure",
                failable);
    }
}

From source file:org.mifos.server.wartest.MifosPackagedWARBasicTest.java

License:Open Source License

@Test
public void testPackagedWARStartup() throws Exception {
    WARServerLauncher serverLauncher = mifosLauncher(7077);
    serverLauncher.startServer();/*from  w w  w. ja v a2  s.  com*/

    WebDriver wd = new FirefoxDriver();
    wd.get("http://localhost:7077/mifos/");

    wd.findElement(By.id("login.input.username")).sendKeys("mifos");
    wd.findElement(By.id("login.input.password")).sendKeys("testmifos");
    wd.findElement(By.id("login.button.login")).click();

    Assert.assertTrue(wd.getPageSource().contains("Mifos"));
    Assert.assertTrue(wd.getPageSource().contains("Home"));
    Assert.assertTrue(wd.getPageSource().contains("Search"));

    wd.quit();

    serverLauncher.stopServer();
    serverLauncher = null;
}

From source file:org.mifos.server.workspace.WorkspaceServerLauncherTest.java

License:Open Source License

@Test
public void testLogin() throws Exception {
    WebDriver wd = new FirefoxDriver();
    wd.get(getAppURL());//from  w w w .java 2  s . c om

    wd.findElement(By.id(UID)).sendKeys("mifos");
    wd.findElement(By.id(PWD)).sendKeys("testmifos");
    wd.findElement(By.id(BTN)).click();

    Assert.assertTrue(wd.getPageSource().contains("Mifos"));
    Assert.assertTrue(wd.getPageSource().contains("Home"));
    Assert.assertTrue(wd.getPageSource().contains("Search"));

    wd.quit();
}

From source file:org.musetest.selenium.plugins.WebdriverCapturePlugin.java

License:Open Source License

private void collectScreenshotAndPageContent() {
    WebDriver driver = getDriver();
    if (driver == null)
        return;/* w  ww .j ava2  s  .c o  m*/

    // capture screenshot
    if (_collect_screenshot) {
        if (driver instanceof TakesScreenshot) {
            final byte[] screenshot_bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            if (shouldSaveScreenshot(screenshot_bytes)) {
                final TestResultData data = new ScreenshotData(screenshot_bytes);
                final String varname = _context.createVariable("_captured_screenshot", data);
                _context.raiseEvent(TestResultStoredEventType.create(varname, "screenshot"));
            }
        }
    }

    // capture HTML
    if (_collect_html) {
        final byte[] html_bytes = driver.getPageSource().getBytes();
        if (shouldSaveHtml(html_bytes)) {
            final HtmlData data = new HtmlData(html_bytes);
            final String varname = _context.createVariable("_captured_html", data);
            _context.raiseEvent(TestResultStoredEventType.create(varname, "page HTML"));
        }
    }
}

From source file:org.nuxeo.functionaltests.ScreenshotTaker.java

License:Apache License

public File dumpPageSource(WebDriver driver, String filename) {
    if (driver == null) {
        return null;
    }//from ww w.  ja  v a 2  s.  c  o m
    FileWriter writer = null;
    try {
        String location = System.getProperty("basedir") + File.separator + "target";
        File outputFolder = new File(location);
        if (!outputFolder.exists() || !outputFolder.isDirectory()) {
            outputFolder = null;
        }
        if (outputFolder != null && !StringUtils.isBlank(targetDirName)) {
            outputFolder = new File(outputFolder, targetDirName);
            outputFolder.mkdir();
        }
        File tmpFile = File.createTempFile(filename, ".html", outputFolder);
        log.trace(String.format("Created page source file named '%s'", tmpFile.getPath()));
        writer = new FileWriter(tmpFile);
        writer.write(driver.getPageSource());
        return tmpFile;
    } catch (IOException e) {
        throw new WebDriverException(e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.ocpsoft.rewrite.faces.jsession.JSessionIdTest.java

License:Apache License

@Test
public void withCookiesAndStandardOutcome() throws Exception {

    // GIVEN a browser with cookies enabled
    WebDriver driver = createBrowserAndLoadPage(true);
    assertThat(driver.getPageSource(), Matchers.not(Matchers.containsString("jsessionid")));

    // WHEN a JSF action redirects with a standard outcome
    driver.findElement(By.id("form:standardOutcome")).click();

    // THEN the browser should be redirected
    assertThat(driver.getCurrentUrl(), Matchers.containsString("redirected=true"));

    // AND there should be no jsessionid in the URL
    assertThat(driver.getCurrentUrl(), Matchers.not(Matchers.containsString("jsessionid")));

}

From source file:org.ocpsoft.rewrite.faces.jsession.JSessionIdTest.java

License:Apache License

@Test
public void withCookiesAndNavigateOutcome() throws Exception {

    // GIVEN a browser with cookies enabled
    WebDriver driver = createBrowserAndLoadPage(true);
    assertThat(driver.getPageSource(), Matchers.not(Matchers.containsString("jsessionid")));

    // WHEN a JSF action redirects with a standard outcome
    driver.findElement(By.id("form:navigateOutcome")).click();

    // THEN the browser should be redirected
    assertThat(driver.getCurrentUrl(), Matchers.containsString("redirected=true"));

    // AND there should be no jsessionid in the URL
    assertThat(driver.getCurrentUrl(), Matchers.not(Matchers.containsString("jsessionid")));

}