org.openqa.selenium.WebDriver Java Examples

The following examples show how to use org.openqa.selenium.WebDriver. 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: ScreenshotListener.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
@Override
public void onTestFailure(ITestResult failingTest) {
    try {
        WebDriver driver = getDriver();
        String screenshotDirectory = System.getProperty("screenshotDirectory", "target/screenshots");
        String screenshotAbsolutePath = screenshotDirectory + File.separator + System.currentTimeMillis() + "_" + failingTest.getName() + ".png";
        File screenshot = new File(screenshotAbsolutePath);
        if (createFile(screenshot)) {
            try {
                writeScreenshotToFile(driver, screenshot);
            } catch (ClassCastException weNeedToAugmentOurDriverObject) {
                writeScreenshotToFile(new Augmenter().augment(driver), screenshot);
            }
            System.out.println("Written screenshot to " + screenshotAbsolutePath);
        } else {
            System.err.println("Unable to create " + screenshotAbsolutePath);
        }
    } catch (Exception ex) {
        System.err.println("Unable to capture screenshot: " + ex.getCause());

    }
}
 
Example #2
Source File: CustomConditions.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits until an attribute's
 * value contains the specified text.
 */
public static ExpectedCondition<Boolean> elementAttributeToContain(final WebElement element, String attribute, String text, boolean caseInsensitive) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            String value = element.getAttribute(attribute);

            if (caseInsensitive) {
                return value.toLowerCase().contains(text.toLowerCase());
            } else {
                return value.contains(text);
            }
        }

        @Override
        public String toString() {
            return "element text to contain: " + text;
        }
    };
}
 
Example #3
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * An expectation to check if js executable.
 *
 * Useful when you know that there should be a Javascript value or something at the stage.
 *
 * @param javaScript used as executable script
 * @return true once javaScript executed without errors
 */
public static ExpectedCondition<Boolean> javaScriptThrowsNoExceptions(final String javaScript) {
  return new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver driver) {
      try {
        ((JavascriptExecutor) driver).executeScript(javaScript);
        return true;
      } catch (WebDriverException e) {
        return false;
      }
    }

    @Override
    public String toString() {
      return String.format("js %s to be executable", javaScript);
    }
  };
}
 
Example #4
Source File: ULSetMethod.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean _set( WebElement webElement, WebDriver webDriver, String value, String setType, String xFID )
{
    List<WebElement> dropdownToggle = webElement.findElements( By.xpath( "./preceding-sibling::*[@uib-dropdown-toggle]" ) );
    if ( dropdownToggle.isEmpty() )
        dropdownToggle = webElement.findElements( By.xpath( "./preceding-sibling::*[@data-toggle]" ) );
    
    if ( dropdownToggle.isEmpty() )
        dropdownToggle = webElement.findElements( By.xpath( "../preceding-sibling::*[@data-toggle]" ) );
    
    if ( !dropdownToggle.isEmpty() )
        dropdownToggle.get( 0 ).click();
    
    List<WebElement> selectList = webElement.findElements( By.xpath( "./li/a[contains( text(), '" + value + "')]" ) );
    
    if ( selectList.isEmpty() )
        selectList = webElement.findElements( By.xpath( ".//a[contains( text(), '" + value + "')]" ) );
    
    if ( selectList.isEmpty() )
        return false;
    else
    {
        selectList.get( 0 ).click();
    }
    return true;
}
 
Example #5
Source File: ElementFinder.java    From selenium with Apache License 2.0 6 votes vote down vote up
private WebElement findElementDirectlyIfNecessary(WebDriver driver, String locator) {
  if (locator.startsWith("xpath=")) {
    return xpathWizardry(driver, locator.substring("xpath=".length()));
  }
  if (locator.startsWith("//")) {
    return xpathWizardry(driver, locator);
  }

  if (locator.startsWith("css=")) {
    String selector = locator.substring("css=".length());
    try {
      return driver.findElement(By.cssSelector(selector));
    } catch (WebDriverException e) {
      return fallbackToSizzle(driver, selector);
    }
  }

  return null;
}
 
