org.openqa.selenium.By Java Examples

The following examples show how to use org.openqa.selenium.By. 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: SearchTest.java    From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License 6 votes vote down vote up
@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 #2
Source File: MalformedHtmlTest.java    From htmlunit with 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 #3
Source File: DemoTravelCompanySequenceGenerationAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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 #4
Source File: SeleniumTests.java    From demo with 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 #5
Source File: HTMLTextAreaElementTest.java    From htmlunit with 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 #6
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 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 #7
Source File: SimpleTestDriver.java    From portals-pluto with 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 #8
Source File: TableImpl.java    From masquerade with 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 #9
Source File: DemoTravelAccountMultivalueLookUpAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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 #10
Source File: CommonMethods.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
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 File: GoogleLoginPage.java    From teammates with 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
Source File: HtmlBackgroundSoundTest.java    From htmlunit with 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 #13
Source File: NodeTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = {"1", "2", "§§URL§§second"},
        CHROME = {"1", "2", "§§URL§§"},
        FF = {"1", "2", "§§URL§§"},
        FF68 = {"1", "2", "§§URL§§"})
public void eventListener_returnValue_false() throws Exception {
    final String html
        = "<html><head>\n"
        + "<script>\n"
        + "  function clicking1() {\n"
        + "    alert(1);\n"
        + "  }\n"
        + "  function clicking2() {\n"
        + "    alert(2);\n"
        + "    if (window.event)\n"
        + "      window.event.returnValue = false;\n"
        + "  }\n"
        + "  function test() {\n"
        + "    var e = document.getElementById('myAnchor');\n"
        + "    e.addEventListener('click', clicking1, false);\n"
        + "    e.addEventListener('click', clicking2, false);\n"
        + "  }\n"
        + "</script></head><body onload='test()'>\n"
        + "  <a href='second' id='myAnchor'>Click me</a>\n"
        + "</body></html>";

    getMockWebConnection().setDefaultResponse("<html><body>Test</body></html>");
    expandExpectedAlertsVariables(URL_FIRST);

    final WebDriver driver = loadPage2(html);
    driver.findElement(By.id("myAnchor")).click();
    verifyAlerts(driver, ArrayUtils.subarray(getExpectedAlerts(), 0, 2));
    Thread.sleep(200); // FF60 WebDriver
    assertEquals(getExpectedAlerts()[2], driver.getCurrentUrl());
}
 
Example #14
Source File: HtmlMapTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
public void isDisplayedMissingImage() throws Exception {
    final String html = "<html><head><title>Page A</title></head>\n"
            + "<body>\n"
            + "  <map id='myMap' name='imgmap' style='display: none'>\n"
            + "    <area id='myArea' shape='rect' coords='0,0,1,1'>\n"
            + "  </map>\n"
            + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);

    final boolean displayed = driver.findElement(By.id("myMap")).isDisplayed();
    assertFalse(displayed);
}
 
Example #15
Source File: AbstractMultipleSelect2.java    From keycloak with 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 #16
Source File: CrossDomainTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void canNavigateBetweenDomains() {
  driver.get(pages.iframePage);
  assertThat(driver.getCurrentUrl()).isEqualTo(pages.iframePage);
  WebElement body1 = driver.findElement(By.tagName("body"));

  driver.get(otherPages.iframePage);
  assertThat(driver.getCurrentUrl()).isEqualTo(otherPages.iframePage);
  driver.findElement(By.tagName("body"));

  assertThatExceptionOfType(StaleElementReferenceException.class)
      .isThrownBy(body1::getTagName);
}
 
Example #17
Source File: TrAddPage.java    From oxTrust with 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);
}
 
Example #18
Source File: AndroidTest.java    From appium-stf-example with Apache License 2.0 5 votes vote down vote up
@Test(dependsOnMethods = {"currentActivityTest"})
public void scrollingToSubElement() {
    androidDriver.findElementByAccessibilityId("Views").click();
    AndroidElement list = (AndroidElement) androidDriver.findElement(By.id("android:id/list"));
    MobileElement radioGroup = list
            .findElement(MobileBy
                    .AndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView("
                            + "new UiSelector().text(\"Radio Group\"));"));
    Assert.assertNotNull(radioGroup.getLocation());
}
 
