Java Code Examples for org.openqa.selenium.By

The following examples show how to use org.openqa.selenium.By. These examples are extracted from open source projects. 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 Project: masquerade   Source File: TableImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SelenideElement deselectRow(By rowBy) {
    this.shouldBe(VISIBLE)
            .shouldBe(ENABLED);

    SelenideElement row = getRow(rowBy)
            .shouldBe(visible)
            .shouldHave(selectedClass);

    WebDriver webDriver = WebDriverRunner.getWebDriver();
    Actions action = new Actions(webDriver);

    Keys controlKey = getControlKey();

    action.keyDown(controlKey)
            .click(row.getWrappedElement())
            .keyUp(controlKey)
            .build()
            .perform();

    return row;
}
 
Example 2
Source Project: htmlunit   Source File: HTMLTextAreaElementTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("foo")
public void onChange() throws Exception {
    final String html
        = "<html>\n"
        + "<head><title>foo</title></head>\n"
        + "<body>\n"
        + "  <p>hello world</p>\n"
        + "  <form name='form1'>\n"
        + "    <textarea name='textarea1' onchange='alert(this.value)'></textarea>\n"
        + "    <input name='myButton' type='button' onclick='document.form1.textarea1.value=\"from button\"'>\n"
        + "  </form>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final WebElement textarea = driver.findElement(By.name("textarea1"));
    textarea.sendKeys("foo");
    driver.findElement(By.name("myButton")).click();

    verifyAlerts(driver, getExpectedAlerts());
}
 
Example 3
Source Project: htmlunit   Source File: HtmlLabelTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts({"click check1Label", "click listItem1", "click list",
            "click check1", "click listItem1", "click list", "false"})
public void triggerCheckboxCheckedFor() 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\")'>Checkbox 1</label>\n"
        + "      <input id='check1' name='checks' value='1' type='checkbox' checked "
                    + "onclick='log(\"click check1\");'>\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("check1Label")).click();
    driver.findElement(By.id("check")).click();
    assertTitle(driver, String.join(";", getExpectedAlerts()) + ";");
}
 
Example 4
private void testSearchSelect() throws Exception {
    waitAndClickByValue("CAT");
    waitAndClickByXpath("//div[@data-label='Travel Account Type Code']/div/div/button[@class='btn btn-default uif-action icon-search']");
	waitSearchAndReturnFromLightbox();
    waitAndClickButtonByText(WebDriverLegacyITBase.SEARCH);

    By[] bysPresent = new By[] {By.xpath("//a[contains(text(), 'a6')]"), By.xpath("//a[contains(text(), 'a9')]"), By.xpath("//a[contains(text(), 'a14')]")};
    assertElementsPresentInResultPages(bysPresent);

    waitAndClickByName(LOOKUP_RESULTS);
    assertButtonEnabledByText(WebDriverLegacyITBase.RETURN_SELECTED_BUTTON_TEXT);
    waitAndClickByName(LOOKUP_RESULTS);
    assertButtonDisabledByText(WebDriverLegacyITBase.RETURN_SELECTED_BUTTON_TEXT);

    assertMultiValueSelectAllThisPage();
    assertMultiValueDeselectAllThisPage();

    waitAndClickByName(LOOKUP_RESULTS);
    waitAndClickButtonByText(WebDriverLegacyITBase.SEARCH);
    checkForIncidentReport();
}
 
Example 5
Source Project: demo   Source File: SeleniumTests.java    License: MIT License 6 votes vote down vote up
/**
 * In this case, we have one book and one borrower,
 * so we should get a dropdown
 *
 * more detail:
 * Under lending, books and borrowers inputs have three modes.
 * a) if no books/borrowers, lock the input
 * b) If 1 - 9, show a dropdown
 * c) If 10 and up, show an autocomplete
 */
