Search in sources :

Example 11 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project selenium_java by sergueik.

the class SuvianTest method test0_1.

// Firebug console validation:
// $x("<xpath>")
// $$("<cssSelector>")
@Test(enabled = true)
public void test0_1() {
    // Arrange
    driver.get("http://suvian.in/selenium/1.1link.html");
    // Wait page to load
    wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector(".container .row .intro-message h3 a"))));
    List<WebElement> elements = driver.findElements(By.xpath("//div[1]/div/div/div/div/h3[2]/a"));
    // assertTrue(elements.size() > 0);
    // http://grepcode.com/file/repo1.maven.org/maven2/org.testng/testng/6.8/org/testng/asserts/SoftAssert.java
    SoftAssert softAssert = new SoftAssert();
    softAssert.assertTrue(elements.size() > 0);
    // System.out.println("softAssert Method Was Executed");
    softAssert.assertAll();
    // Act
    WebElement element = elements.get(0);
    highlight(element);
    assertTrue(element.getText().equalsIgnoreCase("Click Here"), element.getText());
    element.click();
    // Wait page to load
    try {
        wait.until(ExpectedConditions.urlContains("1.1link_validate.html"));
    } catch (UnreachableBrowserException e) {
    }
    // 1. Expected Condition uses enclosing element
    try {
        wait.until(new ExpectedCondition<Boolean>() {

            @Override
            public Boolean apply(WebDriver d) {
                String t = d.findElement(By.className("intro-message")).getText();
                Boolean result = t.contains("Link Successfully clicked");
                System.err.println("in apply: Text = " + t + "\nresult = " + result.toString());
                return result;
            }
        });
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
    }
    // 3. Alternative wait, functional style, with Optional <WebElement>
    // http://www.nurkiewicz.com/2013/08/optional-in-java-8-cheat-sheet.html
    // and capture-loaded Predicate
    Predicate<WebElement> textCheck = _element -> {
        String _text = _element.getText();
        System.err.println("in stream filter (3): Text = " + _text);
        return (Boolean) (_text.contains("Navigate Back"));
    };
    try {
        WebElement checkElement = wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver d) {
                Optional<WebElement> e = d.findElements(By.cssSelector("div.container div.row div.intro-message h3")).stream().filter(textCheck).findFirst();
                return (e.isPresent()) ? e.get() : (WebElement) null;
            }
        });
        System.err.println("element check: " + checkElement.getAttribute("innerHTML"));
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
    }
    // http://stackoverflow.com/questions/12858972/how-can-i-ask-the-selenium-webdriver-to-wait-for-few-seconds-in-java
    // http://stackoverflow.com/questions/31102351/selenium-java-lambda-implementation-for-explicit-waits
    Predicate<WebElement> textCheck2 = _element -> {
        String _text = _element.getText();
        System.err.println("(in filter) Text: " + _text);
        return (Boolean) (_text.equalsIgnoreCase("Link Successfully clicked"));
    };
    elements = driver.findElements(By.cssSelector(".container .row .intro-message h3"));
    // longer version
    Stream<WebElement> elementsStream = elements.stream();
    elements = elementsStream.filter(textCheck2).collect(Collectors.toList());
    // shorter version
    elements = driver.findElements(By.cssSelector(".container .row .intro-message h3")).stream().filter(_element -> "Link Successfully clicked".equalsIgnoreCase(_element.getText())).collect(Collectors.toList());
    assertThat(elements.size(), equalTo(1));
    elements = driver.findElements(By.cssSelector(".container .row .intro-message h3")).stream().filter(_element -> _element.getText().equalsIgnoreCase("Link Successfully clicked")).collect(Collectors.toList());
    assertThat(elements.size(), equalTo(1));
    element = elements.get(0);
    highlight(element);
    assertTrue(element.getText().equalsIgnoreCase("Link Successfully clicked"), element.getText());
}
Also used : WebDriver(org.openqa.selenium.WebDriver) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) Enumeration(java.util.Enumeration) WebElement(org.openqa.selenium.WebElement) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) StringUtils(org.apache.commons.lang3.StringUtils) Locatable(org.openqa.selenium.internal.Locatable) Coordinates(org.openqa.selenium.interactions.internal.Coordinates) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) Matcher(java.util.regex.Matcher) Point(org.openqa.selenium.Point) Map(java.util.Map) Method(java.lang.reflect.Method) HasInputDevices(org.openqa.selenium.interactions.HasInputDevices) FindBy(org.openqa.selenium.support.FindBy) SoftAssert(org.testng.asserts.SoftAssert) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ExpectedConditions(org.openqa.selenium.support.ui.ExpectedConditions) Predicate(java.util.function.Predicate) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) Mouse(org.openqa.selenium.interactions.Mouse) Collectors(java.util.stream.Collectors) FindBys(org.openqa.selenium.support.FindBys) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) WebDriver(org.openqa.selenium.WebDriver) WebDriverException(org.openqa.selenium.WebDriverException) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) InvalidSelectorException(org.openqa.selenium.InvalidSelectorException) ITestResult(org.testng.ITestResult) ArrayList(java.util.ArrayList) Select(org.openqa.selenium.support.ui.Select) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LinkedList(java.util.LinkedList) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) ByChained(org.openqa.selenium.support.pagefactory.ByChained) Iterator(java.util.Iterator) Keys(org.openqa.selenium.Keys) By(org.openqa.selenium.By) Consumer(java.util.function.Consumer) Assert.assertTrue(org.testng.Assert.assertTrue) Comparator(java.util.Comparator) Collections(java.util.Collections) Optional(java.util.Optional) SoftAssert(org.testng.asserts.SoftAssert) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) WebElement(org.openqa.selenium.WebElement) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) WebDriverException(org.openqa.selenium.WebDriverException) InvalidSelectorException(org.openqa.selenium.InvalidSelectorException) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) Test(org.testng.annotations.Test)

