Search in sources :

Example 46 with ExpectedCondition

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

the class ChromePagePerformanceTest method beforeMethod.

@Before
public void beforeMethod() throws IOException {
    driver.get(baseURL);
    // Wait for page url to update
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.pollingEvery(500, TimeUnit.MILLISECONDS);
    ExpectedCondition<Boolean> urlChange = driver -> driver.getCurrentUrl().matches(String.format("^%s.*", baseURL));
    wait.until(urlChange);
    System.err.println("Current  URL: " + driver.getCurrentUrl());
/*
		// Take screenshot
		// under headless Chrome, some vendor pages behave differently e.g.
		// www.royalcaribbean.com redirects to the
		// "Oops... Looks like RoyalCaribbean.com is on vacation" page
		File screenShot = ((TakesScreenshot) driver)
				.getScreenshotAs(OutputType.FILE);
		
		// To get the width of image.
		BufferedImage readImage = ImageIO.read(screenShot);
		int width = readImage.getWidth();
		FileUtils.copyFile(screenShot, new File(System.getProperty("user.dir")
				+ System.getProperty("file.separator") + "test.png"));
		 */
}
Also used : ChromeDriver(org.openqa.selenium.chrome.ChromeDriver) Arrays(java.util.Arrays) SQLiteConnection(org.sqlite.SQLiteConnection) Connection(java.sql.Connection) WebElement(org.openqa.selenium.WebElement) Scanner(java.util.Scanner) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) ChromeOptions(org.openqa.selenium.chrome.ChromeOptions) Matcher(java.util.regex.Matcher) ChromePagePerformanceObject(org.utils.ChromePagePerformanceObject) ResultSet(java.sql.ResultSet) Map(java.util.Map) ImageIO(javax.imageio.ImageIO) Alert(org.openqa.selenium.Alert) Actions(org.openqa.selenium.interactions.Actions) Function(org.sqlite.Function) AfterClass(org.junit.AfterClass) BufferedImage(java.awt.image.BufferedImage) Set(java.util.Set) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) PreparedStatement(java.sql.PreparedStatement) Collectors(java.util.stream.Collectors) List(java.util.List) ById(org.openqa.selenium.By.ById) Stream(java.util.stream.Stream) Pattern(java.util.regex.Pattern) ChromePagePerformanceUtil(org.utils.ChromePagePerformanceUtil) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) BeforeClass(org.junit.BeforeClass) OutputType(org.openqa.selenium.OutputType) WebDriver(org.openqa.selenium.WebDriver) WebDriverException(org.openqa.selenium.WebDriverException) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) HashMap(java.util.HashMap) DatabaseMetaData(java.sql.DatabaseMetaData) ArrayList(java.util.ArrayList) CapabilityType(org.openqa.selenium.remote.CapabilityType) SQLException(java.sql.SQLException) TakesScreenshot(org.openqa.selenium.TakesScreenshot) NoAlertPresentException(org.openqa.selenium.NoAlertPresentException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) Dimension(org.openqa.selenium.Dimension) Iterator(java.util.Iterator) By(org.openqa.selenium.By) FileUtils(org.apache.commons.io.FileUtils) Test(org.junit.Test) IOException(java.io.IOException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Ignore(org.junit.Ignore) Statement(java.sql.Statement) Collections(java.util.Collections) DriverManager(java.sql.DriverManager) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) Before(org.junit.Before)

Example 47 with ExpectedCondition

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

the class PlunkerTest method testFullScreeenInNewWindow.

