Example usage for org.openqa.selenium By partialLinkText

List of usage examples for org.openqa.selenium By partialLinkText

Introduction

In this page you can find the example usage for org.openqa.selenium By partialLinkText.

Prototype

public static By partialLinkText(String partialLinkText) 

Source Link

Usage

From source file:org.sugarcrm.voodoodriver.EventLoop.java

License:Apache License

private WebElement findElement(VDDHash event, WebElement parent, boolean required) {
    WebElement element = null;//from  w w  w.  ja va  2s.  c  o  m
    By by = null;
    boolean href = false;
    boolean alt = false;
    boolean text = false;
    boolean value = false;
    boolean exists = true;
    String how = "";
    String what = "";
    int index = -1;
    int timeout = this.eventTimeout;
    String msg = "";

    if (event.containsKey("exists")) {
        exists = this.clickToBool(replaceString((String) event.get("exists")));
    }

    if (event.containsKey("timeout")) {
        timeout = Integer.valueOf(event.get("timeout").toString());
        msg = String.format("Resetting default element finding timeout to: '%d' seconds.", timeout);
        this.report.Log(msg);
    }

    this.hackTimeout = timeout; // Hackily plumb the timeout attribute

    if (event.containsKey("index")) {
        String inx = event.get("index").toString();
        inx = this.replaceString(inx);

        if (!Utils.isInt(inx)) {
            msg = String.format("Error: index value: '%s' is not an integer!", inx);
            this.report.ReportError(msg);
            return null;
        }

        index = Integer.valueOf(inx).intValue();
    }

    this.resetThreadTime();

    try {
        msg = "";
        how = event.get("how").toString();
        what = event.get(how).toString();
        what = this.replaceString(what);
        String dowhat = event.get("do").toString();

        this.report.Log("Trying to find page element '" + dowhat + "' by: " + "'" + how + "' => '" + what + "'"
                + ((index > -1 && !how.equals("index")) ? " index => '" + index + "'" : "") + ".");

        if (how.matches("class") && what.matches(".*\\s+.*")) {
            String elem_type = event.get("do").toString();
            String old_how = how;
            how = "css";
            String css_sel = String.format("%s[%s=\"%s\"]", elem_type, old_how, what);
            what = css_sel;
        }

        if (how.contains("index")) {
            how = "tagname";
            what = event.get("do").toString();

            if (what.contains("link")) {
                what = "a";
            }

            if (what.contains("image")) {
                what = "img";
            }
        }

        switch (ElementHow.valueOf(how.toUpperCase())) {
        case ID:
            by = By.id(what);
            break;
        case CLASS:
            by = By.className(what);
            break;
        case CSS:
            by = By.cssSelector(what);
            break;
        case LINK:
            by = By.linkText(what);
            break;
        case HREF:
            by = By.tagName("a");
            href = true;
            break;
        case TEXT:
            text = true;
            break;
        case NAME:
            by = By.name(what);
            break;
        case PARLINK:
            by = By.partialLinkText(what);
            break;
        case TAGNAME:
            by = By.tagName(what);
            break;
        case XPATH:
            by = By.xpath(what);
            break;
        case VALUE:
            value = true;
            break;
        case ALT:
            alt = true;
            break;
        default:
            /* not reached */
            this.report.ReportError(String.format("Error: findElement, unknown how: '%s'!\n", how));
            System.exit(4);
            break;
        }

        if (href) {
            element = this.findElementByHref(event.get("href").toString(), parent);
        } else if (alt) {
            element = this.findElementByAlt(event.get("alt").toString(), parent);
        } else if (value) {
            element = this.slowFindElement((String) event.get("html_tag"), (String) event.get("html_type"),
                    what, parent, index);
        } else if (text) {
            element = this.findElementByText((String) event.get("html_tag"), (String) event.get("text"), parent,
                    index);
        } else {
            List<WebElement> elements;

            elements = findElementsInternal(by, parent);
            elements = filterElements(elements, event);
            index = (index < 0) ? 0 : index;
            if (index >= elements.size()) {
                String m = ((index > 0) ? "No elements found."
                        : String.format("Index (%d) out of bounds.", index));
                throw new NoSuchElementException(m);
            }
            element = elements.get(index);
        }
    } catch (NoSuchElementException exp) {
        element = null;
    } catch (Exception exp) {
        this.report.ReportException(exp);
        element = null;
    }

    this.resetThreadTime();

    if (element == null && exists == true) {
        if (required) {
            msg = String.format("Failed to find element: '%s' => '%s'", how, what);
            this.report.ReportError(msg);
        } else {
            msg = String.format("Failed to find element, but required => 'false' : '%s' => '%s'", how, what);
            this.report.Log(msg);
        }
    } else if (element != null && exists != true) {
        this.report.ReportError("Found element with exist => 'false'!");
    } else if (element == null && exists != true) {
        this.report.Log("Did not find element as exist => 'false'.");
    } else {
        this.report.Log("Found element.");
    }

    return element;
}

