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

The following examples show how to use org.openqa.selenium.support.ui.ExpectedCondition. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: appiumpro   Source File: Edition018_Espresso_Beta.java    License: 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 2
@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 3
Source Project: opentest   Source File: CustomConditions.java    License: 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 4
Source Project: hifive-pitalium   Source File: PtlWebElement.java    License: 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 5
Source Project: opentest   Source File: CustomConditions.java    License: 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 6
Source Project: selenium-example   Source File: FirefoxTest.java    License: 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 7
Source Project: che   Source File: CodenvyEditor.java    License: 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 8
Source Project: opentest   Source File: CustomConditions.java    License: 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 9
Source Project: teasy   Source File: TeasyExpectedConditions.java    License: 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 10
Source Project: teasy   Source File: TeasyExpectedConditions.java    License: 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 11
Source Project: SeleniumBestPracticesBook   Source File: SeleniumWrapper.java    License: 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 12
Source Project: opentest   Source File: CustomConditions.java    License: 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 13
/**
 * 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 14
Source Project: cia   Source File: UserPageVisit.java    License: 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 15
Source Project: che   Source File: GitCommit.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Wait for item check-box in the 'Git changed files tree panel' to be indeterminate.
 *
 * @param itemName name of the item
 */
public void waitItemCheckBoxToBeIndeterminate(String itemName) {
  new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
      .until(
          (ExpectedCondition<Boolean>)
              webDriver ->
                  seleniumWebDriver
                      .findElement(
                          By.xpath(
                              String.format(Locators.TREE_ITEM_CHECK_BOX + "//input", itemName)))
                      .getAttribute("id")
                      .endsWith("indeterminate"));
}
 
Example 16
Source Project: bobcat   Source File: WebElementConditions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Condition that checks if animation of provided WebElement finished.
 *
 * @param element WebElement to be checked
 * @return ExpectedCondition representing the above check
 */
public ExpectedCondition<WebElement> hasAnimationFinished(final WebElement element) {
  final Deque<Point> locations = new ArrayDeque<>();
  return webDriver -> {
    Point currentLocation = element.getLocation();
    boolean animationStopped = false;
    if (!locations.isEmpty()) {
      animationStopped = locations.peekFirst().equals(currentLocation);
    }

    locations.addFirst(currentLocation);
    return animationStopped ? element : null;
  };
}
 
Example 17
Source Project: portals-pluto   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
public static ExpectedCondition<Boolean> backgroundColor(By locator, int red, int green, int blue) {

      String colorCode = getColorCode(red, green, blue);

      return and(visibilityOfElementLocated(locator),
            or(attributeContains(locator, "style", "background-color:" + colorCode + ";"),
                  attributeContains(locator, "style",
                        "background-color: rgb(" + red + ", " + green + ", " + blue + ");")));
   }
 
Example 18
Source Project: che   Source File: CodenvyEditor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks that active line has specified {@code lineNumber}.
 *
 * @param lineNumber line's number which should be active
 */
public void expectedNumberOfActiveLine(final int lineNumber) {
  waitActive();
  webDriverWaitFactory
      .get()
      .until((ExpectedCondition<Boolean>) driver -> lineNumber == getPositionVisible());
}
 
Example 19
Source Project: vividus   Source File: DropDownStateTests.java    License: Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("dataForGetExpectedConditionTest")
void testGetExpectedCondition(DropDownState state, String expectedConditionPattern)
{
    WebElement webElement = mock(WebElement.class);
    ExpectedCondition<?> expectedCondition = state.getExpectedCondition(webElement);
    assertTrue(expectedCondition.toString().matches(expectedConditionPattern));
}
 
Example 20
public static ExpectedCondition<Boolean> currentURIIs(final URI pageURI) {

    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver webDriver) {
        try {
          return new URI(webDriver.getCurrentUrl()).equals(pageURI);
        } catch (URISyntaxException e) {
          return false;
        }
      }
    };

  }
 
Example 21
Source Project: che   Source File: Events.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/** wait while event message panel will be empty */
public void waitEmptyEventsPanel() {
  new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
      .until(
          (ExpectedCondition<Boolean>)
              driver -> {
                List<WebElement> messageCloseIcons =
                    seleniumWebDriver.findElements(By.id(CLOSE_EVENT_ICON));
                return messageCloseIcons.size() == 0;
              });
}
 
Example 22
Source Project: aquality-selenium-java   Source File: Browser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Waits until page is loaded
 * TimeoutException will be thrown if page is not loaded during timeout
 * Default timeout is fetched from settings file.
 * Use setPageLoadTimeout to configure your own timeout from code if it is necessary
 */
public void waitForPageToLoad() {
    ExpectedCondition<Boolean> condition = d -> {
        Object result = executeScript(JavaScript.IS_PAGE_LOADED.getScript());
        return result instanceof Boolean && (Boolean) result;
    };
    conditionalWait.waitFor(condition,
            timeouts.getPageLoad(),
            timeouts.getPollingInterval(),
            localizationManager.getLocalizedMessage("loc.browser.page.timeout"));
}
 
