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 } }
@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); } }
/** * 根据内容中包含某个子串来等待 * @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); } }
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())); } }
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()); }
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()); }
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(); }
@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()); }
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); } } } }
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; }); }
@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); }
@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(); } }
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); }); }
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; }); }
@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); }
/** * 根据标题中包含某个子串来等待 * @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); } }); }
/** * 根据内容中包含某个子串来等待 * @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); } }); }
public WebDriverAwareElementFinder(final WebDriver webDriver, final WebDriverWait webDriverWait, Integer waitTimeout) { this.driver = webDriver; this.wait = webDriverWait; if (waitTimeout != null) { this.waitTimeout = waitTimeout; } }
@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(); }
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(); }
/** * 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; } }); }
/** * 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(); } }
@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; } }
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")); }
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()); }
private void waitForBucketEmptyMessage() { WebElement messagePanel = getMessagePanel(); WebDriverWait webDriverWait = new WebDriverWait(this.webDriver, 3); webDriverWait.until(ExpectedConditions.textToBePresentInElement(messagePanel, "No such bucket.")); }
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()); } }
@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(); }
@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))); }
@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(); }
/** * 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; } }); }
/** * 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; }
public boolean isAlertPresent() { WebDriverWait wait = new WebDriverWait(driver, 0); try { wait.until(ExpectedConditions.alertIsPresent()); return true; } catch (Exception e) { return false; } }
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; } }
@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")); }
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"))); }
/** * */ 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); } }
/** * 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); } }
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; }