@Test
public void test_shouldShowDropdowns() {
    // clear the database...
    driver.get("http://localhost:8080/demo/flyway");
    ApiCalls.registerBook("some book");
    ApiCalls.registerBorrowers("some borrower");

    driver.get("http://localhost:8080/demo/library.html");

    // using the arrow keys to select an element is a very "dropdown" kind of behavior.
    driver.findElement(By.id("lend_book")).sendKeys(Keys.ARROW_UP);
    driver.findElement(By.id("lend_borrower")).sendKeys(Keys.ARROW_UP);
    driver.findElement(By.id("lend_book_submit")).click();
    final String result = driver.findElement(By.id("result")).getText();
    assertEquals("SUCCESS", result);
}
 
Example 6
Source Project: htmlunit   Source File: MalformedHtmlTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts("frame loaded")
@NotYetImplemented
public void framesetInsideForm() throws Exception {
    final String html = "<html>\n"
            + "<form id='tester'>\n"
            + "  <frameset>\n"
            + "    <frame name='main' src='" + URL_SECOND + "' />\n"
            + "  </frameset>\n"
            + "</form>\n"
            + "</html>";

    final String html2 = "<html><body>\n"
            + "<script>\n"
            + "  alert('frame loaded');\n"
            + "</script>\n"
            + "</body></html>";

    getMockWebConnection().setResponse(URL_SECOND, html2);
    final WebDriver webDriver = loadPageWithAlerts2(html);
    assertEquals(1, webDriver.findElements(By.name("main")).size());
    assertEquals(0, webDriver.findElements(By.id("tester")).size());
}
 
Example 7
protected void testTravelCompanyCreateNewDocumentSequenceGeneration() throws Exception {
    waitAndClickByLinkText("Create New");

    createTravelCompanyDoc();
    int travelCompanyIdDoc1 = Integer.parseInt(findElement(By.xpath(TRAVEL_CO_ID_XPATH)).getText());

    navigate();
    waitAndClickByLinkText("Create New");

    createTravelCompanyDoc();
    int travelCompanyIdDoc2 = Integer.parseInt(findElement(By.xpath(TRAVEL_CO_ID_XPATH)).getText());

    assertTrue("The Travel Company Id on the second document should be one higher than the first document.  "
            + "travelCompanyIdDoc1: " + travelCompanyIdDoc1 + ", travelCompanyIdDoc2: " + travelCompanyIdDoc2 ,
            travelCompanyIdDoc2 == travelCompanyIdDoc1 + 1);
}
 
Example 8
Source Project: portals-pluto   Source File: SimpleTestDriver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called to login to the portal if necessary.
 */
protected static void login() {

   driver.get(loginUrl);

   List<WebElement> uels = driver.findElements(By.id(usernameId));
   List<WebElement> pwels = driver.findElements(By.id(passwordId));

   // If there is no login or password fields, don't need to login.
   if (!uels.isEmpty() && !pwels.isEmpty()) {

      System.out.println("login: found userid and password fields");
      WebElement userEl = uels.get(0);
      WebElement pwEl = pwels.get(0);

      // perform login
      userEl.clear();
      userEl.sendKeys(username);
      pwEl.clear();
      pwEl.sendKeys(password);
      pwEl.submit();

   }
}
 
Example 9
Source Project: htmlunit   Source File: HtmlBackgroundSoundTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "[object HTMLUnknownElement]",
        IE = "[object HTMLBGSoundElement]")
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"
        + "  <bgsound id='myId'/>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver && getExpectedAlerts()[0].contains("Sound")) {
        assertTrue(HtmlBackgroundSound.class.isInstance(toHtmlElement(driver.findElement(By.id("myId")))));
    }
}
 
