JAVA-21486 Split or move selenium-junit-testng module (moved-4) (#14366)

Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
timis1
2023-07-09 14:56:19 +03:00
committed by GitHub
parent 92c575498c
commit cff81e0975
38 changed files with 39 additions and 32 deletions
@@ -0,0 +1,70 @@
package com.baeldung.selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import com.baeldung.selenium.config.SeleniumConfig;
public class SeleniumExample {
private SeleniumConfig config;
private String url = "http://www.baeldung.com/";
public SeleniumExample() {
config = new SeleniumConfig();
config.getDriver()
.get(url);
}
public void closeWindow() {
this.config.getDriver()
.close();
}
public String getTitle() {
return this.config.getDriver()
.getTitle();
}
public void getAboutBaeldungPage() {
closeOverlay();
clickAboutLink();
clickAboutUsLink();
}
private void closeOverlay() {
List<WebElement> webElementList = this.config.getDriver()
.findElements(By.tagName("a"));
if (webElementList != null) {
webElementList.stream()
.filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title")))
.filter(WebElement::isDisplayed)
.findAny()
.ifPresent(WebElement::click);
}
}
private void clickAboutLink() {
Actions actions = new Actions(config.getDriver());
WebElement aboutElement = this.config.getDriver()
.findElement(By.id("menu-item-6138"));
actions.moveToElement(aboutElement).perform();
}
private void clickAboutUsLink() {
WebElement element = this.config.getDriver()
.findElement(By.partialLinkText("About Baeldung."));
element.click();
}
public boolean isAuthorInformationAvailable() {
return this.config.getDriver()
.getPageSource()
.contains("Hey ! I'm Eugen");
}
}
@@ -0,0 +1,51 @@
package com.baeldung.selenium.config;
import java.io.File;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumConfig {
private WebDriver driver;
public SeleniumConfig() {
driver = new FirefoxDriver();
driver.manage()
.timeouts()
.implicitlyWait(Duration.ofSeconds(5));
}
static {
System.setProperty("webdriver.gecko.driver", findFile("geckodriver.mac"));
}
private static String findFile(String filename) {
String[] paths = { "", "bin/", "target/classes" }; // if you have chromedriver somewhere else on the path, then put it here.
for (String path : paths) {
if (new File(path + filename).exists())
return path + filename;
}
return "";
}
public void close() {
driver.close();
}
public void navigateTo(String url) {
driver.navigate()
.to(url);
}
public void clickElement(WebElement element) {
element.click();
}
public WebDriver getDriver() {
return driver;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.selenium.models;
import com.baeldung.selenium.config.SeleniumConfig;
import com.baeldung.selenium.pages.BaeldungAboutPage;
import org.openqa.selenium.support.PageFactory;
public class BaeldungAbout {
private SeleniumConfig config;
public BaeldungAbout(SeleniumConfig config) {
this.config = config;
PageFactory.initElements(config.getDriver(), BaeldungAboutPage.class);
}
public void navigateTo() {
config.navigateTo("http://www.baeldung.com/about/");
}
public String getPageTitle() {
return BaeldungAboutPage.title.getText();
}
}
@@ -0,0 +1,10 @@
package com.baeldung.selenium.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class BaeldungAboutPage {
@FindBy(css = ".page-header > h1")
public static WebElement title;
}
@@ -0,0 +1,37 @@
package com.baeldung.selenium.pages;
import com.baeldung.selenium.config.SeleniumConfig;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class BaeldungHomePage {
private SeleniumConfig config;
@FindBy(css = ".nav--logo_mobile")
private WebElement title;
@FindBy(css = ".header--menu")
private WebElement startHere;
public BaeldungHomePage(SeleniumConfig config) {
this.config = config;
PageFactory.initElements(this.config.getDriver(), this);
}
public void navigate() {
this.config.navigateTo("http://www.baeldung.com/");
}
public String getPageTitle() {
return title.getAttribute("title");
}
public StartHerePage clickOnStartHere() {
config.clickElement(startHere);
StartHerePage startHerePage = new StartHerePage(config);
PageFactory.initElements(config.getDriver(), startHerePage);
return startHerePage;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.selenium.pages;
import com.baeldung.selenium.config.SeleniumConfig;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class StartHerePage {
private SeleniumConfig config;
@FindBy(css = ".page-title")
private WebElement title;
public StartHerePage(SeleniumConfig config) {
this.config = config;
}
public String getPageTitle() {
return title.getText();
}
}
@@ -0,0 +1,86 @@
package com.baeldung.selenium.stale;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class RobustWebDriver implements WebDriver {
private final WebDriver originalWebDriver;
public RobustWebDriver(WebDriver webDriver) {
this.originalWebDriver = webDriver;
}
@Override
public void get(String url) {
this.originalWebDriver.get(url);
}
@Override
public String getCurrentUrl() {
return this.originalWebDriver.getCurrentUrl();
}
@Override
public String getTitle() {
return this.originalWebDriver.getTitle();
}
@Override
public List<WebElement> findElements(By by) {
return this.originalWebDriver.findElements(by)
.stream().map(e -> new RobustWebElement(e, by, this))
.collect(Collectors.toList());
}
@Override
public WebElement findElement(By by) {
return new RobustWebElement(this.originalWebDriver.findElement(by), by, this);
}
@Override
public String getPageSource() {
return this.originalWebDriver.getPageSource();
}
@Override
public void close() {
this.originalWebDriver.close();
}
@Override
public void quit() {
this.originalWebDriver.quit();
}
@Override
public Set<String> getWindowHandles() {
return this.originalWebDriver.getWindowHandles();
}
@Override
public String getWindowHandle() {
return this.originalWebDriver.getWindowHandle();
}
@Override
public TargetLocator switchTo() {
return this.originalWebDriver.switchTo();
}
@Override
public Navigation navigate() {
return this.originalWebDriver.navigate();
}
@Override
public Options manage() {
return this.originalWebDriver.manage();
}
}
@@ -0,0 +1,176 @@
package com.baeldung.selenium.stale;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class RobustWebElement implements WebElement {
private WebElement originalElement;
private final RobustWebDriver driver;
private final By by;
private static final int MAX_RETRIES = 10;
private static final String SERE = "Element is no longer attached to the DOM";
public RobustWebElement(WebElement element, By by, RobustWebDriver driver) {
this.originalElement = element;
this.by = by;
this.driver = driver;
}
@Override
public void click() {
executeMethodWithRetries(WebElement::click);
}
@Override
public void submit() {
executeMethodWithRetries(WebElement::submit);
}
@Override
public void sendKeys(CharSequence... keysToSend) {
executeMethodWithRetriesVoid(WebElement::sendKeys, keysToSend);
}
@Override
public void clear() {
executeMethodWithRetries(WebElement::clear);
}
@Override
public String getTagName() {
return executeMethodWithRetries(WebElement::getTagName);
}
@Override
public String getAttribute(String name) {
return executeMethodWithRetries(WebElement::getAttribute, name);
}
@Override
public boolean isSelected() {
return executeMethodWithRetries(WebElement::isSelected);
}
@Override
public boolean isEnabled() {
return executeMethodWithRetries(WebElement::isEnabled);
}
@Override
public String getText() {
return executeMethodWithRetries(WebElement::getText);
}
@Override
public List<WebElement> findElements(By by) {
return executeMethodWithRetries(WebElement::findElements, by);
}
@Override
public WebElement findElement(By by) {
return executeMethodWithRetries(WebElement::findElement, by);
}
@Override
public boolean isDisplayed() {
return executeMethodWithRetries(WebElement::isDisplayed);
}
@Override
public Point getLocation() {
return executeMethodWithRetries(WebElement::getLocation);
}
@Override
public Dimension getSize() {
return executeMethodWithRetries(WebElement::getSize);
}
@Override
public Rectangle getRect() {
return executeMethodWithRetries(WebElement::getRect);
}
@Override
public String getCssValue(String propertyName) {
return executeMethodWithRetries(WebElement::getCssValue, propertyName);
}
@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
return executeMethodWithRetries(WebElement::getScreenshotAs, target);
}
private void executeMethodWithRetries(Consumer<WebElement> method) {
int retries = 0;
while (retries < MAX_RETRIES) {
try {
WebElementUtils.callMethod(originalElement, method);
return;
} catch (StaleElementReferenceException ex) {
refreshElement();
}
retries++;
}
throw new StaleElementReferenceException(SERE);
}
private <T> T executeMethodWithRetries(Function<WebElement, T> method) {
int retries = 0;
while (retries < MAX_RETRIES) {
try {
return WebElementUtils.callMethodWithReturn(originalElement, method);
} catch (StaleElementReferenceException ex) {
refreshElement();
}
retries++;
}
throw new StaleElementReferenceException(SERE);
}
private <U> void executeMethodWithRetriesVoid(BiConsumer<WebElement, U> method, U parameter) {
int retries = 0;
while (retries < MAX_RETRIES) {
try {
WebElementUtils.callMethod(originalElement, method, parameter);
return;
} catch (StaleElementReferenceException ex) {
refreshElement();
}
retries++;
}
throw new StaleElementReferenceException(SERE);
}
private <T, U> T executeMethodWithRetries(BiFunction<WebElement, U, T> method, U parameter) {
int retries = 0;
while (retries < MAX_RETRIES) {
try {
return WebElementUtils.callMethodWithReturn(originalElement, method, parameter);
} catch (StaleElementReferenceException ex) {
refreshElement();
}
retries++;
}
throw new StaleElementReferenceException(SERE);
}
private void refreshElement() {
this.originalElement = driver.findElement(by);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.selenium.stale;
import org.openqa.selenium.WebElement;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class WebElementUtils {
private WebElementUtils(){
}
public static void callMethod(WebElement element, Consumer<WebElement> method) {
method.accept(element);
}
public static <U> void callMethod(WebElement element, BiConsumer<WebElement, U> method, U parameter) {
method.accept(element, parameter);
}
public static <T> T callMethodWithReturn(WebElement element, Function<WebElement, T> method) {
return method.apply(element);
}
public static <T, U> T callMethodWithReturn(WebElement element, BiFunction<WebElement, U, T> method, U parameter) {
return method.apply(element, parameter);
}
}
@@ -0,0 +1,76 @@
package com.baeldung.selenium.tabs;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import javax.annotation.Nonnull;
import java.util.Optional;
import java.util.Set;
/**
* Helper class for browser tab handling.
*/
public class TabHelper {
private final WebDriver driver;
public TabHelper(@Nonnull final WebDriver driver) {
this.driver = driver;
}
/**
* Switch to the given browser tab.
*
* @param destinationWindowHandle the window handle of the destination tab.
* @return the window handle of the current tab before switching.
*/
public String switchToTab(@Nonnull final String destinationWindowHandle) {
final String currentWindowHandle = driver.getWindowHandle();
driver.switchTo().window(destinationWindowHandle);
return currentWindowHandle;
}
/**
* Close all browser tabs except the given one.
*
* @param windowHandle the window handle of the tab that should stay open.
*/
public void closeAllTabsExcept(@Nonnull final String windowHandle) {
for (final String handle : driver.getWindowHandles()) {
if (!handle.equals(windowHandle)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(windowHandle);
}
/**
* Close all browser tabs except the current active one.
*/
public void closeAllTabsExceptCurrent() {
final String currentWindow = driver.getWindowHandle();
closeAllTabsExcept(currentWindow);
}
/**
* Open the given link and switch to the new opened tab.
* If the link is not opened in a new tab then no switch will be performed.
*
* @param link By of the link to open.
* @return the window handle of the tab before switching.
*/
public String openLinkAndSwitchToNewTab(@Nonnull final By link) {
final String windowHandle = driver.getWindowHandle();
final Set<String> windowHandlesBefore = driver.getWindowHandles();
driver.findElement(link).click();
final Set<String> windowHandlesAfter = driver.getWindowHandles();
windowHandlesAfter.removeAll(windowHandlesBefore);
final Optional<String> newWindowHandle = windowHandlesAfter.stream().findFirst();
newWindowHandle.ifPresent(s -> driver.switchTo().window(s));
return windowHandle;
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,66 @@
package com.baeldung.selenium.clickusingjavascript;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class SeleniumJavaScriptClickLiveTest {
private WebDriver driver;
private WebDriverWait wait;
@Before
public void setUp() {
System.setProperty("webdriver.chrome.driver", new File("src/main/resources/chromedriver.mac").getAbsolutePath());
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.of(20, ChronoUnit.SECONDS));
}
@After
public void cleanUp() {
driver.close();
}
@Test
public void whenSearchForSeleniumArticles_thenReturnNotEmptyResults() {
driver.get("https://baeldung.com");
String title = driver.getTitle();
assertEquals("Baeldung", title);
wait.until(ExpectedConditions.elementToBeClickable(By.className("nav--menu_item_anchor")));
WebElement searchButton = driver.findElement(By.className("nav--menu_item_anchor"));
clickElement(searchButton);
wait.until(ExpectedConditions.elementToBeClickable(By.id("menu-item-40489")));
WebElement searchInput = driver.findElement(By.id("menu-item-40489"));
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".nav--menu_item")));
WebElement seeSearchResultsButton = driver.findElement(By.cssSelector(".nav--menu_item"));
clickElement(seeSearchResultsButton);
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("nav--menu_item_anchor")));
int seleniumPostsCount = driver.findElements(By.className("nav--menu_item_anchor"))
.size();
assertTrue(seleniumPostsCount > 0);
}
private void clickElement(WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
}
}
@@ -0,0 +1,121 @@
package com.baeldung.selenium.cookies;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import java.io.File;
import java.time.Duration;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniumCookiesJUnitLiveTest {
private WebDriver driver;
private String navUrl;
private final String COOKIE = "SNS";
@Before
public void setUp() {
System.setProperty("webdriver.gecko.driver", findFile("geckodriver.mac"));
driver = new FirefoxDriver();
navUrl = "https://baeldung.com";
driver.navigate().to(navUrl);
WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(1000));
wait.until(d -> d.manage().getCookieNamed(COOKIE) != null);
}
private static String findFile(String filename) {
String[] paths = { "", "bin/", "target/classes" }; // if you have chromedriver somewhere else on the path, then put it here.
for (String path : paths) {
if (new File(path + filename).exists())
return path + filename;
}
return "";
}
@After
public void teardown() {
driver.quit();
}
@Test
public void whenNavigate_thenCookiesExist() {
Set<Cookie> cookies = driver.manage().getCookies();
assertThat(cookies, is(not(empty())));
}
@Test
public void whenNavigate_thenLpCookieExists() {
Cookie lpCookie = driver.manage().getCookieNamed(COOKIE);
assertThat(lpCookie, is(not(nullValue())));
}
@Test
public void whenNavigate_thenLpCookieIsHasCorrectValue() {
Cookie lpCookie = driver.manage().getCookieNamed(COOKIE);
assertThat(lpCookie.getValue(), containsString("1"));
}
@Test
public void whenNavigate_thenLpCookieHasCorrectProps() {
Cookie lpCookie = driver.manage().getCookieNamed(COOKIE);
assertThat(lpCookie.getDomain(), equalTo("www.baeldung.com"));
assertThat(lpCookie.getPath(), equalTo("/"));
assertThat(lpCookie.isSecure(), equalTo(false));
assertThat(lpCookie.isHttpOnly(), equalTo(false));
}
@Test
public void whenAddingCookie_thenItIsPresent() {
Cookie cookie = new Cookie("foo", "bar");
driver.manage().addCookie(cookie);
Cookie driverCookie = driver.manage().getCookieNamed("foo");
assertThat(driverCookie.getValue(), equalTo("bar"));
}
@Test
public void whenDeletingCookie_thenItIsAbsent() {
Cookie lpCookie = driver.manage().getCookieNamed("SNS");
assertThat(lpCookie, is(not(nullValue())));
driver.manage().deleteCookie(lpCookie);
Cookie deletedCookie = driver.manage().getCookieNamed(COOKIE);
assertThat(deletedCookie, is(nullValue()));
}
@Test
public void whenOverridingCookie_thenItIsUpdated() {
Cookie lpCookie = driver.manage().getCookieNamed(COOKIE);
driver.manage().deleteCookie(lpCookie);
Cookie newLpCookie = new Cookie(COOKIE, "foo");
driver.manage().addCookie(newLpCookie);
Cookie overriddenCookie = driver.manage().getCookieNamed(COOKIE);
assertThat(overriddenCookie.getValue(), equalTo("foo"));
}
}
@@ -0,0 +1,39 @@
package com.baeldung.selenium.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.selenium.SeleniumExample;
public class SeleniumWithJUnitLiveTest {
private static SeleniumExample seleniumExample;
private String expectedTitle = "About Baeldung | Baeldung";
@BeforeClass
public static void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterClass
public static void tearDown() throws IOException {
seleniumExample.closeWindow();
}
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(expectedTitle, actualTitle);
assertTrue(seleniumExample.isAuthorInformationAvailable());
}
}
@@ -0,0 +1,50 @@
package com.baeldung.selenium.pages;
import com.baeldung.selenium.config.SeleniumConfig;
import com.baeldung.selenium.models.BaeldungAbout;
import com.baeldung.selenium.pages.BaeldungHomePage;
import com.baeldung.selenium.pages.StartHerePage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class SeleniumPageObjectLiveTest {
private SeleniumConfig config;
private BaeldungHomePage homePage;
private BaeldungAbout about;
@Before
public void setUp() {
config = new SeleniumConfig();
homePage = new BaeldungHomePage(config);
about = new BaeldungAbout(config);
}
@After
public void teardown() {
config.close();
}
@Test
public void givenHomePage_whenNavigate_thenTitleMatch() {
homePage.navigate();
assertThat(homePage.getPageTitle(), is("Baeldung"));
}
@Test
public void givenHomePage_whenNavigate_thenShouldBeInStartHere() {
homePage.navigate();
StartHerePage startHerePage = homePage.clickOnStartHere();
assertThat(startHerePage.getPageTitle(), is("Start Here"));
}
@Test
public void givenAboutPage_whenNavigate_thenTitleMatch() {
about.navigateTo();
assertThat(about.getPageTitle(), is("About Baeldung"));
}
}
@@ -0,0 +1,83 @@
package com.baeldung.selenium.screenshot;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.coordinates.WebDriverCoordsProvider;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class TakeScreenShotSeleniumLiveTest {
private static ChromeDriver driver;
@BeforeClass
public static void setUp() {
System.setProperty("webdriver.chrome.driver", resolveResourcePath("chromedriver.mac"));
driver = new ChromeDriver();
driver.manage()
.timeouts()
.implicitlyWait(Duration.ofSeconds(5));
driver.get("http://www.google.com/");
}
@AfterClass
public static void tearDown() {
driver.close();
System.clearProperty("webdriver.chrome.driver");
}
@Test
public void whenGoogleIsLoaded_thenCaptureScreenshot() throws IOException {
takeScreenshot(resolveTestResourcePath("google-home.png"));
assertTrue(new File(resolveTestResourcePath("google-home.png")).exists());
}
@Test
public void whenGoogleIsLoaded_thenCaptureLogo() throws IOException {
WebElement logo = driver.findElement(By.id("hplogo"));
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
.coordsProvider(new WebDriverCoordsProvider())
.takeScreenshot(driver, logo);
ImageIO.write(screenshot.getImage(), "jpg", new File(resolveTestResourcePath("google-logo.png")));
assertTrue(new File(resolveTestResourcePath("google-logo.png")).exists());
}
public void takeScreenshot(String pathname) throws IOException {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File(pathname));
}
private static String resolveResourcePath(String filename) {
File file = new File("src/main/resources/" + filename);
return file.getAbsolutePath();
}
private static String resolveTestResourcePath(String filename) {
File file = new File("src/test/resources/" + filename);
return file.getAbsolutePath();
}
}
@@ -0,0 +1,58 @@
package com.baeldung.selenium.stale;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.time.Duration;
final class RobustWebElementLiveTest {
private static RobustWebDriver driver;
private static final int TIMEOUT = 10;
private static final By LOCATOR_REFRESH = By.xpath("//a[.='click here']");
private static final By LOCATOR_DYNAMIC_CONTENT = By.xpath(
"(//div[@id='content']//div[@class='large-10 columns'])[1]");
private static void setupChromeDriver() {
WebDriverManager.chromedriver().setup();
final ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
driver = new RobustWebDriver(new ChromeDriver(options));
options();
}
private static void options() {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
}
@BeforeEach
public void init() {
setupChromeDriver();
}
@Test
void givenDynamicPage_whenRefreshingAndAccessingSavedElement_thenOK() {
driver.navigate().to("https://the-internet.herokuapp.com/dynamic_content?with_content=static");
final WebElement element = driver.findElement(LOCATOR_DYNAMIC_CONTENT);
driver.findElement(LOCATOR_REFRESH).click();
Assertions.assertDoesNotThrow(element::getText);
}
@AfterEach
void teardown() {
if (driver != null) {
driver.quit();
driver = null;
}
}
}
@@ -0,0 +1,102 @@
package com.baeldung.selenium.stale;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.time.Duration;
final class StaleElementReferenceLiveTest {
private static WebDriver driver;
private static final int TIMEOUT = 10;
private static final By LOCATOR_REFRESH = By.xpath("//a[.='click here']");
private static final By LOCATOR_DYNAMIC_CONTENT = By.xpath(
"(//div[@id='content']//div[@class='large-10 columns'])[1]");
private static void setupChromeDriver() {
WebDriverManager.chromedriver().setup();
final ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
driver = new ChromeDriver(options);
options();
}
private static void options() {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
}
@BeforeEach
public void init() {
setupChromeDriver();
}
@Test
void givenDynamicPage_whenRefreshingAndAccessingSavedElement_thenSERE() {
driver.navigate().to("https://the-internet.herokuapp.com/dynamic_content?with_content=static");
final WebElement element = driver.findElement(LOCATOR_DYNAMIC_CONTENT);
driver.findElement(LOCATOR_REFRESH).click();
Assertions.assertThrows(StaleElementReferenceException.class, element::getText);
}
@Test
void givenDynamicPage_whenRefreshingAndAccessingSavedElement_thenHandleSERE() {
driver.navigate().to("https://the-internet.herokuapp.com/dynamic_content?with_content=static");
final WebElement element = driver.findElement(LOCATOR_DYNAMIC_CONTENT);
if (!retryingFindClick(LOCATOR_REFRESH)) {
Assertions.fail("Element is still stale after 5 attempts");
}
Assertions.assertDoesNotThrow(() -> retryingFindGetText(LOCATOR_DYNAMIC_CONTENT));
}
private boolean retryingFindClick(By locator) {
boolean result = false;
int attempts = 0;
while (attempts < 5) {
try {
driver.findElement(locator).click();
result = true;
break;
} catch (StaleElementReferenceException ex) {
System.out.println(ex.getMessage());
}
attempts++;
}
return result;
}
private String retryingFindGetText(By locator) {
String result = null;
int attempts = 0;
while (attempts < 5) {
try {
result = driver.findElement(locator).getText();
break;
} catch (StaleElementReferenceException ex) {
System.out.println(ex.getMessage());
}
attempts++;
}
return result;
}
@AfterEach
void teardown() {
if (driver != null) {
driver.quit();
driver = null;
}
}
}
@@ -0,0 +1,53 @@
package com.baeldung.selenium.tabs;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.time.Duration;
public class SeleniumOpenNewTabLiveTest {
private WebDriver driver;
private static final int TIMEOUT = 10;
private static final int EXPECTED_TABS_COUNT = 2;
@BeforeMethod
public void initDriver() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
@Test
public void whenUseTabsApiOpenWindow_thenNewTabOpened() {
driver.switchTo().newWindow(WindowType.TAB);
waitTabsCount(EXPECTED_TABS_COUNT);
}
@Test
public void whenExecuteOpenWindowJsScript_thenNewTabOpened() {
((JavascriptExecutor) driver).executeScript("window.open()");
waitTabsCount(EXPECTED_TABS_COUNT);
}
@AfterMethod
public void closeBrowser() {
driver.quit();
}
private void waitTabsCount(int tabsCount) {
new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT))
.withMessage("Tabs count should be: " + tabsCount)
.until(ExpectedConditions.numberOfWindowsToBe(tabsCount));
}
}
@@ -0,0 +1,97 @@
package com.baeldung.selenium.tabs;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WindowType;
import static org.junit.jupiter.api.Assertions.assertEquals;
final class SeleniumTabsLiveTest extends SeleniumTestBase {
private static final By LINK_TO_ATTRIBUTES_PAGE_XPATH = By.xpath("//a[.='Attributes in new page']");
private static final By LINK_TO_ALERT_PAGE_XPATH = By.xpath("//a[.='Alerts In A New Window From JavaScript']");
private static final String MAIN_PAGE_URL = "https://testpages.herokuapp.com/styled/windows-test.html";
private static final String ATTRIBUTES_PAGE_URL = "https://testpages.herokuapp.com/styled/attributes-test.html";
private static final String ALERT_PAGE_URL = "https://testpages.herokuapp.com/styled/alerts/alert-test.html";
@Test
void givenOneTab_whenOpenTab_thenTwoTabsOpen() {
//given
driver.get(MAIN_PAGE_URL);
assertEquals(1, driver.getWindowHandles().size());
//when
driver.switchTo().newWindow(WindowType.TAB);
//then
assertEquals(2, driver.getWindowHandles().size());
}
@Test
void givenOneTab_whenOpenLinkInTab_thenTwoTabsOpen() {
//given
driver.get(MAIN_PAGE_URL);
//when
final String mainWindow = tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ATTRIBUTES_PAGE_XPATH);
assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());
//then
tabHelper.switchToTab(mainWindow);
assertEquals(MAIN_PAGE_URL, driver.getCurrentUrl());
assertEquals(2, driver.getWindowHandles().size());
}
@Test
void givenTwoTabs_whenCloseAllExceptMainTab_thenOneTabOpen() {
//given
driver.get(MAIN_PAGE_URL);
final String mainWindow = tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ATTRIBUTES_PAGE_XPATH);
assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());
assertEquals(2, driver.getWindowHandles().size());
//when
tabHelper.closeAllTabsExcept(mainWindow);
//then
assertEquals(1, driver.getWindowHandles().size());
assertEquals(MAIN_PAGE_URL, driver.getCurrentUrl());
}
@Test
void givenTwoTabs_whenSwitching_thenCorrectTabOpen() {
//given
driver.get(MAIN_PAGE_URL);
final String mainWindow = tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ATTRIBUTES_PAGE_XPATH);
assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());
assertEquals(2, driver.getWindowHandles().size());
//when/then
final String secondWindow = tabHelper.switchToTab(mainWindow);
assertEquals(MAIN_PAGE_URL, driver.getCurrentUrl());
tabHelper.switchToTab(secondWindow);
assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());
}
@Test
void givenThreeTabs_whenSwitching_thenCorrectTabOpen() {
//given
driver.get(MAIN_PAGE_URL);
final String mainWindow = tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ATTRIBUTES_PAGE_XPATH);
final String secondWindow = tabHelper.switchToTab(mainWindow);
tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ALERT_PAGE_XPATH);
final String thirdWindow = driver.getWindowHandle();
assertEquals(3, driver.getWindowHandles().size());
//when/then
tabHelper.switchToTab(mainWindow);
assertEquals(MAIN_PAGE_URL, driver.getCurrentUrl());
tabHelper.switchToTab(secondWindow);
assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());
tabHelper.switchToTab(thirdWindow);
assertEquals(ALERT_PAGE_URL, driver.getCurrentUrl());
}
}
@@ -0,0 +1,55 @@
package com.baeldung.selenium.tabs;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
/**
* Base class for Selenium Tests. This class handles the WebDriver setup and configuration.
* It takes care about closing all tabs except one after each test. After a test class it will close the browser.
*/
public class SeleniumTestBase {
protected static WebDriver driver;
protected static TabHelper tabHelper;
private static void setupChromeDriver() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
options();
tabHelper = new TabHelper(driver);
}
private static void options() {
driver.manage().window().maximize();
}
/**
* Initializes the ChromeDriver before all tests.
*/
@BeforeAll
public static void init() {
setupChromeDriver();
}
/**
* After each test all tabs except the current tab will be closed.
*/
@AfterEach
public void closeTabs() {
tabHelper.closeAllTabsExceptCurrent();
}
/**
* After all tests the browser will be closed.
*/
@AfterAll
public static void cleanup() {
if (driver != null) {
driver.quit();
}
}
}
@@ -0,0 +1,36 @@
package com.baeldung.selenium.testng;
import com.baeldung.selenium.SeleniumExample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class SeleniumWithTestNGLiveTest {
private SeleniumExample seleniumExample;
private String expectedTitle = "About Baeldung | Baeldung";
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(expectedTitle, actualTitle);
assertTrue(seleniumExample.isAuthorInformationAvailable());
}
}
@@ -0,0 +1,43 @@
package com.baeldung.selenium.webdriver;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class SeleniumWebDriverUnitTest {
private WebDriver driver;
private static final String URL = "https://duckduckgo.com/";
private static final String INPUT_ID = "searchbox_input__bEGm3";
@BeforeEach
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
@AfterEach
public void tearDown() {
driver.quit();
}
@Test
public void givenDuckDuckGoHomePage_whenInputHelloWorld_thenInputValueIsHelloWorld() {
driver.get(URL);
WebElement inputElement = driver.findElement(By.className(INPUT_ID));
inputElement.sendKeys(Keys.chord(Keys.CONTROL, "a"), Keys.DELETE);
inputElement.sendKeys("Hello World!");
String inputValue = inputElement.getAttribute("value");
Assert.assertEquals("Hello World!", inputValue);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.selenium.webdriver.fileupload;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class FileUploadWebDriverUnitTest {
private WebDriver driver;
private static final String URL = "http://www.csm-testcenter.org/test?do=show&subdo=common&test=file_upload";
private static final String INPUT_NAME = "file_upload";
@BeforeEach
public void setUp() {
WebDriverManager.firefoxdriver()
.setup();
driver = new FirefoxDriver();
}
@AfterEach
public void tearDown() {
driver.quit();
}
@Test
public void givenFileUploadPage_whenInputFilePath_thenFileUploadEndsWithFilename() {
driver.get(URL);
String filePath = System.getProperty("user.dir") + "/1688web.png";
WebElement inputElement = driver.findElement(By.name(INPUT_NAME));
WebElement submitButton = driver.findElement(By.name("http_submit"));
inputElement.sendKeys(filePath);
String actualFilePath = inputElement.getAttribute("value");
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
submitButton.click();
Assert.assertTrue(actualFilePath.endsWith(fileName));
}
}