Java Code Examples for org.openqa.selenium.By

The following are top voted examples for showing how to use org.openqa.selenium.By. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Selenium-Foundation   File: WebDriverUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void testBrowserName() {
    WebDriver driver = getDriver();
    ExamplePage page = getPage();
    WebElement element = page.findElement(By.tagName("html"));
    SeleniumConfig config = SeleniumConfig.getConfig();
    String browserName = config.getBrowserCaps().getBrowserName();
    
    assertEquals(WebDriverUtils.getBrowserName((SearchContext) driver), browserName);
    assertEquals(WebDriverUtils.getBrowserName(page), browserName);
    assertEquals(WebDriverUtils.getBrowserName(element), browserName);
    
    try {
        WebDriverUtils.getBrowserName(mock(WebDriver.class));
        fail("No exception was thrown");
    } catch (UnsupportedOperationException e) {
        assertEquals(e.getMessage(), "The specified context is unable to describe its capabilities");
    }
}
 
Example 2
Project: Cognizant-Intelligent-Test-Scripter   File: AngularFindBy.java   View source code 6 votes vote down vote up
@SProperty(name = "ng-exactRepeat-row")
public By getByExactRepeaterRow(String repeaterRow) {
    String repeater = repeaterRow.split("###")[0];
    int row = Integer.valueOf(repeaterRow.split("###")[1]);
    return new ByAngularRepeaterRow(NgWebDriver.DEFAULT_ROOT_SELECTOR, repeater, true, row) {
        @Override
        public List<WebElement> findElements(SearchContext searchContext) {
            List<WebElement> elements = new ArrayList<>();
            try {
                elements.add(this.findElement(searchContext));
            } catch (Exception ex) {

            }
            return elements;
        }
    };
}
 
Example 3
Project: marathonv5   File: JavaDriverTest.java   View source code 6 votes vote down vote up
@Test(enabled = false) public void moveTo() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    WebElement element1 = driver.findElement(By.name("click-me"));
    new Actions(driver).moveToElement(element1).click().perform();
    buttonMouseActions.setLength(0);
    new Actions(driver).moveToElement(element1).perform();
    AssertJUnit.assertTrue(buttonMouseActions.length() > 0);
    AssertJUnit.assertEquals("moved-", buttonMouseActions.toString());
    new Actions(driver).moveToElement(element1, 10, 10).perform();
    AssertJUnit.assertEquals("moved-moved-", buttonMouseActions.toString());
}
 
Example 4
Project: marathonv5   File: JPasswordFieldTest.java   View source code 6 votes vote down vote up
public void login() throws Throwable {
    driver = new JavaDriver();
    WebElement passField = driver.findElement(By.cssSelector("password-field"));
    AssertJUnit.assertEquals("true", passField.getAttribute("enabled"));
    passField.clear();
    AssertJUnit.assertEquals("", passField.getText());
    passField.sendKeys("password");
    WebElement button = driver.findElement(By.cssSelector("button"));
    button.click();
    driver.switchTo().window("Error Message");
    WebElement label = driver.findElement(By.cssSelector("label[text*='Invalid']"));
    AssertJUnit.assertEquals("Invalid password. Try again.", label.getText());
    WebElement button1 = driver.findElement(By.cssSelector("button"));
    button1.click();
    driver.switchTo().window("JPasswordFieldTest");
    passField.clear();
    passField.sendKeys("bugaboo", Keys.ENTER);
    driver.switchTo().window("Message");
    WebElement label2 = driver.findElement(By.cssSelector("label[text*='Success']"));
    AssertJUnit.assertEquals("Success! You typed the right password.", label2.getText());
}
 
Example 5
Project: saladium   File: BySelec.java   View source code 6 votes vote down vote up
/**
 * Retourne un selecteur selenium à partir d'un type et d'une valeur sous forme de String. Les différents sélecteur disponible sont.
 * <ul>
 * <li>id</li>
 * <li>name</li>
 * <li>className</li>
 * <li>xpath</li>
 * <li>css</li>
 * <li>linkText</li>
 * <li>tagName</li>
 * <li>partialLinkText</li>
 * </ul>
 * Retourne null si aucun sélecteur correspondant au type passé en paramètre n'est trouvé.
 * @param type
 * @param selector
 * @return By
 */