Example #6
Source File: WebClient6Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Regression test for bug 3017719: a 302 redirect should change the page url.
 * @throws Exception if an error occurs
 */
@Test
public void redirect302ChangePageUrl() throws Exception {
    final String html = "<html><body><a href='redirect.html'>redirect</a></body></html>";

    final URL url = new URL(URL_FIRST, "page2.html");
    getMockWebConnection().setResponse(url, html);

    final List<NameValuePair> headers = new ArrayList<>();
    headers.add(new NameValuePair("Location", "/page2.html"));
    getMockWebConnection().setDefaultResponse("", 302, "Found", null, headers);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.tagName("a")).click();
    assertEquals(url.toString(), driver.getCurrentUrl());
}
 
Example #7
Source File: HtmlDefinitionListTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("[object HTMLDListElement]")
public void simpleScriptable() throws Exception {
    final String html = "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('myId'));\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <dl id='myId'>\n"
        + "    <dt>Some Term</dt>\n"
        + "    <dd>A description</dd>\n"
        + "  </dl>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertTrue(HtmlDefinitionList.class.isInstance(page.getHtmlElementById("myId")));
    }
}
 
Example #8
Source File: HtmlNumberInputTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"10", ""})
public void clearInput() throws Exception {
    final String html = "<html>\n"
        + "<body>\n"
        + "<form>\n"
        + "  <input type='number' id='tester' value='10'>\n"
        + "</form>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);
    final WebElement element = driver.findElement(By.id("tester"));
    assertEquals(getExpectedAlerts()[0], element.getAttribute("value"));

    element.clear();
    assertEquals(getExpectedAlerts()[1], element.getAttribute("value"));
}
 
Example #9
Source File: HtmlLabelTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"click span1", "click check1Label", "click listItem1", "click list",
            "click check1", "click check1Label",
            "click listItem1", "click list", "false"})
public void triggerCheckboxComplexCaseChecked() throws Exception {
    final String html =
          "  <ul onclick='log(\"click list\")'>\n"
        + "    <li onclick='log(\"click listItem1\")'>\n"
        + "      <label id='check1Label' for='check1' onclick='log(\"click check1Label\")'>\n"
        + "        <span>\n"
        + "          <input id='check1' name='checks' value='1' type='checkbox' checked "
                        + "onclick='log(\"click check1\");'>\n"
        + "          <span id='check1Span' onclick='log(\"click span1\")'>Checkbox 1</span>\n"
        + "        </span>\n"
        + "      </label>\n"
        + "    </li>\n"
        + "  </ul>\n"
        + "  <button id='check' onclick='log(document.getElementById(\"check1\").checked)'>Check</button>\n";
    final WebDriver driver = loadPage2(generatePage(html));
    driver.findElement(By.id("check1Span")).click();
    driver.findElement(By.id("check")).click();
    assertTitle(driver, String.join(";", getExpectedAlerts()) + ";");
}
 
Example #10
Source File: ComponentContainerTest.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Create mocked {@link WebElement} object.
 * 
 * @param type element type
 * @param value element value
 * @param isCheckbox 'true' is checkbox is desired; otherwise 'false'
 * @return mocked WebElement object
 */
private static WebElement mockElement(String type, String value, boolean isCheckbox) {
    WebElement element = mock(WebElement.class, withSettings().extraInterfaces(WrapsDriver.TYPE));
    when(element.getTagName()).thenReturn(type);
    if (isCheckbox) {
        when(element.getAttribute("type")).thenReturn("checkbox");
        when(element.getAttribute("value")).thenReturn("isSelected: " + value);
        when(element.isSelected()).thenReturn(Boolean.parseBoolean(value));
    } else {
        when(element.getAttribute("type")).thenReturn("text");
        when(element.getAttribute("value")).thenReturn(value);
        when(element.isSelected()).thenReturn(false);
    }

    WebDriver driver = mockDriver();
    when(WrapsDriver.getWrappedDriver.apply(element)).thenReturn(driver);
    return element;
}
 
