org.openqa.selenium.support.ui.ExpectedCondition Java Examples

The following examples show how to use org.openqa.selenium.support.ui.ExpectedCondition. 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: SeleniumWrapper.java    From SeleniumBestPracticesBook with Apache License 2.0 6 votes vote down vote up
public void waitForAnimation() {

    new WebDriverWait(selenium, 60000) {
    }.until(new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driverObject) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        Long
            returnedValue =
            (Long) ((JavascriptExecutor) driverObject)
                .executeScript("return jQuery(':animated').length");

        return returnedValue == 0;
      }

    });
  }
 
Example #2
Source File: CustomConditions.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits until an element is not
 * active (in focus).
 */
public static ExpectedCondition<Boolean> elementToNotBeActive(final WebElement element) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            try {
                if (!element.equals((driver.switchTo().activeElement()))) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception ex) {
                return false;
            }
        }

        @Override
        public String toString() {
            return "element to not be active (in focus): " + element.toString();
        }
    };
}
 
Example #3
Source File: TeasyExpectedConditions.java    From teasy with MIT License 6 votes vote down vote up
/**
 * We don't know the actual window title without switching to one.
 * This method was always used to make sure that the window appeared. After it we switched to appeared window.
 * Switching between windows is rather time consuming operation
 * <p>
 * To avoid the double switching to the window we are switching to window in this method
 * <p>
 * The same approach is applies to all ExpectedConditions for windows
 *
 * @param title - title of window
 * @return - handle of expected window
 */
public static ExpectedCondition<String> appearingOfWindowAndSwitchToIt(final String title) {
    return new ExpectedCondition<String>() {
        @Override
        public String apply(final WebDriver driver) {
            final String initialHandle = driver.getWindowHandle();
            for (final String handle : driver.getWindowHandles()) {
                if (needToSwitch(initialHandle, handle)) {
                    driver.switchTo().window(handle);
                    if (driver.getTitle().equals(title)) {
                        return handle;
                    }
                }
            }
            driver.switchTo().window(initialHandle);
            return null;
        }

        @Override
        public String toString() {
            return String.format("appearing of window by title %s and switch to it", title);
        }
    };
}
 
Example #4
Source File: TeasyExpectedConditions.java    From teasy with MIT License 6 votes vote down vote up
public static ExpectedCondition<String> appearingOfWindowByPartialUrl(final String url) {
    return new ExpectedCondition<String>() {
        @Override
        public String apply(final WebDriver driver) {
            final String initialHandle = driver.getWindowHandle();
            for (final String handle : driver.getWindowHandles()) {
                if (needToSwitch(initialHandle, handle)) {
                    driver.switchTo().window(handle);
                    if (driver.getCurrentUrl().contains(url)) {
                        return handle;
                    }
                }
            }
            driver.switchTo().window(initialHandle);
            return null;
        }

        @Override
        public String toString() {
            return String.format("appearing of window by partial url %s and switch to it", url);
        }
    };
}
 
Example #5
Source File: CodenvyEditor.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Waits until editor's tab with specified {@code fileName} is in default color.
 *
 * <p>Note! Default color depends on tab's focus.
 *
 * @param fileName title of editor's tab which should be checked
 */
public void waitDefaultColorTab(final String fileName) {
  waitActive();

  final String expectedColor =
      waitTabVisibilityAndCheckFocus(fileName) ? FOCUSED_DEFAULT.get() : UNFOCUSED_DEFAULT.get();

  webDriverWaitFactory
      .get()
      .until(
          (ExpectedCondition<Boolean>)
              webDriver ->
                  seleniumWebDriverHelper
                      .waitVisibility(By.xpath(format(TAB_FILE_NAME_XPATH, fileName)))
                      .getCssValue("color")
                      .equals(expectedColor));
}
 
Example #6
Source File: Edition018_Espresso_Beta.java    From appiumpro with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogin_Espresso() throws MalformedURLException {
    AndroidDriver driver = getDriver("Espresso");
    WebDriverWait wait = new WebDriverWait(driver, 10);
    ExpectedCondition<WebElement> loginScreenReady =
        ExpectedConditions.presenceOfElementLocated(loginScreen);

    try {
        wait.until(loginScreenReady).click();
        driver.findElement(username).sendKeys("alice");
        driver.findElement(password).sendKeys("mypassword");
        driver.findElement(loginBtn).click();
        driver.findElement(verificationTextEspresso);
    } finally {
        driver.quit();
    }
}
 
