下面列出了org.openqa.selenium.support.ui.WebDriverWait#until ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void editRole(String role){
WebDriverWait waitLoad = new WebDriverWait(driver, 10);
WebElement permissionItem = driver.findElement(By.xpath(uiElementMapper.getElement("emm.roles.update.permissionItemLogin")));
permissionItem.click();
WebElement editRoleButton = driver.findElement(By.id(uiElementMapper.getElement("emm.roles.update.role.button")));
editRoleButton.click();
try {
By roleCreatedMsg = By.xpath(uiElementMapper.getElement(("emm.roles.update.role.created.msg.div")));
waitLoad.until(ExpectedConditions.visibilityOfElementLocated(roleCreatedMsg));
String resultText = driver.findElement(roleCreatedMsg
).getText();
if(!resultText.contains("PERMISSIONS WERE ASSIGNED TO THE ROLE SUCCESSFULLY")){
throw new IllegalStateException("Role was not edited");
}
} catch (TimeoutException e) {
throw new IllegalStateException("Role was not edited");
}
}
/**
* 切换到alter,并点击确认框
*/
public void clickAlert(String msg) {
WebDriverWait webDriverWait = new WebDriverWait(driver, 10);
Alert alert;
baseOpt.wait(20);
// Alert alert = driver.switchTo().alert();
try { // 不稳定,原因待查。还是用上面的吧
// wait and switchTo, Otherwise, throws a TimeoutException
alert = webDriverWait.until(ExpectedConditions.alertIsPresent());
} catch (Exception e) {
this.screenShot();
LogUtil.info(driver.manage().logs() + "==>alert等待超时!");
alert = driver.switchTo().alert(); // 与waituntil功能重复,但until经常失败,为了增强健壮性才如此写
}
if (msg != null) {
AssertUtil.assertEquals(alert.getText(), msg, "提示语错误");
}
alert.accept();
baseOpt.wait(30);
}
/**
* Performs the delete user action.
* @return After deleting a user, returns back to the user listing page.
*/
public UserListingPage deleteUser() throws IOException, InterruptedException {
WebElement deleteBtn = driver.findElement(By.xpath(
uiElementMapper.getElement("iot.admin.deleteUser.btn.xpath")));
WebDriverWait wait = new WebDriverWait(driver, UIUtils.webDriverTimeOut);
wait.until(ExpectedConditions.visibilityOf(deleteBtn));
deleteBtn.click();
WebElement deleteConfirmationBtn = driver.findElement(
By.xpath(uiElementMapper.getElement("iot.admin.deleteUser.yes.link.xpath")));
wait.until(ExpectedConditions.visibilityOf(deleteConfirmationBtn));
deleteConfirmationBtn.click();
Thread.sleep(UIUtils.threadTimeout);
WebElement deleteSuccessBtn = driver.findElement(
By.xpath(uiElementMapper.getElement("iot.admin.deleteUser.success.link.xpath")));
deleteSuccessBtn.click();
return new UserListingPage(driver);
}
@Test
public void testLogging_Hybrid() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("automationName", "UiAutomator2");
capabilities.setCapability("deviceName", "Android Emulator");
capabilities.setCapability("app", APP_ANDROID);
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new AndroidDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
WebDriverWait wait = new WebDriverWait(driver, 10);
// get to webview screen and enter webview mode
wait.until(ExpectedConditions.presenceOfElementLocated(hybridScreen)).click();
wait.until(ExpectedConditions.presenceOfElementLocated(urlInput));
driver.context(getWebContext(driver));
// now we can run the same routine as for the browser
loggingRoutine(driver);
}
/**
* Returns if a {@value CHANGE_EVENT} event has not been fired for the element to which the hook is associated.
* Note that this only detects the presence of firing of {@value CHANGE_EVENT} events and not does not keep track of
* how many {@value CHANGE_EVENT} events are fired.
*/
private boolean isChangeEventNotFired() {
WebDriverWait wait = new WebDriverWait(browser.driver, MAXIMUM_SECONDS_REQUIRED_FOR_ALL_CPUS_TO_FIRE_EVENT);
try {
wait.until(ExpectedConditions.attributeContains(By.tagName("body"), HOOK_ATTRIBUTE, "true"));
return false;
} catch (TimeoutException e) {
return true;
}
}
@Test(groups = "wso2.es.publisher", description = "Testing adding a new asset")
public void testAddAsset() throws Exception {
driver.get(baseUrl + PUBLISHER_GADGET_LIST_PAGE);
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Addgadget")));
driver.findElement(By.id("Addgadget")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("overview_name")));
driver.findElement(By.name("overview_name")).clear();
driver.findElement(By.name("overview_name")).sendKeys(assetName);
driver.findElement(By.name("overview_version")).clear();
driver.findElement(By.name("overview_version")).sendKeys(ASSET_VERSION_1);
driver.findElement(By.name("overview_url")).clear();
driver.findElement(By.name("overview_url")).sendKeys(ASSET_URL_1);
driver.findElement(By.name("overview_description")).clear();
driver.findElement(By.name("overview_description")).sendKeys(ASSET_DESCRIPTION_1);
driver.findElement(By.name("images_thumbnail")).sendKeys(FrameworkPathUtil.getReportLocation()
+"/../src/test/resources/images/thumbnail.jpg");
driver.findElement(By.name("images_banner")).sendKeys(FrameworkPathUtil.getReportLocation()
+"/../src/test/resources/images/banner.jpg");
driver.findElement(By.id("btn-create-asset")).click();
//driver.get(baseUrl + PUBLISHER_GADGET_LIST_PAGE);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Addgadget")));
driver.findElementPoll(By.linkText(assetName), MAX_POLL_COUNT);
//check if the created gadget is shown
assertTrue(isElementPresent(driver, By.linkText(assetName)), "Adding an asset failed for user:" + currentUserName);
driver.findElement(By.linkText(assetName)).click();
assertEquals(assetName, driver.findElement(By.cssSelector("#collapseOverview div:nth-child(2) div:nth-child(2)")).getText());
assertEquals(ASSET_VERSION_1, driver.findElement(By.cssSelector("#collapseOverview div:nth-child(3) div:nth-child(2)")).getText(),
"Incorrect version");
assertEquals(ASSET_CATEGORY_1, driver.findElement(By.cssSelector("#collapseOverview div:nth-child(4) div:nth-child(2)")).getText());
assertEquals(ASSET_URL_1, driver.findElement(By.cssSelector("#collapseOverview div:nth-child(5) div:nth-child(2)")).getText(),
"Incorrect URL");
assertEquals(ASSET_DESCRIPTION_1, driver.findElement(By.cssSelector("#collapseOverview div:nth-child(6) div:nth-child(2)")).getText(),
"Incorrect description");
}
@Test
public void testWithEmptyPassword()
{
goToLoginPage();
setFieldValue( "user-login-form-username", getProperty( "ADMIN_USERNAME" ) );
Assert.assertTrue(getWebDriver().findElement( By.id("modal-login-ok") ).isDisplayed());
Assert.assertTrue(getWebDriver().findElement( By.id("modal-login-ok") ).isEnabled());
clickLinkWithLocator( "modal-login-ok", false );
WebDriverWait wait = new WebDriverWait(getWebDriver(), 2);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("modal-login"), "This field is required."));
}
protected void createNewNote() {
clickAndWait(By.xpath("//div[contains(@class, \"col-md-4\")]/div/h5/a[contains(.,'Create new" +
" note')]"));
WebDriverWait block = new WebDriverWait(driver, MAX_BROWSER_TIMEOUT_SEC);
block.until(ExpectedConditions.visibilityOfElementLocated(By.id("noteCreateModal")));
clickAndWait(By.id("createNoteButton"));
block.until(ExpectedConditions.invisibilityOfElementLocated(By.id("createNoteButton")));
}
/**
* Locates and returns a UI element.
*/
protected WebElement getElement(By locator, int explicitWaitSec) {
WebDriverWait wait = new WebDriverWait(driver, explicitWaitSec);
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
@Test
public void name() {
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en");
WebDriverWait waiter = new WebDriverWait(driver, 10);
waiter.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("input#Email"))));
driver.findElement(By.cssSelector("a.need-help")).click();
waiter.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("input#Email")));
driver.findElement(By.id("identifier")).sendKeys("email");
Assertions.assertEquals( "email", driver.findElement(By.id("identifier")).getAttribute("value"));
}
@Override
public void run() {
super.run();
By locator = this.readLocatorArgument("locator");
String text = this.readStringArgument("text", null);
String key = this.readStringArgument("key", null);
Boolean clearContent = this.readBooleanArgument("clearContent", Boolean.FALSE);
Boolean sendEnter = this.readBooleanArgument("sendEnter", Boolean.FALSE);
this.waitForAsyncCallsToFinish();
try {
WebElement element = this.getElement(locator);
WebDriverWait wait = new WebDriverWait(this.driver, this.getExplicitWaitSec());
wait.until(ExpectedConditions.elementToBeClickable(element));
if (clearContent) {
element.clear();
}
if (text != null) {
element.sendKeys(text);
} else if (key != null) {
element.sendKeys(Keys.valueOf(key.toUpperCase()));
} else {
throw new RuntimeException("Neither the \"text\" argument, nor the \"key\" argument were provided.");
}
if (sendEnter) {
element.sendKeys(Keys.ENTER);
}
} catch (Exception ex) {
throw new RuntimeException(String.format(
"Failed sending keys to element %s",
locator), ex
);
}
}
@Test
public void testWeatherApp() {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AccessibilityId("NameAndConditions")));
for (WebElement el : driver.findElements(By.xpath("//ListItem[contains(@Name, 'day ')]"))) {
el.click();
WebElement sunrise = driver.findElement(MobileBy.AccessibilityId("Almanac_Sunrise"));
WebElement sunset = driver.findElement(MobileBy.AccessibilityId("Almanac_Sunset"));
System.out.println(el.getAttribute("Name"));
System.out.println("Sunrise: " + sunrise.getAttribute("Name"));
System.out.println("Sunset: " + sunset.getAttribute("Name"));
System.out.println("----------------------------");
}
}
/**
* 等待frame可以用,切换到指定的frame
*
* @param by
*/
public void switchTo(By frameby) {
WebDriverWait webDriverWait = new WebDriverWait(driver, DRIVER_WAIT_TIMEOUT_IN_SECOND);
try {
// wait and switchTo, Otherwise, throws a TimeoutException
webDriverWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameby));
// driver.switchTo().frame(this.findElement(frameby));
LogUtil.info(driver.manage().logs() + "==>switchTo frame:" + frameby.toString() + "成功.");
} catch (Exception e) {
this.screenShot();
LogUtil.info(driver.manage().logs() + "==>switchTo frame:" + frameby.toString() + "等待超时!");
driver.switchTo().frame(this.findElement(frameby)); // 与waituntil功能重复,但until经常失败,为了增强健壮性才如此写
}
}
protected void deleteTrashNotebook(final WebDriver driver) {
WebDriverWait block = new WebDriverWait(driver, MAX_BROWSER_TIMEOUT_SEC);
driver.findElement(By.xpath(".//*[@id='main']//button[@ng-click='removeNote(note.id)']"))
.sendKeys(Keys.ENTER);
block.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='main']//button[@ng-click='removeNote(note.id)']")));
driver.findElement(By.xpath("//div[@class='modal-dialog'][contains(.,'This cannot be undone. Are you sure?')]" +
"//div[@class='modal-footer']//button[contains(.,'OK')]")).click();
ZeppelinITUtils.sleep(100, false);
}
@Test
public void testThatUsingAccessKeysWorks() {
driver.get("http://web.masteringselenium.com/accessKeysHome.html");
WebDriverWait wait = new WebDriverWait(driver, 5, 100);
List<WebElement> home = driver.findElements(By.id("home"));
assertThat(home.size()).isEqualTo(1);
triggerAccessKey("9");
WebElement access = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about")));
home = driver.findElements(By.id("home"));
assertThat(home.size()).isEqualTo(0);
assertThat(access.isDisplayed()).isTrue();
}
/**
* Waits the given amount of time for a link with the supplied text to be placed in the DOM. Note that the
* element does not have to be visible just present in the HTML.
*
* @param waitDuration The maximum amount of time to wait for
* @param alias If this word is found in the step, it means the linkContent is found from the
* data set.
* @param linkContent The text content of the link we are wait for
* @param ignoringTimeout The presence of this text indicates that timeouts are ignored
*/
@When("^I wait \"(\\d+)\" seconds for a link with the text content of"
+ "( alias)? \"([^\"]*)\" to be present(,? ignoring timeouts?)?")
public void presentLinkStep(
final String waitDuration,
final String alias,
final String linkContent,
final String ignoringTimeout) {
try {
final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();
final String content = autoAliasUtils.getValue(
linkContent, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());
final WebDriverWait wait = new WebDriverWait(
webDriver,
Integer.parseInt(waitDuration),
Constants.ELEMENT_WAIT_SLEEP_TIMEOUT);
wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText(content)));
} catch (final TimeoutException ex) {
/*
Rethrow if we have not ignored errors
*/
if (StringUtils.isBlank(ignoringTimeout)) {
throw ex;
}
}
}
public <E> E waitFor(ExpectedCondition<E> expectedCondition) {
WebDriverWait wait = new WebDriverWait(browser.driver, TestProperties.TEST_TIMEOUT);
return wait.until(expectedCondition);
}
/**
* Clicks on an element that may or may not be visible on the page
*
* @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 timesAlias If this word is found in the step, it means the times is found from the
* data set.
* @param times If this text is set, the click operation will be repeated the specified number of times.
* @param exists If this text is set, an error that would be thrown because the element was not
* found is ignored. Essentially setting this text makes this an optional statement.
*/
@When("^I click (?:a|an|the) hidden element with (?:a|an|the) (ID|class|xpath|name|css selector)( alias)? "
+ "of \"([^\"]*)\"(?:( alias)? \"(.*?)\" times)?( if it exists)?$")
public void clickHiddenElementStep(
final String selector,
final String alias,
final String selectorValue,
final String timesAlias,
final String times,
final String exists) {
try {
final Integer fixedTimes = countConverter.convertCountToInteger(timesAlias, times);
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;
/*
PhantomJS doesn't support the click method, so "element.click()" won't work
here. We need to dispatch the event instead.
*/
for (int i = 0; i < fixedTimes; ++i) {
javaScriptRunner.interactHiddenElementMouseEvent(element, "click", js);
sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
}
} catch (final TimeoutException | NoSuchElementException ex) {
if (StringUtils.isBlank(exists)) {
throw ex;
}
}
}
@Override
public void run() {
super.run();
By locator = this.readLocatorArgument("locator");
this.waitForAsyncCallsToFinish();
WebDriverWait wait = new WebDriverWait(this.driver, this.getExplicitWaitSec());
wait.until(ExpectedConditions.elementSelectionStateToBe(locator, true));
}
@Override
public void run() {
super.run();
By locator = this.readLocatorArgument("locator");
this.waitForAsyncCallsToFinish();
WebDriverWait wait = new WebDriverWait(this.driver, this.getExplicitWaitSec());
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}