Java Code Examples for org.openqa.selenium.support.ui.WebDriverWait

The following are top voted examples for showing how to use org.openqa.selenium.support.ui.WebDriverWait. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Cognizant-Intelligent-Test-Scripter   File: AutomationObject.java   View source code 8 votes vote down vote up
private void switchFrame(String frameData) {
    try {
        if (frameData != null && !frameData.trim().isEmpty()) {
            driver.switchTo().defaultContent();
            if (frameData.trim().matches("[0-9]+")) {
                driver.switchTo().frame(Integer.parseInt(frameData.trim()));
            } else {
                WebDriverWait wait = new WebDriverWait(driver,
                        SystemDefaults.waitTime.get());
                wait.until(ExpectedConditions
                        .frameToBeAvailableAndSwitchToIt(frameData));
            }

        }
    } catch (Exception ex) {
        //Error while switching to frame
    }
}
 
Example 2
Project: opentest   File: ClearContent.java   View source code 7 votes vote down vote up
@Override
public void run() {
    super.run();

    By locator = this.readLocatorArgument("locator");

    this.waitForAsyncCallsToFinish();

    try {
        WebElement element = this.getElement(locator);
        WebDriverWait wait = new WebDriverWait(this.driver, this.explicitWaitSec);
        wait.until(ExpectedConditions.elementToBeClickable(element));

        element.clear();
    } catch (Exception ex) {
        throw new RuntimeException(String.format(
                "Failed clicking on element %s",
                locator), ex);
    }
}
 
Example 3
Project: jspider   File: WebDriverEx.java   View source code 6 votes vote down vote up
/**
 * 根据内容中包含某个子串来等待
 * @param content 内容子串
 * @param timeOutInMillis 超时时间毫秒数
 * @param delayedMillis 延迟毫秒数
 */
public void waitWithContentAndDelayed(final String content, int timeOutInMillis, int delayedMillis) {
    (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            String html = d.getPageSource();
            if (StringUtils.isEmpty(content)) {
                //等到有内容就停止
                return StringUtils.isNotBlank(html);
            }
            return html != null && html.contains(content);
        }
    });
    if (delayedMillis > 0) {
        sleep(delayedMillis);
    }
}
 
Example 4
Project: opentest   File: AppiumTestAction.java   View source code 6 votes vote down vote up
protected void swipeAndCheckElementVisible(By locator, String direction) {
    Logger.trace(String.format("AppiumTestAction.swipeAndCheckElementVisible (%s, %s)",
            locator,
            direction));

    if (direction.equalsIgnoreCase("none")) {
        WebDriverWait wait = new WebDriverWait(driver, AppiumHelper.getExplicitWaitSec());
        wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
    } else {
        // TODO: Revisit this and implement a smarter algorithm - not ok to repeat this for an arbitrary number of times
        int maxSwipeCount = Integer.valueOf(AppiumTestAction.config.getString("appium.maxSwipeCount", "50"));

        for (int i = 0; i < maxSwipeCount; i++) {
            try {
                Logger.trace(String.format("AppiumTestAction.swipeAndCheckElementVisible iteration %s", i + 1));
                waitForElementVisible(locator, 1);
                return;
            } catch (Exception ex) {
                swipe(direction);
            }
        }

        throw new RuntimeException(String.format("Element was not visible: %s", locator.toString()));
    }
}
 
Example 5
Project: marathonv5   File: JTreeDynamicTreeTest.java   View source code 6 votes vote down vote up
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());
}
 
