Search in sources :

Example 6 with ExpectedCondition

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

the class SeleniumEasyTest method alertPromptTest.

@Test(enabled = true)
public void alertPromptTest() {
    // wrong selector
    String buttonText = "Click for Prompt Box";
    String buttonSelector = String.format("//*[@id='easycont']//div[@class='panel-heading'][contains(normalize-space(.), '%s')]/..//button[contains(normalize-space(.), '%s')]", "Java Script Alert Box", buttonText);
    try {
        WebElement buttonElement = wait.until(new ExpectedCondition<WebElement>() {

            Predicate<WebElement> textCheck = _element -> {
                String _text = _element.getText();
                System.err.format("in filter: Text: \"%s\" expecting : \"%s\"\n", _text, buttonText);
                return (Boolean) (_text.contains(buttonText));
            };

            @Override
            public WebElement apply(WebDriver d) {
                System.err.println("Locating " + buttonSelector);
                Optional<WebElement> e = d.findElements(By.xpath(buttonSelector)).stream().filter(textCheck).findFirst();
                return (e.isPresent()) ? e.get() : (WebElement) null;
            }
        });
        System.err.println("Acting on: " + buttonElement.getAttribute("outerHTML"));
        highlight(buttonElement);
        flash(buttonElement);
        buttonElement.click();
        sleep(1000);
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
        verificationErrors.append("Exception: " + e.toString());
    }
    try {
        // fill the data in the alert
        Alert alert = driver.switchTo().alert();
        System.err.println("In alert " + alert.toString());
        alert.sendKeys("Harry Potter");
        alert.accept();
    } catch (NoAlertPresentException ex) {
    // Alert not present - ignore
    } catch (WebDriverException ex) {
        System.err.println("Alert was not handled : " + ex.getStackTrace().toString());
        return;
    }
    wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("prompt-demo")));
    assertThat(wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("prompt-demo")))).getText(), is(equalTo("You have entered 'Harry Potter' !")));
}
Also used : WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) CoreMatchers(org.hamcrest.CoreMatchers) ExpectedConditions(org.openqa.selenium.support.ui.ExpectedConditions) Predicate(java.util.function.Predicate) By(org.openqa.selenium.By) WebDriver(org.openqa.selenium.WebDriver) WebDriverException(org.openqa.selenium.WebDriverException) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) BeforeMethod(org.testng.annotations.BeforeMethod) WebElement(org.openqa.selenium.WebElement) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) ITestResult(org.testng.ITestResult) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) Optional(java.util.Optional) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Alert(org.openqa.selenium.Alert) Method(java.lang.reflect.Method) WebDriver(org.openqa.selenium.WebDriver) Optional(java.util.Optional) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) Alert(org.openqa.selenium.Alert) WebElement(org.openqa.selenium.WebElement) WebDriverException(org.openqa.selenium.WebDriverException) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) WebDriverException(org.openqa.selenium.WebDriverException) Test(org.testng.annotations.Test)

Example 7 with ExpectedCondition

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

the class SuvianTest method test10.

@Test(enabled = true)
public void test10() {
    // Arrange
    driver.get("http://suvian.in/selenium/1.10selectElementFromDD.html");
    WebElement buttonDropDown = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector(".container .row .intro-message div.dropdown button.dropbtn"))));
    assertThat(buttonDropDown, notNullValue());
    // Act
    buttonDropDown.click();
    wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector(".container .row .intro-message div.dropdown div#myDropdown"))));
    List<WebElement> optionElements = driver.findElements(By.cssSelector(".container .row .intro-message div.dropdown div#myDropdown")).stream().filter(o -> o.getText().contains("Option 2")).collect(Collectors.toList());
    assertTrue(optionElements.size() > 0);
    final String currentHandle = driver.getWindowHandle();
    final String text = "Congratulations.. You Selected option 2. Close this browser tab and proceed to end of Level 1.";
    optionElements.get(0).click();
    // Assert
    try {
        wait.until(new ExpectedCondition<Boolean>() {

            @Override
            public Boolean apply(WebDriver d) {
                Boolean result = false;
                System.err.println("Inspecting driver Window handles");
                Set<String> windowHandles = d.getWindowHandles();
                if (windowHandles.size() > 1) {
                    System.err.println("Found " + (windowHandles.size() - 1) + " additional tabs opened");
                } else {
                    System.out.println("No other tabs found");
                    return false;
                }
                // String handle = windowHandleIterator.next();
                for (String handle : windowHandles) {
                    if (!handle.equals(currentHandle)) {
                        System.err.println("Switch to: " + handle);
                        driver.switchTo().window(handle);
                        String t = d.getPageSource();
                        System.err.println(String.format("Page source: %s", t.substring(org.apache.commons.lang3.StringUtils.indexOf(t, "<body>"), t.length() - 1)));
                        if (t.contains(text)) {
                            System.err.println("Found text: " + text);
                            result = true;
                        }
                        if (result) {
                            System.err.println("Close the browser tab: " + handle);
                            d.close();
                        }
                        System.err.println("Switch to the main window.");
                        driver.switchTo().window(currentHandle);
                        driver.switchTo().defaultContent();
                    }
                }
                return result;
            }
        });
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
        verificationErrors.append(e.toString());
    // throw new RuntimeException(e.toString());
    }
}
Also used : 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) WebDriver(org.openqa.selenium.WebDriver) Set(java.util.Set) 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) Test(org.testng.annotations.Test)

Example 8 with ExpectedCondition

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

the class SuvianTest method test0_3.

