diff --git a/.github/workflows/selenium-examples.yml b/.github/workflows/selenium-examples.yml index b6fbfd91..3a739a2e 100644 --- a/.github/workflows/selenium-examples.yml +++ b/.github/workflows/selenium-examples.yml @@ -9,19 +9,31 @@ on: pull_request: jobs: + formatting: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: axel-op/googlejavaformat-action@v3 + with: + args: "--replace" + files: "selenium-examples/**/*.java" + skip-commit: true + - name: Print diffs + run: git --no-pager diff --exit-code + build: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest] + os: [ ubuntu-latest ] steps: - - uses: actions/checkout@v2 - - name: Set up Java - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Run tests - env: - SAUCE_USERNAME: ${{ secrets.SAUCE_USERNAME }} - SAUCE_ACCESS_KEY: ${{ secrets.SAUCE_ACCESS_KEY }} - run: mvn test -pl selenium-examples -X + - uses: actions/checkout@v2 + - name: Set up Java + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Run tests + env: + SAUCE_USERNAME: ${{ secrets.SAUCE_USERNAME }} + SAUCE_ACCESS_KEY: ${{ secrets.SAUCE_ACCESS_KEY }} + run: mvn test -pl selenium-examples -X diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/PerformanceTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/PerformanceTest.java index a3599f23..7ae7d0c1 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/PerformanceTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/PerformanceTest.java @@ -11,69 +11,71 @@ import java.util.HashMap; import java.util.Map; -/** - * Performance Test. - */ +/** Performance Test. */ public class PerformanceTest extends SeleniumTestBase { - @BeforeEach - public void setup(TestInfo testInfo) { - ChromeOptions options = new ChromeOptions(); - options.setPlatformName("Windows 10"); - options.setBrowserVersion("117"); - - Map sauceOptions = new HashMap<>(); - sauceOptions.put("capturePerformance", true); - sauceOptions.put("extendedDebugging", true); - options.setCapability("sauce:options", sauceOptions); - - basicSetup(testInfo, options); - } - - @DisplayName("Ensure all metrics within historical limits") - @Test - public void performanceAllMetrics() { - driver.get("https://www.saucedemo.com"); - - HashMap args = new HashMap<>(); - args.put("name", watcher.getName()); - Map performance = (Map) driver.executeScript("sauce:performance", args); - - Assertions.assertEquals("pass", performance.get("result")); - } - - @DisplayName("Ensure provided metrics within historical limits") - @Test - public void performanceSpecificMetrics() { - driver.get("https://www.saucedemo.com"); - - HashMap args = new HashMap<>(); - args.put("name", watcher.getName()); - args.put("metrics", Arrays.asList("load", "firstContentfulPaint")); - - Map performance = (Map) driver.executeScript("sauce:performance", args); - Assertions.assertEquals("pass", performance.get("result")); - } - - @DisplayName("Get log of performance metrics from previous navigation") - @Test - public void performanceLog() { - driver.get("https://www.saucedemo.com"); - - HashMap metricsLog = new HashMap<>(); - metricsLog.put("type", "sauce:performance"); - Map metrics = (Map) driver.executeScript("sauce:log", metricsLog); - - Assertions.assertTrue((long)metrics.get("firstInteractive") < 5000 ); - } - - @DisplayName("Get jankiness metrics from previous navigation") - @Test - public void jankiness() { - driver.get("https://www.saucedemo.com"); - - Map metrics = (Map) driver.executeScript("sauce:jankinessCheck"); - - Assertions.assertTrue((double) metrics.get("score") > 0.5 ); - } + @BeforeEach + public void setup(TestInfo testInfo) { + ChromeOptions options = new ChromeOptions(); + options.setPlatformName("Windows 10"); + options.setBrowserVersion("117"); + + Map sauceOptions = new HashMap<>(); + sauceOptions.put("capturePerformance", true); + sauceOptions.put("extendedDebugging", true); + options.setCapability("sauce:options", sauceOptions); + + basicSetup(testInfo, options); + } + + @DisplayName("Ensure all metrics within historical limits") + @Test + public void performanceAllMetrics() { + driver.get("https://www.saucedemo.com"); + + HashMap args = new HashMap<>(); + args.put("name", watcher.getName()); + Map performance = + (Map) driver.executeScript("sauce:performance", args); + + Assertions.assertEquals("pass", performance.get("result")); + } + + @DisplayName("Ensure provided metrics within historical limits") + @Test + public void performanceSpecificMetrics() { + driver.get("https://www.saucedemo.com"); + + HashMap args = new HashMap<>(); + args.put("name", watcher.getName()); + args.put("metrics", Arrays.asList("load", "firstContentfulPaint")); + + Map performance = + (Map) driver.executeScript("sauce:performance", args); + Assertions.assertEquals("pass", performance.get("result")); + } + + @DisplayName("Get log of performance metrics from previous navigation") + @Test + public void performanceLog() { + driver.get("https://www.saucedemo.com"); + + HashMap metricsLog = new HashMap<>(); + metricsLog.put("type", "sauce:performance"); + Map metrics = + (Map) driver.executeScript("sauce:log", metricsLog); + + Assertions.assertTrue((long) metrics.get("firstInteractive") < 5000); + } + + @DisplayName("Get jankiness metrics from previous navigation") + @Test + public void jankiness() { + driver.get("https://www.saucedemo.com"); + + Map metrics = + (Map) driver.executeScript("sauce:jankinessCheck"); + + Assertions.assertTrue((double) metrics.get("score") > 0.5); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/SeleniumTestBase.java b/selenium-examples/src/test/java/com/saucedemo/selenium/SeleniumTestBase.java index f4adfb59..24dea2c6 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/SeleniumTestBase.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/SeleniumTestBase.java @@ -13,80 +13,81 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; + public class SeleniumTestBase { - public RemoteWebDriver driver; + public RemoteWebDriver driver; + + @RegisterExtension + public SeleniumTestBase.SauceTestWatcher watcher = new SeleniumTestBase.SauceTestWatcher(); + + public void basicSetup(TestInfo testInfo, MutableCapabilities options) { + Map sauceOptions = (Map) options.getCapability("sauce:options"); + + if (sauceOptions == null) { + sauceOptions = new HashMap<>(); + } + + sauceOptions.put("username", System.getenv("SAUCE_USERNAME")); + sauceOptions.put("accessKey", System.getenv("SAUCE_ACCESS_KEY")); + sauceOptions.put("name", testInfo.getDisplayName()); + options.setCapability("sauce:options", sauceOptions); - @RegisterExtension - public SeleniumTestBase.SauceTestWatcher watcher = new SeleniumTestBase.SauceTestWatcher(); + watcher.setName(testInfo.getDisplayName()); - public void basicSetup(TestInfo testInfo, MutableCapabilities options) { - Map sauceOptions = (Map) options.getCapability("sauce:options"); + URL url; + try { + url = new URL("https://ondemand.us-west-1.saucelabs.com/wd/hub"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + + driver = new RemoteWebDriver(url, options); + watcher.setId(driver.getSessionId()); + } + + public void basicSetup(TestInfo testInfo) { + ChromeOptions options = new ChromeOptions(); + options.setPlatformName("Windows 10"); + options.setBrowserVersion("latest"); - if (sauceOptions == null) { - sauceOptions = new HashMap<>(); - } + basicSetup(testInfo, options); + } - sauceOptions.put("username", System.getenv("SAUCE_USERNAME")); - sauceOptions.put("accessKey", System.getenv("SAUCE_ACCESS_KEY")); - sauceOptions.put("name", testInfo.getDisplayName()); - options.setCapability("sauce:options", sauceOptions); + public class SauceTestWatcher implements TestWatcher { + private String name; + private String id; - watcher.setName(testInfo.getDisplayName()); + @Override + public void testSuccessful(ExtensionContext context) { + printResults(); + driver.executeScript("sauce:job-result=passed"); + driver.quit(); + } - URL url; - try { - url = new URL("https://ondemand.us-west-1.saucelabs.com/wd/hub"); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + printResults(); + driver.executeScript("sauce:job-result=failed"); + driver.quit(); + } - driver = new RemoteWebDriver(url, options); - watcher.setId(driver.getSessionId()); + public void printResults() { + String sauceReporter = String.format("SauceOnDemandSessionID=%s job-name=%s", id, name); + String sauceTestLink = String.format("Test Job Link: https://app.saucelabs.com/tests/%s", id); + System.out.print(sauceReporter + "\n" + sauceTestLink + "\n"); } - public void basicSetup(TestInfo testInfo) { - ChromeOptions options = new ChromeOptions(); - options.setPlatformName("Windows 10"); - options.setBrowserVersion("latest"); + public void setName(String displayName) { + this.name = displayName; + } - basicSetup(testInfo, options); + public String getName() { + return name; } - public class SauceTestWatcher implements TestWatcher { - private String name; - private String id; - - @Override - public void testSuccessful(ExtensionContext context) { - printResults(); - driver.executeScript("sauce:job-result=passed"); - driver.quit(); - } - - @Override - public void testFailed(ExtensionContext context, Throwable cause) { - printResults(); - driver.executeScript("sauce:job-result=failed"); - driver.quit(); - } - - public void printResults() { - String sauceReporter = String.format("SauceOnDemandSessionID=%s job-name=%s", id, name); - String sauceTestLink = String.format("Test Job Link: https://app.saucelabs.com/tests/%s", id); - System.out.print(sauceReporter + "\n" + sauceTestLink + "\n"); - } - - public void setName(String displayName) { - this.name = displayName; - } - - public String getName() { - return name; - } - - public void setId(SessionId sessionId) { - this.id = String.valueOf(sessionId); - } + public void setId(SessionId sessionId) { + this.id = String.valueOf(sessionId); } + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/DequeAxeTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/DequeAxeTest.java index 5f99ae72..f937dbc0 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/DequeAxeTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/DequeAxeTest.java @@ -9,24 +9,22 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; -/** - * Accessibility Tests with Deque Library. - */ +/** Accessibility Tests with Deque Library. */ public class DequeAxeTest extends SeleniumTestBase { - @BeforeEach - public void setup(TestInfo testInfo) { - basicSetup(testInfo); - } + @BeforeEach + public void setup(TestInfo testInfo) { + basicSetup(testInfo); + } - @DisplayName("Deque Axe Test With Selenium Not html") - @Test - public void accessibilityTest() { - driver.navigate().to("https://www.saucedemo.com"); + @DisplayName("Deque Axe Test With Selenium Not html") + @Test + public void accessibilityTest() { + driver.navigate().to("https://www.saucedemo.com"); - AxeBuilder axeBuilder = new AxeBuilder(); - Results accessibilityResults = axeBuilder.analyze(driver); + AxeBuilder axeBuilder = new AxeBuilder(); + Results accessibilityResults = axeBuilder.analyze(driver); - Assertions.assertEquals(3, accessibilityResults.getViolations().size()); - } + Assertions.assertEquals(3, accessibilityResults.getViolations().size()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/SauceBindingsTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/SauceBindingsTest.java index 11f09a62..c56110b1 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/SauceBindingsTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/accessibility/SauceBindingsTest.java @@ -6,24 +6,22 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** - * Accessibility Tests with Sauce Bindings. - */ +/** Accessibility Tests with Sauce Bindings. */ public class SauceBindingsTest extends SauceBaseTest { - @DisplayName("Accessibility of Swag Labs") - @Test - public void sauceDemoAccessibility() { - driver.navigate().to("https://www.saucedemo.com"); - Results results = session.getAccessibilityResults(); - Assertions.assertEquals(3, results.getViolations().size()); - } + @DisplayName("Accessibility of Swag Labs") + @Test + public void sauceDemoAccessibility() { + driver.navigate().to("https://www.saucedemo.com"); + Results results = session.getAccessibilityResults(); + Assertions.assertEquals(3, results.getViolations().size()); + } - @DisplayName("Accessibility of abcdcomputech") - @Test - public void abcdcomputechTest() { - driver.navigate().to("http://abcdcomputech.dequecloud.com"); - Results results = session.getAccessibilityResults(); - Assertions.assertEquals(8, results.getViolations().size()); - } + @DisplayName("Accessibility of abcdcomputech") + @Test + public void abcdcomputechTest() { + driver.navigate().to("http://abcdcomputech.dequecloud.com"); + Results results = session.getAccessibilityResults(); + Assertions.assertEquals(8, results.getViolations().size()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SauceBindingsTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SauceBindingsTest.java index 507bf2b0..520a8199 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SauceBindingsTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SauceBindingsTest.java @@ -12,48 +12,41 @@ import org.junit.jupiter.api.extension.TestWatcher; import org.openqa.selenium.remote.RemoteWebDriver; -/** - * Demo tests using Sauce bindings. - */ +/** Demo tests using Sauce bindings. */ public class SauceBindingsTest { - private SauceSession session; - protected RemoteWebDriver driver; + private SauceSession session; + protected RemoteWebDriver driver; - /** - * A Test Watcher is needed to be able to get the results of a Test so that it can be sent to Sauce Labs. - * Note that the name is never actually used - */ - @RegisterExtension - public SauceTestWatcher watcher = new SauceTestWatcher(); + /** + * A Test Watcher is needed to be able to get the results of a Test so that it can be sent to + * Sauce Labs. Note that the name is never actually used + */ + @RegisterExtension public SauceTestWatcher watcher = new SauceTestWatcher(); - @BeforeEach - public void setup(TestInfo testInfo) { - SauceOptions sauceOptions = SauceOptions.chrome() - .setName(testInfo.getDisplayName()) - .build(); - session = new SauceSession(sauceOptions); - driver = session.start(); - } + @BeforeEach + public void setup(TestInfo testInfo) { + SauceOptions sauceOptions = SauceOptions.chrome().setName(testInfo.getDisplayName()).build(); + session = new SauceSession(sauceOptions); + driver = session.start(); + } - @DisplayName("Sauce Bindings Navigation Test") - @Test - public void sauceBindingsNavigationTest() { - driver.navigate().to("https://www.saucedemo.com"); - Assertions.assertEquals("Swag Labs", driver.getTitle()); - } + @DisplayName("Sauce Bindings Navigation Test") + @Test + public void sauceBindingsNavigationTest() { + driver.navigate().to("https://www.saucedemo.com"); + Assertions.assertEquals("Swag Labs", driver.getTitle()); + } - /** - * Custom TestWatcher for Sauce Labs projects. - */ - public class SauceTestWatcher implements TestWatcher { - @Override - public void testSuccessful(ExtensionContext context) { - session.stop(true); - } + /** Custom TestWatcher for Sauce Labs projects. */ + public class SauceTestWatcher implements TestWatcher { + @Override + public void testSuccessful(ExtensionContext context) { + session.stop(true); + } - @Override - public void testFailed(ExtensionContext context, Throwable cause) { - session.stop(false); - } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + session.stop(false); } + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SaucebindingsJunitTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SaucebindingsJunitTest.java index 90d16ffc..581c2ae3 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SaucebindingsJunitTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SaucebindingsJunitTest.java @@ -8,15 +8,15 @@ /** * saucebindings.junit5 package provides a default superclass to handle set up and tear down * - * @see Sauce Binding Test Runners - * for more information + * @see Sauce Binding Test + * Runners for more information */ public class SaucebindingsJunitTest extends SauceBaseTest { - @DisplayName("Sauce Bindings Test Runner Navigation Example") - @Test - public void sauceBindingsTestRunnerTest() { - driver.navigate().to("https://www.saucedemo.com"); - Assertions.assertEquals("Swag Labs", driver.getTitle()); - } + @DisplayName("Sauce Bindings Test Runner Navigation Example") + @Test + public void sauceBindingsTestRunnerTest() { + driver.navigate().to("https://www.saucedemo.com"); + Assertions.assertEquals("Swag Labs", driver.getTitle()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SeleniumTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SeleniumTest.java index 09dfdc98..caf34263 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SeleniumTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/demo/SeleniumTest.java @@ -16,57 +16,52 @@ import java.util.HashMap; import java.util.Map; -/** - * Demo tests with Selenium. - */ +/** Demo tests with Selenium. */ public class SeleniumTest { - public RemoteWebDriver driver; + public RemoteWebDriver driver; - /** - * A Test Watcher is needed to be able to get the results of a Test so that it can be sent to Sauce Labs. - * Note that the name is never actually used - */ - @RegisterExtension - public SauceTestWatcher watcher = new SauceTestWatcher(); + /** + * A Test Watcher is needed to be able to get the results of a Test so that it can be sent to + * Sauce Labs. Note that the name is never actually used + */ + @RegisterExtension public SauceTestWatcher watcher = new SauceTestWatcher(); - @BeforeEach - public void setup(TestInfo testInfo) throws MalformedURLException { - ChromeOptions options = new ChromeOptions(); - options.setPlatformName("Windows 10"); - options.setBrowserVersion("latest"); + @BeforeEach + public void setup(TestInfo testInfo) throws MalformedURLException { + ChromeOptions options = new ChromeOptions(); + options.setPlatformName("Windows 10"); + options.setBrowserVersion("latest"); - Map sauceOptions = new HashMap<>(); - sauceOptions.put("username", System.getenv("SAUCE_USERNAME")); - sauceOptions.put("accessKey", System.getenv("SAUCE_ACCESS_KEY")); - sauceOptions.put("name", testInfo.getDisplayName()); + Map sauceOptions = new HashMap<>(); + sauceOptions.put("username", System.getenv("SAUCE_USERNAME")); + sauceOptions.put("accessKey", System.getenv("SAUCE_ACCESS_KEY")); + sauceOptions.put("name", testInfo.getDisplayName()); - options.setCapability("sauce:options", sauceOptions); - URL url = new URL("https://ondemand.us-west-1.saucelabs.com/wd/hub"); + options.setCapability("sauce:options", sauceOptions); + URL url = new URL("https://ondemand.us-west-1.saucelabs.com/wd/hub"); - driver = new RemoteWebDriver(url, options); - } + driver = new RemoteWebDriver(url, options); + } - @DisplayName("Selenium Navigation Test") - @Test - public void navigateAndClose() { - driver.navigate().to("https://www.saucedemo.com"); - Assertions.assertEquals("Swag Labs", driver.getTitle()); - } + @DisplayName("Selenium Navigation Test") + @Test + public void navigateAndClose() { + driver.navigate().to("https://www.saucedemo.com"); + Assertions.assertEquals("Swag Labs", driver.getTitle()); + } - /** - * Custom TestWatcher for Sauce Labs projects. - */ - public class SauceTestWatcher implements TestWatcher { - @Override - public void testSuccessful(ExtensionContext context) { - driver.executeScript("sauce:job-result=passed"); - driver.quit(); - } + /** Custom TestWatcher for Sauce Labs projects. */ + public class SauceTestWatcher implements TestWatcher { + @Override + public void testSuccessful(ExtensionContext context) { + driver.executeScript("sauce:job-result=passed"); + driver.quit(); + } - @Override - public void testFailed(ExtensionContext context, Throwable cause) { - driver.executeScript("sauce:job-result=failed"); - driver.quit(); - } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + driver.executeScript("sauce:job-result=failed"); + driver.quit(); } + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/login/SauceBindingsLoginTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/login/SauceBindingsLoginTest.java index 1331bb67..60b424b9 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/login/SauceBindingsLoginTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/login/SauceBindingsLoginTest.java @@ -10,31 +10,29 @@ import java.time.Duration; -/** - * Login Test Using Sauce Bindings. - */ +/** Login Test Using Sauce Bindings. */ public class SauceBindingsLoginTest extends SauceBaseTest { - @DisplayName("Swag Labs Login with Sauce Bindings") - @Test - public void swagLabsLoginTest() { - driver.get("https://www.saucedemo.com"); + @DisplayName("Swag Labs Login with Sauce Bindings") + @Test + public void swagLabsLoginTest() { + driver.get("https://www.saucedemo.com"); - By usernameFieldLocator = By.id("user-name"); - By passwordFieldLocator = By.id("password"); - By submitButtonLocator = By.id("login-button"); + By usernameFieldLocator = By.id("user-name"); + By passwordFieldLocator = By.id("password"); + By submitButtonLocator = By.id("login-button"); - WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20)); - wait.until((driver) -> driver.findElement(usernameFieldLocator).isDisplayed()); + WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20)); + wait.until((driver) -> driver.findElement(usernameFieldLocator).isDisplayed()); - WebElement userNameField = driver.findElement(usernameFieldLocator); - WebElement passwordField = driver.findElement(passwordFieldLocator); - WebElement submitButton = driver.findElement(submitButtonLocator); + WebElement userNameField = driver.findElement(usernameFieldLocator); + WebElement passwordField = driver.findElement(passwordFieldLocator); + WebElement submitButton = driver.findElement(submitButtonLocator); - userNameField.sendKeys("standard_user"); - passwordField.sendKeys("secret_sauce"); - submitButton.click(); + userNameField.sendKeys("standard_user"); + passwordField.sendKeys("secret_sauce"); + submitButton.click(); - Assertions.assertEquals("https://www.saucedemo.com/inventory.html", driver.getCurrentUrl()); - } + Assertions.assertEquals("https://www.saucedemo.com/inventory.html", driver.getCurrentUrl()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/login/SeleniumLoginTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/login/SeleniumLoginTest.java index 352e94b4..ab9ea126 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/login/SeleniumLoginTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/login/SeleniumLoginTest.java @@ -12,35 +12,33 @@ import java.time.Duration; -/** - * Login tests with Selenium. - */ +/** Login tests with Selenium. */ public class SeleniumLoginTest extends SeleniumTestBase { - @BeforeEach - public void setup(TestInfo testInfo) { - basicSetup(testInfo); - } + @BeforeEach + public void setup(TestInfo testInfo) { + basicSetup(testInfo); + } - @DisplayName("Swag Labs Login with Selenium") - @Test - public void swagLabsLoginTest() { - driver.get("https://www.saucedemo.com"); + @DisplayName("Swag Labs Login with Selenium") + @Test + public void swagLabsLoginTest() { + driver.get("https://www.saucedemo.com"); - By usernameFieldLocator = By.cssSelector("#user-name"); - By passwordFieldLocator = By.cssSelector("#password"); - By submitButtonLocator = By.cssSelector(".btn_action"); + By usernameFieldLocator = By.cssSelector("#user-name"); + By passwordFieldLocator = By.cssSelector("#password"); + By submitButtonLocator = By.cssSelector(".btn_action"); - WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20)); - wait.until((driver) -> driver.findElement(usernameFieldLocator).isDisplayed()); + WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20)); + wait.until((driver) -> driver.findElement(usernameFieldLocator).isDisplayed()); - WebElement userNameField = driver.findElement(usernameFieldLocator); - WebElement passwordField = driver.findElement(passwordFieldLocator); - WebElement submitButton = driver.findElement(submitButtonLocator); + WebElement userNameField = driver.findElement(usernameFieldLocator); + WebElement passwordField = driver.findElement(passwordFieldLocator); + WebElement submitButton = driver.findElement(submitButtonLocator); - userNameField.sendKeys("standard_user"); - passwordField.sendKeys("secret_sauce"); - submitButton.click(); + userNameField.sendKeys("standard_user"); + passwordField.sendKeys("secret_sauce"); + submitButton.click(); - Assertions.assertEquals("https://www.saucedemo.com/inventory.html", driver.getCurrentUrl()); - } + Assertions.assertEquals("https://www.saucedemo.com/inventory.html", driver.getCurrentUrl()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/AttributePropertyTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/AttributePropertyTest.java index 8bec2a24..39daf598 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/AttributePropertyTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/AttributePropertyTest.java @@ -6,100 +6,102 @@ import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; + public class AttributePropertyTest extends SauceBaseTest { - /** - * Property and Attribute often return the same value (especially in Java, since values are converted to Strings, - * but they are different - * attribute is defined in html spec: https://dom.spec.whatwg.org/#concept-element-attribute - * property is defined in ecma spec: https://262.ecma-international.org/5.1/#sec-4.3.26 - * - * WebElement#getAttribute guesses which value you want from an element's attribute or property value and returns that - * - * Since this doesn't make sense in a specification, w3c defines 2 new endpoints, made available in Selenium as: - * WebElement#getDomProperty and WebElement#getDomAttribute - * - * The old behavior with the existing method is still available, but executes a large javascript blob - * New behavior should be preferred for performance and preciseness - */ - - @DisplayName("getDomProperty returns false, getDomAttribute returns null") - @Test - public void domPropertyReturnsFalseInsteadOfNullForBoolean() { - driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); - WebElement element = driver.findElement(By.id("new_user_interests_books")); - - Assertions.assertEquals("true", element.getAttribute("checked")); - Assertions.assertEquals("true", element.getDomProperty("checked")); - - element.click(); - - Assertions.assertNull(element.getAttribute("checked")); - Assertions.assertEquals("false", element.getDomProperty("checked")); - } - - @DisplayName("getDomProperty Boolean result updates, getDomAttribute does not") - @Test - public void attributePropertyDoesNotUpdateBoolean() { - driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); - WebElement element = driver.findElement(By.id("new_user_interests_books")); - - Assertions.assertEquals("true", element.getAttribute("checked")); - Assertions.assertEquals("true", element.getDomAttribute("checked")); - Assertions.assertEquals("true", element.getDomProperty("checked")); - - element.click(); - - Assertions.assertNull(element.getAttribute("checked")); - Assertions.assertEquals("false", element.getDomProperty("checked")); - Assertions.assertEquals("true", element.getDomAttribute("checked")); - } - - @DisplayName("getDomProperty String result updates, getDomAttribute does not") - @Test - public void attributePropertyDoesNotUpdateString() { - driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); - WebElement element = driver.findElement(By.id("new_user_occupation")); - - Assertions.assertEquals("Developer", element.getAttribute("value")); - Assertions.assertEquals("Developer", element.getDomAttribute("value")); - Assertions.assertEquals("Developer", element.getDomProperty("value")); - - element.clear(); - element.sendKeys("Engineer"); - - Assertions.assertEquals("Engineer", element.getAttribute("value")); - Assertions.assertEquals("Developer", element.getDomAttribute("value")); - Assertions.assertEquals("Engineer", element.getDomProperty("value")); - } - - @DisplayName("getDomAttribute is what is in the DOM, getDomProperty may includes parsing") - @Test - public void urlValues() { - driver.navigate().to("http://watir.com/examples/non_control_elements.html"); - WebElement element = driver.findElement(By.id("link_3")); - - Assertions.assertEquals("http://watir.com/examples/forms_with_input_elements.html", element.getDomProperty("href")); - Assertions.assertEquals("forms_with_input_elements.html", element.getDomAttribute("href")); - } - - @DisplayName("getDomProperty is case sensitive, getDomAttribute is not") - @Test - public void caseSensitivity() { - driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); - WebElement element = driver.findElement(By.name("new_user_email")); - - Assertions.assertEquals("new_user_email", element.getDomAttribute("nAme")); - Assertions.assertNull(element.getDomProperty("nAme")); - } - - @DisplayName("property className is equivalent to attribute class") - @Test - public void className() { - driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); - WebElement element = driver.findElement(By.id("new_user_first_name")); - - Assertions.assertEquals("name", element.getDomProperty("className")); - Assertions.assertEquals("name", element.getDomAttribute("class")); - } + /** + * Property and Attribute often return the same value (especially in Java, since values are + * converted to Strings, but they are different attribute is defined in html spec: + * https://dom.spec.whatwg.org/#concept-element-attribute property is defined in ecma spec: + * https://262.ecma-international.org/5.1/#sec-4.3.26 + * + *

WebElement#getAttribute guesses which value you want from an element's attribute or property + * value and returns that + * + *

Since this doesn't make sense in a specification, w3c defines 2 new endpoints, made + * available in Selenium as: WebElement#getDomProperty and WebElement#getDomAttribute + * + *

The old behavior with the existing method is still available, but executes a large + * javascript blob New behavior should be preferred for performance and preciseness + */ + @DisplayName("getDomProperty returns false, getDomAttribute returns null") + @Test + public void domPropertyReturnsFalseInsteadOfNullForBoolean() { + driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); + WebElement element = driver.findElement(By.id("new_user_interests_books")); + + Assertions.assertEquals("true", element.getAttribute("checked")); + Assertions.assertEquals("true", element.getDomProperty("checked")); + + element.click(); + + Assertions.assertNull(element.getAttribute("checked")); + Assertions.assertEquals("false", element.getDomProperty("checked")); + } + + @DisplayName("getDomProperty Boolean result updates, getDomAttribute does not") + @Test + public void attributePropertyDoesNotUpdateBoolean() { + driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); + WebElement element = driver.findElement(By.id("new_user_interests_books")); + + Assertions.assertEquals("true", element.getAttribute("checked")); + Assertions.assertEquals("true", element.getDomAttribute("checked")); + Assertions.assertEquals("true", element.getDomProperty("checked")); + + element.click(); + + Assertions.assertNull(element.getAttribute("checked")); + Assertions.assertEquals("false", element.getDomProperty("checked")); + Assertions.assertEquals("true", element.getDomAttribute("checked")); + } + + @DisplayName("getDomProperty String result updates, getDomAttribute does not") + @Test + public void attributePropertyDoesNotUpdateString() { + driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); + WebElement element = driver.findElement(By.id("new_user_occupation")); + + Assertions.assertEquals("Developer", element.getAttribute("value")); + Assertions.assertEquals("Developer", element.getDomAttribute("value")); + Assertions.assertEquals("Developer", element.getDomProperty("value")); + + element.clear(); + element.sendKeys("Engineer"); + + Assertions.assertEquals("Engineer", element.getAttribute("value")); + Assertions.assertEquals("Developer", element.getDomAttribute("value")); + Assertions.assertEquals("Engineer", element.getDomProperty("value")); + } + + @DisplayName("getDomAttribute is what is in the DOM, getDomProperty may includes parsing") + @Test + public void urlValues() { + driver.navigate().to("http://watir.com/examples/non_control_elements.html"); + WebElement element = driver.findElement(By.id("link_3")); + + Assertions.assertEquals( + "http://watir.com/examples/forms_with_input_elements.html", element.getDomProperty("href")); + Assertions.assertEquals("forms_with_input_elements.html", element.getDomAttribute("href")); + } + + @DisplayName("getDomProperty is case sensitive, getDomAttribute is not") + @Test + public void caseSensitivity() { + driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); + WebElement element = driver.findElement(By.name("new_user_email")); + + Assertions.assertEquals("new_user_email", element.getDomAttribute("nAme")); + Assertions.assertNull(element.getDomProperty("nAme")); + } + + @DisplayName("property className is equivalent to attribute class") + @Test + public void className() { + driver.navigate().to("http://watir.com/examples/forms_with_input_elements.html"); + WebElement element = driver.findElement(By.id("new_user_first_name")); + + Assertions.assertEquals("name", element.getDomProperty("className")); + Assertions.assertEquals("name", element.getDomAttribute("class")); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ChromeNetworkTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ChromeNetworkTest.java index 3be4fb42..f0ae1d5e 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ChromeNetworkTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ChromeNetworkTest.java @@ -11,19 +11,21 @@ public class ChromeNetworkTest extends SauceBaseTest { - @Test - public void toggleOffline() { - WebDriver augmentedDriver = new Augmenter().augment(driver); - ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions(); - networkConditions.setOffline(true); - ((HasNetworkConditions) augmentedDriver).setNetworkConditions(networkConditions); + @Test + public void toggleOffline() { + WebDriver augmentedDriver = new Augmenter().augment(driver); + ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions(); + networkConditions.setOffline(true); + ((HasNetworkConditions) augmentedDriver).setNetworkConditions(networkConditions); - try { - driver.get("https://www.saucedemo.com"); - Assertions.fail("If Network is set to be offline, the previous line should throw an exception"); - } catch (WebDriverException ex) { - ((HasNetworkConditions) augmentedDriver).setNetworkConditions(new ChromiumNetworkConditions()); - } - driver.get("https://www.saucedemo.com"); + try { + driver.get("https://www.saucedemo.com"); + Assertions.fail( + "If Network is set to be offline, the previous line should throw an exception"); + } catch (WebDriverException ex) { + ((HasNetworkConditions) augmentedDriver) + .setNetworkConditions(new ChromiumNetworkConditions()); } + driver.get("https://www.saucedemo.com"); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxAddonTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxAddonTest.java index c03c5f29..c50a05d1 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxAddonTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxAddonTest.java @@ -15,23 +15,26 @@ public class FirefoxAddonTest extends SauceBaseTest { - public SauceOptions createSauceOptions() { - return SauceOptions.firefox().build(); - } - - @Test - public void addons() { - driver.setFileDetector(new LocalFileDetector()); - WebDriver augmentedDriver = new Augmenter().augment(driver); - String id = ((HasExtensions) augmentedDriver).installExtension(Paths.get("src/test/resources/selenium-example.xpi")); - - driver.get("https://www.saucedemo.com"); - WebElement injected = driver.findElement(By.id("webextensions-selenium-example")); - Assertions.assertEquals("Content injected by webextensions-selenium-example", injected.getText()); - - ((HasExtensions) augmentedDriver).uninstallExtension(id); - - driver.navigate().refresh(); - Assertions.assertEquals(0, driver.findElements(By.id("webextensions-selenium-example")).size()); - } + public SauceOptions createSauceOptions() { + return SauceOptions.firefox().build(); + } + + @Test + public void addons() { + driver.setFileDetector(new LocalFileDetector()); + WebDriver augmentedDriver = new Augmenter().augment(driver); + String id = + ((HasExtensions) augmentedDriver) + .installExtension(Paths.get("src/test/resources/selenium-example.xpi")); + + driver.get("https://www.saucedemo.com"); + WebElement injected = driver.findElement(By.id("webextensions-selenium-example")); + Assertions.assertEquals( + "Content injected by webextensions-selenium-example", injected.getText()); + + ((HasExtensions) augmentedDriver).uninstallExtension(id); + + driver.navigate().refresh(); + Assertions.assertEquals(0, driver.findElements(By.id("webextensions-selenium-example")).size()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxContextTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxContextTest.java index 8a5078c5..a677e5ec 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxContextTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/FirefoxContextTest.java @@ -14,28 +14,35 @@ public class FirefoxContextTest extends SauceBaseTest { - public SauceOptions createSauceOptions() { - FirefoxOptions firefoxOptions = new FirefoxOptions(); - firefoxOptions.addPreference("intl.accept_languages", "de-DE"); - return SauceOptions.firefox(firefoxOptions).setGeckodriverVersion("0.30.0").build(); - } - - @Test - public void changePrefs() { - driver.get("https://www.google.com"); - - String lang1 = driver.findElement(By.id("gws-output-pages-elements-homepage_additional_languages__als")).getText(); - Assertions.assertTrue(lang1.contains("angeboten auf")); - - WebDriver augmentedDriver = new Augmenter().augment(driver); - ((HasContext) augmentedDriver).setContext(FirefoxCommandContext.CHROME); - - ((JavascriptExecutor) driver).executeScript("Services.prefs.setStringPref('intl.accept_languages', 'es-ES')"); - - ((HasContext) augmentedDriver).setContext(FirefoxCommandContext.CONTENT); - driver.navigate().refresh(); - - String lang2 = driver.findElement(By.id("gws-output-pages-elements-homepage_additional_languages__als")).getText(); - Assertions.assertTrue(lang2.contains("Ofrecido por")); - } + public SauceOptions createSauceOptions() { + FirefoxOptions firefoxOptions = new FirefoxOptions(); + firefoxOptions.addPreference("intl.accept_languages", "de-DE"); + return SauceOptions.firefox(firefoxOptions).setGeckodriverVersion("0.30.0").build(); + } + + @Test + public void changePrefs() { + driver.get("https://www.google.com"); + + String lang1 = + driver + .findElement(By.id("gws-output-pages-elements-homepage_additional_languages__als")) + .getText(); + Assertions.assertTrue(lang1.contains("angeboten auf")); + + WebDriver augmentedDriver = new Augmenter().augment(driver); + ((HasContext) augmentedDriver).setContext(FirefoxCommandContext.CHROME); + + ((JavascriptExecutor) driver) + .executeScript("Services.prefs.setStringPref('intl.accept_languages', 'es-ES')"); + + ((HasContext) augmentedDriver).setContext(FirefoxCommandContext.CONTENT); + driver.navigate().refresh(); + + String lang2 = + driver + .findElement(By.id("gws-output-pages-elements-homepage_additional_languages__als")) + .getText(); + Assertions.assertTrue(lang2.contains("Ofrecido por")); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/MSEdgeTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/MSEdgeTest.java index b9e56a4a..cf947123 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/MSEdgeTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/MSEdgeTest.java @@ -11,23 +11,23 @@ public class MSEdgeTest extends SauceBaseTest { - public SauceOptions createSauceOptions() { - EdgeOptions options = new EdgeOptions(); + public SauceOptions createSauceOptions() { + EdgeOptions options = new EdgeOptions(); - // Selenium 3 did not support any direct options for Chromium Edge - // Selenium 4 allows setting all compliant values on EdgeOptions + // Selenium 3 did not support any direct options for Chromium Edge + // Selenium 4 allows setting all compliant values on EdgeOptions - options.setExperimentalOption("excludeSwitches", - Collections.singletonList("disable-popup-blocking")); + options.setExperimentalOption( + "excludeSwitches", Collections.singletonList("disable-popup-blocking")); - return SauceOptions.edge(options).build(); - } + return SauceOptions.edge(options).build(); + } - @Test - public void edgeExecution() { - driver.get("https://deliver.courseavenue.com/PopupTest.aspx"); - driver.findElement(By.cssSelector("input[type=submit]")).click(); + @Test + public void edgeExecution() { + driver.get("https://deliver.courseavenue.com/PopupTest.aspx"); + driver.findElement(By.cssSelector("input[type=submit]")).click(); - Assertions.assertEquals(1, driver.getWindowHandles().size()); - } + Assertions.assertEquals(1, driver.getWindowHandles().size()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/NewWindowTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/NewWindowTest.java index 35e5c6e0..1d2fabec 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/NewWindowTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/NewWindowTest.java @@ -8,18 +8,18 @@ public class NewWindowTest extends SauceBaseTest { - @Test - public void secondWindow() { - driver.switchTo().newWindow(WindowType.WINDOW); - driver.manage().window().setPosition(new Point(100, 400)); + @Test + public void secondWindow() { + driver.switchTo().newWindow(WindowType.WINDOW); + driver.manage().window().setPosition(new Point(100, 400)); - Assertions.assertEquals(2, driver.getWindowHandles().toArray().length); - } + Assertions.assertEquals(2, driver.getWindowHandles().toArray().length); + } - @Test - public void secondTab() { - driver.switchTo().newWindow(WindowType.TAB); + @Test + public void secondTab() { + driver.switchTo().newWindow(WindowType.TAB); - Assertions.assertEquals(2, driver.getWindowHandles().toArray().length); - } + Assertions.assertEquals(2, driver.getWindowHandles().toArray().length); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RelativeLocatorsTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RelativeLocatorsTest.java index 6913c783..3b28e262 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RelativeLocatorsTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RelativeLocatorsTest.java @@ -10,16 +10,15 @@ public class RelativeLocatorsTest extends SauceBaseTest { - @Test - public void relativeLocators() { - driver.get("https://www.diemol.com/selenium-4-demo/relative-locators-demo.html"); + @Test + public void relativeLocators() { + driver.get("https://www.diemol.com/selenium-4-demo/relative-locators-demo.html"); - WebElement element = driver.findElement(with(By.tagName("li")) - .toLeftOf(By.id("berlin")) - .below(By.id("warsaw"))); + WebElement element = + driver.findElement(with(By.tagName("li")).toLeftOf(By.id("berlin")).below(By.id("warsaw"))); - Assertions.assertEquals("london", element.getAttribute("id")); + Assertions.assertEquals("london", element.getAttribute("id")); - driver.executeScript("arguments[0].style.filter='blur(8px)'", element); - } + driver.executeScript("arguments[0].style.filter='blur(8px)'", element); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RemoteWebDriverBuilderTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RemoteWebDriverBuilderTest.java index 9194b094..11ce369f 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RemoteWebDriverBuilderTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/RemoteWebDriverBuilderTest.java @@ -14,43 +14,43 @@ import java.time.Duration; import java.util.HashMap; import java.util.Map; + public class RemoteWebDriverBuilderTest { - /** - * RemoteWebDriver builder gives you a few great things off the bat: - * 1. Allows you to easily set Connection and Read Timeouts - * 2. Automatically applies augmentation for casting to valid interfaces - * 3. Keeps Browser Options and Sauce Options separate - * 4. Address values are Strings not URL, which is just easier - */ - @DisplayName("Use RemoteWebDriverBuilder class") - @Test - public void webDriverBuilder(TestInfo testInfo) { - FirefoxOptions browserOptions = new FirefoxOptions(); - - browserOptions.setPlatformName("Windows 10"); - browserOptions.setBrowserVersion("latest"); - browserOptions.setAcceptInsecureCerts(true); - browserOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE); - - Map sauceOptions = new HashMap<>(); - sauceOptions.put("name", testInfo.getDisplayName()); - sauceOptions.put("build", System.getenv("BUILD_NAME") + ": " + System.getenv("BUILD_NUMBER")); - sauceOptions.put("username", System.getenv("SAUCE_USERNAME")); - sauceOptions.put("accessKey", System.getenv("SAUCE_ACCESS_KEY")); - - ClientConfig config = ClientConfig.defaultConfig() - .readTimeout(Duration.ofMinutes(3)); - - WebDriver driver = RemoteWebDriver.builder() - .oneOf(browserOptions) - .setCapability("sauce:options", sauceOptions) - .address("https://ondemand.us-west-1.saucelabs.com/wd/hub") - .config(config) - .build(); - - ((HasFullPageScreenshot) driver).getFullPageScreenshotAs(OutputType.FILE); - - driver.quit(); - } + /** + * RemoteWebDriver builder gives you a few great things off the bat: 1. Allows you to easily set + * Connection and Read Timeouts 2. Automatically applies augmentation for casting to valid + * interfaces 3. Keeps Browser Options and Sauce Options separate 4. Address values are Strings + * not URL, which is just easier + */ + @DisplayName("Use RemoteWebDriverBuilder class") + @Test + public void webDriverBuilder(TestInfo testInfo) { + FirefoxOptions browserOptions = new FirefoxOptions(); + + browserOptions.setPlatformName("Windows 10"); + browserOptions.setBrowserVersion("latest"); + browserOptions.setAcceptInsecureCerts(true); + browserOptions.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE); + + Map sauceOptions = new HashMap<>(); + sauceOptions.put("name", testInfo.getDisplayName()); + sauceOptions.put("build", System.getenv("BUILD_NAME") + ": " + System.getenv("BUILD_NUMBER")); + sauceOptions.put("username", System.getenv("SAUCE_USERNAME")); + sauceOptions.put("accessKey", System.getenv("SAUCE_ACCESS_KEY")); + + ClientConfig config = ClientConfig.defaultConfig().readTimeout(Duration.ofMinutes(3)); + + WebDriver driver = + RemoteWebDriver.builder() + .oneOf(browserOptions) + .setCapability("sauce:options", sauceOptions) + .address("https://ondemand.us-west-1.saucelabs.com/wd/hub") + .config(config) + .build(); + + ((HasFullPageScreenshot) driver).getFullPageScreenshotAs(OutputType.FILE); + + driver.quit(); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/TimeoutsTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/TimeoutsTest.java index 959d07f5..5cf5be1a 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/TimeoutsTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/TimeoutsTest.java @@ -6,19 +6,20 @@ import org.openqa.selenium.WebDriver; import java.time.Duration; + public class TimeoutsTest extends SauceBaseTest { - @Test - public void getTimoutValues() { - WebDriver.Timeouts timeouts = driver.manage().timeouts(); + @Test + public void getTimoutValues() { + WebDriver.Timeouts timeouts = driver.manage().timeouts(); - timeouts.pageLoadTimeout(Duration.ofSeconds(33)); - timeouts.implicitlyWait(Duration.ofMillis(333)); - timeouts.scriptTimeout(Duration.ofSeconds(33)); - timeouts.getPageLoadTimeout(); - // These getters do not exist in Selenium 3 - Assertions.assertEquals(Duration.ofSeconds(33), timeouts.getPageLoadTimeout()); - Assertions.assertEquals(Duration.ofMillis(333), timeouts.getImplicitWaitTimeout()); - Assertions.assertEquals(Duration.ofSeconds(33), timeouts.getScriptTimeout()); - } + timeouts.pageLoadTimeout(Duration.ofSeconds(33)); + timeouts.implicitlyWait(Duration.ofMillis(333)); + timeouts.scriptTimeout(Duration.ofSeconds(33)); + timeouts.getPageLoadTimeout(); + // These getters do not exist in Selenium 3 + Assertions.assertEquals(Duration.ofSeconds(33), timeouts.getPageLoadTimeout()); + Assertions.assertEquals(Duration.ofMillis(333), timeouts.getImplicitWaitTimeout()); + Assertions.assertEquals(Duration.ofSeconds(33), timeouts.getScriptTimeout()); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageChromeTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageChromeTest.java index cd82dbc0..407956fb 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageChromeTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageChromeTest.java @@ -14,34 +14,34 @@ import java.nio.file.Paths; public class ViewPageChromeTest extends SauceBaseTest { - public final static String directory = "src/test/screenshots/"; + public static final String directory = "src/test/screenshots/"; - public SauceOptions createSauceOptions() { - ChromeOptions options = new ChromeOptions(); - // note: headless only actually required for print page - options.addArguments("--headless=new"); + public SauceOptions createSauceOptions() { + ChromeOptions options = new ChromeOptions(); + // note: headless only actually required for print page + options.addArguments("--headless=new"); - return SauceOptions.chrome(options).build(); - } + return SauceOptions.chrome(options).build(); + } - @Test - public void printPage() throws IOException { - driver.navigate().to("https://www.saucedemo.com/v1/inventory.html"); + @Test + public void printPage() throws IOException { + driver.navigate().to("https://www.saucedemo.com/v1/inventory.html"); - Path printPage = Paths.get(directory + "PrintPageChrome.pdf"); - printPage.toFile().deleteOnExit(); - Pdf print = driver.print(new PrintOptions()); + Path printPage = Paths.get(directory + "PrintPageChrome.pdf"); + printPage.toFile().deleteOnExit(); + Pdf print = driver.print(new PrintOptions()); - Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent())); - } + Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent())); + } - @Test - public void takeScreenshot() throws IOException { - driver.navigate().to("https://www.saucedemo.com/v1/inventory.html"); - byte[] screenshotAs = driver.getScreenshotAs(OutputType.BYTES); + @Test + public void takeScreenshot() throws IOException { + driver.navigate().to("https://www.saucedemo.com/v1/inventory.html"); + byte[] screenshotAs = driver.getScreenshotAs(OutputType.BYTES); - Path screenshot = Paths.get(directory + "FirefoxScreenshotChrome.png"); - screenshot.toFile().deleteOnExit(); - Files.write(screenshot, screenshotAs); - } + Path screenshot = Paths.get(directory + "FirefoxScreenshotChrome.png"); + screenshot.toFile().deleteOnExit(); + Files.write(screenshot, screenshotAs); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageFirefoxTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageFirefoxTest.java index bb9ad657..ac1a7b56 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageFirefoxTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4newfeatures/ViewPageFirefoxTest.java @@ -18,46 +18,43 @@ import java.nio.file.Paths; public class ViewPageFirefoxTest extends SauceBaseTest { - public final static String directory = "src/test/screenshots/"; - - public SauceOptions createSauceOptions() { - return SauceOptions.firefox() - .setGeckodriverVersion("0.30.0") - .setBrowserVersion("beta") - .build(); - } - - @BeforeEach - public void navigate() { - driver.navigate().to("https://www.saucedemo.com/v1/inventory.html"); - } - - @Test - public void printPage() throws IOException { - - Path printPage = Paths.get(directory + "FirefoxPrintPage.pdf"); - printPage.toFile().deleteOnExit(); - Pdf print = driver.print(new PrintOptions()); - - Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent())); - } - - @Test - public void takeScreenshot() throws IOException { - Path screenshot = Paths.get(directory + "FirefoxScreenshot.png"); - screenshot.toFile().deleteOnExit(); - byte[] screenshotAs = driver.getScreenshotAs(OutputType.BYTES); - - Files.write(screenshot, screenshotAs); - } - - @Test - public void takeFullPageScreenshot() throws IOException { - WebDriver augmentedDriver = new Augmenter().augment(driver); - File file = ((HasFullPageScreenshot) augmentedDriver).getFullPageScreenshotAs(OutputType.FILE); - - Path fullPageScreenshot = Paths.get(directory + "FirefoxFullPageScreenshot.png"); - fullPageScreenshot.toFile().deleteOnExit(); - Files.move(file.toPath(), fullPageScreenshot); - } + public static final String directory = "src/test/screenshots/"; + + public SauceOptions createSauceOptions() { + return SauceOptions.firefox().setGeckodriverVersion("0.30.0").setBrowserVersion("beta").build(); + } + + @BeforeEach + public void navigate() { + driver.navigate().to("https://www.saucedemo.com/v1/inventory.html"); + } + + @Test + public void printPage() throws IOException { + + Path printPage = Paths.get(directory + "FirefoxPrintPage.pdf"); + printPage.toFile().deleteOnExit(); + Pdf print = driver.print(new PrintOptions()); + + Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent())); + } + + @Test + public void takeScreenshot() throws IOException { + Path screenshot = Paths.get(directory + "FirefoxScreenshot.png"); + screenshot.toFile().deleteOnExit(); + byte[] screenshotAs = driver.getScreenshotAs(OutputType.BYTES); + + Files.write(screenshot, screenshotAs); + } + + @Test + public void takeFullPageScreenshot() throws IOException { + WebDriver augmentedDriver = new Augmenter().augment(driver); + File file = ((HasFullPageScreenshot) augmentedDriver).getFullPageScreenshotAs(OutputType.FILE); + + Path fullPageScreenshot = Paths.get(directory + "FirefoxFullPageScreenshot.png"); + fullPageScreenshot.toFile().deleteOnExit(); + Files.move(file.toPath(), fullPageScreenshot); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/CapabilitiesMergeTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/CapabilitiesMergeTest.java index 31513ce3..b645fa26 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/CapabilitiesMergeTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/CapabilitiesMergeTest.java @@ -6,34 +6,36 @@ import org.openqa.selenium.PageLoadStrategy; import org.openqa.selenium.UnexpectedAlertBehaviour; import org.openqa.selenium.chrome.ChromeOptions; -public class CapabilitiesMergeTest { - @DisplayName("Selenium 4 Can not merge in place!") - @Test - public void doesNotMergeInPlace() { - ChromeOptions options1 = new ChromeOptions(); - ChromeOptions options2 = new ChromeOptions(); +public class CapabilitiesMergeTest { - options1.setPageLoadStrategy(PageLoadStrategy.EAGER); - options2.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE); + @DisplayName("Selenium 4 Can not merge in place!") + @Test + public void doesNotMergeInPlace() { + ChromeOptions options1 = new ChromeOptions(); + ChromeOptions options2 = new ChromeOptions(); - options1.merge(options2); + options1.setPageLoadStrategy(PageLoadStrategy.EAGER); + options2.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE); - Assertions.assertNotEquals(UnexpectedAlertBehaviour.IGNORE, options1.getCapability("unhandledPromptBehavior")); - } + options1.merge(options2); - @DisplayName("Selenium 4 Has to merge as a new object") - @Test - public void mergeNewObject() { - ChromeOptions options1 = new ChromeOptions(); - ChromeOptions options2 = new ChromeOptions(); + Assertions.assertNotEquals( + UnexpectedAlertBehaviour.IGNORE, options1.getCapability("unhandledPromptBehavior")); + } - options1.setPageLoadStrategy(PageLoadStrategy.EAGER); - options2.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE); + @DisplayName("Selenium 4 Has to merge as a new object") + @Test + public void mergeNewObject() { + ChromeOptions options1 = new ChromeOptions(); + ChromeOptions options2 = new ChromeOptions(); - ChromeOptions options3 = options1.merge(options2); + options1.setPageLoadStrategy(PageLoadStrategy.EAGER); + options2.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE); - Assertions.assertEquals(UnexpectedAlertBehaviour.IGNORE, options3.getCapability("unhandledPromptBehavior")); - } + ChromeOptions options3 = options1.merge(options2); + Assertions.assertEquals( + UnexpectedAlertBehaviour.IGNORE, options3.getCapability("unhandledPromptBehavior")); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/DurationParameterTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/DurationParameterTest.java index c85ab608..47705273 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/DurationParameterTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/DurationParameterTest.java @@ -7,27 +7,28 @@ import java.time.Duration; import java.util.concurrent.TimeUnit; + public class DurationParameterTest extends SauceBaseTest { - @DisplayName("Timeout integers still work but are deprecated") - @Test - public void timeoutIntegersDeprecated() { + @DisplayName("Timeout integers still work but are deprecated") + @Test + public void timeoutIntegersDeprecated() { - // Uses Seconds - WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(5)); + // Uses Seconds + WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5)); - // Uses Long / TimeUnit - driver.manage().timeouts().implicitlyWait(Duration.ofMillis(555)); - } + // Uses Long / TimeUnit + driver.manage().timeouts().implicitlyWait(Duration.ofMillis(555)); + } - @DisplayName("Timeouts now use Duration instances") - @Test - public void timeoutUnitsDeprecated() { + @DisplayName("Timeouts now use Duration instances") + @Test + public void timeoutUnitsDeprecated() { - // Uses Seconds - WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5)); + // Uses Seconds + WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5)); - // Uses Long / TimeoutUnit - driver.manage().timeouts().implicitlyWait(Duration.ofMillis(555)); - } + // Uses Long / TimeoutUnit + driver.manage().timeouts().implicitlyWait(Duration.ofMillis(555)); + } } diff --git a/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/FindByTest.java b/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/FindByTest.java index 1a419d38..005b93ae 100644 --- a/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/FindByTest.java +++ b/selenium-examples/src/test/java/com/saucedemo/selenium/se4updates/FindByTest.java @@ -3,19 +3,20 @@ import com.saucelabs.saucebindings.junit5.SauceBaseTest; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; + public class FindByTest extends SauceBaseTest { - @Test - public void findElement() { - driver.navigate().to("https://www.saucedemo.com"); + @Test + public void findElement() { + driver.navigate().to("https://www.saucedemo.com"); - // These are no longer available at all in Selenium 4: - // driver.findElementById("user-name"); - // driver.findElementByCssSelector("#password"); - // driver.findElementByClassName("btn_action"); + // These are no longer available at all in Selenium 4: + // driver.findElementById("user-name"); + // driver.findElementByCssSelector("#password"); + // driver.findElementByClassName("btn_action"); - driver.findElement(By.cssSelector("#user-name")); - driver.findElement(By.cssSelector("#password")); - driver.findElement(By.cssSelector(".btn_action")); - } + driver.findElement(By.cssSelector("#user-name")); + driver.findElement(By.cssSelector("#password")); + driver.findElement(By.cssSelector(".btn_action")); + } }