Example 6
Project: marathonv5   File: JTreeDynamicTreeTest.java   View source code 6 votes vote down vote up
public void expandTree() throws Throwable {
    WebElement tree = page.getTree();
    tree.click();
    WebElement root = tree.findElement(By.cssSelector(".::nth-node(1)"));
    AssertJUnit.assertEquals("false", root.getAttribute("expanded"));
    AssertJUnit.assertEquals(1 + "", tree.getAttribute("rowCount"));
    new Actions(driver).doubleClick(root).perform();
    new WebDriverWait(driver, 3).until(hasAttributeValue(root, "expanded", "true"));
    AssertJUnit.assertEquals("true", root.getAttribute("expanded"));
    AssertJUnit.assertEquals(3 + "", tree.getAttribute("rowCount"));
    WebElement node1 = tree.findElement(By.cssSelector(".::nth-node(2)"));
    AssertJUnit.assertEquals("Parent 1", node1.getText());
    new Actions(driver).doubleClick(node1).perform();
    WebElement node2 = tree.findElement(By.cssSelector(".::nth-node(3)"));
    AssertJUnit.assertEquals("Child 1", node2.getText());
    WebElement node3 = tree.findElement(By.cssSelector(".::nth-node(4)"));
    AssertJUnit.assertEquals("Child 2", node3.getText());
    WebElement node4 = tree.findElement(By.cssSelector(".::nth-node(5)"));
    AssertJUnit.assertEquals("Parent 2", node4.getText());
    new Actions(driver).doubleClick(node4).perform();
    WebElement node5 = tree.findElement(By.cssSelector(".::nth-node(6)"));
    AssertJUnit.assertEquals("Child 1", node5.getText());
    WebElement node6 = tree.findElement(By.cssSelector(".::nth-node(7)"));
    AssertJUnit.assertEquals("Child 2", node6.getText());
}
 
Example 7
Project: mpay24-java   File: TestRecurringPayments.java   View source code 6 votes vote down vote up
private void doCreditCardPaymentOnPaymentPanel(Payment response) {
	RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation());
	driver.findElement(By.name("selCC|VISA")).click();
	WebDriverWait wait = new WebDriverWait(driver, 20);
	wait.until(ExpectedConditions.elementToBeClickable(By.id("cardnumber")));
	
	driver.findElement(By.id("cardnumber")).sendKeys("4444333322221111");
	driver.findElement(By.id("cvc")).sendKeys("123");
	(new Select(driver.findElement(By.id("expiry-month")))).selectByValue("05");
	(new Select(driver.findElement(By.id("expiry-year")))).selectByValue(getYear());
	driver.findElement(By.name("profile_id")).sendKeys("x");
	
	
	driver.findElement(By.id("right")).click();
	wait.until(ExpectedConditions.elementToBeClickable(By.id("right")));
	driver.findElement(By.id("right")).click();
}
 
Example 8
Project: mpay24-java   File: TestPaymentPanel.java   View source code 6 votes vote down vote up
@Test
public void testShippingAddressWithStreet2() throws PaymentException {
	Payment response = mpay24.paymentPage(getTestPaymentRequest(), getCustomerWithAddress("Coconut 3"));
	assertSuccessfullResponse(response);
	
	RemoteWebDriver driver = openFirefoxAtUrl(response.getRedirectLocation());
	driver.findElement(By.name("selPAYPAL|PAYPAL")).click();
	WebDriverWait wait = new WebDriverWait(driver, 20);
	wait.until(ExpectedConditions.elementToBeClickable(By.name("BillingAddr/Street"))); 
	assertEquals("Testperson-de Approved", driver.findElement(By.name("BillingAddr/Name")).getAttribute("value"));
	assertEquals("Hellersbergstraße 14", driver.findElement(By.name("BillingAddr/Street")).getAttribute("value"));
	assertEquals("Coconut 3", driver.findElement(By.name("BillingAddr/Street2")).getAttribute("value"));
	assertEquals("41460", driver.findElement(By.name("BillingAddr/Zip")).getAttribute("value"));
	assertEquals("Neuss", driver.findElement(By.name("BillingAddr/City")).getAttribute("value"));
	assertEquals("Ankeborg", driver.findElement(By.name("BillingAddr/State")).getAttribute("value"));
	assertEquals("Deutschland", driver.findElement(By.name("BillingAddr/Country/@Code")).findElement(By.xpath("option[@selected='']")).getText());
}
 