public static By get(String type, String selector) {
    By by = null;
    if ("id".equalsIgnoreCase(type)) {
        by = By.id(selector);
    } else if ("name".equalsIgnoreCase(type)) {
        by = By.name(selector);
    } else if ("className".equalsIgnoreCase(type)) {
        by = By.className(selector);
    } else if ("xpath".equalsIgnoreCase(type)) {
        by = By.xpath(selector);
    } else if ("css".equalsIgnoreCase(type)) {
        by = By.cssSelector(selector);
    } else if ("linkText".equalsIgnoreCase(type)) {
        by = By.linkText(selector);
    } else if ("tagName".equalsIgnoreCase(type)) {
        by = By.tagName(selector);
    } else if ("partialLinkText".equalsIgnoreCase(type)) {
        by = By.partialLinkText(selector);
    }
    return by;
}
 
Example 6
Project: marathonv5   File: NativeEventsTest.java   View source code 6 votes vote down vote up
public void pressGeneratesSameEvents() throws Throwable {
    events = MouseEvent.MOUSE_PRESSED;
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            actionsArea.setText("");
        }
    });
    driver = new JavaDriver();
    WebElement b = driver.findElement(By.name("click-me"));
    WebElement t = driver.findElement(By.name("actions"));

    Point location = EventQueueWait.call_noexc(button, "getLocationOnScreen");
    Dimension size = EventQueueWait.call_noexc(button, "getSize");
    Robot r = new Robot();
    r.setAutoDelay(10);
    r.setAutoWaitForIdle(true);
    r.mouseMove(location.x + size.width / 2, location.y + size.height / 2);
    r.mousePress(InputEvent.BUTTON1_MASK);
    r.mouseRelease(InputEvent.BUTTON1_MASK);
    new EventQueueWait() {
        @Override public boolean till() {
            return actionsArea.getText().length() > 0;
        }
    }.wait("Waiting for actionsArea failed?");
    String expected = t.getText();
    tclear();
    Point location2 = EventQueueWait.call_noexc(actionsArea, "getLocationOnScreen");
    Dimension size2 = EventQueueWait.call_noexc(actionsArea, "getSize");
    r.mouseMove(location2.x + size2.width / 2, location2.y + size2.height / 2);
    r.mousePress(InputEvent.BUTTON1_MASK);
    r.mouseRelease(InputEvent.BUTTON1_MASK);

    b.click();
    AssertJUnit.assertEquals(expected, t.getText());

    tclear();
    new Actions(driver).moveToElement(b).click().perform();
    AssertJUnit.assertEquals(expected, t.getText());

}
 