Example 10
public HashMap<String, String> getCellValue(WebElement Element, int tr,
        int td) {
    int rowCounter = 0;
    int colCounter = 0;
    String rowKey = null;
    String colKey = null;
    HashMap<String, String> HashTable = new HashMap<>();

    String strObj = Data;
    List<WebElement> tableList = Element.findElements(By
            .cssSelector("div[class='" + strObj + "'] tr td"));
    for (WebElement listIterator : tableList) {
        String TagName = listIterator.getTagName();
        if (TagName.equals("tr")) {
            rowKey = "R" + rowCounter++;
        }
        if (TagName.equals("td")) {
            colKey = "C" + colCounter++;
        }
        HashTable.put(rowKey + colKey, listIterator.getText());
    }
    return HashTable;
}
 
Example 11
Source Project: teammates   Source File: GoogleLoginPage.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void completeFillIdentifierSteps(String identifier) {
    By switchAccountButtonBy = By.cssSelector("div[aria-label='Switch account']");
    By useAnotherAccountButtonBy = By.xpath("//div[contains(text(), 'Use another account')]");

    if (isElementPresent(switchAccountButtonBy)) {
        click(switchAccountButtonBy);
        waitForLoginPanelAnimationToComplete();
    }

    if (isElementPresent(useAnotherAccountButtonBy)) {
        click(useAnotherAccountButtonBy);
        waitForLoginPanelAnimationToComplete();
    }

    fillTextBox(identifierTextBox, identifier);
}
 
Example 12
@Parameters({"searchWord", "items"})
@Test
public void searchProduct(String searchWord, int items) {

    // find search box and enter search string
    WebElement searchBox = driver.findElement(By.name("q"));

    searchBox.sendKeys(searchWord);

    WebElement searchButton =
            driver.findElement(By.className("search-button"));

    searchButton.click();

    assertThat(driver.getTitle())
            .isEqualTo("Search results for: '" + searchWord  + "'");

    List<WebElement> searchItems = driver
            .findElements(By.xpath("//h2[@class='product-name']/a"));

    assertThat(searchItems.size())
            .isEqualTo(items);
}
 
Example 13
public InstructorStudentListPage clickShowPhoto(String courseId, String studentName) {
    String rowId = getStudentRowId(courseId, studentName);
    WebElement photoCell = browser.driver.findElement(By.id("studentphoto-c" + rowId));
    WebElement photoLink = photoCell.findElement(By.tagName("a"));
    click(photoLink);
    return this;
}
 
Example 14
Source Project: demo-java   Source File: SauceDemoTest.java    License: MIT License 5 votes vote down vote up
@Test
public void SauceDemo() {
    browser.goTo("https://www.saucedemo.com/");

    String email = "standard_user";
    String password = "secret_sauce";

    browser.element(By.id("user-name")).setText(email);
    browser.element(By.id("password")).setText(password);
    browser.element(By.className("btn_action")).click();
}
 
Example 15
@Test
public void testBattlegroundCreation1() throws Exception {
    SeleniumTestUtils.login(driver, codeDefendersHome, "codedefenders", "codedefenderspw");

    driver.findElement(By.id("createBattleground")).click();
    driver.findElement(By.id("maxAssertionsPerTest")).click();
    driver.findElement(By.id("maxAssertionsPerTest")).clear();
    driver.findElement(By.id("maxAssertionsPerTest")).sendKeys("3");
    driver.findElement(By.xpath("(//button[@type='button'])[3]")).click();
    driver.findElement(By.linkText("moderate")).click();
    driver.findElement(By.id("createButton")).click();

    checkNrOfGames();
}
 
Example 16
public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) {
    WebElement commentRow = waitForElementPresence(By.id("responseCommentRow" + commentIdSuffix));
    click(commentRow.findElements(By.tagName("a")).get(1));
    WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix));
    fillRichTextEditor("responsecommenttext" + commentIdSuffix, newCommentText);
    click(commentEditForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a")));
    ThreadHelper.waitFor(1000);
}
 