Example 9
Project: opentest   File: AppiumTestAction.java   View source code 6 votes vote down vote up
protected void swipeAndCheckElementNotVisible(By locator, String direction) {
    Logger.trace(String.format("AppiumTestAction.swipeAndCheckElementNotVisible (%s, %s)",
            locator,
            direction));

    if (direction.equalsIgnoreCase("none")) {
        WebDriverWait wait = new WebDriverWait(driver, AppiumHelper.getExplicitWaitSec());
        wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
    } else {
        // TODO: Revisit this and implement a smarter algorithm - not ok to repeat this for an arbitrary number of times
        int maxSwipeCount = Integer.valueOf(AppiumTestAction.config.getString("appium.maxSwipeCount", "50"));

        for (int i = 0; i < maxSwipeCount; i++) {
            try {
                Logger.trace(String.format("AppiumTestAction.swipeAndCheckElementVisible iteration %s", i + 1));
                waitForElementVisible(locator, 1);
                throw new RuntimeException(String.format("Element was found to be visible: %s", locator.toString()));
            } catch (Exception ex) {
                swipe(direction);
            }
        }
    }
}
 
Example 10
Project: AutomationFrameworkTPG   File: BasePage.java   View source code 6 votes vote down vote up
protected void waitForElements(BasePage page, final WebElement... elements) {
	new WebDriverWait(getDriverProxy(), 40)
	.withMessage("Timed out navigating to [" + page.getClass().getName() + "]. Expected elements were not found. See screenshot for more details.")
	.until((WebDriver d) -> {
		for (WebElement elm : elements) {
			try {
				elm.isDisplayed();
			} catch (NoSuchElementException e) {
				// This is expected exception since we are waiting for the selenium element to come into existence.
				// This method will be called repeatedly until it reaches timeout or finds all selenium given.
				return false;
			}
		}
		return true;
	});
}
 
Example 11
Project: SWET   File: SwetTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void beforeSuiteMethod() throws Exception {

	// browser selection is hard-coded

	System.err.println("os: " + osName);
	if (osName.startsWith("windows")) {
		driver = BrowserDriver.initialize(browser);
	} else if (osName.startsWith("mac")) {
		driver = BrowserDriver.initialize("safari");
	} else {
		driver = BrowserDriver.initialize("firefox");
	}
	driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
	wait = new WebDriverWait(driver, flexibleWait);
	wait.pollingEvery(pollingInterval, TimeUnit.MILLISECONDS);
	actions = new Actions(driver);
}
 
Example 12
Project: daf-cacher   File: MetabaseSniperPageImpl.java   View source code 6 votes vote down vote up
@Override
public void visit(WebDriver driver, String url) {

    final int implicitWait = Integer.parseInt(properties.getProperty("caching.page_load_wait"));
    driver.manage().timeouts().implicitlyWait(implicitWait, TimeUnit.SECONDS);
    driver.get(url);
    LOGGER.fine("Wait for JS complete");
    (new WebDriverWait(driver, implicitWait)).until((ExpectedCondition<Boolean>) d -> {
        final String status = (String) ((JavascriptExecutor) d).executeScript("return document.readyState");
        return status.equals("complete");
    });
    LOGGER.fine("JS complete");


    LOGGER.fine("Wait for footer");
    (new WebDriverWait(driver, implicitWait))
            .until(
                    ExpectedConditions.visibilityOf(
                            driver.findElement(By.name("downarrow"))));
    LOGGER.info("Footer is there");
    try {
        Thread.sleep(implicitWait * 1000l);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
Example 13
Project: testing_security_development_enterprise_systems   File: PageObject.java   View source code 6 votes vote down vote up
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);
    });
}
 
