com.codeborne.selenide.SelenideElement Java Examples

The following examples show how to use com.codeborne.selenide.SelenideElement. 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: TableImpl.java    From masquerade with Apache License 2.0 7 votes vote down vote up
@Override
public ElementsCollection selectRows(By rowBy) {
    this.shouldBe(VISIBLE)
            .shouldBe(LOADED)
            .shouldBe(ENABLED);

    ElementsCollection rows = getRows(rowBy);

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

    for (SelenideElement row : rows) {
        row.shouldNotHave(selectedClass);

        Keys controlKey = getControlKey();

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

    return rows;
}
 
Example #2
Source File: InputInteractionSteps.java    From akita with Apache License 2.0 6 votes vote down vote up
/**
 * Ввод в поле текущей даты в заданном формате
 * При неверном формате, используется dd.MM.yyyy
 */
@Когда("^элемент \"([^\"]*)\" заполняется текущей датой в формате \"([^\"]*)\"$")
@When("^element named \"([^\"]*)\" has been filled with current date in format \"([^\"]*)\"$")
public void currentDate(String fieldName, String dateFormat) {
    long date = System.currentTimeMillis();
    String currentStringDate;
    try {
        currentStringDate = new SimpleDateFormat(dateFormat).format(date);
    } catch (IllegalArgumentException ex) {
        currentStringDate = new SimpleDateFormat("dd.MM.yyyy").format(date);
        log.error("Неверный формат даты. Будет использоваться значание по умолчанию в формате dd.MM.yyyy");
    }
    SelenideElement valueInput = akitaScenario.getCurrentPage().getElement(fieldName);
    valueInput.setValue("");
    valueInput.setValue(currentStringDate);
    akitaScenario.write("Текущая дата " + currentStringDate);
}
 
Example #3
Source File: SelenideAddons.java    From neodymium-library with MIT License 6 votes vote down vote up
/**
 * Drag and drop an element to a given position. The position will be set by the user. It drags the element and
 * moves it to a specific position of the respective slider.
 * 
 * @param elementToMove
 *            The selector of the slider to drag and drop
 * @param elementToCheck
 *            The locator of the slider value
 * @param horizontalMovement
 *            The offset for the horizontal movement
 * @param verticalMovement
 *            The offset for the vertical movement
 * @param pauseBetweenMovements
 *            Time to pass after the slider do the next movement step
 * @param retryMovements
 *            Amount of retries the slider will be moved
 * @param condition
 *            The condition for the slider to verify the movement
 */

public static void dragAndDropUntilCondition(SelenideElement elementToMove, SelenideElement elementToCheck, int horizontalMovement, int verticalMovement,
                                             int pauseBetweenMovements, int retryMovements, Condition condition)
{
    Actions moveSlider = new Actions(Neodymium.getDriver());

    int counter = 0;
    while (!elementToCheck.has(condition))
    {
        if (counter > retryMovements)
        {
            SelenideAddons.wrapAssertionError(() -> {
                Assert.assertTrue("CircutBreaker: Was not able to move the element and to reach the condition. Tried: " + retryMovements
                                  + " times to move the element.", false);
            });
        }
        Action action = moveSlider.dragAndDropBy(elementToMove.getWrappedElement(), horizontalMovement, verticalMovement).build();
        action.perform();
        Selenide.sleep(pauseBetweenMovements);
        counter++;
    }
}
 
Example #4
Source File: OptionsGroupImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
@Override
public String getSelectedValue() {
    impl.shouldBe(visible);

    SelenideElement selectedOpt = $(byChain(by, SELECTED_OPTION));
    if (selectedOpt.is(visible)) {
        return selectedOpt.getText();
    } else {
        return null;
    }
}
 
Example #5
Source File: GroupTableImpl.java    From masquerade with Apache License 2.0 6 votes vote down vote up
@Override
public GroupTable expand(By groupRowSelector) {
    SelenideElement element = $(byChain(by, groupRowSelector))
            .shouldBe(visible)
            .shouldHave(cssClass(GROUP_ROW_CAPTION_CLASS_NAME));

    while (element != null
            && !element.has(cssClass(TABLE_CLASS_NAME))
            && !element.has(cssClass(GROUP_ROW_CLASS_NAME))) {
        element = element.parent();
    }

    if (element != null
            && element.has(cssClass(GROUP_ROW_CLASS_NAME))) {
        expandRow(element);
    }

    return this;
}
 
Example #6
Source File: DateTimeFieldImpl.java    From masquerade with Apache License 2.0 5 votes vote down vote up
@Override
public DateTimeField setTimeValue(String value) {
    SelenideElement timeFieldImpl = $(byChain(by, TIMEPART));

    timeFieldImpl
            .shouldBe(visible)
            .shouldBe(enabled)
            .shouldNotBe(readonly)
            .click();

    timeFieldImpl.sendKeys(Keys.HOME, value);
    return this;
}
 
Example #7
Source File: SelenideAddonsTest.java    From neodymium-library with MIT License 5 votes vote down vote up
@Test()
public void testDownVerticalDragAndDropUntilCondition()
{
    Selenide.open("https://demos.telerik.com/kendo-ui/slider/index");

    SelenideElement slider = $("#equalizer .k-slider-vertical:first-child a");
    SelenideAddons.dragAndDropUntilCondition(slider, slider, 0, 10, 3000, 23, Condition.attribute("aria-valuenow", "-6"));

    Assert.assertEquals($("#equalizer .k-slider-vertical:first-child a").getAttribute("aria-valuenow"), "-6");
}
 
Example #8
Source File: SelenideDockerJupiterTest.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
@Test
public void testDockerSelenideChrome(
        @DockerBrowser(type = CHROME) SelenideDriver driver) {
    driver.open("https://bonigarcia.github.io/selenium-jupiter/");
    SelenideElement about = driver.$(linkText("About"));
    about.shouldBe(visible);
    about.click();
}
 
Example #9
Source File: AkitaPage.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Приведение объекта к типу SelenideElement
 */
private static SelenideElement castToSelenideElement(Object object) {
    if (object instanceof SelenideElement) {
        return (SelenideElement) object;
    }
    return null;
}
 
Example #10
Source File: N2oOutputText.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void shouldBeEmpty() {
    element().shouldBe(Condition.exist);
    SelenideElement elm = element().$(".text");
    if (elm.exists())
        elm.shouldBe(Condition.empty);
}
 
Example #11
Source File: N2oInputText.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void shouldHavePlaceholder(String placeholder) {
    Condition condition = Condition.attribute("placeholder", placeholder);

    SelenideElement elm = inputElement();
    if (elm.exists()) elm.shouldHave(condition);
    else cellInputElement().shouldHave(condition);
}
 
Example #12
Source File: N2oStandardTableHeader.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void click() {
    SelenideElement elm = element().$(".n2o-checkbox");
    if (elm.exists())
        elm.click();
    else
        element().$("a").should(Condition.exist).click();
}
 
Example #13
Source File: GoogleTestWithDocker.java    From testcontainers with MIT License 5 votes vote down vote up
@Test
public void search() {
  open("https://google.com/ncr");
  $(By.name("q")).val("Selenide").pressEnter();
  $$("#res .g").shouldHave(sizeGreaterThan(3));

  for (int i = 0; i < 3; i++) {
    SelenideElement link = $("#res .g", i).find("a");
    System.out.println(link.attr("href"));
    link.click();
    back();
  }
  sleep(1000);
}
 
Example #14
Source File: ElementsVerificationSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Проверка, что элемент содержит указанный класс (в приоритете: из property, из переменной сценария, значение аргумента)
 * Например:
 * если нужно проверить что элемент не отображается на странице, но проверки Selenium отрабатывают неверно,
 * можно использовать данный метод и проверить, что среди его классов есть disabled
 */
@Тогда("^элемент \"([^\"]*)\" содержит класс со значением \"(.*)\"$")
@Then("^element named \"([^\"]*)\" contains class with value of \"(.*)\"$")
public void checkElemClassContainsExpectedValue(String elementName, String expectedClassValue) {
    SelenideElement currentElement = akitaScenario.getCurrentPage().getElement(elementName);
    expectedClassValue = getPropertyOrStringVariableOrValue(expectedClassValue);
    String currentClassValue = currentElement.getAttribute("class");
    assertThat(String.format("Элемент [%s] не содержит класс со значением [%s]", elementName, expectedClassValue)
            , currentClassValue.toLowerCase(), containsString(expectedClassValue.toLowerCase()));
}
 
Example #15
Source File: ElementsVerificationSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Проверка, что элемент на странице кликабелен
 */
@Тогда("^(?:поле|элемент) \"([^\"]*)\" кликабельно$")
@Then("^(?:field|element) named \"([^\"]*)\" is clickable$")
public void clickableField(String elementName) {
    SelenideElement element = akitaScenario.getCurrentPage().getElement(elementName);
    assertTrue(element.isEnabled(), String.format("Элемент [%s] не кликабелен", elementName));
}
 
Example #16
Source File: AkitaPage.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Получение текста элемента, как редактируемого поля, так и статичного элемента по значению элемента
 */
public String getAnyElementText(SelenideElement element) {
    if (element.getTagName().equals("input") || element.getTagName().equals("textarea")) {
        return element.getValue();
    } else {
        return element.getText();
    }
}
 
Example #17
Source File: N2oInputMoney.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void shouldHavePlaceholder(String value) {
    Condition condition = Condition.attribute("placeholder", value);
    SelenideElement elm = inputElement();
    if (elm.exists()) elm.shouldHave(condition);
    else element().$(".n2o-editable-cell .n2o-editable-cell-text").shouldHave(condition);
}
 
Example #18
Source File: AkitaPage.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Поиск и инициализация элементов страницы c аннотацией Hidden
 */
private List<SelenideElement> readWithHiddenElements() {
    return Arrays.stream(getClass().getDeclaredFields())
            .filter(f -> f.getDeclaredAnnotation(Hidden.class) != null)
            .map(this::extractFieldValueViaReflection)
            .flatMap(v -> v instanceof List ? ((List<?>) v).stream() : Stream.of(v))
            .map(AkitaPage::castToSelenideElement)
            .filter(Objects::nonNull)
            .collect(toList());
}
 
Example #19
Source File: ListVerificationSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Проверка, что каждый элемент списка не содержит ожидаемый текст
 */
@Тогда("^элементы списка \"([^\"]*)\" не содержат текст \"([^\"]*)\"$")
@When("^elements of the \"([^\"]*)\" list do not contain text \"([^\"]*)\"$")
public void checkListElementsNotContainsText(String listName, String expectedValue) {
    final String value = getPropertyOrValue(expectedValue);
    List<SelenideElement> listOfElementsFromPage = akitaScenario.getCurrentPage().getElementsList(listName);
    List<String> elementsListText = listOfElementsFromPage.stream()
            .map(element -> element.getText().trim().toLowerCase())
            .collect(toList());
    assertFalse(elementsListText.stream().allMatch(item -> item.contains(value.toLowerCase())),
            String.format("Элемены списка %s: [%s] содержат текст [%s] ", listName, elementsListText, value));
}
 
Example #20
Source File: SelenideAppiumFieldDecorator.java    From selenide-appium with MIT License 5 votes vote down vote up
@Override
public Object decorate(ClassLoader loader, Field field) {
  builder.setAnnotated(field);
  By selector = builder.buildBy();

  if (selector == null) {
    selector = new Annotations(field).buildBy();
  }

  if (selector instanceof ByIdOrName) {
    return decorateWithAppium(loader, field);
  }
  else if (SelenideElement.class.isAssignableFrom(field.getType())) {
    return ElementFinder.wrap(driver, driver.getWebDriver(), selector, 0);
  }
  else if (ElementsCollection.class.isAssignableFrom(field.getType())) {
    return new ElementsCollection(new BySelectorCollection(driver, selector));
  }
  else if (ElementsContainer.class.isAssignableFrom(field.getType())) {
    return createElementsContainer(selector, field);
  }
  else if (isDecoratableList(field, ElementsContainer.class)) {
    return createElementsContainerList(field);
  }
  else if (isDecoratableList(field, SelenideElement.class)) {
    return SelenideElementListProxy.wrap(driver, factory.createLocator(field));
  }

  return super.decorate(loader, field);
}
 
Example #21
Source File: DropDownListInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выбор из выпадающего списка элемента, содержащего заданный текст
 * (в приоритете: из property, из переменной сценария, значение аргумента)
 */
@Тогда("^в выпадающем списке \"([^\"]*)\" выбран элемент содержащий текст \"([^\"]*)\"$")
@Then("^in drop down list named \"([^\"]*)\" element containing text \"([^\"]*)\" had been selected$")
public void selectELementFromDropDownListContainingText (String listName, String expectedText) {
    final String text = getPropertyOrStringVariableOrValue(expectedText);
    SelenideElement list = akitaScenario.getCurrentPage().getElement(listName);
    list.selectOptionContainingText(text);
}
 
Example #22
Source File: DataGridImpl.java    From masquerade with Apache License 2.0 5 votes vote down vote up
protected DataGrid.SortDirection getSortDirection(SelenideElement columnHeaderCell) {
    if (columnHeaderCell.has(cssClass("sort-asc"))) {
        return DataGrid.SortDirection.ASCENDING;
    }
    if (columnHeaderCell.has(cssClass("sort-desc"))) {
        return DataGrid.SortDirection.DESCENDING;
    }
    return DataGrid.SortDirection.NONE;
}
 
Example #23
Source File: SelenideAddonsTest.java    From neodymium-library with MIT License 5 votes vote down vote up
private void leftHorizontalDragAndDropUntilText(SelenideElement elementToMove, SelenideElement elementToCheck, int horizontalMovement,
                                                String sliderValueAttributeName, String moveUntil)
{
    // Example: create a special method to move until a given text
    SelenideAddons.dragAndDropUntilCondition(elementToMove, elementToCheck, horizontalMovement, 0, 3000, 10,
                                             Condition.attribute(sliderValueAttributeName, moveUntil));
}
 
Example #24
Source File: SelenideAddons.java    From neodymium-library with MIT License 5 votes vote down vote up
/**
 * Returns an supplier that will return all results if any. It will return elements that are found by parentSelector
 * and have a result for subElementSelector. It does NOT return the subelements, it is meant to be a workaround for
 * poor CSS where the parent is only recognizable by looking at its children, but we don't need the children.
 * Important, this is meant to be lazy so don't call get() when you setup a field or so, only when you really need
 * the element. It reselects all the time!
 *
 * @param parentSelector
 *            The selector that is used to find subElementSelector
 * @param subElementSelector
 *            The selector that is shall have the element selected by parentSelector
 * @return an supplier that will return the result later
 */
public static Supplier<ElementsCollection> parentsBySubElement(final By parentSelector, final By subElementSelector)
{
    return new Supplier<ElementsCollection>()
    {
        @Override
        public ElementsCollection get()
        {
            List<SelenideElement> list = $$(parentSelector).stream().filter(e -> {
                return e.$(subElementSelector).exists();
            }).collect(Collectors.toList());
            return new ElementsCollection(new WebElementsCollectionWrapper(WebDriverRunner.driver(), list));
        };
    };
}
 
Example #25
Source File: N2oPasswordControl.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void shouldHaveValue(String value) {
    SelenideElement elm = inputElement();
    if (elm.exists()) elm.shouldHave(value == null || value.isEmpty() ?
            Condition.empty : Condition.value(value));
    else element().$(".n2o-editable-cell .n2o-editable-cell-text").shouldHave(value == null || value.isEmpty() ?
            Condition.empty : Condition.text(value));
}
 
Example #26
Source File: NotificationImpl.java    From masquerade with Apache License 2.0 5 votes vote down vote up
@Override
public String getCaption() {
    impl.shouldBe(visible);

    SelenideElement captionImpl = $(byChain(by, NOTIFICATION_CAPTION));
    if (captionImpl.is(visible)) {
        return captionImpl.getText();
    } else {
        return null;
    }
}
 
Example #27
Source File: SelenideAppiumFieldDecorator.java    From selenide-appium with MIT License 5 votes vote down vote up
private ElementsContainer initElementsContainer(Class<?> type, SelenideElement self) throws Exception {
  Constructor<?> constructor = type.getDeclaredConstructor();
  constructor.setAccessible(true);
  ElementsContainer result = (ElementsContainer) constructor.newInstance();
  PageFactory.initElements(new SelenideFieldDecorator(new SelenidePageFactory(), driver, self), result);
  result.setSelf(self);
  return result;
}
 
Example #28
Source File: ElementsInteractionSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Выполняется наведение курсора на элемент
 */
@Когда("^выполнен ховер на (?:поле|элемент) \"([^\"]*)\"$")
@When("^hovered (?:field|element) named \"([^\"]*)\"$")
public void elementHover(String elementName) {
    SelenideElement field = akitaScenario.getCurrentPage().getElement(elementName);
    field.hover();
}
 
Example #29
Source File: ElementsVerificationSteps.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Проверка, что у элемента есть атрибут с ожидаемым значением (в приоритете: из property, из переменной сценария, значение аргумента)
 */
@Тогда("^элемент \"([^\"]*)\" содержит атрибут \"([^\"]*)\" со значением \"(.*)\"$")
@Then("^element named \"([^\"]*)\" contains attribute named \"([^\"]*)\" with value of \"(.*)\"$")
public void checkElemContainsAtrWithValue(String elementName, String attribute, String expectedAttributeValue) {
    expectedAttributeValue = getPropertyOrStringVariableOrValue(expectedAttributeValue);
    SelenideElement currentElement = akitaScenario.getCurrentPage().getElement(elementName);
    String currentAtrValue = currentElement.attr(attribute);
    assertThat(String.format("Элемент [%s] не содержит атрибут [%s] со значением [%s]", elementName, attribute, expectedAttributeValue)
            , currentAtrValue, equalToIgnoringCase(expectedAttributeValue));
}
 
Example #30
Source File: AkitaPage.java    From akita with Apache License 2.0 5 votes vote down vote up
/**
 * Получение текстов всех элементов, содержащихся в элементе-списке,
 * состоящего как из редактируемых полей, так и статичных элементов по имени
 * Используется метод innerText(), который получает как видимый, так и скрытый текст из элемента,
 * обрезая перенос строк и пробелы в конце и начале строчки.
 */
public List<String> getAnyElementsListInnerTexts(String listName) {
    List<SelenideElement> elementsList = getElementsList(listName);
    return elementsList.stream()
            .map(element -> element.getTagName().equals("input")
                    ? element.getValue().trim()
                    : element.innerText().trim()
            )
            .collect(toList());
}