Example 17
Source Project: bromium   Source File: RecordClickCssSelectorIT.java    License: MIT License 5 votes vote down vote up
@Override
public void run(RecordingSimulatorModule recordingSimulatorModule) {
    String baseUrl = (String) opts.get(URL);
    WebDriver driver = recordingSimulatorModule.getWebDriver();
    WebDriverWait wait = new WebDriverWait(driver, 10);
    driver.get(baseUrl + Pages.DYNAMIC_DEMO_PAGE);
    driver.findElement(By.id(CREATE_DYNAMIC_ID)).click();

    wait.until(ExpectedConditions.elementToBeClickable(By.id(LATE_CREATION_ID)));
}
 
Example 18
Source Project: masquerade   Source File: LoggingInvocationHandler.java    License: Apache License 2.0 5 votes vote down vote up
private String formatBy(By by) {
    if (by instanceof Selectors.ByChain) {
        return formatBy(((Selectors.ByChain) by).getLastBy());
    }
    if (by instanceof Selectors.ByCubaId) {
        return ((Selectors.ByCubaId) by).getCubaId();
    }
    return by.toString();
}
 
Example 19
@Test
public void webrtcTest(FirefoxDriver driver) {
    driver.get(
            "https://webrtc.github.io/samples/src/content/devices/input-output/");
    assertThat(driver.findElement(By.id("video")).getTagName(),
            equalTo("video"));
}
 
Example 20
Source Project: che   Source File: FindAction.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * click on the found action
 *
 * @param action name of action
 */
public void clickOnFoundAction(String action) {
  actionsFactory
      .createAction(seleniumWebDriver)
      .doubleClick(
          waitWithRedrawTimeout.until(
              ExpectedConditions.elementToBeClickable(
                  By.xpath(String.format(FOUND_ACTION_BY_NAME, action)))))
      .perform();
}
 
Example 21
Source Project: selenium   Source File: ByChainedTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findElementsTwoByEmptyChild() {
  final AllDriver driver = mock(AllDriver.class);
  final WebElement elem1 = mock(WebElement.class, "webElement1");
  final WebElement elem2 = mock(AllElement.class, "webElement2");
  final WebElement elem3 = mock(AllElement.class, "webElement3");
  final WebElement elem4 = mock(AllElement.class, "webElement4");
  final WebElement elem5 = mock(AllElement.class, "webElement5");

  final List<WebElement> elems = new ArrayList<>();
  final List<WebElement> elems12 = new ArrayList<>();
  elems12.add(elem1);
  elems12.add(elem2);
  final List<WebElement> elems34 = new ArrayList<>();
  elems34.add(elem3);
  elems34.add(elem4);
  final List<WebElement> elems5 = new ArrayList<>();
  elems5.add(elem5);
  final List<WebElement> elems345 = new ArrayList<>();
  elems345.addAll(elems34);
  elems345.addAll(elems5);

  when(driver.findElements(By.name("cheese"))).thenReturn(elems12);
  when(elem1.findElements(By.name("photo"))).thenReturn(elems);
  when(elem2.findElements(By.name("photo"))).thenReturn(elems5);

  ByChained by = new ByChained(By.name("cheese"), By.name("photo"));
  assertThat(by.findElements(driver)).isEqualTo(elems5);
}
 
Example 22
protected void actionSendKeysArrowDown(String id) {
    Actions actions = new Actions(driver);
    actions.moveToElement(driver.findElement(By.id(id)));
    actions.click();
    actions.sendKeys(Keys.ARROW_DOWN);
    actions.build().perform();
}
 
Example 23
Source Project: development   Source File: AppConfigurationTester.java    License: Apache License 2.0 5 votes vote down vote up
private String returnInputValueForm2(int index) {

        return driver
                .findElement(By.xpath("//form[@id='"
                        + AppHtmlElements.APP_CONFIG_FORM2
                        + "']/table/tbody[1]/tr/[" + index + "]/td[2]/input"))
                .getAttribute(ATTRIUBTE_VALUE);
    }
 