From source file:org.tdar.web.functional.resource.CompleteDocumentSeleniumWebITCase.java

@Test
public void testCreateDocumentEditSavehasResource() {
    gotoPage("/document/add");
    WebElement form = find("#metadataForm").first();

    HashMap<String, String> docValMap2 = new HashMap<String, String>();
    docValMap2.put("document.title", "My Sample Document");
    docValMap2.put("document.documentType", "OTHER");
    docValMap2.put("document.description", "A resource description");
    docValMap2.put("document.date", "1923");
    docValMap2.put("projectId", "-1");
    String ORIGINAL_START_DATE = "1200";
    String COVERAGE_START = "coverageDates[0].startDate";
    docValMap2.put(COVERAGE_START, ORIGINAL_START_DATE);
    String ORIGINAL_END_DATE = "1500";
    docValMap2.put("coverageDates[0].endDate", ORIGINAL_END_DATE);
    docValMap2.put("coverageDates[0].dateType", CoverageType.CALENDAR_DATE.name());

    for (String key : docValMap2.keySet()) {
        find(By.name(key)).val(docValMap2.get(key));
    }/*from w w w  . j a  va2 s  .  c om*/

    submitForm();

    String path = getDriver().getCurrentUrl();
    logger.trace(find("body").getText());
    assertTrue("expecting to be on view page. Actual path:" + path + "\n" + find("body").getText(),
            path.matches(REGEX_DOCUMENT_VIEW));
    assertTrue("expected value on view page", sourceContains(ORIGINAL_START_DATE));
    assertTrue("expected value on view page", sourceContains(ORIGINAL_END_DATE));

    assertEquals("count of edit buttons", 1, find(By.partialLinkText("EDIT")).size());
    find(By.partialLinkText("EDIT")).click();
    expandAllTreeviews();

    String NEW_START_DATE = "100";
    find(By.name(COVERAGE_START)).val(NEW_START_DATE);
    submitForm();

    path = getDriver().getCurrentUrl();
    logger.trace(find("body").getText());
    assertTrue("expecting to be on view page. Actual path:" + path + "\n" + find("body").getText(),
            path.matches(REGEX_DOCUMENT_VIEW));
    assertTrue(sourceContains(NEW_START_DATE));
    assertFalse(sourceContains(ORIGINAL_START_DATE));
    assertTrue(sourceContains(ORIGINAL_END_DATE));
    logger.trace(find("body").getText());
}

From source file:org.tdar.web.functional.resource.CompleteDocumentSeleniumWebITCase.java