Example #11
Source File: AdminRoleSystemITest.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Site admin application configuration test.
 *
 * @throws Exception
 *             the exception
 */
@Test(timeout = 60000)
public void siteAdminApplicationConfigurationTest() throws Exception {
	final WebDriver driver = getWebDriver();
	assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver);

	final UserPageVisit userPageVisit = new UserPageVisit(driver, browser);
	loginAsAdmin(userPageVisit);

	userPageVisit
			.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, ""));
	assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Configuration"));

	clickFirstRowInGrid(userPageVisit);

	userPageVisit
			.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, ""));

	userPageVisit.updateConfigurationProperty("Update Configuration.propertyValue", String.valueOf(false));

	userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, ""));

}
 
Example #12
Source File: HTMLAnchorElement2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"http://htmlunit.sourceforge.net/", "§§URL§§test", "§§URL§§#test",
    "§§URL§§#", "§§URL§§"})
public void getDefaultValue() throws Exception {
    final String html
        = "<html><head><title>AnchorTest</title>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    alert(document.getElementById('absolute'));\n"
        + "    alert(document.getElementById('relative'));\n"
        + "    alert(document.getElementById('hash'));\n"
        + "    alert(document.getElementById('hashOnly'));\n"
        + "    alert(document.getElementById('empty'));\n"
        + "  }\n</script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "  <a href='http://htmlunit.sourceforge.net/' id='absolute'>bla</a>\n"
        + "  <a href='test' id='relative'>bla</a>\n"
        + "  <a href='#test' id='hash'>bla</a>\n"
        + "  <a href='#' id='hashOnly'>bla</a>\n"
        + "  <a href='' id='empty'>bla</a>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    expandExpectedAlertsVariables(URL_FIRST);

    verifyAlerts(driver, getExpectedAlerts());
}
 
Example #13
Source File: HTMLLabelElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void clickByJSAfterHtmlForSetByJS() throws Exception {
    final String html
        = "<html>\n"
        + "  <head>\n"
        + "    <script>\n"
        + "      function doTest() {\n"
        + "        document.getElementById('label1').htmlFor = 'checkbox1';\n"
        + "      }\n"
        + "      function delegateClick() {\n"
        + "        try {\n"
        + "          document.getElementById('label1').click();\n"
        + "        } catch (e) {}\n"
        + "      }\n"
        + "    </script>\n"
        + "  </head>\n"
        + "  <body onload='doTest()'>\n"
        + "    <label id='label1'>My Label</label>\n"
        + "    <input type='checkbox' id='checkbox1'><br>\n"
        + "    <input type=button id='button1' value='Test' onclick='delegateClick()'>\n"
        + "  </body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);
    final WebElement checkbox = driver.findElement(By.id("checkbox1"));
    assertFalse(checkbox.isSelected());
    driver.findElement(By.id("button1")).click();
    assertTrue(checkbox.isSelected());
}
 
Example #14
Source File: PromiseTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = {"done", "true", "42"},
        IE = {})
public void resolvePromise() throws Exception {
    final String html =
        "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "    function test() {\n"
        + "      if (window.Promise) {\n"
        + "        var original = Promise.resolve(42);\n"
        + "        var cast = Promise.resolve(original);\n"
        + "        cast.then(function(v) {\n"
        + "          log(v);\n"
        + "        });\n"
        + "        log('done');\n"
        + "        log(original === cast);\n"
        + "      }\n"
        + "    }\n"
        + "    function log(x) {\n"
        + "      document.getElementById('log').value += x + '\\n';\n"
        + "    }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "  <textarea id='log' cols='80' rows='40'></textarea>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);

    verifyAlerts(() -> driver.findElement(By.id("log"))
            .getAttribute("value").trim().replaceAll("\r", ""), String.join("\n", getExpectedAlerts()));
}
 