Example 14
Project: AutomationFrameworkTPG   File: BasePage.java   View source code 6 votes vote down vote up
protected void waitForElements(BasePage page, final By... elements) {
	new WebDriverWait(getDriverProxy(), 40)
	.withMessage("Timed out navigating to [" + page.getClass().getName() + "]. Expected selenium elements were not found. See screenshot for more details.")
	.until((WebDriver d) -> {
		boolean success = true;
		for (By elm : elements) {
			List<WebElement> foundElements = d.findElements(elm);
			if (!foundElements.isEmpty()) {
				try {
					((WebElement) foundElements.get(0)).isDisplayed();
				} catch (NoSuchElementException e) {
					// This is expected exception since we are waiting for the selenium element to come into existence.
					// This method will be called repeatedly until it reaches timeout or finds all selenium given.
					success = false;
					break;
				}
			} else {
				success = false;
				break;
			}
		}
		return success;
	});
}
 
Example 15
Project: QAExercises   File: MatrixBoardTest.java   View source code 5 votes vote down vote up
@BeforeClass//Аннотация Junit. Говорит, что метод должен запускаться каждый раз после создания экземпляра класса, перед всеми тестами
    public static void setUp() {
        //Устанавливаем System Property, чтобы наше приложени смогло найти драйвер
        System.setProperty("webdriver.gecko.driver", "C:\\Program Files\\Java\\geckodriver.exe");
        //Инициализируем драйвер
//        driver = new FirefoxDriver();
        driver = DriverManager.getDriver();
        //Инициализируем Implicit Wait
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //инициализируем Explicit Wait
        wait = new WebDriverWait(driver, 10);
    }
 
Example 16
Project: jspider   File: WebDriverEx.java   View source code 5 votes vote down vote up
/**
 * 根据标题中包含某个子串来等待
 * @param title 标题子串
 * @param timeOutInMillis 超时时间毫秒数
 */
public void waitWithTitle(final String title, int timeOutInMillis) {
    (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            String t = d.getTitle();
            if (StringUtils.isEmpty(title)) {
                //等到有title就停止
                return StringUtils.isNotBlank(t);
            }
            return t != null && t.contains(title);
        }
    });
}
 
Example 17
Project: jspider   File: WebDriverEx.java   View source code 5 votes vote down vote up
/**
 * 根据内容中包含某个子串来等待
 * @param content 内容子串
 * @param timeOutInMillis 超时时间毫秒数
 */
public void waitWithContent(final String content, int timeOutInMillis) {
    (new WebDriverWait(this, timeOutInMillis/1000)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            String html = d.getPageSource();
            if (StringUtils.isEmpty(content)) {
                //等到有内容就停止
                return StringUtils.isNotBlank(html);
            }
            return html != null && html.contains(content);
        }
    });
}
 
Example 18
Project: teasy   File: WebDriverAwareElementFinder.java   View source code 5 votes vote down vote up
public WebDriverAwareElementFinder(final WebDriver webDriver, final WebDriverWait webDriverWait, Integer waitTimeout) {
    this.driver = webDriver;
    this.wait = webDriverWait;
    if (waitTimeout != null) {
        this.waitTimeout = waitTimeout;
    }
}
 
Example 19
Project: appium_tutorial   File: AndroidTest.java   View source code 5 votes vote down vote up
@Test
public void SettingsViewButton() { 
	WebDriverWait wait = new WebDriverWait(driver, 10);
	WebElement menuButton = driver.findElement(By.xpath("//android.widget.ImageButton[@content-desc=\"Open navigation\"]"));
    menuButton.click();
    WebElement settingsViewButton = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@text=\"Settings\"]"))));
    settingsViewButton.click();
}
 
