Search in sources :

Example 51 with ExpectedCondition

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

the class SuvianTest method test0_8.

// http://software-testing.ru/forum/index.php?/topic/17746-podskazhite-po-xpath/
// http://automated-testing.info/t/vopros-na-znanie-xpath-pochemu-ne-nahodit-element/18600/4
@Test(enabled = true)
public void test0_8() {
    // Arrange
    driver.get("http://suvian.in/selenium/1.1link.html");
    String expectedText = "Click Here";
    WebElement element = null;
    String[] xpathMatchers = new String[] { "//a[text() = '%s']", "//a[normalize-space(.) = '%s']", "//a[normalize-space(text()) = '%s']", "//*[normalize-space(text()) = '%s']", "//a[contains(text()[normalize-space()],'%s')]", "//a[contains(normalize-space(.), '%s')]", // NOTE: way too permissive for a selector
    "//*[contains(normalize-space(.), '%s')]" };
    for (int cnt = 0; cnt != xpathMatchers.length; cnt++) {
        String xpathMatcher = String.format(xpathMatchers[cnt], expectedText);
        // try {
        element = wait.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver _driver) {
                System.err.println("xpath matcher:" + xpathMatcher);
                Optional<WebElement> _element = _driver.findElements(By.xpath(xpathMatcher)).stream().filter(o -> {
                    String t = o.getText();
                    System.err.println("In filter: " + o.getTagName() + ' ' + (t.length() > 20 ? t.substring(0, 20) : t));
                    Pattern pattern = Pattern.compile("^ *" + Pattern.quote(expectedText), Pattern.CASE_INSENSITIVE);
                    return pattern.matcher(t).find();
                // quicker, less precise
                // return (Boolean)
                // (__element.getText().contains(expectedText));
                }).findFirst();
                return (_element.isPresent()) ? _element.get() : (WebElement) null;
            }
        });
        String expectedTag = null;
        Pattern pattern = Pattern.compile("^/+([^\\[]+)\\[.*$", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(xpathMatcher);
        if (matcher.find()) {
            expectedTag = matcher.group(1);
        }
        System.err.println(String.format("Expecting tag: \"%s\": ", expectedTag));
        if (!expectedTag.matches("\\*")) {
            // case
            assertThat("tag match", element.getTagName(), is(expectedTag));
        }
        assertThat("text match", element.getAttribute("innerHTML"), containsString(expectedText));
        System.err.println("Element: " + element.getTagName() + " with text: " + element.getAttribute("innerHTML"));
    // } catch (Exception e) {
    // System.err.println("Exception: " + e.toString());
    // }
    // Act
    }
    highlight(element);
}
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) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) WebElement(org.openqa.selenium.WebElement) Point(org.openqa.selenium.Point) Test(org.testng.annotations.Test)

Example 52 with ExpectedCondition

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

the class TabTest method test1.

@Test(enabled = true)
public void test1() {
    String handle = createWindow(altURL);
    WebDriver handleDriver = switchToWindow(handle);
    ExpectedCondition<Boolean> urlChange = driver -> driver.getCurrentUrl().matches(String.format("^%s.*", altURL));
    (new WebDriverWait(handleDriver, flexibleWait)).until(urlChange);
    System.err.println("Current  URL: " + driver.getCurrentUrl());
    for (int cnt = 0; cnt != 5; cnt++) {
        switchToParent();
        switchToWindow(handle);
    }
    close(handle);
}
Also used : WebDriver(org.openqa.selenium.WebDriver) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) WebDriver(org.openqa.selenium.WebDriver) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) BeforeMethod(org.testng.annotations.BeforeMethod) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) Method(java.lang.reflect.Method) ITestResult(org.testng.ITestResult) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) Test(org.testng.annotations.Test)

Example 53 with ExpectedCondition

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

the class GmailTest method loginTest.