Example #19
Source File: LabsUifTooltipAft.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected void testUifTooltipByName(String nameField1, String nameField2) throws Exception {
    findElement(By.name(nameField2)); // fields must be in view for tooltips to be displayed

    // check if tooltip opens on focus
    fireEvent(nameField1, "focus");
    fireMouseOverEventByName(nameField1);

    String tooltipContents = getText(By.cssSelector("[data-for='ucbjiy8_control']"));
    assertEquals("This tooltip is triggered by focus or and mouse over.", tooltipContents);
    fireEvent(nameField1, "blur");

    fireEvent(nameField2, "focus");
    Thread.sleep(5000);

    // check if tooltip opens on mouse over
    fireMouseOverEventByName(nameField2);
    assertFalse("unable to detect tooltip", isVisibleByXpath("//td[contains(.,\"This is a tool-tip with different position and tail options\")]"));

    // check if tooltip closed on mouse out of nameField2
    fireEvent(nameField2, "blur");
    fireMouseOverEventByName(nameField1);
    waitAndTypeByName(nameField1, "");
    Thread.sleep(5000);
    assertFalse("able to detect tooltip", isVisibleByXpath(
            "//td[contains(.,\"This is a tool-tip with different position and tail options\")]"));

    // check that default tooltip does not display when there are an error message on the field
    waitAndTypeByName(nameField1, "1");
    fireEvent(nameField1, "blur");
    fireMouseOverEventByName(nameField1);
    Thread.sleep(10000);
}
 
Example #20
Source File: OteSetupConsoleScreenshotTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void get_admin_fails_badEmail() throws Throwable {
  server.setIsAdmin(true);
  driver.get(server.getUrl("/registrar-ote-setup"));
  driver.waitForElement(By.tagName("h1"));
  driver.findElement(By.id("clientId")).sendKeys("acmereg");
  driver.findElement(By.id("email")).sendKeys("bad email");
  driver.findElement(By.id("submit-button")).click();
  driver.waitForElement(By.tagName("h1"));
  driver.diffPage("oteResultFailed");
}
 
Example #21
Source File: JiraAwareAftBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected void jiraAwareWaitFor(By by, int waitSeconds, String message, JiraAwareFailable failable) throws InterruptedException {
    try {
        WebDriverUtils.waitFor(getDriver(), waitSeconds, by, message);
    } catch (Throwable t) {
        jiraAwareFail(by.toString(), message, t, failable);
    }
}
 
Example #22
Source File: ActivityPage.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public PullRequestsPage clickPullRequestsTab() {
    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.pr"))).click();
    logger.info("Clicked on PR tab");
    PullRequestsPage page = pullRequestsPageFactory.withPipeline(pipeline);
    Assert.assertNotNull("AbstractPipeline object is null", page);
    return page.checkUrl();
}
 
Example #23
Source File: CargoDetailsPage.java    From dddsample-core with MIT License 5 votes vote down vote up
public CargoDetailsPage(WebDriver driver) {
    this.driver = driver;

    WebElement newCargoTableCaption = driver.findElement(By.cssSelector("table caption"));

    assertTrue(newCargoTableCaption.getText().startsWith(TRACKING_ID_HEADER));
    trackingId = newCargoTableCaption.getText().replaceFirst(TRACKING_ID_HEADER, "");
}
 
Example #24
Source File: AppConfigurationTester.java    From development with 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 #25
Source File: InstructorStudentListPage.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
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 #26
Source File: BaseStepUtils.java    From OpenESPI-Common-java with 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 #27
Source File: FrontEndTests.java    From M2Doc with 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 #28
Source File: TypeFinderTest.java    From webtester2-core with 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 #29
Source File: AppPage.java    From teammates with 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 #30
Source File: DomListenerOnAttachIT.java    From flow with 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);
}