下面列出了怎么用org.openqa.selenium.support.ui.ExpectedConditions的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(groups = "wso2.es.store", description = "Test Anonymous Navigation from top menu")
public void testAnonNavigationTop() throws Exception {
//test menu navigation
driver.get(resolveStoreUrl());
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("popoverExampleTwo")));
driver.findElement(By.id("popoverExampleTwo")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Gadget")));
driver.findElement(By.linkText("Gadget")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText(LINE_CHART )));
driver.findElementPoll(By.linkText(LINE_CHART ), MAX_POLL_COUNT);
assertEquals(LINE_CHART, driver.findElement(By.linkText(LINE_CHART ))
.getText(), "Gadgets Menu not working");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("popoverExampleTwo")));
driver.findElement(By.id("popoverExampleTwo")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Site")));
driver.findElement(By.linkText("Site")).click();
driver.findElementPoll(By.linkText(AMAZON), MAX_POLL_COUNT);
assertEquals(AMAZON, driver.findElement(By.linkText(AMAZON)).getText(),
"Sites Menu not working");
driver.findElement(By.cssSelector("h2.app-title")).click();
}
public WebElement selectValue( String locator, String value, boolean scrollToView )
{
int count = 5;
boolean check = true;
WebDriverWait wait = new WebDriverWait( getWebDriver( ), 10 );
WebElement element = null;
while(check && count-->0)
{
try
{
element = findElement( locator );
List<WebElement> elementList = new ArrayList<>( );
elementList.add( element );
wait.until( ExpectedConditions.visibilityOfAllElements( elementList ) );
check=false;
} catch (Throwable e) {
logger.info("Waiting for select element {} to be visible", locator);
}
}
Select select = new Select(element);
select.selectByValue( value );
return element;
}
/**
* Clears the contents of an element
*
* @param selector Either ID, class, xpath, name or css selector
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias was
* set, this value is found from the data set. Otherwise it is a literal value.
*/
@When("^I clear (?:a|an|the) hidden element with (?:a|an|the) "
+ "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\"")
public void clearHiddenElement(final String selector, final String alias, final String selectorValue) {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final By by = getBy.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, State.getFeatureStateForThread());
final WebDriverWait wait = new WebDriverWait(
webDriver,
State.getFeatureStateForThread().getDefaultWait(),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
final WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(by));
mouseMovementUtils.mouseGlide(
webDriver,
(JavascriptExecutor) webDriver,
element,
Constants.MOUSE_MOVE_TIME,
Constants.MOUSE_MOVE_STEPS);
final JavascriptExecutor js = (JavascriptExecutor) webDriver;
js.executeScript("arguments[0].value='';", element);
sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
}
@Override
public void sendKeys(CharSequence... arg0) {
int attemp = 1;
boolean typeSucess = false;
while (!typeSucess && attemp <= 5) {
try {
WebDriverWait wait = new WebDriverWait(this.nativeAppDriver, maxWaitTime, 500);
wait.until(ExpectedConditions.presenceOfElementLocated(this.getByLocator()));
attemp++;
webElement.sendKeys(arg0);
typeSucess = true;
} catch (Exception e) {
if (attemp > 5) {
Reporter.log("Unable to enter text into element by " + this.getByLocator().toString());
this.getCateredWebDriver().captureScreenshot();
throw e;
}
}
}
}
private void automateClipboard(AppiumDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 5);
try {
wait.until(ExpectedConditions.presenceOfElementLocated(clipboardNav)).click();
String text = "Hello World";
((HasClipboard) driver).setClipboardText(text);
wait.until(ExpectedConditions.presenceOfElementLocated(refreshClipboardBtn)).click();
By clipboardText = MobileBy.AccessibilityId(text);
Assert.assertEquals(driver.findElement(clipboardText).getText(), text);
text = "Hello World Again";
driver.findElement(clipboardInput).sendKeys(text);
try {
driver.hideKeyboard();
} catch (Exception ign) {}
driver.findElement(setTextBtn).click();
Assert.assertEquals(((HasClipboard) driver).getClipboardText(), text);
} finally {
driver.quit();
}
}
/**
* select given branch check enabled or not button checkout
*
* @param nameOfBranch is name of branch
*/
public void selectBranchAndCheckEnabledButtonCheckout(final String nameOfBranch) {
new WebDriverWait(seleniumWebDriver, 5)
.until(
new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
new WebDriverWait(seleniumWebDriver, 5)
.until(
ExpectedConditions.visibilityOfElementLocated(
By.id(
String.format(Locators.BRANCH_NAME_IN_LIST_PREFIX, nameOfBranch))))
.click();
return seleniumWebDriver.findElement(By.id(Locators.CHECKOUT_BTN_ID)).isEnabled();
}
});
}
@Test
public void testLocationPermissions() {
// first, set the geolocation to something arbitrary
double newLat = 49.2827, newLong = 123.1207;
driver.setLocation(new Location(newLat, newLong, 0));
// now navigate to the location demo
wait.until(ExpectedConditions.presenceOfElementLocated(geolocation)).click();
// if permissions were set correctly, we should get no popup and instead be
// able to read the latitude and longitude that were previously set
By newLatEl = MobileBy.AccessibilityId("Latitude: " + newLat);
By newLongEl = MobileBy.AccessibilityId("Longitude: " + newLong);
wait.until(ExpectedConditions.presenceOfElementLocated(newLatEl));
wait.until(ExpectedConditions.presenceOfElementLocated(newLongEl));
}
public void testShadowElementsWithJS(AppiumDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(URL);
// find the web component
WebElement switchComponent = wait.until(ExpectedConditions.presenceOfElementLocated(
SWITCH_COMPONENT));
// pierce shadow dom to get checked status of inner control, and assert on it
boolean checked = (boolean) driver.executeScript(INPUT_CHECKED, switchComponent);
Assert.assertEquals(false, checked);
// change the state from off to on by clicking inner input
// (clicking the parent component will not work)
driver.executeScript(CLICK_INPUT, switchComponent);
// check that state of inner control has changed appropriately
checked = (boolean) driver.executeScript(INPUT_CHECKED, switchComponent);
Assert.assertEquals(true, checked);
}
/**
* @param conditions
* list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
* @throws FailureException
* if the scenario encounters a functional error.
*/
@Conditioned
@Alors("La partie referenceur du portail BAKERY est affichée(\\?)")
@Then("The referencer part of the BAKERY portal is displayed(\\?)")
public void checkReferencerPage(List<GherkinStepCondition> conditions) throws FailureException {
try {
Wait.until(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(referencerPage.titleMessage)));
if (!referencerPage.checkPage()) {
logInToBakeryWithBakeryRobot();
}
if (!referencerPage.checkPage()) {
new Result.Failure<>(referencerPage.getApplication(), Messages.getMessage(Messages.FAIL_MESSAGE_UNKNOWN_CREDENTIALS), true, referencerPage.getCallBack());
}
} catch (Exception e) {
new Result.Failure<>(referencerPage.getApplication(), Messages.getMessage(Messages.FAIL_MESSAGE_UNKNOWN_CREDENTIALS), true, referencerPage.getCallBack());
}
Auth.setConnected(true);
}
/**
* Wait for render a html element
*
* @param method
* @param element
* @param sTimeout
*/
@When("^I wait for element '([^:]*?):(.+?)' to be available for '(\\d+?)' seconds$")
public void seleniumWait(String method, String element, String sTimeout) {
Integer timeout = sTimeout != null ? Integer.parseInt(sTimeout) : null;
RemoteWebDriver driver = commonspec.getDriver();
WebDriverWait driverWait = new WebDriverWait(driver, timeout);
By criteriaSel = null;
if ("id".equals(method)) {
criteriaSel = By.id(element);
} else if ("name".equals(method)) {
criteriaSel = By.name(element);
} else if ("class".equals(method)) {
criteriaSel = By.className(element);
} else if ("xpath".equals(method)) {
criteriaSel = By.xpath(element);
} else if ("css".equals(method)) {
criteriaSel = By.cssSelector(element);
} else {
fail("Unknown search method: " + method);
}
driverWait.until(ExpectedConditions.
presenceOfElementLocated(criteriaSel));
}
/**
* Clears the contents of an element
*
* @param selector Either ID, class, xpath, name or css selector
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias was
* set, this value is found from the data set. Otherwise it is a literal value.
*/
@When("^I clear (?:a|an|the) element with (?:a|an|the) "
+ "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\"")
public void clearElement(final String selector, final String alias, final String selectorValue) {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final By by = getBy.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, State.getFeatureStateForThread());
final WebDriverWait wait = new WebDriverWait(
webDriver,
State.getFeatureStateForThread().getDefaultWait(),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
final WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(by));
mouseMovementUtils.mouseGlide(
webDriver,
(JavascriptExecutor) webDriver,
element,
Constants.MOUSE_MOVE_TIME,
Constants.MOUSE_MOVE_STEPS);
element.clear();
sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
}
public void waitOrganizationName(String name) {
redrawUiElementsTimeout.until(
ExpectedConditions.attributeToBeNotEmpty(organizationName, "value"));
redrawUiElementsTimeout.until(
(WebDriver driver) ->
driver
.findElement(By.xpath(Locators.ORGANIZATION_NAME))
.getAttribute("value")
.equals(name));
}
/**
* Verifies that the element is placed in the DOM within a certain amount of time. Note that the element
* does not have to be visible, just present in the HTML.
* You can use this step to verify that the page is in the correct state before proceeding with the script.
*
* @param waitDuration The maximum amount of time to wait for
* @param selector Either ID, class, xpath, name or css selector
* @param alias If this word is found in the step, it means the selectorValue is found from the
* data set.
* @param selectorValue The value used in conjunction with the selector to match the element. If alias
* was set, this value is found from the data set. Otherwise it is a literal
* value.
* @param ignoringTimeout Include this text to ignore a timeout while waiting for the element to be
* present
*/
@Then("^(?:I verify(?: that)? )?(?:a|an|the) element with (?:a|an|the) "
+ "(ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" "
+ "is present(?: within \"(\\d+)\" seconds?)?(,? ignoring timeouts?)?")
public void presentWaitStep(
final String selector,
final String alias,
final String selectorValue,
final String waitDuration,
final String ignoringTimeout) {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final By by = getBy.getBy(selector, StringUtils.isNotBlank(alias), selectorValue, State.getFeatureStateForThread());
final WebDriverWait wait = new WebDriverWait(
webDriver,
NumberUtils.toLong(waitDuration, State.getFeatureStateForThread().getDefaultWait()),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
try {
wait.until(ExpectedConditions.presenceOfElementLocated(by));
} catch (final TimeoutException ex) {
/*
Rethrow if we have not ignored errors
*/
if (StringUtils.isBlank(ignoringTimeout)) {
throw ex;
}
}
}
/**
* close by click on the tab name of process
*
* @param nameProcess is name tab name of process
*/
public void closeProcessByTabName(String nameProcess) {
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.elementToBeClickable(
By.xpath(String.format(Locators.TAB_PROCESS_CLOSE_ICON, nameProcess))))
.click();
}
public void waitForMarkers() {
new WebDriverWait(driver, MAP_LOAD_TIMEOUT).withMessage("Map never stopped loading")
.until(ExpectedConditions.presenceOfElementLocated(cssSelector(".service-view-container:not(.hide) .map-loading-spinner > .loading-spinner.hide")));
try {
Thread.sleep(WAIT_FOR_MAP_FIT_TO_BOUNDS);
} catch (final InterruptedException e) {
fail(e.getMessage());
}
}
public SearchFileResult getResults() {
String text =
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.SEARCH_RESULTS)))
.getText();
return new SearchFileResult(text);
}
@After
public void deleteAlarm(){
//click on delete
Utils.clickWhenReady(driver, driver.findElements(By.name("remove-subscription")).get(0));
LOGGER.info("open alarm deletion modal");
//wait and click on delete
new WebDriverWait(driver,Utils.DEFAULT_WAITING_TIME).until(ExpectedConditions.visibilityOfElementLocated(By.id("modal-delete")));
Utils.clickWhenReady(driver, By.id("modal-delete-subscription-ok"));
LOGGER.info("alarm is removed");
//wait list of alarms
new WebDriverWait(driver,Utils.DEFAULT_WAITING_TIME).until(ExpectedConditions.visibilityOfElementLocated(By.id("filterBarText")));
}
/** wait for disappearing of delete button in ssh keys menu. */
public void waitDeleteButtonDisappear() {
new WebDriverWait(seleniumWebDriver, 30)
.until(
ExpectedConditions.invisibilityOfElementLocated(
By.xpath(String.format(Locators.DELETE_SSH_KEY_BTN, testUser.getName()))));
}
/** Clear opened and closed panel */
public void clearAllMessages() {
List<WebElement> messageCloseIcons = seleniumWebDriver.findElements(By.xpath(CLOSE_EVENT_ICON));
for (WebElement messageCloseIcon : messageCloseIcons) {
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(ExpectedConditions.visibilityOf(messageCloseIcon));
messageCloseIcon.click();
}
waitEmptyEventsPanel();
}
@Test
public void testSavedTextAfterUpgrade () throws IOException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "Android Emulator");
capabilities.setCapability("automationName", "UiAutomator2");
capabilities.setCapability("app", APP_V1_0_0);
// change this to APP_V1_0_1 to experience a failing scenario
String appUpgradeVersion = APP_V1_0_2;
// Open the app.
AndroidDriver driver = new AndroidDriver(new URL("http://localhost:4723/wd/hub"), capabilities);
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
wait.until(ExpectedConditions.presenceOfElementLocated(echoBox)).click();
wait.until(ExpectedConditions.presenceOfElementLocated(msgInput)).sendKeys(TEST_MESSAGE);
wait.until(ExpectedConditions.presenceOfElementLocated(saveMsgBtn)).click();
String savedText = wait.until(ExpectedConditions.presenceOfElementLocated(savedMsg)).getText();
Assert.assertEquals(savedText, TEST_MESSAGE);
driver.installApp(appUpgradeVersion);
Activity activity = new Activity(APP_PKG, APP_ACT);
driver.startActivity(activity);
wait.until(ExpectedConditions.presenceOfElementLocated(echoBox)).click();
savedText = wait.until(ExpectedConditions.presenceOfElementLocated(savedMsg)).getText();
Assert.assertEquals(savedText, TEST_MESSAGE);
} finally {
driver.quit();
}
}
/** type text into 'Find Action' form */
public void typeTextIntoFindActionForm(String text) {
waitEnterActionFormIsOpen();
clearTextBoxActionForm();
for (char symbol : text.toCharArray()) {
waitWithRedrawTimeout
.until(ExpectedConditions.visibilityOf(textBoxActionForm))
.sendKeys(Character.toString(symbol));
}
waitWithRedrawTimeout.until(
ExpectedConditions.textToBePresentInElementValue(textBoxActionForm, text));
}
public void runCommandByName(String commandName) {
new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
.until(ExpectedConditions.visibilityOf(getCommandByName(commandName)));
new Actions(seleniumWebDriver).doubleClick(getCommandByName(commandName)).build().perform();
commandsEditor.waitActive();
commandsEditor.clickOnRunButton();
commandsEditor.clickOnCancelCommandEditorButton();
}
/** type into password field on Google authorization page user - defined password */
public void typePasswordDefinedByUser(String password) {
new WebDriverWait(seleniumWebDriver, 10)
.until(ExpectedConditions.visibilityOf(passwordInput))
.sendKeys(password);
passwordInput.sendKeys(Keys.ENTER.toString());
}
public static boolean isElementPresent(Log log, WebDriver driver, By by) {
try {
WebDriverWait wait = new WebDriverWait(driver, webDriverTime);
wait.until(ExpectedConditions.presenceOfElementLocated(by));
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
log.error(by.toString() + " is not present");
return false;
}
}
/**
* Gets the connected cup device web app URL.
* @return : Link of the connected cup device web app.
*/
public String getDeviceLink() {
WebDriverWait wait = new WebDriverWait(driverServer, UIUtils.webDriverTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(
uiElementMapper.getElement("iot.sample.connectedcup.gotodevice.xpath"))));
return driverServer.findElement(By.xpath(
uiElementMapper.getElement("iot.sample.connectedcup.gotodevice.xpath"))).getAttribute("href");
}
@Test
@RunAsClient
public void testNavigationActionMethod2() throws MalformedURLException
{
driver.get(new URL(contextPath, "origin.xhtml").toString());
WebElement button = driver.findElement(By.id("destination:pb004ActionMethod2"));
button.click();
Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("overviewPage"),
"You arrived at overview page").apply(driver));
}
/**
* Select the type of packaging on Wizard
*
* @param mavenType type project of Maven
*/
public void selectPackagingType(PackagingMavenType mavenType) {
List<WebElement> DropDownList =
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.presenceOfAllElementsLocatedBy(
By.xpath(Locators.SELECT_PACKAGING_DROPDOWN_BLOCK)));
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath(Locators.SELECT_PACKAGING_DROPDOWN)))
.click();
switch (mavenType) {
case JAR:
DropDownList.get(1).click();
break;
case WAR:
DropDownList.get(2).click();
break;
case POM:
DropDownList.get(3).click();
break;
default:
DropDownList.get(0).click();
break;
}
}
/**
* To check the given text contains by the element located by the locator
*
* @param by
* @param text
* @return
*/
public boolean verifyElementTextContains(By by, String text) {
boolean result = false;
String actualText = "";
int attempt = 0;
NativeAppElement webElment = findElement(by);
while (!result && attempt <= 5) {
try {
attempt++;
WebDriverWait wait = (WebDriverWait) new WebDriverWait(
appiumDriver, maxWaitTime, 500);
wait.until(ExpectedConditions.presenceOfElementLocated(by));
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
if (webElment.getTagName().equalsIgnoreCase("input")
|| webElment.getTagName().equalsIgnoreCase("textarea")) {
actualText = webElment.getAttribute("value");
} else {
actualText = webElment.readInnerText();
}
} catch (Exception e) {
System.err.println("attempt " + attempt + "...");
if (attempt > 5) {
Reporter.log("Unable to get the text by locator "
+ by.toString());
captureScreenshot();
throw new WebDriverException(e);
}
}
result = actualText.contains(text);
}
if (result) {
return true;
} else {
Reporter.log("\"" + text + "\" not found in \"" + actualText + "\"");
captureScreenshot();
throw new AssertionError("\"" + text + "\" not found in \""
+ actualText + "\"" + "\n"
+ Thread.currentThread().getStackTrace().toString());
}
}
/** Start CommandPalette widget by Shift+F10 hot keys */
public void openCommandPaletteByHotKeys() {
loader.waitOnClosed();
actionsFactory
.createAction(seleniumWebDriver)
.sendKeys(Keys.SHIFT.toString(), Keys.F10.toString())
.perform();
redrawUiElementTimeout.until(ExpectedConditions.visibilityOf(commandPalette));
}
/** type project name on wizard */
public void typeProjectNameOnWizard(String projectName) {
new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
.until(ExpectedConditions.visibilityOf(projectNameInput))
.clear();
waitProjectNameOnWizard();
new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
.until(ExpectedConditions.visibilityOf(projectNameInput))
.sendKeys(projectName);
loader.waitOnClosed();
}