Example 7
Project: Cognizant-Intelligent-Test-Scripter   File: CheckBox.java   View source code 6 votes vote down vote up
@Action(object = ObjectType.BROWSER, desc = "Check all the check boxes in the context")
public void checkAllCheckBoxes() {
    try {
        List<WebElement> checkboxes = Driver.findElements(By.cssSelector("input[type=checkbox]"));
        if (checkboxes.isEmpty()) {
            Report.updateTestLog(Action, "No Checkbox present in the page", Status.WARNING);
        } else {
            for (WebElement checkbox : checkboxes) {
                if (checkbox.isDisplayed() && !checkbox.isSelected()) {
                    checkbox.click();
                }
            }
            Report.updateTestLog(Action, "All checkboxes are checked", Status.PASS);
        }
    } catch (Exception ex) {
        Report.updateTestLog(Action, "Error while checking checkboxes - " + ex, Status.FAIL);
        Logger.getLogger(CheckBox.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 8
Project: syndesis-qe   File: TechnicalExtensionSteps.java   View source code 5 votes vote down vote up
@Then("^she can see notification about integrations \"([^\"]*)\" in which is tech extension used$")
public void usedInIntegrations(String integrations) throws Throwable {
	String[] integrationsNames = integrations.split(", ");
	
	for (String integrationName : integrationsNames) {
		modalDialogPage.getElementContainingText(By.cssSelector("strong"), integrationName).shouldBe(visible);
	}
}
 
Example 9
Project: WebAndAppUITesting   File: MainFramePage.java   View source code 5 votes vote down vote up
/**
 * 点击 顶部TAB
 * 
 * @param barname
 */
public static void clickTopTab(String barname) {
	LogUtil.info("点击 顶部TAB:" + barname);
	By parentBy = By.xpath("//android.widget.HorizontalScrollView");
	By findBy = By.name(barname);
	MobileElement element = baseOpt.scrollToView(parentBy, findBy, 2, 5);
	element.click();
}
 
Example 10
Project: NoraUi   File: Utilities.java   View source code 5 votes vote down vote up
/**
 * An expectation for checking that there is at least one element present on a web page.
 *
 * @param locator
 *            used to find the element
 * @param nb
 *            is exactly number of responses
 * @return the list of WebElements once they are located
 */
public static ExpectedCondition<List<WebElement>> presenceOfNbElementsLocatedBy(final By locator, final int nb) {
    return new ExpectedCondition<List<WebElement>>() {
        @Override
        public List<WebElement> apply(WebDriver driver) {
            final List<WebElement> elements = driver.findElements(locator);
            return elements.size() == nb ? elements : null;
        }
    };
}
 
Example 11
Project: zucchini   File: ClickStep.java   View source code 5 votes vote down vote up
private WebElement findTextAtRow(String text, List<WebElement> rows) {
    for (WebElement r : rows) {
        List<WebElement> cells = r.findElements(By.tagName("td"));
        for (WebElement cell : cells) {
            if(text.trim().equals(cell.getText().trim())){
                return r;
            }
        }
    }
    return null;
}
 
Example 12
Project: ServiceNow_Selenium   File: ServiceNow.java   View source code 5 votes vote down vote up
/**
 * @category Set Element
 */
private void typeInElement(WebElement element, String content) {
	_action.moveToElement(element);
	switch (this.getFieldType(element)) {
	case "choice":
		List<WebElement> options = element.findElements(By.tagName("option"));
		for (int i = 0; i < options.size(); i++) {
			if (options.get(i).getText().trim().equalsIgnoreCase(content)) {
				element.click();
				options.get(i).click();
				break;
			}
		}
		break;
	default:
		_action.click();
		if(!this.getFieldValueByID(element.getAttribute("id")).equalsIgnoreCase("")) {
			//TODO - Find a faster way to do this.
			_action.sendKeys(Keys.END);
			for (int i = 0; i <this.getFieldValueByID(element.getAttribute("id")).length(); i ++) {
				_action.sendKeys(Keys.BACK_SPACE);
			}

		}
		_action.sendKeys(content);
		_action.sendKeys(Keys.TAB);
	_action.perform();
	}

}
 
Example 13
Project: marathonv5   File: JavaDriverTest.java   View source code 5 votes vote down vote up
public void getEnabled() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    WebElement button = driver.findElement(By.cssSelector("button"));
    AssertJUnit.assertEquals("Click Me!!", button.getText());
    AssertJUnit.assertEquals("true", button.getAttribute("enabled"));
    button.click();
}
 
Example 14
Project: colibri-ui   File: TestIOSByFactory.java   View source code 5 votes vote down vote up
@Test
public void testByID() {
    IElement element = ElementBuilders.element()
            .withName("elementByID")
            .withId("textFieldID")
            .please();
    By expected = By.id("textFieldID");

    By byElementFromFactory = byFactory.byElement(element);
    Assert.assertEquals("Результат работы IOSFactory по id некорректен", expected, byElementFromFactory);
}
 
Example 15
Project: WebAndAppUITesting   File: BaseOpt.java   View source code 5 votes vote down vote up
/**
 * 查找元素集合
 * 
 * @param by
 * @return
 */
public List<WebElement> findElements(By by) {
	List<WebElement> elementList = null;
	try {
		elementList = getDriver().findElements(by);
	} catch (Exception e) {
		LogUtil.error(getDriver().manage().logs() + "==>" + by.toString() + " 未找到!" + e);
		screenShot();
		AssertUtil.fail(by.toString() + " 未找到!");
	}

	return elementList;
}
 
Example 16
Project: hippo   File: PublicationsOverviewPage.java   View source code 5 votes vote down vote up
public List<UpcomingPublicationOverivewWidget> getUpcomingPublicationsWidgets() {
    return getWebDriver()
        .findElements(By.xpath("//*[@data-uipath='ps.overview.upcoming-publications.publication']"))
        .stream()
        .map(UpcomingPublicationOverivewWidget::new)
        .collect(toList());
}
 
Example 17
Project: satisfy   File: TableBddSteps.java   View source code 5 votes vote down vote up
@When("in '$identity' table click on '$element' for row with parameters: $params")
public void whenInTableClickElementForRowWithParameters(By identity,
                                                        By element,
                                                        ExamplesTable
                                                                params) {
    WebStepsFactory.getTableSteps(identity)
            .inTableClickOnIdentityInRowsWithParameters(element, params);
}
 
Example 18
Project: phoenix.webui.framework   File: AbstractSeleniumAttrLocator.java   View source code 5 votes vote down vote up
@Override
public WebElement findElement(SearchContext driver)
{
	String attrName = getAttrName();
	String attrVal = getValue();
	By by = getBy();

	List<WebElement> elementList = driver.findElements(by);
	for(WebElement ele : elementList)
	{
		if(driver instanceof WebDriver)
		{
			new Actions((WebDriver) driver).moveToElement(ele);
		}
		
		if(attrVal.equals(ele.getAttribute(attrName)))
		{
			return ele;
		}
	}
	
	return null;
}
 
Example 19
Project: ServiceNow_Selenium   File: ServiceNow.java   View source code 5 votes vote down vote up
private String getFieldType(WebElement element) {
	this.focusForm(true);
	String type = element.findElement(By.id(element.getAttribute("id").replaceFirst("element", "label"))).getAttribute("type");
	try {
		if(type.equalsIgnoreCase("Choice") && element.findElement(By.tagName("select")).getAttribute("disabled").equalsIgnoreCase("true")) {
			type = "String";
		}
	}catch (Exception ex) {
		//TODO - find a way to check if the field is readonly.
	}
	return type;
}
 
Example 20
Project: Appium-Sample   File: Helpers.java   View source code 5 votes vote down vote up
/**
 * Return a static text locator that contains text *
 */
public static By for_text(String text) {
    String up = text.toUpperCase();
    String down = text.toLowerCase();
    return By.xpath("//UIAStaticText[@visible=\"true\" and (contains(translate(@name,\"" + up
            + "\",\"" + down + "\"), \"" + down + "\") or contains(translate(@hint,\"" + up
            + "\",\"" + down + "\"), \"" + down + "\") or contains(translate(@label,\"" + up
            + "\",\"" + down + "\"), \"" + down + "\") or contains(translate(@value,\"" + up
            + "\",\"" + down + "\"), \"" + down + "\"))]");
}
 
Example 21
Project: marathonv5   File: JTextFieldTest.java   View source code 5 votes vote down vote up
public void getText() throws Throwable {
    driver = new JavaDriver();
    WebElement textField = driver.findElement(By.cssSelector("text-field"));
    textField.clear();
    AssertJUnit.assertEquals("", textField.getText());
    textField.sendKeys("Lewis Carroll");
    AssertJUnit.assertEquals("Lewis Carroll", textField.getText());
    textField.clear();
    AssertJUnit.assertEquals("", textField.getText());
    textField.sendKeys("htt://www.google.com ");
    AssertJUnit.assertEquals("htt://www.google.com", textField.getText().trim());

}
 
Example 22
Project: marathonv5   File: LaunchCommandLineTest.java   View source code 5 votes vote down vote up
public void checkBasicRecording() throws Throwable {
    List<WebElement> buttons = driver.findElements(By.cssSelector("toggle-button"));
    AssertJUnit.assertTrue(buttons.size() > 0);
    buttons.get(3).click();
    buttons.get(0).click();
    System.out.println(scriptElements);
    AssertJUnit.assertTrue(scriptElements.size() > 0);
}
 
Example 23
Project: marathonv5   File: JTextFieldTest.java   View source code 5 votes vote down vote up
public void sendKeys() throws Throwable {
    driver = new JavaDriver();
    WebElement textField = driver.findElement(By.cssSelector("text-field"));
    AssertJUnit.assertEquals("true", textField.getAttribute("editable"));
    textField.clear();
    AssertJUnit.assertEquals("", textField.getText());
    textField.sendKeys("Lewis CarrollR");
    textField.sendKeys(Keys.BACK_SPACE);
    AssertJUnit.assertEquals("Lewis Carroll", textField.getText());
    textField.sendKeys(Keys.HOME + "Jhon ");
    AssertJUnit.assertEquals("Jhon Lewis Carroll", textField.getText());
    textField.sendKeys(OSUtils.getKeysFor(textField, "select-all"));
    textField.sendKeys(Keys.DELETE);
    AssertJUnit.assertEquals("", textField.getText());
}
 
Example 24
Project: testcontainers   File: GoogleTestWithDockerNoVideo.java   View source code 5 votes vote down vote up
@Test
public void search() {
  open("https://google.com/");
  $(By.name("q")).val("Selenide").pressEnter();
  $$("#ires .g").shouldHave(CollectionCondition.sizeGreaterThan(5));

  for (int i = 0; i < 5; i++) {
    SelenideElement link = $("#ires .g", i).find("a");
    System.out.println(link.attr("href"));
    link.click();
    back();
  }
  sleep(1000);
}
 
Example 25
Project: marathonv5   File: JavaDriverTest.java   View source code 5 votes vote down vote up
public void getLabelText() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    WebElement element1 = driver.findElement(By.cssSelector("label"));
    AssertJUnit.assertEquals("lbl:Enter The Text", element1.getAttribute("labelText"));
}
 
Example 26
Project: mot-automated-testsuite   File: WebDriverWrapper.java   View source code 5 votes vote down vote up
/**
 * Check if an element is visible.
 *
 * @param selector Selector to find the element.
 * @return Return whether the element is visible or not.
 */
public boolean isVisible(By selector) {
    WebElement element = webDriver.findElement(selector);

    if (element == null) {
        return false;
    }

    return element.isDisplayed();
}
 
Example 27
Project: marathonv5   File: JMenuHorizontalTest.java   View source code 5 votes vote down vote up
private void performClickOnMenuItemInMenu(WebElement menu, WebElement menuItem, int itemsB4Click, int itemsAfterClick)
        throws InterruptedException {
    menu.click();
    List<WebElement> menuItemsBeforeClick = driver.findElements(By.cssSelector("menu-item"));
    AssertJUnit.assertEquals(itemsB4Click, menuItemsBeforeClick.size());
    menuItem.click();
    List<WebElement> menuItemsAfterClick = driver.findElements(By.cssSelector("menu-item"));
    AssertJUnit.assertEquals(itemsAfterClick, menuItemsAfterClick.size());
}
 
Example 28
Project: SeWebDriver_Homework   File: ShoppingCartPage.java   View source code 5 votes vote down vote up
public void deleteLastProduct() {
    //delete the last position
     try {
         driver.findElement(By.xpath("//*[contains(@name, 'remove_cart_item')]")).click();
         driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
     } catch (NoSuchElementException ex3) {
         wait.until(elementToBeClickable(By.xpath("//*[contains(@name, 'remove_cart_item')]"))).click();
         driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
     }
    wait.until(invisibilityOfAllElements(driver.findElements(By.xpath("//td[@class='item']"))));
    System.out.println("Position " + n + " deleted.");
}
 
Example 29
Project: twitter-stuff   File: StatusUtils.java   View source code 5 votes vote down vote up
public static void takeStatusScreenshot(Status status, MongoDatabase mongoDatabase, WebDriver driver) {
    long id = status.getId();
    User user = status.getUser();
    try {
        // visit the twitter url
        driver.get(TWITTER_BASE_URL + user.getScreenName() + "/status/" + id);

        WebDriverWait webDriverWait = new WebDriverWait(driver, 4);
        webDriverWait.until(
                ExpectedConditions.visibilityOfElementLocated(
                        By.cssSelector(PERMALINK_TWEET_CONTAINER)));

        // Find the tweet container
        WebElement element = driver.findElement(By.cssSelector(PERMALINK_TWEET_CONTAINER));

        // take a full screenshot
        File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // create in memory image data
        BufferedImage screenshotImage = ImageIO.read(screenshotFile);

        // calculate the position of the tweet element
        Point point = element.getLocation();
        int elementWidth = element.getSize().getWidth();
        int elementHeight = element.getSize().getHeight();

        // crop to get only the container of the tweet itself (sometimes this doesn't work on mac)
        BufferedImage elementScreenshotImage =
                screenshotImage.getSubimage(
                        point.getX() + 4,
                        point.getY() + 4,
                        elementWidth - 4,
                        screenshotImage.getHeight() < point.getY() + elementHeight
                                ? screenshotImage.getHeight() - 4
                                : elementHeight - 4);
        ImageIO.write(elementScreenshotImage, "png", screenshotFile);
        FileUtils.copyFile(screenshotFile, new File("screenshot/" + id + ".png"));
    } catch (Exception e) {
        saveFailureStatusProcesssed(mongoDatabase, id, false);
        System.out.println(
                String.format(
                        "Unable to create screenshot for %s with id: %d",
                        user.getScreenName(),
                        id));
        e.printStackTrace();
    }
}
 
Example 30
Project: ToDoMVCEmberJS   File: BasicTodoMvcPage.java   View source code 5 votes vote down vote up
@Step("delete todo item")
public boolean deleteTodoItem(String itemName){
    Assert.assertTrue(driver.findElement(By.xpath("//label[.='" + itemName + "']")).isDisplayed());
    WebElement divElt = driver.findElement(By.xpath("//label[.='" + itemName + "']")).findElement(By.xpath(".."));
    driver.findElement(By.xpath("//label[.='" + itemName + "']")).click();
    divElt.findElement(By.tagName("button")).click();
    try{
        driver.findElement(By.xpath("//label[.='" + itemName + "']")).isDisplayed();
    }catch(Exception e){
        return true;
    }
    return false;
}
 
Example 31
Project: hippo   File: DashboardPage.java   View source code 5 votes vote down vote up
public void changePasswordTo(String password) {
    helper.findElement(By.partialLinkText("Change password")).click();

    helper.findElement(By.name("current-password:widget")).sendKeys("admin");
    helper.findElement(By.name("new-password:widget")).sendKeys(password);
    helper.findElement(By.name("check-password:widget")).sendKeys(password);

    helper.findElement(By.xpath("//input[@type='submit' and @value='Change']")).click();
}
 
Example 32
Project: testing_security_development_enterprise_systems   File: HomePageObject.java   View source code 5 votes vote down vote up
public void changeData(String value){

        WebElement text = getDriver().findElement(By.id("form:text"));
        WebElement button = getDriver().findElement(By.id("form:modify"));

        text.clear();
        text.sendKeys(value);
        button.click();
        waitForPageToLoad();
    }
 
Example 33
Project: ats-framework   File: HiddenHtmlTable.java   View source code 5 votes vote down vote up
/**
 * @return how many columns this table has
 */
@PublicAtsApi
public int getColumnCount() {

    new HiddenHtmlElementState(this).waitToBecomeExisting();

    String css = this.getElementProperty("_css");

    try {
        if (!StringUtils.isNullOrEmpty(css)) {
            StringBuilder sb = new StringBuilder(css);
            sb.append(" tr:nth-child(1) td");
            int count = webDriver.findElements(By.cssSelector(sb.toString())).size();
            sb = new StringBuilder(css);
            sb.append(" tr:nth-child(1) th");
            count += webDriver.findElements(By.cssSelector(sb.toString())).size();
            return count;
        } else {
            // get elements matching the following xpath
            return this.webDriver.findElements(By.xpath("("
                                                        + properties.getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR)
                                                        + "//tr[th or td])[1]/*"))
                                 .size();
        }
    } catch (Exception e) {
        throw new SeleniumOperationException(this, "getColumnsCount", e);
    }
}
 