Example 24
Source Project: OpenESPI-Common-java   Source File: BaseStepUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void submitLoginForm(String username, String password) {
	WebElement usernameInput = driver.findElement(By.name("j_username"));
	usernameInput.clear();
	usernameInput.sendKeys(username);
	WebElement passwordInput = driver.findElement(By.name("j_password"));
	passwordInput.clear();
	passwordInput.sendKeys(password);
	WebElement login = driver.findElement(By.name("submit"));
	login.click();
}
 
Example 25
Source Project: webtester2-core   Source File: TypeFinderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("by(By) returns found element")
void byForByReturnsElement() {

    WebElement webElement = mock(WebElement.class);
    TestFragment mockElement = mock(TestFragment.class);

    doReturn(webElement).when(searchContext).findElement(any(By.ById.class));
    doReturn(mockElement).when(factory).createInstanceOf(descriptor(TestFragment.class, webElement));

    TestFragment element = cut.by(id("someId"));
    assertThat(element).isSameAs(mockElement);

}
 
Example 26
Source Project: flow   Source File: DomListenerOnAttachIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void filtering() {
    open();

    String status = findElement(By.id("status")).getText();
    Assert.assertEquals("Event received", status);
}
 
Example 27
Source Project: teammates   Source File: AppPage.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Waits for a confirmation modal to appear and click the cancel button.
 */
public void waitForConfirmationModalAndClickCancel() {
    waitForModalShown();
    WebElement cancelButton = browser.driver.findElement(By.className("modal-btn-cancel"));
    waitForElementToBeClickable(cancelButton);
    clickDismissModalButtonAndWaitForModalHidden(cancelButton);
}
 
Example 28
Source Project: M2Doc   Source File: FrontEndTests.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void completionApply() throws InterruptedException {
    driver.navigate().to(url);

    // Start the add-in
    driver.findElement(By.id("startButton")).click();

    driver.findElement(By.id("genconfURI")).sendKeys(genconfURI);
    driver.findElement(By.id("expression")).click();
    driver.findElement(By.id("expression")).sendKeys("self.n");
    Thread.sleep(2000);
    driver.findElement(By.id("expression")).sendKeys("a");
    Thread.sleep(1000);

    assertEquals(
            "[{\"documentation\":\"EAttribute named name in ENamedElement(http://www.eclipse.org/emf/2002/Ecore)\",\"cursorOffset\":9,\"label\":\"name\",\"type\":\"EAttribute\",\"value\":\"name\"}]",
            driver.executeScript("return JSON.stringify(window.awesomplete._list)"));
    assertEquals("Feature na not found in EClass EPackage (4, 7)",
            driver.findElement(By.id("validationDiv")).getText());
    assertEquals("null", driver.findElement(By.id("resultDiv")).getText());

    driver.findElement(By.id("awesomplete_list_1_item_0")).click();
    Thread.sleep(1000);
    assertEquals("self.name", driver.findElement(By.id("expression")).getAttribute("value"));
    assertEquals("", driver.findElement(By.id("validationDiv")).getText());
    assertEquals("anydsl", driver.findElement(By.id("resultDiv")).getText());
}
 
Example 29
Source Project: keycloak   Source File: AbstractMultipleSelect2.java    License: Apache License 2.0 5 votes vote down vote up
protected BiFunction<WebElement, R, Boolean> deselect() {
    return (selected, value) -> {
        WebElement selection = selected.findElements(By.tagName("div")).get(0);
        if (identity().apply(value).equals(selection.getText())) {
            WebElement element = selected.findElement(By.xpath(".//a[contains(@class,'select2-search-choice-close')]"));
            JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("arguments[0].click();", element);
            pause(500);
            return true;
        }
        return false;
    };
}
 
Example 30
Source Project: oxTrust   Source File: TrAddPage.java    License: MIT License 5 votes vote down vote up
public void configureRp(String profile) {
	fluentWait(ONE_SEC);
	WebElement element = webDriver.findElement(By.className("checkbox1"));
	element.click();
	fluentWait(ONE_SEC);
	WebElement link = waitElementByClass("RelyingPartyConfigLink");
	link.click();

	pickprofileAndSave(profile);
}