下面列出了org.openqa.selenium.NoSuchWindowException#org.openqa.selenium.support.ui.ExpectedCondition 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
@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");
}
/**
* 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;
}
};
}
/**
* 要素を表示状態にします。
*/
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);
}
}
/**
* 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();
}
};
}
@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("我眼中软件工程人员该有的常识");
}
})
);
}
/**
* 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));
}
/**
* 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();
}
};
}
/**
* 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);
}
};
}
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);
}
};
}
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;
}
});
}
/**
* 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;
}
};
}
/**
* 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;
};
}
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);
}
};
}
/**
* 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"));
}
/**
* 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;
};
}
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 + ");")));
}
/**
* 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());
}
@ParameterizedTest
@MethodSource("dataForGetExpectedConditionTest")
void testGetExpectedCondition(DropDownState state, String expectedConditionPattern)
{
WebElement webElement = mock(WebElement.class);
ExpectedCondition<?> expectedCondition = state.getExpectedCondition(webElement);
assertTrue(expectedCondition.toString().matches(expectedConditionPattern));
}
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;
}
}
};
}
/** 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;
});
}
/**
* 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"));
}
/**
* 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;
}
@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();
}
}
/**
* 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;
}
};
}
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;
}
};
}
/** 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();
}
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");
}
}
/** 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);
});
}
/** 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();
}