Example #7
Source File: FirefoxTest.java    From selenium-example with MIT License 6 votes vote down vote up
@Test
public void testTitle() throws IOException {

    // Find elements by attribute lang="READ_MORE_BTN"
    List<WebElement> elements = driver
            .findElements(By.cssSelector("[lang=\"READ_MORE_BTN\"]"));

    //Click the selected button
    elements.get(0).click();


    assertTrue("The page title should be chagned as expected",
            (new WebDriverWait(driver, 3))
                    .until(new ExpectedCondition<Boolean>() {
                        public Boolean apply(WebDriver d) {
                            return d.getTitle().equals("我眼中软件工程人员该有的常识");
                        }
                    })
    );
}
 
Example #8
Source File: UserPageVisit.java    From cia with Apache License 2.0 6 votes vote down vote up
public ExpectedCondition<Boolean> containsButton(final String value) {
	return new ExpectedCondition<Boolean>() {

		@Override
		public Boolean apply(final WebDriver driver) {
			for (final WebElement webElement : getButtons()) {

				final WebElement refreshElement = StaleElementUtils.refreshElement(webElement, driver);
				if (ExpectedConditions.not(ExpectedConditions.stalenessOf(refreshElement)).apply(driver) && (value.equalsIgnoreCase(refreshElement.getText().trim()) || refreshElement.getText().trim().endsWith(value))) {
					return true;
				}
			}

			return false;
		}

		@Override
		public String toString() {
			return String.format("Button \"%s\". ", value);
		}
	};
}
 
Example #9
Source File: CustomConditions.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits for the current page URL
 * to match the provided regular expression.
 */
public static ExpectedCondition<Boolean> urlToMatch(final Pattern regexPattern) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            String url = driver.getCurrentUrl();
            Boolean matches = regexPattern.matcher(url).matches();
            return matches;
        }

        @Override
        public String toString() {
            return "current page URL to match: " + regexPattern.toString();
        }
    };
}
 
Example #10
Source File: BasicTestIT.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
@Test
public void googleCheeseExample() {
    driver.get("http://www.google.com");

    GoogleHomePage googleHomePage = new GoogleHomePage();

    System.out.println("Page title is: " + driver.getTitle());

    googleHomePage.enterSearchTerm("Cheese")
            .submitSearch();

    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until((ExpectedCondition<Boolean>) d -> d.getTitle().toLowerCase().startsWith("cheese"));

    System.out.println("Page title is: " + driver.getTitle());
    assertThat(driver.getTitle()).containsIgnoringCase("cheese");
}
 
Example #11
Source File: NoraUiExpectedConditions.java    From NoraUi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Expects that at least one of the given elements is present.
 *
 * @param locators
 *            The list of elements identified by their locators
 * @return true or false
 */
public static ExpectedCondition<WebElement> atLeastOneOfTheseElementsIsPresent(final By... locators) {
    return (@Nullable WebDriver driver) -> {
        WebElement element = null;
        if (driver != null && locators.length > 0) {
            for (final By b : locators) {
                try {
                    element = driver.findElement(b);
                    break;
                } catch (final Exception e) {
                }
            }
        }
        return element;
    };
}
 
Example #12
Source File: CustomConditions.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits until an element's text
 * content contains the specified text.
 */
public static ExpectedCondition<Boolean> elementTextToContain(final WebElement element, String text, boolean caseInsensitive) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            String elementText = element.getText();

            if (caseInsensitive) {
                return elementText.toLowerCase().contains(text.toLowerCase());
            } else {
                return elementText.contains(text);
            }
        }

        @Override
        public String toString() {
            return "element text to contain: " + text;
        }
    };
}
 
Example #13
Source File: PtlWebElement.java    From hifive-pitalium with Apache License 2.0 6 votes vote down vote up
/**
 * 要素を表示状態にします。
 */
public void show() {
	if (!isVisibilityHidden() && isDisplayed()) {
		LOG.debug("[Show element] already visible. ({})", this);
		return;
	}

	LOG.debug("[Show element start] ({})", this);
	executeJavaScript("return arguments[0].style.visibility = 'visible'", this);
	try {
		new WebDriverWait(driver, SHOW_HIDE_TIMEOUT).until(new ExpectedCondition<Boolean>() {
			@Override
			public Boolean apply(WebDriver webDriver) {
				return !isVisibilityHidden() && isDisplayed();
			}
		});
		LOG.debug("[Show element finished] ({})", this);
	} catch (TimeoutException e) {
		LOG.warn("[Show element timeout] {}", this);
	}
}
 
Example #14
Source File: CustomConditions.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits until an attribute's
 * value contains the specified text.
 */
public static ExpectedCondition<Boolean> elementAttributeToContain(final WebElement element, String attribute, String text, boolean caseInsensitive) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            String value = element.getAttribute(attribute);

            if (caseInsensitive) {
                return value.toLowerCase().contains(text.toLowerCase());
            } else {
                return value.contains(text);
            }
        }

        @Override
        public String toString() {
            return "element text to contain: " + text;
        }
    };
}
 