Example 12 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project selenium_java by sergueik.

the class GmailTest method loginAfterTest.

@Test(priority = 3, enabled = false)
public void loginAfterTest() throws InterruptedException, IOException {
    // Click on Sign in Link
    System.err.println("Click on Sign in Link");
    driver.findElement(signInLink).click();
    // Wait for page url to change
    System.err.println("Wait for page url to change");
    ExpectedCondition<Boolean> urlChange = driver -> driver.getCurrentUrl().matches("^https://accounts.google.com/signin.*");
    wait.until(urlChange);
    // Enter the email id
    System.err.println("Enter the email id");
    enterData(identifier, "automationnewuser24@gmail.com");
    // Click on next button
    System.err.println("Click on next button");
    clickNextButton(identifierNextButton);
    // Enter the password
    System.err.println("Enter the password");
    enterData(passwordInput, "automationnewuser2410");
    // Click on next button
    System.err.println("Click on next button");
    clickNextButton(passwordNextButton);
    // Wait for page url to change
    urlChange = driver -> {
        String url = driver.getCurrentUrl();
        System.err.println("The url is: " + url);
        return (Boolean) url.matches("^https://mail.google.com/mail.*");
    };
    wait.until(urlChange);
    // Click on profile image
    System.err.println("Click on profile image");
    wait.until((WebDriver driver) -> {
        WebElement element = null;
        try {
            element = driver.findElement(profileImage);
        } catch (Exception e) {
            return null;
        }
        return (element.isDisplayed()) ? element : null;
    }).click();
    // Sign out
    System.err.println("Sign out");
    highlight(driver.findElement(signOutButton), 100);
    driver.findElement(signOutButton).click();
    try {
        alert = driver.switchTo().alert();
        alert.accept();
    } catch (NoAlertPresentException ex) {
        // Alert not present
        System.err.println("NoAlertPresentException: " + ex.getStackTrace());
    } catch (WebDriverException ex) {
        System.err.println("Alert was not handled by PhantomJS: " + ex.getStackTrace().toString());
    }
    // Wait for page url to change
    System.err.println("Wait for page url to change");
    urlChange = driver -> driver.getCurrentUrl().matches("^https://accounts.google.com/signin.*");
    wait.until(urlChange);
    // Click on Choose user Link
    sleep(100);
    /*
		List<WebElement> x = driver.findElements(By.cssSelector("svg"));
		for (WebElement y : x) {      
		  System.err.println(y.getAttribute("outerHTML"));
		}
		*/
    System.err.println("Click on users list link");
    WebElement svgSelector = // svg")).findElement(By.xpath(".."));
    driver.findElements(By.cssSelector("div[role='button'] svg[width='24px']")).get(0).findElement(By.xpath(".."));
    // System.err.println(svgSelector.findElement(By.xpath("..")).findElement(By.xpath("..")).findElement(By.xpath("..")).findElement(By.xpath("..")).findElement(By.xpath("..")).findElement(By.xpath("..")).getAttribute("outerHTML"));
    /*
		<?xml version="1.0"?>
		<div>
		<h1 class="sfYUmb" data-a11y-title-piece="" id="headingText" jsname="z6sL2b">Hi auto</h1>
		<div class="FgbZLd r5i3od">
		<img jsname="XpilHb" alt="" src="https://lh3.googleusercontent.com/-wFVXorRrucg/AAAAAAAAAAI/AAAAAAAAAAA/AMp5VUqt1um4XARGfeTINdbjBR3yAa_CpQ/mo/photo.jpg?sz=64" class="iarmfc"/>
		<div id="profileIdentifier" class="RRP0oc ilEhd" data-a11y-title-piece="">automationnewuser24@gmail.com</div>
		<div jscontroller="hgUmTc" jsaction="JIbuQc:BV9TTc(af8ijd)">
		  <div role="button" class="mUbCce fKz7Od YYBxpf KEavsb" jscontroller="VXdfxd" jsaction="click:cOuCgd; mousedown:UX7yZ; mouseup:lbsD7e; mouseenter:tfO1Yc; mouseleave:JywGue;touchstart:p6p2H; touchmove:FwuNnf; touchend:yfqBxc(preventMouseEvents=true|preventDefault=true); touchcancel:JMtRjd;focus:AHmuwe; blur:O22p3e; contextmenu:mg9Pef;" jsshadow="" jsname="af8ijd" aria-label="Switch account" aria-disabled="false" tabindex="0">
		    <div class="VTBa7b MbhUzd" jsname="ksKsZd"/>
		    <content class="xjKiLb">
		      <span style="top: -12px">
		        <span>
		          <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" width="24px" height="24px" viewBox="0 0 24 24" fill="#000000">
		            <path d="M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z"/>
		            <path d="M0-.75h24v24H0z" fill="none"/>
		          </svg>
		        </span>
		      </span>
		    </content>
		  </div>
		</div>
		</div>
		</div>
		
		*/
    highlight(svgSelector, 100);
    svgSelector.click();
    // Wait for page url to change
    System.err.println("Wait for page url to change");
    urlChange = driver -> driver.getCurrentUrl().matches("^https://accounts.google.com/ServiceLogin/signinchooser.*");
    wait.until(urlChange);
    // TODO: examine cookies
    sleep(1000);
}
Also used : By(org.openqa.selenium.By) WebDriver(org.openqa.selenium.WebDriver) WebDriverException(org.openqa.selenium.WebDriverException) BeforeClass(org.testng.annotations.BeforeClass) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) BeforeMethod(org.testng.annotations.BeforeMethod) WebElement(org.openqa.selenium.WebElement) IOException(java.io.IOException) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) ArrayList(java.util.ArrayList) List(java.util.List) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) Assert.assertTrue(org.testng.Assert.assertTrue) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) WebDriver(org.openqa.selenium.WebDriver) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) WebElement(org.openqa.selenium.WebElement) WebDriverException(org.openqa.selenium.WebDriverException) IOException(java.io.IOException) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) WebDriverException(org.openqa.selenium.WebDriverException) Test(org.testng.annotations.Test)

