/** * 通用的元素查找方法 * @param by 具体的查找方法 * @return */ private WebElement findElement(By by) { WebDriver driver = engine.getDriver(); driver = engine.turnToRootDriver(driver); if(element.getTimeOut() > 0) { WebDriverWait wait = new WebDriverWait(driver, element.getTimeOut()); wait.until(ExpectedConditions.visibilityOfElementLocated(by)); } if(parentElement != null) { return parentElement.findElement(by); } else { return driver.findElement(by); } }
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(RecordingSimulatorModule recordingSimulatorModule) { String baseUrl = (String) opts.get(URL); WebDriver driver = recordingSimulatorModule.getWebDriver(); WebDriverWait wait = new WebDriverWait(driver, 10); driver.get(baseUrl + Pages.CLICK_CLASS_BY_TEXT_DEMO_PAGE); Optional<WebElement> webElementOptional = driver.findElements(By.className("item")) .stream() .filter(webElement -> webElement.getText().equals(TARGET)) .findAny(); assertTrue(webElementOptional.isPresent()); webElementOptional.get().click(); wait.until(ExpectedConditions.elementToBeClickable(By.id("success-indicator"))); }
@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); } }
/** * Check JHipsterSampleApp portal page. * * @throws FailureException * if the scenario encounters a functional error. */ @Then("The JHIPSTERSAMPLEAPP portal is displayed") public void checkJHipsterSampleAppPage() throws FailureException { try { Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(jHipsterSampleAppPage.signInMessage))); if (!jHipsterSampleAppPage.isDisplayed()) { logInToJHipsterSampleAppWithNoraRobot(); } if (!jHipsterSampleAppPage.checkPage()) { new Result.Failure<>(jHipsterSampleAppPage.getApplication(), Messages.FAIL_MESSAGE_UNKNOWN_CREDENTIALS, true, jHipsterSampleAppPage.getCallBack()); } } catch (Exception e) { new Result.Failure<>(jHipsterSampleAppPage.getApplication(), Messages.FAIL_MESSAGE_UNKNOWN_CREDENTIALS, true, jHipsterSampleAppPage.getCallBack()); } Auth.setConnected(true); }
/** * Update a html input text with a text. * * @param pageElement * Is target element * @param textOrKey * Is the new data (text or text in context (after a save)) * @param keysToSend * character to send to the element after {@link org.openqa.selenium.WebElement#sendKeys(CharSequence...) sendKeys} with textOrKey * @param args * list of arguments to format the found selector with * @throws TechnicalException * is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. * Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_ERROR_ON_INPUT} message (with screenshot, no exception) * @throws FailureException * if the scenario encounters a functional error */ protected void updateText(PageElement pageElement, String textOrKey, CharSequence keysToSend, Object... args) throws TechnicalException, FailureException { String value = Context.getValue(textOrKey) != null ? Context.getValue(textOrKey) : textOrKey; if (!"".equals(value)) { try { WebElement element = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(pageElement, args))); element.clear(); if (DriverFactory.IE.equals(Context.getBrowser())) { String javascript = "arguments[0].value='" + value + "';"; ((JavascriptExecutor) getDriver()).executeScript(javascript, element); } else { element.sendKeys(value); } if (keysToSend != null) { element.sendKeys(keysToSend); } } catch (Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_ERROR_ON_INPUT), pageElement, pageElement.getPage().getApplication()), true, pageElement.getPage().getCallBack()); } } else { logger.debug("Empty data provided. No need to update text. If you want clear data, you need use: \"I clear text in ...\""); } }
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(); }
/** * Checks a checkbox type element (value corresponding to key "valueKey"). * * @param element * Target page element * @param valueKeyOrKey * is valueKey (valueKey or key in context (after a save)) to match in values map * @param values * Values map * @throws TechnicalException * is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. * Failure with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT} message (with screenshot) * @throws FailureException * if the scenario encounters a functional error */ protected void selectCheckbox(PageElement element, String valueKeyOrKey, Map<String, Boolean> values) throws TechnicalException, FailureException { String valueKey = Context.getValue(valueKeyOrKey) != null ? Context.getValue(valueKeyOrKey) : valueKeyOrKey; try { WebElement webElement = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element))); Boolean checkboxValue = values.get(valueKey); if (checkboxValue == null) { checkboxValue = values.get("Default"); } if (webElement.isSelected() != checkboxValue.booleanValue()) { webElement.click(); } } catch (Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT), element, element.getPage().getApplication()), true, element.getPage().getCallBack()); } }
@Alors("Le portail COUNTRIES est affiché") @Then("The COUNTRIES portal is displayed") public void checkDemoPortalPage() throws FailureException { try { Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(dashboardPage.signInMessage))); if (!dashboardPage.checkPage()) { logInToCountriesWithCountriesRobot(); } if (!dashboardPage.checkPage()) { new Result.Failure<>(dashboardPage.getApplication(), Messages.getMessage(Messages.FAIL_MESSAGE_UNKNOWN_CREDENTIALS), true, dashboardPage.getCallBack()); } } catch (Exception e) { new Result.Failure<>(dashboardPage.getApplication(), Messages.getMessage(Messages.FAIL_MESSAGE_UNKNOWN_CREDENTIALS), true, dashboardPage.getCallBack()); } Auth.setConnected(true); }
@Override public void etrePlein(String type, String selector) { this.logger.info("etrePlein(String id)"); By locator = BySelec.get(type, selector); WebElement elem = wait.until(ExpectedConditions.presenceOfElementLocated(locator)); if (elem.getAttribute("value") != null) { if (elem.getAttribute("value").toString().trim().isEmpty()) { Assert.fail("l'élément ne devrait pas être vide!"); } } else { if (elem.getText().trim().isEmpty()) { Assert.fail("l'élément ne devrait pas être vide!"); } } }
@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()); }
@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(); } }
static public void esperaCargaPaginaNoTexto(WebDriver driver, String texto, int timeout) { Boolean resultado = (new WebDriverWait(driver, timeout)).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(text(),'" + texto + "')]"))); assertTrue(resultado); }
private void clickButtonOnModalDialogOnce(String buttonText) { helper.findElement( By.xpath("//div[contains(@class, 'wicket-modal')]//input[@type='submit' and @value='"+ buttonText +"']")) .click(); helper.waitForElementUntil(ExpectedConditions.invisibilityOfElementLocated( By.xpath("//div[contains(@class, 'wicket-modal')]"))); }
public boolean openContentTab() { getWebDriver().findElement( By.xpath(XpathSelectors.TABBED_PANEL + "//li[contains(@class, 'tab2')]")).click(); return helper.waitForElementUntil( ExpectedConditions.attributeContains( By.xpath(XpathSelectors.TABBED_PANEL + "//li[contains(@class, 'tab2')]"), "class", "selected")); }
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(); }
/** * @category Get Button Label */ private WebElement getButtonByLabel(String buttonLabel) { WebElement button = null; List<WebElement> buttonList = _wait .until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.tagName("button"))); for (int i = 0; i < buttonList.size(); i++) { if (buttonList.get(i).getText().trim().equalsIgnoreCase(buttonLabel)) { button = buttonList.get(i); break; } } return button; }
/** * @category Set Field ID * The fieldID must be the element.TABLENAME.FIELDNAME format */ public void populateFieldByID(String fieldID, String content) { this.focusForm(true); WebElement element = _wait.until(ExpectedConditions.presenceOfElementLocated(By.id(fieldID))); this.typeInElement(element, content); this.focusForm(false); }
@Override public void waitAjaxIsFinished() { if (AJAX_LOADER_ID_IS_DEFINED) { doWait().until(ExpectedConditions.invisibilityOfElementLocated(By .id(AJAX_LOADER_ID))); } }
/** * Types into the search bar in the top right and searches. * * @param content * - The value to type into the search bar. */ public void searchFor(String content) { this.focusForm(false); WebElement mGTypeArea = _wait.until(ExpectedConditions.presenceOfElementLocated(By.name("sysparm_search"))); if (!mGTypeArea.getClass().toString().contains("focus")) { WebElement magnifyingGlass = _wait .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("[action='textsearch.do']"))); magnifyingGlass.click(); } if(!mGTypeArea.getAttribute("value").equalsIgnoreCase("")) { mGTypeArea.clear(); } mGTypeArea.sendKeys(content); mGTypeArea.sendKeys(Keys.ENTER); }
@Test public void testAdminWithAuthAndRole() throws MalformedURLException, InterruptedException { try { indexPage.clickLogin(); loginPage.login("test-admin", "password"); indexPage.clickAdmin(); assertTrue(Graphene.waitGui().until(ExpectedConditions.textToBePresentInElementLocated(By.className("message"), MESSAGE_ADMIN))); indexPage.clickLogout(); } catch (Exception e) { fail("Should display logged in user"); } }
private void waitForBucketEmptyMessage() { WebElement messagePanel = getMessagePanel(); WebDriverWait webDriverWait = new WebDriverWait(this.webDriver, 3); webDriverWait.until(ExpectedConditions.textToBePresentInElement(messagePanel, "No such bucket.")); }
public static Optional<WebElement> elementExists( WebDriver driver, By locator, int timeout ) { int duration = timeout * 100 / 5; WebDriverWait wdw = new WebDriverWait( driver, timeout, duration ); try { WebElement we = wdw.until( ExpectedConditions.presenceOfElementLocated( locator ) ); return Optional.of( we ); } catch( TimeoutException te ) { return Optional.absent(); } }
/** * Check for alert presence. * * @return - true if an alert is present */ public boolean isAlertPresent(){ boolean foundAlert = false; // check for alert presence with no timeout (0 seconds) WebDriverWait wait = new WebDriverWait(driver, 0); try { wait.until(ExpectedConditions.alertIsPresent()); foundAlert = true; } catch (TimeoutException eTO) { foundAlert = false; } return foundAlert; }
public boolean isComponentPresent(String locator, long seconds) { try { WebDriverWait wait = new WebDriverWait(driver, seconds); wait.until(ExpectedConditions.presenceOfElementLocated(determineLocator(locator))); return true; } catch (Exception e) { return false; } }
@Test public void testUserWithAuthAndRole() throws MalformedURLException, InterruptedException { try { indexPage.clickLogin(); loginPage.login("alice", "password"); waitNg2Init(); indexPage.clickSecured(); assertTrue(Graphene.waitGui().until(ExpectedConditions.textToBePresentInElementLocated(By.id("message"), MESSAGE_SECURED))); indexPage.clickLogout(); } catch (Exception e) { debugTest(e); fail("Should display logged in user"); } }
/** * 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); } }
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; } }
public boolean isComponentVisibleWithTime(String locator) { try { WebDriverWait wait = new WebDriverWait(driver, SessionContextManager.getInstance().getWaitForElement()); wait.until(ExpectedConditions.visibilityOfElementLocated(determineLocator(locator))); return true; } catch (TimeoutException e) { return false; } }
@Test public void testPublicResource() { try { indexPage.clickPublic(); assertTrue(Graphene.waitGui().until(ExpectedConditions.textToBePresentInElementLocated(By.className("message"), MESSAGE_PUBLIC))); } catch (Exception e) { fail("Should display an error message"); } }
protected BaseWebObject( final By rootBy ) { this.rootBy = rootBy; this.sync = new EventFiringSynchronization( getWrappedDriver() ); this.rootElement = sync.wait10().until( ExpectedConditions.presenceOfElementLocated( rootBy ) ); // initElements(); }
@Test public void testPublicResource() { try { indexPage.clickPublic(); assertTrue(Graphene.waitGui().until(ExpectedConditions.textToBePresentInElementLocated(By.id("message"), MESSAGE_PUBLIC))); } catch (Exception e) { debugTest(e); fail("Should display an error message"); } }
/** * Checks mandatory text field. * * @param pageElement * Is concerned element * @return true or false * @throws FailureException * if the scenario encounters a functional error */ protected boolean checkMandatoryTextField(PageElement pageElement) throws FailureException { WebElement inputText = null; try { inputText = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement))); } catch (Exception e) { new Result.Failure<>(pageElement, Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack()); } return !(inputText == null || "".equals(inputText.getAttribute(VALUE).trim())); }
protected String readValueTextField(PageElement pageElement) throws FailureException { try { return Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement))).getAttribute(VALUE); } catch (Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack()); } return null; }
@Test public void testWebPageElementSearch() { driver.get("https://www.codeproject.com/"); WebElement target = wait.until(ExpectedConditions.visibilityOf(driver .findElement(By.cssSelector("img[src *= 'post_an_article.png']")))); assertThat(target, notNullValue()); utils.injectScripts(Optional.<String> empty()); // pause_after_script_injection if (pause_after_script_injection) { utils.sleep(timeout_after_script_injection); } utils.highlight(target); // Act utils.inspectElement(target); utils.completeVisualSearch("element name"); // Assert String payload = utils.getPayload(); assertFalse(payload.isEmpty()); System.err.println("Result:\n" + utils.readVisualSearchResult(payload)); Map<String, String> details = new HashMap<>(); utils.readData(payload, Optional.of(details)); verifyNeededKeys(details); // verifyEntry(details, "ElementSelectedBy", nil); verifySelectors(details); if (pause_after_test) { utils.sleep(timeout_after_test); } }
/** * Checks that given value is matching the selected radio list button. * * @param pageElement * The page element * @param value * The value to check the selection from * @return true if the given value is selected, false otherwise. * @throws FailureException * if the scenario encounters a functional error */ protected boolean checkRadioList(PageElement pageElement, String value) throws FailureException { try { List<WebElement> radioButtons = Context.waitUntil(ExpectedConditions.presenceOfAllElementsLocatedBy(Utilities.getLocator(pageElement))); for (WebElement button : radioButtons) { if (button.getAttribute(VALUE).equalsIgnoreCase(value) && button.isSelected()) { return true; } } } catch (Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack()); } return false; }
static public void EsperaCargaPaginaNoTexto(WebDriver driver, String texto, int timeout) { Boolean resultado = (new WebDriverWait(driver, timeout)).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[contains(text(),'" + texto + "')]"))); assertTrue(resultado); }
private void setDropDownValue(PageElement element, String text) throws TechnicalException, FailureException { WebElement select = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(element))); Select dropDown = new Select(select); int index = NameUtilities.findOptionByIgnoreCaseText(text, dropDown); if (index != -1) { dropDown.selectByIndex(index); } else { new Result.Failure<>(text, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_VALUE_NOT_AVAILABLE_IN_THE_LIST), element, element.getPage().getApplication()), false, element.getPage().getCallBack()); } }
@Test public void testSecuredResource() throws InterruptedException { try { indexPage.clickSecured(); assertTrue(Graphene.waitGui().until(ExpectedConditions.textToBePresentInElementLocated(By.className("error"), UNAUTHORIZED))); } catch (Exception e) { debugTest(e); fail("Should display an error message"); } }