Example 20
Project: FashionSpider   File: WeiboLoginAndGetCookie.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception{
    //配置ChromeDiver
    System.getProperties().setProperty("webdriver.chrome.driver", "chromedriver.exe");
    //开启新WebDriver进程
    WebDriver webDriver = new ChromeDriver();
    //全局隐式等待
    webDriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    //设定网址
    webDriver.get("https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F");
    //显示等待控制对象
    WebDriverWait webDriverWait=new WebDriverWait(webDriver,10);
    //等待输入框可用后输入账号密码
    webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginName"))).sendKeys(args[0]);
    webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginPassword"))).sendKeys(args[1]);
    //点击登录
    webDriver.findElement(By.id("loginAction")).click();
    //等待2秒用于页面加载,保证Cookie响应全部获取。
    sleep(2000);
    //获取Cookie并打印
    Set<Cookie> cookies=webDriver.manage().getCookies();
    Iterator iterator=cookies.iterator();
    while (iterator.hasNext()){
        System.out.println(iterator.next().toString());
    }
    //关闭WebDriver,否则并不自动关闭
    webDriver.close();
}
 
Example 21
Project: bootstrap   File: AbstractSeleniumTest.java   View source code 5 votes vote down vote up
/**
 * Wait for the given element to have the given text
 * 
 * @param by
 *            Element to wait for
 * @param expectedText
 *            Waiting value
 */
protected void assertElementText(final String expectedText, final By by) {
	new WebDriverWait(driver, timeout).until(d -> {
		try {
			return Optional.ofNullable(driver.findElement(by)).map(WebElement::getText).filter(expectedText::equals).isPresent();
		} catch (final StaleElementReferenceException ex) { // NOSONAR - Not yet ready element, try later
			return false;
		}
	});
}
 
Example 22
Project: ServiceNow_Selenium   File: ServiceNow.java   View source code 5 votes vote down vote up
/**
 * Changes focus of the page so that Selenium knows to interact with the
 * navigation area or The Iframe that the form lives inside.
 * 
 * @param bool
 *            True = Focus the Form False = Focus the whole page
 */
private void focusForm(boolean bool) {
	if (_formFocused == bool) {
		return;
	} else {
		_formFocused = bool;
	}
	if (_formFocused) {
		WebDriverWait wait = new WebDriverWait(_driver, 10);
		WebElement form = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("gsft_main")));
		_driver.switchTo().frame(form);
	} else {
		_driver.switchTo().defaultContent();
	}
}
 
Example 23
Project: phoenix.webui.framework   File: AbstractLocator.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected boolean eleWait(WebDriver driver, long timeout, ExpectedCondition<? extends SearchContext> ...isTrueArray)
{
	if(timeout > 0 && isTrueArray != null && isTrueArray.length > 0)
	{
		WebDriverWait wait = new WebDriverWait(driver, timeout);
		for(ExpectedCondition<? extends SearchContext> isTrue : isTrueArray)
		{
			wait.until(isTrue);
		}
		
		return true;
	}
	else
	{
		return false;
	}
}
 
Example 24
Project: marathonv5   File: JTreeDynamicTreeTest.java   View source code 5 votes vote down vote up
public void expandANode() throws Throwable {
    WebElement tree = page.getTree();
    tree.click();
    tree.click();
    WebElement root = tree.findElement(By.cssSelector(".::root"));
    AssertJUnit.assertEquals(1 + "", tree.getAttribute("rowCount"));
    new Actions(driver).doubleClick(root).perform();
    new WebDriverWait(driver, 3).until(hasAttributeValue(tree, "rowCount", 3 + ""));
    AssertJUnit.assertEquals(3 + "", tree.getAttribute("rowCount"));
}
 
Example 25
Project: marathonv5   File: JTreeDynamicTreeTest.java   View source code 5 votes vote down vote up
public void getNodesByRow() throws Throwable {
    WebElement tree = page.getTree();
    tree.click();
    WebElement root = tree.findElement(By.cssSelector(".::nth-node(1)"));
    AssertJUnit.assertEquals(1 + "", tree.getAttribute("rowCount"));
    new Actions(driver).doubleClick(root).perform();
    new WebDriverWait(driver, 3).until(hasAttributeValue(tree, "rowCount", 3 + ""));
    AssertJUnit.assertEquals(3 + "", tree.getAttribute("rowCount"));
    WebElement node1 = tree.findElement(By.cssSelector(".::nth-node(2)"));
    AssertJUnit.assertEquals("Parent 1", node1.getText());
    WebElement node2 = tree.findElement(By.cssSelector(".::nth-node(3)"));
    AssertJUnit.assertEquals("Parent 2", node2.getText());
}
 