@Test(enabled = true)
public void test0_3() {
    // Arrange
    driver.get("http://suvian.in/selenium/1.1link.html");
    // Wait page to load
    WebElement element = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector(".container .row .intro-message h3 a"))));
    // Act
    element.click();
    // 2. Expected condition with Iterator, uses String methods
    try {
        element = wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver d) {
                Iterator<WebElement> elementsIterator = d.findElements(By.cssSelector("div.container div.row div.intro-message h3")).iterator();
                WebElement result = null;
                while (elementsIterator.hasNext()) {
                    WebElement e = elementsIterator.next();
                    String t = e.getText();
                    System.err.println("in apply iterator (1): Text = " + t);
                    if (t.contains("Navigate Back")) {
                        result = e;
                        break;
                    }
                }
                return result;
            }
        });
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
    }
    // Act
    element.click();
}
Also used : WebDriver(org.openqa.selenium.WebDriver) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) 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) Test(org.testng.annotations.Test)

Example 9 with ExpectedCondition

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

the class SuvianTest method test6_3.

// reverse usage of following-sibling to locate check box by its label
@Test(enabled = true)
public void test6_3() {
    // Arrange
    driver.get("http://suvian.in/selenium/1.6checkbox.html");
    List<String> hobbies = new ArrayList<>(Arrays.asList("Singing", "Dancing", "Sports"));
    WebElement checkElement = null;
    try {
        checkElement = wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver d) {
                return d.findElements(By.cssSelector("div.container div.row div.intro-message h3")).stream().filter(o -> o.getText().toLowerCase().indexOf("select your hobbies") > -1).findFirst().get();
            }
        });
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
    }
    assertThat(checkElement, notNullValue());
    // Act
    List<WebElement> checkBoxes = checkElement.findElements(By.xpath("..//input[@type = 'checkbox']")).stream().filter(o -> {
        WebElement label = o.findElement(By.xpath("following-sibling::label"));
        if (hobbies.contains(label.getText())) {
            System.err.println(String.format("checkbox element %s: '%s'", o.getAttribute("id"), label.getText()));
            return true;
        } else {
            return false;
        }
    }).collect(Collectors.toList());
    assertTrue(checkBoxes.size() > 0);
    checkBoxes.stream().forEach(o -> {
        highlight(o);
        sleep(100);
        o.click();
    });
    // Assert
    assertTrue(driver.findElements(By.cssSelector(".container .intro-message input[type='checkbox']")).stream().filter(o -> o.isSelected()).count() == hobbies.size());
}
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) ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) 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) Test(org.testng.annotations.Test)

Example 10 with ExpectedCondition

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

the class SuvianTest method test6_4.

// Selecting check boxes by their sibling labels, ByChained
@Test(enabled = true)
public void test6_4() {
    // Arrange
    List<String> hobbies = new ArrayList<>(Arrays.asList("Singing", "Dancing"));
    driver.get("http://suvian.in/selenium/1.6checkbox.html");
    try {
        WebElement checkElement = wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver _driver) {
                return _driver.findElements(By.cssSelector("div.container div.row div.intro-message h3")).stream().filter(_element -> _element.getText().toLowerCase().indexOf("select your hobbies") > -1).findFirst().get();
            }
        });
        System.err.println("element check: " + checkElement.getAttribute("innerHTML"));
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
    }
    // Act
    WebElement formElement = driver.findElement(By.cssSelector("input[id]")).findElement(By.xpath(".."));
    assertThat(formElement, notNullValue());
    highlight(formElement, 1000);
    List<WebElement> inputElements = formElement.findElements(By.cssSelector("label[for]")).stream().filter(_element -> hobbies.contains(_element.getText())).collect(Collectors.toList());
    // C#: dataMap = elements.ToDictionary(x => x.GetAttribute("for"), x =>
    // x.Text);
    Map<String, String> dataMap = inputElements.stream().map(_element -> {
        System.err.println("input element id: " + _element);
        System.err.println("input element text: " + _element.getText());
        System.err.println("input element 'for' attribute: " + _element.getAttribute("for"));
        System.err.println("input element HTML: " + _element.getAttribute("outerHTML"));
        System.err.println("input element XPath: " + xpathOfElement(_element));
        System.err.println("input element CSS: " + cssSelectorOfElement(_element));
        return _element;
    }).collect(Collectors.toMap(_element -> _element.getText(), _element -> _element.getAttribute("for")));
    List<WebElement> checkboxes = new ArrayList<>();
    for (String hobby : hobbies) {
        try {
            System.err.println("finding: " + dataMap.get(hobby));
            checkboxes.add(driver.findElements(new ByChained(By.cssSelector("input[id]"), By.xpath(".."), By.cssSelector(String.format("input#%s", dataMap.get(hobby))))).get(0));
        } catch (InvalidSelectorException e) {
            System.err.println("ignored: " + e.toString());
        }
        try {
            checkboxes.add(formElement.findElement(// will not throw exception
            By.xpath(String.format("input[@id='%s']", dataMap.get(hobby)))));
        } catch (Exception e) {
            System.err.println("ignored: " + e.toString());
        }
    }
    Consumer<WebElement> act = _element -> {
        highlight(_element);
        _element.click();
    };
    checkboxes.stream().forEach(act);
    // Assert
    assertTrue(formElement.findElements(By.cssSelector("input[type='checkbox']")).stream().filter(o -> o.isSelected()).count() == hobbies.size());
}
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) InvalidSelectorException(org.openqa.selenium.InvalidSelectorException) ArrayList(java.util.ArrayList) 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) ByChained(org.openqa.selenium.support.pagefactory.ByChained) Test(org.testng.annotations.Test)

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