@Test
public void testCreateDocument() {
    gotoPage("/document/add");
    expandAllTreeviews();// w w w . j a  va2s  .co m
    prepIndexedFields();
    uploadFileAsync(FileAccessRestriction.CONFIDENTIAL, new File(TEST_DOCUMENT));

    docValMap.putAll(docUnorderdValMap);

    // fill in various text fields
    for (Map.Entry<String, String> entry : docValMap.entrySet()) {
        find(By.name(entry.getKey())).val(entry.getValue());
    }

    // check various keyword checkboxes
    for (String key : docMultiValMap.keySet()) {
        for (String val : docMultiValMap.get(key)) {
            try {
                logger.trace("setting value for field: {} - start", key);
                find(By.name(key)).val(val);
                logger.trace("setting value for field: {} - end", key);
            } catch (ElementNotVisibleException en) {
                logger.error("element not visible: {} {}", key, val);
                fail("could not find " + key + " because it was not visible");
            }
        }
    }

    // add some authusers
    find("#accessRightsRecordsAddAnotherButton").click();
    find("#accessRightsRecordsAddAnotherButton").click();

    addAuthuser("authorizedUsersFullNames[0]", "authorizedUsers[0].generalPermission", "Michelle Elliott",
            "michelle.elliott@dsu.edu", "person-121", MODIFY_RECORD);
    addAuthuser("authorizedUsersFullNames[1]", "authorizedUsers[1].generalPermission", "Joshua Watts",
            "joshua.watts@dsu.edu", "person-5349", VIEW_ALL);

    docUnorderdValMap.put("authorizedUsers[0].user.id", "121");
    docUnorderdValMap.put("authorizedUsers[1].user.id", "5349");
    docUnorderdValMap.put("authorizedUsers[0].generalPermission", MODIFY_RECORD.name());
    docUnorderdValMap.put("authorizedUsers[1].generalPermission", VIEW_ALL.name());
    docUnorderdValMap.put("authorizedUsersFullNames[0]", "Michelle Elliott");
    docUnorderdValMap.put("authorizedUsersFullNames[1]", "Joshua Watts");

    // add a person to satisfy the confidential file requirement
    addPersonWithRole(new Person(LOBLAW, ROBERT, "bobloblaw@netflix.com"), "creditProxies[0]",
            ResourceCreatorRole.CONTACT);

    logger.trace(getDriver().getPageSource());
    submitForm();

    String path = getDriver().getCurrentUrl();
    assertTrue("expecting to be on view page. Actual path:" + path + "\n" + find("body").getText(),
            path.matches(REGEX_DOCUMENT_VIEW));

    logger.trace(find("body").getText());
    for (String key : docValMap.keySet()) {
        // avoid the issue of the fuzzy distances or truncation... use just
        // the top of the lat/long
        if (key.startsWith("latitudeLongitudeBox")) {
            assertTrue(textContains(docValMap.get(key).substring(0, docValMap.get(key).indexOf("."))));
            // these are displayed by "type" or not "displayed"
        } else if (key.equals("document.documentType") || key.equals("resourceLanguage")) {
            assertTrue(textContains(docValMap.get(key)));
        } else if (!key.equals("document.journalName") && !key.equals("document.bookTitle")
                && !key.startsWith("authorInstitutions")
                && !key.equals(AbstractWebTestCase.PROJECT_ID_FIELDNAME) && !key.contains("Ids")
                && !key.contains("Email") && !key.equals("ticketId") && !key.contains("generalPermission")
                && !key.contains(".id") && !key.contains(".email") && !key.contains(".type")
                && !key.contains(".dateType") && !key.contains(".licenseType") && !key.contains("role")
                && !key.contains("person.institution.name")) {
            assertTrue("looking for:" + docValMap.get(key), textContains(docValMap.get(key)));
        }
    }
    for (String alt : alternateTextLookup) {
        assertTrue("looking for '" + alt + "' in source", textContains(alt));
    }
    for (String alt : alternateCodeLookup) {
        assertTrue("looking for '" + alt + "' in source", sourceContains(alt));
    }

    assertFalse(sourceContains("embargo"));
    for (String key : docMultiValMapLab.keySet()) {
        for (String val : docMultiValMapLab.get(key)) {
            assertTrue("looking for '" + val + "' in source", sourceContains(val));
        }
    }

    // go to the edit page and ensure (some) of the form fields and values that we originally created are still present
    find(By.partialLinkText("EDIT")).click();
    expandAllTreeviews();
    logger.debug("----now on edit page----");
    logger.trace(find("body").getText());

    for (String key : docValMap.keySet()) {
        String val = docValMap.get(key);

        // ignore id fields, file uploads, and fields with UPPER CASE VALUES (huh?)
        if (key.contains("Ids") || key.contains("upload") || val.toUpperCase().equals(val)
                || key.contains("email")) {
            continue;
        }

        if (docUnorderdValMap.containsKey(key)) {
            assertTrue("looking for '" + val + "' in text", textContains(val));
        } else {
            assertEquals(val, find(By.name(key)).val());
        }
    }

    for (String key : docMultiValMap.keySet()) {
        for (String val : docMultiValMap.get(key)) {
            assertTrue(String.format("key:%s  expected val:%s", key, val),
                    find(By.name(key)).vals().contains(val));
        }
    }

    // specific checks for auth users we added earlier
    String sectionText = find("#divAccessRights").getText().toLowerCase();
    logger.debug("\n\n------ access rights text ---- \n" + sectionText);

    assertThat(sectionText, containsString("joshua watts"));
    assertThat(sectionText, containsString("michelle elliott"));
    assertThat(sectionText, containsString(VIEW_ALL.getLabel().toLowerCase()));
    assertThat(sectionText, containsString(MODIFY_RECORD.getLabel().toLowerCase()));

    // make sure our 'async' file was added to the resource
    assertThat(getSource(), containsString(TEST_DOCUMENT_NAME));
}

