下面列出了怎么用org.openqa.selenium.support.ui.WebDriverWait的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* scroll terminal by pressing key 'End'
*
* @param item is the name of the highlighted item
*/
public void moveDownListTerminal(String item) {
loader.waitOnClosed();
typeIntoActiveTerminal(Keys.END.toString());
WaitUtils.sleepQuietly(2);
WebElement element =
seleniumWebDriver.findElement(
By.xpath(format("(//span[contains(text(), '%s')])[position()=1]", item)));
if (!element.getCssValue("background-color").equals(LINE_HIGHLIGHTED_GREEN)) {
typeIntoActiveTerminal(Keys.ARROW_UP.toString());
element =
seleniumWebDriver.findElement(
By.xpath(format("(//span[contains(text(), '%s')])[position()=1]", item)));
WaitUtils.sleepQuietly(2);
}
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(visibilityOf(element));
WebElement finalElement = element;
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
(WebDriver input) ->
finalElement.getCssValue("background-color").equals(LINE_HIGHLIGHTED_GREEN));
}
@Test
@Ignore("See if can be run with phantomjs and/or update to geckodriver")
public void testErrorMessageForNonNullAnnotatedComponent() throws InterruptedException {
driver.navigate().to(
"http://localhost:5678/"
+ MBeanFieldGroupRequiredErrorMessage.class.getCanonicalName());
new WebDriverWait(driver, 30).until(VaadinConditions::ajaxCallsCompleted);
WebElement txtField = driver.findElement(By.id("txtStreet"));
Actions toolAct = new Actions(driver);
toolAct.moveToElement(txtField).build().perform();
Thread.sleep(1000);
WebElement toolTipElement = driver.findElement(By.cssSelector(".v-app.v-overlay-container > .v-tooltip > .popupContent .v-errormessage > div > div"));
assertThat(toolTipElement.getText(), is(expectedMessage));
}
@Override
public void run() {
super.run();
By locator = this.readLocatorArgument("locator");
String className = this.readStringArgument("class");
this.waitForAsyncCallsToFinish();
WebElement element = this.getElement(locator);
try {
WebDriverWait wait = new WebDriverWait(this.driver, this.getExplicitWaitSec());
wait.until(CustomConditions.elementToHaveClass(element, className));
} catch (Exception ex) {
throw new RuntimeException(String.format(
"Failed to find class \"%s\" on element. The value of the element's class attribute was \"%s\"",
className,
element.getAttribute("class")), ex);
}
}
public void editANodeWithEditor() throws Throwable {
System.err.println("Ignore the following NPE. The DynamicTree class has a bug");
WebElement tree = page.getTree();
tree.click();
final WebElement root = tree.findElement(By.cssSelector(".::root"));
AssertJUnit.assertEquals("Root Node", root.getText());
WebElement editor = root.findElement(By.cssSelector(".::editor"));
editor.clear();
editor.sendKeys("Hello World", Keys.ENTER);
root.submit();
new WebDriverWait(driver, 3).until(new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver input) {
return root.getText().equals("Hello World");
}
});
AssertJUnit.assertEquals("Hello World", root.getText());
}
@Test
@NotYetImplemented(SAFARI)
public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchTo() {
driver.manage().timeouts().implicitlyWait(1, SECONDS);
driver.get(pages.xhtmlTestPage);
driver.findElement(By.name("windowOne")).click();
Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(1));
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
String handle = (String)driver.getWindowHandles().toArray()[1];
WebDriver newWindow = driver.switchTo().window(handle);
long start = System.currentTimeMillis();
newWindow.findElements(By.id("this-crazy-thing-does-not-exist"));
long end = System.currentTimeMillis();
long time = end - start;
assertThat(time).isGreaterThanOrEqualTo(1000);
}
public Object executeScriptAndWaitOutput(final String command) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.withMessage("Timeout executing script: " + command);
final Object[] out = new Object[1];
wait.until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d) {
try {
out[0] = executeScript(command);
} catch (WebDriverException we) {
log.warn("Exception executing script", we);
out[0] = null;
}
return out[0] != null;
}
});
return out[0];
}
public void deleteCommandByName(String commandName) {
selectCommandByName(commandName);
loader.waitOnClosed();
new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[@id='command_" + commandName + "']")))
.click();
new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath(
"//div[@id='command_"
+ commandName
+ "']//span[@id='commands_tree-button-remove']")))
.click();
askDialog.waitFormToOpen();
askDialog.confirmAndWaitClosed();
}
/**
* Wait till the element is displayed and swipe till the particular time
* slot
*
* @param id
* - id of the element
*/
public void swipe(String id) {
try {
if (isAndroid()) {
new WebDriverWait(appiumDriver, 20).until(ExpectedConditions
.presenceOfElementLocated(By.id(id)));
Dimension dimension = appiumDriver.manage().window().getSize();
int ht = dimension.height;
int width = dimension.width;
appiumDriver.swipe((width / 2), (ht / 4), (width / 2),
(ht / 2), 1000);
} else {
new WebDriverWait(appiumDriver, 20).until(ExpectedConditions
.presenceOfElementLocated(By.id(id)));
if (deviceName.equalsIgnoreCase("iphone 5")) {
appiumDriver.swipe((int) 0.1, 557, 211, 206, 500);
} else if (deviceName.equalsIgnoreCase("iphone 6")) {
appiumDriver.swipe((int) 0.1, 660, 50, 50, 500);
}
}
} catch (Throwable e) {
Reporter.log("Element by Id " + id + " not visible");
captureScreenshot();
throw e;
}
}
public void typeAndWait(String value) {
component.clear();
component.sendKeys(Keys.BACK_SPACE, value);
final AdfComponent comp = component;
new WebDriverWait(component.getDriver(), 10, 100).until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver webDriver) {
if (isPopupVisible()) {
comp.waitForPpr();
return true;
} else {
return false;
}
}
});
}
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;
}
@Test
public void testIOSFaceId() {
driver.executeScript("mobile:enrollBiometric", ImmutableMap.of("isEnabled", true));
WebElement loginButton = driver.findElementByAccessibilityId("Log In");
loginButton.click();
driver.switchTo().alert().accept();
driver.executeScript("mobile:sendBiometricMatch", ImmutableMap.of("type", "faceId", "match", true));
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Log Out")));
WebElement logoutButton = driver.findElementByAccessibilityId("Log Out");
logoutButton.click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("Log In")));
loginButton = driver.findElementByAccessibilityId("Log In");
loginButton.click();
driver.executeScript("mobile:sendBiometricMatch", ImmutableMap.of("type", "faceId", "match", false));
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().dismiss();
}
@Deprecated
public WebElement clickTreeItemExpandCollapseIcon(final String itemLabel) {
final WebElement webElement =
driver.findElement(By.xpath("//li[span[text()='" + itemLabel + "']]/img[contains(@class, 'expand-collapse-padding')]"));
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOf(webElement));
webElement.click();
return webElement;
}
protected Boolean waitForPageToLoad() {
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebDriverWait wait = new WebDriverWait(driver, 10); //give up after 10 seconds
//keep executing the given JS till it returns "true", when page is fully loaded and ready
return wait.until((ExpectedCondition<Boolean>) input -> {
String res = jsExecutor.executeScript("return /loaded|complete/.test(document.readyState);").toString();
return Boolean.parseBoolean(res);
});
}
public void clickOnCancelChangesBtn() {
// this timeout is needed for the Cancel to appears after renaming of a workspace
WaitUtils.sleepQuietly(3);
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(visibilityOf(cancelBtn))
.click();
}
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")));
}
/** click on authorize button */
public void clickOnAuthorizeBtn() {
waitAuthorizeBtn();
new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
.until(ExpectedConditions.elementToBeClickable(authorizeBtn));
authorizeBtn.click();
}
/**
* wait text into 'Source Folder'
*
* @param expText is a value of text
*/
public void waitExpTextInSourceFolder(String expText, String typeFolder) {
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath(String.format(Locators.FOLDER_PATH_FIELD_XPATH, typeFolder))));
WebElement fieldFolder =
seleniumWebDriver.findElement(
By.xpath(String.format(Locators.FOLDER_PATH_FIELD_XPATH, typeFolder)));
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
(WebDriver webDriver) -> {
return fieldFolder.getAttribute("value").contains(expText);
});
}
private String getAuthorizationResponseUrl() throws InterruptedException {
// Optional, if not specified, WebDriver will search your path for chromedriver.
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
WebDriver driver = new ChromeDriver();
OAuth2Api auth2Api = new OAuth2Api();
String authorizeUrl = auth2Api.generateUserAuthorizationUrl(EXECUTION_ENV, SCOPE_LIST, Optional.of("current-page"));
driver.get(authorizeUrl);
Thread.sleep(5000);
WebElement userId = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("input[type='text']"))));
WebElement password = driver.findElement(By.cssSelector("input[type='password']"));
userId.sendKeys(CRED_USERNAME);
password.sendKeys(CRED_PASSWORD);
driver.findElement(By.name("sgnBt")).submit();
Thread.sleep(5000);
String url = null;
if (driver.getCurrentUrl().contains("code=")) {
printDetailedLog("Code Obtained");
url = driver.getCurrentUrl();
} else {
WebElement agreeBtn = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("submit"))));
agreeBtn.submit();
Thread.sleep(5000);
url = driver.getCurrentUrl();
}
driver.quit();
return url;
}
private WebDriverWait getWait(int timeOutInSeconds,int pollingEveryInMiliSec) {
oLog.debug("");
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.pollingEvery(pollingEveryInMiliSec, TimeUnit.MILLISECONDS);
wait.ignoring(NoSuchElementException.class);
wait.ignoring(ElementNotVisibleException.class);
wait.ignoring(StaleElementReferenceException.class);
wait.ignoring(NoSuchFrameException.class);
return wait;
}
/**
* This method executes Connected cup sample web app.
* @return : The Connected cup web page.
*/
public ConnectedCupDeviceInterface gotoDevice() throws IOException {
WebDriverWait wait = new WebDriverWait(driverServer, UIUtils.webDriverTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(
uiElementMapper.getElement("iot.sample.connectedcup.gotodevice.xpath"))));
String link = driverServer.findElement(By.xpath(
uiElementMapper.getElement("iot.sample.connectedcup.gotodevice.xpath"))).getAttribute("href");
driverDevice.get(link);
return new ConnectedCupDeviceInterface(driverDevice);
}
public void actualTest(AppiumDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
driver.get("https://appiumpro.com/test");
// click the link
wait.until(ExpectedConditions.presenceOfElementLocated(link)).click();
// assert we navigated as expected
wait.until(ExpectedConditions.urlToBe("https://appiumpro.com/"));
} finally {
driver.quit();
}
}
public void selectItemInFindInfoPanelByDoubleClick(String fileName, String textToFind) {
List<WebElement> webElementList =
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(
By.xpath(String.format(Locators.OCCURRENCE, fileName))));
for (WebElement webElement : webElementList) {
if (webElement.getText().equals(textToFind)) {
actionsFactory.createAction(seleniumWebDriver).doubleClick(webElement).perform();
break;
}
}
}
private boolean checkIfExpectedWindow(Session session, String identifier, String value) {
boolean result = false;
WebDriverWait wait = new WebDriverWait(session.getDriver(), TIMEOUT_WEBELEMENT);
String title;
switch (identifier) {
case Identifier.IDENTIFIER_URL: {
wait.until(ExpectedConditions.not(ExpectedConditions.urlToBe("about:blank")));
return session.getDriver().getCurrentUrl().equals(value);
}
case Identifier.IDENTIFIER_REGEXTITLE:
wait.until(ExpectedConditions.not(ExpectedConditions.titleIs("")));
title = session.getDriver().getTitle();
Pattern pattern = Pattern.compile(value);
Matcher matcher = pattern.matcher(title);
result = matcher.find();
default:
wait.until(ExpectedConditions.not(ExpectedConditions.titleIs("")));
title = session.getDriver().getTitle();
if (title.equals(value)) {
result = true;
}
}
return result;
}
@Before
public void setUp() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "11.4");
capabilities.setCapability("deviceName", "iPhone 6");
capabilities.setCapability("browserName", "Safari");
driver = new IOSDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
wait = new WebDriverWait(driver, 10);
}
@Inject
public GitPanel(SeleniumWebDriver seleniumWebDriver, ActionsFactory actionsFactory) {
this.seleniumWebDriver = seleniumWebDriver;
this.actionsFactory = actionsFactory;
this.uiWait = new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC);
this.loadWait = new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC);
PageFactory.initElements(seleniumWebDriver, this);
}
@Test
public void testPortraitUpsideDown() {
new WebDriverWait(driver, 20).until(ExpectedConditions
.elementToBeClickable(driver.findElementById("android:id/content")
.findElement(MobileBy.AccessibilityId("Graphics"))));
DeviceRotation landscapeRightRotation = new DeviceRotation(0, 0, 180);
driver.rotate(landscapeRightRotation);
assertEquals(driver.rotation(), landscapeRightRotation);
}
@Inject
public CommandsPalette(
SeleniumWebDriver seleniumWebDriver, Loader loader, ActionsFactory actionsFactory) {
this.seleniumWebDriver = seleniumWebDriver;
this.loader = loader;
this.actionsFactory = actionsFactory;
this.redrawUiElementTimeout =
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC);
this.actions = new Actions(seleniumWebDriver);
PageFactory.initElements(seleniumWebDriver, this);
}
/**
* Verifies that the element is not displayed (i.e. to be visible) on the page within a given amount of time.
* 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 continue the script in the event that the element can't be
* found
*/
@Then("^(?:I verify(?: that)? )?(?:a|an|the) element with "
+ "(?:a|an|the) (ID|class|xpath|name|css selector)( alias)? of \"([^\"]*)\" is not displayed"
+ "(?: within \"(\\d+)\" seconds?)(,? ignoring timeouts?)?")
public void notDisplayWaitStep(
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 {
final boolean result = wait.until(
ExpectedConditions.not(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)));
if (!result) {
throw new TimeoutException(
"Gave up after waiting " + Integer.parseInt(waitDuration)
+ " seconds for the element to not be displayed");
}
} catch (final TimeoutException ex) {
/*
Rethrow if we have not ignored errors
*/
if (StringUtils.isBlank(ignoringTimeout)) {
throw ex;
}
}
}
/**
* wait the project is present in the 'All projects' tab
*
* @param projectName name of project
*/
public void waitProjectIsPresent(String projectName) {
new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC)
.until(
visibilityOfElementLocated(
By.xpath(String.format(Locators.PROJECT_BY_NAME, projectName))));
}
protected Boolean waitForPageToLoad() {
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebDriverWait wait = new WebDriverWait(driver, 10); //give up after 10 seconds
//keep executing the given JS till it returns "true", when page is fully loaded and ready
return wait.until((ExpectedCondition<Boolean>) input -> {
String res = jsExecutor.executeScript("return /loaded|complete/.test(document.readyState);").toString();
return Boolean.parseBoolean(res);
});
}