Example 34
Project: dashboard1b   File: Selenium.java   View source code 5 votes vote down vote up
/**
 * Editar sugerencia
 *
 * @throws Exception
 */
@Test
public void prueba14() throws Exception {
	driver.get(baseUrl + "/");
	SeleniumUtils.EsperaCargaPagina(driver, "id", "login", 25);
	driver.findElement(By.id("email")).clear();
	driver.findElement(By.id("email")).sendKeys("[email protected]");
	driver.findElement(By.id("password")).clear();
	driver.findElement(By.id("password")).sendKeys("password");
	driver.findElement(By.id("login")).click();
	driver.findElement(By.id("botonEditar")).click();
	driver.findElement(By.id("titulo")).clear();
	driver.findElement(By.id("titulo")).sendKeys("Sugerencia 4");

}
 
Example 35
Project: marathonv5   File: JavaDriverTest.java   View source code 5 votes vote down vote up
public void findElementOfElement() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
    WebElement element = driver.findElement(By.name("box-panel"));
    AssertJUnit.assertNotNull(element);
    WebElement clickMe = element.findElement(By.name("click-me"));
    AssertJUnit.assertNotNull(clickMe);
}
 
Example 36
Project: oscm   File: WebTester.java   View source code 5 votes vote down vote up
/**
 * Attempts a login to the OSCM marketplace with the given credentials. Note
 * that this method assumes the webdriver to be at the login page.
 * 
 * @param user
 *            the user name
 * @param password
 *            the password
 */