Example #15
Source File: AbstractHtmlEngine.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
public AbstractHtmlEngine( UiDriver uiDriver,
                           AbstractElementsFactory elementsFactory ) {

    super(uiDriver, elementsFactory);

    AbstractHtmlDriver htmlDriver = (AbstractHtmlDriver) uiDriver;
    webDriver = (WebDriver) htmlDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
    mainWindowHandle = webDriver.getWindowHandle();
}
 
Example #16
Source File: UserRoleSystemITest.java    From cia with Apache License 2.0 5 votes vote down vote up
/**
 * Site committee document activity test.
 *
 * @throws Exception
 *             the exception
 */
@Test(timeout = 60000)
public void siteCommitteeDocumentActivityTest() throws Exception {
	final WebDriver driver = getWebDriver();
	assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver);

	final UserPageVisit userPageVisit = new UserPageVisit(driver, browser);

	userPageVisit.visitDirectPage(new PageModeMenuCommand(UserViews.COMMITTEE_VIEW_NAME,
			CommitteePageMode.DOCUMENTACTIVITY.toString(), "UU"));

}
 
Example #17
Source File: AddMember.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void waitForElementDisappearance(String xpath) {
  FluentWait<WebDriver> wait =
      new FluentWait<WebDriver>(seleniumWebDriver)
          .withTimeout(REDRAW_UI_ELEMENTS_TIMEOUT_SEC, TimeUnit.SECONDS)
          .pollingEvery(200, TimeUnit.MILLISECONDS)
          .ignoring(StaleElementReferenceException.class);

  wait.until(
      (Function<WebDriver, Boolean>)
          driver -> {
            List<WebElement> elements = seleniumWebDriver.findElements(By.xpath(xpath));
            return elements.isEmpty() || elements.get(0).isDisplayed();
          });
}
 
Example #18
Source File: Utils.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static boolean isEdgeOrSafari(WebDriver driver) {
    if (!(driver instanceof RemoteWebDriver)) {
        return false;
    }
    String browserName = ((RemoteWebDriver) driver).getCapabilities().getBrowserName();
    return BrowserType.EDGE.equals(browserName) || BrowserType.SAFARI.equals(browserName);
}
 