Example #15
Source File: Wizard.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * check present a text in group id field On Wizard
 *
 * @param text
 * @return is text present
 */
public void checkGroupIdOnWizardContainsText(final String text) {
  new WebDriverWait(seleniumWebDriver, 5)
      .until(
          new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
              WebElement element =
                  seleniumWebDriver.findElement(By.xpath(Locators.GROUP_ID_INPUT));
              return element.getAttribute("value").contains(text);
            }
          });
}
 
Example #16
Source File: SynchronisationService.java    From senbot with MIT License 5 votes vote down vote up
/**
 * Waits until the expectations are full filled or timeout runs out 
 * 
 * @param condition The conditions the element should meet
 * @param timeout The timeout to wait 
 * @return True if element meets the condition
 */
public boolean waitForExpectedCondition(ExpectedCondition<?> condition, int timeout) {
    WebDriver driver = getWebDriver();
    boolean conditionMet = true;
    try {
        new WebDriverWait(driver, timeout).until(condition);
    } catch (TimeoutException e) {
        conditionMet = false;
    }
    return conditionMet;
}
 
Example #17
Source File: SimpleWebElementInteractionImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
@Override
public WebElement getPresenceElementFoundBy(
		final boolean valueAlias,
		@NotNull final String value,
		@NotNull final FeatureState featureState,
		final long waitTime) {

	checkArgument(StringUtils.isNotBlank(value));
	checkNotNull(featureState);

	final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
	long time = 0;

	while (time < waitTime * Constants.MILLISECONDS_PER_SECOND) {
		for (final String locationMethod : LOCATION_METHODS) {
			try {
				final By by = getBy.getBy(locationMethod, valueAlias, value, featureState);
				final FluentWait<WebDriver> wait = new FluentWait<>(webDriver)
					.withTimeout(Duration.ofMillis(Constants.TIME_SLICE));
				final ExpectedCondition<WebElement> condition =
					ExpectedConditions.presenceOfElementLocated(by);

				return wait.until(condition);
			} catch (final Exception ignored) {
				/*
					Do nothing
				 */
			}

			time += Constants.TIME_SLICE;
		}
	}

	throw new WebElementException("All attempts to find element failed");
}
 
Example #18
Source File: MainIT.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void testExecute()
throws Exception
{
    System.setProperty("phantomjs.binary.path", System.getProperty("phantomjs.binary"));
    WebDriver driver = new PhantomJSDriver();
    
    // And now use this to visit birt report viewer
    driver.get("http://localhost:9999");

    // Check the title of the page
    assertEquals("Eclipse BIRT Home", driver.getTitle());
    
    // Click view exmaple button       
    WebElement element = driver.findElement(By.linkText("View Example"));
    element.click();

    // Wait until page loaded
    (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {

            // Check the title of loaded page
            assertEquals("BIRT Report Viewer", d.getTitle());


            // Check the success message
            assertTrue(d.getPageSource().contains("Congratulations!"));
            return true;
        }
    });

    //Close the browser
    driver.quit();    
}
 
Example #19
Source File: ExpectSteps.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @deprecated As of release 4.1, replaced by {@link com.github.noraui.selenium.NoraUiExpectedConditions#textToBeEqualsToExpectedValue(By, String)}
 *             Expects that the target element contains the given value as text.
 *             The inner text and 'value' attribute of the element are checked.
 * @param locator
 *            is the selenium locator
 * @param value
 *            is the expected value
 * @return true or false
 */
@Deprecated
public static ExpectedCondition<Boolean> textToBeEqualsToExpectedValue(final By locator, final String value) {
    return (@Nullable WebDriver driver) -> {
        try {
            final WebElement element = driver.findElement(locator);
            if (element != null && value != null) {
                return !((element.getAttribute(VALUE) == null || !value.equals(element.getAttribute(VALUE).trim())) && !value.equals(element.getText().replaceAll("\n", "")));
            }
        } catch (final Exception e) {
        }
        return false;
    };
}
 
Example #20
Source File: GitBranches.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * select given branch check enabled or not button rename
 *
 * @param nameOfBranch is name of branch
 */
public void selectBranchInListAndCheckEnabledButtonRename(final String nameOfBranch) {
  new WebDriverWait(seleniumWebDriver, 15)
      .until(
          new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver webDriver) {
              seleniumWebDriver
                  .findElement(
                      By.id(String.format(Locators.BRANCH_NAME_IN_LIST_PREFIX, nameOfBranch)))
                  .click();
              return (seleniumWebDriver.findElement(By.id(Locators.RENAME_BTN_ID)).isEnabled());
            }
          });
}
 
