org.openqa.selenium.support.ui.WebDriverWait源码实例Demo

类org.openqa.selenium.support.ui.WebDriverWait源码实例Demo

下面列出了org.openqa.selenium.support.ui.WebDriverWait 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: che   文件: CheTerminal.java
/**
 * 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));
}
 
源代码3 项目: opentest   文件: AssertElementHasClass.java
@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);
    }
}
 
源代码4 项目: marathonv5   文件: JTreeDynamicTreeTest.java
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());
}
 
源代码5 项目: selenium   文件: ImplicitWaitTest.java
@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);
}
 
源代码6 项目: kurento-java   文件: Browser.java
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];
}
 
源代码7 项目: che   文件: CommandsExplorer.java
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();
}
 
源代码8 项目: edx-app-android   文件: NativeAppDriver.java
/**
 * 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;
	}
}
 
源代码9 项目: adf-selenium   文件: AutoSuggestBehavior.java
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;
            }
        }
    });
}
 
源代码10 项目: archiva   文件: AbstractSeleniumTest.java
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;
}
 
源代码11 项目: appiumpro   文件: Edition080_iOS_FaceId.java
@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();
}
 
源代码12 项目: jwala   文件: JwalaUi.java
@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);
    });
}
 
源代码14 项目: che   文件: WorkspaceDetails.java
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();
}
 
源代码15 项目: submarine   文件: AbstractSubmarineIT.java
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")));
}
 
源代码16 项目: che   文件: GitHub.java
/** click on authorize button */
public void clickOnAuthorizeBtn() {
  waitAuthorizeBtn();
  new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC)
      .until(ExpectedConditions.elementToBeClickable(authorizeBtn));
  authorizeBtn.click();
}
 
源代码17 项目: che   文件: Wizard.java
/**
 * 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;
}
 
源代码19 项目: SeleniumCucumber   文件: WaitHelper.java
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;
}
 
源代码20 项目: product-iots   文件: ConnectedCupDeviceViewPage.java
/**
 * 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);
}
 
源代码21 项目: appiumpro   文件: Edition036_NativeWebTap.java
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();
    }
}
 
源代码22 项目: che   文件: FindText.java
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;
    }
  }
}
 
源代码23 项目: cerberus-source   文件: WebDriverService.java
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;
    }
 
源代码24 项目: appiumpro   文件: Edition049_Holidays_2018.java
@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);
}
 
源代码25 项目: che   文件: GitPanel.java
@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);
}
 
源代码26 项目: java-client   文件: UIAutomator2Test.java
@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);
}
 
源代码27 项目: che   文件: CommandsPalette.java
@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;
		}
	}
}
 
源代码29 项目: che   文件: WorkspaceProjects.java
/**
 * 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);
    });
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 类方法
 同包方法