Example #19
Source File: KWSMouse.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
private boolean moveToElementWithJS(WebDriver driver, Element locator) {
	try {

		String mouseOverScript = getJSElement(driver, locator) + " if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false);" +
               " elem.dispatchEvent(evObj);} else if(document.createEventObject) { elem.fireEvent('onmouseover');}";
		((JavascriptExecutor) driver).executeScript(mouseOverScript);
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}
 
Example #20
Source File: HTMLElement2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test the use of innerHTML to set new HTML code.
 * @throws Exception if the test fails
 */
@Test
@Alerts({"Old = <b>Old innerHTML</b><!-- old comment -->",
            "New =  <b><i id=\"newElt\">New cell value</i></b>",
            "I"})
public void getSetInnerHTMLComplex() throws Exception {
    final String html = "<html>\n"
        + "<head>\n"
        + "  <title>test</title>\n"
        + "  <script>\n"
        + "  function log(x) {\n"
        + "    document.getElementById('log').value += x + '\\n';\n"
        + "  }\n"
        + "  function doTest() {\n"
        + "    var myNode = document.getElementById('myNode');\n"
        + "    log('Old = ' + myNode.innerHTML);\n"
        + "    myNode.innerHTML = ' <b><i id=\"newElt\">New cell value</i></b>';\n"
        + "    log('New = ' + myNode.innerHTML);\n"
        + "    log(document.getElementById('newElt').tagName);\n"
        + "  }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='doTest()'>\n"
        + "  <p id='myNode'><b>Old innerHTML</b><!-- old comment --></p>\n"
        + "  <textarea id='log'></textarea>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);
    final WebElement log = driver.findElement(By.id("log"));
    final String text = log.getAttribute("value").trim().replaceAll("\r", "");
    assertEquals(String.join("\n", getExpectedAlerts()), text);

    final WebElement pElt = driver.findElement(By.id("myNode"));
    assertEquals("p", pElt.getTagName());

    final WebElement elt = driver.findElement(By.id("newElt"));
    assertEquals("New cell value", elt.getText());
    assertEquals(1, driver.getWindowHandles().size());
}
 
Example #21
Source File: BrowserLogManager.java    From vividus with Apache License 2.0 5 votes vote down vote up
public static Set<LogEntry> getFilteredLog(WebDriver driver, Collection<BrowserLogLevel> logLevelsToInclude)
{
    LogEntries log = getLog(driver);
    return logLevelsToInclude.stream()
            .map(BrowserLogLevel::getLevel)
            .flatMap(level -> filter(log, level))
            .collect(Collectors.toCollection(LinkedHashSet::new));
}
 
Example #22
Source File: Client.java    From KITE with Apache License 2.0 5 votes vote down vote up
/**
   * Adds the webdriver to the sessionData map.
   * 
   * @param sessionData
   * @throws KiteGridException
   */
  private void addToSessionMap(Map<WebDriver, Map<String, Object>> sessionData) throws KiteGridException {
    Map<String, Object> map = new HashMap<>();
    map.put("end_point", this);
//    if (!this.isApp()) {
      String node = TestUtils.getNode(
        this.getPaas().getUrl(),
        ((RemoteWebDriver) this.getWebDriver()).getSessionId().toString());
      if (node != null) {
        map.put("node_host", node);
      }
//    }
    sessionData.put(this.getWebDriver(), map);
  }
 
Example #23
Source File: HTMLImageElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"load;", "2"})
public void emptyMimeType() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);

        final URL urlImage = new URL(URL_SECOND, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "", emptyList);
        getMockWebConnection().setDefaultResponse("Test");
    }

    final String html = "<html><head>\n"
        + "<script>\n"
        + "  function showInfo(text) {\n"
        + "    document.title += text + ';';\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body>\n"
        + "  <img id='myImage5' src='" + URL_SECOND + "img.jpg' onload='showInfo(\"load\")' "
                + "onerror='showInfo(\"error\")'>\n"
        + "</body></html>";

    final int count = getMockWebConnection().getRequestCount();
    final WebDriver driver = getWebDriver();
    if (driver instanceof HtmlUnitDriver) {
        ((HtmlUnitDriver) driver).setDownloadImages(true);
    }
    loadPage2(html);

    assertTitle(driver, getExpectedAlerts()[0]);
    assertEquals(Integer.parseInt(getExpectedAlerts()[1]), getMockWebConnection().getRequestCount() - count);
}
 
Example #24
Source File: HistoryTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests going in history {@link History#back()} with {@code POST} request.
 *
 * @throws Exception if an error occurs
 */
@Test
@Alerts("49")
// limit varies for IE
public void historyCache() throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    final int testDeep = 70;

    for (int i = 0; i < testDeep; i++) {
        servlets.put("/post" + i, Post1Servlet.class);
    }
    startWebServer("./", new String[0], servlets);

    final WebDriver driver = getWebDriver();

    int count = Post1Servlet.Count_;
    for (int i = 0; i < testDeep; i++) {
        driver.get(URL_FIRST + "post" + i);
        assertTrue(driver.getPageSource(), driver.getPageSource().contains("Call: " + (i + count)));
    }

    count = Post1Servlet.Count_;
    for (int i = 0; i < testDeep - 1; i++) {
        driver.navigate().back();
        if (!driver.getPageSource().contains("Call: " + (count - i - 2))) {
            assertEquals(Integer.parseInt(getExpectedAlerts()[0]), i);
            return;
        }

        if (count != Post1Servlet.Count_) {
            Assert.fail("Server called for " + i);
            break;
        }
    }

    assertEquals(getExpectedAlerts()[0], "done");
}
 