public void loginMarketplace(String user, String password) {
    WebElement userInput = driver
            .findElement(By.id(ELEMENT_MARKETPLACE_USERID));
    userInput.sendKeys(user);

    WebElement pwdInput = driver
            .findElement(By.id(ELEMENT_MARKETPLACE_PASSWORD));
    pwdInput.sendKeys(password);

    driver.findElement(By.id(ELEMENT_MARKETPLACE_LOGIN)).click();

    System.out.println("Login OSCM Marketplace");
}
 
Example 37
Project: marathonv5   File: NativeEventsTest.java   View source code 5 votes vote down vote up
public void rightClickGeneratesSameEvents() throws Throwable {
    events = MouseEvent.MOUSE_CLICKED;
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            actionsArea.setText("");
        }
    });
    driver = new JavaDriver();
    WebElement b = driver.findElement(By.name("click-me"));
    WebElement t = driver.findElement(By.name("actions"));

    Point location = EventQueueWait.call_noexc(button, "getLocationOnScreen");
    Dimension size = EventQueueWait.call_noexc(button, "getSize");
    Robot r = new Robot();
    r.setAutoDelay(10);
    r.setAutoWaitForIdle(true);
    r.mouseMove(location.x + size.width / 2, location.y + size.height / 2);
    r.mousePress(InputEvent.BUTTON3_MASK);
    r.mouseRelease(InputEvent.BUTTON3_MASK);
    new EventQueueWait() {
        @Override public boolean till() {
            return actionsArea.getText().length() > 0;
        }
    }.wait("Waiting for actionsArea failed?");
    String expected = t.getText();
    tclear();
    Point location2 = EventQueueWait.call_noexc(actionsArea, "getLocationOnScreen");
    Dimension size2 = EventQueueWait.call_noexc(actionsArea, "getSize");
    r.mouseMove(location2.x + size2.width / 2, location2.y + size2.height / 2);
    r.mousePress(InputEvent.BUTTON1_MASK);
    r.mouseRelease(InputEvent.BUTTON1_MASK);

    new Actions(driver).moveToElement(b).contextClick().perform();
    AssertJUnit.assertEquals(expected, t.getText());

}
 
