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

The following are top voted examples for showing how to use org.openqa.selenium.support.ui.ExpectedConditions. 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   Source Code and License 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: phoenix.webui.framework   File: PrioritySearchStrategy.java   Source Code and License 7 votes vote down vote up
/**
 * 通用的元素查找方法
 * @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);
	}
}
 
Example 3
Project: bromium   File: RecordClickClassByTextIT.java   Source Code and License 7 votes vote down vote up
@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")));
}
 
Example 4
Project: opentest   File: ClearContent.java   Source Code and License 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 5
Project: noraui-academy   File: JHipsterSampleAppSteps.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 6
Project: ServiceNow_Selenium   File: ServiceNow.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 7
Project: NoraUi   File: Step.java   Source Code and License 6 votes vote down vote up
/**
 * 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 ...\"");
    }
}
 
Example 8
Project: mpay24-java   File: TestRecurringPayments.java   Source Code and License 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 9
Project: NoraUi   File: Step.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 10
Project: NoraUi   File: CountriesSteps.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 11
Project: saladium   File: SaladiumDriver.java   Source Code and License 6 votes vote down vote up
@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!");
        }
    }
}
 
Example 12
Project: mpay24-java   File: TestPaymentPanel.java   Source Code and License 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 13
Project: daf-cacher   File: MetabaseSniperPageImpl.java   Source Code and License 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 14
Project: dashboard1b   File: SeleniumUtils.java   Source Code and License 5 votes vote down vote up
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);	
}
 
Example 15
Project: hippo   File: ContentPage.java   Source Code and License 5 votes vote down vote up
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')]")));

}
 
Example 16
Project: hippo   File: ContentPage.java   Source Code and License 5 votes vote down vote up
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"));
}
 
Example 17
Project: FashionSpider   File: WeiboLoginAndGetCookie.java   Source Code and License 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 18
Project: ServiceNow_Selenium   File: ServiceNow.java   Source Code and License 5 votes vote down vote up
/**
 * @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;
	
}
 
Example 19
Project: ServiceNow_Selenium   File: ServiceNow.java   Source Code and License 5 votes vote down vote up
/**
 * @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);
}
 
Example 20
Project: satisfy   File: BaseWebPage.java   Source Code and License 5 votes vote down vote up
@Override
public void waitAjaxIsFinished() {
    if (AJAX_LOADER_ID_IS_DEFINED) {
        doWait().until(ExpectedConditions.invisibilityOfElementLocated(By
                .id(AJAX_LOADER_ID)));
    }
}
 
Example 21
Project: keycloak_training   File: ArquillianJeeJspTest.java   Source Code and License 5 votes vote down vote up
@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");
    }
}
 
Example 22
Project: tmply   File: TmplyPage.java   Source Code and License 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 23
Project: cucumber-framework-java   File: WebDriverUtils.java   Source Code and License 5 votes vote down vote up
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();
    }
}
 
Example 24
Project: mobileAutomation   File: TestCase.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: cucumber-framework-java   File: WebDriverWebController.java   Source Code and License 5 votes vote down vote up
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;

    }
}
 
Example 26
Project: keycloak_training   File: ArquillianAngular2Test.java   Source Code and License 5 votes vote down vote up
@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");
    }
}
 
Example 27
Project: cucumber-framework-java   File: ControllerBase.java   Source Code and License 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 28
Project: cucumber-framework-java   File: ControllerBase.java   Source Code and License 5 votes vote down vote up
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;

    }
}
 
Example 29
Project: cucumber-framework-java   File: ControllerBase.java   Source Code and License 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 30
Project: cucumber-framework-java   File: ControllerBase.java   Source Code and License 5 votes vote down vote up
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;

    }
}
 
Example 31
Project: keycloak_training   File: ArquillianJeeHtml5Test.java   Source Code and License 5 votes vote down vote up
@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");
    }
}
 
Example 32
Project: cucumber-framework-java   File: BaseWebObject.java   Source Code and License 5 votes vote down vote up
protected BaseWebObject( final By rootBy )
    {
        this.rootBy = rootBy;
        this.sync = new EventFiringSynchronization( getWrappedDriver() );
        this.rootElement = sync.wait10().until( ExpectedConditions.presenceOfElementLocated( rootBy ) );
//        initElements();

    }
 
Example 33
Project: keycloak_training   File: ArquillianAngular2Test.java   Source Code and License 5 votes vote down vote up
@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");
    }
}
 
Example 34
Project: NoraUi   File: Step.java   Source Code and License 5 votes vote down vote up
/**
 * 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()));
}
 
Example 35
Project: NoraUi   File: Step.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: SWET   File: SwetTest.java   Source Code and License 5 votes vote down vote up
@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);
	}
}
 
Example 37
Project: NoraUi   File: Step.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 38
Project: participationSystem3b   File: SeleniumUtils.java   Source Code and License 5 votes vote down vote up
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);	
}
 
Example 39
Project: NoraUi   File: Step.java   Source Code and License 5 votes vote down vote up
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());
    }

}
 
Example 40
Project: twitter-stuff   File: StatusUtils.java   Source Code and License 5 votes vote down vote up
public static void takeStatusScreenshot(Status status, MongoDatabase mongoDatabase, WebDriver driver) {
    long id = status.getId();
    User user = status.getUser();
    try {
        // visit the twitter url
        driver.get(TWITTER_BASE_URL + user.getScreenName() + "/status/" + id);

        WebDriverWait webDriverWait = new WebDriverWait(driver, 4);
        webDriverWait.until(
                ExpectedConditions.visibilityOfElementLocated(
                        By.cssSelector(PERMALINK_TWEET_CONTAINER)));

        // Find the tweet container
        WebElement element = driver.findElement(By.cssSelector(PERMALINK_TWEET_CONTAINER));

        // take a full screenshot
        File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // create in memory image data
        BufferedImage screenshotImage = ImageIO.read(screenshotFile);

        // calculate the position of the tweet element
        Point point = element.getLocation();
        int elementWidth = element.getSize().getWidth();
        int elementHeight = element.getSize().getHeight();

        // crop to get only the container of the tweet itself (sometimes this doesn't work on mac)
        BufferedImage elementScreenshotImage =
                screenshotImage.getSubimage(
                        point.getX() + 4,
                        point.getY() + 4,
                        elementWidth - 4,
                        screenshotImage.getHeight() < point.getY() + elementHeight
                                ? screenshotImage.getHeight() - 4
                                : elementHeight - 4);
        ImageIO.write(elementScreenshotImage, "png", screenshotFile);
        FileUtils.copyFile(screenshotFile, new File("screenshot/" + id + ".png"));
    } catch (Exception e) {
        saveFailureStatusProcesssed(mongoDatabase, id, false);
        System.out.println(
                String.format(
                        "Unable to create screenshot for %s with id: %d",
                        user.getScreenName(),
                        id));
        e.printStackTrace();
    }
}