// Failed tests: afterMethod(com.mycompany.app.PlunkerTest): no such window:
// target window already closed(..)
@Test(enabled = false)
public void testFullScreeenInNewWindow() {
    projectId = "WFJYrM";
    driver.get(String.format("https://plnkr.co/edit/%s/?p=info", projectId));
    WebElement runButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("body > nav button i.icon-play")));
    assertThat(runButton, notNullValue());
    highlight(runButton);
    runButton.click();
    WebElement previewIframe = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("iframe[name='plunkerPreviewTarget']")));
    assertThat(previewIframe, notNullValue());
    WebDriver iframe = driver.switchTo().frame(previewIframe);
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
    }
    // System.err.println(iframe.getPageSource());
    // the fullscreen button is not in the preview frame
    driver.switchTo().defaultContent();
    WebElement fullScreenButton = null;
    try {
        fullScreenButton = wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver d) {
                Optional<WebElement> e = d.findElements(By.cssSelector("button#expand-preview")).stream().filter(o -> {
                    String t = o.getAttribute("title");
                    return (Boolean) (t.contains("Launch the preview in a separate window"));
                }).findFirst();
                return (e.isPresent()) ? e.get() : (WebElement) null;
            }
        });
    } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
    }
    assertThat(fullScreenButton, notNullValue());
    String currentHandle = null;
    try {
        currentHandle = driver.getWindowHandle();
    // System.err.println("Thread: Current Window handle: " + currentHandle);
    } catch (NoSuchWindowException e) {
    }
    // open fullscreen view in a new browser window.
    String openinLinkNewBrowserWindow = Keys.chord(Keys.SHIFT, Keys.RETURN);
    fullScreenButton.sendKeys(openinLinkNewBrowserWindow);
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
    }
    // confirm it opens in a new browser window.
    windowHandles = driver.getWindowHandles();
    assertThat(windowHandles.size(), equalTo(2));
    Iterator<String> windowHandleIterator = windowHandles.iterator();
    while (windowHandleIterator.hasNext()) {
        String handle = windowHandleIterator.next();
        if (!handle.equals(currentHandle)) {
            driver.switchTo().window(handle);
            assertThat(getBaseURL(), equalTo("https://run.plnkr.co"));
            // System.err.println(getBaseURL());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
            driver.close();
            // System.err.println("After close");
            try {
                driver.switchTo().defaultContent();
                System.err.println("After defaultcontext");
            } catch (NoSuchWindowException e) {
            }
        }
    }
}
Also used : WebDriver(org.openqa.selenium.WebDriver) URL(java.net.URL) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) WebDriver(org.openqa.selenium.WebDriver) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement) HashMap(java.util.HashMap) Test(org.testng.annotations.Test) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) Matcher(java.util.regex.Matcher) Map(java.util.Map) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) AfterClass(org.testng.annotations.AfterClass) Iterator(java.util.Iterator) MalformedURLException(java.net.MalformedURLException) Keys(org.openqa.selenium.Keys) ExpectedConditions(org.openqa.selenium.support.ui.ExpectedConditions) By(org.openqa.selenium.By) BeforeClass(org.testng.annotations.BeforeClass) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Optional(java.util.Optional) Assert.assertTrue(org.testng.Assert.assertTrue) Pattern(java.util.regex.Pattern) LogManager(org.apache.logging.log4j.LogManager) NoSuchWindowException(org.openqa.selenium.NoSuchWindowException) NoSuchWindowException(org.openqa.selenium.NoSuchWindowException) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NoSuchWindowException(org.openqa.selenium.NoSuchWindowException) Test(org.testng.annotations.Test)

Example 48 with ExpectedCondition

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

the class SeleniumEasyTest method alertConfirmTest.

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

            Predicate<WebElement> textCheck = _element -> {
                String _text = _element.getText();
                System.err.println("in filter: Text = " + _text);
                return (Boolean) (_text.contains("Click me!"));
            };

            @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 {
        // dismiss alert
        driver.switchTo().alert().dismiss();
    } catch (NoAlertPresentException ex) {
    // Alert not present - ignore
    } catch (WebDriverException ex) {
        System.err.println("Alert was not handled : " + ex.getStackTrace().toString());
        return;
    }
    assertThat(driver.findElement(By.id("confirm-demo")).getText(), is(equalTo("You pressed Cancel!")));
}
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) 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 49 with ExpectedCondition

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

the class SuvianTest method test6_2.

// NOTE: this test is broken
// label follows the check box therefore
// the following-sibling to find the check box by its label does not seem to
// be appropriate
// - see the test6_3 for the solution
// however preceding-sibling always finds the check box #1
@Test(enabled = true)
public void test6_2() {
    // Arrange
    List<String> hobbies = new ArrayList<>(Arrays.asList("Singing", "Dancing", "Sports"));
    driver.get("http://suvian.in/selenium/1.6checkbox.html");
    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();
        }
    });
    assertThat(checkElement, notNullValue());
    // Act
    List<WebElement> elements = checkElement.findElements(By.xpath("..//label[@for]")).stream().filter(_element -> hobbies.contains(_element.getText())).collect(Collectors.toList());
    assertTrue(elements.size() > 0);
    List<WebElement> checkBoxes = elements.stream().map(_element -> _element.findElement(By.xpath("preceding-sibling::input"))).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) WebElement(org.openqa.selenium.WebElement) Test(org.testng.annotations.Test)

Example 50 with ExpectedCondition

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

the class SuvianTest method test6_1.

// Selecting check boxes by their sibling labels
@Test(enabled = true)
public void test6_1() {
    // 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(formElement.findElement(// will throw exception
            By.cssSelector(String.format("input#%s", dataMap.get(hobby)))));
        } 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) Test(org.testng.annotations.Test)

Aggregations

ExpectedCondition (org.openqa.selenium.support.ui.ExpectedCondition)61 WebDriver (org.openqa.selenium.WebDriver)57 WebElement (org.openqa.selenium.WebElement)46 WebDriverWait (org.openqa.selenium.support.ui.WebDriverWait)46 JavascriptExecutor (org.openqa.selenium.JavascriptExecutor)32 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