Example 38
Project: yadaframework   File: YadaSeleniumUtil.java   View source code 5 votes vote down vote up
/**
 * Search for text
 * @param from a WebElement to start the search from, or the WebDriver to search in all the page
 * @param by
 * @return the text found, or ""
 */
public String getTextIfExists(SearchContext from, By by) {
	try {
		WebElement webElement = from.findElement(by);
		return webElement.getText();
	} catch (Exception e) {
		return "";
	}
}
 
Example 39
Project: satisfy   File: BaseTableSteps.java   View source code 5 votes vote down vote up
private WebElement getTableElement() {
    WebElement rootElement = webPage.element(tableIdentity);
    tableElement = rootElement;
    if (!rootElement.getTagName().contentEquals(TABLE_TAG))
        tableElement = rootElement.findElement(By.tagName(TABLE_TAG));
    return tableElement;
}
 
Example 40
Project: yadaframework   File: YadaSeleniumUtil.java   View source code 5 votes vote down vote up
/**
 * Return the first element matched by the selector, or null if not found
 * @param from a WebElement to start the search from, or the WebDriver to search in all the page
 * @param by
 * @return
 */
public WebElement findOrNull(SearchContext from, By by) {
	List<WebElement> webElements = from.findElements(by);
	if (webElements.isEmpty()) {
		return null;
	}
	return webElements.get(0);
}