From source file:org.testeditor.fixture.web.AbstractWebFixture.java

License:Open Source License

/**
 * Creates a Selenium identifier for a GUI-element by the given element list
 * key and optional values for the element list entry place holders.
 * /* ww  w  . j  a  va2 s.  com*/
 * @param elementListKey
 *            key in the element list to find the technical locator
 * @param replaceArgs
 *            values to replace the place holders in the element list entry
 * @return a Selenium identifier for a GUI-element
 */
// CHECKSTYLE:OFF
protected By createBy(String elementListKey, String... replaceArgs) {
    // CHECKSTYLE:ON
    String locator = retrieveLocater(elementListKey);

    // replace arguments (e.g. {0}) in locater
    if (replaceArgs.length > 0) {
        Object[] args = Arrays.copyOf(replaceArgs, replaceArgs.length, Object[].class);
        locator = MessageFormat.format(locator, args);
    }

    // Apostrophes in X-Paths must escaped
    // locator = locator.replace("'", "''");

    if (locator.startsWith(ElementPrefix.ID.getName())) {
        locator = locator.substring(ElementPrefix.ID.getName().length());
        return By.id(locator);
    } else if (locator.startsWith(ElementPrefix.XPATH.getName())) {
        locator = locator.substring(ElementPrefix.XPATH.getName().length());
        return By.xpath(locator);
    } else if (locator.startsWith(ElementPrefix.CLASSNAME.getName())) {
        locator = locator.substring(ElementPrefix.CLASSNAME.getName().length());
        return By.className(locator);
    } else if (locator.startsWith(ElementPrefix.CSSSELECTOR.getName())) {
        locator = locator.substring(ElementPrefix.CSSSELECTOR.getName().length());
        return By.cssSelector(locator);
    } else if (locator.startsWith(ElementPrefix.LINKTEXT.getName())) {
        locator = locator.substring(ElementPrefix.LINKTEXT.getName().length());
        return By.linkText(locator);
    } else if (locator.startsWith(ElementPrefix.NAME.getName())) {
        locator = locator.substring(ElementPrefix.NAME.getName().length());
        return By.name(locator);
    } else if (locator.startsWith(ElementPrefix.PARTIAL.getName())) {
        locator = locator.substring(ElementPrefix.PARTIAL.getName().length());
        return By.partialLinkText(locator);
    } else if (locator.startsWith(ElementPrefix.TAGNAME.getName())) {
        locator = locator.substring(ElementPrefix.TAGNAME.getName().length());
        return By.tagName(locator);
    } else if (locator.startsWith("//")) {
        return By.xpath(locator);
    } else {
        return By.id(locator);
    }
}

From source file:org.testeditor.fixture.web.WebFixture.java

License:Open Source License

/**
 * //from   w  w w .  ja va  2  s  . com
 * @param locator
 *            identified by an element of the {@link ElementPrefix}
 * @return By
 */
private By getByFromLacatorWithPraefix(String locator) {
    if (locator.startsWith(ElementPrefix.CLASSNAME.getName())) {
        locator = locator.substring(ElementPrefix.CLASSNAME.getName().length());
        return By.className(locator);
    } else if (locator.startsWith(ElementPrefix.CSSSELECTOR.getName())) {
        locator = locator.substring(ElementPrefix.CSSSELECTOR.getName().length());
        return By.cssSelector(locator);
    } else if (locator.startsWith(ElementPrefix.ID.getName())) {
        locator = locator.substring(ElementPrefix.ID.getName().length());
        return By.id(locator);
    } else if (locator.startsWith(ElementPrefix.LINKTEXT.getName())) {
        locator = locator.substring(ElementPrefix.LINKTEXT.getName().length());
        return By.linkText(locator);
    } else if (locator.startsWith(ElementPrefix.NAME.getName())) {
        locator = locator.substring(ElementPrefix.NAME.getName().length());
        return By.name(locator);
    } else if (locator.startsWith(ElementPrefix.PARTIAL.getName())) {
        locator = locator.substring(ElementPrefix.PARTIAL.getName().length());
        return By.partialLinkText(locator);
    } else if (locator.startsWith(ElementPrefix.TAGNAME.getName())) {
        locator = locator.substring(ElementPrefix.TAGNAME.getName().length());
        return By.tagName(locator);
    } else if (locator.startsWith(ElementPrefix.XPATH.getName())) {
        locator = locator.substring(ElementPrefix.XPATH.getName().length());
        return By.xpath(locator);
    }
    return By.id(locator);
}