Example 13 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project scout.rt by eclipse.

the class SeleniumExpectedConditions method tableToHaveNumberOfRows.

/**
 * @param parentElement
 *          if not null, findElement below the given parent, if null, findElements in document
 * @param rowText
 *          text of element table-row, compared with 'contains'
 * @param numRows
 * @return The table-rows found by the expected condition
 */
public static ExpectedCondition<List<WebElement>> tableToHaveNumberOfRows(final WebElement parentElement, final String rowText, final int numRows) {
    return new ExpectedCondition<List<WebElement>>() {

        @Override
        public List<WebElement> apply(WebDriver driver) {
            try {
                By by = By.className("table-row");
                List<WebElement> tableRows = parentElement != null ? parentElement.findElements(by) : driver.findElements(by);
                // we must have exactly the requested count of rows (too many rows is as bad as too few rows)
                if (numRows != tableRows.size()) {
                    return null;
                }
                // and each one of these rows must contain the given text
                for (WebElement tableRow : tableRows) {
                    if (!tableRow.getText().contains(rowText)) {
                        return null;
                    }
                }
                return tableRows;
            } catch (StaleElementReferenceException e) {
            // NOSONAR
            // NOP
            }
            return null;
        }

        @Override
        public String toString() {
            return String.format("table should have %d rows with text '%s'", numRows, rowText);
        }
    };
}
Also used : WebDriver(org.openqa.selenium.WebDriver) By(org.openqa.selenium.By) StaleElementReferenceException(org.openqa.selenium.StaleElementReferenceException) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement)