Example #21
Source File: TeasyExpectedConditions.java    From teasy with MIT License 5 votes vote down vote up
/**
 * Expected condition to look for elements inside given Context (inside element) in frames that will return as soon as elements are found in any frame
 *
 * @param searchContext
 * @param locator
 * @return
 */
public static ExpectedCondition<List<WebElement>> visibilityOfFirstElements(final TeasyElement searchContext, final By locator) {
    return new ExpectedCondition<List<WebElement>>() {
        @Override
        public List<WebElement> apply(final WebDriver driver) {
            List<WebElement> visibleElements = getFirstVisibleWebElements(driver, searchContext, locator);
            return isNotEmpty(visibleElements) ? visibleElements : null;
        }

        @Override
        public String toString() {
            return String.format("visibility of element located by %s -> %s", searchContext, locator);
        }
    };
}
 
Example #22
Source File: GitBranches.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** click on checkout button */
public void clickCheckOutBtn() {
  new WebDriverWait(seleniumWebDriver, 10)
      .until(
          new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver webDriver) {
              return (seleniumWebDriver.findElement(By.id(Locators.CHECKOUT_BTN_ID)).isEnabled());
            }
          });
  checkOutBtn.click();
}
 
Example #23
Source File: FindText.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * wait text into 'FileNameFilter' field
 *
 * @param expText is expected text
 */
public void waitTextIntoFileNameFilter(String expText) {
  new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
      .until(
          (ExpectedCondition<Boolean>)
              webDriver ->
                  seleniumWebDriver
                      .findElement(By.id(Locators.FILE_MASK_FIELD))
                      .getAttribute("value")
                      .equals(expText));
}
 
Example #24
Source File: CodenvyEditor.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public void waitCountTabsWithProvidedName(int countTabs, String tabName) {
  webDriverWaitFactory
      .get()
      .until(
          (ExpectedCondition<Boolean>)
              driver -> countTabs == getAllTabsWithProvidedName(tabName).size());
}
 
Example #25
Source File: KeycloakFederatedIdentitiesPage.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void waitTextInSuccessAlert(String expectedText) {
  loadPageWait.until(
      (ExpectedCondition<Boolean>)
          driver ->
              seleniumWebDriverHelper
                  .waitVisibility(xpath(SUCCESS_ALERT))
                  .getText()
                  .equals(expectedText));
}
 
Example #26
Source File: SeleniumWebDriverHelper.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Waits during {@code timeout} until specified {@code element} contains the specified {@code
 * expected} one.
 *
 * <p>Note! Text is extracted by {@link WebElement#getText()} method.
 *
 * @param element element which should be checked
 * @param expected text which should be presented
 * @param timeout waiting time in seconds
 */
public void waitTextContains(WebElement element, String expected, int timeout) {
  String[] actual = new String[1];
  webDriverWaitFactory
      .get(
          timeout,
          () -> format("\nactual text:\n'%s'\ndidn't contain:\n'%s'\n", actual[0], expected))
      .until(
          (ExpectedCondition<Boolean>)
              driver -> {
                actual[0] = waitVisibilityAndGetText(element, timeout);
                return actual[0].contains(expected);
              });
}
 
Example #27
Source File: BrokerTestTools.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void waitForPage(WebDriver driver, final String title, final boolean isHtmlTitle) {
    waitForPageToLoad();

    WebDriverWait wait = new WebDriverWait(driver, 5);
    ExpectedCondition<Boolean> condition = (WebDriver input) -> isHtmlTitle ? input.getTitle().toLowerCase().contains(title) : PageUtils.getPageTitle(input).toLowerCase().contains(title);

    wait.until(condition);
}
 
Example #28
Source File: Wizard.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * wait text from the 'Parent Directory' input
 *
 * @param nameDirectory is expected text from the 'Parent Directory' input
 */
public void waitTextParentDirectoryName(String nameDirectory) {
  new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
      .until(
          (ExpectedCondition<Boolean>)
              driver -> getNameFromParentDirectoryInput().equals(nameDirectory));
}
 
Example #29
Source File: ExtendedWebElement.java    From carina with Apache License 2.0 5 votes vote down vote up
/**
   * Check that element clickable within specified timeout.
   *
   * @param timeout - timeout.
   * @return element clickability status.
   */
  public boolean isClickable(long timeout) {
  	ExpectedCondition<?> waitCondition;
  	
if (element != null) {
	waitCondition = ExpectedConditions.elementToBeClickable(element);
} else {
	waitCondition = ExpectedConditions.elementToBeClickable(getBy());
}

  	return waitUntil(waitCondition, timeout);
  }
 
Example #30
Source File: AbstractWebappUiIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public static ExpectedCondition<Boolean> containsCurrentUrl(final String url) {

    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver webDriver) {
        return webDriver.getCurrentUrl().contains(url);
      }
    };

  }