Example #25
Source File: HtmlMetaTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void asText() throws Exception {
    final String html = "<html><head><meta id='m' http-equiv='a' content='b'></head><body></body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    final String text = driver.findElement(By.id("m")).getText();
    assertEquals("", text);
}
 
Example #26
Source File: Window2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"number", "done", "42"})
public void setIntervalWithParams() throws Exception {
    final String html = "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "    var id;\n"
        + "    function test() {\n"
        + "      id = window.setInterval( function(p1) { log(p1); clearInterval(id); }, 20, 42);\n"
        + "      log(typeof id);\n"
        + "      log('done');\n"
        + "    }\n"
        + "\n"
        + "    function log(x) {\n"
        + "      document.getElementById('log').value += x + '\\n';\n"
        + "    }\n"
        + "</script></head>\n"
        + "<body onload='test()'>\n"
        + "  <textarea id='log' cols='80' rows='40'></textarea>\n"
        + "</body>\n"
        + "</html>\n";

    final WebDriver driver = loadPage2(html);
    Thread.sleep(200);
    final String text = driver.findElement(By.id("log")).getAttribute("value").trim().replaceAll("\r", "");
    assertEquals(String.join("\n", getExpectedAlerts()), text);
}
 
Example #27
Source File: SeleniumTestUtilities.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
public static WebDriver getFirefoxDriver(String pathToFirefoxExecutable)
{
       String path = "src/test/resources/geckodriver";
	System.setProperty("webdriver.gecko.driver", path);
	System.setProperty("webdriver.firefox.bin", pathToFirefoxExecutable);

	DesiredCapabilities capabilities =  DesiredCapabilities.firefox();
       capabilities.setCapability("marionette", true);
       capabilities.setCapability("networkConnectionEnabled", true);
       capabilities.setCapability("browserConnectionEnabled", true);

	WebDriver driver = new MarionetteDriver(capabilities);

	return driver;
}
 
Example #28
Source File: HtmlBreakTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void asText() throws Exception {
    final String html = "<html><head>\n"
        + "</head><body>\n"
        + "Hello<br/>world\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final HtmlPage page = (HtmlPage) getWebWindowOf((HtmlUnitDriver) driver).getEnclosedPage();
        assertEquals("Hello" + System.lineSeparator() + "world", page.getBody().asText());
    }
}
 
Example #29
Source File: WidgetListInterceptor.java    From java-client with Apache License 2.0 5 votes vote down vote up
WidgetListInterceptor(CacheableLocator locator, WebDriver driver,
    Map<ContentType, Constructor<? extends Widget>> instantiationMap,
    Class<? extends Widget> declaredType, Duration duration) {
    super(locator);
    this.instantiationMap = instantiationMap;
    this.declaredType = declaredType;
    this.duration = duration;
    this.driver = driver;
}
 
Example #30
Source File: TeasyDriver.java    From teasy with MIT License 5 votes vote down vote up
public WebDriver init(DesiredCapabilities extraCaps) {
    DriverFactory driverFactory;
    URL gridUrl = getGridHubUrl();
    boolean isHeadless = Configuration.headless;
    if (Configuration.runWithGrid) {
        driverFactory = new RemoteDriverFactory(Configuration.browser, Configuration.platform, extraCaps.merge(Configuration.customCaps), isHeadless, gridUrl);
    } else {
        driverFactory = new StandaloneDriverFactory(Configuration.browser, Configuration.platform, extraCaps.merge(Configuration.customCaps), isHeadless, gridUrl);
    }

    return driverFactory.get();
}