Example 14 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project thewaiter by iamalittletester.

the class Waiter method waitForElementTextContainsString.

/**
 * Method that waits for the text on the element to contain an expected String.
 * Checks whether the value resulted from getText() on the element contains the expected String.
 * Will wait for up to the specifiedTimeout number of seconds for the text on the element to contain the expected one.
 *
 * @param element          - the WebElement whose text will be checked
 * @param expectedString   - the value expected to be contained in the WebElement's text
 * @param driver           - the WebDriver instance
 * @param specifiedTimeout - amount of seconds you want to wait for
 */
public void waitForElementTextContainsString(WebElement element, String expectedString, WebDriver driver, int specifiedTimeout) {
    WebDriverWait wait = new WebDriverWait(driver, specifiedTimeout);
    ExpectedCondition<Boolean> elementTextContainsString = arg0 -> element.getText().contains(expectedString);
    wait.until(elementTextContainsString);
}
Also used : WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) Wait(org.openqa.selenium.support.ui.Wait) WebDriver(org.openqa.selenium.WebDriver) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait)

Example 15 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project thewaiter by iamalittletester.

the class Waiter method waitForElementAttributeEqualsString.

/**
 * Method that waits for an element's specified attribute's value to equal another specified String.
 * Compares the value resulted from getAttribute(nameOfAttribute) on the element with the expected String.
 * Will wait for up to the specified number of seconds for an element's attribute value to equal an expected String.
 *
 * @param element          - the WebElement whose attribute we are interested in
 * @param attribute        - the attribute whose value needs to be compared to another value
 * @param expectedString   - the expected value of the WebElement's attribute
 * @param driver           - the WebDriver instance
 * @param specifiedTimeout - amount of seconds you want to wait for
 */
public void waitForElementAttributeEqualsString(WebElement element, String attribute, String expectedString, WebDriver driver, int specifiedTimeout) {
    WebDriverWait wait = new WebDriverWait(driver, specifiedTimeout);
    ExpectedCondition<Boolean> elementAttributeEqualsString = arg0 -> element.getAttribute(attribute).equals(expectedString);
    wait.until(elementAttributeEqualsString);
}
Also used : WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) Wait(org.openqa.selenium.support.ui.Wait) WebDriver(org.openqa.selenium.WebDriver) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait)

Aggregations

ExpectedCondition (org.openqa.selenium.support.ui.ExpectedCondition)57 WebDriver (org.openqa.selenium.WebDriver)54 WebElement (org.openqa.selenium.WebElement)45 WebDriverWait (org.openqa.selenium.support.ui.WebDriverWait)44 JavascriptExecutor (org.openqa.selenium.JavascriptExecutor)31 By (org.openqa.selenium.By)19 Wait (org.openqa.selenium.support.ui.Wait)19 CoreMatchers.notNullValue (org.hamcrest.CoreMatchers.notNullValue)16 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)16 List (java.util.List)15 WebDriverException (org.openqa.selenium.WebDriverException)15 Test (org.testng.annotations.Test)15 NoAlertPresentException (org.openqa.selenium.NoAlertPresentException)14 BeforeMethod (org.testng.annotations.BeforeMethod)14 Map (java.util.Map)13 ExpectedConditions (org.openqa.selenium.support.ui.ExpectedConditions)12 AfterMethod (org.testng.annotations.AfterMethod)12 ArrayList (java.util.ArrayList)11 Iterator (java.util.Iterator)11 Optional (java.util.Optional)11