Example 26
Project: tmply   File: TmplyPage.java   View source code 5 votes vote down vote up
private void waitForBucketEmptyMessage()
{
	WebElement messagePanel = getMessagePanel();

	WebDriverWait webDriverWait = new WebDriverWait(this.webDriver, 3);
	webDriverWait.until(ExpectedConditions.textToBePresentInElement(messagePanel, "No such bucket."));
}
 
Example 27
Project: SWET   File: Utils.java   View source code 5 votes vote down vote up
public void highlight(WebElement element, long highlight_interval) {
	try {
		new WebDriverWait(driver, flexibleWait)
				.until(ExpectedConditions.visibilityOf(element));
		executeScript("arguments[0].style.border='3px solid yellow'", element);
		Thread.sleep(highlight_interval);
		executeScript("arguments[0].style.border=''", element);
	} catch (InterruptedException e) {
		System.err.println("Exception (ignored): " + e.toString());
	}
}
 
Example 28
Project: appium_tutorial   File: AndroidTest.java   View source code 5 votes vote down vote up
@Test
public void AccountsViewButton() {
	WebDriverWait wait = new WebDriverWait(driver, 10);
	WebElement menuButton = driver.findElement(By.xpath("//android.widget.ImageButton[@content-desc=\"Open navigation\"]"));
    menuButton.click();
    WebElement accountsViewButton = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@text=\"Accounts\"]"))));
    accountsViewButton.click();
}
 
Example 29
Project: bromium   File: RecordNotExposedPageLoadingIT.java   View source code 5 votes vote down vote up
@Override
public void run(RecordingSimulatorModule recordingSimulatorModule) {
    String baseUrl = (String) opts.get(URL);
    WebDriver driver = recordingSimulatorModule.getWebDriver();
    WebDriverWait webDriverWait = new WebDriverWait(driver, 10);
    driver.get(baseUrl + "ajax.html");
    webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.id(AJAX_DEMO_ID)));
}
 
Example 30
Project: appium_tutorial   File: AndroidTest.java   View source code 5 votes vote down vote up
@Test
public void ChartsViewButton() {
	WebDriverWait wait = new WebDriverWait(driver, 10);
	WebElement menuButton = driver.findElement(By.xpath("//android.widget.ImageButton[@content-desc=\"Open navigation\"]"));
    menuButton.click();
    WebElement chartsViewButton = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@text=\"Reports\"]"))));
    chartsViewButton.click();
}
 
Example 31
Project: bootstrap   File: AbstractSeleniumTest.java   View source code 5 votes vote down vote up
/**
 * Wait for the given element to be hidden on screen
 * 
 * @param by
 *            Element to wait for
 */
protected void assertElementHidden(final By by) {
	new WebDriverWait(driver, timeout).until(d -> {
		try {
			return driver.findElements(by).stream().noneMatch(WebElement::isDisplayed);
		} catch (final StaleElementReferenceException ex) { // NOSONAR - Not yet ready element, try later
			return false;
		}
	});
}
 
Example 32
Project: opentest   File: SeleniumTestAction.java   View source code 5 votes vote down vote up
/**
 * Locates and returns a UI element.
 */
protected WebElement getElement(By locator, int timeoutSec) {
    WebDriverWait wait = new WebDriverWait(driver, timeoutSec);
    WebElement element = wait.until(
            ExpectedConditions.presenceOfElementLocated(locator));
    return element;
}
 