Example 23
Source Project: hsac-fitnesse-fixtures   Source File: BrowserTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries the condition one last time before throwing an exception.
 * This to prevent exception messages in the wiki that show no problem, which could happen if the browser's
 * window content has changed between last (failing) try at condition and generation of the exception.
 * @param <T> the return type of the method, which must not be Void
 * @param condition condition that caused exception.
 * @param e exception that will be thrown if condition does not return a result.
 * @return last attempt results, if not null or false.
 * @throws SlimFixtureException throws e if last attempt returns null.
 */
protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) {
    T lastAttemptResult = null;
    try {
        // last attempt to ensure condition has not been met
        // this to prevent messages that show no problem
        lastAttemptResult = condition.apply(getSeleniumHelper().driver());
    } catch (Throwable t) {
        // ignore
    }
    if (lastAttemptResult == null || Boolean.FALSE.equals(lastAttemptResult)) {
        throw e;
    }
    return lastAttemptResult;
}
 
Example 24
Source Project: appiumpro   Source File: Edition002_Android_Photos.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSeedPhotoPicker() throws IOException {
    DesiredCapabilities capabilities = new DesiredCapabilities();

    File classpathRoot = new File(System.getProperty("user.dir"));

    capabilities.setCapability("platformName", "Android");
    capabilities.setCapability("deviceName", "Android Emulator");
    capabilities.setCapability("automationName", "UiAutomator2");
    capabilities.setCapability("appPackage", "com.google.android.apps.photos");
    capabilities.setCapability("appActivity", ".home.HomeActivity");

    // Open the app.
    AndroidDriver driver = new AndroidDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);

    try {
        // there's some screens we need to navigate through and ensure there are no existing photos
        setupAppState(driver);

        // set up the file we want to push to the phone's library
        File assetDir = new File(classpathRoot, "../assets");
        File img = new File(assetDir.getCanonicalPath(), "cloudgrey.png");

        // actually push the file
        driver.pushFile(ANDROID_PHOTO_PATH + "/" + img.getName(), img);

        // wait for the system to acknowledge the new photo, and use the WebDriverWait to verify
        // that the new photo is there
        WebDriverWait wait = new WebDriverWait(driver, 10);
        ExpectedCondition condition = ExpectedConditions.numberOfElementsToBe(photo,1);
        wait.until(condition);
    } finally {
        driver.quit();
    }
}
 
Example 25
/**
 * Wait for the specified number of windows to exist, e.g. when launching a new one to ensure
 * it has been fully instantiated before interacting with it.
 *
 * @param	numberOfWindows	an int representing the desired number of windows to wait for.
 * @return	boolean true if the number of windows is currently numberOfWindows, false if not
 */
public static ExpectedCondition<Boolean> numberOfWindowsToBe(final int numberOfWindows) {
	return new ExpectedCondition<Boolean>() {
		@Override
		public Boolean apply(WebDriver driver) {
			driver.getWindowHandles();
			return driver.getWindowHandles().size() == numberOfWindows;
		}
	};
}
 
Example 26
private ExpectedCondition<Boolean> ZoomUIPresent() {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            try {
                driver.findElement(LEAVE_BTN);
                return true;
            } catch (NoSuchElementException ign) {
                driver.findElement(CONTENT).click();
            }
            return false;
        }
    };
}
 
Example 27
Source Project: che   Source File: Swagger.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/** expand 'workspace' item */
private void expandWorkSpaceItem() {
  Wait fluentWait =
      new FluentWait(seleniumWebDriver)
          .withTimeout(ELEMENT_TIMEOUT_SEC, SECONDS)
          .pollingEvery(MINIMUM_SEC, SECONDS)
          .ignoring(StaleElementReferenceException.class, NoSuchElementException.class);
  fluentWait.until((ExpectedCondition<Boolean>) input -> workSpaceLink.isEnabled());
  workSpaceLink.click();
}
 
Example 28
Source Project: mamute   Source File: PageObject.java    License: Apache License 2.0 5 votes vote down vote up
private void waitFor(int time, ExpectedCondition<WebElement> expectedCondition, String elementName) {
	try {
        new WebDriverWait(driver, time).until(expectedCondition);
       } catch (TimeoutException e) {
           LOG.warn("waited for element " + elementName + " but it didn't show up");
       }
}
 
Example 29
Source Project: che   Source File: SeleniumWebDriver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/** wait while in a browser appears more the 1 window */
public void waitOpenedSomeWin() {
  new WebDriverWait(this, 30)
      .until(
          (ExpectedCondition<Boolean>)
              input -> {
                Set<String> driverWindows = getWindowHandles();
                return (driverWindows.size() > 1);
              });
}
 
Example 30
Source Project: che   Source File: GitBranches.java    License: 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();
}