Search in sources :

Example 41 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project devonfw-testing by devonfw.

the class DriverExtention method waitForElement.

public WebElement waitForElement(final By by) throws BFElementNotFoundException {
    BasePage.getAnalytics().sendMethodEvent(BasePage.analitycsCategoryName);
    long startTime = System.currentTimeMillis();
    WebElement element = null;
    try {
        element = webDriverWait().until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver driver) {
                return driver.findElement(by);
            }
        });
    } catch (TimeoutException | NoSuchElementException e) {
        boolean isTimeout = true;
        throw new BFElementNotFoundException(by, isTimeout, BasePage.EXPLICITYWAITTIMER);
    }
    BFLogger.logTime(startTime, "waitForElement()", by.toString());
    return element;
}
Also used : WebDriver(org.openqa.selenium.WebDriver) BFElementNotFoundException(com.capgemini.ntc.selenium.core.exceptions.BFElementNotFoundException) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement) NoSuchElementException(org.openqa.selenium.NoSuchElementException) TimeoutException(org.openqa.selenium.TimeoutException)

Example 42 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project devonfw-testing by devonfw.

the class DriverExtention method waitForPageLoaded.

public void waitForPageLoaded() throws BFElementNotFoundException {
    long startTime = System.currentTimeMillis();
    final String jsVariable = "return document.readyState";
    ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {

        public Boolean apply(WebDriver driver) {
            return ((JavascriptExecutor) driver).executeScript(jsVariable).equals("complete");
        }
    };
    int progressBarWaitTimer = BasePage.PROGRESSBARWAITTIMER;
    WebDriverWait wait = webDriverWait(progressBarWaitTimer);
    try {
        wait.until(expectation);
    } catch (TimeoutException | NoSuchElementException e) {
        boolean isTimeout = true;
        throw new BFElementNotFoundException(By.cssSelector(jsVariable), isTimeout, progressBarWaitTimer);
    }
    BFLogger.logTime(startTime, "waitForPageLoaded");
}
Also used : WebDriver(org.openqa.selenium.WebDriver) BFElementNotFoundException(com.capgemini.ntc.selenium.core.exceptions.BFElementNotFoundException) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) NoSuchElementException(org.openqa.selenium.NoSuchElementException) TimeoutException(org.openqa.selenium.TimeoutException)

Example 43 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 44 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 45 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)

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