From source file:org.testeditor.fixture.web.WebFixtureTest.java

License:Open Source License

/**
 * Test for createBy./* www .  ja v a2 s . c  om*/
 */
@Test
public void createByProvidesCorrectObject() {
    fixture.setElementlist(ELEMENT_LIST);

    assertTrue(fixture.createBy("common.file").toString().startsWith("By.id:"));
    assertTrue(fixture.createBy("view.rename").toString().startsWith("By.xpath:"));
    assertTrue(fixture.createBy("view.run").toString().startsWith("By.xpath:"));

    // test all prefixes
    assertEquals(By.id("myId"), fixture.createBy("prefix_id"));
    assertEquals(By.className("myClass"), fixture.createBy("prefix_classname"));
    assertEquals(By.cssSelector("myCss"), fixture.createBy("prefix_cssselector"));
    assertEquals(By.linkText("myLinkText"), fixture.createBy("prefix_linktext"));
    assertEquals(By.name("myName"), fixture.createBy("prefix_name"));
    assertEquals(By.partialLinkText("myPartial"), fixture.createBy("prefix_partial"));
    assertEquals(By.tagName("myTagName"), fixture.createBy("prefix_tagname"));
    assertEquals(By.xpath("myXPath"), fixture.createBy("prefix_xpath"));

    // value with argument
    assertEquals(By.id("Button 1 id"), fixture.createBy("common.args", "1"));
    assertEquals(By.id("Button new id"), fixture.createBy("common.args", "new"));
    assertEquals(By.id("Button {0} id"), fixture.createBy("common.args", new String[] {}));
    String nullArgument = null;
    assertEquals(By.id("Button null id"), fixture.createBy("common.args", nullArgument));

    // locater without value
    assertEquals(By.id(""), fixture.createBy("empty"));

    try {
        fixture.createBy(null);
        Assert.fail();
    } catch (StopTestException e) {
        // expected, that null is not a valid key
        assertTrue(true);
    }

    // ::Text is not a valid prefix, use id as fallback
    assertTrue(fixture.createBy("wizard.cancelButton").toString().startsWith("By.id:"));

}

From source file:org.usapi.nodetypes.AbstractNode.java

License:Apache License

protected List<WebElement> findElements(String selector) {
    AjaxMonitor.waitForAjax(getWebDriver());

    List<WebElement> webElements = getWebDriver().findElements(getByForLocator(locator));
    // if no element found there is a chance that the locator is a partial text of a link,
    // so check that explicitly
    if (webElements == null && locator.toLowerCase().startsWith("link"))
        webElements = getWebDriver().findElements(By.partialLinkText(locator.split("=")[1]));
    return webElements;
}

From source file:org.usapi.nodetypes.AbstractNode.java

License:Apache License

protected WebElement findElement(String selector) throws NoSuchElementException {
    AjaxMonitor.waitForAjax(getWebDriver());
    WebElement webElement = getWebDriver().findElement(getByForLocator(locator));
    // if no element found there is a chance that the locator is a partial text of a link,
    // so check that explicitly
    if (webElement == null && locator.toLowerCase().startsWith("link"))
        webElement = getWebDriver().findElement(By.partialLinkText(locator.split("=")[1]));
    return webElement;
}

From source file:org.wso2.am.integration.ui.tests.APIWsdlDownloadTestCase.java

License:Open Source License

/**
 * Logout from the store//from  w  ww. j  a v a2 s. c om
 */
private void storeLogout(String username) throws InterruptedException {
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText(username)));
    driver.findElement(By.partialLinkText(username)).click();
    driver.findElement(By.id("logout-link")).click();
    log.info("After store logout");
}

From source file:org.wso2.es.ui.integration.extension.util.ESUtil.java

License:Open Source License

public static void login(WebDriver driver, String url, String webApp, String userName, String password)
        throws XPathExpressionException {

    if (webApp.equalsIgnoreCase("store")) {
        url = url + storeSuffix;//from www .  j a  v  a 2s  . c o  m
        driver.get(url);
        driver.findElement(By.partialLinkText("Sign in")).click();

    } else if (webApp.equalsIgnoreCase("publisher")) {
        url = url + publisherSuffix;
        driver.get(url);
    }

    driver.findElement(By.id("username")).clear();
    driver.findElement(By.id("username")).sendKeys(userName);
    driver.findElement(By.id("password")).clear();
    driver.findElement(By.id("password")).sendKeys(password);
    driver.findElement(By.xpath("//button[@type='submit']")).click();
    driver.get(url);
}