// the gmail of showing the identity confirmation page the test is not ready to handle
@Test(priority = 4, enabled = false)
public void loginTest() throws InterruptedException, IOException {
    // Click on Sign in Link
    driver.findElement(signInLink).click();
    // origin:
    // https://github.com/TsvetomirSlavov/JavaScriptForSeleniumMyCollection
    // Wait for page url to change
    ExpectedCondition<Boolean> urlChange = driver -> driver.getCurrentUrl().matches("^https://accounts.google.com/signin.*");
    wait.until(urlChange);
    // TODO: examine it landed on https://accounts.google.com/AccountChooser
    // Enter the email id
    enterData(identifier, "automationnewuser24@gmail.com");
    /*
		File screenshotFile = screenshot.getScreenshotAs(OutputType.FILE);
		// Move image file to new destination
		FileUtils.copyFile(screenshotFile, new File("c:\\temp\\UserID.jpg"));
		*/
    // Click on next button
    clickNextButton(identifierNextButton);
    // Enter the password
    enterData(passwordInput, "automationnewuser2410");
    // 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);
		 */
    wait.until(new ExpectedCondition<Boolean>() {

        public Boolean apply(WebDriver webDriver) {
            System.out.println("Checking if mail page is loaded...");
            // https://github.com/pawnu/SeleniumQA/blob/master/EcommerceProject/RunTest.java
            return checkPage();
        }
    });
    // Wait until form is redndered, old semantics
    wait.until(new ExpectedCondition<Boolean>() {

        @Override
        public Boolean apply(WebDriver driver) {
            System.err.println("Wait for form to finish rendering");
            JavascriptExecutor js = ((JavascriptExecutor) driver);
            Boolean active = (Boolean) js.executeScript("return document.readyState == 'complete'");
            if (active) {
                System.err.println("Done");
            }
            return active;
        }
    });
    System.err.println("Click on profile image");
    // 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();
    // Wait until form is redndered, lambda semantics
    wait.until((WebDriver driver) -> {
        System.err.println("Wait for form to finish rendering");
        JavascriptExecutor js = ((JavascriptExecutor) driver);
        Boolean active = (Boolean) js.executeScript("return document.readyState == 'complete'");
        if (active) {
            System.err.println("Done");
        }
        return active;
    });
    // 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 (ignored): " + ex.getStackTrace());
        return;
    } catch (WebDriverException ex) {
        System.err.println("Alert was not handled by PhantomJS: " + ex.getStackTrace().toString());
        return;
    }
}
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) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) 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 54 with ExpectedCondition

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

the class PlunkerTest method testFullScreeen.

@Test(enabled = true)
public void testFullScreeen() {
    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);
    sleep(500);
    // 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());
    // confirm it opens in a new tab.
    // fullScreenButton.click();
    // alternatively, enforce open in a new tab:
    String openinLinkNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
    fullScreenButton.sendKeys(openinLinkNewTab);
    sleep(500);
    // confirm it opens in a new tab.
    String currentHandle = null;
    try {
        currentHandle = driver.getWindowHandle();
    // System.err.println("Thread: Current Window handle: " + currentHandle);
    } catch (NoSuchWindowException e) {
    }
    windowHandles = driver.getWindowHandles();
    assertThat(windowHandles.size(), equalTo(2));
    // String handle = windowHandleIterator.next();
    for (String handle : windowHandles) {
        if (!handle.equals(currentHandle)) {
            driver.switchTo().window(handle);
            assertThat(getBaseURL(), equalTo("https://run.plnkr.co"));
            // System.err.println(getBaseURL());
            driver.switchTo().defaultContent();
        }
    }
}
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 55 with ExpectedCondition

use of org.openqa.selenium.support.ui.ExpectedCondition in project muikku by otavanopisto.

the class AbstractUITest method waitUntilAnimationIsDone.

protected void waitUntilAnimationIsDone(final String cssLocator) {
    WebDriverWait wdw = new WebDriverWait(getWebDriver(), 20);
    ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {

        @Override
        public Boolean apply(WebDriver driver) {
            String temp = ((JavascriptExecutor) driver).executeScript("return jQuery('" + cssLocator + "').is(':animated')").toString();
            return temp.equalsIgnoreCase("false");
        }
    };
    try {
        wdw.until(expectation);
    } catch (Exception e) {
        throw new AssertionError("Element animation is not finished in time. Css locator: " + cssLocator);
    }
}
Also used : WebDriver(org.openqa.selenium.WebDriver) RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) WebDriverWait(org.openqa.selenium.support.ui.WebDriverWait) ExpectedCondition(org.openqa.selenium.support.ui.ExpectedCondition) JsonParseException(com.fasterxml.jackson.core.JsonParseException) StaleElementReferenceException(org.openqa.selenium.StaleElementReferenceException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) WebDriverException(org.openqa.selenium.WebDriverException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

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