Example 33
Project: cucumber-framework-java   File: WebDriverWebController.java   View source code 5 votes vote down vote up
public boolean isAlertPresent() {
    WebDriverWait wait = new WebDriverWait(driver, 0);
    try {
        wait.until(ExpectedConditions.alertIsPresent());
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 34
Project: cucumber-framework-java   File: WebDriverWebController.java   View source code 5 votes vote down vote up
public boolean isComponentVisible(String locator, long seconds) {
    try {
        WebDriverWait wait = new WebDriverWait(driver, seconds);
        wait.until(ExpectedConditions.visibilityOfElementLocated(determineLocator(locator)));
        return true;
    } catch (TimeoutException e) {
        return false;

    }
}
 
Example 35
Project: GitTalent   File: GitTalentIntegrationTest.java   View source code 5 votes vote down vote up
@Test
public void testDeveloperTab() throws InterruptedException {
    RemoteWebDriver driver = chrome.getWebDriver();
    driver.get("http://gittalentbackend:8080/githubimport/developer/ldoguin");
    driver.get("http://gittalentbackend:8080/githubimport/status");
    while(driver.getPageSource().contains("false")) {
        Thread.sleep(1000);
        driver.navigate().refresh();
    };
    driver.get("http://gittalentfrontend/");
    WebElement myDynamicElement = (new WebDriverWait(driver, 20))
                .until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/app-root/div/developers/div[1]/div[2]/div[1]/table/tbody/tr/td[2]")));
    Assert.assertTrue(myDynamicElement.getText().equals("ldoguin"));
}
 
Example 36
Project: cucumber-framework-java   File: WebDriverWebController.java   View source code 5 votes vote down vote up
public void waitForPageToLoad()
{
    JavaScriptHelper js = new JavaScriptHelper();
    ExpectedCondition expectedCondition = new ExpectedCondition<Boolean>(){
        public Boolean apply(WebDriver driver){
            return js.executeScript( "return document.readyState" ).equals( "complete" );
        }
    };

    WebDriverWait wait = new WebDriverWait(driver, SessionContextManager.getWaitForPageToLoad(), THREAD_SLEEP);
    wait.until(expectedCondition);

    wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.tagName("div")));
}
 
Example 37
Project: cucumber-framework-java   File: ControllerBase.java   View source code 5 votes vote down vote up
/**
 *
 */

public WebElement waitForElement(String locator, long waitSeconds) {
    try {
        WebDriverWait wait = new WebDriverWait(driver, waitSeconds, THREAD_SLEEP);
        return wait.until(ExpectedConditions.visibilityOfElementLocated(determineLocator(locator)));

    } catch (TimeoutException e) {
        takeScreenShot();
        throw new TimeoutException("Exception has been thrown", e);
    }
}
 
Example 38
Project: cucumber-framework-java   File: ControllerBase.java   View source code 5 votes vote down vote up
/**
 * waitForElementInvisibility(java.lang.String, long)
 */

public void waitForElementInvisibility(String locator, long waitSeconds) {
    try {
        WebDriverWait wait = new WebDriverWait(driver, waitSeconds);
        wait.until(ExpectedConditions.invisibilityOfElementLocated(determineLocator(locator)));
    } catch (Exception e) {
        takeScreenShot();
        throw new TimeoutException("Exception has been thrown", e);
    }

}
 
Example 39
Project: dashboard1b   File: SeleniumUtils.java   View source code 5 votes vote down vote up
static public List<WebElement> EsperaCargaPaginaxpath(WebDriver driver, String xpath, int timeout) {
	WebElement resultado = (new WebDriverWait(driver, timeout))
			.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
	assertTrue(resultado != null);
	List<WebElement> elementos = driver.findElements(By.xpath(xpath));

	return elementos;
}
 
Example 40
Project: cucumber-framework-java   File: ControllerBase.java   View source code 5 votes vote down vote up
public boolean isAlertPresent() {
    WebDriverWait wait = new WebDriverWait(driver, 0);
    try {
        wait.until(ExpectedConditions.alertIsPresent());
        return true;
    } catch (Exception e) {
        return false;
    }
}